summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/app/app.qbs6
-rw-r--r--src/app/app_version_header.qbs16
-rw-r--r--src/app/main.cpp63
-rw-r--r--src/libs/3rdparty/botan/botan.pri2
-rw-r--r--src/libs/3rdparty/cplusplus/Bind.cpp24
-rw-r--r--src/libs/3rdparty/cplusplus/Control.cpp6
-rw-r--r--src/libs/3rdparty/cplusplus/Names.cpp21
-rw-r--r--src/libs/3rdparty/cplusplus/Parser.cpp71
-rw-r--r--src/libs/3rdparty/cplusplus/Parser.h2
-rw-r--r--src/libs/3rdparty/cplusplus/Scope.cpp4
-rw-r--r--src/libs/3rdparty/cplusplus/Symbol.cpp35
-rw-r--r--src/libs/3rdparty/cplusplus/Symbol.h7
-rw-r--r--src/libs/3rdparty/cplusplus/Symbols.cpp6
-rw-r--r--src/libs/3rdparty/cplusplus/Templates.cpp8
-rw-r--r--src/libs/3rdparty/cplusplus/Token.cpp2
-rw-r--r--src/libs/3rdparty/cplusplus/TranslationUnit.cpp14
-rw-r--r--src/libs/3rdparty/cplusplus/TranslationUnit.h25
-rw-r--r--src/libs/3rdparty/cplusplus/cplusplus.pri4
-rw-r--r--src/libs/QtcLibrary.qbs15
-rw-r--r--src/libs/cplusplus/ASTParent.h2
-rw-r--r--src/libs/cplusplus/CppDocument.cpp25
-rw-r--r--src/libs/cplusplus/CppDocument.h12
-rw-r--r--src/libs/cplusplus/CppRewriter.cpp6
-rw-r--r--src/libs/cplusplus/DeprecatedGenTemplateInstance.cpp4
-rw-r--r--src/libs/cplusplus/ExpressionUnderCursor.cpp33
-rw-r--r--src/libs/cplusplus/FastPreprocessor.cpp22
-rw-r--r--src/libs/cplusplus/FastPreprocessor.h2
-rw-r--r--src/libs/cplusplus/FindUsages.cpp30
-rw-r--r--src/libs/cplusplus/LookupContext.cpp156
-rw-r--r--src/libs/cplusplus/LookupContext.h7
-rw-r--r--src/libs/cplusplus/MatchingText.cpp2
-rw-r--r--src/libs/cplusplus/PPToken.cpp2
-rw-r--r--src/libs/cplusplus/PreprocessorClient.cpp14
-rw-r--r--src/libs/cplusplus/PreprocessorEnvironment.cpp9
-rw-r--r--src/libs/cplusplus/ResolveExpression.cpp155
-rw-r--r--src/libs/cplusplus/ResolveExpression.h8
-rw-r--r--src/libs/cplusplus/SnapshotSymbolVisitor.cpp2
-rw-r--r--src/libs/cplusplus/TypeOfExpression.cpp2
-rw-r--r--src/libs/cplusplus/cplusplus.qbs144
-rw-r--r--src/libs/cplusplus/pp-engine.cpp27
-rw-r--r--src/libs/cplusplus/pp-scanner.cpp11
-rw-r--r--src/libs/extensionsystem/extensionsystem.qbs4
-rw-r--r--src/libs/extensionsystem/optionsparser.cpp2
-rw-r--r--src/libs/extensionsystem/plugindetailsview.cpp3
-rw-r--r--src/libs/extensionsystem/plugindetailsview.ui264
-rw-r--r--src/libs/extensionsystem/pluginmanager.cpp187
-rw-r--r--src/libs/extensionsystem/pluginmanager.h21
-rw-r--r--src/libs/extensionsystem/pluginmanager_p.h3
-rw-r--r--src/libs/extensionsystem/pluginspec.cpp67
-rw-r--r--src/libs/extensionsystem/pluginspec.h2
-rw-r--r--src/libs/extensionsystem/pluginspec_p.h2
-rw-r--r--src/libs/extensionsystem/pluginview.cpp3
-rw-r--r--src/libs/glsl/glslast.h2
-rw-r--r--src/libs/glsl/glslsymbols.cpp7
-rw-r--r--src/libs/glsl/glsltypes.cpp4
-rw-r--r--src/libs/languageutils/languageutils-lib.pri2
-rw-r--r--src/libs/languageutils/languageutils.qbs1
-rw-r--r--src/libs/qmldebug/qmldebug-lib.pri2
-rw-r--r--src/libs/qmldebug/qmlprofilereventtypes.h4
-rw-r--r--src/libs/qmldebug/qmlprofilertraceclient.cpp34
-rw-r--r--src/libs/qmldebug/qmlprofilertraceclient.h20
-rw-r--r--src/libs/qmleditorwidgets/contextpanetext.ui4
-rw-r--r--src/libs/qmleditorwidgets/contextpanetextwidget.cpp4
-rw-r--r--src/libs/qmleditorwidgets/contextpanewidget.cpp23
-rw-r--r--src/libs/qmleditorwidgets/contextpanewidgetborderimage.ui2
-rw-r--r--src/libs/qmleditorwidgets/contextpanewidgetimage.cpp37
-rw-r--r--src/libs/qmleditorwidgets/contextpanewidgetimage.ui2
-rw-r--r--src/libs/qmleditorwidgets/contextpanewidgetrectangle.cpp6
-rw-r--r--src/libs/qmleditorwidgets/contextpanewidgetrectangle.ui4
-rw-r--r--src/libs/qmleditorwidgets/easingpane/easingcontextpane.cpp4
-rw-r--r--src/libs/qmleditorwidgets/easingpane/easingpane.pri1
-rw-r--r--src/libs/qmleditorwidgets/gradientline.cpp20
-rw-r--r--src/libs/qmleditorwidgets/qmleditorwidgets-lib.pri2
-rw-r--r--src/libs/qmleditorwidgets/qmleditorwidgets.qbs72
-rw-r--r--src/libs/qmljs/jsoncheck.cpp4
-rw-r--r--src/libs/qmljs/parser/qmljs.g2
-rw-r--r--src/libs/qmljs/parser/qmljslexer.cpp2
-rw-r--r--src/libs/qmljs/parser/qmljsparser_p.h2
-rw-r--r--src/libs/qmljs/qmljs-lib.pri2
-rw-r--r--src/libs/qmljs/qmljs.qbs165
-rw-r--r--src/libs/qmljs/qmljsbind.cpp9
-rw-r--r--src/libs/qmljs/qmljsbundle.cpp4
-rw-r--r--src/libs/qmljs/qmljscheck.cpp7
-rw-r--r--src/libs/qmljs/qmljspropertyreader.cpp26
-rw-r--r--src/libs/qmljs/qmljsreformatter.cpp7
-rw-r--r--src/libs/qmljs/qmljsrewriter.cpp7
-rw-r--r--src/libs/qmljs/qmljsscopebuilder.cpp4
-rw-r--r--src/libs/qtcomponents/styleitem/qstyleitem.cpp3
-rw-r--r--src/libs/qtcomponents/styleitem/qtmenu.cpp5
-rw-r--r--src/libs/qtcomponents/styleitem/styleitem.qbs3
-rw-r--r--src/libs/qtcreatorcdbext/common.cpp2
-rw-r--r--src/libs/qtcreatorcdbext/eventcallback.cpp2
-rw-r--r--src/libs/ssh/sftpfilesystemmodel.cpp4
-rw-r--r--src/libs/ssh/ssh.pro2
-rw-r--r--src/libs/ssh/ssh.qbs9
-rw-r--r--src/libs/ssh/sshcapabilities.cpp4
-rw-r--r--src/libs/ssh/sshcapabilities_p.h3
-rw-r--r--src/libs/ssh/sshconnection.cpp128
-rw-r--r--src/libs/ssh/sshconnection.h10
-rw-r--r--src/libs/ssh/sshconnection_p.h3
-rw-r--r--src/libs/ssh/sshconnectionmanager.cpp51
-rw-r--r--src/libs/ssh/sshconnectionmanager.h26
-rw-r--r--src/libs/ssh/sshincomingpacket.cpp25
-rw-r--r--src/libs/ssh/sshincomingpacket_p.h13
-rw-r--r--src/libs/ssh/sshinit.cpp52
-rw-r--r--src/libs/ssh/sshinit_p.h (renamed from src/plugins/debugger/gdb/abstractgdbprocess.cpp)8
-rw-r--r--src/libs/ssh/sshkeygenerator.cpp2
-rw-r--r--src/libs/ssh/sshoutgoingpacket.cpp24
-rw-r--r--src/libs/ssh/sshoutgoingpacket_p.h9
-rw-r--r--src/libs/ssh/sshpacket_p.h2
-rw-r--r--src/libs/ssh/sshremoteprocess.cpp5
-rw-r--r--src/libs/ssh/sshremoteprocess.h1
-rw-r--r--src/libs/ssh/sshremoteprocessrunner.cpp4
-rw-r--r--src/libs/ssh/sshsendfacility.cpp21
-rw-r--r--src/libs/ssh/sshsendfacility_p.h9
-rw-r--r--src/libs/utils/ansiescapecodehandler.cpp205
-rw-r--r--src/libs/utils/ansiescapecodehandler.h72
-rw-r--r--src/libs/utils/basetreeview.cpp4
-rw-r--r--src/libs/utils/buildablehelperlibrary.cpp31
-rw-r--r--src/libs/utils/buildablehelperlibrary.h2
-rw-r--r--src/libs/utils/checkablemessagebox.cpp22
-rw-r--r--src/libs/utils/checkablemessagebox.h9
-rw-r--r--src/libs/utils/consoleprocess.h2
-rw-r--r--src/libs/utils/consoleprocess_unix.cpp6
-rw-r--r--src/libs/utils/consoleprocess_win.cpp4
-rw-r--r--src/libs/utils/environment.cpp38
-rw-r--r--src/libs/utils/environment.h6
-rw-r--r--src/libs/utils/fancymainwindow.cpp4
-rw-r--r--src/libs/utils/filesearch.cpp8
-rw-r--r--src/libs/utils/fileutils.cpp14
-rw-r--r--src/libs/utils/fileutils.h1
-rw-r--r--src/libs/utils/function.cpp (renamed from src/plugins/analyzerbase/ianalyzerengine.cpp)45
-rw-r--r--src/libs/utils/function.h47
-rw-r--r--src/libs/utils/historycompleter.cpp7
-rw-r--r--src/libs/utils/hostosinfo.h41
-rw-r--r--src/libs/utils/iwelcomepage.h4
-rw-r--r--src/libs/utils/json.cpp40
-rw-r--r--src/libs/utils/json.h24
-rw-r--r--src/libs/utils/osspecificaspects.h74
-rw-r--r--src/libs/utils/outputformatter.cpp13
-rw-r--r--src/libs/utils/outputformatter.h4
-rw-r--r--src/libs/utils/pathchooser.cpp6
-rw-r--r--src/libs/utils/pathchooser.h5
-rw-r--r--src/libs/utils/persistentsettings.cpp2
-rw-r--r--src/libs/utils/process_ctrlc_stub.cpp2
-rw-r--r--src/libs/utils/projectintropage.cpp2
-rw-r--r--src/libs/utils/qtcprocess.cpp24
-rw-r--r--src/libs/utils/qtcprocess.h14
-rw-r--r--src/libs/utils/reloadpromptutils.cpp57
-rw-r--r--src/libs/utils/reloadpromptutils.h27
-rw-r--r--src/libs/utils/sleep.cpp (renamed from src/plugins/pythoneditor/pythoneditor_global.h)24
-rw-r--r--src/libs/utils/sleep.h (renamed from src/plugins/madde/madde_exports.h)20
-rw-r--r--src/libs/utils/stylehelper.cpp2
-rw-r--r--src/libs/utils/synchronousprocess.cpp151
-rw-r--r--src/libs/utils/synchronousprocess.h33
-rw-r--r--src/libs/utils/textfileformat.cpp33
-rw-r--r--src/libs/utils/textfileformat.h2
-rw-r--r--src/libs/utils/tooltip/tipcontents.cpp2
-rw-r--r--src/libs/utils/tooltip/tooltip.cpp36
-rw-r--r--src/libs/utils/tooltip/tooltip.h20
-rw-r--r--src/libs/utils/unixutils.cpp10
-rw-r--r--src/libs/utils/utils-lib.pri12
-rw-r--r--src/libs/utils/utils.qbs8
-rw-r--r--src/libs/utils/winutils.cpp6
-rw-r--r--src/libs/utils/winutils.h2
-rw-r--r--src/libs/zeroconf/servicebrowser.cpp2
-rw-r--r--src/pluginjsonmetadata.xsl3
-rw-r--r--src/plugins/QtcPlugin.qbs19
-rw-r--r--src/plugins/analyzerbase/AnalyzerBase.pluginspec.in2
-rw-r--r--src/plugins/analyzerbase/analyzerbase.pro6
-rw-r--r--src/plugins/analyzerbase/analyzerbase.qbs6
-rw-r--r--src/plugins/analyzerbase/analyzerconstants.h4
-rw-r--r--src/plugins/analyzerbase/analyzermanager.cpp360
-rw-r--r--src/plugins/analyzerbase/analyzermanager.h31
-rw-r--r--src/plugins/analyzerbase/analyzerplugin.cpp8
-rw-r--r--src/plugins/analyzerbase/analyzerplugin.h2
-rw-r--r--src/plugins/analyzerbase/analyzerrunconfigwidget.cpp82
-rw-r--r--src/plugins/analyzerbase/analyzerrunconfigwidget.h45
-rw-r--r--src/plugins/analyzerbase/analyzerruncontrol.cpp121
-rw-r--r--src/plugins/analyzerbase/analyzerruncontrol.h64
-rw-r--r--src/plugins/analyzerbase/analyzersettings.cpp239
-rw-r--r--src/plugins/analyzerbase/analyzersettings.h192
-rw-r--r--src/plugins/analyzerbase/analyzerstartparameters.h6
-rw-r--r--src/plugins/analyzerbase/analyzerutils.cpp2
-rw-r--r--src/plugins/analyzerbase/ianalyzerengine.h112
-rw-r--r--src/plugins/analyzerbase/ianalyzertool.cpp44
-rw-r--r--src/plugins/analyzerbase/ianalyzertool.h77
-rw-r--r--src/plugins/android/Android.pluginspec.in2
-rw-r--r--src/plugins/android/addnewavddialog.ui49
-rw-r--r--src/plugins/android/android.pro26
-rw-r--r--src/plugins/android/android.qbs28
-rw-r--r--src/plugins/android/android_dependencies.pri7
-rw-r--r--src/plugins/android/androidanalyzesupport.cpp42
-rw-r--r--src/plugins/android/androidanalyzesupport.h10
-rw-r--r--src/plugins/android/androidconfigurations.cpp356
-rw-r--r--src/plugins/android/androidconfigurations.h33
-rw-r--r--src/plugins/android/androidcreatekeystorecertificate.cpp143
-rw-r--r--src/plugins/android/androidcreatekeystorecertificate.h4
-rw-r--r--src/plugins/android/androidcreatekeystorecertificate.ui289
-rw-r--r--src/plugins/android/androiddeployconfiguration.cpp27
-rw-r--r--src/plugins/android/androiddeployconfiguration.h4
-rw-r--r--src/plugins/android/androiddeployqtstep.cpp554
-rw-r--r--src/plugins/android/androiddeployqtstep.h160
-rw-r--r--src/plugins/android/androiddeployqtwidget.cpp314
-rw-r--r--src/plugins/android/androiddeployqtwidget.h86
-rw-r--r--src/plugins/android/androiddeployqtwidget.ui295
-rw-r--r--src/plugins/android/androiddeploystep.cpp118
-rw-r--r--src/plugins/android/androiddeploystep.h11
-rw-r--r--src/plugins/android/androiddeploystepwidget.cpp14
-rw-r--r--src/plugins/android/androiddeploystepwidget.h1
-rw-r--r--src/plugins/android/androiddeploystepwidget.ui17
-rw-r--r--src/plugins/android/androiddevice.cpp7
-rw-r--r--src/plugins/android/androiddevice.h3
-rw-r--r--src/plugins/android/androiddevicedialog.cpp471
-rw-r--r--src/plugins/android/androiddevicedialog.h75
-rw-r--r--src/plugins/android/androiddevicedialog.ui95
-rw-r--r--src/plugins/android/androiderrormessage.cpp74
-rw-r--r--src/plugins/android/androiderrormessage.h (renamed from src/plugins/debugger/gdb/abstractplaingdbadapter.h)43
-rw-r--r--src/plugins/android/androidgdbserverkitinformation.cpp82
-rw-r--r--src/plugins/android/androidgdbserverkitinformation.h20
-rw-r--r--src/plugins/android/androidmanager.cpp322
-rw-r--r--src/plugins/android/androidmanager.h19
-rw-r--r--src/plugins/android/androidmanifestdocument.cpp4
-rw-r--r--src/plugins/android/androidmanifesteditor.cpp5
-rw-r--r--src/plugins/android/androidmanifesteditor.h1
-rw-r--r--src/plugins/android/androidmanifesteditorfactory.cpp20
-rw-r--r--src/plugins/android/androidmanifesteditorfactory.h6
-rw-r--r--src/plugins/android/androidmanifesteditorwidget.cpp195
-rw-r--r--src/plugins/android/androidmanifesteditorwidget.h8
-rw-r--r--src/plugins/android/androidpackagecreationstep.cpp91
-rw-r--r--src/plugins/android/androidpackagecreationstep.h7
-rw-r--r--src/plugins/android/androidpackagecreationwidget.cpp49
-rw-r--r--src/plugins/android/androidpackagecreationwidget.h5
-rw-r--r--src/plugins/android/androidpackagecreationwidget.ui131
-rw-r--r--src/plugins/android/androidpackageinstallationfactory.cpp27
-rw-r--r--src/plugins/android/androidpackageinstallationstep.cpp28
-rw-r--r--src/plugins/android/androidpackageinstallationstep.h7
-rw-r--r--src/plugins/android/androidplugin.cpp13
-rw-r--r--src/plugins/android/androidqbspropertyprovider.cpp80
-rw-r--r--src/plugins/android/androidqbspropertyprovider.h (renamed from src/plugins/qnx/blackberryutils.h)29
-rw-r--r--src/plugins/android/androidqtversion.cpp16
-rw-r--r--src/plugins/android/androidqtversion.h5
-rw-r--r--src/plugins/android/androidrunconfiguration.cpp10
-rw-r--r--src/plugins/android/androidrunconfiguration.h2
-rw-r--r--src/plugins/android/androidrunfactories.cpp2
-rw-r--r--src/plugins/android/androidrunner.cpp15
-rw-r--r--src/plugins/android/androidsettingspage.cpp18
-rw-r--r--src/plugins/android/androidsettingswidget.cpp12
-rw-r--r--src/plugins/android/androidtoolchain.cpp139
-rw-r--r--src/plugins/android/androidtoolchain.h18
-rw-r--r--src/plugins/android/certificatesmodel.cpp73
-rw-r--r--src/plugins/android/certificatesmodel.h58
-rw-r--r--src/plugins/autotoolsprojectmanager/AutotoolsProjectManager.pluginspec.in2
-rw-r--r--src/plugins/autotoolsprojectmanager/autogenstep.cpp11
-rw-r--r--src/plugins/autotoolsprojectmanager/autoreconfstep.cpp7
-rw-r--r--src/plugins/autotoolsprojectmanager/autotoolsbuildconfiguration.cpp136
-rw-r--r--src/plugins/autotoolsprojectmanager/autotoolsbuildconfiguration.h25
-rw-r--r--src/plugins/autotoolsprojectmanager/autotoolsbuildsettingswidget.cpp13
-rw-r--r--src/plugins/autotoolsprojectmanager/autotoolsbuildsettingswidget.h1
-rw-r--r--src/plugins/autotoolsprojectmanager/autotoolsproject.cpp9
-rw-r--r--src/plugins/autotoolsprojectmanager/autotoolsproject.h3
-rw-r--r--src/plugins/autotoolsprojectmanager/autotoolsprojectconstants.h1
-rw-r--r--src/plugins/autotoolsprojectmanager/autotoolsprojectfile.cpp14
-rw-r--r--src/plugins/autotoolsprojectmanager/autotoolsprojectfile.h3
-rw-r--r--src/plugins/autotoolsprojectmanager/autotoolsprojectnode.cpp18
-rw-r--r--src/plugins/autotoolsprojectmanager/autotoolsprojectnode.h16
-rw-r--r--src/plugins/autotoolsprojectmanager/autotoolsprojectplugin.cpp3
-rw-r--r--src/plugins/autotoolsprojectmanager/configurestep.cpp9
-rw-r--r--src/plugins/autotoolsprojectmanager/makestep.cpp4
-rw-r--r--src/plugins/baremetal/BareMetal.pluginspec.in17
-rw-r--r--src/plugins/baremetal/baremetal.pro34
-rw-r--r--src/plugins/baremetal/baremetal.qbs30
-rw-r--r--src/plugins/baremetal/baremetal_dependencies.pri13
-rw-r--r--src/plugins/baremetal/baremetalconstants.h45
-rw-r--r--src/plugins/baremetal/baremetaldeploystepfactory.cpp104
-rw-r--r--src/plugins/baremetal/baremetaldevice.cpp121
-rw-r--r--src/plugins/baremetal/baremetaldevice.h75
-rw-r--r--src/plugins/baremetal/baremetaldeviceconfigurationfactory.cpp80
-rw-r--r--src/plugins/baremetal/baremetaldeviceconfigurationfactory.h54
-rw-r--r--src/plugins/baremetal/baremetaldeviceconfigurationwidget.cpp97
-rw-r--r--src/plugins/baremetal/baremetaldeviceconfigurationwidget.h61
-rw-r--r--src/plugins/baremetal/baremetaldeviceconfigurationwidget.ui82
-rw-r--r--src/plugins/baremetal/baremetaldeviceconfigurationwizard.cpp85
-rw-r--r--src/plugins/baremetal/baremetaldeviceconfigurationwizard.h58
-rw-r--r--src/plugins/baremetal/baremetaldeviceconfigurationwizardpages.cpp93
-rw-r--r--src/plugins/baremetal/baremetaldeviceconfigurationwizardpages.h69
-rw-r--r--src/plugins/baremetal/baremetaldeviceconfigurationwizardsetuppage.ui83
-rw-r--r--src/plugins/baremetal/baremetalgdbcommandsdeploystep.cpp142
-rw-r--r--src/plugins/baremetal/baremetalgdbcommandsdeploystep.h91
-rw-r--r--src/plugins/baremetal/baremetalplugin.cpp77
-rw-r--r--src/plugins/baremetal/baremetalplugin.h (renamed from src/plugins/qnx/blackberrydeviceprocesssupport.h)32
-rw-r--r--src/plugins/baremetal/baremetalrunconfiguration.cpp210
-rw-r--r--src/plugins/baremetal/baremetalrunconfiguration.h94
-rw-r--r--src/plugins/baremetal/baremetalrunconfigurationfactory.cpp133
-rw-r--r--src/plugins/baremetal/baremetalrunconfigurationfactory.h65
-rw-r--r--src/plugins/baremetal/baremetalrunconfigurationwidget.cpp161
-rw-r--r--src/plugins/baremetal/baremetalrunconfigurationwidget.h71
-rw-r--r--src/plugins/baremetal/baremetalruncontrolfactory.cpp138
-rw-r--r--src/plugins/baremetal/baremetalruncontrolfactory.h55
-rw-r--r--src/plugins/bazaar/Bazaar.pluginspec.in2
-rw-r--r--src/plugins/bazaar/annotationhighlighter.cpp3
-rw-r--r--src/plugins/bazaar/annotationhighlighter.h2
-rw-r--r--src/plugins/bazaar/bazaarclient.cpp27
-rw-r--r--src/plugins/bazaar/bazaarclient.h1
-rw-r--r--src/plugins/bazaar/bazaarcommitwidget.cpp3
-rw-r--r--src/plugins/bazaar/bazaareditor.cpp6
-rw-r--r--src/plugins/bazaar/bazaareditor.h2
-rw-r--r--src/plugins/bazaar/bazaarplugin.cpp8
-rw-r--r--src/plugins/bazaar/clonewizard.cpp38
-rw-r--r--src/plugins/bazaar/clonewizard.h15
-rw-r--r--src/plugins/bazaar/commiteditor.cpp3
-rw-r--r--src/plugins/bineditor/BinEditor.pluginspec.in2
-rw-r--r--src/plugins/bineditor/bineditor.cpp29
-rw-r--r--src/plugins/bineditor/bineditor.h2
-rw-r--r--src/plugins/bineditor/bineditorplugin.cpp115
-rw-r--r--src/plugins/bineditor/bineditorplugin.h4
-rw-r--r--src/plugins/bookmarks/Bookmarks.pluginspec.in2
-rw-r--r--src/plugins/bookmarks/bookmarkmanager.cpp44
-rw-r--r--src/plugins/bookmarks/bookmarkmanager.h10
-rw-r--r--src/plugins/bookmarks/bookmarksplugin.cpp7
-rw-r--r--src/plugins/classview/ClassView.pluginspec.in2
-rw-r--r--src/plugins/classview/classviewmanager.cpp212
-rw-r--r--src/plugins/classview/classviewmanager.h136
-rw-r--r--src/plugins/classview/classviewnavigationwidget.cpp82
-rw-r--r--src/plugins/classview/classviewnavigationwidget.h55
-rw-r--r--src/plugins/classview/classviewnavigationwidgetfactory.cpp25
-rw-r--r--src/plugins/classview/classviewnavigationwidgetfactory.h12
-rw-r--r--src/plugins/classview/classviewparser.cpp182
-rw-r--r--src/plugins/classview/classviewparser.h134
-rw-r--r--src/plugins/classview/classviewparsertreeitem.cpp99
-rw-r--r--src/plugins/classview/classviewparsertreeitem.h84
-rw-r--r--src/plugins/classview/classviewplugin.cpp8
-rw-r--r--src/plugins/classview/classviewplugin.h5
-rw-r--r--src/plugins/classview/classviewsymbolinformation.cpp11
-rw-r--r--src/plugins/classview/classviewsymbolinformation.h10
-rw-r--r--src/plugins/classview/classviewsymbollocation.cpp8
-rw-r--r--src/plugins/classview/classviewsymbollocation.h5
-rw-r--r--src/plugins/classview/classviewtreeitemmodel.cpp14
-rw-r--r--src/plugins/classview/classviewtreeitemmodel.h9
-rw-r--r--src/plugins/classview/classviewutils.cpp40
-rw-r--r--src/plugins/classview/classviewutils.h41
-rw-r--r--src/plugins/clearcase/ClearCase.pluginspec.in2
-rw-r--r--src/plugins/clearcase/annotationhighlighter.cpp3
-rw-r--r--src/plugins/clearcase/annotationhighlighter.h2
-rw-r--r--src/plugins/clearcase/clearcase.pro3
-rw-r--r--src/plugins/clearcase/clearcase.qbs2
-rw-r--r--src/plugins/clearcase/clearcasecontrol.cpp2
-rw-r--r--src/plugins/clearcase/clearcaseeditor.cpp6
-rw-r--r--src/plugins/clearcase/clearcaseeditor.h2
-rw-r--r--src/plugins/clearcase/clearcaseplugin.cpp237
-rw-r--r--src/plugins/clearcase/clearcaseplugin.h4
-rw-r--r--src/plugins/clearcase/clearcasesettings.cpp1
-rw-r--r--src/plugins/clearcase/clearcasesubmiteditor.cpp3
-rw-r--r--src/plugins/cmakeprojectmanager/CMakeProjectManager.pluginspec.in2
-rw-r--r--src/plugins/cmakeprojectmanager/cmakebuildconfiguration.cpp141
-rw-r--r--src/plugins/cmakeprojectmanager/cmakebuildconfiguration.h21
-rw-r--r--src/plugins/cmakeprojectmanager/cmakebuildinfo.h65
-rw-r--r--src/plugins/cmakeprojectmanager/cmakeeditor.cpp46
-rw-r--r--src/plugins/cmakeprojectmanager/cmakeeditor.h4
-rw-r--r--src/plugins/cmakeprojectmanager/cmakeeditorfactory.cpp24
-rw-r--r--src/plugins/cmakeprojectmanager/cmakeeditorfactory.h11
-rw-r--r--src/plugins/cmakeprojectmanager/cmakefilecompletionassist.h2
-rw-r--r--src/plugins/cmakeprojectmanager/cmakehighlighter.cpp32
-rw-r--r--src/plugins/cmakeprojectmanager/cmakehighlighter.h15
-rw-r--r--src/plugins/cmakeprojectmanager/cmakehighlighterfactory.cpp45
-rw-r--r--src/plugins/cmakeprojectmanager/cmakehighlighterfactory.h51
-rw-r--r--src/plugins/cmakeprojectmanager/cmakelocatorfilter.cpp24
-rw-r--r--src/plugins/cmakeprojectmanager/cmakeopenprojectwizard.cpp31
-rw-r--r--src/plugins/cmakeprojectmanager/cmakeopenprojectwizard.h24
-rw-r--r--src/plugins/cmakeprojectmanager/cmakeparser.cpp206
-rw-r--r--src/plugins/cmakeprojectmanager/cmakeparser.h60
-rw-r--r--src/plugins/cmakeprojectmanager/cmakeproject.cpp283
-rw-r--r--src/plugins/cmakeprojectmanager/cmakeproject.h22
-rw-r--r--src/plugins/cmakeprojectmanager/cmakeprojectconstants.h1
-rw-r--r--src/plugins/cmakeprojectmanager/cmakeprojectmanager.cpp5
-rw-r--r--src/plugins/cmakeprojectmanager/cmakeprojectmanager.pro14
-rw-r--r--src/plugins/cmakeprojectmanager/cmakeprojectmanager.qbs7
-rw-r--r--src/plugins/cmakeprojectmanager/cmakeprojectnodes.cpp12
-rw-r--r--src/plugins/cmakeprojectmanager/cmakeprojectnodes.h14
-rw-r--r--src/plugins/cmakeprojectmanager/cmakeprojectplugin.cpp17
-rw-r--r--src/plugins/cmakeprojectmanager/cmakeprojectplugin.h6
-rw-r--r--src/plugins/cmakeprojectmanager/cmakerunconfiguration.cpp2
-rw-r--r--src/plugins/cmakeprojectmanager/makestep.cpp53
-rw-r--r--src/plugins/cmakeprojectmanager/makestep.h6
-rw-r--r--src/plugins/coreplugin/Core.pluginspec.in2
-rw-r--r--src/plugins/coreplugin/actionmanager/actioncontainer.cpp17
-rw-r--r--src/plugins/coreplugin/actionmanager/actionmanager.cpp98
-rw-r--r--src/plugins/coreplugin/actionmanager/actionmanager.h10
-rw-r--r--src/plugins/coreplugin/actionmanager/command.cpp9
-rw-r--r--src/plugins/coreplugin/actionmanager/commandmappings.cpp2
-rw-r--r--src/plugins/coreplugin/actionmanager/commandsfile.cpp2
-rw-r--r--src/plugins/coreplugin/basefilewizard.cpp272
-rw-r--r--src/plugins/coreplugin/basefilewizard.h90
-rw-r--r--src/plugins/coreplugin/core.qrc2
-rw-r--r--src/plugins/coreplugin/coreconstants.h3
-rw-r--r--src/plugins/coreplugin/coreplugin.cpp17
-rw-r--r--src/plugins/coreplugin/coreplugin.pro26
-rw-r--r--src/plugins/coreplugin/coreplugin.qbs343
-rw-r--r--src/plugins/coreplugin/designmode.cpp6
-rw-r--r--src/plugins/coreplugin/dialogs/addtovcsdialog.cpp62
-rw-r--r--src/plugins/coreplugin/dialogs/addtovcsdialog.h58
-rw-r--r--src/plugins/coreplugin/dialogs/addtovcsdialog.ui93
-rw-r--r--src/plugins/coreplugin/dialogs/iwizard.cpp10
-rw-r--r--src/plugins/coreplugin/dialogs/iwizard.h69
-rw-r--r--src/plugins/coreplugin/dialogs/newdialog.cpp50
-rw-r--r--src/plugins/coreplugin/dialogs/readonlyfilesdialog.cpp12
-rw-r--r--src/plugins/coreplugin/dialogs/saveitemsdialog.cpp4
-rw-r--r--src/plugins/coreplugin/dialogs/settingsdialog.cpp13
-rw-r--r--src/plugins/coreplugin/dialogs/shortcutsettings.cpp16
-rw-r--r--src/plugins/coreplugin/documentmanager.cpp86
-rw-r--r--src/plugins/coreplugin/documentmanager.h15
-rw-r--r--src/plugins/coreplugin/editmode.cpp9
-rw-r--r--src/plugins/coreplugin/editmode.h1
-rw-r--r--src/plugins/coreplugin/editormanager/documentmodel.cpp398
-rw-r--r--src/plugins/coreplugin/editormanager/documentmodel.h (renamed from src/plugins/coreplugin/editormanager/openeditorsmodel.h)71
-rw-r--r--src/plugins/coreplugin/editormanager/editormanager.cpp808
-rw-r--r--src/plugins/coreplugin/editormanager/editormanager.h236
-rw-r--r--src/plugins/coreplugin/editormanager/editorview.cpp149
-rw-r--r--src/plugins/coreplugin/editormanager/editorview.h3
-rw-r--r--src/plugins/coreplugin/editormanager/ieditor.cpp3
-rw-r--r--src/plugins/coreplugin/editormanager/ieditor.h8
-rw-r--r--src/plugins/coreplugin/editormanager/iexternaleditor.cpp5
-rw-r--r--src/plugins/coreplugin/editormanager/openeditorsmodel.cpp365
-rw-r--r--src/plugins/coreplugin/editormanager/openeditorsview.cpp162
-rw-r--r--src/plugins/coreplugin/editormanager/openeditorsview.h32
-rw-r--r--src/plugins/coreplugin/editormanager/openeditorswindow.cpp28
-rw-r--r--src/plugins/coreplugin/editormanager/openeditorswindow.h6
-rw-r--r--src/plugins/coreplugin/editormanager/systemeditor.cpp4
-rw-r--r--src/plugins/coreplugin/editortoolbar.cpp78
-rw-r--r--src/plugins/coreplugin/editortoolbar.h5
-rw-r--r--src/plugins/coreplugin/externaltool.cpp170
-rw-r--r--src/plugins/coreplugin/externaltoolmanager.h42
-rw-r--r--src/plugins/coreplugin/fancyactionbar.cpp25
-rw-r--r--src/plugins/coreplugin/fancyactionbar.h5
-rw-r--r--src/plugins/coreplugin/featureprovider.cpp6
-rw-r--r--src/plugins/coreplugin/fileiconprovider.cpp156
-rw-r--r--src/plugins/coreplugin/fileiconprovider.h38
-rw-r--r--src/plugins/coreplugin/fileutils.cpp9
-rw-r--r--src/plugins/coreplugin/fileutils.h1
-rw-r--r--src/plugins/coreplugin/generalsettings.cpp12
-rw-r--r--src/plugins/coreplugin/helpmanager.cpp49
-rw-r--r--src/plugins/coreplugin/helpmanager.h54
-rw-r--r--src/plugins/coreplugin/icore.cpp158
-rw-r--r--src/plugins/coreplugin/icore.h26
-rw-r--r--src/plugins/coreplugin/id.cpp2
-rw-r--r--src/plugins/coreplugin/idocument.cpp91
-rw-r--r--src/plugins/coreplugin/idocument.h18
-rw-r--r--src/plugins/coreplugin/idocumentfactory.h27
-rw-r--r--src/plugins/coreplugin/images/sidebysidediff.pngbin0 -> 257 bytes
-rw-r--r--src/plugins/coreplugin/images/textdiff.pngbin0 -> 258 bytes
-rw-r--r--src/plugins/coreplugin/mainwindow.cpp116
-rw-r--r--src/plugins/coreplugin/mainwindow.h15
-rw-r--r--src/plugins/coreplugin/manhattanstyle.cpp12
-rw-r--r--src/plugins/coreplugin/messagemanager.cpp18
-rw-r--r--src/plugins/coreplugin/messagemanager.h36
-rw-r--r--src/plugins/coreplugin/mimedatabase.cpp132
-rw-r--r--src/plugins/coreplugin/mimedatabase.h70
-rw-r--r--src/plugins/coreplugin/mimetypesettings.cpp23
-rw-r--r--src/plugins/coreplugin/mimetypesettings.h2
-rw-r--r--src/plugins/coreplugin/modemanager.cpp6
-rw-r--r--src/plugins/coreplugin/modemanager.h16
-rw-r--r--src/plugins/coreplugin/navigationwidget.cpp2
-rw-r--r--src/plugins/coreplugin/outputpane.cpp19
-rw-r--r--src/plugins/coreplugin/outputpane.h1
-rw-r--r--src/plugins/coreplugin/outputpanemanager.cpp11
-rw-r--r--src/plugins/coreplugin/outputwindow.cpp18
-rw-r--r--src/plugins/coreplugin/outputwindow.h2
-rw-r--r--src/plugins/coreplugin/plugintestutils.cpp2
-rw-r--r--src/plugins/coreplugin/progressmanager/futureprogress.cpp6
-rw-r--r--src/plugins/coreplugin/progressmanager/futureprogress.h5
-rw-r--r--src/plugins/coreplugin/progressmanager/progressmanager.cpp67
-rw-r--r--src/plugins/coreplugin/progressmanager/progressmanager.h30
-rw-r--r--src/plugins/coreplugin/progressmanager/progressmanager_mac.mm2
-rw-r--r--src/plugins/coreplugin/progressmanager/progressmanager_p.h12
-rw-r--r--src/plugins/coreplugin/progressmanager/progressmanager_win.cpp4
-rw-r--r--src/plugins/coreplugin/progressmanager/progressmanager_x11.cpp2
-rw-r--r--src/plugins/coreplugin/progressmanager/progressview.cpp2
-rw-r--r--src/plugins/coreplugin/scriptmanager/metatypedeclarations.h61
-rw-r--r--src/plugins/coreplugin/scriptmanager/scriptmanager.cpp280
-rw-r--r--src/plugins/coreplugin/styleanimator.cpp3
-rw-r--r--src/plugins/coreplugin/testdatadir.cpp70
-rw-r--r--src/plugins/coreplugin/testdatadir.h59
-rw-r--r--src/plugins/coreplugin/textdocument.cpp4
-rw-r--r--src/plugins/coreplugin/toolsettings.cpp8
-rw-r--r--src/plugins/coreplugin/toolsettings.h2
-rw-r--r--src/plugins/coreplugin/variablemanager.cpp84
-rw-r--r--src/plugins/coreplugin/variablemanager.h13
-rw-r--r--src/plugins/coreplugin/vcsmanager.cpp45
-rw-r--r--src/plugins/coreplugin/vcsmanager.h35
-rw-r--r--src/plugins/cpaster/CodePaster.pluginspec.in2
-rw-r--r--src/plugins/cpaster/codepasterprotocol.cpp212
-rw-r--r--src/plugins/cpaster/codepasterprotocol.h81
-rw-r--r--src/plugins/cpaster/codepastersettings.cpp99
-rw-r--r--src/plugins/cpaster/columnindicatortextedit.cpp1
-rw-r--r--src/plugins/cpaster/cpaster.pro4
-rw-r--r--src/plugins/cpaster/cpaster.qbs4
-rw-r--r--src/plugins/cpaster/cpasterplugin.cpp17
-rw-r--r--src/plugins/cpaster/fileshareprotocol.cpp7
-rw-r--r--src/plugins/cpaster/frontend/frontend.qbs31
-rw-r--r--src/plugins/cpaster/kdepasteprotocol.cpp2
-rw-r--r--src/plugins/cpaster/pastebindotcaprotocol.cpp24
-rw-r--r--src/plugins/cpaster/pastebindotcaprotocol.h2
-rw-r--r--src/plugins/cpaster/pastebindotcomprotocol.cpp23
-rw-r--r--src/plugins/cpaster/pasteview.cpp1
-rw-r--r--src/plugins/cpaster/pasteview.h3
-rw-r--r--src/plugins/cpaster/pasteview.ui2
-rw-r--r--src/plugins/cpaster/protocol.cpp1
-rw-r--r--src/plugins/cpaster/protocol.h3
-rw-r--r--src/plugins/cppeditor/CppEditor.mimetypes.xml9
-rw-r--r--src/plugins/cppeditor/CppEditor.pluginspec.in2
-rw-r--r--src/plugins/cppeditor/cppautocompleter.cpp8
-rw-r--r--src/plugins/cppeditor/cppclasswizard.cpp14
-rw-r--r--src/plugins/cppeditor/cppclasswizard.h13
-rw-r--r--src/plugins/cppeditor/cppeditor.cpp155
-rw-r--r--src/plugins/cppeditor/cppeditor.h6
-rw-r--r--src/plugins/cppeditor/cppeditor.pro2
-rw-r--r--src/plugins/cppeditor/cppeditor.qbs7
-rw-r--r--src/plugins/cppeditor/cppeditorplugin.cpp184
-rw-r--r--src/plugins/cppeditor/cppeditorplugin.h26
-rw-r--r--src/plugins/cppeditor/cppelementevaluator.cpp14
-rw-r--r--src/plugins/cppeditor/cppelementevaluator.h3
-rw-r--r--src/plugins/cppeditor/cppfilewizard.cpp8
-rw-r--r--src/plugins/cppeditor/cppfilewizard.h9
-rw-r--r--src/plugins/cppeditor/cppfunctiondecldeflink.cpp24
-rw-r--r--src/plugins/cppeditor/cpphighlighter.cpp82
-rw-r--r--src/plugins/cppeditor/cpphighlighter.h10
-rw-r--r--src/plugins/cppeditor/cpphighlighterfactory.cpp48
-rw-r--r--src/plugins/cppeditor/cpphighlighterfactory.h51
-rw-r--r--src/plugins/cppeditor/cpphoverhandler.cpp3
-rw-r--r--src/plugins/cppeditor/cppoutline.cpp5
-rw-r--r--src/plugins/cppeditor/cppquickfix_test.cpp371
-rw-r--r--src/plugins/cppeditor/cppquickfixassistant.cpp2
-rw-r--r--src/plugins/cppeditor/cppquickfixes.cpp370
-rw-r--r--src/plugins/cppeditor/cppquickfixes.h10
-rw-r--r--src/plugins/cppeditor/cppsnippetprovider.cpp9
-rw-r--r--src/plugins/cppeditor/cpptypehierarchy.cpp99
-rw-r--r--src/plugins/cppeditor/cpptypehierarchy.h9
-rw-r--r--src/plugins/cppeditor/fileandtokenactions_test.cpp57
-rw-r--r--src/plugins/cppeditor/followsymbol_switchmethoddecldef_test.cpp48
-rw-r--r--src/plugins/cpptools/CppTools.pluginspec.in2
-rw-r--r--src/plugins/cpptools/abstracteditorsupport.h1
-rw-r--r--src/plugins/cpptools/builtinindexingsupport.cpp30
-rw-r--r--src/plugins/cpptools/completionsettingspage.cpp4
-rw-r--r--src/plugins/cpptools/cppchecksymbols.cpp78
-rw-r--r--src/plugins/cpptools/cppclassesfilter.cpp23
-rw-r--r--src/plugins/cpptools/cppclassesfilter.h7
-rw-r--r--src/plugins/cpptools/cppcodeformatter.cpp6
-rw-r--r--src/plugins/cpptools/cppcodemodelsettings.cpp69
-rw-r--r--src/plugins/cpptools/cppcodemodelsettings.h (renamed from src/plugins/cpptools/cppcompletionsupport.h)60
-rw-r--r--src/plugins/cpptools/cppcodemodelsettingspage.cpp148
-rw-r--r--src/plugins/cpptools/cppcodemodelsettingspage.h90
-rw-r--r--src/plugins/cpptools/cppcodemodelsettingspage.ui97
-rw-r--r--src/plugins/cpptools/cppcodestylesettings.cpp2
-rw-r--r--src/plugins/cpptools/cppcodestylesettingspage.cpp8
-rw-r--r--src/plugins/cpptools/cppcompletion_test.cpp681
-rw-r--r--src/plugins/cpptools/cppcompletionassist.cpp189
-rw-r--r--src/plugins/cpptools/cppcompletionassist.h6
-rw-r--r--src/plugins/cpptools/cppcompletionassistprovider.h18
-rw-r--r--src/plugins/cpptools/cppcurrentdocumentfilter.cpp37
-rw-r--r--src/plugins/cpptools/cppcurrentdocumentfilter.h7
-rw-r--r--src/plugins/cpptools/cppfilesettingspage.cpp52
-rw-r--r--src/plugins/cpptools/cppfilesettingspage.h2
-rw-r--r--src/plugins/cpptools/cppfilesettingspage.ui167
-rw-r--r--src/plugins/cpptools/cppfindreferences.cpp65
-rw-r--r--src/plugins/cpptools/cppfindreferences.h4
-rw-r--r--src/plugins/cpptools/cppfunctionsfilter.cpp28
-rw-r--r--src/plugins/cpptools/cppfunctionsfilter.h7
-rw-r--r--src/plugins/cpptools/cppheadersource_test.cpp72
-rw-r--r--src/plugins/cpptools/cpphighlightingsupport.cpp4
-rw-r--r--src/plugins/cpptools/cpphighlightingsupport.h9
-rw-r--r--src/plugins/cpptools/cpphighlightingsupportinternal.cpp9
-rw-r--r--src/plugins/cpptools/cpphighlightingsupportinternal.h11
-rw-r--r--src/plugins/cpptools/cpplocalsymbols.cpp8
-rw-r--r--src/plugins/cpptools/cpplocatordata.cpp162
-rw-r--r--src/plugins/cpptools/cpplocatordata.h (renamed from src/plugins/debugger/gdb/remoteplaingdbadapter.h)71
-rw-r--r--src/plugins/cpptools/cpplocatorfilter.cpp121
-rw-r--r--src/plugins/cpptools/cpplocatorfilter.h24
-rw-r--r--src/plugins/cpptools/cpplocatorfilter_test.cpp294
-rw-r--r--src/plugins/cpptools/cppmodelmanager.cpp565
-rw-r--r--src/plugins/cpptools/cppmodelmanager.h95
-rw-r--r--src/plugins/cpptools/cppmodelmanager_test.cpp372
-rw-r--r--src/plugins/cpptools/cppmodelmanagerinterface.cpp79
-rw-r--r--src/plugins/cpptools/cppmodelmanagerinterface.h86
-rw-r--r--src/plugins/cpptools/cppmodelmanagersupport.cpp (renamed from src/plugins/help/help_global.h)15
-rw-r--r--src/plugins/cpptools/cppmodelmanagersupport.h58
-rw-r--r--src/plugins/cpptools/cppmodelmanagersupportinternal.cpp (renamed from src/plugins/analyzerbase/analyzeroptionspage.cpp)43
-rw-r--r--src/plugins/cpptools/cppmodelmanagersupportinternal.h (renamed from src/plugins/cmakeprojectmanager/cmakeuicodemodelsupport.h)44
-rw-r--r--src/plugins/cpptools/cpppointerdeclarationformatter.cpp10
-rw-r--r--src/plugins/cpptools/cpppreprocessertesthelper.cpp56
-rw-r--r--src/plugins/cpptools/cpppreprocessertesthelper.h53
-rw-r--r--src/plugins/cpptools/cpppreprocessor.cpp127
-rw-r--r--src/plugins/cpptools/cpppreprocessor.h2
-rw-r--r--src/plugins/cpptools/cpppreprocessor_test.cpp120
-rw-r--r--src/plugins/cpptools/cppprojectfile.cpp9
-rw-r--r--src/plugins/cpptools/cpprefactoringchanges.cpp4
-rw-r--r--src/plugins/cpptools/cppsemanticinfo.h4
-rw-r--r--src/plugins/cpptools/cpptools.pro30
-rw-r--r--src/plugins/cpptools/cpptools.qbs34
-rw-r--r--src/plugins/cpptools/cpptoolsconstants.h6
-rw-r--r--src/plugins/cpptools/cpptoolseditorsupport.cpp49
-rw-r--r--src/plugins/cpptools/cpptoolseditorsupport.h15
-rw-r--r--src/plugins/cpptools/cpptoolsplugin.cpp119
-rw-r--r--src/plugins/cpptools/cpptoolsplugin.h54
-rw-r--r--src/plugins/cpptools/cpptoolssettings.cpp48
-rw-r--r--src/plugins/cpptools/includeutils.cpp20
-rw-r--r--src/plugins/cpptools/insertionpointlocator.cpp14
-rw-r--r--src/plugins/cpptools/modelmanagertesthelper.cpp16
-rw-r--r--src/plugins/cpptools/modelmanagertesthelper.h3
-rw-r--r--src/plugins/cpptools/searchsymbols.cpp62
-rw-r--r--src/plugins/cpptools/searchsymbols.h54
-rw-r--r--src/plugins/cpptools/symbolfinder.cpp44
-rw-r--r--src/plugins/cpptools/symbolsearcher_test.cpp298
-rw-r--r--src/plugins/cpptools/symbolsfindfilter.cpp48
-rw-r--r--src/plugins/cpptools/symbolsfindfilter.h4
-rw-r--r--src/plugins/cpptools/uicodecompletionsupport.cpp246
-rw-r--r--src/plugins/cvs/CVS.pluginspec.in2
-rw-r--r--src/plugins/cvs/annotationhighlighter.cpp3
-rw-r--r--src/plugins/cvs/annotationhighlighter.h2
-rw-r--r--src/plugins/cvs/checkoutwizard.cpp38
-rw-r--r--src/plugins/cvs/checkoutwizard.h14
-rw-r--r--src/plugins/cvs/cvseditor.cpp7
-rw-r--r--src/plugins/cvs/cvseditor.h2
-rw-r--r--src/plugins/cvs/cvsplugin.cpp75
-rw-r--r--src/plugins/cvs/cvsplugin.h8
-rw-r--r--src/plugins/debugger/Debugger.pluginspec.in2
-rw-r--r--src/plugins/debugger/breakhandler.cpp10
-rw-r--r--src/plugins/debugger/breakpoint.cpp2
-rw-r--r--src/plugins/debugger/breakwindow.cpp7
-rw-r--r--src/plugins/debugger/cdb/cdb.pri1
-rw-r--r--src/plugins/debugger/cdb/cdbengine.cpp81
-rw-r--r--src/plugins/debugger/cdb/cdbengine.h2
-rw-r--r--src/plugins/debugger/cdb/cdboptionspage.cpp10
-rw-r--r--src/plugins/debugger/cdb/cdbparsehelpers.cpp47
-rw-r--r--src/plugins/debugger/cdb/cdbparsehelpers.h2
-rw-r--r--src/plugins/debugger/commonoptionspage.cpp6
-rw-r--r--src/plugins/debugger/debugger.pro20
-rw-r--r--src/plugins/debugger/debugger.qbs442
-rw-r--r--src/plugins/debugger/debuggeractions.cpp25
-rw-r--r--src/plugins/debugger/debuggeractions.h15
-rw-r--r--src/plugins/debugger/debuggerconstants.h2
-rw-r--r--src/plugins/debugger/debuggercore.h9
-rw-r--r--src/plugins/debugger/debuggerdialogs.cpp31
-rw-r--r--src/plugins/debugger/debuggerdialogs.h3
-rw-r--r--src/plugins/debugger/debuggerengine.cpp111
-rw-r--r--src/plugins/debugger/debuggerengine.h7
-rw-r--r--src/plugins/debugger/debuggerinternalconstants.h1
-rw-r--r--src/plugins/debugger/debuggerkitconfigwidget.cpp1248
-rw-r--r--src/plugins/debugger/debuggerkitconfigwidget.h155
-rw-r--r--src/plugins/debugger/debuggerkitinformation.cpp392
-rw-r--r--src/plugins/debugger/debuggerkitinformation.h95
-rw-r--r--src/plugins/debugger/debuggermainwindow.cpp37
-rw-r--r--src/plugins/debugger/debuggerplugin.cpp333
-rw-r--r--src/plugins/debugger/debuggerplugin.h2
-rw-r--r--src/plugins/debugger/debuggerprotocol.cpp17
-rw-r--r--src/plugins/debugger/debuggerprotocol.h4
-rw-r--r--src/plugins/debugger/debuggerrunconfigurationaspect.cpp53
-rw-r--r--src/plugins/debugger/debuggerrunconfigurationaspect.h17
-rw-r--r--src/plugins/debugger/debuggerrunner.cpp36
-rw-r--r--src/plugins/debugger/debuggerstartparameters.h5
-rw-r--r--src/plugins/debugger/debuggertooltipmanager.cpp72
-rw-r--r--src/plugins/debugger/debuggertooltipmanager.h3
-rw-r--r--src/plugins/debugger/disassembleragent.cpp14
-rw-r--r--src/plugins/debugger/dumper.pro2
-rw-r--r--src/plugins/debugger/gdb/attachgdbadapter.cpp10
-rw-r--r--src/plugins/debugger/gdb/attachgdbadapter.h5
-rw-r--r--src/plugins/debugger/gdb/classicgdbengine.cpp14
-rw-r--r--src/plugins/debugger/gdb/coregdbadapter.cpp12
-rw-r--r--src/plugins/debugger/gdb/coregdbadapter.h4
-rw-r--r--src/plugins/debugger/gdb/gdb.pri16
-rw-r--r--src/plugins/debugger/gdb/gdbengine.cpp103
-rw-r--r--src/plugins/debugger/gdb/gdbengine.h13
-rw-r--r--src/plugins/debugger/gdb/gdboptionspage.cpp8
-rw-r--r--src/plugins/debugger/gdb/gdbplainengine.cpp (renamed from src/plugins/debugger/gdb/abstractplaingdbadapter.cpp)105
-rw-r--r--src/plugins/debugger/gdb/gdbplainengine.h (renamed from src/plugins/debugger/gdb/localplaingdbadapter.h)31
-rw-r--r--src/plugins/debugger/gdb/gdbprocess.cpp (renamed from src/plugins/debugger/gdb/localgdbprocess.cpp)52
-rw-r--r--src/plugins/debugger/gdb/gdbprocess.h (renamed from src/plugins/debugger/gdb/localgdbprocess.h)48
-rw-r--r--src/plugins/debugger/gdb/localplaingdbadapter.cpp123
-rw-r--r--src/plugins/debugger/gdb/pythongdbengine.cpp12
-rw-r--r--src/plugins/debugger/gdb/remotegdbprocess.cpp405
-rw-r--r--src/plugins/debugger/gdb/remotegdbprocess.h128
-rw-r--r--src/plugins/debugger/gdb/remotegdbserveradapter.cpp26
-rw-r--r--src/plugins/debugger/gdb/remotegdbserveradapter.h4
-rw-r--r--src/plugins/debugger/gdb/remoteplaingdbadapter.cpp126
-rw-r--r--src/plugins/debugger/gdb/startgdbserverdialog.cpp17
-rw-r--r--src/plugins/debugger/gdb/termgdbadapter.cpp10
-rw-r--r--src/plugins/debugger/gdb/termgdbadapter.h4
-rw-r--r--src/plugins/debugger/imageviewer.cpp4
-rw-r--r--src/plugins/debugger/lldb/lldb.pri2
-rw-r--r--src/plugins/debugger/lldb/lldbengine.cpp40
-rw-r--r--src/plugins/debugger/lldb/lldbengine.h6
-rw-r--r--src/plugins/debugger/lldblib/guest/lldbengineguest.cpp4
-rw-r--r--src/plugins/debugger/lldblib/ipcengineguest.h10
-rw-r--r--src/plugins/debugger/lldblib/ipcenginehost.cpp28
-rw-r--r--src/plugins/debugger/lldblib/ipcenginehost.h10
-rw-r--r--src/plugins/debugger/lldblib/lldbenginehost.cpp34
-rw-r--r--src/plugins/debugger/lldblib/lldboptionspage.cpp6
-rw-r--r--src/plugins/debugger/loadcoredialog.cpp4
-rw-r--r--src/plugins/debugger/logwindow.cpp28
-rw-r--r--src/plugins/debugger/logwindow.h2
-rw-r--r--src/plugins/debugger/memoryagent.cpp10
-rw-r--r--src/plugins/debugger/moduleshandler.cpp2
-rw-r--r--src/plugins/debugger/pdb/pdbengine.cpp34
-rw-r--r--src/plugins/debugger/pdb/pdbengine.h2
-rw-r--r--src/plugins/debugger/procinterrupt.cpp93
-rw-r--r--src/plugins/debugger/qml/baseqmldebuggerclient.h2
-rw-r--r--src/plugins/debugger/qml/qmladapter.cpp2
-rw-r--r--src/plugins/debugger/qml/qmlcppengine.cpp14
-rw-r--r--src/plugins/debugger/qml/qmlcppengine.h2
-rw-r--r--src/plugins/debugger/qml/qmlengine.cpp97
-rw-r--r--src/plugins/debugger/qml/qmlengine.h6
-rw-r--r--src/plugins/debugger/qml/qmlinspectoradapter.cpp32
-rw-r--r--src/plugins/debugger/qml/qmlinspectoradapter.h2
-rw-r--r--src/plugins/debugger/qml/qmlinspectoragent.cpp10
-rw-r--r--src/plugins/debugger/qml/qmlv8debuggerclient.cpp78
-rw-r--r--src/plugins/debugger/qml/qscriptdebuggerclient.cpp10
-rw-r--r--src/plugins/debugger/registerhandler.cpp3
-rw-r--r--src/plugins/debugger/registerpostmortemaction.cpp2
-rw-r--r--src/plugins/debugger/registerpostmortemaction.h2
-rw-r--r--src/plugins/debugger/registerwindow.cpp4
-rw-r--r--src/plugins/debugger/script/script.pri9
-rw-r--r--src/plugins/debugger/script/scriptengine.cpp815
-rw-r--r--src/plugins/debugger/script/scriptengine.h129
-rw-r--r--src/plugins/debugger/shared/cdbsymbolpathlisteditor.cpp2
-rw-r--r--src/plugins/debugger/shared/shared.pri2
-rw-r--r--src/plugins/debugger/shared/symbolpathsdialog.cpp3
-rw-r--r--src/plugins/debugger/sourceagent.cpp9
-rw-r--r--src/plugins/debugger/sourcefileshandler.cpp2
-rw-r--r--src/plugins/debugger/sourceutils.cpp6
-rw-r--r--src/plugins/debugger/stackhandler.cpp3
-rw-r--r--src/plugins/debugger/stackwindow.cpp6
-rw-r--r--src/plugins/debugger/threadshandler.cpp1
-rw-r--r--src/plugins/debugger/watchdata.cpp1
-rw-r--r--src/plugins/debugger/watchhandler.cpp21
-rw-r--r--src/plugins/designer/Designer.pluginspec.in2
-rw-r--r--src/plugins/designer/README.txt2
-rw-r--r--src/plugins/designer/codemodelhelpers.cpp3
-rw-r--r--src/plugins/designer/cpp/cpp.pri2
-rw-r--r--src/plugins/designer/cpp/cppsettingspage.cpp2
-rw-r--r--src/plugins/designer/cpp/cppsettingspage.h2
-rw-r--r--src/plugins/designer/cpp/formclasswizard.cpp13
-rw-r--r--src/plugins/designer/cpp/formclasswizard.h14
-rw-r--r--src/plugins/designer/cpp/formclasswizarddialog.cpp2
-rw-r--r--src/plugins/designer/cpp/formclasswizardpage.cpp5
-rw-r--r--src/plugins/designer/cpp/formclasswizardparameters.cpp2
-rw-r--r--src/plugins/designer/designer.pro15
-rw-r--r--src/plugins/designer/designer.qbs129
-rw-r--r--src/plugins/designer/designerxmleditorwidget.cpp (renamed from src/plugins/designer/designerxmleditor.cpp)22
-rw-r--r--src/plugins/designer/designerxmleditorwidget.h (renamed from src/plugins/designer/designerxmleditor.h)16
-rw-r--r--src/plugins/designer/formeditorfactory.cpp28
-rw-r--r--src/plugins/designer/formeditorfactory.h9
-rw-r--r--src/plugins/designer/formeditorplugin.cpp44
-rw-r--r--src/plugins/designer/formeditorplugin.h5
-rw-r--r--src/plugins/designer/formeditorw.cpp229
-rw-r--r--src/plugins/designer/formwindoweditor.cpp161
-rw-r--r--src/plugins/designer/formwindoweditor.h35
-rw-r--r--src/plugins/designer/formwindowfile.cpp111
-rw-r--r--src/plugins/designer/formwindowfile.h33
-rw-r--r--src/plugins/designer/formwizard.cpp9
-rw-r--r--src/plugins/designer/formwizard.h12
-rw-r--r--src/plugins/designer/gotoslot_test.cpp161
-rw-r--r--src/plugins/designer/qtcreatorintegration.cpp53
-rw-r--r--src/plugins/designer/qtdesignerformclasscodegenerator.cpp2
-rw-r--r--src/plugins/designer/resourcehandler.cpp49
-rw-r--r--src/plugins/designer/resourcehandler.h3
-rw-r--r--src/plugins/diffeditor/DiffEditor.pluginspec.in2
-rw-r--r--src/plugins/diffeditor/diffeditor.cpp22
-rw-r--r--src/plugins/diffeditor/diffeditor.h5
-rw-r--r--src/plugins/diffeditor/diffeditorfactory.cpp21
-rw-r--r--src/plugins/diffeditor/diffeditorfactory.h6
-rw-r--r--src/plugins/diffeditor/diffeditorfile.cpp19
-rw-r--r--src/plugins/diffeditor/diffeditorfile.h5
-rw-r--r--src/plugins/diffeditor/diffeditorplugin.cpp3
-rw-r--r--src/plugins/diffeditor/diffeditorwidget.cpp236
-rw-r--r--src/plugins/diffeditor/diffeditorwidget.h10
-rw-r--r--src/plugins/diffeditor/diffshoweditor.cpp27
-rw-r--r--src/plugins/diffeditor/diffshoweditor.h7
-rw-r--r--src/plugins/diffeditor/diffshoweditorfactory.cpp21
-rw-r--r--src/plugins/diffeditor/diffshoweditorfactory.h6
-rw-r--r--src/plugins/fakevim/FakeVim.pluginspec.in2
-rw-r--r--src/plugins/fakevim/fakevim.qbs3
-rw-r--r--src/plugins/fakevim/fakevim_test.cpp243
-rw-r--r--src/plugins/fakevim/fakevimactions.h2
-rw-r--r--src/plugins/fakevim/fakevimhandler.cpp1816
-rw-r--r--src/plugins/fakevim/fakevimplugin.cpp77
-rw-r--r--src/plugins/find/Find.pluginspec.in2
-rw-r--r--src/plugins/find/basetextfind.cpp60
-rw-r--r--src/plugins/find/basetextfind.h25
-rw-r--r--src/plugins/find/currentdocumentfind.cpp20
-rw-r--r--src/plugins/find/currentdocumentfind.h17
-rw-r--r--src/plugins/find/find.qbs7
-rw-r--r--src/plugins/find/findplugin.cpp37
-rw-r--r--src/plugins/find/findplugin.h12
-rw-r--r--src/plugins/find/findtoolbar.cpp90
-rw-r--r--src/plugins/find/findtoolbar.h8
-rw-r--r--src/plugins/find/findtoolwindow.cpp12
-rw-r--r--src/plugins/find/ifindfilter.cpp31
-rw-r--r--src/plugins/find/ifindfilter.h4
-rw-r--r--src/plugins/find/searchresulttreeitems.cpp14
-rw-r--r--src/plugins/find/searchresulttreeview.cpp8
-rw-r--r--src/plugins/find/searchresulttreeview.h2
-rw-r--r--src/plugins/find/searchresultwidget.cpp2
-rw-r--r--src/plugins/find/searchresultwindow.h3
-rw-r--r--src/plugins/find/textfindconstants.h2
-rw-r--r--src/plugins/find/treeviewfind.cpp23
-rw-r--r--src/plugins/find/treeviewfind.h10
-rw-r--r--src/plugins/genericprojectmanager/GenericProjectManager.pluginspec.in2
-rw-r--r--src/plugins/genericprojectmanager/genericbuildconfiguration.cpp141
-rw-r--r--src/plugins/genericprojectmanager/genericbuildconfiguration.h28
-rw-r--r--src/plugins/genericprojectmanager/genericmakestep.cpp8
-rw-r--r--src/plugins/genericprojectmanager/genericproject.cpp46
-rw-r--r--src/plugins/genericprojectmanager/genericproject.h3
-rw-r--r--src/plugins/genericprojectmanager/genericprojectconstants.h2
-rw-r--r--src/plugins/genericprojectmanager/genericprojectfileseditor.cpp27
-rw-r--r--src/plugins/genericprojectmanager/genericprojectfileseditor.h6
-rw-r--r--src/plugins/genericprojectmanager/genericprojectnodes.cpp23
-rw-r--r--src/plugins/genericprojectmanager/genericprojectnodes.h17
-rw-r--r--src/plugins/genericprojectmanager/genericprojectplugin.cpp16
-rw-r--r--src/plugins/genericprojectmanager/genericprojectwizard.cpp32
-rw-r--r--src/plugins/genericprojectmanager/genericprojectwizard.h3
-rw-r--r--src/plugins/genericprojectmanager/pkgconfigtool.cpp8
-rw-r--r--src/plugins/genericprojectmanager/selectablefilesmodel.cpp2
-rw-r--r--src/plugins/git/Git.pluginspec.in2
-rw-r--r--src/plugins/git/annotationhighlighter.cpp3
-rw-r--r--src/plugins/git/annotationhighlighter.h2
-rw-r--r--src/plugins/git/branchdialog.cpp108
-rw-r--r--src/plugins/git/branchdialog.h2
-rw-r--r--src/plugins/git/branchdialog.ui20
-rw-r--r--src/plugins/git/branchmodel.cpp177
-rw-r--r--src/plugins/git/branchmodel.h7
-rw-r--r--src/plugins/git/changeselectiondialog.cpp11
-rw-r--r--src/plugins/git/changeselectiondialog.h4
-rw-r--r--src/plugins/git/clonewizard.cpp31
-rw-r--r--src/plugins/git/clonewizard.h14
-rw-r--r--src/plugins/git/clonewizardpage.cpp27
-rw-r--r--src/plugins/git/clonewizardpage.h4
-rw-r--r--src/plugins/git/commitdata.cpp5
-rw-r--r--src/plugins/git/commitdata.h8
-rw-r--r--src/plugins/git/gerrit/gerrit.pri2
-rw-r--r--src/plugins/git/gerrit/gerritdialog.cpp2
-rw-r--r--src/plugins/git/gerrit/gerritmodel.cpp12
-rw-r--r--src/plugins/git/gerrit/gerritoptionspage.cpp2
-rw-r--r--src/plugins/git/gerrit/gerritplugin.cpp55
-rw-r--r--src/plugins/git/gerrit/gerritplugin.h1
-rw-r--r--src/plugins/git/gerrit/gerritpushdialog.cpp43
-rw-r--r--src/plugins/git/gerrit/gerritpushdialog.h6
-rw-r--r--src/plugins/git/gitclient.cpp1034
-rw-r--r--src/plugins/git/gitclient.h65
-rw-r--r--src/plugins/git/giteditor.cpp121
-rw-r--r--src/plugins/git/giteditor.h8
-rw-r--r--src/plugins/git/githighlighters.cpp64
-rw-r--r--src/plugins/git/githighlighters.h25
-rw-r--r--src/plugins/git/gitorious/gitorious.pri1
-rw-r--r--src/plugins/git/gitorious/gitoriousclonewizard.cpp29
-rw-r--r--src/plugins/git/gitorious/gitoriousclonewizard.h14
-rw-r--r--src/plugins/git/gitplugin.cpp225
-rw-r--r--src/plugins/git/gitplugin.h5
-rw-r--r--src/plugins/git/gitsettings.cpp2
-rw-r--r--src/plugins/git/gitsettings.h1
-rw-r--r--src/plugins/git/gitsubmiteditor.cpp8
-rw-r--r--src/plugins/git/gitsubmiteditorwidget.cpp46
-rw-r--r--src/plugins/git/gitsubmiteditorwidget.h15
-rw-r--r--src/plugins/git/gitversioncontrol.cpp6
-rw-r--r--src/plugins/git/logchangedialog.cpp13
-rw-r--r--src/plugins/git/mergetool.cpp8
-rw-r--r--src/plugins/git/remotedialog.cpp9
-rw-r--r--src/plugins/git/remotedialog.h2
-rw-r--r--src/plugins/git/remotemodel.cpp3
-rw-r--r--src/plugins/git/settingspage.cpp2
-rw-r--r--src/plugins/git/settingspage.ui79
-rw-r--r--src/plugins/glsleditor/GLSLEditor.pluginspec.in2
-rw-r--r--src/plugins/glsleditor/glslautocompleter.cpp3
-rw-r--r--src/plugins/glsleditor/glslcompletionassist.h2
-rw-r--r--src/plugins/glsleditor/glsleditor.cpp76
-rw-r--r--src/plugins/glsleditor/glsleditor.h23
-rw-r--r--src/plugins/glsleditor/glsleditor.pro3
-rw-r--r--src/plugins/glsleditor/glsleditor.qbs3
-rw-r--r--src/plugins/glsleditor/glsleditoreditable.h6
-rw-r--r--src/plugins/glsleditor/glsleditorfactory.cpp38
-rw-r--r--src/plugins/glsleditor/glsleditorfactory.h9
-rw-r--r--src/plugins/glsleditor/glsleditorplugin.cpp200
-rw-r--r--src/plugins/glsleditor/glsleditorplugin.h51
-rw-r--r--src/plugins/glsleditor/glslfilewizard.cpp17
-rw-r--r--src/plugins/glsleditor/glslfilewizard.h16
-rw-r--r--src/plugins/glsleditor/glslhighlighter.cpp68
-rw-r--r--src/plugins/glsleditor/glslhighlighter.h9
-rw-r--r--src/plugins/glsleditor/glslhighlighterfactory.cpp49
-rw-r--r--src/plugins/glsleditor/glslhighlighterfactory.h51
-rw-r--r--src/plugins/helloworld/HelloWorld.pluginspec.in2
-rw-r--r--src/plugins/helloworld/helloworldwindow.h2
-rw-r--r--src/plugins/help/Help.pluginspec.in2
-rw-r--r--src/plugins/help/centralwidget.cpp3
-rw-r--r--src/plugins/help/docsettingspage.cpp24
-rw-r--r--src/plugins/help/filtersettingspage.cpp25
-rw-r--r--src/plugins/help/generalsettingspage.cpp34
-rw-r--r--src/plugins/help/help.pro1
-rw-r--r--src/plugins/help/help.qbs122
-rw-r--r--src/plugins/help/helpindexfilter.cpp9
-rw-r--r--src/plugins/help/helpplugin.cpp207
-rw-r--r--src/plugins/help/localhelpmanager.cpp3
-rw-r--r--src/plugins/help/openpagesmanager.cpp6
-rw-r--r--src/plugins/help/searchwidget.cpp3
-rw-r--r--src/plugins/help/xbelsupport.cpp3
-rw-r--r--src/plugins/imageviewer/ImageViewer.pluginspec.in2
-rw-r--r--src/plugins/imageviewer/imageviewer.cpp28
-rw-r--r--src/plugins/imageviewer/imageviewer.h4
-rw-r--r--src/plugins/imageviewer/imagevieweractionhandler.h2
-rw-r--r--src/plugins/imageviewer/imageviewerfactory.cpp57
-rw-r--r--src/plugins/imageviewer/imageviewerfactory.h4
-rw-r--r--src/plugins/imageviewer/imageviewerfile.cpp22
-rw-r--r--src/plugins/imageviewer/imageviewerfile.h5
-rw-r--r--src/plugins/imageviewer/imageviewerplugin.cpp2
-rw-r--r--src/plugins/locator/Locator.pluginspec.in2
-rw-r--r--src/plugins/locator/basefilefilter.cpp30
-rw-r--r--src/plugins/locator/commandlocator.cpp15
-rw-r--r--src/plugins/locator/executefilter.cpp19
-rw-r--r--src/plugins/locator/filesystemfilter.cpp42
-rw-r--r--src/plugins/locator/filesystemfilter.h5
-rw-r--r--src/plugins/locator/ilocatorfilter.cpp9
-rw-r--r--src/plugins/locator/ilocatorfilter.h1
-rw-r--r--src/plugins/locator/locator.pro14
-rw-r--r--src/plugins/locator/locator.qbs22
-rw-r--r--src/plugins/locator/locator_test.cpp178
-rw-r--r--src/plugins/locator/locatorfiltersfilter.cpp4
-rw-r--r--src/plugins/locator/locatorfiltertest.cpp89
-rw-r--r--src/plugins/locator/locatorfiltertest.h98
-rw-r--r--src/plugins/locator/locatormanager.cpp17
-rw-r--r--src/plugins/locator/locatormanager.h12
-rw-r--r--src/plugins/locator/locatorplugin.cpp39
-rw-r--r--src/plugins/locator/locatorplugin.h19
-rw-r--r--src/plugins/locator/locatorsearchutils.cpp65
-rw-r--r--src/plugins/locator/locatorsearchutils.h47
-rw-r--r--src/plugins/locator/locatorwidget.cpp68
-rw-r--r--src/plugins/locator/opendocumentsfilter.cpp46
-rw-r--r--src/plugins/locator/opendocumentsfilter.h12
-rw-r--r--src/plugins/locator/settingspage.h2
-rw-r--r--src/plugins/macros/Macros.pluginspec.in2
-rw-r--r--src/plugins/macros/findmacrohandler.cpp5
-rw-r--r--src/plugins/macros/findmacrohandler.h6
-rw-r--r--src/plugins/macros/imacrohandler.cpp2
-rw-r--r--src/plugins/macros/imacrohandler.h9
-rw-r--r--src/plugins/macros/macro.cpp2
-rw-r--r--src/plugins/macros/macro.h6
-rw-r--r--src/plugins/macros/macroevent.cpp2
-rw-r--r--src/plugins/macros/macroevent.h6
-rw-r--r--src/plugins/macros/macrolocatorfilter.cpp20
-rw-r--r--src/plugins/macros/macromanager.cpp21
-rw-r--r--src/plugins/macros/macromanager.h28
-rw-r--r--src/plugins/macros/macrooptionspage.h4
-rw-r--r--src/plugins/macros/macrooptionswidget.cpp4
-rw-r--r--src/plugins/macros/macros.pro1
-rw-r--r--src/plugins/macros/macros.qbs1
-rw-r--r--src/plugins/macros/macros_global.h41
-rw-r--r--src/plugins/macros/macrosplugin.cpp2
-rw-r--r--src/plugins/macros/macrosplugin.h3
-rw-r--r--src/plugins/macros/texteditormacrohandler.cpp6
-rw-r--r--src/plugins/macros/texteditormacrohandler.h10
-rw-r--r--src/plugins/madde/Madde.pluginspec.in2
-rw-r--r--src/plugins/madde/debianmanager.cpp4
-rw-r--r--src/plugins/madde/madde.pro1
-rw-r--r--src/plugins/madde/madde.qbs1
-rw-r--r--src/plugins/madde/maddedevice.cpp15
-rw-r--r--src/plugins/madde/maddedevice.h3
-rw-r--r--src/plugins/madde/maddedevicetester.cpp6
-rw-r--r--src/plugins/madde/maddedevicetester.h6
-rw-r--r--src/plugins/madde/maddeqemustartstep.cpp2
-rw-r--r--src/plugins/madde/maddeuploadandinstallpackagesteps.cpp2
-rw-r--r--src/plugins/madde/maemodeploybymountsteps.cpp4
-rw-r--r--src/plugins/madde/maemodeviceconfigwizard.cpp16
-rw-r--r--src/plugins/madde/maemoglobal.h10
-rw-r--r--src/plugins/madde/maemoinstalltosysrootstep.cpp8
-rw-r--r--src/plugins/madde/maemopackagecreationstep.cpp4
-rw-r--r--src/plugins/madde/maemopublisherfremantlefree.cpp4
-rw-r--r--src/plugins/madde/maemoqemumanager.cpp39
-rw-r--r--src/plugins/madde/maemoqemuruntimeparser.cpp4
-rw-r--r--src/plugins/madde/maemorunconfiguration.cpp18
-rw-r--r--src/plugins/madde/maemorunconfiguration.h2
-rw-r--r--src/plugins/madde/qt4maemodeployconfiguration.cpp6
-rw-r--r--src/plugins/mercurial/Mercurial.pluginspec.in2
-rw-r--r--src/plugins/mercurial/annotationhighlighter.cpp3
-rw-r--r--src/plugins/mercurial/annotationhighlighter.h2
-rw-r--r--src/plugins/mercurial/clonewizard.cpp40
-rw-r--r--src/plugins/mercurial/clonewizard.h11
-rw-r--r--src/plugins/mercurial/commiteditor.cpp3
-rw-r--r--src/plugins/mercurial/mercurialclient.cpp47
-rw-r--r--src/plugins/mercurial/mercurialclient.h10
-rw-r--r--src/plugins/mercurial/mercurialcommitwidget.cpp3
-rw-r--r--src/plugins/mercurial/mercurialeditor.cpp9
-rw-r--r--src/plugins/mercurial/mercurialeditor.h2
-rw-r--r--src/plugins/mercurial/mercurialplugin.cpp21
-rw-r--r--src/plugins/mercurial/mercurialplugin.h6
-rw-r--r--src/plugins/mercurial/optionspage.cpp9
-rw-r--r--src/plugins/perforce/Perforce.pluginspec.in2
-rw-r--r--src/plugins/perforce/annotationhighlighter.cpp3
-rw-r--r--src/plugins/perforce/annotationhighlighter.h1
-rw-r--r--src/plugins/perforce/perforceeditor.cpp10
-rw-r--r--src/plugins/perforce/perforceeditor.h3
-rw-r--r--src/plugins/perforce/perforceplugin.cpp132
-rw-r--r--src/plugins/perforce/perforceplugin.h46
-rw-r--r--src/plugins/perforce/perforcesettings.cpp5
-rw-r--r--src/plugins/perforce/perforcesettings.h2
-rw-r--r--src/plugins/perforce/perforcesubmiteditor.cpp7
-rw-r--r--src/plugins/perforce/perforcesubmiteditor.h2
-rw-r--r--src/plugins/perforce/settingspage.cpp4
-rw-r--r--src/plugins/plugins.pro40
-rw-r--r--src/plugins/plugins.qbs2
-rw-r--r--src/plugins/projectexplorer/ProjectExplorer.pluginspec.in2
-rw-r--r--src/plugins/projectexplorer/abi.cpp74
-rw-r--r--src/plugins/projectexplorer/abi.h2
-rw-r--r--src/plugins/projectexplorer/abstractmsvctoolchain.cpp15
-rw-r--r--src/plugins/projectexplorer/abstractmsvctoolchain.h4
-rw-r--r--src/plugins/projectexplorer/abstractprocessstep.cpp3
-rw-r--r--src/plugins/projectexplorer/allprojectsfilter.cpp7
-rw-r--r--src/plugins/projectexplorer/allprojectsfilter.h7
-rw-r--r--src/plugins/projectexplorer/allprojectsfind.cpp14
-rw-r--r--src/plugins/projectexplorer/allprojectsfind.h4
-rw-r--r--src/plugins/projectexplorer/applicationlauncher.cpp23
-rw-r--r--src/plugins/projectexplorer/applicationlauncher.h3
-rw-r--r--src/plugins/projectexplorer/appoutputpane.cpp20
-rw-r--r--src/plugins/projectexplorer/buildconfiguration.cpp58
-rw-r--r--src/plugins/projectexplorer/buildconfiguration.h33
-rw-r--r--src/plugins/projectexplorer/buildenvironmentwidget.h2
-rw-r--r--src/plugins/projectexplorer/buildinfo.h74
-rw-r--r--src/plugins/projectexplorer/buildmanager.cpp139
-rw-r--r--src/plugins/projectexplorer/buildmanager.h79
-rw-r--r--src/plugins/projectexplorer/buildprogress.cpp10
-rw-r--r--src/plugins/projectexplorer/buildsettingspropertiespage.cpp47
-rw-r--r--src/plugins/projectexplorer/buildsettingspropertiespage.h4
-rw-r--r--src/plugins/projectexplorer/buildstep.cpp5
-rw-r--r--src/plugins/projectexplorer/buildsteplist.cpp8
-rw-r--r--src/plugins/projectexplorer/buildsteplist.h1
-rw-r--r--src/plugins/projectexplorer/cesdkhandler.cpp4
-rw-r--r--src/plugins/projectexplorer/cesdkhandler.h2
-rw-r--r--src/plugins/projectexplorer/clangparser.cpp6
-rw-r--r--src/plugins/projectexplorer/codestylesettingspropertiespage.cpp2
-rw-r--r--src/plugins/projectexplorer/compileoutputwindow.cpp21
-rw-r--r--src/plugins/projectexplorer/compileoutputwindow.h5
-rw-r--r--src/plugins/projectexplorer/currentprojectfilter.cpp6
-rw-r--r--src/plugins/projectexplorer/currentprojectfilter.h4
-rw-r--r--src/plugins/projectexplorer/currentprojectfind.cpp23
-rw-r--r--src/plugins/projectexplorer/currentprojectfind.h10
-rw-r--r--src/plugins/projectexplorer/customparser.cpp287
-rw-r--r--src/plugins/projectexplorer/customparser.h94
-rw-r--r--src/plugins/projectexplorer/customparserconfigdialog.cpp173
-rw-r--r--src/plugins/projectexplorer/customparserconfigdialog.h74
-rw-r--r--src/plugins/projectexplorer/customparserconfigdialog.ui244
-rw-r--r--src/plugins/projectexplorer/customtoolchain.cpp139
-rw-r--r--src/plugins/projectexplorer/customtoolchain.h40
-rw-r--r--src/plugins/projectexplorer/customwizard/customwizard.cpp60
-rw-r--r--src/plugins/projectexplorer/customwizard/customwizard.h38
-rw-r--r--src/plugins/projectexplorer/customwizard/customwizard.pri1
-rw-r--r--src/plugins/projectexplorer/customwizard/customwizardparameters.cpp75
-rw-r--r--src/plugins/projectexplorer/customwizard/customwizardparameters.h4
-rw-r--r--src/plugins/projectexplorer/customwizard/customwizardpreprocessor.cpp2
-rw-r--r--src/plugins/projectexplorer/dependenciespanel.cpp54
-rw-r--r--src/plugins/projectexplorer/dependenciespanel.h33
-rw-r--r--src/plugins/projectexplorer/deployconfiguration.cpp14
-rw-r--r--src/plugins/projectexplorer/devicesupport/desktopdevice.cpp16
-rw-r--r--src/plugins/projectexplorer/devicesupport/desktopdevice.h5
-rw-r--r--src/plugins/projectexplorer/devicesupport/desktopdeviceconfigurationwidget.cpp2
-rw-r--r--src/plugins/projectexplorer/devicesupport/desktopdevicefactory.cpp2
-rw-r--r--src/plugins/projectexplorer/devicesupport/desktopdeviceprocess.cpp124
-rw-r--r--src/plugins/projectexplorer/devicesupport/desktopdeviceprocess.h72
-rw-r--r--src/plugins/projectexplorer/devicesupport/desktopprocesssignaloperation.cpp207
-rw-r--r--src/plugins/projectexplorer/devicesupport/desktopprocesssignaloperation.h62
-rw-r--r--src/plugins/projectexplorer/devicesupport/deviceapplicationrunner.cpp75
-rw-r--r--src/plugins/projectexplorer/devicesupport/deviceapplicationrunner.h16
-rw-r--r--src/plugins/projectexplorer/devicesupport/devicecheckbuildstep.cpp2
-rw-r--r--src/plugins/projectexplorer/devicesupport/devicemanager.cpp26
-rw-r--r--src/plugins/projectexplorer/devicesupport/devicemanager.h2
-rw-r--r--src/plugins/projectexplorer/devicesupport/devicemanagermodel.cpp2
-rw-r--r--src/plugins/projectexplorer/devicesupport/deviceprocess.cpp52
-rw-r--r--src/plugins/projectexplorer/devicesupport/deviceprocess.h (renamed from src/plugins/debugger/gdb/abstractgdbprocess.h)66
-rw-r--r--src/plugins/projectexplorer/devicesupport/deviceprocessesdialog.cpp16
-rw-r--r--src/plugins/projectexplorer/devicesupport/deviceprocessesdialog.h4
-rw-r--r--src/plugins/projectexplorer/devicesupport/deviceprocesslist.cpp12
-rw-r--r--src/plugins/projectexplorer/devicesupport/deviceprocesslist.h14
-rw-r--r--src/plugins/projectexplorer/devicesupport/devicesettingswidget.cpp25
-rw-r--r--src/plugins/projectexplorer/devicesupport/devicesettingswidget.h3
-rw-r--r--src/plugins/projectexplorer/devicesupport/devicesettingswidget.ui233
-rw-r--r--src/plugins/projectexplorer/devicesupport/devicetestdialog.cpp (renamed from src/plugins/remotelinux/linuxdevicetestdialog.cpp)47
-rw-r--r--src/plugins/projectexplorer/devicesupport/devicetestdialog.h (renamed from src/plugins/remotelinux/linuxdevicetestdialog.h)29
-rw-r--r--src/plugins/projectexplorer/devicesupport/devicetestdialog.ui (renamed from src/plugins/remotelinux/linuxdevicetestdialog.ui)8
-rw-r--r--src/plugins/projectexplorer/devicesupport/deviceusedportsgatherer.cpp4
-rw-r--r--src/plugins/projectexplorer/devicesupport/idevice.cpp43
-rw-r--r--src/plugins/projectexplorer/devicesupport/idevice.h63
-rw-r--r--src/plugins/projectexplorer/devicesupport/localprocesslist.cpp64
-rw-r--r--src/plugins/projectexplorer/devicesupport/localprocesslist.h8
-rw-r--r--src/plugins/projectexplorer/devicesupport/sshdeviceprocess.cpp331
-rw-r--r--src/plugins/projectexplorer/devicesupport/sshdeviceprocess.h88
-rw-r--r--src/plugins/projectexplorer/devicesupport/sshdeviceprocesslist.cpp46
-rw-r--r--src/plugins/projectexplorer/devicesupport/sshdeviceprocesslist.h6
-rw-r--r--src/plugins/projectexplorer/editorconfiguration.cpp121
-rw-r--r--src/plugins/projectexplorer/editorconfiguration.h4
-rw-r--r--src/plugins/projectexplorer/environmentaspect.cpp33
-rw-r--r--src/plugins/projectexplorer/environmentaspect.h14
-rw-r--r--src/plugins/projectexplorer/environmentitemswidget.cpp3
-rw-r--r--src/plugins/projectexplorer/foldernavigationwidget.cpp32
-rw-r--r--src/plugins/projectexplorer/foldernavigationwidget.h3
-rw-r--r--src/plugins/projectexplorer/gccparser.cpp70
-rw-r--r--src/plugins/projectexplorer/gcctoolchain.cpp276
-rw-r--r--src/plugins/projectexplorer/gcctoolchain.h12
-rw-r--r--src/plugins/projectexplorer/gcctoolchainfactories.h20
-rw-r--r--src/plugins/projectexplorer/gnumakeparser.cpp21
-rw-r--r--src/plugins/projectexplorer/importwidget.cpp (renamed from src/plugins/qt4projectmanager/wizards/importwidget.cpp)4
-rw-r--r--src/plugins/projectexplorer/importwidget.h (renamed from src/plugins/qt4projectmanager/wizards/importwidget.h)4
-rw-r--r--src/plugins/projectexplorer/ioutputparser.cpp2
-rw-r--r--src/plugins/projectexplorer/iprojectmanager.h3
-rw-r--r--src/plugins/projectexplorer/kit.cpp144
-rw-r--r--src/plugins/projectexplorer/kit.h14
-rw-r--r--src/plugins/projectexplorer/kitchooser.cpp48
-rw-r--r--src/plugins/projectexplorer/kitchooser.h15
-rw-r--r--src/plugins/projectexplorer/kitconfigwidget.cpp56
-rw-r--r--src/plugins/projectexplorer/kitconfigwidget.h14
-rw-r--r--src/plugins/projectexplorer/kitinformation.cpp146
-rw-r--r--src/plugins/projectexplorer/kitinformation.h21
-rw-r--r--src/plugins/projectexplorer/kitinformationconfigwidget.cpp58
-rw-r--r--src/plugins/projectexplorer/kitinformationconfigwidget.h14
-rw-r--r--src/plugins/projectexplorer/kitmanager.cpp106
-rw-r--r--src/plugins/projectexplorer/kitmanager.h56
-rw-r--r--src/plugins/projectexplorer/kitmanagerconfigwidget.cpp49
-rw-r--r--src/plugins/projectexplorer/kitmanagerconfigwidget.h2
-rw-r--r--src/plugins/projectexplorer/kitmodel.cpp11
-rw-r--r--src/plugins/projectexplorer/ldparser.cpp25
-rw-r--r--src/plugins/projectexplorer/linuxiccparser.cpp13
-rw-r--r--src/plugins/projectexplorer/localapplicationruncontrol.cpp16
-rw-r--r--src/plugins/projectexplorer/localapplicationruncontrol.h2
-rw-r--r--src/plugins/projectexplorer/localenvironmentaspect.cpp16
-rw-r--r--src/plugins/projectexplorer/localenvironmentaspect.h7
-rw-r--r--src/plugins/projectexplorer/miniprojecttargetselector.cpp188
-rw-r--r--src/plugins/projectexplorer/miniprojecttargetselector.h29
-rw-r--r--src/plugins/projectexplorer/msvcparser.cpp86
-rw-r--r--src/plugins/projectexplorer/msvctoolchain.cpp38
-rw-r--r--src/plugins/projectexplorer/msvctoolchain.h9
-rw-r--r--src/plugins/projectexplorer/nodesvisitor.cpp8
-rw-r--r--src/plugins/projectexplorer/osparser.cpp (renamed from src/plugins/cmakeprojectmanager/cmakeuicodemodelsupport.cpp)51
-rw-r--r--src/plugins/projectexplorer/osparser.h59
-rw-r--r--src/plugins/projectexplorer/pluginfilefactory.cpp23
-rw-r--r--src/plugins/projectexplorer/pluginfilefactory.h5
-rw-r--r--src/plugins/projectexplorer/processstep.cpp4
-rw-r--r--src/plugins/projectexplorer/project.cpp53
-rw-r--r--src/plugins/projectexplorer/project.h10
-rw-r--r--src/plugins/projectexplorer/projectexplorer.cpp832
-rw-r--r--src/plugins/projectexplorer/projectexplorer.h16
-rw-r--r--src/plugins/projectexplorer/projectexplorer.pro45
-rw-r--r--src/plugins/projectexplorer/projectexplorer.qbs562
-rw-r--r--src/plugins/projectexplorer/projectexplorerconstants.h7
-rw-r--r--src/plugins/projectexplorer/projectexplorersettingspage.cpp4
-rw-r--r--src/plugins/projectexplorer/projectfilewizardextension.cpp41
-rw-r--r--src/plugins/projectexplorer/projectimporter.cpp130
-rw-r--r--src/plugins/projectexplorer/projectimporter.h78
-rw-r--r--src/plugins/projectexplorer/projectmodels.cpp5
-rw-r--r--src/plugins/projectexplorer/projectnodes.cpp31
-rw-r--r--src/plugins/projectexplorer/projectnodes.h19
-rw-r--r--src/plugins/projectexplorer/projecttreewidget.cpp26
-rw-r--r--src/plugins/projectexplorer/projectwelcomepage.cpp57
-rw-r--r--src/plugins/projectexplorer/projectwelcomepage.h10
-rw-r--r--src/plugins/projectexplorer/projectwindow.cpp19
-rw-r--r--src/plugins/projectexplorer/removetaskhandler.cpp3
-rw-r--r--src/plugins/projectexplorer/runconfiguration.cpp114
-rw-r--r--src/plugins/projectexplorer/runconfiguration.h93
-rw-r--r--src/plugins/projectexplorer/runsettingspropertiespage.cpp18
-rw-r--r--src/plugins/projectexplorer/session.cpp505
-rw-r--r--src/plugins/projectexplorer/session.h124
-rw-r--r--src/plugins/projectexplorer/sessiondialog.cpp38
-rw-r--r--src/plugins/projectexplorer/sessiondialog.h11
-rw-r--r--src/plugins/projectexplorer/settingsaccessor.cpp188
-rw-r--r--src/plugins/projectexplorer/target.cpp27
-rw-r--r--src/plugins/projectexplorer/target.h1
-rw-r--r--src/plugins/projectexplorer/targetsettingspanel.cpp13
-rw-r--r--src/plugins/projectexplorer/targetsetuppage.cpp533
-rw-r--r--src/plugins/projectexplorer/targetsetuppage.h (renamed from src/plugins/qt4projectmanager/wizards/targetsetuppage.h)64
-rw-r--r--src/plugins/projectexplorer/targetsetupwidget.cpp (renamed from src/plugins/qt4projectmanager/qt4targetsetupwidget.cpp)170
-rw-r--r--src/plugins/projectexplorer/targetsetupwidget.h (renamed from src/plugins/qt4projectmanager/qt4targetsetupwidget.h)52
-rw-r--r--src/plugins/projectexplorer/task.cpp6
-rw-r--r--src/plugins/projectexplorer/task.h4
-rw-r--r--src/plugins/projectexplorer/taskhub.cpp57
-rw-r--r--src/plugins/projectexplorer/taskhub.h45
-rw-r--r--src/plugins/projectexplorer/taskmodel.cpp2
-rw-r--r--src/plugins/projectexplorer/taskwindow.cpp27
-rw-r--r--src/plugins/projectexplorer/taskwindow.h2
-rw-r--r--src/plugins/projectexplorer/toolchain.cpp31
-rw-r--r--src/plugins/projectexplorer/toolchain.h27
-rw-r--r--src/plugins/projectexplorer/toolchainmanager.cpp199
-rw-r--r--src/plugins/projectexplorer/toolchainmanager.h41
-rw-r--r--src/plugins/projectexplorer/toolchainoptionspage.cpp9
-rw-r--r--src/plugins/projectexplorer/unconfiguredprojectpanel.cpp (renamed from src/plugins/qt4projectmanager/unconfiguredprojectpanel.cpp)67
-rw-r--r--src/plugins/projectexplorer/unconfiguredprojectpanel.h (renamed from src/plugins/qt4projectmanager/unconfiguredprojectpanel.h)22
-rw-r--r--src/plugins/projectexplorer/vcsannotatetaskhandler.cpp25
-rw-r--r--src/plugins/projectexplorer/wincetoolchain.cpp23
-rw-r--r--src/plugins/projectexplorer/wincetoolchain.h5
-rw-r--r--src/plugins/pythoneditor/PythonEditor.pluginspec.in2
-rw-r--r--src/plugins/pythoneditor/pythoneditor.cpp13
-rw-r--r--src/plugins/pythoneditor/pythoneditor.h6
-rw-r--r--src/plugins/pythoneditor/pythoneditor.pro3
-rw-r--r--src/plugins/pythoneditor/pythoneditor.qbs67
-rw-r--r--src/plugins/pythoneditor/pythoneditorfactory.cpp21
-rw-r--r--src/plugins/pythoneditor/pythoneditorfactory.h20
-rw-r--r--src/plugins/pythoneditor/pythoneditorplugin.cpp36
-rw-r--r--src/plugins/pythoneditor/pythoneditorplugin.h2
-rw-r--r--src/plugins/pythoneditor/pythoneditorwidget.cpp2
-rw-r--r--src/plugins/pythoneditor/pythoneditorwidget.h6
-rw-r--r--src/plugins/pythoneditor/tools/lexical/pythonscanner.cpp5
-rw-r--r--src/plugins/pythoneditor/tools/pythonhighlighter.cpp59
-rw-r--r--src/plugins/pythoneditor/tools/pythonhighlighter.h10
-rw-r--r--src/plugins/pythoneditor/tools/pythonhighlighterfactory.cpp45
-rw-r--r--src/plugins/pythoneditor/tools/pythonhighlighterfactory.h51
-rw-r--r--src/plugins/pythoneditor/tools/pythonindenter.h3
-rw-r--r--src/plugins/pythoneditor/wizard/pythonclassnamepage.cpp2
-rw-r--r--src/plugins/pythoneditor/wizard/pythonclassnamepage.h2
-rw-r--r--src/plugins/pythoneditor/wizard/pythonclasswizard.cpp30
-rw-r--r--src/plugins/pythoneditor/wizard/pythonclasswizard.h7
-rw-r--r--src/plugins/pythoneditor/wizard/pythonclasswizarddialog.cpp2
-rw-r--r--src/plugins/pythoneditor/wizard/pythonclasswizarddialog.h2
-rw-r--r--src/plugins/pythoneditor/wizard/pythonfilewizard.cpp28
-rw-r--r--src/plugins/pythoneditor/wizard/pythonfilewizard.h10
-rw-r--r--src/plugins/pythoneditor/wizard/pythonsourcegenerator.cpp2
-rw-r--r--src/plugins/pythoneditor/wizard/pythonsourcegenerator.h5
-rw-r--r--src/plugins/qbsprojectmanager/QbsProjectManager.pluginspec.in2
-rw-r--r--src/plugins/qbsprojectmanager/defaultpropertyprovider.cpp125
-rw-r--r--src/plugins/qbsprojectmanager/defaultpropertyprovider.h48
-rw-r--r--src/plugins/qbsprojectmanager/propertyprovider.h53
-rw-r--r--src/plugins/qbsprojectmanager/qbsbuildconfiguration.cpp142
-rw-r--r--src/plugins/qbsprojectmanager/qbsbuildconfiguration.h23
-rw-r--r--src/plugins/qbsprojectmanager/qbsbuildconfigurationwidget.cpp15
-rw-r--r--src/plugins/qbsprojectmanager/qbsbuildconfigurationwidget.h1
-rw-r--r--src/plugins/qbsprojectmanager/qbsbuildinfo.h52
-rw-r--r--src/plugins/qbsprojectmanager/qbsbuildstep.cpp2
-rw-r--r--src/plugins/qbsprojectmanager/qbsbuildstep.h1
-rw-r--r--src/plugins/qbsprojectmanager/qbsbuildstepconfigwidget.ui2
-rw-r--r--src/plugins/qbsprojectmanager/qbsconstants.h62
-rw-r--r--src/plugins/qbsprojectmanager/qbsdeployconfigurationfactory.cpp9
-rw-r--r--src/plugins/qbsprojectmanager/qbslogsink.cpp7
-rw-r--r--src/plugins/qbsprojectmanager/qbsnodes.cpp33
-rw-r--r--src/plugins/qbsprojectmanager/qbsnodes.h23
-rw-r--r--src/plugins/qbsprojectmanager/qbsproject.cpp237
-rw-r--r--src/plugins/qbsprojectmanager/qbsproject.h16
-rw-r--r--src/plugins/qbsprojectmanager/qbsprojectfile.cpp19
-rw-r--r--src/plugins/qbsprojectmanager/qbsprojectfile.h3
-rw-r--r--src/plugins/qbsprojectmanager/qbsprojectmanager.cpp116
-rw-r--r--src/plugins/qbsprojectmanager/qbsprojectmanager.h11
-rw-r--r--src/plugins/qbsprojectmanager/qbsprojectmanager.pro27
-rw-r--r--src/plugins/qbsprojectmanager/qbsprojectmanager.qbs27
-rw-r--r--src/plugins/qbsprojectmanager/qbsprojectmanagerconstants.h5
-rw-r--r--src/plugins/qbsprojectmanager/qbsprojectmanagerplugin.cpp87
-rw-r--r--src/plugins/qbsprojectmanager/qbsprojectmanagerplugin.h4
-rw-r--r--src/plugins/qbsprojectmanager/qbsrunconfiguration.cpp21
-rw-r--r--src/plugins/qbsprojectmanager/qbsrunconfiguration.h1
-rw-r--r--src/plugins/qmldesigner/QmlDesigner.pluginspec.in5
-rw-r--r--src/plugins/qmldesigner/components/componentcore/componentcore.pri4
-rw-r--r--src/plugins/qmldesigner/components/componentcore/crumblebar.cpp (renamed from src/plugins/qmldesigner/components/formeditor/formeditorcrumblebar.cpp)70
-rw-r--r--src/plugins/qmldesigner/components/componentcore/crumblebar.h (renamed from src/plugins/qmldesigner/components/formeditor/formeditorcrumblebar.h)13
-rw-r--r--src/plugins/qmldesigner/components/componentcore/designeractionmanager.cpp204
-rw-r--r--src/plugins/qmldesigner/components/componentcore/designeractionmanager.h23
-rw-r--r--src/plugins/qmldesigner/components/componentcore/designeractionmanagerview.cpp196
-rw-r--r--src/plugins/qmldesigner/components/componentcore/designeractionmanagerview.h100
-rw-r--r--src/plugins/qmldesigner/components/componentcore/modelnodecontextmenu.cpp9
-rw-r--r--src/plugins/qmldesigner/components/componentcore/modelnodecontextmenu.h6
-rw-r--r--src/plugins/qmldesigner/components/componentcore/modelnodecontextmenu_helper.cpp169
-rw-r--r--src/plugins/qmldesigner/components/componentcore/modelnodecontextmenu_helper.h6
-rw-r--r--src/plugins/qmldesigner/components/componentcore/modelnodeoperations.cpp478
-rw-r--r--src/plugins/qmldesigner/components/componentcore/selectioncontext.cpp39
-rw-r--r--src/plugins/qmldesigner/components/componentcore/selectioncontext.h19
-rw-r--r--src/plugins/qmldesigner/components/debugview/debugview.cpp35
-rw-r--r--src/plugins/qmldesigner/components/debugview/debugview.h10
-rw-r--r--src/plugins/qmldesigner/components/formeditor/abstractformeditortool.cpp43
-rw-r--r--src/plugins/qmldesigner/components/formeditor/abstractformeditortool.h3
-rw-r--r--src/plugins/qmldesigner/components/formeditor/anchorindicator.cpp178
-rw-r--r--src/plugins/qmldesigner/components/formeditor/anchorindicator.h70
-rw-r--r--src/plugins/qmldesigner/components/formeditor/anchorindicatorgraphicsitem.cpp262
-rw-r--r--src/plugins/qmldesigner/components/formeditor/anchorindicatorgraphicsitem.h (renamed from src/plugins/qmldesigner/components/propertyeditor/resetwidget.h)85
-rw-r--r--src/plugins/qmldesigner/components/formeditor/bindingindicator.cpp191
-rw-r--r--src/plugins/qmldesigner/components/formeditor/bindingindicator.h68
-rw-r--r--src/plugins/qmldesigner/components/formeditor/bindingindicatorgraphicsitem.cpp65
-rw-r--r--src/plugins/qmldesigner/components/formeditor/bindingindicatorgraphicsitem.h55
-rw-r--r--src/plugins/qmldesigner/components/formeditor/contentnoteditableindicator.cpp106
-rw-r--r--src/plugins/qmldesigner/components/formeditor/contentnoteditableindicator.h (renamed from src/plugins/qt4projectmanager/qtuicodemodelsupport.h)48
-rw-r--r--src/plugins/qmldesigner/components/formeditor/dragtool.cpp8
-rw-r--r--src/plugins/qmldesigner/components/formeditor/formeditor.pri16
-rw-r--r--src/plugins/qmldesigner/components/formeditor/formeditoritem.cpp93
-rw-r--r--src/plugins/qmldesigner/components/formeditor/formeditoritem.h9
-rw-r--r--src/plugins/qmldesigner/components/formeditor/formeditorview.cpp134
-rw-r--r--src/plugins/qmldesigner/components/formeditor/formeditorview.h13
-rw-r--r--src/plugins/qmldesigner/components/formeditor/formeditorwidget.cpp19
-rw-r--r--src/plugins/qmldesigner/components/formeditor/formeditorwidget.h4
-rw-r--r--src/plugins/qmldesigner/components/formeditor/movemanipulator.cpp30
-rw-r--r--src/plugins/qmldesigner/components/formeditor/movemanipulator.h6
-rw-r--r--src/plugins/qmldesigner/components/formeditor/movetool.cpp33
-rw-r--r--src/plugins/qmldesigner/components/formeditor/movetool.h7
-rw-r--r--src/plugins/qmldesigner/components/formeditor/resizehandleitem.cpp18
-rw-r--r--src/plugins/qmldesigner/components/formeditor/resizehandleitem.h6
-rw-r--r--src/plugins/qmldesigner/components/formeditor/resizeindicator.cpp21
-rw-r--r--src/plugins/qmldesigner/components/formeditor/resizeindicator.h19
-rw-r--r--src/plugins/qmldesigner/components/formeditor/resizemanipulator.cpp44
-rw-r--r--src/plugins/qmldesigner/components/formeditor/resizemanipulator.h2
-rw-r--r--src/plugins/qmldesigner/components/formeditor/resizetool.cpp6
-rw-r--r--src/plugins/qmldesigner/components/formeditor/resizetool.h2
-rw-r--r--src/plugins/qmldesigner/components/formeditor/rubberbandselectionmanipulator.cpp6
-rw-r--r--src/plugins/qmldesigner/components/formeditor/selectiontool.cpp33
-rw-r--r--src/plugins/qmldesigner/components/formeditor/selectiontool.h6
-rw-r--r--src/plugins/qmldesigner/components/formeditor/singleselectionmanipulator.cpp6
-rw-r--r--src/plugins/qmldesigner/components/formeditor/singleselectionmanipulator.h2
-rw-r--r--src/plugins/qmldesigner/components/formeditor/snapper.cpp4
-rw-r--r--src/plugins/qmldesigner/components/formeditor/toolbox.cpp37
-rw-r--r--src/plugins/qmldesigner/components/formeditor/toolbox.h6
-rw-r--r--src/plugins/qmldesigner/components/importmanager/importlabel.cpp76
-rw-r--r--src/plugins/qmldesigner/components/importmanager/importlabel.h (renamed from src/plugins/cpaster/codepastersettings.h)39
-rw-r--r--src/plugins/qmldesigner/components/importmanager/importmanager.pri11
-rw-r--r--src/plugins/qmldesigner/components/importmanager/importmanagerview.cpp257
-rw-r--r--src/plugins/qmldesigner/components/importmanager/importmanagerview.h106
-rw-r--r--src/plugins/qmldesigner/components/importmanager/importswidget.cpp156
-rw-r--r--src/plugins/qmldesigner/components/importmanager/importswidget.h (renamed from src/plugins/qmldesigner/components/propertyeditor/basiclayouts.cpp)67
-rw-r--r--src/plugins/qmldesigner/components/integration/componentview.cpp7
-rw-r--r--src/plugins/qmldesigner/components/integration/componentview.h2
-rw-r--r--src/plugins/qmldesigner/components/integration/designdocument.cpp147
-rw-r--r--src/plugins/qmldesigner/components/integration/designdocument.h17
-rw-r--r--src/plugins/qmldesigner/components/integration/designdocumentview.cpp6
-rw-r--r--src/plugins/qmldesigner/components/integration/designdocumentview.h2
-rw-r--r--src/plugins/qmldesigner/components/itemlibrary/customdraganddrop.cpp3
-rw-r--r--src/plugins/qmldesigner/components/itemlibrary/itemlibrary.pri4
-rw-r--r--src/plugins/qmldesigner/components/itemlibrary/itemlibrary.qrc2
-rw-r--r--src/plugins/qmldesigner/components/itemlibrary/itemlibraryimageprovider.cpp2
-rw-r--r--src/plugins/qmldesigner/components/itemlibrary/itemlibraryimageprovider.h4
-rw-r--r--src/plugins/qmldesigner/components/itemlibrary/itemlibrarymodel.cpp278
-rw-r--r--src/plugins/qmldesigner/components/itemlibrary/itemlibrarymodel.h91
-rw-r--r--src/plugins/qmldesigner/components/itemlibrary/itemlibraryview.cpp17
-rw-r--r--src/plugins/qmldesigner/components/itemlibrary/itemlibraryview.h5
-rw-r--r--src/plugins/qmldesigner/components/itemlibrary/itemlibrarywidget.cpp83
-rw-r--r--src/plugins/qmldesigner/components/itemlibrary/itemlibrarywidget.h15
-rw-r--r--src/plugins/qmldesigner/components/itemlibrary/qml/ItemsView.qml271
-rw-r--r--src/plugins/qmldesigner/components/itemlibrary/qml/ItemsViewStyle.qml2
-rw-r--r--src/plugins/qmldesigner/components/itemlibrary/qml/Scrollbar.qml2
-rw-r--r--src/plugins/qmldesigner/components/itemlibrary/qml/SectionView.qml44
-rw-r--r--src/plugins/qmldesigner/components/itemlibrary/qml/Selector.qml2
-rw-r--r--src/plugins/qmldesigner/components/itemlibrary/qml/SingleItemView.qml (renamed from src/plugins/qmldesigner/components/itemlibrary/qml/ItemView.qml)4
-rw-r--r--src/plugins/qmldesigner/components/navigator/navigatortreemodel.cpp19
-rw-r--r--src/plugins/qmldesigner/components/navigator/navigatortreemodel.h6
-rw-r--r--src/plugins/qmldesigner/components/navigator/navigatortreeview.cpp6
-rw-r--r--src/plugins/qmldesigner/components/navigator/navigatorview.cpp31
-rw-r--r--src/plugins/qmldesigner/components/navigator/navigatorview.h8
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/basiclayouts.h177
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/basicwidgets.cpp1460
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/basicwidgets.h120
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/behaviordialog.cpp165
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/behaviordialog.h95
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/behaviordialog.ui472
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/declarativewidgetview.cpp144
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/designerpropertymap.h10
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/gradientlineqmladaptor.cpp8
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/layoutwidget.cpp106
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/layoutwidget.h136
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/propertyeditor.cpp1124
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/propertyeditor.pri31
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/propertyeditorcontextobject.cpp1
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/propertyeditorcontextobject.h10
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/propertyeditorqmlbackend.cpp513
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/propertyeditorqmlbackend.h99
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/propertyeditortransaction.cpp2
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/propertyeditortransaction.h6
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/propertyeditorvalue.cpp16
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/propertyeditorvalue.h12
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/propertyeditorview.cpp751
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/propertyeditorview.h (renamed from src/plugins/qmldesigner/components/propertyeditor/propertyeditor.h)96
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/propertyeditorwidget.cpp (renamed from src/plugins/cpptools/cppcompletionsupport.cpp)15
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/propertyeditorwidget.h (renamed from src/plugins/glsleditor/glsleditor_global.h)31
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/qmlanchorbindingproxy.cpp234
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/qmlanchorbindingproxy.h6
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/quick2propertyeditorview.cpp112
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/quick2propertyeditorview.h (renamed from src/plugins/qmldesigner/components/propertyeditor/declarativewidgetview.h)36
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/resetwidget.cpp130
-rw-r--r--src/plugins/qmldesigner/components/stateseditor/HorizontalScrollBar.qml2
-rw-r--r--src/plugins/qmldesigner/components/stateseditor/stateseditor.pri2
-rw-r--r--src/plugins/qmldesigner/components/stateseditor/stateseditorimageprovider.cpp2
-rw-r--r--src/plugins/qmldesigner/components/stateseditor/stateseditorimageprovider.h4
-rw-r--r--src/plugins/qmldesigner/components/stateseditor/stateseditorview.cpp123
-rw-r--r--src/plugins/qmldesigner/components/stateseditor/stateseditorview.h28
-rw-r--r--src/plugins/qmldesigner/components/stateseditor/stateseditorwidget.cpp54
-rw-r--r--src/plugins/qmldesigner/components/stateseditor/stateseditorwidget.h6
-rw-r--r--src/plugins/qmldesigner/components/stateseditor/stateslist.qml7
-rw-r--r--src/plugins/qmldesigner/componentsplugin/components.metainfo16
-rw-r--r--src/plugins/qmldesigner/designercore/designercore-lib.pri2
-rw-r--r--src/plugins/qmldesigner/designercore/filemanager/changeimportsvisitor.cpp8
-rw-r--r--src/plugins/qmldesigner/designercore/filemanager/changepropertyvisitor.cpp3
-rw-r--r--src/plugins/qmldesigner/designercore/filemanager/removepropertyvisitor.cpp4
-rw-r--r--src/plugins/qmldesigner/designercore/include/abstractview.h18
-rw-r--r--src/plugins/qmldesigner/designercore/include/anchorline.h118
-rw-r--r--src/plugins/qmldesigner/designercore/include/bindingproperty.h1
-rw-r--r--src/plugins/qmldesigner/designercore/include/import.h9
-rw-r--r--src/plugins/qmldesigner/designercore/include/itemlibraryinfo.h4
-rw-r--r--src/plugins/qmldesigner/designercore/include/model.h6
-rw-r--r--src/plugins/qmldesigner/designercore/include/modelnode.h11
-rw-r--r--src/plugins/qmldesigner/designercore/include/nodeinstance.h5
-rw-r--r--src/plugins/qmldesigner/designercore/include/nodeinstanceview.h6
-rw-r--r--src/plugins/qmldesigner/designercore/include/nodelistproperty.h2
-rw-r--r--src/plugins/qmldesigner/designercore/include/nodemetainfo.h3
-rw-r--r--src/plugins/qmldesigner/designercore/include/qmlanchors.h4
-rw-r--r--src/plugins/qmldesigner/designercore/include/qmlchangeset.h2
-rw-r--r--src/plugins/qmldesigner/designercore/include/qmlitemnode.h34
-rw-r--r--src/plugins/qmldesigner/designercore/include/qmlmodelnodefacade.h13
-rw-r--r--src/plugins/qmldesigner/designercore/include/qmlmodelview.h139
-rw-r--r--src/plugins/qmldesigner/designercore/include/qmlobjectnode.h16
-rw-r--r--src/plugins/qmldesigner/designercore/include/qmlstate.h12
-rw-r--r--src/plugins/qmldesigner/designercore/include/rewriterview.h2
-rw-r--r--src/plugins/qmldesigner/designercore/include/signalhandlerproperty.h1
-rw-r--r--src/plugins/qmldesigner/designercore/include/variantproperty.h1
-rw-r--r--src/plugins/qmldesigner/designercore/include/viewmanager.h22
-rw-r--r--src/plugins/qmldesigner/designercore/instances/nodeinstance.cpp28
-rw-r--r--src/plugins/qmldesigner/designercore/instances/nodeinstanceserverproxy.cpp107
-rw-r--r--src/plugins/qmldesigner/designercore/instances/nodeinstanceserverproxy.h10
-rw-r--r--src/plugins/qmldesigner/designercore/instances/nodeinstanceview.cpp88
-rw-r--r--src/plugins/qmldesigner/designercore/metainfo/itemlibraryinfo.cpp4
-rw-r--r--src/plugins/qmldesigner/designercore/metainfo/metainfo.cpp16
-rw-r--r--src/plugins/qmldesigner/designercore/metainfo/metainforeader.cpp2
-rw-r--r--src/plugins/qmldesigner/designercore/metainfo/nodemetainfo.cpp16
-rw-r--r--src/plugins/qmldesigner/designercore/metainfo/subcomponentmanager.cpp10
-rw-r--r--src/plugins/qmldesigner/designercore/model/abstractview.cpp116
-rw-r--r--src/plugins/qmldesigner/designercore/model/anchorline.cpp129
-rw-r--r--src/plugins/qmldesigner/designercore/model/bindingproperty.cpp22
-rw-r--r--src/plugins/qmldesigner/designercore/model/import.cpp28
-rw-r--r--src/plugins/qmldesigner/designercore/model/internalnode.cpp5
-rw-r--r--src/plugins/qmldesigner/designercore/model/internalnode_p.h1
-rw-r--r--src/plugins/qmldesigner/designercore/model/model.cpp319
-rw-r--r--src/plugins/qmldesigner/designercore/model/model_p.h49
-rw-r--r--src/plugins/qmldesigner/designercore/model/modelmerger.cpp2
-rw-r--r--src/plugins/qmldesigner/designercore/model/modelnode.cpp119
-rw-r--r--src/plugins/qmldesigner/designercore/model/nodeabstractproperty.cpp2
-rw-r--r--src/plugins/qmldesigner/designercore/model/nodelistproperty.cpp10
-rw-r--r--src/plugins/qmldesigner/designercore/model/qmlanchors.cpp63
-rw-r--r--src/plugins/qmldesigner/designercore/model/qmlchangeset.cpp22
-rw-r--r--src/plugins/qmldesigner/designercore/model/qmlitemnode.cpp370
-rw-r--r--src/plugins/qmldesigner/designercore/model/qmlmodelnodefacade.cpp42
-rw-r--r--src/plugins/qmldesigner/designercore/model/qmlmodelview.cpp449
-rw-r--r--src/plugins/qmldesigner/designercore/model/qmlobjectnode.cpp124
-rw-r--r--src/plugins/qmldesigner/designercore/model/qmlstate.cpp198
-rw-r--r--src/plugins/qmldesigner/designercore/model/rewriteaction.cpp4
-rw-r--r--src/plugins/qmldesigner/designercore/model/rewriteactioncompressor.cpp12
-rw-r--r--src/plugins/qmldesigner/designercore/model/rewriterview.cpp11
-rw-r--r--src/plugins/qmldesigner/designercore/model/signalhandlerproperty.cpp7
-rw-r--r--src/plugins/qmldesigner/designercore/model/texttomodelmerger.cpp33
-rw-r--r--src/plugins/qmldesigner/designercore/model/variantproperty.cpp7
-rw-r--r--src/plugins/qmldesigner/designercore/model/viewmanager.cpp61
-rw-r--r--src/plugins/qmldesigner/designmodewidget.cpp42
-rw-r--r--src/plugins/qmldesigner/designmodewidget.h7
-rw-r--r--src/plugins/qmldesigner/documentmanager.cpp145
-rw-r--r--src/plugins/qmldesigner/documentmanager.h4
-rw-r--r--src/plugins/qmldesigner/qmldesigner_dependencies.pri1
-rw-r--r--src/plugins/qmldesigner/qmldesignerconstants.h2
-rw-r--r--src/plugins/qmldesigner/qmldesignerplugin.cpp24
-rw-r--r--src/plugins/qmldesigner/qmldesignerplugin.h4
-rw-r--r--src/plugins/qmldesigner/qmldesignerplugin.pro1
-rw-r--r--src/plugins/qmldesigner/shortcutmanager.cpp46
-rw-r--r--src/plugins/qmldesigner/styledoutputpaneplaceholder.cpp10
-rw-r--r--src/plugins/qmldesigner/styledoutputpaneplaceholder.h8
-rw-r--r--src/plugins/qmljseditor/QmlJSEditor.pluginspec.in2
-rw-r--r--src/plugins/qmljseditor/jsfilewizard.cpp9
-rw-r--r--src/plugins/qmljseditor/jsfilewizard.h14
-rw-r--r--src/plugins/qmljseditor/qmlfilewizard.cpp6
-rw-r--r--src/plugins/qmljseditor/qmlfilewizard.h8
-rw-r--r--src/plugins/qmljseditor/qmljscompletionassist.cpp10
-rw-r--r--src/plugins/qmljseditor/qmljscompletionassist.h4
-rw-r--r--src/plugins/qmljseditor/qmljscomponentfromobjectdef.cpp2
-rw-r--r--src/plugins/qmljseditor/qmljseditor.cpp38
-rw-r--r--src/plugins/qmljseditor/qmljseditor.pro2
-rw-r--r--src/plugins/qmljseditor/qmljseditor.qbs2
-rw-r--r--src/plugins/qmljseditor/qmljseditoreditable.cpp13
-rw-r--r--src/plugins/qmljseditor/qmljseditoreditable.h4
-rw-r--r--src/plugins/qmljseditor/qmljseditorfactory.cpp42
-rw-r--r--src/plugins/qmljseditor/qmljseditorfactory.h9
-rw-r--r--src/plugins/qmljseditor/qmljseditorplugin.cpp77
-rw-r--r--src/plugins/qmljseditor/qmljsfindreferences.cpp16
-rw-r--r--src/plugins/qmljseditor/qmljsfindreferences.h4
-rw-r--r--src/plugins/qmljseditor/qmljshighlighter.cpp39
-rw-r--r--src/plugins/qmljseditor/qmljshighlighter.h8
-rw-r--r--src/plugins/qmljseditor/qmljshighlighterfactory.cpp51
-rw-r--r--src/plugins/qmljseditor/qmljshighlighterfactory.h51
-rw-r--r--src/plugins/qmljseditor/qmljshoverhandler.cpp31
-rw-r--r--src/plugins/qmljseditor/qmljsoutline.cpp5
-rw-r--r--src/plugins/qmljseditor/qmljsquickfix.cpp2
-rw-r--r--src/plugins/qmljseditor/qmljsquickfixassist.cpp2
-rw-r--r--src/plugins/qmljseditor/qmljssnippetprovider.cpp6
-rw-r--r--src/plugins/qmljseditor/qmltaskmanager.cpp11
-rw-r--r--src/plugins/qmljseditor/qmltaskmanager.h1
-rw-r--r--src/plugins/qmljseditor/quicktoolbar.cpp7
-rw-r--r--src/plugins/qmljstools/QmlJSTools.pluginspec.in2
-rw-r--r--src/plugins/qmljstools/qmlconsoleitemmodel.h2
-rw-r--r--src/plugins/qmljstools/qmlconsoleview.cpp4
-rw-r--r--src/plugins/qmljstools/qmljscodestylesettingspage.cpp10
-rw-r--r--src/plugins/qmljstools/qmljsfindexportedcpptypes.cpp3
-rw-r--r--src/plugins/qmljstools/qmljsfunctionfilter.cpp3
-rw-r--r--src/plugins/qmljstools/qmljsmodelmanager.cpp95
-rw-r--r--src/plugins/qmljstools/qmljsplugindumper.cpp13
-rw-r--r--src/plugins/qmljstools/qmljssemanticinfo.cpp4
-rw-r--r--src/plugins/qmljstools/qmljstools.qbs5
-rw-r--r--src/plugins/qmljstools/qmljstoolsplugin.cpp35
-rw-r--r--src/plugins/qmljstools/qmljstoolsplugin.h5
-rw-r--r--src/plugins/qmljstools/qmljstoolssettings.cpp48
-rw-r--r--src/plugins/qmlprofiler/QmlProfiler.pluginspec.in2
-rw-r--r--src/plugins/qmlprofiler/abstracttimelinemodel.cpp82
-rw-r--r--src/plugins/qmlprofiler/abstracttimelinemodel.h113
-rw-r--r--src/plugins/qmlprofiler/canvas/canvas.pri2
-rw-r--r--src/plugins/qmlprofiler/canvas/qdeclarativecanvas.cpp24
-rw-r--r--src/plugins/qmlprofiler/canvas/qdeclarativecanvas_p.h17
-rw-r--r--src/plugins/qmlprofiler/canvas/qdeclarativecanvastimer.cpp14
-rw-r--r--src/plugins/qmlprofiler/canvas/qdeclarativecanvastimer_p.h14
-rw-r--r--src/plugins/qmlprofiler/canvas/qdeclarativecontext2d.cpp45
-rw-r--r--src/plugins/qmlprofiler/canvas/qdeclarativecontext2d_p.h14
-rw-r--r--src/plugins/qmlprofiler/canvas/qmlprofilercanvas.cpp6
-rw-r--r--src/plugins/qmlprofiler/canvas/qmlprofilercanvas.h6
-rw-r--r--src/plugins/qmlprofiler/localqmlprofilerrunner.cpp24
-rw-r--r--src/plugins/qmlprofiler/localqmlprofilerrunner.h10
-rw-r--r--src/plugins/qmlprofiler/qml/Detail.qml4
-rw-r--r--src/plugins/qmlprofiler/qml/Label.qml66
-rw-r--r--src/plugins/qmlprofiler/qml/MainView.qml169
-rw-r--r--src/plugins/qmlprofiler/qml/Overview.js111
-rw-r--r--src/plugins/qmlprofiler/qml/Overview.qml39
-rw-r--r--src/plugins/qmlprofiler/qml/RangeDetails.qml78
-rw-r--r--src/plugins/qmlprofiler/qml/RangeMover.qml2
-rw-r--r--src/plugins/qmlprofiler/qml/SelectionRange.qml18
-rw-r--r--src/plugins/qmlprofiler/qml/SelectionRangeDetails.qml2
-rw-r--r--src/plugins/qmlprofiler/qml/TimeDisplay.qml8
-rw-r--r--src/plugins/qmlprofiler/qml/TimeMarks.qml43
-rw-r--r--src/plugins/qmlprofiler/qmlprofiler.pro30
-rw-r--r--src/plugins/qmlprofiler/qmlprofiler.qbs126
-rw-r--r--src/plugins/qmlprofiler/qmlprofiler_dependencies.pri1
-rw-r--r--src/plugins/qmlprofiler/qmlprofilerclientmanager.cpp63
-rw-r--r--src/plugins/qmlprofiler/qmlprofilerclientmanager.h16
-rw-r--r--src/plugins/qmlprofiler/qmlprofilerdatamodel.cpp1689
-rw-r--r--src/plugins/qmlprofiler/qmlprofilerdatamodel.h201
-rw-r--r--src/plugins/qmlprofiler/qmlprofilerdetailsrewriter.cpp17
-rw-r--r--src/plugins/qmlprofiler/qmlprofilerdetailsrewriter.h10
-rw-r--r--src/plugins/qmlprofiler/qmlprofilerengine.cpp74
-rw-r--r--src/plugins/qmlprofiler/qmlprofilerengine.h16
-rw-r--r--src/plugins/qmlprofiler/qmlprofilereventsmodelproxy.cpp479
-rw-r--r--src/plugins/qmlprofiler/qmlprofilereventsmodelproxy.h172
-rw-r--r--src/plugins/qmlprofiler/qmlprofilereventview.cpp668
-rw-r--r--src/plugins/qmlprofiler/qmlprofilereventview.h98
-rw-r--r--src/plugins/qmlprofiler/qmlprofilermodelmanager.cpp364
-rw-r--r--src/plugins/qmlprofiler/qmlprofilermodelmanager.h161
-rw-r--r--src/plugins/qmlprofiler/qmlprofilerpainteventsmodelproxy.cpp458
-rw-r--r--src/plugins/qmlprofiler/qmlprofilerpainteventsmodelproxy.h123
-rw-r--r--src/plugins/qmlprofiler/qmlprofilerplugin.cpp56
-rw-r--r--src/plugins/qmlprofiler/qmlprofilerplugin.h10
-rw-r--r--src/plugins/qmlprofiler/qmlprofilerprocessedmodel.cpp182
-rw-r--r--src/plugins/qmlprofiler/qmlprofilerprocessedmodel.h (renamed from src/plugins/analyzerbase/analyzeroptionspage.h)36
-rw-r--r--src/plugins/qmlprofiler/qmlprofilerruncontrolfactory.cpp80
-rw-r--r--src/plugins/qmlprofiler/qmlprofilersimplemodel.cpp117
-rw-r--r--src/plugins/qmlprofiler/qmlprofilersimplemodel.h (renamed from src/plugins/coreplugin/scriptmanager/scriptmanager.h)77
-rw-r--r--src/plugins/qmlprofiler/qmlprofilerstatewidget.cpp43
-rw-r--r--src/plugins/qmlprofiler/qmlprofilerstatewidget.h7
-rw-r--r--src/plugins/qmlprofiler/qmlprofilertimelinemodelproxy.cpp721
-rw-r--r--src/plugins/qmlprofiler/qmlprofilertimelinemodelproxy.h146
-rw-r--r--src/plugins/qmlprofiler/qmlprofilertool.cpp196
-rw-r--r--src/plugins/qmlprofiler/qmlprofilertool.h16
-rw-r--r--src/plugins/qmlprofiler/qmlprofilertracefile.cpp561
-rw-r--r--src/plugins/qmlprofiler/qmlprofilertracefile.h134
-rw-r--r--src/plugins/qmlprofiler/qmlprofilertraceview.cpp167
-rw-r--r--src/plugins/qmlprofiler/qmlprofilertraceview.h18
-rw-r--r--src/plugins/qmlprofiler/qmlprofilertreeview.cpp92
-rw-r--r--src/plugins/qmlprofiler/qmlprofilertreeview.h (renamed from src/plugins/coreplugin/scriptmanager/scriptmanager_p.h)51
-rw-r--r--src/plugins/qmlprofiler/qmlprofilerviewmanager.cpp50
-rw-r--r--src/plugins/qmlprofiler/qmlprofilerviewmanager.h5
-rw-r--r--src/plugins/qmlprofiler/qv8profilerdatamodel.cpp64
-rw-r--r--src/plugins/qmlprofiler/qv8profilerdatamodel.h10
-rw-r--r--src/plugins/qmlprofiler/qv8profilereventview.cpp725
-rw-r--r--src/plugins/qmlprofiler/qv8profilereventview.h163
-rw-r--r--src/plugins/qmlprofiler/timelinemodelaggregator.cpp373
-rw-r--r--src/plugins/qmlprofiler/timelinemodelaggregator.h122
-rw-r--r--src/plugins/qmlprofiler/timelinerenderer.cpp467
-rw-r--r--src/plugins/qmlprofiler/timelinerenderer.h88
-rw-r--r--src/plugins/qmlprojectmanager/QmlProjectManager.pluginspec.in2
-rw-r--r--src/plugins/qmlprojectmanager/fileformat/filefilteritems.h8
-rw-r--r--src/plugins/qmlprojectmanager/fileformat/qmlprojectfileformat.cpp109
-rw-r--r--src/plugins/qmlprojectmanager/fileformat/qmlprojectfileformat.h12
-rw-r--r--src/plugins/qmlprojectmanager/fileformat/qmlprojectitem.cpp12
-rw-r--r--src/plugins/qmlprojectmanager/fileformat/qmlprojectitem.h11
-rw-r--r--src/plugins/qmlprojectmanager/qmlapp.cpp2
-rw-r--r--src/plugins/qmlprojectmanager/qmlapplicationwizard.cpp68
-rw-r--r--src/plugins/qmlprojectmanager/qmlapplicationwizard.h14
-rw-r--r--src/plugins/qmlprojectmanager/qmlproject.cpp68
-rw-r--r--src/plugins/qmlprojectmanager/qmlproject.h3
-rw-r--r--src/plugins/qmlprojectmanager/qmlprojectconstants.h4
-rw-r--r--src/plugins/qmlprojectmanager/qmlprojectenvironmentaspect.cpp9
-rw-r--r--src/plugins/qmlprojectmanager/qmlprojectenvironmentaspect.h4
-rw-r--r--src/plugins/qmlprojectmanager/qmlprojectfile.cpp16
-rw-r--r--src/plugins/qmlprojectmanager/qmlprojectfile.h3
-rw-r--r--src/plugins/qmlprojectmanager/qmlprojectmanager.pro2
-rw-r--r--src/plugins/qmlprojectmanager/qmlprojectmanager.qbs68
-rw-r--r--src/plugins/qmlprojectmanager/qmlprojectnodes.cpp18
-rw-r--r--src/plugins/qmlprojectmanager/qmlprojectnodes.h18
-rw-r--r--src/plugins/qmlprojectmanager/qmlprojectplugin.cpp15
-rw-r--r--src/plugins/qmlprojectmanager/qmlprojectrunconfiguration.cpp34
-rw-r--r--src/plugins/qmlprojectmanager/qmlprojectruncontrol.cpp15
-rw-r--r--src/plugins/qmlprojectmanager/qmlprojectruncontrol.h2
-rw-r--r--src/plugins/qnx/Qnx.pluginspec.in2
-rw-r--r--src/plugins/qnx/bardescriptordocument.cpp32
-rw-r--r--src/plugins/qnx/bardescriptordocument.h4
-rw-r--r--src/plugins/qnx/bardescriptoreditor.cpp50
-rw-r--r--src/plugins/qnx/bardescriptoreditor.h13
-rw-r--r--src/plugins/qnx/bardescriptoreditorfactory.cpp19
-rw-r--r--src/plugins/qnx/bardescriptoreditorfactory.h10
-rw-r--r--src/plugins/qnx/bardescriptoreditorwidget.cpp14
-rw-r--r--src/plugins/qnx/bardescriptoreditorwidget.h1
-rw-r--r--src/plugins/qnx/blackberryabstractdeploystep.cpp7
-rw-r--r--src/plugins/qnx/blackberryapplicationrunner.cpp184
-rw-r--r--src/plugins/qnx/blackberryapplicationrunner.h24
-rw-r--r--src/plugins/qnx/blackberrycertificate.cpp28
-rw-r--r--src/plugins/qnx/blackberrycertificate.h5
-rw-r--r--src/plugins/qnx/blackberrycertificatemodel.cpp205
-rw-r--r--src/plugins/qnx/blackberryconfiguration.cpp505
-rw-r--r--src/plugins/qnx/blackberryconfiguration.h95
-rw-r--r--src/plugins/qnx/blackberryconfigurationmanager.cpp372
-rw-r--r--src/plugins/qnx/blackberryconfigurationmanager.h92
-rw-r--r--src/plugins/qnx/blackberrycreatecertificatedialog.cpp72
-rw-r--r--src/plugins/qnx/blackberrycreatecertificatedialog.h5
-rw-r--r--src/plugins/qnx/blackberrycreatecertificatedialog.ui35
-rw-r--r--src/plugins/qnx/blackberrycreatepackagestep.cpp2
-rw-r--r--src/plugins/qnx/blackberrycsjregistrar.cpp116
-rw-r--r--src/plugins/qnx/blackberrydebugtokenrequestdialog.cpp66
-rw-r--r--src/plugins/qnx/blackberrydebugtokenrequestdialog.h9
-rw-r--r--src/plugins/qnx/blackberrydebugtokenrequestdialog.ui80
-rw-r--r--src/plugins/qnx/blackberrydebugtokenrequester.cpp6
-rw-r--r--src/plugins/qnx/blackberrydebugtokenuploader.cpp2
-rw-r--r--src/plugins/qnx/blackberrydebugtokenuploader.h3
-rw-r--r--src/plugins/qnx/blackberrydeployconfiguration.cpp4
-rw-r--r--src/plugins/qnx/blackberrydeployinformation.cpp8
-rw-r--r--src/plugins/qnx/blackberrydeviceconfiguration.cpp29
-rw-r--r--src/plugins/qnx/blackberrydeviceconfiguration.h7
-rw-r--r--src/plugins/qnx/blackberrydeviceconfigurationwidget.cpp17
-rw-r--r--src/plugins/qnx/blackberrydeviceconfigurationwidget.ui73
-rw-r--r--src/plugins/qnx/blackberrydeviceconfigurationwizard.cpp22
-rw-r--r--src/plugins/qnx/blackberrydeviceconfigurationwizard.h14
-rw-r--r--src/plugins/qnx/blackberrydeviceconfigurationwizardconfigpage.ui159
-rw-r--r--src/plugins/qnx/blackberrydeviceconfigurationwizardpages.cpp409
-rw-r--r--src/plugins/qnx/blackberrydeviceconfigurationwizardpages.h95
-rw-r--r--src/plugins/qnx/blackberrydeviceconfigurationwizardquerypage.ui47
-rw-r--r--src/plugins/qnx/blackberrydeviceconfigurationwizardsetuppage.ui150
-rw-r--r--src/plugins/qnx/blackberrydeviceconfigurationwizardsshkeypage.ui78
-rw-r--r--src/plugins/qnx/blackberrydeviceconnection.cpp7
-rw-r--r--src/plugins/qnx/blackberrydeviceconnectionmanager.cpp88
-rw-r--r--src/plugins/qnx/blackberrydeviceconnectionmanager.h10
-rw-r--r--src/plugins/qnx/blackberrydeviceinformation.cpp77
-rw-r--r--src/plugins/qnx/blackberrydeviceinformation.h13
-rw-r--r--src/plugins/qnx/blackberrydevicelistdetector.cpp95
-rw-r--r--src/plugins/qnx/blackberrydevicelistdetector.h (renamed from src/plugins/qnx/blackberrycsjregistrar.h)34
-rw-r--r--src/plugins/qnx/blackberrydeviceprocesssupport.cpp45
-rw-r--r--src/plugins/qnx/blackberrykeyspage.cpp5
-rw-r--r--src/plugins/qnx/blackberrykeyswidget.cpp210
-rw-r--r--src/plugins/qnx/blackberrykeyswidget.h38
-rw-r--r--src/plugins/qnx/blackberrykeyswidget.ui223
-rw-r--r--src/plugins/qnx/blackberrylogprocessrunner.cpp256
-rw-r--r--src/plugins/qnx/blackberrylogprocessrunner.h (renamed from src/plugins/qnx/blackberrycertificatemodel.h)90
-rw-r--r--src/plugins/qnx/blackberryndkprocess.cpp29
-rw-r--r--src/plugins/qnx/blackberryndkprocess.h8
-rw-r--r--src/plugins/qnx/blackberryndksettingspage.cpp10
-rw-r--r--src/plugins/qnx/blackberryndksettingswidget.cpp250
-rw-r--r--src/plugins/qnx/blackberryndksettingswidget.h41
-rw-r--r--src/plugins/qnx/blackberryndksettingswidget.ui243
-rw-r--r--src/plugins/qnx/blackberryqtversion.cpp34
-rw-r--r--src/plugins/qnx/blackberryqtversion.h5
-rw-r--r--src/plugins/qnx/blackberryregisterkeydialog.cpp324
-rw-r--r--src/plugins/qnx/blackberryregisterkeydialog.ui360
-rw-r--r--src/plugins/qnx/blackberryruncontrol.cpp35
-rw-r--r--src/plugins/qnx/blackberryruncontrol.h6
-rw-r--r--src/plugins/qnx/blackberryruncontrolfactory.cpp10
-rw-r--r--src/plugins/qnx/blackberrysetupwizard.cpp89
-rw-r--r--src/plugins/qnx/blackberrysetupwizard.h19
-rw-r--r--src/plugins/qnx/blackberrysetupwizardcertificatepage.ui108
-rw-r--r--src/plugins/qnx/blackberrysetupwizardkeyspage.ui233
-rw-r--r--src/plugins/qnx/blackberrysetupwizardpages.cpp183
-rw-r--r--src/plugins/qnx/blackberrysetupwizardpages.h42
-rw-r--r--src/plugins/qnx/blackberrysigningutils.cpp180
-rw-r--r--src/plugins/qnx/blackberrysigningutils.h (renamed from src/plugins/qnx/blackberryregisterkeydialog.h)74
-rw-r--r--src/plugins/qnx/blackberrysshkeysgenerator.cpp30
-rw-r--r--src/plugins/qnx/blackberrysshkeysgenerator.h7
-rw-r--r--src/plugins/qnx/qnx.pro33
-rw-r--r--src/plugins/qnx/qnx.qbs30
-rw-r--r--src/plugins/qnx/qnxabstractrunsupport.cpp10
-rw-r--r--src/plugins/qnx/qnxabstractrunsupport.h7
-rw-r--r--src/plugins/qnx/qnxanalyzesupport.cpp33
-rw-r--r--src/plugins/qnx/qnxanalyzesupport.h6
-rw-r--r--src/plugins/qnx/qnxdebugsupport.cpp14
-rw-r--r--src/plugins/qnx/qnxdeviceconfiguration.cpp75
-rw-r--r--src/plugins/qnx/qnxdeviceconfiguration.h8
-rw-r--r--src/plugins/qnx/qnxdeviceconfigurationwizard.cpp6
-rw-r--r--src/plugins/qnx/qnxdeviceprocesslist.cpp80
-rw-r--r--src/plugins/qnx/qnxdeviceprocesslist.h57
-rw-r--r--src/plugins/qnx/qnxdeviceprocesssignaloperation.cpp90
-rw-r--r--src/plugins/qnx/qnxdeviceprocesssignaloperation.h (renamed from src/plugins/qnx/blackberryutils.cpp)65
-rw-r--r--src/plugins/qnx/qnxdevicetester.cpp8
-rw-r--r--src/plugins/qnx/qnxdevicetester.h6
-rw-r--r--src/plugins/qnx/qnxplugin.cpp11
-rw-r--r--src/plugins/qnx/qnxrunconfiguration.cpp23
-rw-r--r--src/plugins/qnx/qnxrunconfiguration.h4
-rw-r--r--src/plugins/qnx/qnxruncontrolfactory.cpp26
-rw-r--r--src/plugins/qnx/qnxutils.cpp41
-rw-r--r--src/plugins/qnx/qnxutils.h15
-rw-r--r--src/plugins/qt4projectmanager/Qt4ProjectManager.pluginspec.in2
-rw-r--r--src/plugins/qt4projectmanager/addlibrarywizard.cpp2
-rw-r--r--src/plugins/qt4projectmanager/buildconfigurationinfo.h74
-rw-r--r--src/plugins/qt4projectmanager/customwidgetwizard/customwidgetwidgetswizardpage.ui2
-rw-r--r--src/plugins/qt4projectmanager/customwidgetwizard/customwidgetwizard.cpp23
-rw-r--r--src/plugins/qt4projectmanager/customwidgetwizard/customwidgetwizard.h7
-rw-r--r--src/plugins/qt4projectmanager/customwidgetwizard/customwidgetwizard.pri1
-rw-r--r--src/plugins/qt4projectmanager/externaleditors.cpp3
-rw-r--r--src/plugins/qt4projectmanager/librarydetailscontroller.cpp20
-rw-r--r--src/plugins/qt4projectmanager/librarydetailswidget.ui2
-rw-r--r--src/plugins/qt4projectmanager/makestep.cpp15
-rw-r--r--src/plugins/qt4projectmanager/makestep.h1
-rw-r--r--src/plugins/qt4projectmanager/profileeditor.cpp35
-rw-r--r--src/plugins/qt4projectmanager/profileeditor.h5
-rw-r--r--src/plugins/qt4projectmanager/profileeditorfactory.cpp38
-rw-r--r--src/plugins/qt4projectmanager/profileeditorfactory.h12
-rw-r--r--src/plugins/qt4projectmanager/profilehighlighter.cpp25
-rw-r--r--src/plugins/qt4projectmanager/profilehighlighter.h7
-rw-r--r--src/plugins/qt4projectmanager/profilehighlighterfactory.cpp47
-rw-r--r--src/plugins/qt4projectmanager/profilehighlighterfactory.h51
-rw-r--r--src/plugins/qt4projectmanager/profilehoverhandler.cpp4
-rw-r--r--src/plugins/qt4projectmanager/qmakebuildinfo.h63
-rw-r--r--src/plugins/qt4projectmanager/qmakekitconfigwidget.cpp10
-rw-r--r--src/plugins/qt4projectmanager/qmakekitconfigwidget.h3
-rw-r--r--src/plugins/qt4projectmanager/qmakekitinformation.cpp89
-rw-r--r--src/plugins/qt4projectmanager/qmakekitinformation.h6
-rw-r--r--src/plugins/qt4projectmanager/qmakeprojectimporter.cpp254
-rw-r--r--src/plugins/qt4projectmanager/qmakeprojectimporter.h64
-rw-r--r--src/plugins/qt4projectmanager/qmakerunconfigurationfactory.cpp2
-rw-r--r--src/plugins/qt4projectmanager/qmakestep.cpp13
-rw-r--r--src/plugins/qt4projectmanager/qt-desktop/qt4runconfiguration.h2
-rw-r--r--src/plugins/qt4projectmanager/qt4buildconfiguration.cpp326
-rw-r--r--src/plugins/qt4projectmanager/qt4buildconfiguration.h43
-rw-r--r--src/plugins/qt4projectmanager/qt4nodes.cpp360
-rw-r--r--src/plugins/qt4projectmanager/qt4nodes.h39
-rw-r--r--src/plugins/qt4projectmanager/qt4project.cpp151
-rw-r--r--src/plugins/qt4projectmanager/qt4project.h20
-rw-r--r--src/plugins/qt4projectmanager/qt4projectconfigwidget.cpp77
-rw-r--r--src/plugins/qt4projectmanager/qt4projectconfigwidget.h1
-rw-r--r--src/plugins/qt4projectmanager/qt4projectconfigwidget.ui55
-rw-r--r--src/plugins/qt4projectmanager/qt4projectmanager.cpp123
-rw-r--r--src/plugins/qt4projectmanager/qt4projectmanager.h18
-rw-r--r--src/plugins/qt4projectmanager/qt4projectmanager.pro20
-rw-r--r--src/plugins/qt4projectmanager/qt4projectmanager.qbs315
-rw-r--r--src/plugins/qt4projectmanager/qt4projectmanagerconstants.h6
-rw-r--r--src/plugins/qt4projectmanager/qt4projectmanagerplugin.cpp36
-rw-r--r--src/plugins/qt4projectmanager/qtuicodemodelsupport.cpp74
-rw-r--r--src/plugins/qt4projectmanager/wizards/abstractmobileappwizard.cpp23
-rw-r--r--src/plugins/qt4projectmanager/wizards/abstractmobileappwizard.h10
-rw-r--r--src/plugins/qt4projectmanager/wizards/consoleappwizard.cpp23
-rw-r--r--src/plugins/qt4projectmanager/wizards/consoleappwizard.h6
-rw-r--r--src/plugins/qt4projectmanager/wizards/emptyprojectwizard.cpp23
-rw-r--r--src/plugins/qt4projectmanager/wizards/emptyprojectwizard.h8
-rw-r--r--src/plugins/qt4projectmanager/wizards/guiappwizard.cpp42
-rw-r--r--src/plugins/qt4projectmanager/wizards/guiappwizard.h17
-rw-r--r--src/plugins/qt4projectmanager/wizards/html5appwizard.cpp41
-rw-r--r--src/plugins/qt4projectmanager/wizards/html5appwizard.h5
-rw-r--r--src/plugins/qt4projectmanager/wizards/librarywizard.cpp26
-rw-r--r--src/plugins/qt4projectmanager/wizards/librarywizard.h9
-rw-r--r--src/plugins/qt4projectmanager/wizards/librarywizarddialog.cpp3
-rw-r--r--src/plugins/qt4projectmanager/wizards/modulespage.cpp2
-rw-r--r--src/plugins/qt4projectmanager/wizards/qtquickappwizard.cpp106
-rw-r--r--src/plugins/qt4projectmanager/wizards/qtquickappwizard.h8
-rw-r--r--src/plugins/qt4projectmanager/wizards/qtwizard.cpp61
-rw-r--r--src/plugins/qt4projectmanager/wizards/qtwizard.h29
-rw-r--r--src/plugins/qt4projectmanager/wizards/subdirsprojectwizard.cpp23
-rw-r--r--src/plugins/qt4projectmanager/wizards/subdirsprojectwizard.h10
-rw-r--r--src/plugins/qt4projectmanager/wizards/targetsetuppage.cpp723
-rw-r--r--src/plugins/qt4projectmanager/wizards/testwizard.cpp30
-rw-r--r--src/plugins/qt4projectmanager/wizards/testwizard.h6
-rw-r--r--src/plugins/qtsupport/QtSupport.pluginspec.in2
-rw-r--r--src/plugins/qtsupport/baseqtversion.cpp210
-rw-r--r--src/plugins/qtsupport/baseqtversion.h4
-rw-r--r--src/plugins/qtsupport/debugginghelper.cpp2
-rw-r--r--src/plugins/qtsupport/debugginghelperbuildtask.cpp5
-rw-r--r--src/plugins/qtsupport/exampleslistmodel.cpp13
-rw-r--r--src/plugins/qtsupport/gettingstartedwelcomepage.cpp48
-rw-r--r--src/plugins/qtsupport/gettingstartedwelcomepage.h10
-rw-r--r--src/plugins/qtsupport/profilereader.cpp2
-rw-r--r--src/plugins/qtsupport/profilereader.h2
-rw-r--r--src/plugins/qtsupport/qmldumptool.cpp16
-rw-r--r--src/plugins/qtsupport/qtkitconfigwidget.cpp42
-rw-r--r--src/plugins/qtsupport/qtkitconfigwidget.h3
-rw-r--r--src/plugins/qtsupport/qtkitinformation.cpp53
-rw-r--r--src/plugins/qtsupport/qtkitinformation.h5
-rw-r--r--src/plugins/qtsupport/qtoptionspage.cpp81
-rw-r--r--src/plugins/qtsupport/qtparser.cpp10
-rw-r--r--src/plugins/qtsupport/qtsupport.pro12
-rw-r--r--src/plugins/qtsupport/qtsupport.qbs21
-rw-r--r--src/plugins/qtsupport/qtsupport_dependencies.pri1
-rw-r--r--src/plugins/qtsupport/qtsupportconstants.h4
-rw-r--r--src/plugins/qtsupport/qtsupportplugin.cpp39
-rw-r--r--src/plugins/qtsupport/qtversioninfo.ui22
-rw-r--r--src/plugins/qtsupport/qtversionmanager.cpp155
-rw-r--r--src/plugins/qtsupport/qtversionmanager.h54
-rw-r--r--src/plugins/qtsupport/uicodemodelsupport.cpp451
-rw-r--r--src/plugins/qtsupport/uicodemodelsupport.h (renamed from src/plugins/cpptools/uicodecompletionsupport.h)86
-rw-r--r--src/plugins/remotelinux/RemoteLinux.pluginspec.in2
-rw-r--r--src/plugins/remotelinux/abstractpackagingstep.cpp4
-rw-r--r--src/plugins/remotelinux/abstractremotelinuxdeployservice.cpp4
-rw-r--r--src/plugins/remotelinux/abstractremotelinuxdeploystep.cpp4
-rw-r--r--src/plugins/remotelinux/abstractremotelinuxrunsupport.cpp32
-rw-r--r--src/plugins/remotelinux/abstractremotelinuxrunsupport.h7
-rw-r--r--src/plugins/remotelinux/genericdirectuploadstep.cpp2
-rw-r--r--src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.cpp14
-rw-r--r--src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.h1
-rw-r--r--src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.ui40
-rw-r--r--src/plugins/remotelinux/genericlinuxdeviceconfigurationwizard.cpp8
-rw-r--r--src/plugins/remotelinux/genericlinuxdeviceconfigurationwizardpages.cpp10
-rw-r--r--src/plugins/remotelinux/linuxdevice.cpp52
-rw-r--r--src/plugins/remotelinux/linuxdevice.h17
-rw-r--r--src/plugins/remotelinux/linuxdeviceprocess.cpp84
-rw-r--r--src/plugins/remotelinux/linuxdeviceprocess.h64
-rw-r--r--src/plugins/remotelinux/linuxdevicetester.cpp7
-rw-r--r--src/plugins/remotelinux/linuxdevicetester.h24
-rw-r--r--src/plugins/remotelinux/remotelinux.pro11
-rw-r--r--src/plugins/remotelinux/remotelinux.qbs7
-rw-r--r--src/plugins/remotelinux/remotelinux_constants.h1
-rw-r--r--src/plugins/remotelinux/remotelinuxanalyzesupport.cpp41
-rw-r--r--src/plugins/remotelinux/remotelinuxanalyzesupport.h4
-rw-r--r--src/plugins/remotelinux/remotelinuxcheckforfreediskspacestep.cpp2
-rw-r--r--src/plugins/remotelinux/remotelinuxcustomcommanddeploymentstep.cpp2
-rw-r--r--src/plugins/remotelinux/remotelinuxdebugsupport.cpp28
-rw-r--r--src/plugins/remotelinux/remotelinuxdeployconfigurationfactory.cpp2
-rw-r--r--src/plugins/remotelinux/remotelinuxenvironmentaspect.cpp9
-rw-r--r--src/plugins/remotelinux/remotelinuxenvironmentaspect.h4
-rw-r--r--src/plugins/remotelinux/remotelinuxenvironmentaspectwidget.cpp2
-rw-r--r--src/plugins/remotelinux/remotelinuxenvironmentreader.cpp75
-rw-r--r--src/plugins/remotelinux/remotelinuxenvironmentreader.h15
-rw-r--r--src/plugins/remotelinux/remotelinuxrunconfiguration.cpp37
-rw-r--r--src/plugins/remotelinux/remotelinuxrunconfiguration.h12
-rw-r--r--src/plugins/remotelinux/remotelinuxrunconfigurationwidget.cpp2
-rw-r--r--src/plugins/remotelinux/remotelinuxruncontrol.cpp19
-rw-r--r--src/plugins/remotelinux/remotelinuxruncontrolfactory.cpp11
-rw-r--r--src/plugins/remotelinux/remotelinuxsignaloperation.cpp133
-rw-r--r--src/plugins/remotelinux/remotelinuxsignaloperation.h78
-rw-r--r--src/plugins/remotelinux/tarpackagecreationstep.cpp4
-rw-r--r--src/plugins/remotelinux/uploadandinstalltarpackagestep.cpp2
-rw-r--r--src/plugins/resourceeditor/ResourceEditor.pluginspec.in2
-rw-r--r--src/plugins/resourceeditor/qrceditor/qrceditor.cpp2
-rw-r--r--src/plugins/resourceeditor/qrceditor/resourcefile.cpp5
-rw-r--r--src/plugins/resourceeditor/qrceditor/test/main.cpp3
-rw-r--r--src/plugins/resourceeditor/qrceditor/test/mainwindow.cpp2
-rw-r--r--src/plugins/resourceeditor/resourceeditor.pro2
-rw-r--r--src/plugins/resourceeditor/resourceeditor.qbs43
-rw-r--r--src/plugins/resourceeditor/resourceeditorfactory.cpp22
-rw-r--r--src/plugins/resourceeditor/resourceeditorfactory.h6
-rw-r--r--src/plugins/resourceeditor/resourceeditorplugin.cpp15
-rw-r--r--src/plugins/resourceeditor/resourceeditorw.cpp90
-rw-r--r--src/plugins/resourceeditor/resourceeditorw.h17
-rw-r--r--src/plugins/resourceeditor/resourcewizard.cpp4
-rw-r--r--src/plugins/resourceeditor/resourcewizard.h3
-rw-r--r--src/plugins/subversion/Subversion.pluginspec.in2
-rw-r--r--src/plugins/subversion/annotationhighlighter.cpp3
-rw-r--r--src/plugins/subversion/annotationhighlighter.h2
-rw-r--r--src/plugins/subversion/checkoutwizard.cpp36
-rw-r--r--src/plugins/subversion/checkoutwizard.h14
-rw-r--r--src/plugins/subversion/subversioneditor.cpp5
-rw-r--r--src/plugins/subversion/subversioneditor.h2
-rw-r--r--src/plugins/subversion/subversionplugin.cpp54
-rw-r--r--src/plugins/subversion/subversionplugin.h6
-rw-r--r--src/plugins/subversion/subversionsubmiteditor.cpp3
-rw-r--r--src/plugins/tasklist/TaskList.pluginspec.in2
-rw-r--r--src/plugins/tasklist/stopmonitoringhandler.cpp2
-rw-r--r--src/plugins/tasklist/taskfile.cpp28
-rw-r--r--src/plugins/tasklist/taskfile.h9
-rw-r--r--src/plugins/tasklist/taskfilefactory.cpp33
-rw-r--r--src/plugins/tasklist/taskfilefactory.h16
-rw-r--r--src/plugins/tasklist/tasklist.pro1
-rw-r--r--src/plugins/tasklist/tasklist.qbs1
-rw-r--r--src/plugins/tasklist/tasklist_export.h41
-rw-r--r--src/plugins/tasklist/tasklistplugin.cpp263
-rw-r--r--src/plugins/tasklist/tasklistplugin.h27
-rw-r--r--src/plugins/texteditor/TextEditor.pluginspec.in2
-rw-r--r--src/plugins/texteditor/autocompleter.cpp3
-rw-r--r--src/plugins/texteditor/basefilefind.cpp24
-rw-r--r--src/plugins/texteditor/basefilefind.h8
-rw-r--r--src/plugins/texteditor/basehoverhandler.cpp8
-rw-r--r--src/plugins/texteditor/basetextdocument.cpp62
-rw-r--r--src/plugins/texteditor/basetextdocument.h22
-rw-r--r--src/plugins/texteditor/basetextdocumentlayout.cpp6
-rw-r--r--src/plugins/texteditor/basetexteditor.cpp265
-rw-r--r--src/plugins/texteditor/basetexteditor.h32
-rw-r--r--src/plugins/texteditor/basetexteditor_p.h1
-rw-r--r--src/plugins/texteditor/basetextmark.cpp52
-rw-r--r--src/plugins/texteditor/behaviorsettingspage.cpp5
-rw-r--r--src/plugins/texteditor/codeassist/basicproposalitemlistmodel.cpp33
-rw-r--r--src/plugins/texteditor/codeassist/basicproposalitemlistmodel.h2
-rw-r--r--src/plugins/texteditor/codeassist/codeassistant.cpp97
-rw-r--r--src/plugins/texteditor/codeassist/codeassistant.h3
-rw-r--r--src/plugins/texteditor/codeassist/functionhintproposalwidget.cpp9
-rw-r--r--src/plugins/texteditor/codeassist/genericproposalwidget.cpp9
-rw-r--r--src/plugins/texteditor/codeassist/iassistinterface.cpp4
-rw-r--r--src/plugins/texteditor/codeassist/iassistproposalwidget.cpp2
-rw-r--r--src/plugins/texteditor/codeassist/iassistproposalwidget.h1
-rw-r--r--src/plugins/texteditor/codeassist/iassistprovider.cpp2
-rw-r--r--src/plugins/texteditor/codeassist/igenericproposalmodel.h2
-rw-r--r--src/plugins/texteditor/codeassist/keywordscompletionassist.cpp8
-rw-r--r--src/plugins/texteditor/codecselector.cpp2
-rw-r--r--src/plugins/texteditor/codestyleeditor.cpp3
-rw-r--r--src/plugins/texteditor/codestylepool.cpp28
-rw-r--r--src/plugins/texteditor/codestylepool.h6
-rw-r--r--src/plugins/texteditor/codestyleselectorwidget.cpp2
-rw-r--r--src/plugins/texteditor/findincurrentfile.cpp14
-rw-r--r--src/plugins/texteditor/findinfiles.cpp19
-rw-r--r--src/plugins/texteditor/findinfiles.h3
-rw-r--r--src/plugins/texteditor/findinopenfiles.cpp18
-rw-r--r--src/plugins/texteditor/fontsettingspage.cpp10
-rw-r--r--src/plugins/texteditor/fontsettingspage.ui2
-rw-r--r--src/plugins/texteditor/generichighlighter/highlighter.cpp95
-rw-r--r--src/plugins/texteditor/generichighlighter/highlighter.h53
-rw-r--r--src/plugins/texteditor/generichighlighter/managedefinitionsdialog.cpp4
-rw-r--r--src/plugins/texteditor/generichighlighter/manager.cpp65
-rw-r--r--src/plugins/texteditor/generichighlighter/manager.h1
-rw-r--r--src/plugins/texteditor/helpitem.cpp4
-rw-r--r--src/plugins/texteditor/highlighterutils.cpp76
-rw-r--r--src/plugins/texteditor/highlighterutils.h55
-rw-r--r--src/plugins/texteditor/icodestylepreferences.cpp12
-rw-r--r--src/plugins/texteditor/icodestylepreferences.h8
-rw-r--r--src/plugins/texteditor/ihighlighterfactory.h66
-rw-r--r--src/plugins/texteditor/itexteditor.cpp24
-rw-r--r--src/plugins/texteditor/itexteditor.h32
-rw-r--r--src/plugins/texteditor/linenumberfilter.cpp5
-rw-r--r--src/plugins/texteditor/outlinefactory.cpp5
-rw-r--r--src/plugins/texteditor/plaintexteditor.cpp79
-rw-r--r--src/plugins/texteditor/plaintexteditor.h4
-rw-r--r--src/plugins/texteditor/plaintexteditorfactory.cpp25
-rw-r--r--src/plugins/texteditor/plaintexteditorfactory.h10
-rw-r--r--src/plugins/texteditor/refactoringchanges.cpp32
-rw-r--r--src/plugins/texteditor/refactoringchanges.h3
-rw-r--r--src/plugins/texteditor/snippets/snippet.cpp239
-rw-r--r--src/plugins/texteditor/snippets/snippet.h27
-rw-r--r--src/plugins/texteditor/snippets/snippeteditor.h1
-rw-r--r--src/plugins/texteditor/snippets/snippetssettingspage.cpp2
-rw-r--r--src/plugins/texteditor/syntaxhighlighter.cpp34
-rw-r--r--src/plugins/texteditor/syntaxhighlighter.h7
-rw-r--r--src/plugins/texteditor/texteditor.pro6
-rw-r--r--src/plugins/texteditor/texteditor.qbs10
-rw-r--r--src/plugins/texteditor/texteditoractionhandler.cpp556
-rw-r--r--src/plugins/texteditor/texteditoractionhandler.h12
-rw-r--r--src/plugins/texteditor/texteditorconstants.h2
-rw-r--r--src/plugins/texteditor/texteditoroverlay.cpp28
-rw-r--r--src/plugins/texteditor/texteditoroverlay.h4
-rw-r--r--src/plugins/texteditor/texteditorplugin.cpp55
-rw-r--r--src/plugins/texteditor/texteditorplugin.h5
-rw-r--r--src/plugins/texteditor/texteditorsettings.cpp190
-rw-r--r--src/plugins/texteditor/texteditorsettings.h63
-rw-r--r--src/plugins/texteditor/textfilewizard.cpp10
-rw-r--r--src/plugins/texteditor/textfilewizard.h5
-rw-r--r--src/plugins/todo/Todo.pluginspec.in2
-rw-r--r--src/plugins/todo/todoitemsprovider.cpp20
-rw-r--r--src/plugins/updateinfo/UpdateInfo.pluginspec.in2
-rw-r--r--src/plugins/updateinfo/updateinfo.qbs5
-rw-r--r--src/plugins/updateinfo/updateinfoplugin.cpp16
-rw-r--r--src/plugins/valgrind/Valgrind.pluginspec.in2
-rw-r--r--src/plugins/valgrind/callgrind/callgrind.pri2
-rw-r--r--src/plugins/valgrind/callgrind/callgrindcontroller.cpp12
-rw-r--r--src/plugins/valgrind/callgrind/callgrinddatamodel.cpp12
-rw-r--r--src/plugins/valgrind/callgrindengine.cpp49
-rw-r--r--src/plugins/valgrind/callgrindengine.h8
-rw-r--r--src/plugins/valgrind/callgrindtool.cpp200
-rw-r--r--src/plugins/valgrind/callgrindtool.h11
-rw-r--r--src/plugins/valgrind/callgrindvisualisation.cpp7
-rw-r--r--src/plugins/valgrind/memcheck/memcheck.pri2
-rw-r--r--src/plugins/valgrind/memcheck/memcheckrunner.cpp130
-rw-r--r--src/plugins/valgrind/memcheckengine.cpp68
-rw-r--r--src/plugins/valgrind/memcheckengine.h8
-rw-r--r--src/plugins/valgrind/memcheckerrorview.cpp6
-rw-r--r--src/plugins/valgrind/memcheckerrorview.h10
-rw-r--r--src/plugins/valgrind/memchecktool.cpp200
-rw-r--r--src/plugins/valgrind/memchecktool.h35
-rw-r--r--src/plugins/valgrind/suppressiondialog.cpp10
-rw-r--r--src/plugins/valgrind/suppressiondialog.h5
-rw-r--r--src/plugins/valgrind/valgrind.pro8
-rw-r--r--src/plugins/valgrind/valgrind.qbs171
-rw-r--r--src/plugins/valgrind/valgrindconfigwidget.cpp18
-rw-r--r--src/plugins/valgrind/valgrindconfigwidget.ui322
-rw-r--r--src/plugins/valgrind/valgrindengine.cpp103
-rw-r--r--src/plugins/valgrind/valgrindengine.h21
-rw-r--r--src/plugins/valgrind/valgrindplugin.cpp171
-rw-r--r--src/plugins/valgrind/valgrindplugin.h15
-rw-r--r--src/plugins/valgrind/valgrindprocess.cpp383
-rw-r--r--src/plugins/valgrind/valgrindprocess.h132
-rw-r--r--src/plugins/valgrind/valgrindruncontrolfactory.cpp97
-rw-r--r--src/plugins/valgrind/valgrindrunner.cpp5
-rw-r--r--src/plugins/valgrind/valgrindsettings.cpp211
-rw-r--r--src/plugins/valgrind/valgrindsettings.h55
-rw-r--r--src/plugins/valgrind/valgrindtool.cpp183
-rw-r--r--src/plugins/valgrind/valgrindtool.h19
-rw-r--r--src/plugins/valgrind/xmlprotocol/parser.cpp25
-rw-r--r--src/plugins/valgrind/xmlprotocol/xmlprotocol.pri2
-rw-r--r--src/plugins/vcsbase/VcsBase.pluginspec.in2
-rw-r--r--src/plugins/vcsbase/baseannotationhighlighter.cpp50
-rw-r--r--src/plugins/vcsbase/baseannotationhighlighter.h9
-rw-r--r--src/plugins/vcsbase/basecheckoutwizard.cpp65
-rw-r--r--src/plugins/vcsbase/basecheckoutwizard.h26
-rw-r--r--src/plugins/vcsbase/basecheckoutwizardpage.ui4
-rw-r--r--src/plugins/vcsbase/basevcseditorfactory.cpp31
-rw-r--r--src/plugins/vcsbase/basevcseditorfactory.h8
-rw-r--r--src/plugins/vcsbase/basevcssubmiteditorfactory.cpp49
-rw-r--r--src/plugins/vcsbase/basevcssubmiteditorfactory.h12
-rw-r--r--src/plugins/vcsbase/checkoutjobs.cpp215
-rw-r--r--src/plugins/vcsbase/checkoutjobs.h94
-rw-r--r--src/plugins/vcsbase/checkoutprogresswizardpage.cpp84
-rw-r--r--src/plugins/vcsbase/checkoutprogresswizardpage.h15
-rw-r--r--src/plugins/vcsbase/checkoutwizarddialog.cpp15
-rw-r--r--src/plugins/vcsbase/checkoutwizarddialog.h6
-rw-r--r--src/plugins/vcsbase/cleandialog.cpp4
-rw-r--r--src/plugins/vcsbase/command.cpp551
-rw-r--r--src/plugins/vcsbase/command.h80
-rw-r--r--src/plugins/vcsbase/diffhighlighter.cpp86
-rw-r--r--src/plugins/vcsbase/diffhighlighter.h9
-rw-r--r--src/plugins/vcsbase/submiteditorfile.cpp37
-rw-r--r--src/plugins/vcsbase/submiteditorfile.h13
-rw-r--r--src/plugins/vcsbase/submiteditorwidget.cpp21
-rw-r--r--src/plugins/vcsbase/submiteditorwidget.h1
-rw-r--r--src/plugins/vcsbase/submitfilemodel.cpp2
-rw-r--r--src/plugins/vcsbase/vcsbase.pro2
-rw-r--r--src/plugins/vcsbase/vcsbase.qbs2
-rw-r--r--src/plugins/vcsbase/vcsbaseclient.cpp69
-rw-r--r--src/plugins/vcsbase/vcsbaseclient.h9
-rw-r--r--src/plugins/vcsbase/vcsbaseeditor.cpp143
-rw-r--r--src/plugins/vcsbase/vcsbaseeditor.h20
-rw-r--r--src/plugins/vcsbase/vcsbaseoutputwindow.cpp26
-rw-r--r--src/plugins/vcsbase/vcsbaseoutputwindow.h7
-rw-r--r--src/plugins/vcsbase/vcsbaseplugin.cpp329
-rw-r--r--src/plugins/vcsbase/vcsbaseplugin.h36
-rw-r--r--src/plugins/vcsbase/vcsbasesubmiteditor.cpp71
-rw-r--r--src/plugins/vcsbase/vcsbasesubmiteditor.h9
-rw-r--r--src/plugins/vcsbase/vcsplugin.cpp3
-rw-r--r--src/plugins/welcome/Welcome.pluginspec.in2
-rw-r--r--src/plugins/welcome/communitywelcomepage.h2
-rw-r--r--src/plugins/welcome/welcome.pro5
-rw-r--r--src/plugins/welcome/welcome.qbs7
-rw-r--r--src/plugins/welcome/welcome_global.h41
-rw-r--r--src/plugins/welcome/welcomeplugin.cpp87
-rw-r--r--src/plugins/welcome/welcomeplugin.h2
-rw-r--r--src/shared/cpaster/cgi.cpp6
-rw-r--r--src/shared/designerintegrationv2/formresizer.cpp2
-rw-r--r--src/shared/help/bookmarkmanager.cpp14
-rw-r--r--src/shared/help/contentwindow.cpp8
-rw-r--r--src/shared/help/indexwindow.cpp12
m---------src/shared/qbs0
-rw-r--r--src/shared/qtsingleapplication/qtlocalpeer.h2
-rw-r--r--src/src.qbs6
-rw-r--r--src/tools/QtcTool.qbs3
-rw-r--r--src/tools/qml2puppet/qml2puppet/qml2puppet.pro7
-rw-r--r--src/tools/qtcdebugger/main.cpp2
-rw-r--r--src/tools/qtcdebugger/qtcdebugger.qbs5
-rw-r--r--src/tools/qtcreatorcrashhandler/qtcreatorcrashhandler.qbs32
-rw-r--r--src/tools/sdktool/operation.cpp2
-rw-r--r--src/tools/sdktool/sdktool.qbs1
-rw-r--r--src/tools/tools.pro16
-rw-r--r--src/tools/tools.qbs3
-rw-r--r--src/tools/valgrindfake/main.cpp4
-rw-r--r--src/tools/valgrindfake/outputgenerator.cpp9
-rw-r--r--src/tools/valgrindfake/valgrindfake.pro4
-rw-r--r--src/tools/valgrindfake/valgrindfake.qbs13
-rw-r--r--src/tools/wininterrupt/wininterrupt.c (renamed from src/tools/win64interrupt/win64interrupt.c)0
-rw-r--r--src/tools/wininterrupt/wininterrupt.pro (renamed from src/tools/win64interrupt/win64interrupt.pro)12
2055 files changed, 61046 insertions, 44556 deletions
diff --git a/src/app/app.qbs b/src/app/app.qbs
index c995ed5042..aebc44643e 100644
--- a/src/app/app.qbs
+++ b/src/app/app.qbs
@@ -1,5 +1,4 @@
import qbs
-import "../../qbs/defaults.js" as Defaults
Application {
name: project.ide_app_target
@@ -7,17 +6,14 @@ Application {
cpp.rpaths: qbs.targetOS.contains("osx") ? ["@executable_path/.."]
: ["$ORIGIN/../lib/qtcreator"]
- cpp.defines: Defaults.defines(qbs)
+ cpp.defines: project.generalDefines
cpp.linkerFlags: {
if (qbs.buildVariant == "release" && (qbs.toolchain.contains("gcc") || qbs.toolchain.contains("mingw")))
return ["-Wl,-s"]
}
cpp.includePaths: [
- "..",
- "../libs",
"../shared/qtsingleapplication",
"../shared/qtlockedfile",
- buildDirectory
]
Depends { name: "app_version_header" }
diff --git a/src/app/app_version_header.qbs b/src/app/app_version_header.qbs
index ddefebb83e..4908bcff4e 100644
--- a/src/app/app_version_header.qbs
+++ b/src/app/app_version_header.qbs
@@ -5,10 +5,6 @@ Product {
name: "app_version_header"
type: "hpp"
files: "app_version.h.in"
- property string ide_version_major: project.ide_version_major
- property string ide_version_minor: project.ide_version_minor
- property string ide_version_release: project.ide_version_release
- property string qtcreator_version: project.qtcreator_version
Transformer {
inputs: ["app_version.h.in"]
@@ -20,10 +16,6 @@ Product {
var cmd = new JavaScriptCommand();
cmd.description = "generating app_version.h";
cmd.highlight = "codegen";
- cmd.qtcreator_version = product.qtcreator_version;
- cmd.ide_version_major = product.ide_version_major;
- cmd.ide_version_minor = product.ide_version_minor;
- cmd.ide_version_release = product.ide_version_release;
cmd.onWindows = (product.moduleProperty("qbs", "targetOS").contains("windows"));
cmd.sourceCode = function() {
var file = new TextFile(input.fileName);
@@ -34,10 +26,10 @@ Product {
if (onWindows)
content = content.replace(/\r\n/g, "\n");
// replace the magic qmake incantations
- content = content.replace(/(\n#define IDE_VERSION) .+\n/, "$1 " + qtcreator_version + "\n");
- content = content.replace(/(\n#define IDE_VERSION_MAJOR) .+\n/, "$1 " + ide_version_major + "\n")
- content = content.replace(/(\n#define IDE_VERSION_MINOR) .+\n/, "$1 " + ide_version_minor + "\n")
- content = content.replace(/(\n#define IDE_VERSION_RELEASE) .+\n/, "$1 " + ide_version_release + "\n")
+ content = content.replace(/(\n#define IDE_VERSION) .+\n/, "$1 " + project.qtcreator_version + "\n");
+ content = content.replace(/(\n#define IDE_VERSION_MAJOR) .+\n/, "$1 " + project.ide_version_major + "\n")
+ content = content.replace(/(\n#define IDE_VERSION_MINOR) .+\n/, "$1 " + project.ide_version_minor + "\n")
+ content = content.replace(/(\n#define IDE_VERSION_RELEASE) .+\n/, "$1 " + project.ide_version_release + "\n")
file = new TextFile(output.fileName, TextFile.WriteOnly);
file.truncate();
file.write(content);
diff --git a/src/app/main.cpp b/src/app/main.cpp
index 77d9936648..bb16db908f 100644
--- a/src/app/main.cpp
+++ b/src/app/main.cpp
@@ -27,7 +27,6 @@
**
****************************************************************************/
-#include "qtsingleapplication.h"
#include "../tools/qtcreatorcrashhandler/crashhandlersetup.h"
#include <app/app_version.h>
@@ -35,6 +34,7 @@
#include <extensionsystem/pluginerroroverview.h>
#include <extensionsystem/pluginmanager.h>
#include <extensionsystem/pluginspec.h>
+#include <qtsingleapplication.h>
#include <QDebug>
#include <QDir>
@@ -62,9 +62,9 @@ using namespace ExtensionSystem;
enum { OptionIndent = 4, DescriptionIndent = 34 };
-static const char appNameC[] = "Qt Creator";
-static const char corePluginNameC[] = "Core";
-static const char fixedOptionsC[] =
+const char appNameC[] = "Qt Creator";
+const char corePluginNameC[] = "Core";
+const char fixedOptionsC[] =
" [OPTION]... [FILE]...\n"
"Options:\n"
" -help Display this help\n"
@@ -72,18 +72,20 @@ static const char fixedOptionsC[] =
" -client Attempt to connect to already running first instance\n"
" -settingspath <path> Override the default path where user settings are stored\n"
" -pid <pid> Attempt to connect to instance given by pid\n"
-" -block Block until editor is closed\n";
-
-
-static const char HELP_OPTION1[] = "-h";
-static const char HELP_OPTION2[] = "-help";
-static const char HELP_OPTION3[] = "/h";
-static const char HELP_OPTION4[] = "--help";
-static const char VERSION_OPTION[] = "-version";
-static const char CLIENT_OPTION[] = "-client";
-static const char SETTINGS_OPTION[] = "-settingspath";
-static const char PID_OPTION[] = "-pid";
-static const char BLOCK_OPTION[] = "-block";
+" -block Block until editor is closed\n"
+" -pluginpath <path> Add a custom search path for plugins\n";
+
+const char HELP_OPTION1[] = "-h";
+const char HELP_OPTION2[] = "-help";
+const char HELP_OPTION3[] = "/h";
+const char HELP_OPTION4[] = "--help";
+const char VERSION_OPTION[] = "-version";
+const char CLIENT_OPTION[] = "-client";
+const char SETTINGS_OPTION[] = "-settingspath";
+const char TEST_OPTION[] = "-test";
+const char PID_OPTION[] = "-pid";
+const char BLOCK_OPTION[] = "-block";
+const char PLUGINPATH_OPTION[] = "-pluginpath";
typedef QList<PluginSpec *> PluginSpecSet;
@@ -263,6 +265,7 @@ static inline QSettings *userSettings()
|| lowerFile.startsWith(QLatin1String("toolchains.xml"))
|| lowerFile.startsWith(QLatin1String("qtversion.xml"))
|| lowerFile.startsWith(QLatin1String("devices.xml"))
+ || lowerFile.startsWith(QLatin1String("debuggers.xml"))
|| lowerFile.startsWith(QLatin1String("qtcreator.")))
QFile::copy(srcDir.absoluteFilePath(file), destDir.absoluteFilePath(file));
if (file == QLatin1String("qtcreator"))
@@ -309,14 +312,21 @@ int main(int argc, char **argv)
#if QT_VERSION >= 0x050100
app.setAttribute(Qt::AA_UseHighDpiPixmaps);
+# if defined(Q_OS_WIN) || defined(Q_OS_MAC)
+ // Prevent native windows from being created for the sibling widgets of the welcome screen.
+ // Causes flicker on Linux, though.
+ app.setAttribute(Qt::AA_DontCreateNativeWidgetSiblings);
+# endif
#endif
// Manually determine -settingspath command line option
// We can't use the regular way of the plugin manager, because that needs to parse pluginspecs
// but the settings path can influence which plugins are enabled
QString settingsPath;
+ QStringList customPluginPaths;
QStringList arguments = app.arguments(); // adapted arguments list is passed to plugin manager later
QMutableStringListIterator it(arguments);
+ bool testOptionProvided = false;
while (it.hasNext()) {
const QString &arg = it.next();
if (arg == QLatin1String(SETTINGS_OPTION)) {
@@ -325,8 +335,21 @@ int main(int argc, char **argv)
settingsPath = QDir::fromNativeSeparators(it.next());
it.remove();
}
+ } else if (arg == QLatin1String(PLUGINPATH_OPTION)) {
+ it.remove();
+ if (it.hasNext()) {
+ customPluginPaths << QDir::fromNativeSeparators(it.next());
+ it.remove();
+ }
+ } else if (arg == QLatin1String(TEST_OPTION)) {
+ testOptionProvided = true;
}
}
+ if (settingsPath.isEmpty() && testOptionProvided) {
+ settingsPath = QDir::tempPath() + QString::fromLatin1("/qtc-%1-test-settings")
+ .arg(QLatin1String(Core::Constants::IDE_VERSION_LONG));
+ settingsPath = QDir::cleanPath(settingsPath);
+ }
if (!settingsPath.isEmpty())
QSettings::setPath(QSettings::IniFormat, QSettings::UserScope, settingsPath);
@@ -392,19 +415,17 @@ int main(int argc, char **argv)
QNetworkProxy proxy(QNetworkProxy::HttpProxy, proxyUrl.host(),
proxyUrl.port(), proxyUrl.userName(), proxyUrl.password());
QNetworkProxy::setApplicationProxy(proxy);
- }
# if defined(Q_OS_MAC) // unix and mac
- else {
+ } else {
QNetworkProxyFactory::setUseSystemConfiguration(true);
- }
# endif
+ }
#else // windows
QNetworkProxyFactory::setUseSystemConfiguration(true);
#endif
// Load
- const QStringList pluginPaths = getPluginPaths();
+ const QStringList pluginPaths = getPluginPaths() + customPluginPaths;
PluginManager::setPluginPaths(pluginPaths);
-
QMap<QString, QString> foundAppOptions;
if (arguments.size() > 1) {
QMap<QString, bool> appOptions;
diff --git a/src/libs/3rdparty/botan/botan.pri b/src/libs/3rdparty/botan/botan.pri
index 3c65676629..3ff57ded1b 100644
--- a/src/libs/3rdparty/botan/botan.pri
+++ b/src/libs/3rdparty/botan/botan.pri
@@ -36,7 +36,7 @@ win32 {
win32-msvc* {
QMAKE_CXXFLAGS += -wd4251 -wd4290 -wd4250
- DEFINES += BOTAN_BUILD_COMPILER_IS_MSVC BOTAN_TARGET_OS_HAS_GMTIME_S
+ DEFINES += BOTAN_BUILD_COMPILER_IS_MSVC BOTAN_TARGET_OS_HAS_GMTIME_S _SCL_SECURE_NO_WARNINGS
} else {
QMAKE_CFLAGS += -fpermissive -finline-functions -Wno-long-long
QMAKE_CXXFLAGS += -fpermissive -finline-functions -Wno-long-long
diff --git a/src/libs/3rdparty/cplusplus/Bind.cpp b/src/libs/3rdparty/cplusplus/Bind.cpp
index 183bebdef1..0defcc0a1f 100644
--- a/src/libs/3rdparty/cplusplus/Bind.cpp
+++ b/src/libs/3rdparty/cplusplus/Bind.cpp
@@ -1142,11 +1142,11 @@ const StringLiteral *Bind::asStringLiteral(unsigned firstToken, unsigned lastTok
std::string buffer;
for (unsigned index = firstToken; index != lastToken; ++index) {
const Token &tk = tokenAt(index);
- if (tk.whitespace() || tk.newline())
+ if (index != firstToken && (tk.whitespace() || tk.newline()))
buffer += ' ';
buffer += tk.spell();
}
- return control()->stringLiteral(buffer.c_str(), buffer.size());
+ return control()->stringLiteral(buffer.c_str(), unsigned(buffer.size()));
}
// StatementAST
@@ -1168,7 +1168,7 @@ bool Bind::visit(QtMemberDeclarationAST *ast)
privateClass += nameId->identifier()->chars();
privateClass += "Private";
- const Name *privName = control()->identifier(privateClass.c_str(), privateClass.size());
+ const Name *privName = control()->identifier(privateClass.c_str(), unsigned(privateClass.size()));
declTy.setType(control()->namedType(privName));
}
}
@@ -1262,7 +1262,7 @@ bool Bind::visit(ForeachStatementAST *ast)
unsigned endOfExpression = ast->expression->lastToken();
const StringLiteral *sl = asStringLiteral(startOfExpression, endOfExpression);
const std::string buff = std::string("*") + sl->chars() + ".begin()";
- initializer = control()->stringLiteral(buff.c_str(), buff.size());
+ initializer = control()->stringLiteral(buff.c_str(), unsigned(buff.size()));
}
}
@@ -1312,7 +1312,7 @@ bool Bind::visit(RangeBasedForStatementAST *ast)
unsigned endOfExpression = ast->expression->lastToken();
const StringLiteral *sl = asStringLiteral(startOfExpression, endOfExpression);
const std::string buff = std::string("*") + sl->chars() + ".begin()";
- initializer = control()->stringLiteral(buff.c_str(), buff.size());
+ initializer = control()->stringLiteral(buff.c_str(), unsigned(buff.size()));
}
}
@@ -1861,7 +1861,7 @@ bool Bind::visit(SimpleDeclarationAST *ast)
setDeclSpecifiers(decl, type);
if (Function *fun = decl->type()->asFunctionType()) {
- fun->setScope(_scope);
+ fun->setEnclosingScope(_scope);
fun->setSourceLocation(sourceLocation, translationUnit());
setDeclSpecifiers(fun, type);
@@ -2591,7 +2591,7 @@ bool Bind::visit(ObjCSelectorAST *ast) // ### review
}
if (! arguments.empty()) {
- _name = control()->selectorNameId(&arguments[0], arguments.size(), hasArgs);
+ _name = control()->selectorNameId(&arguments[0], unsigned(arguments.size()), hasArgs);
ast->name = _name;
}
@@ -2676,7 +2676,7 @@ bool Bind::visit(TemplateIdAST *ast)
_name = control()->templateNameId(id, isSpecialization);
else
_name = control()->templateNameId(id, isSpecialization, &templateArguments[0],
- templateArguments.size());
+ unsigned(templateArguments.size()));
ast->name = _name;
return false;
@@ -3016,18 +3016,10 @@ bool Bind::visit(EnumSpecifierAST *ast)
this->enumerator(it->value, e);
}
- if (ast->stray_comma_token /* && ! translationUnit()->cxx0xEnabled()*/) {
- const Token &tk = tokenAt(ast->stray_comma_token);
- if (! tk.generated())
- translationUnit()->warning(ast->stray_comma_token,
- "commas at the end of enumerator lists are a C++0x-specific feature");
- }
-
(void) switchScope(previousScope);
return false;
}
-
// PtrOperatorAST
bool Bind::visit(PointerToMemberAST *ast)
{
diff --git a/src/libs/3rdparty/cplusplus/Control.cpp b/src/libs/3rdparty/cplusplus/Control.cpp
index e274a20906..42028ae4ed 100644
--- a/src/libs/3rdparty/cplusplus/Control.cpp
+++ b/src/libs/3rdparty/cplusplus/Control.cpp
@@ -584,7 +584,7 @@ const Identifier *Control::identifier(const char *chars, unsigned size)
const Identifier *Control::identifier(const char *chars)
{
- unsigned length = std::strlen(chars);
+ const unsigned length = unsigned(std::strlen(chars));
return identifier(chars, length);
}
@@ -611,7 +611,7 @@ const StringLiteral *Control::stringLiteral(const char *chars, unsigned size)
const StringLiteral *Control::stringLiteral(const char *chars)
{
- unsigned length = std::strlen(chars);
+ const unsigned length = unsigned(std::strlen(chars));
return stringLiteral(chars, length);
}
@@ -620,7 +620,7 @@ const NumericLiteral *Control::numericLiteral(const char *chars, unsigned size)
const NumericLiteral *Control::numericLiteral(const char *chars)
{
- unsigned length = std::strlen(chars);
+ const unsigned length = unsigned(std::strlen(chars));
return numericLiteral(chars, length);
}
diff --git a/src/libs/3rdparty/cplusplus/Names.cpp b/src/libs/3rdparty/cplusplus/Names.cpp
index 4d92110284..7f26ea1ad6 100644
--- a/src/libs/3rdparty/cplusplus/Names.cpp
+++ b/src/libs/3rdparty/cplusplus/Names.cpp
@@ -100,7 +100,7 @@ const Identifier *TemplateNameId::identifier() const
{ return _identifier; }
unsigned TemplateNameId::templateArgumentCount() const
-{ return _templateArguments.size(); }
+{ return unsigned(_templateArguments.size()); }
const FullySpecifiedType &TemplateNameId::templateArgumentAt(unsigned index) const
{ return _templateArguments[index]; }
@@ -130,10 +130,23 @@ bool TemplateNameId::isEqualTo(const Name *other) const
bool TemplateNameId::Compare::operator()(const TemplateNameId *name,
const TemplateNameId *other) const
{
+ if (name == 0)
+ return other != 0;
+ if (other == 0)
+ return false;
+ if (name == other)
+ return false;
+
const Identifier *id = name->identifier();
const Identifier *otherId = other->identifier();
- if (id == otherId) {
+ if (id == 0)
+ return otherId != 0;
+ if (otherId == 0)
+ return false;
+
+ const int c = std::strcmp(id->chars(), otherId->chars());
+ if (c == 0) {
// we have to differentiate TemplateNameId with respect to specialization or instantiation
if (name->isSpecialization() == other->isSpecialization()) {
return std::lexicographical_compare(name->firstTemplateArgument(),
@@ -145,7 +158,7 @@ bool TemplateNameId::Compare::operator()(const TemplateNameId *name,
}
}
- return id < otherId;
+ return c < 0;
}
OperatorNameId::OperatorNameId(Kind kind)
@@ -217,7 +230,7 @@ const Identifier *SelectorNameId::identifier() const
}
unsigned SelectorNameId::nameCount() const
-{ return _names.size(); }
+{ return unsigned(_names.size()); }
const Name *SelectorNameId::nameAt(unsigned index) const
{ return _names[index]; }
diff --git a/src/libs/3rdparty/cplusplus/Parser.cpp b/src/libs/3rdparty/cplusplus/Parser.cpp
index 9c6804219b..b67920266f 100644
--- a/src/libs/3rdparty/cplusplus/Parser.cpp
+++ b/src/libs/3rdparty/cplusplus/Parser.cpp
@@ -333,7 +333,9 @@ bool Parser::skipUntilStatement()
case T_USING:
return true;
+ case T_AT_TRY:
case T_AT_SYNCHRONIZED:
+ case T_AT_THROW:
if (objCEnabled())
return true;
@@ -3106,9 +3108,15 @@ bool Parser::parseStatement(StatementAST *&node)
return true;
}
+ case T_AT_TRY:
+ return objCEnabled() && parseObjCTryStatement(node);
+
case T_AT_SYNCHRONIZED:
return objCEnabled() && parseObjCSynchronizedStatement(node);
+ case T_AT_THROW:
+ return objCEnabled() && parseObjCThrowStatement(node);
+
case T_Q_D:
case T_Q_Q: {
QtMemberDeclarationAST *ast = new (_pool) QtMemberDeclarationAST;
@@ -4404,6 +4412,52 @@ bool Parser::parseObjCStringLiteral(ExpressionAST *&node)
return true;
}
+/// objc-try-catch-statement:
+/// @try compound-statement objc-catch-list[opt]
+/// @try compound-statement objc-catch-list[opt] @finally compound-statement
+///
+/// objc-catch-list:
+/// @catch ( parameter-declaration ) compound-statement
+/// objc-catch-list @catch ( catch-parameter-declaration ) compound-statement
+/// catch-parameter-declaration:
+/// parameter-declaration
+/// '...' [OBJC2]
+///
+bool Parser::parseObjCTryStatement(StatementAST *& /*node*/)
+{
+ DEBUG_THIS_RULE();
+ if (LA() != T_AT_TRY)
+ return false;
+
+ /*try_token =*/ consumeToken();
+ StatementAST *body_statment;
+ parseCompoundStatement(body_statment);
+ while (LA() == T_AT_CATCH) {
+ /*catch_token =*/ consumeToken();
+ unsigned lparen_token;
+ match(T_LPAREN, &lparen_token);
+ if (LA() == T_DOT_DOT_DOT) {
+ /*unsigned ellipsis_token =*/ consumeToken();
+ } else {
+ ParameterDeclarationAST *exception_decl;
+ parseParameterDeclaration(exception_decl);
+ }
+ unsigned rparen_token;
+ match(T_RPAREN, &rparen_token);
+ StatementAST *catch_statement;
+ parseCompoundStatement(catch_statement);
+ }
+
+ if (LA() == T_AT_FINALLY) {
+ StatementAST *finally_statement;
+ parseCompoundStatement(finally_statement);
+ }
+
+ return true;
+}
+
+/// objc-synchronized-statement:
+/// @synchronized expression ;
bool Parser::parseObjCSynchronizedStatement(StatementAST *&node)
{
DEBUG_THIS_RULE();
@@ -4422,6 +4476,23 @@ bool Parser::parseObjCSynchronizedStatement(StatementAST *&node)
return true;
}
+/// objc-throw-statement:
+/// @ throw expression ;
+bool Parser::parseObjCThrowStatement(StatementAST *&/*node*/)
+{
+ DEBUG_THIS_RULE();
+ if (LA() != T_AT_THROW)
+ return false;
+
+ /*throw_token =*/ consumeToken();
+ ExpressionAST *thrown_expression;
+ parseExpression(thrown_expression);
+ unsigned semicolon_token;
+ match(T_SEMICOLON, &semicolon_token);
+
+ return true;
+}
+
bool Parser::parseObjCEncodeExpression(ExpressionAST *&node)
{
DEBUG_THIS_RULE();
diff --git a/src/libs/3rdparty/cplusplus/Parser.h b/src/libs/3rdparty/cplusplus/Parser.h
index 978b1f99a1..1d505024e5 100644
--- a/src/libs/3rdparty/cplusplus/Parser.h
+++ b/src/libs/3rdparty/cplusplus/Parser.h
@@ -222,7 +222,9 @@ public:
bool parseObjCProtocol(DeclarationAST *&node,
SpecifierListAST *attributes = 0);
+ bool parseObjCTryStatement(StatementAST *&node);
bool parseObjCSynchronizedStatement(StatementAST *&node);
+ bool parseObjCThrowStatement(StatementAST *&node);
bool parseObjCEncodeExpression(ExpressionAST *&node);
bool parseObjCProtocolExpression(ExpressionAST *&node);
bool parseObjCSelectorExpression(ExpressionAST *&node);
diff --git a/src/libs/3rdparty/cplusplus/Scope.cpp b/src/libs/3rdparty/cplusplus/Scope.cpp
index 66d422ad35..ab1ba2710d 100644
--- a/src/libs/3rdparty/cplusplus/Scope.cpp
+++ b/src/libs/3rdparty/cplusplus/Scope.cpp
@@ -109,7 +109,7 @@ SymbolTable::~SymbolTable()
void SymbolTable::enterSymbol(Symbol *symbol)
{
- CPP_ASSERT(! symbol->_scope || symbol->enclosingScope() == _owner, return);
+ CPP_ASSERT(! symbol->_enclosingScope || symbol->enclosingScope() == _owner, return);
if (++_symbolCount == _allocatedSymbols) {
_allocatedSymbols <<= 1;
@@ -120,7 +120,7 @@ void SymbolTable::enterSymbol(Symbol *symbol)
}
symbol->_index = _symbolCount;
- symbol->_scope = _owner;
+ symbol->_enclosingScope = _owner;
_symbols[_symbolCount] = symbol;
if (_symbolCount * 5 >= _hashSize * 3)
diff --git a/src/libs/3rdparty/cplusplus/Symbol.cpp b/src/libs/3rdparty/cplusplus/Symbol.cpp
index f5506b8c89..cb55c559b0 100644
--- a/src/libs/3rdparty/cplusplus/Symbol.cpp
+++ b/src/libs/3rdparty/cplusplus/Symbol.cpp
@@ -87,7 +87,7 @@ private:
Symbol::Symbol(TranslationUnit *translationUnit, unsigned sourceLocation, const Name *name)
: _name(0),
- _scope(0),
+ _enclosingScope(0),
_next(0),
_fileId(0),
_sourceLocation(0),
@@ -107,7 +107,7 @@ Symbol::Symbol(TranslationUnit *translationUnit, unsigned sourceLocation, const
Symbol::Symbol(Clone *clone, Subst *subst, Symbol *original)
: _name(clone->name(original->_name, subst)),
- _scope(0),
+ _enclosingScope(0),
_next(0),
_fileId(clone->control()->stringLiteral(original->fileName(), original->fileNameLength())),
_sourceLocation(original->_sourceLocation),
@@ -231,22 +231,22 @@ const Identifier *Symbol::identifier() const
}
Scope *Symbol::enclosingScope() const
-{ return _scope; }
+{ return _enclosingScope; }
-void Symbol::setScope(Scope *scope)
+void Symbol::setEnclosingScope(Scope *scope)
{
- CPP_CHECK(! _scope);
- _scope = scope;
+ CPP_CHECK(! _enclosingScope);
+ _enclosingScope = scope;
}
-void Symbol::resetScope()
+void Symbol::resetEnclosingScope()
{
- _scope = 0;
+ _enclosingScope = 0;
}
Namespace *Symbol::enclosingNamespace() const
{
- for (Scope *s = _scope; s; s = s->enclosingScope()) {
+ for (Scope *s = _enclosingScope; s; s = s->enclosingScope()) {
if (Namespace *ns = s->asNamespace())
return ns;
}
@@ -255,7 +255,7 @@ Namespace *Symbol::enclosingNamespace() const
Template *Symbol::enclosingTemplate() const
{
- for (Scope *s = _scope; s; s = s->enclosingScope()) {
+ for (Scope *s = _enclosingScope; s; s = s->enclosingScope()) {
if (Template *templ = s->asTemplate())
return templ;
}
@@ -264,7 +264,7 @@ Template *Symbol::enclosingTemplate() const
Class *Symbol::enclosingClass() const
{
- for (Scope *s = _scope; s; s = s->enclosingScope()) {
+ for (Scope *s = _enclosingScope; s; s = s->enclosingScope()) {
if (Class *klass = s->asClass())
return klass;
}
@@ -273,7 +273,7 @@ Class *Symbol::enclosingClass() const
Enum *Symbol::enclosingEnum() const
{
- for (Scope *s = _scope; s; s = s->enclosingScope()) {
+ for (Scope *s = _enclosingScope; s; s = s->enclosingScope()) {
if (Enum *e = s->asEnum())
return e;
}
@@ -282,7 +282,7 @@ Enum *Symbol::enclosingEnum() const
Function *Symbol::enclosingFunction() const
{
- for (Scope *s = _scope; s; s = s->enclosingScope()) {
+ for (Scope *s = _enclosingScope; s; s = s->enclosingScope()) {
if (Function *fun = s->asFunction())
return fun;
}
@@ -291,18 +291,13 @@ Function *Symbol::enclosingFunction() const
Block *Symbol::enclosingBlock() const
{
- for (Scope *s = _scope; s; s = s->enclosingScope()) {
+ for (Scope *s = _enclosingScope; s; s = s->enclosingScope()) {
if (Block *block = s->asBlock())
return block;
}
return 0;
}
-Scope *Symbol::scope() const
-{
- return _scope;
-}
-
unsigned Symbol::index() const
{ return _index; }
@@ -430,7 +425,7 @@ void Symbol::copy(Symbol *other)
_hashCode = other->_hashCode;
_storage = other->_storage;
_visibility = other->_visibility;
- _scope = other->_scope;
+ _enclosingScope = other->_enclosingScope;
_index = other->_index;
_next = other->_next;
_fileId = other->_fileId;
diff --git a/src/libs/3rdparty/cplusplus/Symbol.h b/src/libs/3rdparty/cplusplus/Symbol.h
index 30cd28797b..919268b14b 100644
--- a/src/libs/3rdparty/cplusplus/Symbol.h
+++ b/src/libs/3rdparty/cplusplus/Symbol.h
@@ -290,9 +290,8 @@ public:
/// Returns the enclosing Block scope.
Block *enclosingBlock() const;
- Scope *scope() const;
- void setScope(Scope *enclosingScope); // ### make me private
- void resetScope(); // ### make me private
+ void setEnclosingScope(Scope *enclosingScope); // ### make me private
+ void resetEnclosingScope(); // ### make me private
void setSourceLocation(unsigned sourceLocation, TranslationUnit *translationUnit); // ### make me private
void visitSymbol(SymbolVisitor *visitor);
@@ -305,7 +304,7 @@ protected:
private:
const Name *_name;
- Scope *_scope;
+ Scope *_enclosingScope;
Symbol *_next;
const StringLiteral *_fileId;
unsigned _sourceLocation;
diff --git a/src/libs/3rdparty/cplusplus/Symbols.cpp b/src/libs/3rdparty/cplusplus/Symbols.cpp
index 6101e51485..dc20da15aa 100644
--- a/src/libs/3rdparty/cplusplus/Symbols.cpp
+++ b/src/libs/3rdparty/cplusplus/Symbols.cpp
@@ -722,7 +722,7 @@ bool Class::matchType0(const Type *otherType, TypeMatcher *matcher) const
}
unsigned Class::baseClassCount() const
-{ return _baseClasses.size(); }
+{ return unsigned(_baseClasses.size()); }
BaseClass *Class::baseClassAt(unsigned index) const
{ return _baseClasses.at(index); }
@@ -885,7 +885,7 @@ void ObjCClass::setBaseClass(ObjCBaseClass *baseClass)
{ _baseClass = baseClass; }
unsigned ObjCClass::protocolCount() const
-{ return _protocols.size(); }
+{ return unsigned(_protocols.size()); }
ObjCBaseProtocol *ObjCClass::protocolAt(unsigned index) const
{ return _protocols.at(index); }
@@ -951,7 +951,7 @@ ObjCProtocol::~ObjCProtocol()
{}
unsigned ObjCProtocol::protocolCount() const
-{ return _protocols.size(); }
+{ return unsigned(_protocols.size()); }
ObjCBaseProtocol *ObjCProtocol::protocolAt(unsigned index) const
{ return _protocols.at(index); }
diff --git a/src/libs/3rdparty/cplusplus/Templates.cpp b/src/libs/3rdparty/cplusplus/Templates.cpp
index 8e9e2d8170..2e9772e191 100644
--- a/src/libs/3rdparty/cplusplus/Templates.cpp
+++ b/src/libs/3rdparty/cplusplus/Templates.cpp
@@ -188,7 +188,7 @@ Symbol *CloneSymbol::cloneSymbol(Symbol *symbol, Subst *subst)
SymbolSubstPair symbolSubstPair = std::make_pair(symbol, subst);
if (_cache.find(symbolSubstPair) != _cache.end()) {
Symbol *cachedSymbol = _cache[symbolSubstPair];
- if (cachedSymbol->scope() == symbol->scope())
+ if (cachedSymbol->enclosingScope() == symbol->enclosingScope())
return cachedSymbol;
}
@@ -443,7 +443,7 @@ void CloneName::visit(const TemplateNameId *name)
_name = _control->templateNameId(_clone->identifier(name->identifier()), name->isSpecialization());
else
_name = _control->templateNameId(_clone->identifier(name->identifier()), name->isSpecialization(),
- &args[0], args.size());
+ &args[0], unsigned(args.size()));
}
void CloneName::visit(const DestructorNameId *name)
@@ -473,7 +473,7 @@ void CloneName::visit(const SelectorNameId *name)
std::vector<const Name *> names(name->nameCount());
for (unsigned i = 0; i < names.size(); ++i)
names[i] = _clone->name(name->nameAt(i), _subst);
- _name = _control->selectorNameId(&names[0], names.size(), name->hasArguments());
+ _name = _control->selectorNameId(&names[0], unsigned(names.size()), name->hasArguments());
}
@@ -531,7 +531,7 @@ Symbol *Clone::instantiate(Template *templ, const FullySpecifiedType *const args
}
}
if (Symbol *inst = symbol(templ->declaration(), &subst)) {
- inst->setScope(templ->enclosingScope());
+ inst->setEnclosingScope(templ->enclosingScope());
return inst;
}
return 0;
diff --git a/src/libs/3rdparty/cplusplus/Token.cpp b/src/libs/3rdparty/cplusplus/Token.cpp
index ed3319aeab..ab6d3c0317 100644
--- a/src/libs/3rdparty/cplusplus/Token.cpp
+++ b/src/libs/3rdparty/cplusplus/Token.cpp
@@ -23,7 +23,7 @@
using namespace CPlusPlus;
-static const char *token_names[] = {
+const char *token_names[] = {
(""), ("<error>"),
("<C++ comment>"), ("<C++ doxy comment>"),
diff --git a/src/libs/3rdparty/cplusplus/TranslationUnit.cpp b/src/libs/3rdparty/cplusplus/TranslationUnit.cpp
index 79b5af059c..0ecb9827f8 100644
--- a/src/libs/3rdparty/cplusplus/TranslationUnit.cpp
+++ b/src/libs/3rdparty/cplusplus/TranslationUnit.cpp
@@ -117,7 +117,7 @@ const char *TranslationUnit::spell(unsigned index) const
}
unsigned TranslationUnit::commentCount() const
-{ return _comments->size(); }
+{ return unsigned(_comments->size()); }
const Token &TranslationUnit::commentAt(unsigned index) const
{ return _comments->at(index); }
@@ -266,11 +266,11 @@ void TranslationUnit::tokenize()
}
goto _Lrecognize;
} else if (tk.f.kind == T_LBRACE) {
- braces.push(_tokens->size());
+ braces.push(unsigned(_tokens->size()));
} else if (tk.f.kind == T_RBRACE && ! braces.empty()) {
const unsigned open_brace_index = braces.top();
braces.pop();
- (*_tokens)[open_brace_index].close_brace = _tokens->size();
+ (*_tokens)[open_brace_index].close_brace = unsigned(_tokens->size());
} else if (tk.isComment()) {
_comments->push_back(tk);
continue; // comments are not in the regular token stream
@@ -298,7 +298,7 @@ void TranslationUnit::tokenize()
for (; ! braces.empty(); braces.pop()) {
unsigned open_brace_index = braces.top();
- (*_tokens)[open_brace_index].close_brace = _tokens->size();
+ (*_tokens)[open_brace_index].close_brace = unsigned(_tokens->size());
}
}
@@ -428,8 +428,7 @@ void TranslationUnit::getPosition(unsigned tokenOffset,
// If this token is expanded we already have the information directly from the expansion
// section header. Otherwise, we need to calculate it.
- std::map<unsigned, std::pair<unsigned, unsigned> >::const_iterator it =
- _expandedLineColumn.find(tokenOffset);
+ TokenLineColumn::const_iterator it = _expandedLineColumn.find(tokenOffset);
if (it != _expandedLineColumn.end()) {
lineNumber = it->second.first;
columnNumber = it->second.second + 1;
@@ -554,8 +553,7 @@ bool TranslationUnit::maybeSplitGreaterGreaterToken(unsigned tokenIndex)
_tokens->insert(_tokens->begin() + tokenIndex + 1, newGreater);
- std::map<unsigned, std::pair<unsigned, unsigned> >::const_iterator it =
- _expandedLineColumn.find(tok.offset);
+ TokenLineColumn::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));
diff --git a/src/libs/3rdparty/cplusplus/TranslationUnit.h b/src/libs/3rdparty/cplusplus/TranslationUnit.h
index fb4ee91b7c..d6816b99a2 100644
--- a/src/libs/3rdparty/cplusplus/TranslationUnit.h
+++ b/src/libs/3rdparty/cplusplus/TranslationUnit.h
@@ -27,7 +27,18 @@
#include "DiagnosticClient.h"
#include <cstdio>
#include <vector>
-#include <map>
+
+#if !(__cplusplus > 199711L || __GXX_EXPERIMENTAL_CXX0X__ || _MSC_VER >= 1600 || defined( _LIBCPP_VERSION ))
+#define USE_TR1
+#endif
+
+#if defined(_MSC_VER) && _MSC_VER < 1600
+# include <map>
+#elif defined(USE_TR1)
+# include <tr1/unordered_map>
+#else
+# include <unordered_map>
+#endif
namespace CPlusPlus {
@@ -52,7 +63,7 @@ public:
void setSource(const char *source, unsigned size);
- unsigned tokenCount() const { return _tokens->size(); }
+ unsigned tokenCount() const { return unsigned(_tokens->size()); }
const Token &tokenAt(unsigned index) const { return _tokens->at(index); }
int tokenKind(unsigned index) const { return _tokens->at(index).f.kind; }
const char *spell(unsigned index) const;
@@ -175,7 +186,15 @@ private:
std::vector<Token> *_comments;
std::vector<unsigned> _lineOffsets;
std::vector<PPLine> _ppLines;
- std::map<unsigned, std::pair<unsigned, unsigned> > _expandedLineColumn; // TODO: Replace this for a hash
+#if defined(_MSC_VER) && _MSC_VER < 1600
+ // MSVC2008 and earlier do not implement TR1.
+ typedef std::map<unsigned, std::pair<unsigned, unsigned> > TokenLineColumn;
+#elif defined(USE_TR1)
+ typedef std::tr1::unordered_map<unsigned, std::pair<unsigned, unsigned> > TokenLineColumn;
+#else
+ typedef std::unordered_map<unsigned, std::pair<unsigned, unsigned> > TokenLineColumn;
+#endif
+ TokenLineColumn _expandedLineColumn;
MemoryPool *_pool;
AST *_ast;
TranslationUnit *_previousTranslationUnit;
diff --git a/src/libs/3rdparty/cplusplus/cplusplus.pri b/src/libs/3rdparty/cplusplus/cplusplus.pri
index e179f54c89..004ef4014e 100644
--- a/src/libs/3rdparty/cplusplus/cplusplus.pri
+++ b/src/libs/3rdparty/cplusplus/cplusplus.pri
@@ -1,7 +1,3 @@
-
-DEPENDPATH += $$PWD
-INCLUDEPATH += $$PWD
-
HEADERS += \
$$PWD/cppassert.h \
$$PWD/CPlusPlus.h \
diff --git a/src/libs/QtcLibrary.qbs b/src/libs/QtcLibrary.qbs
index a90826df3b..03ab3374d3 100644
--- a/src/libs/QtcLibrary.qbs
+++ b/src/libs/QtcLibrary.qbs
@@ -1,29 +1,32 @@
import qbs.base 1.0
-import "../../qbs/defaults.js" as Defaults
+import "../../qbs/functions.js" as QtcFunctions
DynamicLibrary {
Depends { name: "cpp" }
Depends {
- condition: Defaults.testsEnabled(qbs)
+ condition: project.testsEnabled
name: "Qt.test"
}
- targetName: Defaults.qtLibraryName(qbs, name)
+ targetName: QtcFunctions.qtLibraryName(qbs, name)
+ destinationDirectory: project.ide_library_path
- cpp.defines: Defaults.defines(qbs)
+ cpp.defines: project.generalDefines
cpp.linkerFlags: {
if (qbs.buildVariant == "release" && (qbs.toolchain.contains("gcc") || qbs.toolchain.contains("mingw")))
return ["-Wl,-s"]
+ else if (qbs.buildVariant == "debug" && qbs.toolchain.contains("msvc"))
+ return ["/INCREMENTAL:NO"] // Speed up startup time when debugging with cdb
}
cpp.installNamePrefix: "@rpath/PlugIns/"
cpp.rpaths: qbs.targetOS.contains("osx")
? ["@loader_path/..", "@executable_path/.."]
: ["$ORIGIN", "$ORIGIN/.."]
- cpp.includePaths: [ ".", ".." ]
+ cpp.includePaths: [path]
Export {
Depends { name: "cpp" }
- cpp.includePaths: [ "." ]
+ cpp.includePaths: [path]
}
Group {
diff --git a/src/libs/cplusplus/ASTParent.h b/src/libs/cplusplus/ASTParent.h
index efd7d322d9..02f4a4fea5 100644
--- a/src/libs/cplusplus/ASTParent.h
+++ b/src/libs/cplusplus/ASTParent.h
@@ -40,7 +40,7 @@ namespace CPlusPlus {
class CPLUSPLUS_EXPORT ASTParent: protected ASTVisitor
{
public:
- ASTParent(TranslationUnit *transaltionUnit, AST *rootNode);
+ ASTParent(TranslationUnit *translationUnit, AST *rootNode);
virtual ~ASTParent();
AST *operator()(AST *ast) const;
diff --git a/src/libs/cplusplus/CppDocument.cpp b/src/libs/cplusplus/CppDocument.cpp
index 9b92eda5d8..6ba998a6e4 100644
--- a/src/libs/cplusplus/CppDocument.cpp
+++ b/src/libs/cplusplus/CppDocument.cpp
@@ -177,10 +177,11 @@ protected:
virtual bool visit(Template *symbol)
{
- if (symbol->declaration() && symbol->declaration()->isFunction())
- return process(symbol);
- else
- return true;
+ if (Symbol *decl = symbol->declaration()) {
+ if (decl->isFunction() || decl->isClass())
+ return process(symbol);
+ }
+ return true;
}
// Objective-C
@@ -340,7 +341,7 @@ QString Document::fileName() const
QStringList Document::includedFiles() const
{
QStringList files;
- foreach (const Include &i, _includes)
+ foreach (const Include &i, _resolvedIncludes)
files.append(i.resolvedFileName());
files.removeDuplicates();
return files;
@@ -349,7 +350,10 @@ QStringList Document::includedFiles() const
// This assumes to be called with a QDir::cleanPath cleaned fileName.
void Document::addIncludeFile(const Document::Include &include)
{
- _includes.append(include);
+ if (include.resolvedFileName().isEmpty())
+ _unresolvedIncludes.append(include);
+ else
+ _resolvedIncludes.append(include);
}
void Document::appendMacro(const Macro &macro)
@@ -732,14 +736,16 @@ void Snapshot::insert(Document::Ptr doc)
_documents.insert(doc->fileName(), doc);
}
-Document::Ptr Snapshot::preprocessedDocument(const QString &source, const QString &fileName) const
+Document::Ptr Snapshot::preprocessedDocument(const QByteArray &source,
+ const QString &fileName) const
{
Document::Ptr newDoc = Document::create(fileName);
if (Document::Ptr thisDocument = document(fileName)) {
newDoc->_revision = thisDocument->_revision;
newDoc->_editorRevision = thisDocument->_editorRevision;
newDoc->_lastModified = thisDocument->_lastModified;
- newDoc->_includes = thisDocument->_includes;
+ newDoc->_resolvedIncludes = thisDocument->_resolvedIncludes;
+ newDoc->_unresolvedIncludes = thisDocument->_unresolvedIncludes;
}
FastPreprocessor pp(*this);
@@ -757,7 +763,8 @@ Document::Ptr Snapshot::documentFromSource(const QByteArray &preprocessedCode,
newDoc->_revision = thisDocument->_revision;
newDoc->_editorRevision = thisDocument->_editorRevision;
newDoc->_lastModified = thisDocument->_lastModified;
- newDoc->_includes = thisDocument->_includes;
+ newDoc->_resolvedIncludes = thisDocument->_resolvedIncludes;
+ newDoc->_unresolvedIncludes = thisDocument->_unresolvedIncludes;
newDoc->_definedMacros = thisDocument->_definedMacros;
newDoc->_macroUses = thisDocument->_macroUses;
}
diff --git a/src/libs/cplusplus/CppDocument.h b/src/libs/cplusplus/CppDocument.h
index 593d604c2b..071f9485e8 100644
--- a/src/libs/cplusplus/CppDocument.h
+++ b/src/libs/cplusplus/CppDocument.h
@@ -312,8 +312,11 @@ public:
QStringList includedFiles() const;
void addIncludeFile(const Include &include);
- QList<Include> includes() const
- { return _includes; }
+ QList<Include> resolvedIncludes() const
+ { return _resolvedIncludes; }
+
+ QList<Include> unresolvedIncludes() const
+ { return _unresolvedIncludes; }
QList<Block> skippedBlocks() const
{ return _skippedBlocks; }
@@ -348,7 +351,8 @@ private:
/// All messages generated during lexical/syntactic/semantic analysis.
QList<DiagnosticMessage> _diagnosticMessages;
- QList<Include> _includes;
+ QList<Include> _resolvedIncludes;
+ QList<Include> _unresolvedIncludes;
QList<Macro> _definedMacros;
QList<Block> _skippedBlocks;
QList<MacroUse> _macroUses;
@@ -394,7 +398,7 @@ public:
Snapshot simplified(Document::Ptr doc) const;
- Document::Ptr preprocessedDocument(const QString &source,
+ Document::Ptr preprocessedDocument(const QByteArray &source,
const QString &fileName) const;
Document::Ptr documentFromSource(const QByteArray &preprocessedDocument,
diff --git a/src/libs/cplusplus/CppRewriter.cpp b/src/libs/cplusplus/CppRewriter.cpp
index 4209644906..7a103b85c1 100644
--- a/src/libs/cplusplus/CppRewriter.cpp
+++ b/src/libs/cplusplus/CppRewriter.cpp
@@ -129,9 +129,9 @@ public:
virtual void visit(NamedType *type)
{
FullySpecifiedType ty = rewrite->env->apply(type->name(), rewrite);
- if (! ty->isUndefinedType())
+ if (! ty->isUndefinedType()) {
temps.append(ty);
- else {
+ } else {
const Name *name = rewrite->rewriteName(type->name());
temps.append(control()->namedType(name));
}
@@ -158,7 +158,7 @@ public:
// the copy() call above set the scope to 'type'
// reset it to 0 before adding addMember to avoid assert
- newArg->resetScope();
+ newArg->resetEnclosingScope();
funTy->addMember(newArg);
}
diff --git a/src/libs/cplusplus/DeprecatedGenTemplateInstance.cpp b/src/libs/cplusplus/DeprecatedGenTemplateInstance.cpp
index 0f482141ae..bbae274faf 100644
--- a/src/libs/cplusplus/DeprecatedGenTemplateInstance.cpp
+++ b/src/libs/cplusplus/DeprecatedGenTemplateInstance.cpp
@@ -129,7 +129,7 @@ private:
virtual void visit(Function *funTy)
{
Function *fun = control()->newFunction(/*sourceLocation=*/ 0, funTy->name());
- fun->setScope(funTy->enclosingScope());
+ fun->setEnclosingScope(funTy->enclosingScope());
fun->setConst(funTy->isConst());
fun->setVolatile(funTy->isVolatile());
fun->setVirtual(funTy->isVirtual());
@@ -264,7 +264,7 @@ private:
if (! name)
return name;
- else if (const Identifier *nameId = name->asNameId()) {
+ if (const Identifier *nameId = name->asNameId()) {
const Identifier *id = control()->identifier(nameId->chars(), nameId->size());
return id;
diff --git a/src/libs/cplusplus/ExpressionUnderCursor.cpp b/src/libs/cplusplus/ExpressionUnderCursor.cpp
index 370a4d110e..35e16ab0c1 100644
--- a/src/libs/cplusplus/ExpressionUnderCursor.cpp
+++ b/src/libs/cplusplus/ExpressionUnderCursor.cpp
@@ -176,6 +176,30 @@ int ExpressionUnderCursor::startOfExpression_helper(BackwardsScanner &tk, int in
else if (tk[lessIndex - 1].is(T_SLOT))
return startOfExpression(tk, lessIndex);
}
+ } else if (tk[matchingBraceIndex - 1].is(T_RBRACE)) {
+ // lambda: [](){} ()
+ int leftBraceIndex = tk.startOfMatchingBrace(matchingBraceIndex);
+ if (matchingBraceIndex != leftBraceIndex) {
+ int currentIndex = leftBraceIndex;
+ while (currentIndex >= 0) {
+ if (tk[currentIndex-1].is(T_RPAREN)) {
+ int leftParenIndex = tk.startOfMatchingBrace(currentIndex);
+ if (tk[leftParenIndex-1].is(T_THROW)) {
+ currentIndex = leftParenIndex-1;
+ } else if (tk[leftParenIndex-1].is(T_RBRACKET)) {
+ int leftBracketIndex = tk.startOfMatchingBrace(leftParenIndex);
+ if (leftBracketIndex != leftParenIndex-1)
+ return leftBracketIndex;
+ }
+ } else if (tk[currentIndex-1].is(T_RBRACKET)) {
+ int leftBracketIndex = tk.startOfMatchingBrace(currentIndex);
+ if (leftBracketIndex != currentIndex-1)
+ return leftBracketIndex;
+ } else {
+ --currentIndex;
+ }
+ }
+ }
}
return startOfExpression(tk, matchingBraceIndex);
}
@@ -239,19 +263,20 @@ int ExpressionUnderCursor::startOfFunctionCall(const QTextCursor &cursor) const
forever {
const Token &tk = scanner[index - 1];
- if (tk.is(T_EOF_SYMBOL))
+ if (tk.is(T_EOF_SYMBOL)) {
break;
- else if (tk.is(T_LPAREN))
+ } else if (tk.is(T_LPAREN)) {
return scanner.startPosition() + tk.begin();
- else if (tk.is(T_RPAREN)) {
+ } else if (tk.is(T_RPAREN)) {
int matchingBrace = scanner.startOfMatchingBrace(index);
if (matchingBrace == index) // If no matching brace found
return -1;
index = matchingBrace;
- } else
+ } else {
--index;
+ }
}
return -1;
diff --git a/src/libs/cplusplus/FastPreprocessor.cpp b/src/libs/cplusplus/FastPreprocessor.cpp
index 7156b51f3d..45f1d24d37 100644
--- a/src/libs/cplusplus/FastPreprocessor.cpp
+++ b/src/libs/cplusplus/FastPreprocessor.cpp
@@ -41,7 +41,19 @@ FastPreprocessor::FastPreprocessor(const Snapshot &snapshot)
, _preproc(this, &_env)
{ }
-QByteArray FastPreprocessor::run(Document::Ptr newDoc, const QString &source)
+// This is a temporary fix to handle non-ascii characters. This can be removed when the lexer can
+// handle multi-byte characters.
+static QByteArray convertToLatin1(const QByteArray &contents)
+{
+ const char *p = contents.constData();
+ while (char ch = *p++)
+ if (ch & 0x80)
+ return QString::fromUtf8(contents).toLatin1();
+
+ return contents;
+}
+
+QByteArray FastPreprocessor::run(Document::Ptr newDoc, const QByteArray &source)
{
std::swap(newDoc, _currentDoc);
const QString fileName = _currentDoc->fileName();
@@ -52,11 +64,13 @@ QByteArray FastPreprocessor::run(Document::Ptr newDoc, const QString &source)
_merged.insert(fileName);
mergeEnvironment(Preprocessor::configurationFileName);
- foreach (const Document::Include &i, doc->includes())
+ foreach (const Document::Include &i, doc->resolvedIncludes())
mergeEnvironment(i.resolvedFileName());
}
- const QByteArray preprocessed = _preproc.run(fileName, source);
+ QByteArray src = convertToLatin1(source);
+
+ const QByteArray preprocessed = _preproc.run(fileName, src);
// qDebug("FastPreprocessor::run for %s produced [[%s]]", fileName.toUtf8().constData(), preprocessed.constData());
std::swap(newDoc, _currentDoc);
return preprocessed;
@@ -78,7 +92,7 @@ void FastPreprocessor::mergeEnvironment(const QString &fileName)
_merged.insert(fileName);
if (Document::Ptr doc = _snapshot.document(fileName)) {
- foreach (const Document::Include &i, doc->includes())
+ foreach (const Document::Include &i, doc->resolvedIncludes())
mergeEnvironment(i.resolvedFileName());
_env.addMacros(doc->definedMacros());
diff --git a/src/libs/cplusplus/FastPreprocessor.h b/src/libs/cplusplus/FastPreprocessor.h
index 8e1a818597..ec585e28ca 100644
--- a/src/libs/cplusplus/FastPreprocessor.h
+++ b/src/libs/cplusplus/FastPreprocessor.h
@@ -54,7 +54,7 @@ class CPLUSPLUS_EXPORT FastPreprocessor: public Client
public:
FastPreprocessor(const Snapshot &snapshot);
- QByteArray run(Document::Ptr newDoc, const QString &source);
+ QByteArray run(Document::Ptr newDoc, const QByteArray &source);
// CPlusPlus::Client
virtual void sourceNeeded(unsigned line, const QString &fileName, IncludeType mode);
diff --git a/src/libs/cplusplus/FindUsages.cpp b/src/libs/cplusplus/FindUsages.cpp
index 7fe56b90e4..870c696028 100644
--- a/src/libs/cplusplus/FindUsages.cpp
+++ b/src/libs/cplusplus/FindUsages.cpp
@@ -207,7 +207,32 @@ bool FindUsages::checkCandidates(const QList<LookupItem> &candidates) const
}
if (isLocalScope(_declSymbol->enclosingScope()) || isLocalScope(s->enclosingScope())) {
- if (s->enclosingScope()->isTemplate()) {
+ if (_declSymbol->isClass() && _declSymbol->enclosingScope()->isTemplate()
+ && s->isClass() && s->enclosingScope()->isTemplate()) {
+ // for definition of functions of class defined outside the class definition
+ Scope *templEnclosingDeclSymbol = _declSymbol->enclosingScope();
+ Scope *scopeOfTemplEnclosingDeclSymbol
+ = templEnclosingDeclSymbol->enclosingScope();
+ Scope *templEnclosingCandidateSymbol = s->enclosingScope();
+ Scope *scopeOfTemplEnclosingCandidateSymbol
+ = templEnclosingCandidateSymbol->enclosingScope();
+
+ if (scopeOfTemplEnclosingCandidateSymbol != scopeOfTemplEnclosingDeclSymbol)
+ return false;
+ } else if (_declSymbol->isClass() && _declSymbol->enclosingScope()->isTemplate()
+ && s->enclosingScope()->isClass()
+ && s->enclosingScope()->enclosingScope()->isTemplate()) {
+ // for declaration inside template class
+ Scope *templEnclosingDeclSymbol = _declSymbol->enclosingScope();
+ Scope *scopeOfTemplEnclosingDeclSymbol
+ = templEnclosingDeclSymbol->enclosingScope();
+ Scope *templEnclosingCandidateSymbol = s->enclosingScope()->enclosingScope();
+ Scope *scopeOfTemplEnclosingCandidateSymbol
+ = templEnclosingCandidateSymbol->enclosingScope();
+
+ if (scopeOfTemplEnclosingCandidateSymbol != scopeOfTemplEnclosingDeclSymbol)
+ return false;
+ } else if (s->enclosingScope()->isTemplate() && ! _declSymbol->isTypenameArgument()) {
if (_declSymbol->enclosingScope()->isTemplate()) {
if (s->enclosingScope()->enclosingScope() != _declSymbol->enclosingScope()->enclosingScope())
return false;
@@ -218,7 +243,8 @@ bool FindUsages::checkCandidates(const QList<LookupItem> &candidates) const
} else if (_declSymbol->enclosingScope()->isTemplate() && s->isTemplate()) {
if (_declSymbol->enclosingScope()->enclosingScope() != s->enclosingScope())
return false;
- } else if (! s->isUsingDeclaration() && s->enclosingScope() != _declSymbol->enclosingScope()) {
+ } else if (! s->isUsingDeclaration()
+ && s->enclosingScope() != _declSymbol->enclosingScope()) {
return false;
}
}
diff --git a/src/libs/cplusplus/LookupContext.cpp b/src/libs/cplusplus/LookupContext.cpp
index 2947d6f8fa..2c34d5e7ad 100644
--- a/src/libs/cplusplus/LookupContext.cpp
+++ b/src/libs/cplusplus/LookupContext.cpp
@@ -57,7 +57,7 @@ static void addNames(const Name *name, QList<const Name *> *names, bool addAllNa
{
if (! name)
return;
- else if (const QualifiedNameId *q = name->asQualifiedNameId()) {
+ if (const QualifiedNameId *q = name->asQualifiedNameId()) {
addNames(q->base(), names);
addNames(q->name(), names, addAllNames);
} else if (addAllNames || name->isNameId() || name->isTemplateNameId() || name->isAnonymousNameId()) {
@@ -98,7 +98,7 @@ static inline bool compareName(const Name *name, const Name *other)
if (name == other)
return true;
- else if (name && other) {
+ if (name && other) {
const Identifier *id = name->identifier();
const Identifier *otherId = other->identifier();
@@ -246,17 +246,18 @@ QList<LookupItem> LookupContext::lookupByUsing(const Name *name, Scope *scope) c
{
QList<LookupItem> candidates;
// if it is a nameId there can be a using declaration for it
- if (name->isNameId()) {
+ if (name->isNameId() || name->isTemplateNameId()) {
for (unsigned i = 0, count = scope->memberCount(); i < count; ++i) {
if (UsingDeclaration *u = scope->memberAt(i)->asUsingDeclaration()) {
if (const Name *usingDeclarationName = u->name()) {
if (const QualifiedNameId *q = usingDeclarationName->asQualifiedNameId()) {
- if (q->name() && q->name()->isEqualTo(name)) {
+ if (q->name() && q->identifier() && name->identifier()
+ && q->name()->identifier()->isEqualTo(name->identifier())) {
candidates = bindings()->globalNamespace()->find(q);
// if it is not a global scope(scope of scope is not equal 0)
// then add current using declaration as a candidate
- if (scope->scope()) {
+ if (scope->enclosingScope()) {
LookupItem item;
item.setDeclaration(u);
item.setScope(scope);
@@ -267,6 +268,10 @@ QList<LookupItem> LookupContext::lookupByUsing(const Name *name, Scope *scope) c
}
}
}
+ } else if (const QualifiedNameId *q = name->asQualifiedNameId()) {
+ ClassOrNamespace *base = lookupType(q->base(), scope);
+ if (base && base->symbols().size() > 0 && base->symbols().first()->asScope())
+ return lookupByUsing(q->name(), base->symbols().first()->asScope());
}
return candidates;
}
@@ -347,9 +352,28 @@ ClassOrNamespace *LookupContext::lookupType(const Name *name, Scope *scope,
}
}
}
- return lookupType(name, scope->enclosingScope());
+ // try to find it in block (rare case but has priority before enclosing scope)
+ // e.g.: void foo() { struct S {}; S s; }
+ if (ClassOrNamespace *b = bindings()->lookupType(scope, enclosingTemplateInstantiation)) {
+ if (ClassOrNamespace *classOrNamespaceNestedInNestedBlock = b->lookupType(name, block))
+ return classOrNamespaceNestedInNestedBlock;
+ }
+
+ // try to find type in enclosing scope(typical case)
+ if (ClassOrNamespace *found = lookupType(name, scope->enclosingScope()))
+ return found;
+
} else if (ClassOrNamespace *b = bindings()->lookupType(scope, enclosingTemplateInstantiation)) {
return b->lookupType(name);
+ } else if (Class *scopeAsClass = scope->asClass()) {
+ if (scopeAsClass->enclosingScope()->isBlock()) {
+ if (ClassOrNamespace *b = lookupType(scopeAsClass->name(),
+ scopeAsClass->enclosingScope(),
+ enclosingTemplateInstantiation,
+ typedefsBeingResolved)) {
+ return b->lookupType(name);
+ }
+ }
}
return 0;
@@ -396,6 +420,15 @@ QList<LookupItem> LookupContext::lookup(const Name *name, Scope *scope) const
if (! candidates.isEmpty())
return candidates;
+ if (ClassOrNamespace *binding = bindings()->lookupType(scope)) {
+ if (ClassOrNamespace *block = binding->findBlock(scope->asBlock())) {
+ candidates = block->find(name);
+
+ if (! candidates.isEmpty())
+ return candidates;
+ }
+ }
+
} else if (Function *fun = scope->asFunction()) {
bindings()->lookupInScope(name, fun, &candidates, /*templateId = */ 0, /*binding=*/ 0);
@@ -454,6 +487,17 @@ QList<LookupItem> LookupContext::lookup(const Name *name, Scope *scope) const
if (! candidates.isEmpty())
return candidates;
+ // the scope can be defined inside a block, try to find it
+ if (Block *block = scope->enclosingBlock()) {
+ if (ClassOrNamespace *b = bindings()->lookupType(block)) {
+ if (ClassOrNamespace *classOrNamespaceNestedInNestedBlock = b->lookupType(scope->name(), block))
+ candidates = classOrNamespaceNestedInNestedBlock->find(name);
+ }
+ }
+
+ if (! candidates.isEmpty())
+ return candidates;
+
} else if (scope->isObjCClass() || scope->isObjCProtocol()) {
if (ClassOrNamespace *binding = bindings()->lookupType(scope))
candidates = binding->find(name);
@@ -560,10 +604,9 @@ QList<LookupItem> ClassOrNamespace::lookup_helper(const Name *name, bool searchI
if (name) {
if (const QualifiedNameId *q = name->asQualifiedNameId()) {
- if (! q->base()) // e.g. ::std::string
+ if (! q->base()) { // e.g. ::std::string
result = globalNamespace()->find(q->name());
-
- else if (ClassOrNamespace *binding = lookupType(q->base())) {
+ } else if (ClassOrNamespace *binding = lookupType(q->base())) {
result = binding->find(q->name());
QList<const Name *> fullName;
@@ -722,12 +765,54 @@ ClassOrNamespace *ClassOrNamespace::lookupType(const Name *name)
return lookupType_helper(name, &processed, /*searchInEnclosingScope =*/ true, this);
}
+ClassOrNamespace *ClassOrNamespace::lookupType(const Name *name, Block *block)
+{
+ flush();
+
+ QHash<Block *, ClassOrNamespace *>::const_iterator citBlock = _blocks.find(block);
+ if (citBlock != _blocks.end()) {
+ ClassOrNamespace *nestedBlock = citBlock.value();
+ QSet<ClassOrNamespace *> processed;
+ if (ClassOrNamespace *foundInNestedBlock
+ = nestedBlock->lookupType_helper(name,
+ &processed,
+ /*searchInEnclosingScope = */ true,
+ this)) {
+ return foundInNestedBlock;
+ }
+ }
+
+ for (citBlock = _blocks.begin(); citBlock != _blocks.end(); ++citBlock) {
+ if (ClassOrNamespace *foundNestedBlock = citBlock.value()->lookupType(name, block))
+ return foundNestedBlock;
+ }
+
+ return 0;
+}
+
ClassOrNamespace *ClassOrNamespace::findType(const Name *name)
{
QSet<ClassOrNamespace *> processed;
return lookupType_helper(name, &processed, /*searchInEnclosingScope =*/ false, this);
}
+ClassOrNamespace *ClassOrNamespace::findBlock(Block *block)
+{
+ flush();
+
+ QHash<Block *, ClassOrNamespace *>::const_iterator citBlock = _blocks.find(block);
+ if (citBlock != _blocks.end()) {
+ return citBlock.value();
+ }
+
+ for (citBlock = _blocks.begin(); citBlock != _blocks.end(); ++citBlock) {
+ if (ClassOrNamespace *foundNestedBlock = citBlock.value()->findBlock(block))
+ return foundNestedBlock;
+ }
+
+ return 0;
+}
+
Symbol *ClassOrNamespace::lookupInScope(const QList<const Name *> &fullName)
{
if (!_scopeLookupCache) {
@@ -783,7 +868,7 @@ ClassOrNamespace *ClassOrNamespace::lookupType_helper(const Name *name,
if (ClassOrNamespace *e = nestedType(name, origin))
return e;
- else if (_templateId) {
+ if (_templateId) {
if (_usings.size() == 1) {
ClassOrNamespace *delegate = _usings.first();
@@ -1006,7 +1091,7 @@ ClassOrNamespace *ClassOrNamespace::nestedType(const Name *name, ClassOrNamespac
foreach (Symbol *s, reference->symbols()) {
Symbol *clone = cloner.symbol(s, &subst);
- clone->setScope(s->scope());
+ clone->setEnclosingScope(s->enclosingScope());
instantiation->_symbols.append(clone);
#ifdef DEBUG_LOOKUP
Overview oo;oo.showFunctionSignatures = true;
@@ -1161,7 +1246,7 @@ void ClassOrNamespace::NestedClassInstantiator::instantiate(ClassOrNamespace *en
foreach (Symbol *s, nestedClassOrNamespace->_symbols) {
Symbol *clone = _cloner.symbol(s, &_subst);
if (!clone->enclosingScope()) // Not from the cache but just cloned.
- clone->setScope(s->enclosingScope());
+ clone->setEnclosingScope(s->enclosingScope());
nestedClassOrNamespaceInstantiation->_symbols.append(clone);
}
}
@@ -1184,8 +1269,7 @@ bool ClassOrNamespace::NestedClassInstantiator::isInstantiateNestedClassNeeded(c
if (Declaration *declaration = memberAsSymbol->asDeclaration()) {
if (containsTemplateType(declaration))
return true;
- }
- else if (Function *function = memberAsSymbol->asFunction()) {
+ } else if (Function *function = memberAsSymbol->asFunction()) {
if (containsTemplateType(function))
return true;
}
@@ -1366,11 +1450,11 @@ void CreateBindings::process(Document::Ptr doc)
if (! doc)
return;
- else if (Namespace *globalNamespace = doc->globalNamespace()) {
+ if (Namespace *globalNamespace = doc->globalNamespace()) {
if (! _processed.contains(globalNamespace)) {
_processed.insert(globalNamespace);
- foreach (const Document::Include &i, doc->includes()) {
+ foreach (const Document::Include &i, doc->resolvedIncludes()) {
if (Document::Ptr incl = _snapshot.document(i.resolvedFileName()))
process(incl);
}
@@ -1490,8 +1574,46 @@ bool CreateBindings::visit(Declaration *decl)
return false;
}
-bool CreateBindings::visit(Function *)
+bool CreateBindings::visit(Function *function)
{
+ for (unsigned i = 0, count = function->memberCount(); i < count; ++i) {
+ Symbol *s = function->memberAt(i);
+ if (Block *b = s->asBlock())
+ visit(b);
+ }
+ return false;
+}
+
+bool CreateBindings::visit(Block *block)
+{
+ ClassOrNamespace *previous = _currentClassOrNamespace;
+
+ ClassOrNamespace *binding = new ClassOrNamespace(this, previous);
+ binding->_control = control();
+
+ _currentClassOrNamespace = binding;
+ _currentClassOrNamespace->addSymbol(block);
+
+ for (unsigned i = 0; i < block->memberCount(); ++i)
+ // we cannot use lazy processing here, because we have to know
+ // does this block contain any other blocks or classOrNamespaces
+ process(block->memberAt(i), _currentClassOrNamespace);
+
+ // we add this block to parent ClassOrNamespace only if it contains
+ // any nested ClassOrNamespaces or other blocks(which have to contain
+ // nested ClassOrNamespaces)
+ if (! _currentClassOrNamespace->_blocks.empty()
+ || ! _currentClassOrNamespace->_classOrNamespaces.empty()
+ || ! _currentClassOrNamespace->_enums.empty()) {
+ previous->_blocks[block] = binding;
+ _entities.append(binding);
+ } else {
+ delete binding;
+ binding = 0;
+ }
+
+ _currentClassOrNamespace = previous;
+
return false;
}
diff --git a/src/libs/cplusplus/LookupContext.h b/src/libs/cplusplus/LookupContext.h
index 37b6f339b9..cc229cb730 100644
--- a/src/libs/cplusplus/LookupContext.h
+++ b/src/libs/cplusplus/LookupContext.h
@@ -81,7 +81,9 @@ public:
QList<LookupItem> find(const Name *name);
ClassOrNamespace *lookupType(const Name *name);
+ ClassOrNamespace *lookupType(const Name *name, Block *block);
ClassOrNamespace *findType(const Name *name);
+ ClassOrNamespace *findBlock(Block *block);
Symbol *lookupInScope(const QList<const Name *> &fullName);
@@ -126,6 +128,7 @@ private:
QList<Symbol *> _symbols;
QList<ClassOrNamespace *> _usings;
Table _classOrNamespaces;
+ QHash<Block *, ClassOrNamespace *> _blocks;
QList<Enum *> _enums;
QList<Symbol *> _todo;
QSharedPointer<Control> _control;
@@ -238,7 +241,9 @@ protected:
virtual bool visit(ForwardClassDeclaration *klass);
virtual bool visit(Enum *e);
virtual bool visit(Declaration *decl);
- virtual bool visit(Function *);
+ virtual bool visit(Function *function);
+ virtual bool visit(Block *block);
+
virtual bool visit(BaseClass *b);
virtual bool visit(UsingNamespaceDirective *u);
virtual bool visit(UsingDeclaration *u);
diff --git a/src/libs/cplusplus/MatchingText.cpp b/src/libs/cplusplus/MatchingText.cpp
index b6fb54011a..6dedaec364 100644
--- a/src/libs/cplusplus/MatchingText.cpp
+++ b/src/libs/cplusplus/MatchingText.cpp
@@ -244,7 +244,7 @@ QString MatchingText::insertParagraphSeparator(const QTextCursor &tc) const
if (current.is(T_EOF_SYMBOL))
break;
- else if (current.is(T_CLASS) || current.is(T_STRUCT) || current.is(T_UNION) || current.is(T_ENUM)) {
+ if (current.is(T_CLASS) || current.is(T_STRUCT) || current.is(T_UNION) || current.is(T_ENUM)) {
// found a class key.
QString str = QLatin1String("};");
diff --git a/src/libs/cplusplus/PPToken.cpp b/src/libs/cplusplus/PPToken.cpp
index e635d5ffe0..b3e41103bb 100644
--- a/src/libs/cplusplus/PPToken.cpp
+++ b/src/libs/cplusplus/PPToken.cpp
@@ -35,7 +35,7 @@ using namespace CPlusPlus;
bool ByteArrayRef::startsWith(const char *s) const
{
- int l = std::strlen(s);
+ const int l = int(std::strlen(s));
if (l > m_length)
return false;
return !qstrncmp(start(), s, l);
diff --git a/src/libs/cplusplus/PreprocessorClient.cpp b/src/libs/cplusplus/PreprocessorClient.cpp
index 2e2e069e0d..5028cffd81 100644
--- a/src/libs/cplusplus/PreprocessorClient.cpp
+++ b/src/libs/cplusplus/PreprocessorClient.cpp
@@ -44,7 +44,7 @@ using namespace CPlusPlus;
*/
/*!
- \fn void Client::passedMacroDefinitionCheck(unsigned offset, const Macro &macro)
+ \fn void Client::passedMacroDefinitionCheck(unsigned offset, unsigned line, const Macro &macro)
Called when the preprocessor checks whether a macro is defined or not and the
result is positive.
@@ -53,7 +53,7 @@ using namespace CPlusPlus;
*/
/*!
- \fn void Client::failedMacroDefinitionCheck(unsigned offset, const QByteArray &name)
+ \fn void Client::failedMacroDefinitionCheck(unsigned offset, const ByteArrayRef &name)
Called when the preprocessor checks whether a macro is defined or not and the
result is negative.
@@ -62,10 +62,12 @@ using namespace CPlusPlus;
*/
/*!
- \fn void Client::startExpandingMacro(unsigned offset, const Macro &macro, const QByteArray &originalText, bool inCondition = false, const QVector<MacroArgumentReference> &actuals = QVector<MacroArgumentReference>())
-
- Called when starting to expand a macro. The parameter \a inCondition indicates whether the
- expansion is happening inside a preprocessor conditional.
+ \fn void Client::startExpandingMacro(unsigned offset,
+ unsigned line,
+ const Macro &macro,
+ const QVector<MacroArgumentReference> &actuals
+ = QVector<MacroArgumentReference>())
+ Called when starting to expand a macro.
\sa stopExpandingMacro()
*/
diff --git a/src/libs/cplusplus/PreprocessorEnvironment.cpp b/src/libs/cplusplus/PreprocessorEnvironment.cpp
index be736b8569..23327dfefa 100644
--- a/src/libs/cplusplus/PreprocessorEnvironment.cpp
+++ b/src/libs/cplusplus/PreprocessorEnvironment.cpp
@@ -170,8 +170,7 @@ bool Environment::isBuiltinMacro(const ByteArrayRef &s)
}
}
}
- }
- else if (s[2] == 'F') {
+ } else if (s[2] == 'F') {
if (s[3] == 'I') {
if (s[4] == 'L') {
if (s[5] == 'E') {
@@ -183,8 +182,7 @@ bool Environment::isBuiltinMacro(const ByteArrayRef &s)
}
}
}
- }
- else if (s[2] == 'L') {
+ } else if (s[2] == 'L') {
if (s[3] == 'I') {
if (s[4] == 'N') {
if (s[5] == 'E') {
@@ -196,8 +194,7 @@ bool Environment::isBuiltinMacro(const ByteArrayRef &s)
}
}
}
- }
- else if (s[2] == 'T') {
+ } else if (s[2] == 'T') {
if (s[3] == 'I') {
if (s[4] == 'M') {
if (s[5] == 'E') {
diff --git a/src/libs/cplusplus/ResolveExpression.cpp b/src/libs/cplusplus/ResolveExpression.cpp
index 08213d43a4..90b9624860 100644
--- a/src/libs/cplusplus/ResolveExpression.cpp
+++ b/src/libs/cplusplus/ResolveExpression.cpp
@@ -142,11 +142,13 @@ void ResolveExpression::addResults(const QList<LookupItem> &items)
_results += items;
}
-void ResolveExpression::addResult(const FullySpecifiedType &ty, Scope *scope)
+void ResolveExpression::addResult(const FullySpecifiedType &ty, Scope *scope,
+ ClassOrNamespace *binding)
{
LookupItem item;
item.setType(ty);
item.setScope(scope);
+ item.setBinding(binding);
_results.append(item);
}
@@ -366,15 +368,43 @@ bool ResolveExpression::visit(CompoundExpressionAST *ast)
return false;
}
+bool ResolveExpression::visit(LambdaExpressionAST *ast)
+{
+ accept(ast->statement);
+ return false;
+}
+
+bool ResolveExpression::visit(ReturnStatementAST *ast)
+{
+ accept(ast->expression);
+ return false;
+}
+
bool ResolveExpression::visit(NestedExpressionAST *ast)
{
accept(ast->expression);
return false;
}
-bool ResolveExpression::visit(StringLiteralAST *)
+bool ResolveExpression::visit(StringLiteralAST *ast)
{
- FullySpecifiedType charTy = control()->integerType(IntegerType::Char);
+ const Token &tk = tokenAt(ast->literal_token);
+ int intId;
+ switch (tk.kind()) {
+ case T_WIDE_STRING_LITERAL:
+ intId = IntegerType::WideChar;
+ break;
+ case T_UTF16_STRING_LITERAL:
+ intId = IntegerType::Char16;
+ break;
+ case T_UTF32_STRING_LITERAL:
+ intId = IntegerType::Char32;
+ break;
+ default:
+ intId = IntegerType::Char;
+ break;
+ }
+ FullySpecifiedType charTy = control()->integerType(intId);
charTy.setConst(true);
FullySpecifiedType ty(control()->pointerType(charTy));
addResult(ty, _scope);
@@ -564,16 +594,14 @@ bool ResolveExpression::visit(SimpleNameAST *ast)
if (n == 0) {
item.setType(newType);
item.setScope(typeItems[n].scope());
- }
- else {
+ } else {
LookupItem newItem(item);
newItem.setType(newType);
newItem.setScope(typeItems[n].scope());
newCandidates.push_back(newItem);
}
}
- }
- else {
+ } else {
item.setType(item.declaration()->type());
item.setScope(item.declaration()->enclosingScope());
}
@@ -626,6 +654,11 @@ bool ResolveExpression::visit(CallAST *ast)
{
const QList<LookupItem> baseResults = resolve(ast->base_expression, _scope);
+ if (ast->base_expression->asLambdaExpression()) {
+ _results = baseResults;
+ return false;
+ }
+
// Compute the types of the actual arguments.
unsigned actualArgumentCount = 0;
@@ -698,7 +731,7 @@ bool ResolveExpression::visit(CallAST *ast)
} else if (Function *funTy = ty->asFunctionType()) {
if (maybeValidPrototype(funTy, actualArgumentCount))
- addResult(funTy->returnType().simplified(), scope);
+ addResult(funTy->returnType().simplified(), scope, result.binding());
} else if (Class *classTy = ty->asClassType()) {
// Constructor call
@@ -1001,53 +1034,77 @@ ClassOrNamespace *ResolveExpression::baseExpression(const QList<LookupItem> &bas
FullySpecifiedType type = ptrTy->elementType();
if (! ty->isPointerType())
type = ty;
+
+ if (ClassOrNamespace *binding
+ = findClassForTemplateParameterInExpressionScope(r.binding(),
+ type)) {
+ return binding;
+ }
if (ClassOrNamespace *binding = findClass(type, scope))
return binding;
} else if (PointerType *ptrTy = ty->asPointerType()) {
FullySpecifiedType type = ptrTy->elementType();
+ if (ClassOrNamespace *binding
+ = findClassForTemplateParameterInExpressionScope(r.binding(),
+ type)) {
+ return binding;
+ }
if (ClassOrNamespace *binding = findClass(type, scope))
return binding;
- } else if (ClassOrNamespace *binding = findClass(ty, scope)) {
- // lookup for overloads of operator->
+ } else {
+ ClassOrNamespace *binding
+ = findClassForTemplateParameterInExpressionScope(r.binding(),
+ ty);
+ if (! binding)
+ binding = findClass(ty, scope);
- const OperatorNameId *arrowOp = control()->operatorNameId(OperatorNameId::ArrowOp);
- foreach (const LookupItem &r, binding->find(arrowOp)) {
- Symbol *overload = r.declaration();
- if (! overload)
- continue;
- Scope *functionScope = overload->enclosingScope();
+ if (binding){
+ // lookup for overloads of operator->
- if (overload->type()->isFunctionType()) {
- FullySpecifiedType overloadTy = instantiate(binding->templateId(), overload);
- Function *instantiatedFunction = overloadTy->asFunctionType();
- Q_ASSERT(instantiatedFunction != 0);
+ const OperatorNameId *arrowOp
+ = control()->operatorNameId(OperatorNameId::ArrowOp);
+ foreach (const LookupItem &r, binding->find(arrowOp)) {
+ Symbol *overload = r.declaration();
+ if (! overload)
+ continue;
+ Scope *functionScope = overload->enclosingScope();
- FullySpecifiedType retTy = instantiatedFunction->returnType().simplified();
+ if (overload->type()->isFunctionType()) {
+ FullySpecifiedType overloadTy
+ = instantiate(binding->templateId(), overload);
+ Function *instantiatedFunction = overloadTy->asFunctionType();
+ Q_ASSERT(instantiatedFunction != 0);
- typedefsResolver.resolve(&retTy, &functionScope, r.binding());
+ FullySpecifiedType retTy
+ = instantiatedFunction->returnType().simplified();
- if (! retTy->isPointerType() && ! retTy->isNamedType())
- continue;
+ typedefsResolver.resolve(&retTy, &functionScope, r.binding());
- if (PointerType *ptrTy = retTy->asPointerType())
- retTy = ptrTy->elementType();
+ if (! retTy->isPointerType() && ! retTy->isNamedType())
+ continue;
- if (ClassOrNamespace *retBinding = findClass(retTy, functionScope))
- return retBinding;
+ if (PointerType *ptrTy = retTy->asPointerType())
+ retTy = ptrTy->elementType();
- if (scope != functionScope) {
- if (ClassOrNamespace *retBinding = findClass(retTy, scope))
+ if (ClassOrNamespace *retBinding = findClass(retTy, functionScope))
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;
+ 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(retTy, originScope))
+ return retBinding;
+ }
}
}
}
@@ -1065,6 +1122,12 @@ ClassOrNamespace *ResolveExpression::baseExpression(const QList<LookupItem> &bas
}
}
+ if (ClassOrNamespace *binding
+ = findClassForTemplateParameterInExpressionScope(r.binding(),
+ ty)) {
+ return binding;
+ }
+
ClassOrNamespace *enclosingTemplateInstantiation = 0;
if (ClassOrNamespace *binding = r.binding()) {
if (binding->instantiationOrigin())
@@ -1079,6 +1142,24 @@ ClassOrNamespace *ResolveExpression::baseExpression(const QList<LookupItem> &bas
return 0;
}
+ClassOrNamespace *ResolveExpression::findClassForTemplateParameterInExpressionScope(
+ ClassOrNamespace *resultBinding,
+ const FullySpecifiedType &ty) const
+{
+ if (resultBinding && resultBinding->instantiationOrigin()) {
+ if (ClassOrNamespace *origin = resultBinding->instantiationOrigin()) {
+ foreach (Symbol *originSymbol, origin->symbols()) {
+ if (Scope *originScope = originSymbol->asScope()) {
+ if (ClassOrNamespace *retBinding = findClass(ty, originScope))
+ return retBinding;
+ }
+ }
+ }
+ }
+
+ return 0;
+}
+
FullySpecifiedType ResolveExpression::instantiate(const Name *className, Symbol *candidate) const
{
return DeprecatedGenTemplateInstance::instantiate(className, candidate,
diff --git a/src/libs/cplusplus/ResolveExpression.h b/src/libs/cplusplus/ResolveExpression.h
index 68720fae0f..79f843107c 100644
--- a/src/libs/cplusplus/ResolveExpression.h
+++ b/src/libs/cplusplus/ResolveExpression.h
@@ -71,7 +71,7 @@ protected:
void thisObject();
- void addResult(const FullySpecifiedType &ty, Scope *scope);
+ void addResult(const FullySpecifiedType &ty, Scope *scope, ClassOrNamespace *binding = 0);
void addResults(const QList<Symbol *> &symbols);
void addResults(const QList<LookupItem> &items);
@@ -104,6 +104,8 @@ protected:
virtual bool visit(UnaryExpressionAST *ast);
virtual bool visit(CompoundLiteralAST *ast);
virtual bool visit(CompoundExpressionAST *ast);
+ virtual bool visit(LambdaExpressionAST *ast);
+ virtual bool visit(ReturnStatementAST *ast);
//names
virtual bool visit(QualifiedNameAST *ast);
@@ -124,6 +126,10 @@ protected:
private:
+ ClassOrNamespace *findClassForTemplateParameterInExpressionScope(
+ ClassOrNamespace *resultBinding,
+ const FullySpecifiedType &ty) const;
+
Scope *_scope;
const LookupContext& _context;
Bind bind;
diff --git a/src/libs/cplusplus/SnapshotSymbolVisitor.cpp b/src/libs/cplusplus/SnapshotSymbolVisitor.cpp
index 9599607973..1406d778be 100644
--- a/src/libs/cplusplus/SnapshotSymbolVisitor.cpp
+++ b/src/libs/cplusplus/SnapshotSymbolVisitor.cpp
@@ -49,7 +49,7 @@ void SnapshotSymbolVisitor::accept(Document::Ptr doc, QSet<QString> *processed)
if (doc && doc->globalNamespace() && ! processed->contains(doc->fileName())) {
processed->insert(doc->fileName());
- foreach (const Document::Include &i, doc->includes()) {
+ foreach (const Document::Include &i, doc->resolvedIncludes()) {
if (Document::Ptr incl = _snapshot.document(i.resolvedFileName()))
accept(incl, processed);
}
diff --git a/src/libs/cplusplus/TypeOfExpression.cpp b/src/libs/cplusplus/TypeOfExpression.cpp
index 0808bf1a2a..01e9c8f7df 100644
--- a/src/libs/cplusplus/TypeOfExpression.cpp
+++ b/src/libs/cplusplus/TypeOfExpression.cpp
@@ -177,7 +177,7 @@ void TypeOfExpression::processEnvironment(Document::Ptr doc, Environment *env,
if (doc && ! processed->contains(doc->fileName())) {
processed->insert(doc->fileName());
- foreach (const Document::Include &incl, doc->includes())
+ foreach (const Document::Include &incl, doc->resolvedIncludes())
processEnvironment(m_snapshot.document(incl.resolvedFileName()), env, processed);
foreach (const Macro &macro, doc->definedMacros())
diff --git a/src/libs/cplusplus/cplusplus.qbs b/src/libs/cplusplus/cplusplus.qbs
index b683783900..9df7f89707 100644
--- a/src/libs/cplusplus/cplusplus.qbs
+++ b/src/libs/cplusplus/cplusplus.qbs
@@ -85,88 +85,68 @@ QtcLibrary {
]
}
- files: [
- "AlreadyConsideredClassContainer.h",
- "ASTParent.cpp",
- "ASTParent.h",
- "ASTPath.cpp",
- "ASTPath.h",
- "BackwardsScanner.cpp",
- "BackwardsScanner.h",
- "CppDocument.cpp",
- "CppDocument.h",
- "CppRewriter.cpp",
- "CppRewriter.h",
- "DependencyTable.cpp",
- "DependencyTable.h",
- "DeprecatedGenTemplateInstance.cpp",
- "DeprecatedGenTemplateInstance.h",
- "ExpressionUnderCursor.cpp",
- "ExpressionUnderCursor.h",
- "FastPreprocessor.cpp",
- "FastPreprocessor.h",
- "FindUsages.cpp",
- "FindUsages.h",
- "Icons.cpp",
- "Icons.h",
- "LookupContext.cpp",
- "LookupContext.h",
- "LookupItem.cpp",
- "LookupItem.h",
- "Macro.cpp",
- "Macro.h",
- "MatchingText.cpp",
- "MatchingText.h",
- "NamePrettyPrinter.cpp",
- "NamePrettyPrinter.h",
- "Overview.cpp",
- "Overview.h",
- "OverviewModel.cpp",
- "OverviewModel.h",
- "PPToken.cpp",
- "PPToken.h",
- "PreprocessorClient.cpp",
- "PreprocessorClient.h",
- "PreprocessorEnvironment.cpp",
- "PreprocessorEnvironment.h",
- "ResolveExpression.cpp",
- "ResolveExpression.h",
- "SimpleLexer.cpp",
- "SimpleLexer.h",
- "SnapshotSymbolVisitor.cpp",
- "SnapshotSymbolVisitor.h",
- "SymbolNameVisitor.cpp",
- "SymbolNameVisitor.h",
- "TypeOfExpression.cpp",
- "TypeOfExpression.h",
- "TypePrettyPrinter.cpp",
- "TypePrettyPrinter.h",
- "cplusplus.qrc",
- "findcdbbreakpoint.cpp",
- "findcdbbreakpoint.h",
- "pp-cctype.h",
- "pp-engine.cpp",
- "pp-engine.h",
- "pp-scanner.cpp",
- "pp-scanner.h",
- "pp.h",
- "images/class.png",
- "images/enum.png",
- "images/enumerator.png",
- "images/func.png",
- "images/func_priv.png",
- "images/func_prot.png",
- "images/keyword.png",
- "images/macro.png",
- "images/namespace.png",
- "images/signal.png",
- "images/slot.png",
- "images/slot_priv.png",
- "images/slot_prot.png",
- "images/var.png",
- "images/var_priv.png",
- "images/var_prot.png",
- ]
+ Group {
+ name: "General"
+ files: [
+ "AlreadyConsideredClassContainer.h",
+ "ASTParent.cpp", "ASTParent.h",
+ "ASTPath.cpp", "ASTPath.h",
+ "BackwardsScanner.cpp", "BackwardsScanner.h",
+ "CppDocument.cpp", "CppDocument.h",
+ "CppRewriter.cpp", "CppRewriter.h",
+ "DependencyTable.cpp", "DependencyTable.h",
+ "DeprecatedGenTemplateInstance.cpp", "DeprecatedGenTemplateInstance.h",
+ "ExpressionUnderCursor.cpp", "ExpressionUnderCursor.h",
+ "FastPreprocessor.cpp", "FastPreprocessor.h",
+ "FindUsages.cpp", "FindUsages.h",
+ "Icons.cpp", "Icons.h",
+ "LookupContext.cpp", "LookupContext.h",
+ "LookupItem.cpp", "LookupItem.h",
+ "Macro.cpp", "Macro.h",
+ "MatchingText.cpp", "MatchingText.h",
+ "NamePrettyPrinter.cpp", "NamePrettyPrinter.h",
+ "Overview.cpp", "Overview.h",
+ "OverviewModel.cpp", "OverviewModel.h",
+ "PPToken.cpp", "PPToken.h",
+ "PreprocessorClient.cpp", "PreprocessorClient.h",
+ "PreprocessorEnvironment.cpp", "PreprocessorEnvironment.h",
+ "ResolveExpression.cpp", "ResolveExpression.h",
+ "SimpleLexer.cpp", "SimpleLexer.h",
+ "SnapshotSymbolVisitor.cpp", "SnapshotSymbolVisitor.h",
+ "SymbolNameVisitor.cpp", "SymbolNameVisitor.h",
+ "TypeOfExpression.cpp", "TypeOfExpression.h",
+ "TypePrettyPrinter.cpp", "TypePrettyPrinter.h",
+ "cplusplus.qrc",
+ "findcdbbreakpoint.cpp", "findcdbbreakpoint.h",
+ "pp-cctype.h",
+ "pp-engine.cpp", "pp-engine.h",
+ "pp-scanner.cpp", "pp-scanner.h",
+ "pp.h",
+ ]
+ }
+
+ Group {
+ name: "Images"
+ prefix: "images/"
+ files: [
+ "class.png",
+ "enum.png",
+ "enumerator.png",
+ "func.png",
+ "func_priv.png",
+ "func_prot.png",
+ "keyword.png",
+ "macro.png",
+ "namespace.png",
+ "signal.png",
+ "slot.png",
+ "slot_priv.png",
+ "slot_prot.png",
+ "var.png",
+ "var_priv.png",
+ "var_prot.png",
+ ]
+ }
Export {
cpp.includePaths: [
diff --git a/src/libs/cplusplus/pp-engine.cpp b/src/libs/cplusplus/pp-engine.cpp
index 659b888327..15beba1771 100644
--- a/src/libs/cplusplus/pp-engine.cpp
+++ b/src/libs/cplusplus/pp-engine.cpp
@@ -1064,7 +1064,7 @@ bool Preprocessor::handleIdentifier(PPToken *tk)
// This is not the most beautiful approach but it's quite reasonable. What we do here
// is to create a fake identifier token which is only composed by whitespaces. It's
// also not marked as expanded so it it can be treated as a regular token.
- QByteArray content(idTk.f.length + computeDistance(idTk), ' ');
+ const QByteArray content(int(idTk.f.length + computeDistance(idTk)), ' ');
PPToken fakeIdentifier = generateToken(T_IDENTIFIER,
content.constData(), content.length(),
idTk.lineno, false, false);
@@ -1131,7 +1131,7 @@ bool Preprocessor::handleFunctionLikeMacro(const Macro *macro,
for (size_t i = 0; i < bodySize && expanded.size() < MAX_TOKEN_EXPANSION_COUNT;
++i) {
int expandedSize = expanded.size();
- PPToken bodyTk = body.at(i);
+ PPToken bodyTk = body.at(int(i));
if (bodyTk.is(T_IDENTIFIER)) {
const ByteArrayRef id = bodyTk.asByteArrayRef();
@@ -1152,7 +1152,7 @@ bool Preprocessor::handleFunctionLikeMacro(const Macro *macro,
const int actualsSize = actualsForThisParam.size();
- if (i > 0 && body[i - 1].is(T_POUND)) {
+ if (i > 0 && body[int(i) - 1].is(T_POUND)) {
QByteArray enclosedString;
enclosedString.reserve(256);
@@ -1205,7 +1205,7 @@ bool Preprocessor::handleFunctionLikeMacro(const Macro *macro,
expanded.push_back(bodyTk);
}
- if (i > 1 && body[i - 1].is(T_POUND_POUND)) {
+ if (i > 1 && body[int(i) - 1].is(T_POUND_POUND)) {
if (expandedSize < 1 || expanded.size() == expandedSize) //### TODO: [cpp.concat] placemarkers
continue;
const PPToken &leftTk = expanded[expandedSize - 1];
@@ -1414,7 +1414,7 @@ void Preprocessor::preprocess(const QString &fileName, const QByteArray &source,
unsigned trackedColumn = 0;
if (tk.expanded() && !tk.generated()) {
trackedLine = tk.lineno;
- trackedColumn = computeDistance(tk, true);
+ trackedColumn = unsigned(computeDistance(tk, true));
}
m_state.m_expandedTokensInfo.append(qMakePair(trackedLine, trackedColumn));
} else if (m_state.m_expansionStatus == JustFinishedExpansion) {
@@ -1862,12 +1862,11 @@ void Preprocessor::handleElseDirective(PPToken *tk, const PPToken &poundToken)
else if (m_client && !wasSkipping && startSkipping)
startSkippingBlocks(poundToken);
}
- }
#ifndef NO_DEBUG
- else {
+ } else {
std::cerr << "*** WARNING #else without #if" << std::endl;
- }
#endif // NO_DEBUG
+ }
}
void Preprocessor::handleEndIfDirective(PPToken *tk, const PPToken &poundToken)
@@ -1930,12 +1929,11 @@ void Preprocessor::handleIfDefDirective(bool checkUndefined, PPToken *tk)
startSkippingBlocks(*tk);
lex(tk); // consume the identifier
- }
#ifndef NO_DEBUG
- else {
+ } else {
std::cerr << "*** WARNING #ifdef without identifier" << std::endl;
- }
#endif // NO_DEBUG
+ }
}
void Preprocessor::handleUndefDirective(PPToken *tk)
@@ -1948,12 +1946,11 @@ void Preprocessor::handleUndefDirective(PPToken *tk)
if (m_client && macro)
m_client->macroAdded(*macro);
lex(tk); // consume macro name
- }
#ifndef NO_DEBUG
- else {
+ } else {
std::cerr << "*** WARNING #undef without identifier" << std::endl;
- }
#endif // NO_DEBUG
+ }
}
PPToken Preprocessor::generateToken(enum Kind kind,
@@ -1988,7 +1985,7 @@ PPToken Preprocessor::generateToken(enum Kind kind,
else if (kind == T_NUMERIC_LITERAL)
tk.number = m_state.m_lexer->control()->numericLiteral(m_scratchBuffer.constData() + pos, length);
}
- tk.offset = pos;
+ tk.offset = unsigned(pos);
tk.f.length = length;
tk.f.generated = true;
tk.f.expanded = true;
diff --git a/src/libs/cplusplus/pp-scanner.cpp b/src/libs/cplusplus/pp-scanner.cpp
index 9f3320e4d3..2b23a3e228 100644
--- a/src/libs/cplusplus/pp-scanner.cpp
+++ b/src/libs/cplusplus/pp-scanner.cpp
@@ -259,13 +259,13 @@ const char *pp_skip_argument::operator () (const char *__first, const char *__la
lines = 0;
while (__first != __last) {
- if (!depth && (*__first == ')' || *__first == ','))
+ if (!depth && (*__first == ')' || *__first == ',')) {
break;
- else if (*__first == '(')
+ } else if (*__first == '(') {
++depth, ++__first;
- else if (*__first == ')')
+ } else if (*__first == ')') {
--depth, ++__first;
- else if (*__first == '\"') {
+ } else if (*__first == '\"') {
__first = skip_string_literal (__first, __last);
lines += skip_string_literal.lines;
} else if (*__first == '\'') {
@@ -283,8 +283,9 @@ const char *pp_skip_argument::operator () (const char *__first, const char *__la
} else if (*__first == '\n') {
++__first;
++lines;
- } else
+ } else {
++__first;
+ }
}
return __first;
diff --git a/src/libs/extensionsystem/extensionsystem.qbs b/src/libs/extensionsystem/extensionsystem.qbs
index 250a3c69dd..1762f978f2 100644
--- a/src/libs/extensionsystem/extensionsystem.qbs
+++ b/src/libs/extensionsystem/extensionsystem.qbs
@@ -46,4 +46,8 @@ QtcLibrary {
"images/notloaded.png",
"images/ok.png",
]
+
+ Export {
+ Depends { name: "Qt.core" }
+ }
}
diff --git a/src/libs/extensionsystem/optionsparser.cpp b/src/libs/extensionsystem/optionsparser.cpp
index eb17529f0a..00abdc5704 100644
--- a/src/libs/extensionsystem/optionsparser.cpp
+++ b/src/libs/extensionsystem/optionsparser.cpp
@@ -34,7 +34,7 @@
using namespace ExtensionSystem;
using namespace ExtensionSystem::Internal;
-static const char END_OF_OPTIONS[] = "--";
+const char END_OF_OPTIONS[] = "--";
const char *OptionsParser::NO_LOAD_OPTION = "-noload";
const char *OptionsParser::LOAD_OPTION = "-load";
const char *OptionsParser::TEST_OPTION = "-test";
diff --git a/src/libs/extensionsystem/plugindetailsview.cpp b/src/libs/extensionsystem/plugindetailsview.cpp
index a7464cce17..949c8d16c8 100644
--- a/src/libs/extensionsystem/plugindetailsview.cpp
+++ b/src/libs/extensionsystem/plugindetailsview.cpp
@@ -32,6 +32,7 @@
#include "pluginspec.h"
#include <QDir>
+#include <QRegExp>
/*!
\class ExtensionSystem::PluginDetailsView
@@ -84,6 +85,8 @@ void PluginDetailsView::update(PluginSpec *spec)
m_ui->description->setText(spec->description());
m_ui->copyright->setText(spec->copyright());
m_ui->license->setText(spec->license());
+ const QRegExp platforms = spec->platformSpecification();
+ m_ui->platforms->setText(platforms.isEmpty() ? tr("All") : platforms.pattern());
QStringList depStrings;
foreach (const PluginDependency &dep, spec->dependencies()) {
QString depString = dep.name;
diff --git a/src/libs/extensionsystem/plugindetailsview.ui b/src/libs/extensionsystem/plugindetailsview.ui
index e806618b63..696d8f8689 100644
--- a/src/libs/extensionsystem/plugindetailsview.ui
+++ b/src/libs/extensionsystem/plugindetailsview.ui
@@ -11,9 +11,58 @@
</rect>
</property>
<layout class="QGridLayout">
- <property name="margin">
+ <property name="leftMargin">
<number>2</number>
</property>
+ <property name="topMargin">
+ <number>2</number>
+ </property>
+ <property name="rightMargin">
+ <number>2</number>
+ </property>
+ <property name="bottomMargin">
+ <number>2</number>
+ </property>
+ <item row="7" column="1">
+ <widget class="QLabel" name="platforms"/>
+ </item>
+ <item row="8" column="0">
+ <layout class="QVBoxLayout">
+ <item>
+ <widget class="QLabel" name="label_8">
+ <property name="text">
+ <string>Description:</string>
+ </property>
+ <property name="alignment">
+ <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
+ </property>
+ <property name="textInteractionFlags">
+ <set>Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse</set>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <spacer>
+ <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>
+ <item row="1" column="1">
+ <widget class="QLabel" name="version">
+ <property name="textInteractionFlags">
+ <set>Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse</set>
+ </property>
+ </widget>
+ </item>
<item row="0" column="0">
<widget class="QLabel" name="label">
<property name="text">
@@ -27,6 +76,59 @@
</property>
</widget>
</item>
+ <item row="2" column="0">
+ <widget class="QLabel" name="label_3">
+ <property name="text">
+ <string>Compatibility version:</string>
+ </property>
+ <property name="alignment">
+ <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
+ </property>
+ <property name="textInteractionFlags">
+ <set>Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse</set>
+ </property>
+ </widget>
+ </item>
+ <item row="10" column="1">
+ <widget class="QTextEdit" name="license">
+ <property name="tabChangesFocus">
+ <bool>true</bool>
+ </property>
+ <property name="readOnly">
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ <item row="11" column="0">
+ <layout class="QVBoxLayout">
+ <item>
+ <widget class="QLabel" name="label_10">
+ <property name="text">
+ <string>Dependencies:</string>
+ </property>
+ <property name="alignment">
+ <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
+ </property>
+ <property name="textInteractionFlags">
+ <set>Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse</set>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <spacer>
+ <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>
<item row="0" column="1">
<widget class="QLabel" name="name">
<property name="textInteractionFlags">
@@ -47,17 +149,26 @@
</property>
</widget>
</item>
- <item row="1" column="1">
- <widget class="QLabel" name="version">
+ <item row="3" column="0">
+ <widget class="QLabel" name="label_4">
+ <property name="text">
+ <string>Vendor:</string>
+ </property>
+ <property name="alignment">
+ <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
+ </property>
<property name="textInteractionFlags">
<set>Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse</set>
</property>
</widget>
</item>
- <item row="2" column="0">
- <widget class="QLabel" name="label_3">
+ <item row="11" column="1">
+ <widget class="QListWidget" name="dependencies"/>
+ </item>
+ <item row="6" column="0">
+ <widget class="QLabel" name="label_7">
<property name="text">
- <string>Compatibility version:</string>
+ <string>Location:</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
@@ -67,31 +178,24 @@
</property>
</widget>
</item>
- <item row="2" column="1">
- <widget class="QLabel" name="compatVersion">
+ <item row="6" column="1">
+ <widget class="QLabel" name="location">
+ <property name="wordWrap">
+ <bool>false</bool>
+ </property>
<property name="textInteractionFlags">
- <set>Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse</set>
+ <set>Qt::TextBrowserInteraction</set>
</property>
</widget>
</item>
- <item row="3" column="0">
- <widget class="QLabel" name="label_4">
+ <item row="7" column="0">
+ <widget class="QLabel" name="platformsDescriptionLabel">
<property name="text">
- <string>Vendor:</string>
+ <string>Platforms:</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
- <property name="textInteractionFlags">
- <set>Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse</set>
- </property>
- </widget>
- </item>
- <item row="3" column="1">
- <widget class="QLabel" name="vendor">
- <property name="textInteractionFlags">
- <set>Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse</set>
- </property>
</widget>
</item>
<item row="5" column="0">
@@ -117,10 +221,17 @@
</property>
</widget>
</item>
- <item row="6" column="0">
- <widget class="QLabel" name="label_7">
+ <item row="3" column="1">
+ <widget class="QLabel" name="vendor">
+ <property name="textInteractionFlags">
+ <set>Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse</set>
+ </property>
+ </widget>
+ </item>
+ <item row="4" column="0">
+ <widget class="QLabel" name="label_11">
<property name="text">
- <string>Location:</string>
+ <string>Group:</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
@@ -130,47 +241,14 @@
</property>
</widget>
</item>
- <item row="6" column="1">
- <widget class="QLabel" name="location">
- <property name="wordWrap">
- <bool>false</bool>
- </property>
+ <item row="2" column="1">
+ <widget class="QLabel" name="compatVersion">
<property name="textInteractionFlags">
- <set>Qt::TextBrowserInteraction</set>
+ <set>Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse</set>
</property>
</widget>
</item>
- <item row="7" column="0">
- <layout class="QVBoxLayout">
- <item>
- <widget class="QLabel" name="label_8">
- <property name="text">
- <string>Description:</string>
- </property>
- <property name="alignment">
- <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
- </property>
- <property name="textInteractionFlags">
- <set>Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse</set>
- </property>
- </widget>
- </item>
- <item>
- <spacer>
- <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>
- <item row="7" column="1">
+ <item row="8" column="1">
<widget class="QTextEdit" name="description">
<property name="tabChangesFocus">
<bool>true</bool>
@@ -180,7 +258,7 @@
</property>
</widget>
</item>
- <item row="8" column="0">
+ <item row="9" column="0">
<widget class="QLabel" name="label_5">
<property name="text">
<string>Copyright:</string>
@@ -193,14 +271,14 @@
</property>
</widget>
</item>
- <item row="8" column="1">
+ <item row="9" column="1">
<widget class="QLabel" name="copyright">
<property name="textInteractionFlags">
<set>Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse</set>
</property>
</widget>
</item>
- <item row="9" column="0">
+ <item row="10" column="0">
<layout class="QVBoxLayout">
<item>
<widget class="QLabel" name="label_9">
@@ -230,62 +308,6 @@
</item>
</layout>
</item>
- <item row="9" column="1">
- <widget class="QTextEdit" name="license">
- <property name="tabChangesFocus">
- <bool>true</bool>
- </property>
- <property name="readOnly">
- <bool>true</bool>
- </property>
- </widget>
- </item>
- <item row="10" column="0">
- <layout class="QVBoxLayout">
- <item>
- <widget class="QLabel" name="label_10">
- <property name="text">
- <string>Dependencies:</string>
- </property>
- <property name="alignment">
- <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
- </property>
- <property name="textInteractionFlags">
- <set>Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse</set>
- </property>
- </widget>
- </item>
- <item>
- <spacer>
- <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>
- <item row="10" column="1">
- <widget class="QListWidget" name="dependencies"/>
- </item>
- <item row="4" column="0">
- <widget class="QLabel" name="label_11">
- <property name="text">
- <string>Group:</string>
- </property>
- <property name="alignment">
- <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
- </property>
- <property name="textInteractionFlags">
- <set>Qt::LinksAccessibleByMouse|Qt::TextSelectableByMouse</set>
- </property>
- </widget>
- </item>
<item row="4" column="1">
<widget class="QLabel" name="component">
<property name="text">
diff --git a/src/libs/extensionsystem/pluginmanager.cpp b/src/libs/extensionsystem/pluginmanager.cpp
index 8f04c1b581..c7ce379b16 100644
--- a/src/libs/extensionsystem/pluginmanager.cpp
+++ b/src/libs/extensionsystem/pluginmanager.cpp
@@ -38,6 +38,7 @@
#include <QEventLoop>
#include <QDateTime>
#include <QDir>
+#include <QFile>
#include <QMetaProperty>
#include <QSettings>
#include <QTextStream>
@@ -45,14 +46,15 @@
#include <QWriteLocker>
#include <QDebug>
#include <QTimer>
+#include <QSysInfo>
#ifdef WITH_TESTS
#include <QTest>
#endif
-static const char C_IGNORED_PLUGINS[] = "Plugins/Ignored";
-static const char C_FORCEENABLED_PLUGINS[] = "Plugins/ForceEnabled";
-static const int DELAYED_INITIALIZE_INTERVAL = 20; // ms
+const char C_IGNORED_PLUGINS[] = "Plugins/Ignored";
+const char C_FORCEENABLED_PLUGINS[] = "Plugins/ForceEnabled";
+const int DELAYED_INITIALIZE_INTERVAL = 20; // ms
typedef QList<ExtensionSystem::PluginSpec *> PluginSpecSet;
@@ -94,9 +96,9 @@ enum { debugLeaks = 0 };
Usually, the application creates a PluginManager instance and initiates the
loading.
\code
- ExtensionSystem::PluginManager *manager = new ExtensionSystem::PluginManager();
- manager->setPluginPaths(QStringList() << "plugins"); // 'plugins' and subdirs will be searched for plugins
- manager->loadPlugins(); // try to load all the plugins
+ // 'plugins' and subdirs will be searched for plugins
+ ExtensionSystem::PluginManager::setPluginPaths(QStringList() << "plugins");
+ ExtensionSystem::PluginManager::loadPlugins(); // try to load all the plugins
\endcode
Additionally, it is possible to directly access the plugin specifications
(the information in the descriptor file), the plugin instances (via PluginSpec),
@@ -123,7 +125,7 @@ enum { debugLeaks = 0 };
ExtensionSystem::PluginManager::instance()->addObject(handler);
// In plugin A:
QList<MimeTypeHandler *> mimeHandlers =
- ExtensionSystem::PluginManager::instance()->getObjects<MimeTypeHandler>();
+ ExtensionSystem::PluginManager::getObjects<MimeTypeHandler>();
\endcode
@@ -160,8 +162,7 @@ enum { debugLeaks = 0 };
{
using namespace ExtensionSystem;
- QObject *target = PluginManager::instance()
- ->getObjectByClassName("PluginA::SomeProvider");
+ QObject *target = PluginManager::getObjectByClassName("PluginA::SomeProvider");
if (target) {
// Some random argument.
@@ -243,13 +244,14 @@ enum { debugLeaks = 0 };
using namespace ExtensionSystem;
using namespace ExtensionSystem::Internal;
+static Internal::PluginManagerPrivate *d = 0;
+static PluginManager *m_instance = 0;
+
static bool lessThanByPluginName(const PluginSpec *one, const PluginSpec *two)
{
return one->name() < two->name();
}
-PluginManager *PluginManager::m_instance = 0;
-
/*!
Gets the unique plugin manager instance.
*/
@@ -262,9 +264,9 @@ PluginManager *PluginManager::instance()
Creates a plugin manager. Should be done only once per application.
*/
PluginManager::PluginManager()
- : d(new PluginManagerPrivate(this))
{
m_instance = this;
+ d = new PluginManagerPrivate(this);
}
/*!
@@ -291,7 +293,7 @@ PluginManager::~PluginManager()
*/
void PluginManager::addObject(QObject *obj)
{
- m_instance->d->addObject(obj);
+ d->addObject(obj);
}
/*!
@@ -300,7 +302,7 @@ void PluginManager::addObject(QObject *obj)
*/
void PluginManager::removeObject(QObject *obj)
{
- m_instance->d->removeObject(obj);
+ d->removeObject(obj);
}
/*!
@@ -313,7 +315,12 @@ void PluginManager::removeObject(QObject *obj)
*/
QList<QObject *> PluginManager::allObjects()
{
- return m_instance->d->allObjects;
+ return d->allObjects;
+}
+
+QReadWriteLock *PluginManager::listLock()
+{
+ return &d->m_lock;
}
/*!
@@ -326,7 +333,7 @@ QList<QObject *> PluginManager::allObjects()
*/
void PluginManager::loadPlugins()
{
- return m_instance->d->loadPlugins();
+ return d->loadPlugins();
}
/*!
@@ -358,7 +365,7 @@ void PluginManager::shutdown()
*/
QStringList PluginManager::pluginPaths()
{
- return m_instance->d->pluginPaths;
+ return d->pluginPaths;
}
/*!
@@ -371,7 +378,7 @@ QStringList PluginManager::pluginPaths()
*/
void PluginManager::setPluginPaths(const QStringList &paths)
{
- m_instance->d->setPluginPaths(paths);
+ d->setPluginPaths(paths);
}
/*!
@@ -382,7 +389,7 @@ void PluginManager::setPluginPaths(const QStringList &paths)
*/
QString PluginManager::fileExtension()
{
- return m_instance->d->extension;
+ return d->extension;
}
/*!
@@ -393,7 +400,7 @@ QString PluginManager::fileExtension()
*/
void PluginManager::setFileExtension(const QString &extension)
{
- m_instance->d->extension = extension;
+ d->extension = extension;
}
/*!
@@ -403,7 +410,7 @@ void PluginManager::setFileExtension(const QString &extension)
*/
void PluginManager::setSettings(QSettings *settings)
{
- m_instance->d->setSettings(settings);
+ d->setSettings(settings);
}
/*!
@@ -413,7 +420,7 @@ void PluginManager::setSettings(QSettings *settings)
*/
void PluginManager::setGlobalSettings(QSettings *settings)
{
- m_instance->d->setGlobalSettings(settings);
+ d->setGlobalSettings(settings);
}
/*!
@@ -422,7 +429,7 @@ void PluginManager::setGlobalSettings(QSettings *settings)
*/
QSettings *PluginManager::settings()
{
- return m_instance->d->settings;
+ return d->settings;
}
/*!
@@ -430,12 +437,12 @@ QSettings *PluginManager::settings()
*/
QSettings *PluginManager::globalSettings()
{
- return m_instance->d->globalSettings;
+ return d->globalSettings;
}
void PluginManager::writeSettings()
{
- m_instance->d->writeSettings();
+ d->writeSettings();
}
/*!
@@ -444,7 +451,7 @@ void PluginManager::writeSettings()
*/
QStringList PluginManager::arguments()
{
- return m_instance->d->arguments;
+ return d->arguments;
}
/*!
@@ -458,12 +465,12 @@ QStringList PluginManager::arguments()
*/
QList<PluginSpec *> PluginManager::plugins()
{
- return m_instance->d->pluginSpecs;
+ return d->pluginSpecs;
}
QHash<QString, PluginCollection *> PluginManager::pluginCollections()
{
- return m_instance->d->pluginCategories;
+ return d->pluginCategories;
}
static const char argumentKeywordC[] = ":arguments";
@@ -490,13 +497,13 @@ QString PluginManager::serializedArguments()
rc += ps->arguments().join(QString(separator));
}
}
- if (!m_instance->d->arguments.isEmpty()) {
+ if (!d->arguments.isEmpty()) {
if (!rc.isEmpty())
rc += separator;
rc += QLatin1String(argumentKeywordC);
// If the argument appears to be a file, make it absolute
// when sending to another instance.
- foreach (const QString &argument, m_instance->d->arguments) {
+ foreach (const QString &argument, d->arguments) {
rc += separator;
const QFileInfo fi(argument);
if (fi.exists() && fi.isRelative())
@@ -574,7 +581,7 @@ bool PluginManager::parseOptions(const QStringList &args,
QMap<QString, QString> *foundAppOptions,
QString *errorString)
{
- OptionsParser options(args, appOptions, foundAppOptions, errorString, m_instance->d);
+ OptionsParser options(args, appOptions, foundAppOptions, errorString, d);
return options.parse();
}
@@ -620,7 +627,8 @@ void PluginManager::formatOptions(QTextStream &str, int optionIndentation, int d
#ifdef WITH_TESTS
formatOption(str, QString::fromLatin1(OptionsParser::TEST_OPTION)
+ QLatin1String(" <plugin>[,testfunction[:testdata]]..."), QString(),
- QLatin1String("Run plugin's tests"), optionIndentation, descriptionIndentation);
+ QLatin1String("Run plugin's tests (by default a separate settings path is used)"),
+ optionIndentation, descriptionIndentation);
formatOption(str, QString::fromLatin1(OptionsParser::TEST_OPTION) + QLatin1String(" all"),
QString(), QLatin1String("Run tests from all plugins"),
optionIndentation, descriptionIndentation);
@@ -635,8 +643,8 @@ void PluginManager::formatPluginOptions(QTextStream &str, int optionIndentation,
{
typedef PluginSpec::PluginArgumentDescriptions PluginArgumentDescriptions;
// Check plugins for options
- const PluginSpecSet::const_iterator pcend = m_instance->d->pluginSpecs.constEnd();
- for (PluginSpecSet::const_iterator pit = m_instance->d->pluginSpecs.constBegin(); pit != pcend; ++pit) {
+ const PluginSpecSet::const_iterator pcend = d->pluginSpecs.constEnd();
+ for (PluginSpecSet::const_iterator pit = d->pluginSpecs.constBegin(); pit != pcend; ++pit) {
const PluginArgumentDescriptions pargs = (*pit)->argumentDescriptions();
if (!pargs.empty()) {
str << "\nPlugin: " << (*pit)->name() << '\n';
@@ -652,8 +660,8 @@ void PluginManager::formatPluginOptions(QTextStream &str, int optionIndentation,
*/
void PluginManager::formatPluginVersions(QTextStream &str)
{
- const PluginSpecSet::const_iterator cend = m_instance->d->pluginSpecs.constEnd();
- for (PluginSpecSet::const_iterator it = m_instance->d->pluginSpecs.constBegin(); it != cend; ++it) {
+ const PluginSpecSet::const_iterator cend = d->pluginSpecs.constEnd();
+ for (PluginSpecSet::const_iterator it = d->pluginSpecs.constBegin(); it != cend; ++it) {
const PluginSpec *ps = *it;
str << " " << ps->name() << ' ' << ps->version() << ' ' << ps->description() << '\n';
}
@@ -695,17 +703,27 @@ void PluginManager::startTests()
foreach (const QString &userTestFunction, testSpec.testFunctions) {
// There might be a test data suffix like in "testfunction:testdata1".
QString testFunctionName = userTestFunction;
+ QString testDataSuffix;
const int index = testFunctionName.indexOf(QLatin1Char(':'));
- if (index != -1)
+ if (index != -1) {
+ testDataSuffix = testFunctionName.mid(index);
testFunctionName = testFunctionName.left(index);
+ }
- if (allTestFunctions.contains(testFunctionName)) {
+ const QRegExp regExp(testFunctionName, Qt::CaseSensitive, QRegExp::Wildcard);
+ QStringList matchingFunctions;
+ foreach (const QString &testFunction, allTestFunctions) {
+ if (regExp.exactMatch(testFunction))
+ matchingFunctions.append(testFunction);
+ }
+ if (!matchingFunctions.isEmpty()) {
// If the specified test data is invalid, the QTest framework will
// print a reasonable error message for us.
- testFunctionsToExecute.append(userTestFunction);
+ foreach (const QString &matchingFunction, matchingFunctions)
+ testFunctionsToExecute.append(matchingFunction + testDataSuffix);
} else {
QTextStream out(stdout);
- out << "Unknown test function \"" << testFunctionName
+ out << "No test function matches \"" << testFunctionName
<< "\" for plugin \"" << pluginSpec->name() << "\"." << endl
<< " Available test functions for plugin \"" << pluginSpec->name()
<< "\" are:" << endl;
@@ -736,7 +754,7 @@ void PluginManager::startTests()
*/
bool PluginManager::testRunRequested()
{
- return !m_instance->d->testSpecs.isEmpty();
+ return !d->testSpecs.isEmpty();
}
/*!
@@ -761,7 +779,7 @@ QString PluginManager::testDataDirectory()
void PluginManager::profilingReport(const char *what, const PluginSpec *spec)
{
- m_instance->d->profilingReport(what, spec);
+ d->profilingReport(what, spec);
}
@@ -770,7 +788,7 @@ void PluginManager::profilingReport(const char *what, const PluginSpec *spec)
*/
QList<PluginSpec *> PluginManager::loadQueue()
{
- return m_instance->d->loadQueue();
+ return d->loadQueue();
}
//============PluginManagerPrivate===========
@@ -932,7 +950,7 @@ void PluginManagerPrivate::deleteAll()
void PluginManagerPrivate::addObject(QObject *obj)
{
{
- QWriteLocker lock(&(q->m_lock));
+ QWriteLocker lock(&m_lock);
if (obj == 0) {
qWarning() << "PluginManagerPrivate::addObject(): trying to add null object";
return;
@@ -976,7 +994,7 @@ void PluginManagerPrivate::removeObject(QObject *obj)
qDebug() << "PluginManagerPrivate::removeObject" << obj << obj->objectName();
emit q->aboutToRemoveObject(obj);
- QWriteLocker lock(&(q->m_lock));
+ QWriteLocker lock(&m_lock);
allObjects.removeAll(obj);
}
@@ -1199,9 +1217,9 @@ void PluginManagerPrivate::readPluginPaths()
PluginCollection *collection = 0;
// find correct plugin collection or create a new one
- if (pluginCategories.contains(spec->category()))
+ if (pluginCategories.contains(spec->category())) {
collection = pluginCategories.value(spec->category());
- else {
+ } else {
collection = new PluginCollection(spec->category());
pluginCategories.insert(spec->category(), collection);
}
@@ -1325,6 +1343,77 @@ void PluginManagerPrivate::profilingSummary() const
}
}
+static inline QString getPlatformName()
+{
+#if defined(Q_OS_MAC)
+ QString result = QLatin1String("Mac OS");
+ if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_0)
+ result += QLatin1String(" 10.") + QString::number(QSysInfo::MacintoshVersion - QSysInfo::MV_10_0);
+ return result;
+#elif defined(Q_OS_UNIX)
+ QFile osReleaseFile(QLatin1String("/etc/os-release")); // Newer Linuxes
+ if (osReleaseFile.open(QIODevice::ReadOnly)) {
+ QString name;
+ QString version;
+ forever {
+ const QByteArray line = osReleaseFile.readLine();
+ if (line.isEmpty())
+ break;
+ if (line.startsWith("NAME=\""))
+ name = QString::fromLatin1(line.mid(6, line.size() - 8)).trimmed();
+ if (line.startsWith("VERSION_ID=\""))
+ version = QString::fromLatin1(line.mid(12, line.size() - 14)).trimmed();
+ }
+ if (!name.isEmpty()) {
+ if (!version.isEmpty())
+ name += QLatin1Char(' ') + version;
+ return name;
+ }
+ }
+ QFile issueFile(QLatin1String("/etc/issue")); // Older Linuxes
+ if (issueFile.open(QIODevice::ReadOnly)) {
+ QByteArray issue = issueFile.readAll();
+ const int end = issue.lastIndexOf(" \\n");
+ if (end >= 0)
+ issue.truncate(end);
+ return QString::fromLatin1(issue).trimmed();
+ }
+# ifdef Q_OS_LINUX
+ return QLatin1String("Linux");
+# else
+ return QLatin1String("Unix");
+# endif // Q_OS_LINUX
+#elif defined(Q_OS_WIN)
+ QString result = QLatin1String("Windows");
+ switch (QSysInfo::WindowsVersion) {
+ case QSysInfo::WV_XP:
+ result += QLatin1String(" XP");
+ break;
+ case QSysInfo::WV_2003:
+ result += QLatin1String(" 2003");
+ break;
+ case QSysInfo::WV_VISTA:
+ result += QLatin1String(" Vista");
+ break;
+ case QSysInfo::WV_WINDOWS7:
+ result += QLatin1String(" 7");
+ break;
+ default:
+ break;
+ }
+ if (QSysInfo::WindowsVersion >= QSysInfo::WV_WINDOWS8)
+ result += QLatin1String(" 8");
+ return result;
+#endif // Q_OS_WIN
+ return QLatin1String("Unknown");
+}
+
+QString PluginManager::platformName()
+{
+ static const QString result = getPlatformName();
+ return result;
+}
+
/*!
Retrieves one object with \a name from the object pool.
\sa addObject()
@@ -1332,7 +1421,7 @@ void PluginManagerPrivate::profilingSummary() const
QObject *PluginManager::getObjectByName(const QString &name)
{
- QReadLocker lock(&m_instance->m_lock);
+ QReadLocker lock(&d->m_lock);
QList<QObject *> all = allObjects();
foreach (QObject *obj, all) {
if (obj->objectName() == name)
@@ -1350,7 +1439,7 @@ QObject *PluginManager::getObjectByName(const QString &name)
QObject *PluginManager::getObjectByClassName(const QString &className)
{
const QByteArray ba = className.toUtf8();
- QReadLocker lock(&m_instance->m_lock);
+ QReadLocker lock(&d->m_lock);
QList<QObject *> all = allObjects();
foreach (QObject *obj, all) {
if (obj->inherits(ba.constData()))
diff --git a/src/libs/extensionsystem/pluginmanager.h b/src/libs/extensionsystem/pluginmanager.h
index 428559eaf2..a00e2e0099 100644
--- a/src/libs/extensionsystem/pluginmanager.h
+++ b/src/libs/extensionsystem/pluginmanager.h
@@ -34,7 +34,6 @@
#include <aggregation/aggregate.h>
#include <QObject>
-#include <QReadWriteLock>
#include <QStringList>
QT_BEGIN_NAMESPACE
@@ -44,14 +43,13 @@ QT_END_NAMESPACE
namespace ExtensionSystem {
class PluginCollection;
+class IPlugin;
+class PluginSpec;
namespace Internal {
class PluginManagerPrivate;
}
-class IPlugin;
-class PluginSpec;
-
class EXTENSIONSYSTEM_EXPORT PluginManager : public QObject
{
Q_OBJECT
@@ -60,15 +58,16 @@ public:
static PluginManager *instance();
PluginManager();
- virtual ~PluginManager();
+ ~PluginManager();
// Object pool operations
static void addObject(QObject *obj);
static void removeObject(QObject *obj);
static QList<QObject *> allObjects();
+ static QReadWriteLock *listLock();
template <typename T> static QList<T *> getObjects()
{
- QReadLocker lock(&m_instance->m_lock);
+ QReadLocker lock(listLock());
QList<T *> results;
QList<QObject *> all = allObjects();
QList<T *> result;
@@ -81,7 +80,7 @@ public:
}
template <typename T> static T *getObject()
{
- QReadLocker lock(&m_instance->m_lock);
+ QReadLocker lock(listLock());
QList<QObject *> all = allObjects();
T *result = 0;
foreach (QObject *obj, all) {
@@ -129,6 +128,8 @@ public:
static void profilingReport(const char *what, const PluginSpec *spec = 0);
+ static QString platformName();
+
signals:
void objectAdded(QObject *obj);
void aboutToRemoveObject(QObject *obj);
@@ -142,12 +143,6 @@ public slots:
private slots:
void startTests();
-
-private:
- Internal::PluginManagerPrivate *d;
- static PluginManager *m_instance;
- mutable QReadWriteLock m_lock;
-
friend class Internal::PluginManagerPrivate;
};
diff --git a/src/libs/extensionsystem/pluginmanager_p.h b/src/libs/extensionsystem/pluginmanager_p.h
index 6f424f5fc2..58bb191237 100644
--- a/src/libs/extensionsystem/pluginmanager_p.h
+++ b/src/libs/extensionsystem/pluginmanager_p.h
@@ -36,6 +36,7 @@
#include <QStringList>
#include <QObject>
#include <QScopedPointer>
+#include <QReadWriteLock>
QT_BEGIN_NAMESPACE
class QTime;
@@ -129,6 +130,8 @@ public:
static PluginSpec *createSpec();
static PluginSpecPrivate *privateSpec(PluginSpec *spec);
+ mutable QReadWriteLock m_lock;
+
private slots:
void nextDelayedInitialize();
void asyncShutdownFinished();
diff --git a/src/libs/extensionsystem/pluginspec.cpp b/src/libs/extensionsystem/pluginspec.cpp
index c2f1d82e80..1f6c8f8acd 100644
--- a/src/libs/extensionsystem/pluginspec.cpp
+++ b/src/libs/extensionsystem/pluginspec.cpp
@@ -256,6 +256,16 @@ QString PluginSpec::category() const
}
/*!
+ A QRegExp matching the platforms this plugin works on. An empty pattern implies all platforms.
+ \since 3.0
+*/
+
+QRegExp PluginSpec::platformSpecification() const
+{
+ return d->platformSpecification;
+}
+
+/*!
Returns whether the plugin has its experimental flag set.
*/
bool PluginSpec::isExperimental() const
@@ -292,9 +302,12 @@ bool PluginSpec::isEnabledInSettings() const
*/
bool PluginSpec::isEffectivelyEnabled() const
{
- return !d->disabledIndirectly
- && (d->enabledInSettings || d->forceEnabled)
- && !d->forceDisabled;
+ if (d->disabledIndirectly
+ || (!d->enabledInSettings && !d->forceEnabled)
+ || d->forceDisabled) {
+ return false;
+ }
+ return d->platformSpecification.isEmpty() || d->platformSpecification.exactMatch(PluginManager::platformName());
}
/*!
@@ -455,6 +468,7 @@ namespace {
const char DESCRIPTION[] = "description";
const char URL[] = "url";
const char CATEGORY[] = "category";
+ const char PLATFORM[] = "platform";
const char DEPENDENCYLIST[] = "dependencyList";
const char DEPENDENCY[] = "dependency";
const char DEPENDENCY_NAME[] = "name";
@@ -602,8 +616,7 @@ static inline QString msgUnexpectedToken()
*/
void PluginSpecPrivate::readPluginSpec(QXmlStreamReader &reader)
{
- QString element = reader.name().toString();
- if (element != QLatin1String(PLUGIN)) {
+ if (reader.name() != QLatin1String(PLUGIN)) {
reader.raiseError(QCoreApplication::translate("PluginSpec", "Expected element '%1' as top level element")
.arg(QLatin1String(PLUGIN)));
return;
@@ -639,8 +652,8 @@ void PluginSpecPrivate::readPluginSpec(QXmlStreamReader &reader)
while (!reader.atEnd()) {
reader.readNext();
switch (reader.tokenType()) {
- case QXmlStreamReader::StartElement:
- element = reader.name().toString();
+ case QXmlStreamReader::StartElement: {
+ const QStringRef element = reader.name();
if (element == QLatin1String(VENDOR))
vendor = reader.readElementText().trimmed();
else if (element == QLatin1String(COPYRIGHT))
@@ -653,12 +666,22 @@ void PluginSpecPrivate::readPluginSpec(QXmlStreamReader &reader)
url = reader.readElementText().trimmed();
else if (element == QLatin1String(CATEGORY))
category = reader.readElementText().trimmed();
- else if (element == QLatin1String(DEPENDENCYLIST))
+ else if (element == QLatin1String(PLATFORM)) {
+ const QString platformSpec = reader.readElementText().trimmed();
+ if (!platformSpec.isEmpty()) {
+ platformSpecification.setPattern(platformSpec);
+ if (!platformSpecification.isValid())
+ reader.raiseError(QLatin1String("Invalid platform specification \"")
+ + platformSpec + QLatin1String("\": ")
+ + platformSpecification.errorString());
+ }
+ } else if (element == QLatin1String(DEPENDENCYLIST))
readDependencies(reader);
else if (element == QLatin1String(ARGUMENTLIST))
readArgumentDescriptions(reader);
else
- reader.raiseError(msgInvalidElement(name));
+ reader.raiseError(msgInvalidElement(element.toString()));
+ }
break;
case QXmlStreamReader::EndDocument:
case QXmlStreamReader::Comment:
@@ -677,25 +700,22 @@ void PluginSpecPrivate::readPluginSpec(QXmlStreamReader &reader)
*/
void PluginSpecPrivate::readArgumentDescriptions(QXmlStreamReader &reader)
{
- QString element;
while (!reader.atEnd()) {
reader.readNext();
switch (reader.tokenType()) {
case QXmlStreamReader::StartElement:
- element = reader.name().toString();
- if (element == QLatin1String(ARGUMENT))
+ if (reader.name() == QLatin1String(ARGUMENT))
readArgumentDescription(reader);
else
- reader.raiseError(msgInvalidElement(name));
+ reader.raiseError(msgInvalidElement(reader.name().toString()));
break;
case QXmlStreamReader::Comment:
case QXmlStreamReader::Characters:
break;
case QXmlStreamReader::EndElement:
- element = reader.name().toString();
- if (element == QLatin1String(ARGUMENTLIST))
+ if (reader.name() == QLatin1String(ARGUMENTLIST))
return;
- reader.raiseError(msgUnexpectedClosing(element));
+ reader.raiseError(msgUnexpectedClosing(reader.name().toString()));
break;
default:
reader.raiseError(msgUnexpectedToken());
@@ -724,7 +744,7 @@ void PluginSpecPrivate::readArgumentDescription(QXmlStreamReader &reader)
bool PluginSpecPrivate::readBooleanValue(QXmlStreamReader &reader, const char *key)
{
- const QString valueString = reader.attributes().value(QLatin1String(key)).toString();
+ const QStringRef valueString = reader.attributes().value(QLatin1String(key));
const bool isOn = valueString.compare(QLatin1String("true"), Qt::CaseInsensitive) == 0;
if (!valueString.isEmpty() && !isOn
&& valueString.compare(QLatin1String("false"), Qt::CaseInsensitive) != 0) {
@@ -738,25 +758,22 @@ bool PluginSpecPrivate::readBooleanValue(QXmlStreamReader &reader, const char *k
*/
void PluginSpecPrivate::readDependencies(QXmlStreamReader &reader)
{
- QString element;
while (!reader.atEnd()) {
reader.readNext();
switch (reader.tokenType()) {
case QXmlStreamReader::StartElement:
- element = reader.name().toString();
- if (element == QLatin1String(DEPENDENCY))
+ if (reader.name() == QLatin1String(DEPENDENCY))
readDependencyEntry(reader);
else
- reader.raiseError(msgInvalidElement(name));
+ reader.raiseError(msgInvalidElement(reader.name().toString()));
break;
case QXmlStreamReader::Comment:
case QXmlStreamReader::Characters:
break;
case QXmlStreamReader::EndElement:
- element = reader.name().toString();
- if (element == QLatin1String(DEPENDENCYLIST))
+ if (reader.name() == QLatin1String(DEPENDENCYLIST))
return;
- reader.raiseError(msgUnexpectedClosing(element));
+ reader.raiseError(msgUnexpectedClosing(reader.name().toString()));
break;
default:
reader.raiseError(msgUnexpectedToken());
@@ -783,7 +800,7 @@ void PluginSpecPrivate::readDependencyEntry(QXmlStreamReader &reader)
}
dep.type = PluginDependency::Required;
if (reader.attributes().hasAttribute(QLatin1String(DEPENDENCY_TYPE))) {
- QString typeValue = reader.attributes().value(QLatin1String(DEPENDENCY_TYPE)).toString();
+ const QStringRef typeValue = reader.attributes().value(QLatin1String(DEPENDENCY_TYPE));
if (typeValue == QLatin1String(DEPENDENCY_TYPE_HARD)) {
dep.type = PluginDependency::Required;
} else if (typeValue == QLatin1String(DEPENDENCY_TYPE_SOFT)) {
diff --git a/src/libs/extensionsystem/pluginspec.h b/src/libs/extensionsystem/pluginspec.h
index d55fe7174b..53135b0cc4 100644
--- a/src/libs/extensionsystem/pluginspec.h
+++ b/src/libs/extensionsystem/pluginspec.h
@@ -38,6 +38,7 @@
QT_BEGIN_NAMESPACE
class QStringList;
+class QRegExp;
QT_END_NAMESPACE
namespace ExtensionSystem {
@@ -90,6 +91,7 @@ public:
QString description() const;
QString url() const;
QString category() const;
+ QRegExp platformSpecification() const;
bool isExperimental() const;
bool isDisabledByDefault() const;
bool isEnabledInSettings() const;
diff --git a/src/libs/extensionsystem/pluginspec_p.h b/src/libs/extensionsystem/pluginspec_p.h
index bad7369ec9..8c10b9aa8e 100644
--- a/src/libs/extensionsystem/pluginspec_p.h
+++ b/src/libs/extensionsystem/pluginspec_p.h
@@ -36,6 +36,7 @@
#include <QObject>
#include <QStringList>
#include <QXmlStreamReader>
+#include <QRegExp>
namespace ExtensionSystem {
@@ -72,6 +73,7 @@ public:
QString description;
QString url;
QString category;
+ QRegExp platformSpecification;
QList<PluginDependency> dependencies;
bool enabledInSettings;
bool disabledIndirectly;
diff --git a/src/libs/extensionsystem/pluginview.cpp b/src/libs/extensionsystem/pluginview.cpp
index a236aa544c..b8401fc568 100644
--- a/src/libs/extensionsystem/pluginview.cpp
+++ b/src/libs/extensionsystem/pluginview.cpp
@@ -71,7 +71,6 @@ Q_DECLARE_METATYPE(ExtensionSystem::PluginSpec*)
Q_DECLARE_METATYPE(ExtensionSystem::PluginCollection*)
/*!
- \fn PluginView::PluginView(PluginManager *manager, QWidget *parent)
Constructs a PluginView that gets the list of plugins from the
given plugin \a manager with a given \a parent widget.
*/
@@ -106,7 +105,6 @@ PluginView::PluginView(QWidget *parent)
}
/*!
- \fn PluginView::~PluginView()
\internal
*/
PluginView::~PluginView()
@@ -115,7 +113,6 @@ PluginView::~PluginView()
}
/*!
- \fn PluginSpec *PluginView::currentPlugin() const
Returns the current selection in the list of plugins.
*/
PluginSpec *PluginView::currentPlugin() const
diff --git a/src/libs/glsl/glslast.h b/src/libs/glsl/glslast.h
index 78e6d3e63d..e203e16877 100644
--- a/src/libs/glsl/glslast.h
+++ b/src/libs/glsl/glslast.h
@@ -765,7 +765,7 @@ public:
};
StructTypeAST(List<Field *> *_fields)
- : TypeAST(Kind_AnonymousStructType), fields(finish(_fields)) {}
+ : TypeAST(Kind_AnonymousStructType), name(0), fields(finish(_fields)) {}
StructTypeAST(const QString *_name, List<Field *> *_fields)
: TypeAST(Kind_StructType), name(_name), fields(finish(_fields)) {}
diff --git a/src/libs/glsl/glslsymbols.cpp b/src/libs/glsl/glslsymbols.cpp
index 69d02c5d0b..5c4978f021 100644
--- a/src/libs/glsl/glslsymbols.cpp
+++ b/src/libs/glsl/glslsymbols.cpp
@@ -109,9 +109,9 @@ QList<Symbol *> Namespace::members() const
void Namespace::add(Symbol *symbol)
{
Symbol *&sym = _members[symbol->name()];
- if (! sym)
+ if (! sym) {
sym = symbol;
- else if (Function *fun = symbol->asFunction()) {
+ } else if (Function *fun = symbol->asFunction()) {
if (OverloadSet *o = sym->asOverloadSet()) {
o->addFunction(fun);
} else if (Function *firstFunction = sym->asFunction()) {
@@ -121,8 +121,7 @@ void Namespace::add(Symbol *symbol)
o->addFunction(firstFunction);
o->addFunction(fun);
sym = o;
- }
- else {
+ } else {
// ### warning? return false?
}
} else {
diff --git a/src/libs/glsl/glsltypes.cpp b/src/libs/glsl/glsltypes.cpp
index f23f3f14c1..1ac7222ac7 100644
--- a/src/libs/glsl/glsltypes.cpp
+++ b/src/libs/glsl/glsltypes.cpp
@@ -298,9 +298,9 @@ bool MatrixType::isLessThan(const Type *other) const
Q_ASSERT(other != 0);
const MatrixType *mat = other->asMatrixType();
Q_ASSERT(mat != 0);
- if (_columns < mat->columns())
+ if (_columns < mat->columns()) {
return true;
- else if (_columns == mat->columns()) {
+ } else if (_columns == mat->columns()) {
if (_rows < mat->rows())
return true;
else if (_rows == mat->rows() && _elementType < mat->elementType())
diff --git a/src/libs/languageutils/languageutils-lib.pri b/src/libs/languageutils/languageutils-lib.pri
index 6eaa315814..aab3ac1bb4 100644
--- a/src/libs/languageutils/languageutils-lib.pri
+++ b/src/libs/languageutils/languageutils-lib.pri
@@ -4,8 +4,6 @@ contains(CONFIG, dll) {
DEFINES += LANGUAGEUTILS_BUILD_STATIC_LIB
}
-INCLUDEPATH += $$PWD/..
-
HEADERS += \
$$PWD/languageutils_global.h \
$$PWD/fakemetaobject.h \
diff --git a/src/libs/languageutils/languageutils.qbs b/src/libs/languageutils/languageutils.qbs
index 88bc82979e..3f4a53e93c 100644
--- a/src/libs/languageutils/languageutils.qbs
+++ b/src/libs/languageutils/languageutils.qbs
@@ -4,7 +4,6 @@ import "../QtcLibrary.qbs" as QtcLibrary
QtcLibrary {
name: "LanguageUtils"
- cpp.includePaths: base.concat("../3rdparty/cplusplus")
cpp.defines: base.concat([
"LANGUAGEUTILS_BUILD_DIR"
])
diff --git a/src/libs/qmldebug/qmldebug-lib.pri b/src/libs/qmldebug/qmldebug-lib.pri
index 54f09258b0..9afd866e79 100644
--- a/src/libs/qmldebug/qmldebug-lib.pri
+++ b/src/libs/qmldebug/qmldebug-lib.pri
@@ -4,8 +4,6 @@ contains(CONFIG, dll) {
DEFINES += QMLDEBUG_STATIC_LIB
}
-INCLUDEPATH += $$PWD/..
-
HEADERS += \
$$PWD/qmlprofilereventlocation.h \
$$PWD/qmldebugclient.h \
diff --git a/src/libs/qmldebug/qmlprofilereventtypes.h b/src/libs/qmldebug/qmlprofilereventtypes.h
index b0498ab755..a5ece2928c 100644
--- a/src/libs/qmldebug/qmlprofilereventtypes.h
+++ b/src/libs/qmldebug/qmlprofilereventtypes.h
@@ -38,6 +38,8 @@ enum QmlEventType {
Creating,
Binding,
HandlingSignal,
+ PixmapCacheEvent,
+ SceneGraphFrameEvent,
MaximumQmlEventType
};
@@ -46,6 +48,8 @@ enum BindingType {
QmlBinding,
V8Binding,
OptimizedBinding,
+ QPainterEvent,
+ AnimationFrame,
MaximumBindingType
};
diff --git a/src/libs/qmldebug/qmlprofilertraceclient.cpp b/src/libs/qmldebug/qmlprofilertraceclient.cpp
index 157c8ac4f6..b0824ddfdb 100644
--- a/src/libs/qmldebug/qmlprofilertraceclient.cpp
+++ b/src/libs/qmldebug/qmlprofilertraceclient.cpp
@@ -170,7 +170,8 @@ void QmlProfilerTraceClient::messageReceived(const QByteArray &data)
} else if (event == AnimationFrame) {
int frameRate, animationCount;
stream >> frameRate >> animationCount;
- emit this->frame(time, frameRate, animationCount);
+ emit rangedEvent(QmlDebug::Painting, QmlDebug::AnimationFrame, time, 0,
+ QStringList(), QmlDebug::QmlEventLocation(), frameRate, animationCount, 0,0,0);
d->maximumTime = qMax(time, d->maximumTime);
} else if (event == StartTrace) {
emit this->traceStarted(time);
@@ -181,6 +182,32 @@ void QmlProfilerTraceClient::messageReceived(const QByteArray &data)
}
} else if (messageType == Complete) {
emit complete();
+ } else if (messageType == SceneGraphFrame) {
+ int sgEventType;
+ int count = 0;
+ qint64 params[5];
+
+ stream >> sgEventType;
+ while (!stream.atEnd()) {
+ stream >> params[count++];
+ }
+ while (count<5)
+ params[count++] = 0;
+ emit rangedEvent(SceneGraphFrameEvent, sgEventType,time, 0, QStringList(),
+ QmlDebug::QmlEventLocation(), params[0], params[1], params[2], params[3], params[4]);
+ } else if (messageType == PixmapCacheEvent) {
+ int pixEvTy, width = 0, height = 0, refcount = 0;
+ QString pixUrl;
+ stream >> pixEvTy >> pixUrl;
+ if (pixEvTy == (int)PixmapReferenceCountChanged || pixEvTy == (int)PixmapCacheCountChanged) {
+ stream >> refcount;
+ } else if (pixEvTy == (int)PixmapSizeKnown) {
+ stream >> width >> height;
+ refcount = 1;
+ }
+ emit rangedEvent(QmlDebug::PixmapCacheEvent, pixEvTy, time, 0, QStringList(),
+ QmlDebug::QmlEventLocation(pixUrl,0,0), width, height, refcount, 0, 0);
+ d->maximumTime = qMax(time, d->maximumTime);
} else {
int range;
stream >> range;
@@ -240,7 +267,10 @@ void QmlProfilerTraceClient::messageReceived(const QByteArray &data)
BindingType bindingType = QmlBinding;
if ((QmlEventType)range == Binding)
bindingType = d->bindingTypes.pop();
- emit this->range((QmlEventType)range, bindingType, startTime, time - startTime, data, location);
+ if ((QmlEventType)range == Painting)
+ bindingType = QPainterEvent;
+ emit rangedEvent((QmlEventType)range, bindingType, startTime, time - startTime, data,
+ location, 0, 0, 0, 0, 0);
if (d->rangeCount[range] == 0) {
int count = d->rangeDatas[range].count() +
d->rangeStartTimes[range].count() +
diff --git a/src/libs/qmldebug/qmlprofilertraceclient.h b/src/libs/qmldebug/qmlprofilertraceclient.h
index 6e0cf1470a..b8364c0ab0 100644
--- a/src/libs/qmldebug/qmlprofilertraceclient.h
+++ b/src/libs/qmldebug/qmlprofilertraceclient.h
@@ -71,10 +71,23 @@ public:
RangeLocation,
RangeEnd,
Complete,
+ PixmapCacheEvent,
+ SceneGraphFrame,
MaximumMessage
};
+ enum PixmapEventType {
+ PixmapSizeKnown,
+ PixmapReferenceCountChanged,
+ PixmapCacheCountChanged,
+ PixmapLoadingStarted,
+ PixmapLoadingFinished,
+ PixmapLoadingError,
+
+ MaximumPixmapEventType
+ };
+
bool isEnabled() const;
bool isRecording() const;
void setRecording(bool);
@@ -89,10 +102,9 @@ signals:
void event(int event, qint64 time);
void traceFinished( qint64 time );
void traceStarted( qint64 time );
- void range(int type, int bindingType, qint64 startTime, qint64 length,
- const QStringList &data, const QmlDebug::QmlEventLocation &location);
- void frame(qint64 time, int frameRate, int animationCount);
-
+ void rangedEvent(int type, int bindingType, qint64 startTime, qint64 length,
+ const QStringList &data, const QmlDebug::QmlEventLocation &location,
+ qint64 param1, qint64 param2, qint64 param3, qint64 param4, qint64 param5);
void recordingChanged(bool arg);
void enabledChanged();
diff --git a/src/libs/qmleditorwidgets/contextpanetext.ui b/src/libs/qmleditorwidgets/contextpanetext.ui
index d3d77f9425..8a1ceb862a 100644
--- a/src/libs/qmleditorwidgets/contextpanetext.ui
+++ b/src/libs/qmleditorwidgets/contextpanetext.ui
@@ -438,12 +438,12 @@
<customwidget>
<class>QmlEditorWidgets::ColorButton</class>
<extends>QToolButton</extends>
- <header location="global">colorbutton.h</header>
+ <header location="global">qmleditorwidgets/colorbutton.h</header>
</customwidget>
<customwidget>
<class>QmlEditorWidgets::FontSizeSpinBox</class>
<extends>QSpinBox</extends>
- <header location="global">fontsizespinbox.h</header>
+ <header location="global">qmleditorwidgets/fontsizespinbox.h</header>
</customwidget>
</customwidgets>
<resources/>
diff --git a/src/libs/qmleditorwidgets/contextpanetextwidget.cpp b/src/libs/qmleditorwidgets/contextpanetextwidget.cpp
index 5af62c4e39..153ad6095c 100644
--- a/src/libs/qmleditorwidgets/contextpanetextwidget.cpp
+++ b/src/libs/qmleditorwidgets/contextpanetextwidget.cpp
@@ -283,9 +283,9 @@ void ContextPaneTextWidget::onColorDialogApplied(const QColor &)
ContextPaneWidget *parentContextWidget = qobject_cast<ContextPaneWidget*>(parentWidget());
parentContextWidget->onShowColorDialog(false, QPoint());
if (ui->textColorButton->isChecked())
- emit propertyChanged(QLatin1String("styleColor"),parentContextWidget->colorDialog()->color());; //write back color
+ emit propertyChanged(QLatin1String("styleColor"),parentContextWidget->colorDialog()->color()); //write back color
if (ui->colorButton->isChecked())
- emit propertyChanged(QLatin1String("color"),parentContextWidget->colorDialog()->color());; //write back color
+ emit propertyChanged(QLatin1String("color"),parentContextWidget->colorDialog()->color()); //write back color
ui->textColorButton->setChecked(false);
ui->colorButton->setChecked(false);
}
diff --git a/src/libs/qmleditorwidgets/contextpanewidget.cpp b/src/libs/qmleditorwidgets/contextpanewidget.cpp
index 683bef38d1..84fdb2177e 100644
--- a/src/libs/qmleditorwidgets/contextpanewidget.cpp
+++ b/src/libs/qmleditorwidgets/contextpanewidget.cpp
@@ -43,38 +43,17 @@
#include <QGraphicsEffect>
#include <QAction>
#include "contextpanetextwidget.h"
-#include "easingcontextpane.h"
#include "contextpanewidgetimage.h"
#include "contextpanewidgetrectangle.h"
#include "customcolordialog.h"
#include "colorbutton.h"
+#include <qmleditorwidgets/easingpane/easingcontextpane.h>
using namespace Utils;
namespace QmlEditorWidgets {
/* XPM */
-static const char * const line_xpm[] = {
- "14 14 3 1",
- " c None",
- ". c #0c0c0c",
- "x c #1c1c1c",
- "............. ",
- ". . ",
- ". x x . ",
- ". x x . ",
- ". x x . ",
- ". x x . ",
- ". x . ",
- ". x x . ",
- ". x x . ",
- ". x x . ",
- ". x x . ",
- ". . ",
- "............. ",
- " "};
-
-/* XPM */
static const char * pin_xpm[] = {
"12 9 7 1",
" c None",
diff --git a/src/libs/qmleditorwidgets/contextpanewidgetborderimage.ui b/src/libs/qmleditorwidgets/contextpanewidgetborderimage.ui
index fc849a02b2..df35b99cdd 100644
--- a/src/libs/qmleditorwidgets/contextpanewidgetborderimage.ui
+++ b/src/libs/qmleditorwidgets/contextpanewidgetborderimage.ui
@@ -300,7 +300,7 @@
<customwidget>
<class>QmlEditorWidgets::FileWidget</class>
<extends>QComboBox</extends>
- <header location="global">filewidget.h</header>
+ <header location="global">qmleditorwidgets/filewidget.h</header>
</customwidget>
</customwidgets>
<resources>
diff --git a/src/libs/qmleditorwidgets/contextpanewidgetimage.cpp b/src/libs/qmleditorwidgets/contextpanewidgetimage.cpp
index df76de33b7..ab2a3b898f 100644
--- a/src/libs/qmleditorwidgets/contextpanewidgetimage.cpp
+++ b/src/libs/qmleditorwidgets/contextpanewidgetimage.cpp
@@ -779,43 +779,6 @@ static inline int limitPositive(int i)
return 0;
}
-static inline int limit(int i, int zoom)
-{
- static bool flag1 = 1;
- static bool flag2 = 1;
- if (zoom == 1)
- return i;
- if (i < 0) {
- int v = i / zoom;
- if (v)
- return v;
- if (zoom == 2) {
- flag1 =!flag1;
- return flag1 ? -1 : 0;
- }
- flag1 =!flag1;
- if (flag1)
- flag2 =!flag2;
-
- return flag1 && flag2 ? -1 : 0;
- }
- if (i > 0) {
- int v = i / zoom;
- if (v)
- return v;
- if (zoom == 2) {
- flag1 =!flag1;
- return flag1 ? 1 : 0;
- }
- flag1 =!flag1;
- if (flag1)
- flag2 =!flag2;
-
- return flag1 && flag2 ? 1 : 0;
- }
- return 0;
-}
-
void PreviewLabel::mouseMoveEvent(QMouseEvent * event)
{
if (!m_borderImage)
diff --git a/src/libs/qmleditorwidgets/contextpanewidgetimage.ui b/src/libs/qmleditorwidgets/contextpanewidgetimage.ui
index dc0587de5b..ed25fbf0fd 100644
--- a/src/libs/qmleditorwidgets/contextpanewidgetimage.ui
+++ b/src/libs/qmleditorwidgets/contextpanewidgetimage.ui
@@ -285,7 +285,7 @@
<customwidget>
<class>QmlEditorWidgets::FileWidget</class>
<extends>QComboBox</extends>
- <header location="global">filewidget.h</header>
+ <header location="global">qmleditorwidgets/filewidget.h</header>
</customwidget>
</customwidgets>
<resources>
diff --git a/src/libs/qmleditorwidgets/contextpanewidgetrectangle.cpp b/src/libs/qmleditorwidgets/contextpanewidgetrectangle.cpp
index eca08408a5..9fa4d2af1d 100644
--- a/src/libs/qmleditorwidgets/contextpanewidgetrectangle.cpp
+++ b/src/libs/qmleditorwidgets/contextpanewidgetrectangle.cpp
@@ -30,9 +30,9 @@
#include "contextpanewidgetrectangle.h"
#include "ui_contextpanewidgetrectangle.h"
#include "contextpanewidget.h"
+#include "customcolordialog.h"
#include <qmljs/qmljspropertyreader.h>
#include <qmljs/qmljsutils.h>
-#include <customcolordialog.h>
#include <QDebug>
namespace QmlEditorWidgets {
@@ -168,9 +168,9 @@ void ContextPaneWidgetRectangle::onColorDialogApplied(const QColor &)
ContextPaneWidget *parentContextWidget = qobject_cast<ContextPaneWidget*>(parentWidget());
parentContextWidget->onShowColorDialog(false, QPoint());
if (ui->colorColorButton->isChecked())
- emit propertyChanged(QLatin1String("color"),parentContextWidget->colorDialog()->color());; //write back color
+ emit propertyChanged(QLatin1String("color"),parentContextWidget->colorDialog()->color()); //write back color
if (ui->borderColorButton->isChecked())
- emit propertyChanged(QLatin1String("border.color"),parentContextWidget->colorDialog()->color());; //write back color
+ emit propertyChanged(QLatin1String("border.color"),parentContextWidget->colorDialog()->color()); //write back color
if (m_gradientLineDoubleClicked)
ui->gradientLine->setActiveColor(parentContextWidget->colorDialog()->color());
ui->colorColorButton->setChecked(false);
diff --git a/src/libs/qmleditorwidgets/contextpanewidgetrectangle.ui b/src/libs/qmleditorwidgets/contextpanewidgetrectangle.ui
index 43e2c735f7..1f2ba9f39b 100644
--- a/src/libs/qmleditorwidgets/contextpanewidgetrectangle.ui
+++ b/src/libs/qmleditorwidgets/contextpanewidgetrectangle.ui
@@ -298,12 +298,12 @@
<customwidget>
<class>QmlEditorWidgets::ColorButton</class>
<extends>QToolButton</extends>
- <header location="global">colorbutton.h</header>
+ <header location="global">qmleditorwidgets/colorbutton.h</header>
</customwidget>
<customwidget>
<class>QmlEditorWidgets::GradientLine</class>
<extends>QWidget</extends>
- <header location="global">gradientline.h</header>
+ <header location="global">qmleditorwidgets/gradientline.h</header>
<container>1</container>
</customwidget>
</customwidgets>
diff --git a/src/libs/qmleditorwidgets/easingpane/easingcontextpane.cpp b/src/libs/qmleditorwidgets/easingpane/easingcontextpane.cpp
index d54efe5c59..6d6508ca0a 100644
--- a/src/libs/qmleditorwidgets/easingpane/easingcontextpane.cpp
+++ b/src/libs/qmleditorwidgets/easingpane/easingcontextpane.cpp
@@ -228,9 +228,9 @@ void EasingContextPane::setGraphDisplayMode(GraphDisplayMode newMode)
void EasingContextPane::startAnimation()
{
- if (m_simulation->running())
+ if (m_simulation->running()) {
m_simulation->stop();
- else {
+ } else {
m_simulation->animate(ui->durationSpinBox->value(), m_easingGraph->easingCurve());
ui->playButton->setIcon(QIcon(QLatin1String(":/stopicon.png")));
}
diff --git a/src/libs/qmleditorwidgets/easingpane/easingpane.pri b/src/libs/qmleditorwidgets/easingpane/easingpane.pri
index fc6b057d81..a1c04cda4b 100644
--- a/src/libs/qmleditorwidgets/easingpane/easingpane.pri
+++ b/src/libs/qmleditorwidgets/easingpane/easingpane.pri
@@ -1,5 +1,4 @@
VPATH += $$PWD
-INCLUDEPATH += $$PWD
SOURCES += $$PWD/easinggraph.cpp \
$$PWD/easingcontextpane.cpp
diff --git a/src/libs/qmleditorwidgets/gradientline.cpp b/src/libs/qmleditorwidgets/gradientline.cpp
index c1f1cdf9e0..f55d53528e 100644
--- a/src/libs/qmleditorwidgets/gradientline.cpp
+++ b/src/libs/qmleditorwidgets/gradientline.cpp
@@ -52,13 +52,6 @@ void GradientLine::setGradient(const QLinearGradient &gradient)
readGradient();
}
-static inline QColor invertColor(const QColor color)
-{
- QColor c = color.toHsv();
- c.setHsv(c.hue(), c.saturation(), 255 - c.value());
- return c;
-}
-
GradientLine::GradientLine(QWidget *parent) :
QWidget(parent),
m_activeColor(Qt::black),
@@ -327,19 +320,6 @@ void GradientLine::setup()
}
-static inline QColor normalizeColor(const QColor &color)
-{
- QColor newColor = QColor(color.name());
- newColor.setAlpha(color.alpha());
- return newColor;
-}
-
-static inline qreal roundReal(qreal real)
-{
- int i = real * 100;
- return qreal(i) / 100;
-}
-
void GradientLine::updateGradient()
{
if (m_useGradient) {
diff --git a/src/libs/qmleditorwidgets/qmleditorwidgets-lib.pri b/src/libs/qmleditorwidgets/qmleditorwidgets-lib.pri
index da748cf52d..fdaf629f7a 100644
--- a/src/libs/qmleditorwidgets/qmleditorwidgets-lib.pri
+++ b/src/libs/qmleditorwidgets/qmleditorwidgets-lib.pri
@@ -1,7 +1,5 @@
QT += script declarative
-INCLUDEPATH += $$PWD
-
contains(CONFIG, dll) {
DEFINES += BUILD_QMLEDITORWIDGETS_LIB
} else {
diff --git a/src/libs/qmleditorwidgets/qmleditorwidgets.qbs b/src/libs/qmleditorwidgets/qmleditorwidgets.qbs
index d6ae739b31..a8a3ebc2c1 100644
--- a/src/libs/qmleditorwidgets/qmleditorwidgets.qbs
+++ b/src/libs/qmleditorwidgets/qmleditorwidgets.qbs
@@ -4,7 +4,6 @@ import "../QtcLibrary.qbs" as QtcLibrary
QtcLibrary {
name: "QmlEditorWidgets"
- cpp.includePaths: base.concat("easingpane")
cpp.defines: base.concat([
"QWEAKPOINTER_ENABLE_ARROW",
"BUILD_QMLEDITORWIDGETS_LIB"
@@ -15,43 +14,36 @@ QtcLibrary {
Depends { name: "QmlJS" }
Depends { name: "Utils" }
- files: [
- "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",
- "resources.qrc",
- "easingpane/easingcontextpane.cpp",
- "easingpane/easingcontextpane.h",
- "easingpane/easingcontextpane.ui",
- "easingpane/easinggraph.cpp",
- "easingpane/easinggraph.h",
- "easingpane/easingpane.qrc",
- ]
-}
+ Group {
+ name: "General"
+ files: [
+ "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",
+ "resources.qrc"
+ ]
+ }
+ Group {
+ name: "Easing Pane"
+ id: easingPane
+ prefix: "easingpane/"
+ files: [
+ "easingcontextpane.cpp", "easingcontextpane.h", "easingcontextpane.ui",
+ "easinggraph.cpp", "easinggraph.h",
+ "easingpane.qrc",
+ ]
+ }
+}
diff --git a/src/libs/qmljs/jsoncheck.cpp b/src/libs/qmljs/jsoncheck.cpp
index c1a28d311d..c6c455a760 100644
--- a/src/libs/qmljs/jsoncheck.cpp
+++ b/src/libs/qmljs/jsoncheck.cpp
@@ -272,12 +272,12 @@ bool JsonCheck::visit(StringLiteral *ast)
analysis()->boostRanking();
- const QString &literal = ast->value.toString();
+ const QStringRef literal = ast->value;
const QString &pattern = m_schema->pattern();
if (!pattern.isEmpty()) {
QRegExp regExp(pattern);
- if (regExp.indexIn(literal) == -1) {
+ if (regExp.indexIn(literal.toString()) == -1) {
analysis()->m_messages.append(Message(ErrInvalidStringValuePattern,
ast->firstSourceLocation(),
QString(), QString(), false));
diff --git a/src/libs/qmljs/parser/qmljs.g b/src/libs/qmljs/parser/qmljs.g
index 66e1fd204b..998e9df660 100644
--- a/src/libs/qmljs/parser/qmljs.g
+++ b/src/libs/qmljs/parser/qmljs.g
@@ -313,7 +313,7 @@ public:
inline DiagnosticMessage diagnosticMessage() const
{
foreach (const DiagnosticMessage &d, diagnostic_messages) {
- if (! d.kind == DiagnosticMessage::Warning)
+ if (d.kind != DiagnosticMessage::Warning)
return d;
}
diff --git a/src/libs/qmljs/parser/qmljslexer.cpp b/src/libs/qmljs/parser/qmljslexer.cpp
index 99a800e2ef..68e5e9519d 100644
--- a/src/libs/qmljs/parser/qmljslexer.cpp
+++ b/src/libs/qmljs/parser/qmljslexer.cpp
@@ -905,7 +905,7 @@ bool Lexer::scanRegExp(RegExpBodyPrefix prefix)
while (! _char.isNull() && ! isLineTerminator()) {
if (_char == QLatin1Char(']'))
break;
- else if (_char == QLatin1Char('\\')) {
+ if (_char == QLatin1Char('\\')) {
// regular expression backslash sequence
_tokenText += _char;
scanChar();
diff --git a/src/libs/qmljs/parser/qmljsparser_p.h b/src/libs/qmljs/parser/qmljsparser_p.h
index a2aec3d089..eafea8f405 100644
--- a/src/libs/qmljs/parser/qmljsparser_p.h
+++ b/src/libs/qmljs/parser/qmljsparser_p.h
@@ -162,7 +162,7 @@ public:
inline DiagnosticMessage diagnosticMessage() const
{
foreach (const DiagnosticMessage &d, diagnostic_messages) {
- if (! d.kind == DiagnosticMessage::Warning)
+ if (d.kind != DiagnosticMessage::Warning)
return d;
}
diff --git a/src/libs/qmljs/qmljs-lib.pri b/src/libs/qmljs/qmljs-lib.pri
index 12913de0a5..1ea154d3ad 100644
--- a/src/libs/qmljs/qmljs-lib.pri
+++ b/src/libs/qmljs/qmljs-lib.pri
@@ -6,8 +6,6 @@ contains(CONFIG, dll) {
include(parser/parser.pri)
-INCLUDEPATH += $$PWD/..
-
HEADERS += \
$$PWD/qmljs_global.h \
$$PWD/qmljsbind.h \
diff --git a/src/libs/qmljs/qmljs.qbs b/src/libs/qmljs/qmljs.qbs
index 7029b1149f..8df00b7ed4 100644
--- a/src/libs/qmljs/qmljs.qbs
+++ b/src/libs/qmljs/qmljs.qbs
@@ -4,7 +4,6 @@ import "../QtcLibrary.qbs" as QtcLibrary
QtcLibrary {
name: "QmlJS"
- cpp.includePaths: base.concat("parser")
cpp.defines: base.concat([
"QMLJS_BUILD_DIR"
])
@@ -14,101 +13,79 @@ QtcLibrary {
Depends { name: "LanguageUtils" }
Depends { name: "Qt"; submodules: ["widgets", "script", "xml"] }
- files: [
- "jsoncheck.cpp",
- "jsoncheck.h",
- "qmljs.qrc",
- "qmljs_global.h",
- "qmljsbind.cpp",
- "qmljsbind.h",
- "qmljsbundle.cpp",
- "qmljsbundle.h",
- "qmljscheck.cpp",
- "qmljscheck.h",
- "qmljscodeformatter.cpp",
- "qmljscodeformatter.h",
- "qmljscompletioncontextfinder.cpp",
- "qmljscompletioncontextfinder.h",
- "qmljscontext.cpp",
- "qmljscontext.h",
- "qmljsdelta.cpp",
- "qmljsdelta.h",
- "qmljsdocument.cpp",
- "qmljsdocument.h",
- "qmljsevaluate.cpp",
- "qmljsevaluate.h",
- "qmljsicons.cpp",
- "qmljsicons.h",
- "qmljsicontextpane.h",
- "qmljsindenter.cpp",
- "qmljsindenter.h",
- "qmljsinterpreter.cpp",
- "qmljsinterpreter.h",
- "qmljslineinfo.cpp",
- "qmljslineinfo.h",
- "qmljslink.cpp",
- "qmljslink.h",
- "qmljsmodelmanagerinterface.cpp",
- "qmljsmodelmanagerinterface.h",
- "qmljspropertyreader.cpp",
- "qmljspropertyreader.h",
- "qmljsqrcparser.cpp",
- "qmljsqrcparser.h",
- "qmljsreformatter.cpp",
- "qmljsreformatter.h",
- "qmljsrewriter.cpp",
- "qmljsrewriter.h",
- "qmljsscanner.cpp",
- "qmljsscanner.h",
- "qmljsscopeastpath.cpp",
- "qmljsscopeastpath.h",
- "qmljsscopebuilder.cpp",
- "qmljsscopebuilder.h",
- "qmljsscopechain.cpp",
- "qmljsscopechain.h",
- "qmljsstaticanalysismessage.cpp",
- "qmljsstaticanalysismessage.h",
- "qmljstypedescriptionreader.cpp",
- "qmljstypedescriptionreader.h",
- "qmljsutils.cpp",
- "qmljsutils.h",
- "qmljsvalueowner.cpp",
- "qmljsvalueowner.h",
- "images/element.png",
- "images/func.png",
- "images/property.png",
- "images/publicmember.png",
- "parser/qmldirparser.cpp",
- "parser/qmldirparser_p.h",
- "parser/qmlerror.cpp",
- "parser/qmlerror.h",
- "parser/qmljsast.cpp",
- "parser/qmljsast_p.h",
- "parser/qmljsastfwd_p.h",
- "parser/qmljsastvisitor.cpp",
- "parser/qmljsastvisitor_p.h",
- "parser/qmljsengine_p.cpp",
- "parser/qmljsengine_p.h",
- "parser/qmljsglobal_p.h",
- "parser/qmljsgrammar.cpp",
- "parser/qmljsgrammar_p.h",
- "parser/qmljskeywords_p.h",
- "parser/qmljslexer.cpp",
- "parser/qmljslexer_p.h",
- "parser/qmljsmemorypool_p.h",
- "parser/qmljsparser.cpp",
- "parser/qmljsparser_p.h",
- "persistenttrie.cpp",
- "persistenttrie.h",
- "consolemanagerinterface.cpp",
- "consolemanagerinterface.h",
- "consoleitem.cpp",
- "consoleitem.h",
- "iscriptevaluator.h"
- ]
+ Group {
+ name: "General"
+ files: [
+ "consoleitem.cpp", "consoleitem.h",
+ "consolemanagerinterface.cpp", "consolemanagerinterface.h",
+ "iscriptevaluator.h",
+ "jsoncheck.cpp", "jsoncheck.h",
+ "persistenttrie.cpp", "persistenttrie.h",
+ "qmljs.qrc",
+ "qmljs_global.h",
+ "qmljsbind.cpp", "qmljsbind.h",
+ "qmljsbundle.cpp", "qmljsbundle.h",
+ "qmljscheck.cpp", "qmljscheck.h",
+ "qmljscodeformatter.cpp", "qmljscodeformatter.h",
+ "qmljscompletioncontextfinder.cpp", "qmljscompletioncontextfinder.h",
+ "qmljscontext.cpp", "qmljscontext.h",
+ "qmljsdelta.cpp", "qmljsdelta.h",
+ "qmljsdocument.cpp", "qmljsdocument.h",
+ "qmljsevaluate.cpp", "qmljsevaluate.h",
+ "qmljsicons.cpp", "qmljsicons.h",
+ "qmljsicontextpane.h",
+ "qmljsindenter.cpp", "qmljsindenter.h",
+ "qmljsinterpreter.cpp", "qmljsinterpreter.h",
+ "qmljslineinfo.cpp", "qmljslineinfo.h",
+ "qmljslink.cpp", "qmljslink.h",
+ "qmljsmodelmanagerinterface.cpp", "qmljsmodelmanagerinterface.h",
+ "qmljspropertyreader.cpp", "qmljspropertyreader.h",
+ "qmljsqrcparser.cpp", "qmljsqrcparser.h",
+ "qmljsreformatter.cpp", "qmljsreformatter.h",
+ "qmljsrewriter.cpp", "qmljsrewriter.h",
+ "qmljsscanner.cpp", "qmljsscanner.h",
+ "qmljsscopeastpath.cpp", "qmljsscopeastpath.h",
+ "qmljsscopebuilder.cpp", "qmljsscopebuilder.h",
+ "qmljsscopechain.cpp", "qmljsscopechain.h",
+ "qmljssimplereader.cpp", "qmljssimplereader.h",
+ "qmljsstaticanalysismessage.cpp", "qmljsstaticanalysismessage.h",
+ "qmljstypedescriptionreader.cpp", "qmljstypedescriptionreader.h",
+ "qmljsutils.cpp", "qmljsutils.h",
+ "qmljsvalueowner.cpp", "qmljsvalueowner.h"
+ ]
+ }
+
+ Group {
+ name: "Images"
+ prefix: "images/"
+ files: [
+ "element.png",
+ "func.png",
+ "property.png",
+ "publicmember.png",
+ ]
+ }
+
+ Group {
+ name: "Parser"
+ prefix: "parser/"
+ files: [
+ "qmldirparser.cpp", "qmldirparser_p.h",
+ "qmlerror.cpp", "qmlerror.h",
+ "qmljsast.cpp", "qmljsast_p.h",
+ "qmljsastfwd_p.h",
+ "qmljsastvisitor.cpp", "qmljsastvisitor_p.h",
+ "qmljsengine_p.cpp", "qmljsengine_p.h",
+ "qmljsglobal_p.h",
+ "qmljsgrammar.cpp", "qmljsgrammar_p.h",
+ "qmljskeywords_p.h",
+ "qmljslexer.cpp", "qmljslexer_p.h",
+ "qmljsmemorypool_p.h",
+ "qmljsparser.cpp", "qmljsparser_p.h",
+ ]
+ }
Export {
Depends { name: "LanguageUtils" }
}
}
-
diff --git a/src/libs/qmljs/qmljsbind.cpp b/src/libs/qmljs/qmljsbind.cpp
index 54b9a204f2..fd7c7c68cb 100644
--- a/src/libs/qmljs/qmljsbind.cpp
+++ b/src/libs/qmljs/qmljsbind.cpp
@@ -154,9 +154,9 @@ ObjectValue *Bind::bindObject(UiQualifiedId *qualifiedTypeNameId, UiObjectInitia
parentObjectValue = switchObjectValue(objectValue);
- if (parentObjectValue)
+ if (parentObjectValue) {
objectValue->setMember(QLatin1String("parent"), parentObjectValue);
- else if (!_rootObjectValue) {
+ } else if (!_rootObjectValue) {
_rootObjectValue = objectValue;
_rootObjectValue->setClassName(_doc->componentName());
}
@@ -201,10 +201,11 @@ bool Bind::visit(UiImport *ast)
_diagnosticMessages->append(
errorMessage(ast, tr("package import requires a version number")));
}
+ const QString importId = ast->importId.toString();
ImportInfo import = ImportInfo::moduleImport(toString(ast->importUri), version,
- ast->importId.toString(), ast);
+ importId, ast);
if (_doc->language() == Document::QmlLanguage) {
- QString importStr = import.name() + ast->importId.toString();
+ const QString importStr = import.name() + importId;
QmlLanguageBundles langBundles = ModelManagerInterface::instance()->extendedBundles();
QmlBundle qq1 = langBundles.bundleForLanguage(Document::QmlQtQuick1Language);
QmlBundle qq2 = langBundles.bundleForLanguage(Document::QmlQtQuick2Language);
diff --git a/src/libs/qmljs/qmljsbundle.cpp b/src/libs/qmljs/qmljsbundle.cpp
index 9f755f04be..8b2ff587b4 100644
--- a/src/libs/qmljs/qmljsbundle.cpp
+++ b/src/libs/qmljs/qmljsbundle.cpp
@@ -250,6 +250,8 @@ QStringList QmlBundle::maybeReadTrie(Trie &trie, Utils::JsonObjectValue *config,
bool QmlBundle::readFrom(QString path, QStringList *errors)
{
+ Utils::JsonMemoryPool pool;
+
using namespace Utils;
QFile f(path);
if (!f.open(QIODevice::ReadOnly | QIODevice::Text)) {
@@ -257,7 +259,7 @@ bool QmlBundle::readFrom(QString path, QStringList *errors)
(*errors) << QString::fromLatin1("Could not open file at %1 .").arg(path);
return false;
}
- JsonObjectValue *config = JsonValue::create(QString::fromUtf8(f.readAll()))->toObject();
+ JsonObjectValue *config = JsonValue::create(QString::fromUtf8(f.readAll()), &pool)->toObject();
if (config == 0) {
if (errors)
(*errors) << QString::fromLatin1("Could not parse json object in file at %1 .").arg(path);
diff --git a/src/libs/qmljs/qmljscheck.cpp b/src/libs/qmljs/qmljscheck.cpp
index 8d15508557..1122e53ca4 100644
--- a/src/libs/qmljs/qmljscheck.cpp
+++ b/src/libs/qmljs/qmljscheck.cpp
@@ -862,10 +862,11 @@ bool Check::visit(UiPublicMember *ast)
if (ast->type == UiPublicMember::Property) {
// check if the member type is valid
if (!ast->memberType.isEmpty()) {
- const QString &name = ast->memberType.toString();
+ const QStringRef name = ast->memberType;
if (!name.isEmpty() && name.at(0).isLower()) {
- if (!isValidBuiltinPropertyType(name))
- addMessage(ErrInvalidPropertyType, ast->typeToken, name);
+ const QString nameS = name.toString();
+ if (!isValidBuiltinPropertyType(nameS))
+ addMessage(ErrInvalidPropertyType, ast->typeToken, nameS);
}
// warn about dubious use of var/variant
diff --git a/src/libs/qmljs/qmljspropertyreader.cpp b/src/libs/qmljs/qmljspropertyreader.cpp
index 1942860bfa..82e3d69d8a 100644
--- a/src/libs/qmljs/qmljspropertyreader.cpp
+++ b/src/libs/qmljs/qmljspropertyreader.cpp
@@ -99,30 +99,6 @@ static inline QString textAt(const Document::Ptr doc,
return doc->source().mid(from.offset, to.end() - from.begin());
}
-static inline int propertyType(const QString &typeName)
-{
- if (typeName == QLatin1String("bool"))
- return QMetaType::type("bool");
- else if (typeName == QLatin1String("color"))
- return QMetaType::type("QColor");
- else if (typeName == QLatin1String("date"))
- return QMetaType::type("QDate");
- else if (typeName == QLatin1String("int"))
- return QMetaType::type("int");
- else if (typeName == QLatin1String("real"))
- return QMetaType::type("double");
- else if (typeName == QLatin1String("double"))
- return QMetaType::type("double");
- else if (typeName == QLatin1String("string"))
- return QMetaType::type("QString");
- else if (typeName == QLatin1String("url"))
- return QMetaType::type("QUrl");
- else if (typeName == QLatin1String("variant"))
- return QMetaType::type("QVariant");
- else
- return -1;
-}
-
static bool isEnum(AST::Statement *ast);
bool isEnum(AST::ExpressionNode *ast)
@@ -229,7 +205,7 @@ QLinearGradient PropertyReader::parseGradient(const QString &propertyName, bool
initializer->lbraceToken,
initializer->rbraceToken));
const QString objectPropertyName = objectBinding->qualifiedId->name.toString();
- const QString typeName = objectBinding->qualifiedTypeNameId->name.toString();
+ const QStringRef typeName = objectBinding->qualifiedTypeNameId->name;
if (objectPropertyName == propertyName && typeName.contains(QLatin1String("Gradient"))) {
QLinearGradient gradient;
QVector<QGradientStop> stops;
diff --git a/src/libs/qmljs/qmljsreformatter.cpp b/src/libs/qmljs/qmljsreformatter.cpp
index a9eede5e3e..b3d5d1e7d3 100644
--- a/src/libs/qmljs/qmljsreformatter.cpp
+++ b/src/libs/qmljs/qmljsreformatter.cpp
@@ -255,14 +255,13 @@ 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) {
+ } else if (line.size() > maxLineLength) {
result += 3 + (line.size() - maxLineLength);
- }
// and even ok-sized lines should have a cost
- else {
+ } else {
result += 1;
}
diff --git a/src/libs/qmljs/qmljsrewriter.cpp b/src/libs/qmljs/qmljsrewriter.cpp
index b4957f08a2..012bad73ee 100644
--- a/src/libs/qmljs/qmljsrewriter.cpp
+++ b/src/libs/qmljs/qmljsrewriter.cpp
@@ -282,9 +282,8 @@ void Rewriter::changeBinding(UiObjectInitializer *ast,
}
break;
- }
// for grouped properties:
- else if (!prefix.isEmpty()) {
+ } else if (!prefix.isEmpty()) {
if (UiObjectDefinition *def = cast<UiObjectDefinition *>(member)) {
if (toString(def->qualifiedTypeNameId) == prefix)
changeBinding(def->initializer, suffix, newValue, binding);
@@ -384,10 +383,10 @@ 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()) {
+ } else if (!prefix.isEmpty()) {
if (UiObjectDefinition *def = cast<UiObjectDefinition *>(member)) {
if (toString(def->qualifiedTypeNameId) == prefix)
removeGroupedProperty(def, propertyName);
diff --git a/src/libs/qmljs/qmljsscopebuilder.cpp b/src/libs/qmljs/qmljsscopebuilder.cpp
index a68e9e28f2..2178132498 100644
--- a/src/libs/qmljs/qmljsscopebuilder.cpp
+++ b/src/libs/qmljs/qmljsscopebuilder.cpp
@@ -80,10 +80,10 @@ 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)) {
+ } else if (const CppComponentValue *qmlObject = value_cast<CppComponentValue>(owner)) {
if (const ObjectValue *scope = qmlObject->signalScope(name))
_scopeChain->appendJsScope(scope);
}
diff --git a/src/libs/qtcomponents/styleitem/qstyleitem.cpp b/src/libs/qtcomponents/styleitem/qstyleitem.cpp
index d7f2333467..ecdde82d11 100644
--- a/src/libs/qtcomponents/styleitem/qstyleitem.cpp
+++ b/src/libs/qtcomponents/styleitem/qstyleitem.cpp
@@ -860,9 +860,8 @@ QRect QStyleItem::subControlRect(const QString &subcontrolString)
subcontrol = QStyle::SC_SpinBoxDown;
else if (subcontrolString == QLatin1String("up"))
subcontrol = QStyle::SC_SpinBoxUp;
- else if (subcontrolString == QLatin1String("edit")){
+ else if (subcontrolString == QLatin1String("edit"))
subcontrol = QStyle::SC_SpinBoxEditField;
- }
return qApp->style()->subControlRect(control,
qstyleoption_cast<QStyleOptionComplex*>(m_styleoption),
subcontrol, widget());
diff --git a/src/libs/qtcomponents/styleitem/qtmenu.cpp b/src/libs/qtcomponents/styleitem/qtmenu.cpp
index d7ddb363f5..872d581a5f 100644
--- a/src/libs/qtcomponents/styleitem/qtmenu.cpp
+++ b/src/libs/qtcomponents/styleitem/qtmenu.cpp
@@ -28,8 +28,9 @@
****************************************************************************/
#include "qtmenu.h"
-#include "qdebug.h"
-#include <qapplication.h>
+
+#include <QApplication>
+#include <QtDebug>
QtMenu::QtMenu(QObject *parent)
: QObject(parent)
diff --git a/src/libs/qtcomponents/styleitem/styleitem.qbs b/src/libs/qtcomponents/styleitem/styleitem.qbs
index b4b70c8445..f3c2c8ed22 100644
--- a/src/libs/qtcomponents/styleitem/styleitem.qbs
+++ b/src/libs/qtcomponents/styleitem/styleitem.qbs
@@ -1,5 +1,4 @@
import qbs.base 1.0
-import "../../../../qbs/defaults.js" as Defaults
DynamicLibrary {
name: "styleplugin"
@@ -7,7 +6,7 @@ DynamicLibrary {
Depends { name: "cpp" }
Depends { name: "Qt"; submodules: ["core", "widgets", "declarative", "script"] }
- cpp.defines: Defaults.defines(qbs)
+ cpp.defines: project.generalDefines
files: [
"qdeclarativefolderlistmodel.cpp",
diff --git a/src/libs/qtcreatorcdbext/common.cpp b/src/libs/qtcreatorcdbext/common.cpp
index a8263a0e28..5df465f128 100644
--- a/src/libs/qtcreatorcdbext/common.cpp
+++ b/src/libs/qtcreatorcdbext/common.cpp
@@ -73,7 +73,7 @@ std::string msgDebugEngineComResult(HRESULT hr)
return std::string("E_NOTIMPL");
}
if (hr == HRESULT_FROM_WIN32(ERROR_ACCESS_DENIED))
- return std::string("ERROR_ACCESS_DENIED");;
+ return std::string("ERROR_ACCESS_DENIED");
if (hr == HRESULT_FROM_NT(STATUS_CONTROL_C_EXIT))
return std::string("STATUS_CONTROL_C_EXIT");
return std::string("E_FAIL ") + winErrorMessage(HRESULT_CODE(hr));
diff --git a/src/libs/qtcreatorcdbext/eventcallback.cpp b/src/libs/qtcreatorcdbext/eventcallback.cpp
index e7ece0b859..ff261b5c96 100644
--- a/src/libs/qtcreatorcdbext/eventcallback.cpp
+++ b/src/libs/qtcreatorcdbext/eventcallback.cpp
@@ -32,7 +32,7 @@
#include "stringutils.h"
#include "gdbmihelpers.h"
-static const char eventContextC[] = "event";
+const char eventContextC[] = "event";
const static int winExceptionCppException = 0xe06d7363;
diff --git a/src/libs/ssh/sftpfilesystemmodel.cpp b/src/libs/ssh/sftpfilesystemmodel.cpp
index 1f79a2b99a..d4f7ead25f 100644
--- a/src/libs/ssh/sftpfilesystemmodel.cpp
+++ b/src/libs/ssh/sftpfilesystemmodel.cpp
@@ -113,7 +113,7 @@ SftpFileSystemModel::~SftpFileSystemModel()
void SftpFileSystemModel::setSshConnection(const SshConnectionParameters &sshParams)
{
QSSH_ASSERT_AND_RETURN(!d->sshConnection);
- d->sshConnection = SshConnectionManager::instance().acquireConnection(sshParams);
+ d->sshConnection = QSsh::acquireConnection(sshParams);
connect(d->sshConnection, SIGNAL(error(QSsh::SshError)), SLOT(handleSshConnectionFailure()));
if (d->sshConnection->state() == SshConnection::Connected) {
handleSshConnectionEstablished();
@@ -267,7 +267,7 @@ void SftpFileSystemModel::shutDown()
}
if (d->sshConnection) {
disconnect(d->sshConnection, 0, this, 0);
- SshConnectionManager::instance().releaseConnection(d->sshConnection);
+ QSsh::releaseConnection(d->sshConnection);
d->sshConnection = 0;
}
delete d->rootNode;
diff --git a/src/libs/ssh/ssh.pro b/src/libs/ssh/ssh.pro
index 80379d01b4..511d31b1cf 100644
--- a/src/libs/ssh/ssh.pro
+++ b/src/libs/ssh/ssh.pro
@@ -27,6 +27,7 @@ SOURCES = $$PWD/sshsendfacility.cpp \
$$PWD/sshkeypasswordretriever.cpp \
$$PWD/sftpfilesystemmodel.cpp \
$$PWD/sshkeycreationdialog.cpp \
+ $$PWD/sshinit.cpp \
$$PWD/sshdirecttcpiptunnel.cpp
HEADERS = $$PWD/sshsendfacility_p.h \
@@ -62,6 +63,7 @@ HEADERS = $$PWD/sshsendfacility_p.h \
$$PWD/sshkeycreationdialog.h \
$$PWD/ssh_global.h \
$$PWD/sshdirecttcpiptunnel_p.h \
+ $$PWD/sshinit_p.h \
$$PWD/sshdirecttcpiptunnel.h
FORMS = $$PWD/sshkeycreationdialog.ui
diff --git a/src/libs/ssh/ssh.qbs b/src/libs/ssh/ssh.qbs
index 1f60a5726a..2b1949927e 100644
--- a/src/libs/ssh/ssh.qbs
+++ b/src/libs/ssh/ssh.qbs
@@ -29,6 +29,7 @@ QtcLibrary {
"ssherrors.h",
"sshexception_p.h",
"sshincomingpacket_p.h", "sshincomingpacket.cpp",
+ "sshinit_p.h", "sshinit.cpp",
"sshkeycreationdialog.cpp", "sshkeycreationdialog.h", "sshkeycreationdialog.ui",
"sshkeyexchange.cpp", "sshkeyexchange_p.h",
"sshkeygenerator.cpp", "sshkeygenerator.h",
@@ -66,12 +67,14 @@ QtcLibrary {
}
property var botanDefines: {
var result = [];
- if (useSystemBotan)
+ if (useSystemBotan) {
result.push("USE_SYSTEM_BOTAN")
- else {
+ } else {
result.push("BOTAN_DLL=")
if (qbs.toolchain.contains("msvc"))
- result.push("BOTAN_BUILD_COMPILER_IS_MSVC", "BOTAN_TARGET_OS_HAS_GMTIME_S")
+ result.push("BOTAN_BUILD_COMPILER_IS_MSVC",
+ "BOTAN_TARGET_OS_HAS_GMTIME_S",
+ "_SCL_SECURE_NO_WARNINGS")
if (qbs.toolchain.contains("gcc") || qbs.toolchain.contains("mingw"))
result.push("BOTAN_BUILD_COMPILER_IS_GCC")
if (qbs.targetOS.contains("linux"))
diff --git a/src/libs/ssh/sshcapabilities.cpp b/src/libs/ssh/sshcapabilities.cpp
index c92af1ef63..635d9fd392 100644
--- a/src/libs/ssh/sshcapabilities.cpp
+++ b/src/libs/ssh/sshcapabilities.cpp
@@ -78,10 +78,6 @@ const QList<QByteArray> SshCapabilities::CompressionAlgorithms
const QByteArray SshCapabilities::SshConnectionService("ssh-connection");
-const QByteArray SshCapabilities::PublicKeyAuthMethod("publickey");
-const QByteArray SshCapabilities::PasswordAuthMethod("password");
-
-
QByteArray SshCapabilities::findBestMatch(const QList<QByteArray> &myCapabilities,
const QList<QByteArray> &serverCapabilities)
{
diff --git a/src/libs/ssh/sshcapabilities_p.h b/src/libs/ssh/sshcapabilities_p.h
index 97c2428beb..9355026c90 100644
--- a/src/libs/ssh/sshcapabilities_p.h
+++ b/src/libs/ssh/sshcapabilities_p.h
@@ -59,9 +59,6 @@ public:
static const QByteArray SshConnectionService;
- static const QByteArray PublicKeyAuthMethod;
- static const QByteArray PasswordAuthMethod;
-
static QByteArray findBestMatch(const QList<QByteArray> &myCapabilities,
const QList<QByteArray> &serverCapabilities);
};
diff --git a/src/libs/ssh/sshconnection.cpp b/src/libs/ssh/sshconnection.cpp
index 221025f1e9..f71b27e960 100644
--- a/src/libs/ssh/sshconnection.cpp
+++ b/src/libs/ssh/sshconnection.cpp
@@ -36,6 +36,7 @@
#include "sshcryptofacility_p.h"
#include "sshdirecttcpiptunnel.h"
#include "sshexception_p.h"
+#include "sshinit_p.h"
#include "sshkeyexchange_p.h"
#include "sshremoteprocess.h"
@@ -60,29 +61,10 @@
namespace QSsh {
-namespace {
- const QByteArray ClientId("SSH-2.0-QtCreator\r\n");
-
- bool staticInitializationsDone = false;
- QMutex staticInitMutex;
-
- void doStaticInitializationsIfNecessary()
- {
- QMutexLocker locker(&staticInitMutex);
- if (!staticInitializationsDone) {
- Botan::LibraryInitializer::initialize("thread_safe=true");
- qRegisterMetaType<QSsh::SshError>("QSsh::SshError");
- qRegisterMetaType<QSsh::SftpJobId>("QSsh::SftpJobId");
- qRegisterMetaType<QSsh::SftpFileInfo>("QSsh::SftpFileInfo");
- qRegisterMetaType<QList <QSsh::SftpFileInfo> >("QList<QSsh::SftpFileInfo>");
- staticInitializationsDone = true;
- }
- }
-} // anonymous namespace
-
+const QByteArray ClientId("SSH-2.0-QtCreator\r\n");
SshConnectionParameters::SshConnectionParameters() :
- timeout(0), authenticationType(AuthenticationByKey), port(0)
+ timeout(0), authenticationType(AuthenticationTypePublicKey), port(0)
{
options |= SshIgnoreDefaultProxy;
options |= SshEnableStrictConformanceChecks;
@@ -92,7 +74,7 @@ static inline bool equals(const SshConnectionParameters &p1, const SshConnection
{
return p1.host == p2.host && p1.userName == p2.userName
&& p1.authenticationType == p2.authenticationType
- && (p1.authenticationType == SshConnectionParameters::AuthenticationByPassword ?
+ && (p1.authenticationType == SshConnectionParameters::AuthenticationTypePassword ?
p1.password == p2.password : p1.privateKeyFile == p2.privateKeyFile)
&& p1.timeout == p2.timeout && p1.port == p2.port;
}
@@ -112,7 +94,11 @@ bool operator!=(const SshConnectionParameters &p1, const SshConnectionParameters
SshConnection::SshConnection(const SshConnectionParameters &serverInfo, QObject *parent)
: QObject(parent)
{
- doStaticInitializationsIfNecessary();
+ Internal::initSsh();
+ qRegisterMetaType<QSsh::SshError>("QSsh::SshError");
+ qRegisterMetaType<QSsh::SftpJobId>("QSsh::SftpJobId");
+ qRegisterMetaType<QSsh::SftpFileInfo>("QSsh::SftpFileInfo");
+ qRegisterMetaType<QList <QSsh::SftpFileInfo> >("QList<QSsh::SftpFileInfo>");
d = new Internal::SshConnectionPrivate(this, serverInfo);
connect(d, SIGNAL(connected()), this, SIGNAL(connected()),
@@ -256,8 +242,11 @@ void SshConnectionPrivate::setupPacketHandlers()
setupPacketHandler(SSH_MSG_SERVICE_ACCEPT,
StateList() << UserAuthServiceRequested,
&This::handleServiceAcceptPacket);
- setupPacketHandler(SSH_MSG_USERAUTH_PASSWD_CHANGEREQ,
- StateList() << UserAuthRequested, &This::handlePasswordExpiredPacket);
+ if (m_connParams.authenticationType == SshConnectionParameters::AuthenticationTypePassword
+ || m_connParams.authenticationType == SshConnectionParameters::AuthenticationTypeTryAllPasswordBasedMethods) {
+ setupPacketHandler(SSH_MSG_USERAUTH_PASSWD_CHANGEREQ,
+ StateList() << UserAuthRequested, &This::handlePasswordExpiredPacket);
+ }
setupPacketHandler(SSH_MSG_GLOBAL_REQUEST,
StateList() << ConnectionEstablished, &This::handleGlobalRequest);
@@ -268,6 +257,11 @@ void SshConnectionPrivate::setupPacketHandlers()
&This::handleUserAuthSuccessPacket);
setupPacketHandler(SSH_MSG_USERAUTH_FAILURE, authReqList,
&This::handleUserAuthFailurePacket);
+ if (m_connParams.authenticationType == SshConnectionParameters::AuthenticationTypeKeyboardInteractive
+ || m_connParams.authenticationType == SshConnectionParameters::AuthenticationTypeTryAllPasswordBasedMethods) {
+ setupPacketHandler(SSH_MSG_USERAUTH_INFO_REQUEST, authReqList,
+ &This::handleUserAuthInfoRequestPacket);
+ }
const StateList connectedList
= StateList() << ConnectionEstablished;
@@ -443,14 +437,13 @@ void SshConnectionPrivate::handleCurrentPacket()
QHash<SshPacketType, HandlerInStates>::ConstIterator it
= m_packetHandlers.find(m_incomingPacket.type());
- if (it == m_packetHandlers.end()) {
+ if (it == m_packetHandlers.constEnd()) {
m_sendFacility.sendMsgUnimplementedPacket(m_incomingPacket.serverSeqNr());
return;
}
if (!it.value().first.contains(m_state)) {
- throw SshServerException(SSH_DISCONNECT_PROTOCOL_ERROR,
- "Unexpected packet.", tr("Unexpected packet of type %1.")
- .arg(m_incomingPacket.type()));
+ handleUnexpectedPacket();
+ return;
}
(this->*it.value().second)();
}
@@ -513,31 +506,71 @@ void SshConnectionPrivate::handleNewKeysPacket()
void SshConnectionPrivate::handleServiceAcceptPacket()
{
- if (m_connParams.authenticationType == SshConnectionParameters::AuthenticationByPassword) {
- m_sendFacility.sendUserAuthByPwdRequestPacket(m_connParams.userName.toUtf8(),
- SshCapabilities::SshConnectionService, m_connParams.password.toUtf8());
- } else {
- m_sendFacility.sendUserAuthByKeyRequestPacket(m_connParams.userName.toUtf8(),
- SshCapabilities::SshConnectionService);
+ switch (m_connParams.authenticationType) {
+ case SshConnectionParameters::AuthenticationTypeTryAllPasswordBasedMethods:
+ m_triedAllPasswordBasedMethods = false;
+ // Fall-through.
+ case SshConnectionParameters::AuthenticationTypePassword:
+ m_sendFacility.sendUserAuthByPasswordRequestPacket(m_connParams.userName.toUtf8(),
+ SshCapabilities::SshConnectionService, m_connParams.password.toUtf8());
+ break;
+ case SshConnectionParameters::AuthenticationTypeKeyboardInteractive:
+ m_sendFacility.sendUserAuthByKeyboardInteractiveRequestPacket(m_connParams.userName.toUtf8(),
+ SshCapabilities::SshConnectionService);
+ break;
+ case SshConnectionParameters::AuthenticationTypePublicKey:
+ m_sendFacility.sendUserAuthByPublicKeyRequestPacket(m_connParams.userName.toUtf8(),
+ SshCapabilities::SshConnectionService);
+ break;
}
m_state = UserAuthRequested;
}
void SshConnectionPrivate::handlePasswordExpiredPacket()
{
- if (m_connParams.authenticationType == SshConnectionParameters::AuthenticationByKey) {
- throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
- "Got SSH_MSG_USERAUTH_PASSWD_CHANGEREQ, but did not use password.");
+ if (m_connParams.authenticationType == SshConnectionParameters::AuthenticationTypeTryAllPasswordBasedMethods
+ && m_triedAllPasswordBasedMethods) {
+ // This means we just tried to authorize via "keyboard-interactive", in which case
+ // this type of packet is not allowed.
+ handleUnexpectedPacket();
+ return;
}
-
throw SshClientException(SshAuthenticationError, tr("Password expired."));
}
+void SshConnectionPrivate::handleUserAuthInfoRequestPacket()
+{
+ if (m_connParams.authenticationType == SshConnectionParameters::AuthenticationTypeTryAllPasswordBasedMethods
+ && !m_triedAllPasswordBasedMethods) {
+ // This means we just tried to authorize via "password", in which case
+ // this type of packet is not allowed.
+ handleUnexpectedPacket();
+ return;
+ }
+
+ const SshUserAuthInfoRequestPacket requestPacket
+ = m_incomingPacket.extractUserAuthInfoRequest();
+ QStringList responses;
+ responses.reserve(requestPacket.prompts.count());
+
+ // Not very interactive, admittedly, but we don't want to be for now.
+ for (int i = 0; i < requestPacket.prompts.count(); ++i)
+ responses << m_connParams.password;
+ m_sendFacility.sendUserAuthInfoResponsePacket(responses);
+}
+
void SshConnectionPrivate::handleUserAuthBannerPacket()
{
emit dataAvailable(m_incomingPacket.extractUserAuthBanner().message);
}
+void SshConnectionPrivate::handleUnexpectedPacket()
+{
+ throw SshServerException(SSH_DISCONNECT_PROTOCOL_ERROR,
+ "Unexpected packet.", tr("Unexpected packet of type %1.")
+ .arg(m_incomingPacket.type()));
+}
+
void SshConnectionPrivate::handleGlobalRequest()
{
m_sendFacility.sendRequestFailurePacket();
@@ -555,9 +588,20 @@ void SshConnectionPrivate::handleUserAuthSuccessPacket()
void SshConnectionPrivate::handleUserAuthFailurePacket()
{
+ // TODO: Evaluate "authentications that can continue" field and act on it.
+ if (m_connParams.authenticationType
+ == SshConnectionParameters::AuthenticationTypeTryAllPasswordBasedMethods
+ && !m_triedAllPasswordBasedMethods) {
+ m_triedAllPasswordBasedMethods = true;
+ m_sendFacility.sendUserAuthByKeyboardInteractiveRequestPacket(
+ m_connParams.userName.toUtf8(),
+ SshCapabilities::SshConnectionService);
+ return;
+ }
+
m_timeoutTimer.stop();
- const QString errorMsg = m_connParams.authenticationType == SshConnectionParameters::AuthenticationByPassword
- ? tr("Server rejected password.") : tr("Server rejected key.");
+ const QString errorMsg = m_connParams.authenticationType == SshConnectionParameters::AuthenticationTypePublicKey
+ ? tr("Server rejected key.") : tr("Server rejected password.");
throw SshClientException(SshAuthenticationError, errorMsg);
}
void SshConnectionPrivate::handleDebugPacket()
@@ -699,7 +743,7 @@ void SshConnectionPrivate::connectToHost()
m_serverHasSentDataBeforeId = false;
try {
- if (m_connParams.authenticationType == SshConnectionParameters::AuthenticationByKey)
+ if (m_connParams.authenticationType == SshConnectionParameters::AuthenticationTypePublicKey)
createPrivateKey();
} catch (const SshClientException &ex) {
m_error = ex.error;
diff --git a/src/libs/ssh/sshconnection.h b/src/libs/ssh/sshconnection.h
index 9a70a02a0b..621ace3823 100644
--- a/src/libs/ssh/sshconnection.h
+++ b/src/libs/ssh/sshconnection.h
@@ -60,7 +60,15 @@ Q_DECLARE_FLAGS(SshConnectionOptions, SshConnectionOption)
class QSSH_EXPORT SshConnectionParameters
{
public:
- enum AuthenticationType { AuthenticationByPassword, AuthenticationByKey };
+ enum AuthenticationType {
+ AuthenticationTypePassword,
+ AuthenticationTypePublicKey,
+ AuthenticationTypeKeyboardInteractive,
+
+ // Some servers disable "password", others disable "keyboard-interactive".
+ AuthenticationTypeTryAllPasswordBasedMethods
+ };
+
SshConnectionParameters();
QString host;
diff --git a/src/libs/ssh/sshconnection_p.h b/src/libs/ssh/sshconnection_p.h
index 2c21a0556c..7c4e5bbbc3 100644
--- a/src/libs/ssh/sshconnection_p.h
+++ b/src/libs/ssh/sshconnection_p.h
@@ -116,9 +116,11 @@ private:
void handleNewKeysPacket();
void handleServiceAcceptPacket();
void handlePasswordExpiredPacket();
+ void handleUserAuthInfoRequestPacket();
void handleUserAuthSuccessPacket();
void handleUserAuthFailurePacket();
void handleUserAuthBannerPacket();
+ void handleUnexpectedPacket();
void handleGlobalRequest();
void handleDebugPacket();
void handleUnimplementedPacket();
@@ -168,6 +170,7 @@ private:
quint64 m_lastInvalidMsgSeqNr;
QByteArray m_serverId;
bool m_serverHasSentDataBeforeId;
+ bool m_triedAllPasswordBasedMethods;
};
} // namespace Internal
diff --git a/src/libs/ssh/sshconnectionmanager.cpp b/src/libs/ssh/sshconnectionmanager.cpp
index f1e1e4d45c..9431982898 100644
--- a/src/libs/ssh/sshconnectionmanager.cpp
+++ b/src/libs/ssh/sshconnectionmanager.cpp
@@ -41,25 +41,17 @@
namespace QSsh {
namespace Internal {
-class SshConnectionManagerPrivate : public QObject
+class SshConnectionManager : public QObject
{
Q_OBJECT
public:
-
- static QMutex instanceMutex;
- static SshConnectionManager &instance()
- {
- static SshConnectionManager manager;
- return manager;
- }
-
- SshConnectionManagerPrivate()
+ SshConnectionManager()
{
moveToThread(QCoreApplication::instance()->thread());
}
- ~SshConnectionManagerPrivate()
+ ~SshConnectionManager()
{
foreach (SshConnection * const connection, m_unacquiredConnections) {
disconnect(connection, 0, this, 0);
@@ -145,10 +137,7 @@ public:
}
}
if (!haveConnection) {
- // Let's nag clients who release connections with open channels.
- const int channelCount = connection->closeAllChannels();
- QSSH_ASSERT(channelCount == 0);
-
+ connection->closeAllChannels(); // Clean up after neglectful clients.
m_unacquiredConnections.append(connection);
} else {
doDelete = true;
@@ -218,38 +207,32 @@ private:
QMutex m_listMutex;
};
-QMutex SshConnectionManagerPrivate::instanceMutex;
-
} // namespace Internal
-SshConnectionManager &SshConnectionManager::instance()
-{
- QMutexLocker locker(&Internal::SshConnectionManagerPrivate::instanceMutex);
- return Internal::SshConnectionManagerPrivate::instance();
-}
-
-SshConnectionManager::SshConnectionManager()
- : d(new Internal::SshConnectionManagerPrivate)
-{
-}
+static QMutex instanceMutex;
-SshConnectionManager::~SshConnectionManager()
+static Internal::SshConnectionManager &instance()
{
+ static Internal::SshConnectionManager manager;
+ return manager;
}
-SshConnection *SshConnectionManager::acquireConnection(const SshConnectionParameters &sshParams)
+SshConnection *acquireConnection(const SshConnectionParameters &sshParams)
{
- return d->acquireConnection(sshParams);
+ QMutexLocker locker(&instanceMutex);
+ return instance().acquireConnection(sshParams);
}
-void SshConnectionManager::releaseConnection(SshConnection *connection)
+void releaseConnection(SshConnection *connection)
{
- d->releaseConnection(connection);
+ QMutexLocker locker(&instanceMutex);
+ instance().releaseConnection(connection);
}
-void SshConnectionManager::forceNewConnection(const SshConnectionParameters &sshParams)
+void forceNewConnection(const SshConnectionParameters &sshParams)
{
- d->forceNewConnection(sshParams);
+ QMutexLocker locker(&instanceMutex);
+ instance().forceNewConnection(sshParams);
}
} // namespace QSsh
diff --git a/src/libs/ssh/sshconnectionmanager.h b/src/libs/ssh/sshconnectionmanager.h
index a38e4c7ba8..65dab048a4 100644
--- a/src/libs/ssh/sshconnectionmanager.h
+++ b/src/libs/ssh/sshconnectionmanager.h
@@ -32,32 +32,16 @@
#include "ssh_global.h"
-#include <QScopedPointer>
-
namespace QSsh {
+
class SshConnection;
class SshConnectionParameters;
-namespace Internal { class SshConnectionManagerPrivate; }
-
-class QSSH_EXPORT SshConnectionManager
-{
- friend class Internal::SshConnectionManagerPrivate;
-public:
- static SshConnectionManager &instance();
-
- SshConnection *acquireConnection(const SshConnectionParameters &sshParams);
- void releaseConnection(SshConnection *connection);
- // Make sure the next acquireConnection with the given parameters will return a new connection.
- void forceNewConnection(const SshConnectionParameters &sshParams);
-private:
- explicit SshConnectionManager();
- virtual ~SshConnectionManager();
- SshConnectionManager(const SshConnectionManager &);
- SshConnectionManager &operator=(const SshConnectionManager &);
+QSSH_EXPORT SshConnection *acquireConnection(const SshConnectionParameters &sshParams);
+QSSH_EXPORT void releaseConnection(SshConnection *connection);
- const QScopedPointer<Internal::SshConnectionManagerPrivate> d;
-};
+// Make sure the next acquireConnection with the given parameters will return a new connection.
+QSSH_EXPORT void forceNewConnection(const SshConnectionParameters &sshParams);
} // namespace QSsh
diff --git a/src/libs/ssh/sshincomingpacket.cpp b/src/libs/ssh/sshincomingpacket.cpp
index af0f20bd1e..c2cdb7b630 100644
--- a/src/libs/ssh/sshincomingpacket.cpp
+++ b/src/libs/ssh/sshincomingpacket.cpp
@@ -242,6 +242,31 @@ SshUserAuthBanner SshIncomingPacket::extractUserAuthBanner() const
}
}
+SshUserAuthInfoRequestPacket SshIncomingPacket::extractUserAuthInfoRequest() const
+{
+ Q_ASSERT(isComplete());
+ Q_ASSERT(type() == SSH_MSG_USERAUTH_INFO_REQUEST);
+
+ try {
+ SshUserAuthInfoRequestPacket msg;
+ quint32 offset = TypeOffset + 1;
+ msg.name = SshPacketParser::asUserString(m_data, &offset);
+ msg.instruction = SshPacketParser::asUserString(m_data, &offset);
+ msg.languageTag = SshPacketParser::asString(m_data, &offset);
+ const quint32 promptCount = SshPacketParser::asUint32(m_data, &offset);
+ msg.prompts.reserve(promptCount);
+ msg.echos.reserve(promptCount);
+ for (quint32 i = 0; i < promptCount; ++i) {
+ msg.prompts << SshPacketParser::asUserString(m_data, &offset);
+ msg.echos << SshPacketParser::asBool(m_data, &offset);
+ }
+ return msg;
+ } catch (SshPacketParseException &) {
+ throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
+ "Invalid SSH_MSG_USERAUTH_INFO_REQUEST.");
+ }
+}
+
SshDebug SshIncomingPacket::extractDebug() const
{
Q_ASSERT(isComplete());
diff --git a/src/libs/ssh/sshincomingpacket_p.h b/src/libs/ssh/sshincomingpacket_p.h
index 6080e52e83..6469a7a4df 100644
--- a/src/libs/ssh/sshincomingpacket_p.h
+++ b/src/libs/ssh/sshincomingpacket_p.h
@@ -35,8 +35,7 @@
#include "sshcryptofacility_p.h"
#include "sshpacketparser_p.h"
-#include <QList>
-#include <QString>
+#include <QStringList>
namespace QSsh {
namespace Internal {
@@ -80,6 +79,15 @@ struct SshUserAuthBanner
QByteArray language;
};
+struct SshUserAuthInfoRequestPacket
+{
+ QString name;
+ QString instruction;
+ QByteArray languageTag;
+ QStringList prompts;
+ QList<bool> echos;
+};
+
struct SshDebug
{
bool display;
@@ -156,6 +164,7 @@ public:
SshKeyExchangeReply extractKeyExchangeReply(const QByteArray &pubKeyAlgo) const;
SshDisconnect extractDisconnect() const;
SshUserAuthBanner extractUserAuthBanner() const;
+ SshUserAuthInfoRequestPacket extractUserAuthInfoRequest() const;
SshDebug extractDebug() const;
SshUnimplemented extractUnimplemented() const;
diff --git a/src/libs/ssh/sshinit.cpp b/src/libs/ssh/sshinit.cpp
new file mode 100644
index 0000000000..c1d4f4ae38
--- /dev/null
+++ b/src/libs/ssh/sshinit.cpp
@@ -0,0 +1,52 @@
+/****************************************************************************
+**
+** 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 "sshinit_p.h"
+
+#include <botan/botan.h>
+
+#include <QMutex>
+#include <QMutexLocker>
+
+namespace QSsh {
+namespace Internal {
+
+static bool initialized = false;
+static QMutex initMutex;
+
+void initSsh()
+{
+ QMutexLocker locker(&initMutex);
+ if (!initialized) {
+ Botan::LibraryInitializer::initialize("thread_safe=true");
+ initialized = true;
+ }
+}
+
+} // namespace Internal
+} // namespace QSsh
diff --git a/src/plugins/debugger/gdb/abstractgdbprocess.cpp b/src/libs/ssh/sshinit_p.h
index ad9286826f..af8126803d 100644
--- a/src/plugins/debugger/gdb/abstractgdbprocess.cpp
+++ b/src/libs/ssh/sshinit_p.h
@@ -27,10 +27,10 @@
**
****************************************************************************/
-#include "abstractgdbprocess.h"
-
-namespace Debugger {
+namespace QSsh {
namespace Internal {
+void initSsh();
+
} // namespace Internal
-} // namespace Debugger
+} // namespace QSsh
diff --git a/src/libs/ssh/sshkeygenerator.cpp b/src/libs/ssh/sshkeygenerator.cpp
index 992cef1607..395057ae78 100644
--- a/src/libs/ssh/sshkeygenerator.cpp
+++ b/src/libs/ssh/sshkeygenerator.cpp
@@ -31,6 +31,7 @@
#include "sshbotanconversions_p.h"
#include "sshcapabilities_p.h"
+#include "sshinit_p.h"
#include "sshpacket_p.h"
#include <botan/botan.h>
@@ -47,6 +48,7 @@ using namespace Internal;
SshKeyGenerator::SshKeyGenerator() : m_type(Rsa)
{
+ initSsh();
}
bool SshKeyGenerator::generateKeys(KeyType type, PrivateKeyFormat format, int keySize,
diff --git a/src/libs/ssh/sshoutgoingpacket.cpp b/src/libs/ssh/sshoutgoingpacket.cpp
index d1c654a4a4..b4e772973e 100644
--- a/src/libs/ssh/sshoutgoingpacket.cpp
+++ b/src/libs/ssh/sshoutgoingpacket.cpp
@@ -103,7 +103,7 @@ void SshOutgoingPacket::generateServiceRequest(const QByteArray &service)
init(SSH_MSG_SERVICE_REQUEST).appendString(service).finalize();
}
-void SshOutgoingPacket::generateUserAuthByPwdRequestPacket(const QByteArray &user,
+void SshOutgoingPacket::generateUserAuthByPasswordRequestPacket(const QByteArray &user,
const QByteArray &service, const QByteArray &pwd)
{
init(SSH_MSG_USERAUTH_REQUEST).appendString(user).appendString(service)
@@ -111,7 +111,7 @@ void SshOutgoingPacket::generateUserAuthByPwdRequestPacket(const QByteArray &use
.finalize();
}
-void SshOutgoingPacket::generateUserAuthByKeyRequestPacket(const QByteArray &user,
+void SshOutgoingPacket::generateUserAuthByPublicKeyRequestPacket(const QByteArray &user,
const QByteArray &service)
{
init(SSH_MSG_USERAUTH_REQUEST).appendString(user).appendString(service)
@@ -123,6 +123,26 @@ void SshOutgoingPacket::generateUserAuthByKeyRequestPacket(const QByteArray &use
finalize();
}
+void SshOutgoingPacket::generateUserAuthByKeyboardInteractiveRequestPacket(const QByteArray &user,
+ const QByteArray &service)
+{
+ // RFC 4256, 3.1
+ init(SSH_MSG_USERAUTH_REQUEST).appendString(user).appendString(service)
+ .appendString("keyboard-interactive")
+ .appendString(QByteArray()) // Language tag. Deprecated and should be empty
+ .appendString(QByteArray()) // Submethods.
+ .finalize();
+}
+
+void SshOutgoingPacket::generateUserAuthInfoResponsePacket(const QStringList &responses)
+{
+ // RFC 4256, 3.4
+ init(SSH_MSG_USERAUTH_INFO_RESPONSE).appendInt(responses.count());
+ foreach (const QString &response, responses)
+ appendString(response.toUtf8());
+ finalize();
+}
+
void SshOutgoingPacket::generateRequestFailurePacket()
{
init(SSH_MSG_REQUEST_FAILURE).finalize();
diff --git a/src/libs/ssh/sshoutgoingpacket_p.h b/src/libs/ssh/sshoutgoingpacket_p.h
index 03f54cb76d..6f3de1c347 100644
--- a/src/libs/ssh/sshoutgoingpacket_p.h
+++ b/src/libs/ssh/sshoutgoingpacket_p.h
@@ -34,6 +34,8 @@
#include "sshpseudoterminal.h"
+#include <QStringList>
+
namespace QSsh {
namespace Internal {
@@ -52,10 +54,13 @@ public:
const QByteArray &reasonString);
void generateMsgUnimplementedPacket(quint32 serverSeqNr);
void generateUserAuthServiceRequestPacket();
- void generateUserAuthByPwdRequestPacket(const QByteArray &user,
+ void generateUserAuthByPasswordRequestPacket(const QByteArray &user,
const QByteArray &service, const QByteArray &pwd);
- void generateUserAuthByKeyRequestPacket(const QByteArray &user,
+ void generateUserAuthByPublicKeyRequestPacket(const QByteArray &user,
+ const QByteArray &service);
+ void generateUserAuthByKeyboardInteractiveRequestPacket(const QByteArray &user,
const QByteArray &service);
+ void generateUserAuthInfoResponsePacket(const QStringList &responses);
void generateRequestFailurePacket();
void generateIgnorePacket();
void generateInvalidMessagePacket();
diff --git a/src/libs/ssh/sshpacket_p.h b/src/libs/ssh/sshpacket_p.h
index ab1ac47b00..d97979a020 100644
--- a/src/libs/ssh/sshpacket_p.h
+++ b/src/libs/ssh/sshpacket_p.h
@@ -60,6 +60,8 @@ enum SshPacketType {
SSH_MSG_USERAUTH_BANNER = 53,
SSH_MSG_USERAUTH_PK_OK = 60,
SSH_MSG_USERAUTH_PASSWD_CHANGEREQ = 60,
+ SSH_MSG_USERAUTH_INFO_REQUEST = 60,
+ SSH_MSG_USERAUTH_INFO_RESPONSE = 61,
SSH_MSG_GLOBAL_REQUEST = 80,
SSH_MSG_REQUEST_SUCCESS = 81,
diff --git a/src/libs/ssh/sshremoteprocess.cpp b/src/libs/ssh/sshremoteprocess.cpp
index ec40f9c6f3..6602b3c1df 100644
--- a/src/libs/ssh/sshremoteprocess.cpp
+++ b/src/libs/ssh/sshremoteprocess.cpp
@@ -176,6 +176,11 @@ void SshRemoteProcess::addToEnvironment(const QByteArray &var, const QByteArray
d->m_env << qMakePair(var, value); // Cached locally and sent on start()
}
+void SshRemoteProcess::clearEnvironment()
+{
+ d->m_env.clear();
+}
+
void SshRemoteProcess::requestTerminal(const SshPseudoTerminal &terminal)
{
QSSH_ASSERT_AND_RETURN(d->channelState() == Internal::SshRemoteProcessPrivate::Inactive);
diff --git a/src/libs/ssh/sshremoteprocess.h b/src/libs/ssh/sshremoteprocess.h
index a50a3f0f2f..40c7db7790 100644
--- a/src/libs/ssh/sshremoteprocess.h
+++ b/src/libs/ssh/sshremoteprocess.h
@@ -80,6 +80,7 @@ public:
* usually configured to ignore such requests for security reasons.
*/
void addToEnvironment(const QByteArray &var, const QByteArray &value);
+ void clearEnvironment();
void requestTerminal(const SshPseudoTerminal &terminal);
void start();
diff --git a/src/libs/ssh/sshremoteprocessrunner.cpp b/src/libs/ssh/sshremoteprocessrunner.cpp
index 159f5e9f77..8714502c25 100644
--- a/src/libs/ssh/sshremoteprocessrunner.cpp
+++ b/src/libs/ssh/sshremoteprocessrunner.cpp
@@ -111,7 +111,7 @@ void SshRemoteProcessRunner::runInternal(const QByteArray &command,
d->m_exitSignal = SshRemoteProcess::NoSignal;
d->m_exitCode = -1;
d->m_command = command;
- d->m_connection = SshConnectionManager::instance().acquireConnection(sshParams);
+ d->m_connection = QSsh::acquireConnection(sshParams);
connect(d->m_connection, SIGNAL(error(QSsh::SshError)),
SLOT(handleConnectionError(QSsh::SshError)));
connect(d->m_connection, SIGNAL(disconnected()), SLOT(handleDisconnected()));
@@ -211,7 +211,7 @@ void SshRemoteProcessRunner::setState(int newState)
}
if (d->m_connection) {
disconnect(d->m_connection, 0, this, 0);
- SshConnectionManager::instance().releaseConnection(d->m_connection);
+ QSsh::releaseConnection(d->m_connection);
d->m_connection = 0;
}
}
diff --git a/src/libs/ssh/sshsendfacility.cpp b/src/libs/ssh/sshsendfacility.cpp
index 8b600009e4..572ab30482 100644
--- a/src/libs/ssh/sshsendfacility.cpp
+++ b/src/libs/ssh/sshsendfacility.cpp
@@ -109,17 +109,30 @@ void SshSendFacility::sendUserAuthServiceRequestPacket()
sendPacket();
}
-void SshSendFacility::sendUserAuthByPwdRequestPacket(const QByteArray &user,
+void SshSendFacility::sendUserAuthByPasswordRequestPacket(const QByteArray &user,
const QByteArray &service, const QByteArray &pwd)
{
- m_outgoingPacket.generateUserAuthByPwdRequestPacket(user, service, pwd);
+ m_outgoingPacket.generateUserAuthByPasswordRequestPacket(user, service, pwd);
sendPacket();
}
-void SshSendFacility::sendUserAuthByKeyRequestPacket(const QByteArray &user,
+void SshSendFacility::sendUserAuthByPublicKeyRequestPacket(const QByteArray &user,
const QByteArray &service)
{
- m_outgoingPacket.generateUserAuthByKeyRequestPacket(user, service);
+ m_outgoingPacket.generateUserAuthByPublicKeyRequestPacket(user, service);
+ sendPacket();
+}
+
+void SshSendFacility::sendUserAuthByKeyboardInteractiveRequestPacket(const QByteArray &user,
+ const QByteArray &service)
+{
+ m_outgoingPacket.generateUserAuthByKeyboardInteractiveRequestPacket(user, service);
+ sendPacket();
+}
+
+void SshSendFacility::sendUserAuthInfoResponsePacket(const QStringList &responses)
+{
+ m_outgoingPacket.generateUserAuthInfoResponsePacket(responses);
sendPacket();
}
diff --git a/src/libs/ssh/sshsendfacility_p.h b/src/libs/ssh/sshsendfacility_p.h
index 9f58168bc2..2b65d24bb7 100644
--- a/src/libs/ssh/sshsendfacility_p.h
+++ b/src/libs/ssh/sshsendfacility_p.h
@@ -33,6 +33,8 @@
#include "sshcryptofacility_p.h"
#include "sshoutgoingpacket_p.h"
+#include <QStringList>
+
QT_BEGIN_NAMESPACE
class QTcpSocket;
QT_END_NAMESPACE
@@ -59,10 +61,13 @@ public:
const QByteArray &reasonString);
void sendMsgUnimplementedPacket(quint32 serverSeqNr);
void sendUserAuthServiceRequestPacket();
- void sendUserAuthByPwdRequestPacket(const QByteArray &user,
+ void sendUserAuthByPasswordRequestPacket(const QByteArray &user,
const QByteArray &service, const QByteArray &pwd);
- void sendUserAuthByKeyRequestPacket(const QByteArray &user,
+ void sendUserAuthByPublicKeyRequestPacket(const QByteArray &user,
+ const QByteArray &service);
+ void sendUserAuthByKeyboardInteractiveRequestPacket(const QByteArray &user,
const QByteArray &service);
+ void sendUserAuthInfoResponsePacket(const QStringList &responses);
void sendRequestFailurePacket();
void sendIgnorePacket();
void sendInvalidPacket();
diff --git a/src/libs/utils/ansiescapecodehandler.cpp b/src/libs/utils/ansiescapecodehandler.cpp
new file mode 100644
index 0000000000..ecb2285dc5
--- /dev/null
+++ b/src/libs/utils/ansiescapecodehandler.cpp
@@ -0,0 +1,205 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Petar Perisin <petar.perisin@gmail.com>
+** 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 "ansiescapecodehandler.h"
+#include <utils/qtcassert.h>
+
+namespace Utils {
+
+/*!
+ \class Utils::AnsiEscapeCodeHandler
+
+ \brief The AnsiEscapeCodeHandler class parses text and extracts ANSI escape codes from it.
+
+ In order to preserve color information across text segments, an instance of this class
+ must be stored for the lifetime of a stream.
+ Also, one instance of this class should not handle multiple streams (at least not
+ at the same time).
+
+ Its main method is parseText(), which accepts text and default QTextCharFormat.
+ This method is designed to parse text and split colored text to smaller strings,
+ with their appropriate formatting information set inside QTextCharFormat.
+
+ Usage:
+ \list
+ \li Create new instance of AnsiEscapeCodeHandler for a stream.
+ \li To add new text, call parseText() with the text and a default QTextCharFormat.
+ The result of this method is a list of strings with formats set in appropriate
+ QTextCharFormat.
+ \endlist
+*/
+
+AnsiEscapeCodeHandler::AnsiEscapeCodeHandler() :
+ m_previousFormatClosed(true)
+{
+}
+
+static QColor ansiColor(uint code)
+{
+ QTC_ASSERT(code < 8, return QColor());
+
+ const int red = code & 1 ? 170 : 0;
+ const int green = code & 2 ? 170 : 0;
+ const int blue = code & 4 ? 170 : 0;
+ return QColor(red, green, blue);
+}
+
+QList<StringFormatPair> AnsiEscapeCodeHandler::parseText(const QString &text,
+ const QTextCharFormat &defaultFormat)
+{
+ QList<StringFormatPair> outputData;
+
+ QTextCharFormat charFormat = m_previousFormatClosed ? defaultFormat : m_previousFormat;
+
+ const QString escape = QLatin1String("\x1b[");
+ if (!text.contains(escape)) {
+ outputData << StringFormatPair(text, charFormat);
+ return outputData;
+ } else if (!text.startsWith(escape)) {
+ outputData << StringFormatPair(text.left(text.indexOf(escape)), charFormat);
+ }
+
+ const QChar semicolon = QLatin1Char(';');
+ const QChar colorTerminator = QLatin1Char('m');
+ // strippedText always starts with "\e["
+ QString strippedText = text.mid(text.indexOf(escape));
+ while (!strippedText.isEmpty()) {
+ while (strippedText.startsWith(escape)) {
+ strippedText.remove(0, 2);
+
+ // get the number
+ QString strNumber;
+ QStringList numbers;
+ while (strippedText.at(0).isDigit() || strippedText.at(0) == semicolon) {
+ if (strippedText.at(0).isDigit()) {
+ strNumber += strippedText.at(0);
+ } else {
+ numbers << strNumber;
+ strNumber.clear();
+ }
+ strippedText.remove(0, 1);
+ }
+ if (!strNumber.isEmpty())
+ numbers << strNumber;
+
+ // remove terminating char
+ if (!strippedText.startsWith(colorTerminator)) {
+ strippedText.remove(0, 1);
+ continue;
+ }
+ strippedText.remove(0, 1);
+
+ if (numbers.isEmpty()) {
+ charFormat = defaultFormat;
+ endFormatScope();
+ }
+
+ for (int i = 0; i < numbers.size(); ++i) {
+ const int code = numbers.at(i).toInt();
+
+ if (code >= TextColorStart && code <= TextColorEnd) {
+ charFormat.setForeground(ansiColor(code - TextColorStart));
+ setFormatScope(charFormat);
+ } else if (code >= BackgroundColorStart && code <= BackgroundColorEnd) {
+ charFormat.setBackground(ansiColor(code - BackgroundColorStart));
+ setFormatScope(charFormat);
+ } else {
+ switch (code) {
+ case ResetFormat:
+ charFormat = defaultFormat;
+ endFormatScope();
+ break;
+ case BoldText:
+ charFormat.setFontWeight(QFont::Bold);
+ setFormatScope(charFormat);
+ break;
+ case DefaultTextColor:
+ charFormat.setForeground(defaultFormat.foreground());
+ setFormatScope(charFormat);
+ break;
+ case DefaultBackgroundColor:
+ charFormat.setBackground(defaultFormat.background());
+ setFormatScope(charFormat);
+ break;
+ case RgbTextColor:
+ case RgbBackgroundColor:
+ if (++i >= numbers.size())
+ break;
+ if (numbers.at(i).toInt() == 2) {
+ // RGB set with format: 38;2;<r>;<g>;<b>
+ if ((i + 3) < numbers.size()) {
+ (code == RgbTextColor) ?
+ charFormat.setForeground(QColor(numbers.at(i + 1).toInt(),
+ numbers.at(i + 2).toInt(),
+ numbers.at(i + 3).toInt())) :
+ charFormat.setBackground(QColor(numbers.at(i + 1).toInt(),
+ numbers.at(i + 2).toInt(),
+ numbers.at(i + 3).toInt()));
+ setFormatScope(charFormat);
+ }
+ i += 3;
+ } else if (numbers.at(i).toInt() == 5) {
+ // rgb set with format: 38;5;<i>
+ // unsupported because of unclear documentation, so we just skip <i>
+ ++i;
+ }
+ break;
+ default:
+ break;
+ }
+ }
+ }
+ }
+
+ if (strippedText.isEmpty())
+ break;
+ int index = strippedText.indexOf(escape);
+ if (index > 0) {
+ outputData << StringFormatPair(strippedText.left(index), charFormat);
+ strippedText.remove(0, index);
+ } else if (index == -1) {
+ outputData << StringFormatPair(strippedText, charFormat);
+ break;
+ }
+ }
+ return outputData;
+}
+
+void AnsiEscapeCodeHandler::endFormatScope()
+{
+ m_previousFormatClosed = true;
+}
+
+void AnsiEscapeCodeHandler::setFormatScope(const QTextCharFormat &charFormat)
+{
+ m_previousFormat = charFormat;
+ m_previousFormatClosed = false;
+}
+
+} // namespace Utils
diff --git a/src/libs/utils/ansiescapecodehandler.h b/src/libs/utils/ansiescapecodehandler.h
new file mode 100644
index 0000000000..d68490c58e
--- /dev/null
+++ b/src/libs/utils/ansiescapecodehandler.h
@@ -0,0 +1,72 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Petar Perisin <petar.perisin@gmail.com>
+** 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 UTILS_ANSIESCAPECODEHANDLER_H
+#define UTILS_ANSIESCAPECODEHANDLER_H
+
+#include "utils_global.h"
+
+#include <QTextCharFormat>
+
+namespace Utils {
+
+typedef QPair<QString, QTextCharFormat> StringFormatPair;
+
+class QTCREATOR_UTILS_EXPORT AnsiEscapeCodeHandler
+{
+
+enum AnsiEscapeCodes {
+ ResetFormat = 0,
+ BoldText = 1,
+ TextColorStart = 30,
+ TextColorEnd = 37,
+ RgbTextColor = 38,
+ DefaultTextColor = 39,
+ BackgroundColorStart = 40,
+ BackgroundColorEnd = 47,
+ RgbBackgroundColor = 48,
+ DefaultBackgroundColor = 49
+};
+
+public:
+ AnsiEscapeCodeHandler();
+ QList<StringFormatPair> parseText(const QString &text, const QTextCharFormat &defaultFormat);
+ void endFormatScope();
+
+private:
+ void setFormatScope(const QTextCharFormat &charFormat);
+
+ bool m_previousFormatClosed;
+ QTextCharFormat m_previousFormat;
+};
+
+} // namespace Utils
+
+#endif // UTILS_ANSIESCAPECODEHANDLER_H
diff --git a/src/libs/utils/basetreeview.cpp b/src/libs/utils/basetreeview.cpp
index fd3f35e35a..6e178e5c4d 100644
--- a/src/libs/utils/basetreeview.cpp
+++ b/src/libs/utils/basetreeview.cpp
@@ -40,7 +40,7 @@ namespace Utils {
class BaseTreeViewDelegate : public QItemDelegate
{
public:
- BaseTreeViewDelegate() {}
+ BaseTreeViewDelegate(QObject *parent): QItemDelegate(parent) {}
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,
const QModelIndex &index) const
@@ -64,7 +64,7 @@ BaseTreeView::BaseTreeView(QWidget *parent)
setIconSize(QSize(10, 10));
setSelectionMode(QAbstractItemView::ExtendedSelection);
setUniformRowHeights(true);
- setItemDelegate(new BaseTreeViewDelegate);
+ setItemDelegate(new BaseTreeViewDelegate(this));
header()->setDefaultAlignment(Qt::AlignLeft);
header()->setClickable(true);
diff --git a/src/libs/utils/buildablehelperlibrary.cpp b/src/libs/utils/buildablehelperlibrary.cpp
index 670624a20c..492da529e4 100644
--- a/src/libs/utils/buildablehelperlibrary.cpp
+++ b/src/libs/utils/buildablehelperlibrary.cpp
@@ -37,6 +37,32 @@
namespace Utils {
+bool BuildableHelperLibrary::isQtChooser(const QFileInfo &info)
+{
+ return info.isSymLink() && info.symLinkTarget().endsWith(QLatin1String("/qtchooser"));
+}
+
+QString BuildableHelperLibrary::qtChooserToQmakePath(const QString &path)
+{
+ QProcess proc;
+ proc.start(path, QStringList(QLatin1String("-print-env")));
+ if (!proc.waitForStarted(1000))
+ return QString();
+ if (!proc.waitForFinished(1000))
+ return QString();
+ QByteArray output = proc.readAllStandardOutput();
+ int pos = output.indexOf("QTTOOLDIR=");
+ if (pos == -1)
+ return QString();
+ pos += strlen("QTTOOLDIR=\"");
+ int end = output.indexOf('\"', pos);
+ if (end == -1)
+ return QString();
+
+ QString result = QString::fromLocal8Bit(output.mid(pos, end - pos)) + QLatin1String("/qmake");
+ return result;
+}
+
Utils::FileName BuildableHelperLibrary::findSystemQt(const Utils::Environment &env)
{
QStringList paths = env.path();
@@ -45,8 +71,11 @@ Utils::FileName BuildableHelperLibrary::findSystemQt(const Utils::Environment &e
if (!prefix.endsWith(QLatin1Char('/')))
prefix.append(QLatin1Char('/'));
foreach (const QString &possibleCommand, possibleQMakeCommands()) {
- const QFileInfo qmake(prefix + possibleCommand);
+ QFileInfo qmake(prefix + possibleCommand);
if (qmake.exists()) {
+ if (isQtChooser(qmake))
+ qmake.setFile(qtChooserToQmakePath(qmake.symLinkTarget()));
+
if (!qtVersionForQMake(qmake.absoluteFilePath()).isNull())
return Utils::FileName(qmake);
}
diff --git a/src/libs/utils/buildablehelperlibrary.h b/src/libs/utils/buildablehelperlibrary.h
index 2fb4ba2c3e..dd68373edd 100644
--- a/src/libs/utils/buildablehelperlibrary.h
+++ b/src/libs/utils/buildablehelperlibrary.h
@@ -43,6 +43,8 @@ public:
// returns the full path to the first qmake, qmake-qt4, qmake4 that has
// at least version 2.0.0 and thus is a qt4 qmake
static FileName findSystemQt(const Utils::Environment &env);
+ static bool isQtChooser(const QFileInfo &info);
+ static QString qtChooserToQmakePath(const QString &path);
// return true if the qmake at qmakePath is qt4 (used by QtVersion)
static QString qtVersionForQMake(const QString &qmakePath);
static QString qtVersionForQMake(const QString &qmakePath, bool *qmakeIsExecutable);
diff --git a/src/libs/utils/checkablemessagebox.cpp b/src/libs/utils/checkablemessagebox.cpp
index 5b455e19d9..3d6523a09b 100644
--- a/src/libs/utils/checkablemessagebox.cpp
+++ b/src/libs/utils/checkablemessagebox.cpp
@@ -256,6 +256,28 @@ CheckableMessageBox::question(QWidget *parent,
return mb.clickedStandardButton();
}
+QDialogButtonBox::StandardButton
+CheckableMessageBox::information(QWidget *parent,
+ const QString &title,
+ const QString &text,
+ const QString &checkBoxText,
+ bool *checkBoxSetting,
+ QDialogButtonBox::StandardButtons buttons,
+ QDialogButtonBox::StandardButton defaultButton)
+{
+ CheckableMessageBox mb(parent);
+ mb.setWindowTitle(title);
+ mb.setIconPixmap(QMessageBox::standardIcon(QMessageBox::Information));
+ mb.setText(text);
+ mb.setCheckBoxText(checkBoxText);
+ mb.setChecked(*checkBoxSetting);
+ mb.setStandardButtons(buttons);
+ mb.setDefaultButton(defaultButton);
+ mb.exec();
+ *checkBoxSetting = mb.isChecked();
+ return mb.clickedStandardButton();
+}
+
QMessageBox::StandardButton CheckableMessageBox::dialogButtonBoxToMessageBoxButton(QDialogButtonBox::StandardButton db)
{
return static_cast<QMessageBox::StandardButton>(int(db));
diff --git a/src/libs/utils/checkablemessagebox.h b/src/libs/utils/checkablemessagebox.h
index ced2847a1c..42756a4d49 100644
--- a/src/libs/utils/checkablemessagebox.h
+++ b/src/libs/utils/checkablemessagebox.h
@@ -62,6 +62,15 @@ public:
QDialogButtonBox::StandardButtons buttons = QDialogButtonBox::Yes|QDialogButtonBox::No,
QDialogButtonBox::StandardButton defaultButton = QDialogButtonBox::No);
+ static QDialogButtonBox::StandardButton
+ information(QWidget *parent,
+ const QString &title,
+ const QString &text,
+ const QString &checkBoxText,
+ bool *checkBoxSetting,
+ QDialogButtonBox::StandardButtons buttons = QDialogButtonBox::Ok,
+ QDialogButtonBox::StandardButton defaultButton = QDialogButtonBox::NoButton);
+
QString text() const;
void setText(const QString &);
diff --git a/src/libs/utils/consoleprocess.h b/src/libs/utils/consoleprocess.h
index 3c0a5e7a91..2f604cb288 100644
--- a/src/libs/utils/consoleprocess.h
+++ b/src/libs/utils/consoleprocess.h
@@ -99,7 +99,7 @@ signals:
void processError(const QString &error);
// These reflect the state of the actual client process
void processStarted();
- void processStopped();
+ void processStopped(int, QProcess::ExitStatus);
// These reflect the state of the console+stub
void stubStarted();
diff --git a/src/libs/utils/consoleprocess_unix.cpp b/src/libs/utils/consoleprocess_unix.cpp
index e8c85d5ead..d5a40c5be3 100644
--- a/src/libs/utils/consoleprocess_unix.cpp
+++ b/src/libs/utils/consoleprocess_unix.cpp
@@ -295,12 +295,12 @@ void ConsoleProcess::readStubOutput()
d->m_appStatus = QProcess::NormalExit;
d->m_appCode = out.mid(5).toInt();
d->m_appPid = 0;
- emit processStopped();
+ emit processStopped(d->m_appCode, d->m_appStatus);
} else if (out.startsWith("crash ")) {
d->m_appStatus = QProcess::CrashExit;
d->m_appCode = out.mid(6).toInt();
d->m_appPid = 0;
- emit processStopped();
+ emit processStopped(d->m_appCode, d->m_appStatus);
} else {
emit processError(msgUnexpectedOutput(out));
d->m_stubPid = 0;
@@ -323,7 +323,7 @@ void ConsoleProcess::stubExited()
d->m_appStatus = QProcess::CrashExit;
d->m_appCode = -1;
d->m_appPid = 0;
- emit processStopped(); // Maybe it actually did not, but keep state consistent
+ emit processStopped(d->m_appCode, d->m_appStatus); // Maybe it actually did not, but keep state consistent
}
emit stubStopped();
}
diff --git a/src/libs/utils/consoleprocess_win.cpp b/src/libs/utils/consoleprocess_win.cpp
index 8ec72e8f5d..1e8ba85133 100644
--- a/src/libs/utils/consoleprocess_win.cpp
+++ b/src/libs/utils/consoleprocess_win.cpp
@@ -261,7 +261,7 @@ void ConsoleProcess::inferiorExited()
cleanupInferior();
d->m_appStatus = QProcess::NormalExit;
d->m_appCode = chldStatus;
- emit processStopped();
+ emit processStopped(d->m_appCode, d->m_appStatus);
}
void ConsoleProcess::cleanupStub()
@@ -288,7 +288,7 @@ void ConsoleProcess::stubExited()
cleanupInferior();
d->m_appStatus = QProcess::CrashExit;
d->m_appCode = -1;
- emit processStopped();
+ emit processStopped(d->m_appCode, d->m_appStatus);
}
emit stubStopped();
}
diff --git a/src/libs/utils/environment.cpp b/src/libs/utils/environment.cpp
index e0a19db274..663e093fb7 100644
--- a/src/libs/utils/environment.cpp
+++ b/src/libs/utils/environment.cpp
@@ -29,8 +29,6 @@
#include "environment.h"
-#include "hostosinfo.h"
-
#include <QDir>
#include <QProcessEnvironment>
#include <QCoreApplication>
@@ -99,12 +97,12 @@ QStringList EnvironmentItem::toStringList(const QList<EnvironmentItem> &list)
return result;
}
-Environment::Environment(const QStringList &env)
+Environment::Environment(const QStringList &env, OsType osType) : m_osType(osType)
{
foreach (const QString &s, env) {
int i = s.indexOf(QLatin1Char('='));
if (i >= 0) {
- if (HostOsInfo::isWindowsHost())
+ if (m_osType == OsTypeWindows)
m_values.insert(s.left(i).toUpper(), s.mid(i+1));
else
m_values.insert(s.left(i), s.mid(i+1));
@@ -136,17 +134,17 @@ QProcessEnvironment Environment::toProcessEnvironment() const
void Environment::set(const QString &key, const QString &value)
{
- m_values.insert(HostOsInfo::isWindowsHost() ? key.toUpper() : key, value);
+ m_values.insert(m_osType == OsTypeWindows ? key.toUpper() : key, value);
}
void Environment::unset(const QString &key)
{
- m_values.remove(HostOsInfo::isWindowsHost() ? key.toUpper() : key);
+ m_values.remove(m_osType == OsTypeWindows ? key.toUpper() : key);
}
void Environment::appendOrSet(const QString &key, const QString &value, const QString &sep)
{
- const QString &_key = HostOsInfo::isWindowsHost() ? key.toUpper() : key;
+ const QString &_key = m_osType == OsTypeWindows ? key.toUpper() : key;
QMap<QString, QString>::iterator it = m_values.find(_key);
if (it == m_values.end()) {
m_values.insert(_key, value);
@@ -160,7 +158,7 @@ void Environment::appendOrSet(const QString &key, const QString &value, const QS
void Environment::prependOrSet(const QString&key, const QString &value, const QString &sep)
{
- const QString &_key = HostOsInfo::isWindowsHost() ? key.toUpper() : key;
+ const QString &_key = m_osType == OsTypeWindows ? key.toUpper() : key;
QMap<QString, QString>::iterator it = m_values.find(_key);
if (it == m_values.end()) {
m_values.insert(_key, value);
@@ -175,26 +173,26 @@ void Environment::prependOrSet(const QString&key, const QString &value, const QS
void Environment::appendOrSetPath(const QString &value)
{
appendOrSet(QLatin1String("PATH"), QDir::toNativeSeparators(value),
- QString(HostOsInfo::pathListSeparator()));
+ QString(OsSpecificAspects(m_osType).pathListSeparator()));
}
void Environment::prependOrSetPath(const QString &value)
{
prependOrSet(QLatin1String("PATH"), QDir::toNativeSeparators(value),
- QString(HostOsInfo::pathListSeparator()));
+ QString(OsSpecificAspects(m_osType).pathListSeparator()));
}
void Environment::prependOrSetLibrarySearchPath(const QString &value)
{
- switch (HostOsInfo::hostOs()) {
- case HostOsInfo::HostOsWindows: {
+ switch (m_osType) {
+ case OsTypeWindows: {
const QChar sep = QLatin1Char(';');
const QLatin1String path("PATH");
prependOrSet(path, QDir::toNativeSeparators(value), QString(sep));
break;
}
- case HostOsInfo::HostOsLinux:
- case HostOsInfo::HostOsOtherUnix: {
+ case OsTypeLinux:
+ case OsTypeOtherUnix: {
const QChar sep = QLatin1Char(':');
const QLatin1String path("LD_LIBRARY_PATH");
prependOrSet(path, QDir::toNativeSeparators(value), QString(sep));
@@ -243,7 +241,7 @@ QString Environment::searchInPath(const QString &executable,
QFileInfo fi(exec);
QStringList execs(exec);
- if (HostOsInfo::isWindowsHost()) {
+ if (m_osType == OsTypeWindows) {
// Check all the executable extensions on windows:
// PATHEXT is only used if the executable has no extension
if (fi.suffix().isEmpty()) {
@@ -283,8 +281,8 @@ QString Environment::searchInPath(const QString &executable,
QStringList Environment::path() const
{
- return m_values.value(QLatin1String("PATH")).split(HostOsInfo::pathListSeparator(),
- QString::SkipEmptyParts);
+ return m_values.value(QLatin1String("PATH"))
+ .split(OsSpecificAspects(m_osType).pathListSeparator(), QString::SkipEmptyParts);
}
QString Environment::value(const QString &key) const
@@ -398,7 +396,7 @@ bool Environment::hasKey(const QString &key) const
QString Environment::userName() const
{
- return value(QLatin1String(HostOsInfo::isWindowsHost() ? "USERNAME" : "USER"));
+ return value(QLatin1String(m_osType == OsTypeWindows ? "USERNAME" : "USER"));
}
bool Environment::operator!=(const Environment &other) const
@@ -408,7 +406,7 @@ bool Environment::operator!=(const Environment &other) const
bool Environment::operator==(const Environment &other) const
{
- return m_values == other.m_values;
+ return m_osType == other.m_osType && m_values == other.m_values;
}
/** Expand environment variables in a string.
@@ -422,7 +420,7 @@ QString Environment::expandVariables(const QString &input) const
{
QString result = input;
- if (HostOsInfo::isWindowsHost()) {
+ if (m_osType == OsTypeWindows) {
for (int vStart = -1, i = 0; i < result.length(); ) {
if (result.at(i++) == QLatin1Char('%')) {
if (vStart > 0) {
diff --git a/src/libs/utils/environment.h b/src/libs/utils/environment.h
index 46fd72a88c..4442be992c 100644
--- a/src/libs/utils/environment.h
+++ b/src/libs/utils/environment.h
@@ -30,6 +30,7 @@
#ifndef UTILS_ENVIRONMENT_H
#define UTILS_ENVIRONMENT_H
+#include "hostosinfo.h"
#include "utils_global.h"
#include <QMap>
@@ -65,8 +66,8 @@ class QTCREATOR_UTILS_EXPORT Environment
public:
typedef QMap<QString, QString>::const_iterator const_iterator;
- Environment() {}
- explicit Environment(const QStringList &env);
+ explicit Environment(OsType osType = HostOsInfo::hostOs()) : m_osType(osType) {}
+ explicit Environment(const QStringList &env, OsType osType = HostOsInfo::hostOs());
static Environment systemEnvironment();
QStringList toStringList() const;
@@ -112,6 +113,7 @@ public:
private:
QString searchInDirectory(const QStringList &execs, QString directory) const;
QMap<QString, QString> m_values;
+ OsType m_osType;
};
} // namespace Utils
diff --git a/src/libs/utils/fancymainwindow.cpp b/src/libs/utils/fancymainwindow.cpp
index 2c3dd06cf0..8db1e21723 100644
--- a/src/libs/utils/fancymainwindow.cpp
+++ b/src/libs/utils/fancymainwindow.cpp
@@ -124,9 +124,9 @@ void FancyMainWindow::updateDockWidget(QDockWidget *dockWidget)
: QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetFloatable;
if (dockWidget->property("managed_dockwidget").isNull()) { // for the debugger tool bar
QWidget *titleBarWidget = dockWidget->titleBarWidget();
- if (d->m_locked && !titleBarWidget && !dockWidget->isFloating())
+ if (d->m_locked && !titleBarWidget && !dockWidget->isFloating()) {
titleBarWidget = new QWidget(dockWidget);
- else if ((!d->m_locked || dockWidget->isFloating()) && titleBarWidget) {
+ } else if ((!d->m_locked || dockWidget->isFloating()) && titleBarWidget) {
delete titleBarWidget;
titleBarWidget = 0;
}
diff --git a/src/libs/utils/filesearch.cpp b/src/libs/utils/filesearch.cpp
index 68c3d8cef2..44a7a66df3 100644
--- a/src/libs/utils/filesearch.cpp
+++ b/src/libs/utils/filesearch.cpp
@@ -54,14 +54,6 @@ static inline QString msgFound(const QString &searchTerm, int numMatches, int nu
arg(searchTerm).arg(numFilesSearched);
}
-static inline QString msgFound(const QString &searchTerm, int numMatches, int numFilesSearched, int filesSize)
-{
- return QCoreApplication::translate("Utils::FileSearch",
- "%1: %n occurrences found in %2 of %3 files.",
- 0, QCoreApplication::CodecForTr, numMatches).
- arg(searchTerm).arg(numFilesSearched).arg(filesSize);
-}
-
namespace {
const int MAX_LINE_SIZE = 400;
diff --git a/src/libs/utils/fileutils.cpp b/src/libs/utils/fileutils.cpp
index 49e6b93294..80ef5bc5ff 100644
--- a/src/libs/utils/fileutils.cpp
+++ b/src/libs/utils/fileutils.cpp
@@ -160,7 +160,7 @@ bool FileUtils::copyRecursively(const FileName &srcFilePath, const FileName &tgt
/*!
If \a filePath is a directory, the function will recursively check all files and return
true if one of them is newer than \a timeStamp. If \a filePath is a single file, true will
- be returned if the file is newer than \timeStamp.
+ be returned if the file is newer than \a timeStamp.
Returns whether at least one file in \a filePath has a newer date than
\a timeStamp.
@@ -219,6 +219,18 @@ QString FileUtils::shortNativePath(const FileName &path)
return path.toUserOutput();
}
+QString FileUtils::fileSystemFriendlyName(const QString &name)
+{
+ QString result = name;
+ 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;
+}
+
bool FileUtils::makeWritable(const FileName &path)
{
const QString fileName = path.toString();
diff --git a/src/libs/utils/fileutils.h b/src/libs/utils/fileutils.h
index 4477938be5..0cf1db64b1 100644
--- a/src/libs/utils/fileutils.h
+++ b/src/libs/utils/fileutils.h
@@ -96,6 +96,7 @@ public:
static bool isFileNewerThan(const FileName &filePath, const QDateTime &timeStamp);
static FileName resolveSymlinks(const FileName &path);
static QString shortNativePath(const FileName &path);
+ static QString fileSystemFriendlyName(const QString &name);
static bool makeWritable(const FileName &path);
};
diff --git a/src/plugins/analyzerbase/ianalyzerengine.cpp b/src/libs/utils/function.cpp
index 94c0bd09ef..68370976d8 100644
--- a/src/plugins/analyzerbase/ianalyzerengine.cpp
+++ b/src/libs/utils/function.cpp
@@ -2,7 +2,6 @@
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
-** Author: Nicolas Arnaud-Cormos, KDAB (nicolas.arnaud-cormos@kdab.com)
**
** This file is part of Qt Creator.
**
@@ -28,23 +27,43 @@
**
****************************************************************************/
-#include "ianalyzerengine.h"
+#include "function.h"
-namespace Analyzer {
+namespace {
+// just compilation tests
-IAnalyzerEngine::IAnalyzerEngine(IAnalyzerTool *tool, const AnalyzerStartParameters &sp,
- ProjectExplorer::RunConfiguration *runConfiguration)
+void test();
+
+void functionUser(Utils::function<int()> generator, Utils::function<void(int)> consumer)
+{
+ consumer(generator());
+}
+
+struct GenFunctor
+{
+ int operator()() { return 29; }
+};
+
+struct ConsumerFunctor
+{
+ void operator()(int) {}
+};
+
+int generatorF()
+{
+ return 42;
+}
+
+void consumerF(int i)
{
- m_runConfig = runConfiguration;
- m_sp = sp;
- m_tool = tool;
+ if (i < 0)
+ test();
}
-IAnalyzerEngine::IAnalyzerEngine(IAnalyzerTool *tool,
- ProjectExplorer::RunConfiguration *runConfiguration)
+void test()
{
- m_runConfig = runConfiguration;
- m_tool = tool;
+ functionUser(GenFunctor(), ConsumerFunctor());
+ functionUser(&generatorF, &consumerF);
}
-} // namespace Analyzer
+} // end namespace
diff --git a/src/libs/utils/function.h b/src/libs/utils/function.h
new file mode 100644
index 0000000000..d6dbc2f999
--- /dev/null
+++ b/src/libs/utils/function.h
@@ -0,0 +1,47 @@
+/****************************************************************************
+**
+** 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 QTC_FUNCTION_H
+#define QTC_FUNCTION_H
+
+#include <functional>
+#if !(__cplusplus > 199711L || __GXX_EXPERIMENTAL_CXX0X__ || _MSC_VER >= 1600 || defined( _LIBCPP_VERSION ))
+#define USE_TR1
+#endif
+
+#ifdef USE_TR1
+# ifdef __GNUC__
+# include <tr1/functional>
+# endif
+namespace Utils { using std::tr1::function; }
+#else
+namespace Utils { using std::function; }
+#endif
+
+#endif // QTC_FUNCTION_H
diff --git a/src/libs/utils/historycompleter.cpp b/src/libs/utils/historycompleter.cpp
index 65a54d47e0..15fee7dd03 100644
--- a/src/libs/utils/historycompleter.cpp
+++ b/src/libs/utils/historycompleter.cpp
@@ -65,8 +65,9 @@ public:
class HistoryLineDelegate : public QItemDelegate
{
public:
- HistoryLineDelegate()
- : pixmap(QLatin1String(":/core/images/editclear.png"))
+ HistoryLineDelegate(QObject *parent)
+ : QItemDelegate(parent)
+ , pixmap(QLatin1String(":/core/images/editclear.png"))
{}
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
@@ -85,7 +86,7 @@ public:
HistoryLineView(HistoryCompleterPrivate *model_)
: model(model_)
{
- HistoryLineDelegate *delegate = new HistoryLineDelegate;
+ HistoryLineDelegate *delegate = new HistoryLineDelegate(this);
pixmapWidth = delegate->pixmap.width();
setItemDelegate(delegate);
}
diff --git a/src/libs/utils/hostosinfo.h b/src/libs/utils/hostosinfo.h
index 0bb642561b..10ad8785c8 100644
--- a/src/libs/utils/hostosinfo.h
+++ b/src/libs/utils/hostosinfo.h
@@ -32,10 +32,12 @@
#include "utils_global.h"
+#include "osspecificaspects.h"
+
#include <QString>
#ifdef Q_OS_WIN
-#define QTC_HOST_EXE_SUFFIX ".exe"
+#define QTC_HOST_EXE_SUFFIX QTC_WIN_EXE_SUFFIX
#else
#define QTC_HOST_EXE_SUFFIX ""
#endif // Q_OS_WIN
@@ -45,55 +47,54 @@ namespace Utils {
class QTCREATOR_UTILS_EXPORT HostOsInfo
{
public:
- // Add more as needed.
- enum HostOs { HostOsWindows, HostOsLinux, HostOsMac, HostOsOtherUnix, HostOsOther };
- static inline HostOs hostOs();
+ static inline OsType 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 bool isWindowsHost() { return hostOs() == OsTypeWindows; }
+ static bool isLinuxHost() { return hostOs() == OsTypeLinux; }
+ static bool isMacHost() { return hostOs() == OsTypeMac; }
static inline bool isAnyUnixHost();
static QString withExecutableSuffix(const QString &executable)
{
- QString finalName = executable;
- if (isWindowsHost())
- finalName += QLatin1String(QTC_HOST_EXE_SUFFIX);
- return finalName;
+ return hostOsAspects().withExecutableSuffix(executable);
}
static Qt::CaseSensitivity fileNameCaseSensitivity()
{
- return isWindowsHost() ? Qt::CaseInsensitive: Qt::CaseSensitive;
+ return hostOsAspects().fileNameCaseSensitivity();
}
static QChar pathListSeparator()
{
- return isWindowsHost() ? QLatin1Char(';') : QLatin1Char(':');
+ return hostOsAspects().pathListSeparator();
}
static Qt::KeyboardModifier controlModifier()
{
- return isMacHost() ? Qt::MetaModifier : Qt::ControlModifier;
+ return hostOsAspects().controlModifier();
}
+
+private:
+ static OsSpecificAspects hostOsAspects() { return OsSpecificAspects(hostOs()); }
};
-HostOsInfo::HostOs HostOsInfo::hostOs()
+
+OsType HostOsInfo::hostOs()
{
#if defined(Q_OS_WIN)
- return HostOsWindows;
+ return OsTypeWindows;
#elif defined(Q_OS_LINUX)
- return HostOsLinux;
+ return OsTypeLinux;
#elif defined(Q_OS_MAC)
- return HostOsMac;
+ return OsTypeMac;
#elif defined(Q_OS_UNIX)
- return HostOsOtherUnix;
+ return OsTypeOtherUnix;
#else
- return HostOsOther;
+ return OsTypeOther;
#endif
}
diff --git a/src/libs/utils/iwelcomepage.h b/src/libs/utils/iwelcomepage.h
index d05e8b9520..2a7db33974 100644
--- a/src/libs/utils/iwelcomepage.h
+++ b/src/libs/utils/iwelcomepage.h
@@ -35,7 +35,7 @@
#include <QObject>
QT_FORWARD_DECLARE_CLASS(QUrl)
-QT_FORWARD_DECLARE_CLASS(QDeclarativeEngine)
+QT_FORWARD_DECLARE_CLASS(QQmlEngine)
namespace Utils {
@@ -63,7 +63,7 @@ public:
virtual QUrl pageLocation() const = 0;
virtual QString title() const = 0;
virtual int priority() const { return 0; }
- virtual void facilitateQml(QDeclarativeEngine *) {}
+ virtual void facilitateQml(QQmlEngine *) {}
virtual bool hasSearchBar() const { return false; }
virtual Id id() const = 0;
};
diff --git a/src/libs/utils/json.cpp b/src/libs/utils/json.cpp
index dd12224432..8a56f9c4a9 100644
--- a/src/libs/utils/json.cpp
+++ b/src/libs/utils/json.cpp
@@ -39,6 +39,11 @@
using namespace Utils;
+JsonMemoryPool::~JsonMemoryPool()
+{
+ foreach (char *obj, _objs)
+ delete[] obj;
+}
JsonValue::JsonValue(Kind kind)
: m_kind(kind)
@@ -47,7 +52,7 @@ JsonValue::JsonValue(Kind kind)
JsonValue::~JsonValue()
{}
-JsonValue *JsonValue::create(const QString &s)
+JsonValue *JsonValue::create(const QString &s, JsonMemoryPool *pool)
{
QScriptEngine engine;
QScriptValue jsonParser = engine.evaluate(QLatin1String("JSON.parse"));
@@ -55,9 +60,18 @@ JsonValue *JsonValue::create(const QString &s)
if (engine.hasUncaughtException() || !value.isValid())
return 0;
- return build(value.toVariant());
+ return build(value.toVariant(), pool);
}
+void *JsonValue::operator new(size_t size, JsonMemoryPool *pool)
+{ return pool->allocate(size); }
+
+void JsonValue::operator delete(void *)
+{ }
+
+void JsonValue::operator delete(void *, JsonMemoryPool *)
+{ }
+
QString JsonValue::kindToString(JsonValue::Kind kind)
{
if (kind == String)
@@ -78,39 +92,39 @@ QString JsonValue::kindToString(JsonValue::Kind kind)
return QLatin1String("unkown");
}
-JsonValue *JsonValue::build(const QVariant &variant)
+JsonValue *JsonValue::build(const QVariant &variant, JsonMemoryPool *pool)
{
switch (variant.type()) {
case QVariant::List: {
- JsonArrayValue *newValue = new JsonArrayValue;
+ JsonArrayValue *newValue = new (pool) JsonArrayValue;
foreach (const QVariant &element, variant.toList())
- newValue->addElement(build(element));
+ newValue->addElement(build(element, pool));
return newValue;
}
case QVariant::Map: {
- JsonObjectValue *newValue = new JsonObjectValue;
+ JsonObjectValue *newValue = new (pool) JsonObjectValue;
const QVariantMap variantMap = variant.toMap();
for (QVariantMap::const_iterator it = variantMap.begin(); it != variantMap.end(); ++it)
- newValue->addMember(it.key(), build(it.value()));
+ newValue->addMember(it.key(), build(it.value(), pool));
return newValue;
}
case QVariant::String:
- return new JsonStringValue(variant.toString());
+ return new (pool) JsonStringValue(variant.toString());
case QVariant::Int:
- return new JsonIntValue(variant.toInt());
+ return new (pool) JsonIntValue(variant.toInt());
case QVariant::Double:
- return new JsonDoubleValue(variant.toDouble());
+ return new (pool) JsonDoubleValue(variant.toDouble());
case QVariant::Bool:
- return new JsonBooleanValue(variant.toBool());
+ return new (pool) JsonBooleanValue(variant.toBool());
case QVariant::Invalid:
- return new JsonNullValue;
+ return new (pool) JsonNullValue;
default:
break;
@@ -728,7 +742,7 @@ JsonSchema *JsonSchemaManager::parseSchema(const QString &schemaFileName) const
FileReader reader;
if (reader.fetch(schemaFileName, QIODevice::Text)) {
const QString &contents = QString::fromUtf8(reader.data());
- JsonValue *json = JsonValue::create(contents);
+ JsonValue *json = JsonValue::create(contents, &m_pool);
if (json && json->kind() == JsonValue::Object)
return new JsonSchema(json->toObject(), this);
}
diff --git a/src/libs/utils/json.h b/src/libs/utils/json.h
index f574859436..853b4366e5 100644
--- a/src/libs/utils/json.h
+++ b/src/libs/utils/json.h
@@ -49,6 +49,22 @@ class JsonArrayValue;
class JsonBooleanValue;
class JsonNullValue;
+class QTCREATOR_UTILS_EXPORT JsonMemoryPool
+{
+public:
+ ~JsonMemoryPool();
+
+ inline void *allocate(size_t size)
+ {
+ char *obj = new char[size];
+ _objs.append(obj);
+ return obj;
+ }
+
+private:
+ QVector<char *> _objs;
+};
+
/*!
* \brief The JsonValue class
*/
@@ -79,13 +95,16 @@ public:
virtual JsonBooleanValue *toBoolean() { return 0; }
virtual JsonNullValue *toNull() { return 0; }
- static JsonValue *create(const QString &s);
+ static JsonValue *create(const QString &s, JsonMemoryPool *pool);
+ void *operator new(size_t size, JsonMemoryPool *pool);
+ void operator delete(void *);
+ void operator delete(void *, JsonMemoryPool *);
protected:
JsonValue(Kind kind);
private:
- static JsonValue *build(const QVariant &varixant);
+ static JsonValue *build(const QVariant &varixant, JsonMemoryPool *pool);
Kind m_kind;
};
@@ -398,6 +417,7 @@ private:
QStringList m_searchPaths;
mutable QHash<QString, JsonSchemaData> m_schemas;
+ mutable JsonMemoryPool m_pool;
};
} // namespace Utils
diff --git a/src/libs/utils/osspecificaspects.h b/src/libs/utils/osspecificaspects.h
new file mode 100644
index 0000000000..febdcbd022
--- /dev/null
+++ b/src/libs/utils/osspecificaspects.h
@@ -0,0 +1,74 @@
+/**************************************************************************
+**
+** 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 QTC_OSSPECIFICASPECTS_H
+#define QTC_OSSPECIFICASPECTS_H
+
+#include "utils_global.h"
+
+#include <QString>
+
+#define QTC_WIN_EXE_SUFFIX ".exe"
+
+namespace Utils {
+
+// Add more as needed.
+enum OsType { OsTypeWindows, OsTypeLinux, OsTypeMac, OsTypeOtherUnix, OsTypeOther };
+
+class QTCREATOR_UTILS_EXPORT OsSpecificAspects
+{
+public:
+ OsSpecificAspects(OsType osType) : m_osType(osType) { }
+
+ QString withExecutableSuffix(const QString &executable) const {
+ QString finalName = executable;
+ if (m_osType == OsTypeWindows)
+ finalName += QLatin1String(QTC_WIN_EXE_SUFFIX);
+ return finalName;
+ }
+
+ Qt::CaseSensitivity fileNameCaseSensitivity() const {
+ return m_osType == OsTypeWindows ? Qt::CaseInsensitive : Qt::CaseSensitive;
+ }
+
+ QChar pathListSeparator() const {
+ return QLatin1Char(m_osType == OsTypeWindows ? ';' : ':');
+ }
+
+ Qt::KeyboardModifier controlModifier() const {
+ return m_osType == OsTypeMac ? Qt::MetaModifier : Qt::ControlModifier;
+ }
+
+private:
+ const OsType m_osType;
+};
+
+} // namespace Utils
+
+#endif // Include guard.
diff --git a/src/libs/utils/outputformatter.cpp b/src/libs/utils/outputformatter.cpp
index 81649e80be..d2f631d426 100644
--- a/src/libs/utils/outputformatter.cpp
+++ b/src/libs/utils/outputformatter.cpp
@@ -30,6 +30,7 @@
#include "outputformatter.h"
#include <QPlainTextEdit>
+#include <utils/ansiescapecodehandler.h>
using namespace Utils;
@@ -37,6 +38,7 @@ OutputFormatter::OutputFormatter()
: QObject()
, m_plainTextEdit(0)
, m_formats(0)
+ , m_escapeCodeHandler(new AnsiEscapeCodeHandler)
{
}
@@ -44,6 +46,7 @@ OutputFormatter::OutputFormatter()
OutputFormatter::~OutputFormatter()
{
delete[] m_formats;
+ delete m_escapeCodeHandler;
}
QPlainTextEdit *OutputFormatter::plainTextEdit() const
@@ -61,7 +64,9 @@ void OutputFormatter::appendMessage(const QString &text, OutputFormat format)
{
QTextCursor cursor(m_plainTextEdit->document());
cursor.movePosition(QTextCursor::End);
- cursor.insertText(text, m_formats[format]);
+
+ foreach (const StringFormatPair &pair, m_escapeCodeHandler->parseText(text, m_formats[format]))
+ cursor.insertText(pair.first, pair.second);
}
QTextCharFormat OutputFormatter::charFormat(OutputFormat format) const
@@ -131,3 +136,9 @@ void OutputFormatter::setFont(const QFont &font)
m_font = font;
initFormats();
}
+
+void OutputFormatter::flush()
+{
+ if (m_escapeCodeHandler)
+ m_escapeCodeHandler->endFormatScope();
+}
diff --git a/src/libs/utils/outputformatter.h b/src/libs/utils/outputformatter.h
index 789e0da18d..733e7cd52a 100644
--- a/src/libs/utils/outputformatter.h
+++ b/src/libs/utils/outputformatter.h
@@ -44,6 +44,8 @@ QT_END_NAMESPACE
namespace Utils {
+class AnsiEscapeCodeHandler;
+
class QTCREATOR_UTILS_EXPORT OutputFormatter : public QObject
{
Q_OBJECT
@@ -57,6 +59,7 @@ public:
QFont font() const;
void setFont(const QFont &font);
+ void flush();
virtual void appendMessage(const QString &text, OutputFormat format);
virtual void handleLink(const QString &href);
@@ -72,6 +75,7 @@ private:
QPlainTextEdit *m_plainTextEdit;
QTextCharFormat *m_formats;
QFont m_font;
+ AnsiEscapeCodeHandler *m_escapeCodeHandler;
};
} // namespace Utils
diff --git a/src/libs/utils/pathchooser.cpp b/src/libs/utils/pathchooser.cpp
index 3c9961bf8d..1b434d7adc 100644
--- a/src/libs/utils/pathchooser.cpp
+++ b/src/libs/utils/pathchooser.cpp
@@ -246,6 +246,7 @@ PathChooser::PathChooser(QWidget *parent) :
connect(d->m_lineEdit, SIGNAL(validChanged()), this, SIGNAL(validChanged()));
connect(d->m_lineEdit, SIGNAL(validChanged(bool)), this, SIGNAL(validChanged(bool)));
connect(d->m_lineEdit, SIGNAL(editingFinished()), this, SIGNAL(editingFinished()));
+ connect(d->m_lineEdit, SIGNAL(textChanged(QString)), this, SLOT(slotTextChanged()));
d->m_lineEdit->setMinimumWidth(120);
d->m_hLayout->addWidget(d->m_lineEdit);
@@ -421,6 +422,11 @@ void PathChooser::slotBrowse()
d->m_lineEdit->triggerChanged();
}
+void PathChooser::slotTextChanged()
+{
+ emit pathChanged(path());
+}
+
bool PathChooser::isValid() const
{
return d->m_lineEdit->isValid();
diff --git a/src/libs/utils/pathchooser.h b/src/libs/utils/pathchooser.h
index fd687ca514..2dc33c0c9d 100644
--- a/src/libs/utils/pathchooser.h
+++ b/src/libs/utils/pathchooser.h
@@ -50,8 +50,9 @@ class QTCREATOR_UTILS_EXPORT PathChooser : public QWidget
{
Q_OBJECT
Q_ENUMS(Kind)
- Q_PROPERTY(QString path READ path WRITE setPath DESIGNABLE true)
+ Q_PROPERTY(QString path READ path WRITE setPath NOTIFY pathChanged DESIGNABLE true)
Q_PROPERTY(QString promptDialogTitle READ promptDialogTitle WRITE setPromptDialogTitle DESIGNABLE true)
+ Q_PROPERTY(QString promptDialogFilter READ promptDialogFilter WRITE setPromptDialogFilter DESIGNABLE true)
Q_PROPERTY(Kind expectedKind READ expectedKind WRITE setExpectedKind DESIGNABLE true)
Q_PROPERTY(QString baseDirectory READ baseDirectory WRITE setBaseDirectory DESIGNABLE true)
Q_PROPERTY(QStringList commandVersionArguments READ commandVersionArguments WRITE setCommandVersionArguments)
@@ -139,6 +140,7 @@ signals:
void validChanged();
void validChanged(bool validState);
void changed(const QString &text);
+ void pathChanged(const QString &path);
void editingFinished();
void beforeBrowsing();
void browsingFinished();
@@ -150,6 +152,7 @@ public slots:
private slots:
void slotBrowse();
+ void slotTextChanged();
private:
PathChooserPrivate *d;
diff --git a/src/libs/utils/persistentsettings.cpp b/src/libs/utils/persistentsettings.cpp
index 42b04169d7..ce1530055a 100644
--- a/src/libs/utils/persistentsettings.cpp
+++ b/src/libs/utils/persistentsettings.cpp
@@ -316,7 +316,7 @@ ParseContext::Element ParseContext::element(const QStringRef &r) const
QVariant ParseContext::readSimpleValue(QXmlStreamReader &r, const QXmlStreamAttributes &attributes) const
{
// Simple value
- const QString type = attributes.value(typeAttribute).toString();
+ const QStringRef type = attributes.value(typeAttribute);
const QString text = r.readElementText();
if (type == QLatin1String("QChar")) { // Workaround: QTBUG-12345
QTC_ASSERT(text.size() == 1, return QVariant());
diff --git a/src/libs/utils/process_ctrlc_stub.cpp b/src/libs/utils/process_ctrlc_stub.cpp
index 07e200b9db..04cbd87c9d 100644
--- a/src/libs/utils/process_ctrlc_stub.cpp
+++ b/src/libs/utils/process_ctrlc_stub.cpp
@@ -108,7 +108,7 @@ int main(int argc, char **)
while (GetMessage(&msg, NULL, 0, 0))
{
if (msg.message == WM_DESTROY)
- dwExitCode = msg.wParam;
+ dwExitCode = static_cast<DWORD>(msg.wParam);
TranslateMessage(&msg);
DispatchMessage(&msg);
}
diff --git a/src/libs/utils/projectintropage.cpp b/src/libs/utils/projectintropage.cpp
index 0fbebae62f..e7b12675da 100644
--- a/src/libs/utils/projectintropage.cpp
+++ b/src/libs/utils/projectintropage.cpp
@@ -183,7 +183,7 @@ bool ProjectIntroPage::validate()
if (projectDirFile.isDir()) {
displayStatusMessage(Warning, tr("The project already exists."));
- return nameValid;;
+ return nameValid;
}
// Not a directory, but something else, likely causing directory creation to fail
displayStatusMessage(Error, tr("A file with that name already exists."));
diff --git a/src/libs/utils/qtcprocess.cpp b/src/libs/utils/qtcprocess.cpp
index 25c6b63a77..1897a2846a 100644
--- a/src/libs/utils/qtcprocess.cpp
+++ b/src/libs/utils/qtcprocess.cpp
@@ -279,12 +279,6 @@ QStringList QtcProcess::splitArgs(const QString &_args, bool abortOnMeta, SplitE
#else // Q_OS_WIN
-inline static bool isQuoteMeta(QChar cUnicode)
-{
- char c = cUnicode.toLatin1();
- return c == '\\' || c == '\'' || c == '"' || c == '$';
-}
-
inline static bool isMeta(QChar cUnicode)
{
static const uchar iqm[] = {
@@ -736,13 +730,15 @@ void QtcProcess::terminate()
QProcess::terminate();
}
-#ifdef Q_OS_WIN
void QtcProcess::interrupt()
{
+#ifdef Q_OS_WIN
QTC_ASSERT(m_useCtrlCStub, return);
EnumWindows(sendInterruptMessageToAllWindowsOfProcess_enumWnd, pid()->dwProcessId);
+#endif
}
+#ifdef Q_OS_WIN
// This function assumes that the resulting string will be quoted.
// That's irrelevant if it does not contain quotes itself.
static int quoteArgInternal(QString &ret, int bslashes)
@@ -1473,3 +1469,17 @@ void QtcProcess::ArgIterator::appendArg(const QString &str)
m_str->insert(m_pos, QLatin1Char(' ') + qstr);
m_pos += qstr.length() + 1;
}
+
+namespace Utils {
+
+QTCREATOR_UTILS_EXPORT unsigned long qPidToPid(const Q_PID qpid)
+{
+#ifdef Q_OS_WIN
+ const PROCESS_INFORMATION *processInfo = reinterpret_cast<const PROCESS_INFORMATION*>(qpid);
+ return processInfo->dwProcessId;
+#else
+ return qpid;
+#endif
+}
+
+} // namespace Utils
diff --git a/src/libs/utils/qtcprocess.h b/src/libs/utils/qtcprocess.h
index e516c7dd70..b980cb40c5 100644
--- a/src/libs/utils/qtcprocess.h
+++ b/src/libs/utils/qtcprocess.h
@@ -45,22 +45,16 @@ public:
QtcProcess(QObject *parent = 0)
: QProcess(parent),
m_haveEnv(false)
-#ifdef Q_OS_WIN
, m_useCtrlCStub(false)
-#endif
{}
void setEnvironment(const Environment &env)
{ m_environment = env; m_haveEnv = true; }
void setCommand(const QString &command, const QString &arguments)
{ m_command = command; m_arguments = arguments; }
-#ifdef Q_OS_WIN
void setUseCtrlCStub(bool enabled) { m_useCtrlCStub = enabled; }
-#endif
void start();
void terminate();
-#ifdef Q_OS_WIN
void interrupt();
-#endif
enum SplitError {
SplitOk = 0, //! All went just fine
@@ -150,11 +144,13 @@ private:
QString m_arguments;
Environment m_environment;
bool m_haveEnv;
-#ifdef Q_OS_WIN
bool m_useCtrlCStub;
-#endif
};
-}
+// Converts the Q_PID into a integer value. This is a no-op
+// except on Windows.
+QTCREATOR_UTILS_EXPORT unsigned long qPidToPid(const Q_PID qpid);
+
+} // namespace Utils
#endif // QTCPROCESS_H
diff --git a/src/libs/utils/reloadpromptutils.cpp b/src/libs/utils/reloadpromptutils.cpp
index 04f110f46d..3c618d7816 100644
--- a/src/libs/utils/reloadpromptutils.cpp
+++ b/src/libs/utils/reloadpromptutils.cpp
@@ -36,28 +36,34 @@
using namespace Utils;
-QTCREATOR_UTILS_EXPORT Utils::ReloadPromptAnswer
- Utils::reloadPrompt(const QString &fileName, bool modified, QWidget *parent)
+QTCREATOR_UTILS_EXPORT Utils::ReloadPromptAnswer Utils::reloadPrompt(const QString &fileName,
+ bool modified,
+ QWidget *parent)
{
const QString title = QCoreApplication::translate("Utils::reloadPrompt", "File Changed");
QString msg;
- if (modified)
+ if (modified) {
msg = QCoreApplication::translate("Utils::reloadPrompt",
- "The unsaved file <i>%1</i> has been changed outside Qt Creator. Do you want to reload it and discard your changes?");
- else
+ "The unsaved file <i>%1</i> has changed outside Qt Creator. "
+ "Do you want to reload it and discard your changes?");
+ } else {
msg = QCoreApplication::translate("Utils::reloadPrompt",
- "The file <i>%1</i> has changed outside Qt Creator. Do you want to reload it?");
+ "The file <i>%1</i> has changed outside Qt Creator. Do you want to reload it?");
+ }
msg = msg.arg(QFileInfo(fileName).fileName());
return reloadPrompt(title, msg, QDir::toNativeSeparators(fileName), parent);
}
-QTCREATOR_UTILS_EXPORT Utils::ReloadPromptAnswer
- Utils::reloadPrompt(const QString &title, const QString &prompt, const QString &details, QWidget *parent)
+QTCREATOR_UTILS_EXPORT Utils::ReloadPromptAnswer Utils::reloadPrompt(const QString &title,
+ const QString &prompt,
+ const QString &details,
+ QWidget *parent)
{
QMessageBox msg(parent);
- msg.setStandardButtons(QMessageBox::Yes|QMessageBox::YesToAll|QMessageBox::Close|QMessageBox::No|QMessageBox::NoToAll);
+ msg.setStandardButtons(QMessageBox::Yes | QMessageBox::YesToAll | QMessageBox::Close
+ | QMessageBox::No | QMessageBox::NoToAll);
msg.setDefaultButton(QMessageBox::YesToAll);
msg.setWindowTitle(title);
msg.setText(prompt);
@@ -81,23 +87,40 @@ QTCREATOR_UTILS_EXPORT Utils::ReloadPromptAnswer
QTCREATOR_UTILS_EXPORT Utils::FileDeletedPromptAnswer
Utils::fileDeletedPrompt(const QString &fileName, bool triggerExternally, QWidget *parent)
{
- const QString title = QCoreApplication::translate("Utils::fileDeletedPrompt", "File has been removed");
+ const QString title = QCoreApplication::translate("Utils::fileDeletedPrompt",
+ "File has been removed");
QString msg;
- if (triggerExternally)
+ if (triggerExternally) {
msg = QCoreApplication::translate("Utils::fileDeletedPrompt",
- "The file %1 has been removed outside Qt Creator. Do you want to save it under a different name, or close the editor?").arg(QDir::toNativeSeparators(fileName));
- else
+ "The file %1 has been removed outside Qt Creator. "
+ "Do you want to save it under a different name, or close "
+ "the editor?").arg(QDir::toNativeSeparators(fileName));
+ } else {
msg = QCoreApplication::translate("Utils::fileDeletedPrompt",
- "The file %1 was removed. Do you want to save it under a different name, or close the editor?").arg(QDir::toNativeSeparators(fileName));
+ "The file %1 was removed. "
+ "Do you want to save it under a different name, or close "
+ "the editor?").arg(QDir::toNativeSeparators(fileName));
+ }
QMessageBox box(QMessageBox::Question, title, msg, QMessageBox::NoButton, parent);
- QPushButton *close = box.addButton(QCoreApplication::translate("Utils::fileDeletedPrompt", "&Close"), QMessageBox::RejectRole);
- QPushButton *saveas = box.addButton(QCoreApplication::translate("Utils::fileDeletedPrompt", "Save &as..."), QMessageBox::ActionRole);
- QPushButton *save = box.addButton(QCoreApplication::translate("Utils::fileDeletedPrompt", "&Save"), QMessageBox::AcceptRole);
+ QPushButton *close =
+ box.addButton(QCoreApplication::translate("Utils::fileDeletedPrompt", "&Close"),
+ QMessageBox::RejectRole);
+ QPushButton *closeAll =
+ box.addButton(QCoreApplication::translate("Utils::fileDeletedPrompt", "C&lose All"),
+ QMessageBox::RejectRole);
+ QPushButton *saveas =
+ box.addButton(QCoreApplication::translate("Utils::fileDeletedPrompt", "Save &as..."),
+ QMessageBox::ActionRole);
+ QPushButton *save =
+ box.addButton(QCoreApplication::translate("Utils::fileDeletedPrompt", "&Save"),
+ QMessageBox::AcceptRole);
box.setDefaultButton(saveas);
box.exec();
QAbstractButton *clickedbutton = box.clickedButton();
if (clickedbutton == close)
return FileDeletedClose;
+ else if (clickedbutton == closeAll)
+ return FileDeletedCloseAll;
else if (clickedbutton == saveas)
return FileDeletedSaveAs;
else if (clickedbutton == save)
diff --git a/src/libs/utils/reloadpromptutils.h b/src/libs/utils/reloadpromptutils.h
index 73d92c8a9e..1093a31399 100644
--- a/src/libs/utils/reloadpromptutils.h
+++ b/src/libs/utils/reloadpromptutils.h
@@ -39,14 +39,31 @@ QT_END_NAMESPACE
namespace Utils {
-enum ReloadPromptAnswer { ReloadCurrent, ReloadAll, ReloadSkipCurrent, ReloadNone, CloseCurrent };
+enum ReloadPromptAnswer {
+ ReloadCurrent,
+ ReloadAll,
+ ReloadSkipCurrent,
+ ReloadNone,
+ CloseCurrent
+};
-QTCREATOR_UTILS_EXPORT ReloadPromptAnswer reloadPrompt(const QString &fileName, bool modified, QWidget *parent);
-QTCREATOR_UTILS_EXPORT ReloadPromptAnswer reloadPrompt(const QString &title, const QString &prompt, const QString &details, QWidget *parent);
+QTCREATOR_UTILS_EXPORT ReloadPromptAnswer reloadPrompt(const QString &fileName,
+ bool modified,
+ QWidget *parent);
+QTCREATOR_UTILS_EXPORT ReloadPromptAnswer reloadPrompt(const QString &title,
+ const QString &prompt,
+ const QString &details, QWidget *parent);
-enum FileDeletedPromptAnswer { FileDeletedClose, FileDeletedSaveAs, FileDeletedSave };
+enum FileDeletedPromptAnswer {
+ FileDeletedClose,
+ FileDeletedCloseAll,
+ FileDeletedSaveAs,
+ FileDeletedSave
+};
-QTCREATOR_UTILS_EXPORT FileDeletedPromptAnswer fileDeletedPrompt(const QString &fileName, bool triggerExternally, QWidget *parent);
+QTCREATOR_UTILS_EXPORT FileDeletedPromptAnswer fileDeletedPrompt(const QString &fileName,
+ bool triggerExternally,
+ QWidget *parent);
} // namespace Utils
diff --git a/src/plugins/pythoneditor/pythoneditor_global.h b/src/libs/utils/sleep.cpp
index 307700db41..700fdcb671 100644
--- a/src/plugins/pythoneditor/pythoneditor_global.h
+++ b/src/libs/utils/sleep.cpp
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
+** Copyright (C) 2013 Orgad Shaneh <orgads@gmail.com>.
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
@@ -27,15 +27,21 @@
**
****************************************************************************/
-#ifndef PYTHONEDITOR_GLOBAL_H
-#define PYTHONEDITOR_GLOBAL_H
+#include "sleep.h"
-#include <QtGlobal>
-
-#if defined(PYTHONEDITOR_LIBRARY)
-# define PYEDITOR_EXPORT Q_DECL_EXPORT
+#ifdef Q_OS_WIN
+#include <windows.h>
#else
-# define PYEDITOR_EXPORT Q_DECL_IMPORT
+#include <time.h>
+#include <unistd.h>
#endif
-#endif // PYTHONEDITOR_GLOBAL_H
+void Utils::sleep(int msec)
+{
+#ifdef Q_OS_WIN
+ ::Sleep(msec);
+#else
+ struct timespec ts = { msec / 1000, (msec % 1000) * 1000000 };
+ ::nanosleep(&ts, NULL);
+#endif
+}
diff --git a/src/plugins/madde/madde_exports.h b/src/libs/utils/sleep.h
index 9d2c56708c..c8a592ab95 100644
--- a/src/plugins/madde/madde_exports.h
+++ b/src/libs/utils/sleep.h
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
+** Copyright (C) 2013 Orgad Shaneh <orgads@gmail.com>.
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
@@ -27,15 +27,15 @@
**
****************************************************************************/
-#ifndef MADDEEXPORT_H
-#define MADDEEXPORT_H
+#ifndef SLEEP_H
+#define SLEEP_H
-#include <qglobal.h>
+#include "utils_global.h"
-#if defined(MADDE_LIBRARY)
-# define MADDE_EXPORT Q_DECL_EXPORT
-#else
-# define MADDE_EXPORT Q_DECL_IMPORT
-#endif
+namespace Utils {
-#endif // MADDEEXPORT_H
+void QTCREATOR_UTILS_EXPORT sleep(int msec);
+
+}
+
+#endif // SLEEP_H
diff --git a/src/libs/utils/stylehelper.cpp b/src/libs/utils/stylehelper.cpp
index d423c31eac..0be7950587 100644
--- a/src/libs/utils/stylehelper.cpp
+++ b/src/libs/utils/stylehelper.cpp
@@ -176,7 +176,7 @@ void StyleHelper::verticalGradient(QPainter *painter, const QRect &spanRect, con
QColor keyColor = baseColor(lightColored);
key.sprintf("mh_vertical %d %d %d %d %d",
spanRect.width(), spanRect.height(), clipRect.width(),
- clipRect.height(), keyColor.rgb());;
+ clipRect.height(), keyColor.rgb());
QPixmap pixmap;
if (!QPixmapCache::find(key, pixmap)) {
diff --git a/src/libs/utils/synchronousprocess.cpp b/src/libs/utils/synchronousprocess.cpp
index d744e28f98..58b59f4c67 100644
--- a/src/libs/utils/synchronousprocess.cpp
+++ b/src/libs/utils/synchronousprocess.cpp
@@ -36,6 +36,7 @@
#include <QTextCodec>
#include <QDir>
#include <QMessageBox>
+#include <QThread>
#include <QApplication>
@@ -56,7 +57,7 @@
writes them.
The stdOutBuffered(), stdErrBuffered() signals are emitted with complete
- lines based on the '\n' marker if they are enabled using
+ lines based on the '\\n' marker if they are enabled using
stdOutBufferedSignalsEnabled()/setStdErrBufferedSignalsEnabled().
They would typically be used for log windows.
@@ -129,7 +130,6 @@ QString SynchronousProcessResponse::exitMessage(const QString &binary, int timeo
return SynchronousProcess::tr("The command '%1' finished successfully.").arg(QDir::toNativeSeparators(binary));
case FinishedError:
return SynchronousProcess::tr("The command '%1' terminated with exit code %2.").arg(QDir::toNativeSeparators(binary)).arg(exitCode);
- break;
case TerminatedAbnormally:
return SynchronousProcess::tr("The command '%1' terminated abnormally.").arg(QDir::toNativeSeparators(binary));
case StartFailed:
@@ -149,13 +149,19 @@ QTCREATOR_UTILS_EXPORT QDebug operator<<(QDebug str, const SynchronousProcessRes
return str;
}
+SynchronousProcessResponse::Result ExitCodeInterpreter::interpretExitCode(int code) const
+{
+ return code ? SynchronousProcessResponse::FinishedError
+ : SynchronousProcessResponse::Finished;
+}
+
// Data for one channel buffer (stderr/stdout)
struct ChannelBuffer {
ChannelBuffer();
void clearForRun();
- QByteArray linesRead();
+ QString linesRead();
- QByteArray data;
+ QString data;
bool firstData;
bool bufferedSignalsEnabled;
bool firstBuffer;
@@ -178,16 +184,15 @@ void ChannelBuffer::clearForRun()
}
/* Check for complete lines read from the device and return them, moving the
- * buffer position. This is based on the assumption that '\n' is the new line
- * marker in any sane codec. */
-QByteArray ChannelBuffer::linesRead()
+ * buffer position. */
+QString ChannelBuffer::linesRead()
{
// Any new lines?
- const int lastLineIndex = data.lastIndexOf('\n');
+ const int lastLineIndex = data.lastIndexOf(QLatin1Char('\n'));
if (lastLineIndex == -1 || lastLineIndex <= bufferPos)
- return QByteArray();
+ return QString();
const int nextBufferPos = lastLineIndex + 1;
- const QByteArray lines = data.mid(bufferPos, nextBufferPos - bufferPos);
+ const QString lines = data.mid(bufferPos, nextBufferPos - bufferPos);
bufferPos = nextBufferPos;
return lines;
}
@@ -197,7 +202,10 @@ struct SynchronousProcessPrivate {
SynchronousProcessPrivate();
void clearForRun();
- QTextCodec *m_stdOutCodec;
+ QTextCodec *m_codec;
+ ExitCodeInterpreter *m_exitCodeInterpreter;
+ QTextCodec::ConverterState m_stdOutState;
+ QTextCodec::ConverterState m_stdErrState;
TerminalControllingProcess m_process;
QTimer m_timer;
QEventLoop m_eventLoop;
@@ -214,7 +222,8 @@ struct SynchronousProcessPrivate {
};
SynchronousProcessPrivate::SynchronousProcessPrivate() :
- m_stdOutCodec(0),
+ m_codec(QTextCodec::codecForLocale()),
+ m_exitCodeInterpreter(0),
m_hangTimerCount(0),
m_maxHangTimerCount(defaultMaxHangTimerCount),
m_startFailure(false),
@@ -267,14 +276,15 @@ int SynchronousProcess::timeout() const
return d->m_maxHangTimerCount == INT_MAX ? -1 : 1000 * d->m_maxHangTimerCount;
}
-void SynchronousProcess::setStdOutCodec(QTextCodec *c)
+void SynchronousProcess::setCodec(QTextCodec *c)
{
- d->m_stdOutCodec = c;
+ QTC_ASSERT(c, return);
+ d->m_codec = c;
}
-QTextCodec *SynchronousProcess::stdOutCodec() const
+QTextCodec *SynchronousProcess::codec() const
{
- return d->m_stdOutCodec;
+ return d->m_codec;
}
bool SynchronousProcess::stdOutBufferedSignalsEnabled() const
@@ -337,6 +347,16 @@ void SynchronousProcess::setFlags(unsigned tc)
d->m_process.setFlags(tc);
}
+void SynchronousProcess::setExitCodeInterpreter(ExitCodeInterpreter *interpreter)
+{
+ d->m_exitCodeInterpreter = interpreter;
+}
+
+ExitCodeInterpreter *SynchronousProcess::exitCodeInterpreter() const
+{
+ return d->m_exitCodeInterpreter;
+}
+
void SynchronousProcess::setWorkingDirectory(const QString &workingDirectory)
{
d->m_process.setWorkingDirectory(workingDirectory);
@@ -357,6 +377,11 @@ void SynchronousProcess::setProcessChannelMode(QProcess::ProcessChannelMode m)
d->m_process.setProcessChannelMode(m);
}
+static bool isGuiThread()
+{
+ return QThread::currentThread() == QCoreApplication::instance()->thread();
+}
+
SynchronousProcessResponse SynchronousProcess::run(const QString &binary,
const QStringList &args)
{
@@ -373,18 +398,20 @@ SynchronousProcessResponse SynchronousProcess::run(const QString &binary,
d->m_process.closeWriteChannel();
if (!d->m_startFailure) {
d->m_timer.start();
- QApplication::setOverrideCursor(Qt::WaitCursor);
+ if (isGuiThread())
+ QApplication::setOverrideCursor(Qt::WaitCursor);
d->m_eventLoop.exec(QEventLoop::ExcludeUserInputEvents);
if (d->m_result.result == SynchronousProcessResponse::Finished || d->m_result.result == SynchronousProcessResponse::FinishedError) {
processStdOut(false);
processStdErr(false);
}
- d->m_result.stdOut = convertStdOut(d->m_stdOut.data);
- d->m_result.stdErr = convertStdErr(d->m_stdErr.data);
+ d->m_result.stdOut = d->m_stdOut.data;
+ d->m_result.stdErr = d->m_stdErr.data;
d->m_timer.stop();
- QApplication::restoreOverrideCursor();
+ if (isGuiThread())
+ QApplication::restoreOverrideCursor();
}
if (debug)
@@ -392,8 +419,15 @@ SynchronousProcessResponse SynchronousProcess::run(const QString &binary,
return d->m_result;
}
+bool SynchronousProcess::terminate()
+{
+ return stopProcess(d->m_process);
+}
+
static inline bool askToKill(const QString &binary = QString())
{
+ if (!isGuiThread())
+ return true;
const QString title = SynchronousProcess::tr("Process not Responding");
QString msg = binary.isEmpty() ?
SynchronousProcess::tr("The process is not responding.") :
@@ -435,9 +469,14 @@ void SynchronousProcess::finished(int exitCode, QProcess::ExitStatus e)
if (debug)
qDebug() << Q_FUNC_INFO << exitCode << e;
d->m_hangTimerCount = 0;
+
+ ExitCodeInterpreter defaultInterpreter(this);
+ ExitCodeInterpreter *currentInterpreter = d->m_exitCodeInterpreter
+ ? d->m_exitCodeInterpreter : &defaultInterpreter;
+
switch (e) {
case QProcess::NormalExit:
- d->m_result.result = exitCode ? SynchronousProcessResponse::FinishedError : SynchronousProcessResponse::Finished;
+ d->m_result.result = currentInterpreter->interpretExitCode(exitCode);
d->m_result.exitCode = exitCode;
break;
case QProcess::CrashExit:
@@ -474,34 +513,30 @@ void SynchronousProcess::stdErrReady()
processStdErr(true);
}
-QString SynchronousProcess::convertStdErr(const QByteArray &ba)
+QString SynchronousProcess::convertOutput(const QByteArray &ba,
+ QTextCodec::ConverterState *state) const
{
- return QString::fromLocal8Bit(ba.constData(), ba.size()).remove(QLatin1Char('\r'));
-}
-
-QString SynchronousProcess::convertStdOut(const QByteArray &ba) const
-{
- QString stdOut = d->m_stdOutCodec ? d->m_stdOutCodec->toUnicode(ba) : QString::fromLocal8Bit(ba.constData(), ba.size());
- return stdOut.remove(QLatin1Char('\r'));
+ return normalizeNewlines(d->m_codec->toUnicode(ba, ba.size(), state));
}
void SynchronousProcess::processStdOut(bool emitSignals)
{
// Handle binary data
- const QByteArray ba = d->m_process.readAllStandardOutput();
+ const QString stdOutput = convertOutput(d->m_process.readAllStandardOutput(),
+ &d->m_stdOutState);
if (debug > 1)
- qDebug() << Q_FUNC_INFO << emitSignals << ba;
- if (!ba.isEmpty()) {
- d->m_stdOut.data += ba;
+ qDebug() << Q_FUNC_INFO << emitSignals << stdOutput;
+ if (!stdOutput.isEmpty()) {
+ d->m_stdOut.data += stdOutput;
if (emitSignals) {
// Emit binary signals
- emit stdOut(ba, d->m_stdOut.firstData);
+ emit stdOut(stdOutput, d->m_stdOut.firstData);
d->m_stdOut.firstData = false;
// Buffered. Emit complete lines?
if (d->m_stdOut.bufferedSignalsEnabled) {
- const QByteArray lines = d->m_stdOut.linesRead();
+ const QString lines = d->m_stdOut.linesRead();
if (!lines.isEmpty()) {
- emit stdOutBuffered(convertStdOut(lines), d->m_stdOut.firstBuffer);
+ emit stdOutBuffered(lines, d->m_stdOut.firstBuffer);
d->m_stdOut.firstBuffer = false;
}
}
@@ -512,20 +547,21 @@ void SynchronousProcess::processStdOut(bool emitSignals)
void SynchronousProcess::processStdErr(bool emitSignals)
{
// Handle binary data
- const QByteArray ba = d->m_process.readAllStandardError();
+ const QString stdError = convertOutput(d->m_process.readAllStandardError(),
+ &d->m_stdErrState);
if (debug > 1)
- qDebug() << Q_FUNC_INFO << emitSignals << ba;
- if (!ba.isEmpty()) {
- d->m_stdErr.data += ba;
+ qDebug() << Q_FUNC_INFO << emitSignals << stdError;
+ if (!stdError.isEmpty()) {
+ d->m_stdErr.data += stdError;
if (emitSignals) {
// Emit binary signals
- emit stdErr(ba, d->m_stdErr.firstData);
+ emit stdErr(stdError, d->m_stdErr.firstData);
d->m_stdErr.firstData = false;
if (d->m_stdErr.bufferedSignalsEnabled) {
// Buffered. Emit complete lines?
- const QByteArray lines = d->m_stdErr.linesRead();
+ const QString lines = d->m_stdErr.linesRead();
if (!lines.isEmpty()) {
- emit stdErrBuffered(convertStdErr(lines), d->m_stdErr.firstBuffer);
+ emit stdErrBuffered(lines, d->m_stdErr.firstBuffer);
d->m_stdErr.firstBuffer = false;
}
}
@@ -622,11 +658,11 @@ static QString checkBinary(const QDir &dir, const QString &binary)
return QString();
switch (HostOsInfo::hostOs()) {
- case HostOsInfo::HostOsLinux:
- case HostOsInfo::HostOsOtherUnix:
- case HostOsInfo::HostOsOther:
+ case OsTypeLinux:
+ case OsTypeOtherUnix:
+ case OsTypeOther:
break;
- case HostOsInfo::HostOsWindows: {
+ case OsTypeWindows: {
static const char *windowsExtensions[] = {".cmd", ".bat", ".exe", ".com" };
// Check the Windows extensions using the order
const int windowsExtensionCount = sizeof(windowsExtensions)/sizeof(const char*);
@@ -637,7 +673,7 @@ static QString checkBinary(const QDir &dir, const QString &binary)
}
}
break;
- case HostOsInfo::HostOsMac: {
+ case OsTypeMac: {
// Check for Mac app folders
const QFileInfo appFolder(dir.filePath(binary + QLatin1String(".app")));
if (appFolder.isDir()) {
@@ -681,6 +717,25 @@ QString SynchronousProcess::locateBinary(const QString &path, const QString &bin
return QString();
}
+QString SynchronousProcess::normalizeNewlines(const QString &text)
+{
+ const QChar cr(QLatin1Char('\r'));
+ const QChar lf(QLatin1Char('\n'));
+ QString res;
+ res.reserve(text.size());
+ for (int i = 0, count = text.size(); i < count; ++i) {
+ const QChar c = text.at(i);
+ if (c == cr) {
+ res += lf;
+ if (i + 1 < count && text.at(i + 1) == lf)
+ ++i;
+ } else {
+ res += c;
+ }
+ }
+ return res;
+}
+
QString SynchronousProcess::locateBinary(const QString &binary)
{
const QByteArray path = qgetenv("PATH");
diff --git a/src/libs/utils/synchronousprocess.h b/src/libs/utils/synchronousprocess.h
index b90c660468..8cb224f00a 100644
--- a/src/libs/utils/synchronousprocess.h
+++ b/src/libs/utils/synchronousprocess.h
@@ -34,11 +34,9 @@
#include <QProcess>
#include <QSharedPointer>
+#include <QTextCodec>
-QT_BEGIN_NAMESPACE
-class QTextCodec;
-class QDebug;
-QT_END_NAMESPACE
+QT_FORWARD_DECLARE_CLASS(QDebug)
namespace Utils {
@@ -73,6 +71,14 @@ struct QTCREATOR_UTILS_EXPORT SynchronousProcessResponse
QTCREATOR_UTILS_EXPORT QDebug operator<<(QDebug str, const SynchronousProcessResponse &);
+class QTCREATOR_UTILS_EXPORT ExitCodeInterpreter : public QObject
+{
+ Q_OBJECT
+public:
+ ExitCodeInterpreter(QObject *parent) : QObject(parent) {}
+ virtual SynchronousProcessResponse::Result interpretExitCode(int code) const;
+};
+
class QTCREATOR_UTILS_EXPORT SynchronousProcess : public QObject
{
Q_OBJECT
@@ -90,8 +96,8 @@ public:
void setTimeout(int timeoutMS);
int timeout() const;
- void setStdOutCodec(QTextCodec *c);
- QTextCodec *stdOutCodec() const;
+ void setCodec(QTextCodec *c);
+ QTextCodec *codec() const;
QProcess::ProcessChannelMode processChannelMode () const;
void setProcessChannelMode(QProcess::ProcessChannelMode m);
@@ -117,6 +123,9 @@ public:
unsigned flags() const;
void setFlags(unsigned);
+ void setExitCodeInterpreter(ExitCodeInterpreter *interpreter);
+ ExitCodeInterpreter *exitCodeInterpreter() const;
+
SynchronousProcessResponse run(const QString &binary, const QStringList &args);
// Create a (derived) processes with flags applied.
@@ -138,13 +147,18 @@ public:
static QString locateBinary(const QString &binary);
static QString locateBinary(const QString &path, const QString &binary);
+ static QString normalizeNewlines(const QString &text);
+
signals:
- void stdOut(const QByteArray &data, bool firstTime);
- void stdErr(const QByteArray &data, bool firstTime);
+ void stdOut(const QString &text, bool firstTime);
+ void stdErr(const QString &text, bool firstTime);
void stdOutBuffered(const QString &data, bool firstTime);
void stdErrBuffered(const QString &data, bool firstTime);
+public slots:
+ bool terminate();
+
private slots:
void slotTimeout();
void finished(int exitCode, QProcess::ExitStatus e);
@@ -155,8 +169,7 @@ private slots:
private:
void processStdOut(bool emitSignals);
void processStdErr(bool emitSignals);
- static QString convertStdErr(const QByteArray &);
- QString convertStdOut(const QByteArray &) const;
+ QString convertOutput(const QByteArray &, QTextCodec::ConverterState *state) const;
SynchronousProcessPrivate *d;
};
diff --git a/src/libs/utils/textfileformat.cpp b/src/libs/utils/textfileformat.cpp
index 90cb0eec57..bbd90e7a8a 100644
--- a/src/libs/utils/textfileformat.cpp
+++ b/src/libs/utils/textfileformat.cpp
@@ -271,6 +271,39 @@ TextFileFormat::ReadResult
return result;
}
+TextFileFormat::ReadResult TextFileFormat::readFileUTF8(const QString &fileName,
+ QByteArray *plainText, QString *errorString)
+{
+ QByteArray data;
+ try {
+ Utils::FileReader reader;
+ if (!reader.fetch(fileName, errorString))
+ return TextFileFormat::ReadIOError;
+ data = reader.data();
+ } catch (const std::bad_alloc &) {
+ *errorString = QCoreApplication::translate("Utils::TextFileFormat", "Out of memory.");
+ return TextFileFormat::ReadMemoryAllocationError;
+ }
+
+ TextFileFormat format = TextFileFormat::detect(data);
+ if (!format.codec)
+ format.codec = QTextCodec::codecForLocale();
+ if (format.codec->name() == "UTF-8") {
+ if (format.hasUtf8Bom)
+ data.remove(0, 3);
+ *plainText = data;
+ return TextFileFormat::ReadSuccess;
+ }
+
+ QString target;
+ if (!format.decode(data, &target)) {
+ *errorString = QCoreApplication::translate("Utils::TextFileFormat", "An encoding error was encountered.");
+ return TextFileFormat::ReadEncodingError;
+ }
+ *plainText = target.toUtf8();
+ return TextFileFormat::ReadSuccess;
+}
+
/*!
Writes out a text file.
*/
diff --git a/src/libs/utils/textfileformat.h b/src/libs/utils/textfileformat.h
index 9f3825b51f..91121c9a9d 100644
--- a/src/libs/utils/textfileformat.h
+++ b/src/libs/utils/textfileformat.h
@@ -76,6 +76,8 @@ public:
static ReadResult readFile(const QString &fileName, const QTextCodec *defaultCodec,
QString *plainText, TextFileFormat *format, QString *errorString,
QByteArray *decodingErrorSample = 0);
+ static ReadResult readFileUTF8(const QString &fileName, QByteArray *plainText,
+ QString *errorString);
bool writeFile(const QString &fileName, QString plainText, QString *errorString) const;
diff --git a/src/libs/utils/tooltip/tipcontents.cpp b/src/libs/utils/tooltip/tipcontents.cpp
index 147a25f610..9a2d376690 100644
--- a/src/libs/utils/tooltip/tipcontents.cpp
+++ b/src/libs/utils/tooltip/tipcontents.cpp
@@ -185,7 +185,7 @@ bool WidgetContent::pinToolTip(QWidget *w)
for (QWidget *p = w->parentWidget(); p ; p = p->parentWidget()) {
if (Internal::WidgetTip *wt = qobject_cast<Internal::WidgetTip *>(p)) {
wt->pinToolTipWidget();
- ToolTip::instance()->hide();
+ ToolTip::hide();
return true;
}
}
diff --git a/src/libs/utils/tooltip/tooltip.cpp b/src/libs/utils/tooltip/tooltip.cpp
index ab2ade2293..efa35e1b64 100644
--- a/src/libs/utils/tooltip/tooltip.cpp
+++ b/src/libs/utils/tooltip/tooltip.cpp
@@ -67,7 +67,8 @@ ToolTip *ToolTip::instance()
void ToolTip::show(const QPoint &pos, const TipContent &content, QWidget *w, const QRect &rect)
{
- if (acceptShow(content, pos, w, rect)) {
+ ToolTip *t = instance();
+ if (t->acceptShow(content, pos, w, rect)) {
QWidget *target = 0;
if (HostOsInfo::isWindowsHost())
target = QApplication::desktop()->screen(Internal::screenNumber(pos, w));
@@ -76,18 +77,18 @@ void ToolTip::show(const QPoint &pos, const TipContent &content, QWidget *w, con
switch (content.typeId()) {
case TextContent::TEXT_CONTENT_ID:
- m_tip = new TextTip(target);
+ t->m_tip = new TextTip(target);
break;
case ColorContent::COLOR_CONTENT_ID:
- m_tip = new ColorTip(target);
+ t->m_tip = new ColorTip(target);
break;
case WidgetContent::WIDGET_CONTENT_ID:
- m_tip = new WidgetTip(target);
+ t->m_tip = new WidgetTip(target);
break;
}
- setUp(pos, content, w, rect);
- qApp->installEventFilter(this);
- showTip();
+ t->setUp(pos, content, w, rect);
+ qApp->installEventFilter(t);
+ t->showTip();
}
}
@@ -162,17 +163,18 @@ bool ToolTip::tipChanged(const QPoint &pos, const TipContent &content, QWidget *
void ToolTip::setTipRect(QWidget *w, const QRect &rect)
{
- if (!m_rect.isNull() && !w)
+ if (!m_rect.isNull() && !w) {
qWarning("ToolTip::show: Cannot pass null widget if rect is set");
- else{
+ } else {
m_widget = w;
m_rect = rect;
}
}
-bool ToolTip::isVisible() const
+bool ToolTip::isVisible()
{
- return m_tip && m_tip->isVisible();
+ ToolTip *t = instance();
+ return t->m_tip && t->m_tip->isVisible();
}
void ToolTip::showTip()
@@ -191,7 +193,7 @@ void ToolTip::showTip()
void ToolTip::hide()
{
- hideTipWithDelay();
+ instance()->hideTipWithDelay();
}
void ToolTip::hideTipWithDelay()
@@ -293,13 +295,3 @@ bool ToolTip::eventFilter(QObject *o, QEvent *event)
}
return false;
}
-
-QFont ToolTip::font() const
-{
- return QApplication::font("QTipLabel");
-}
-
-void ToolTip::setFont(const QFont &font)
-{
- QApplication::setFont(font, "QTipLabel");
-}
diff --git a/src/libs/utils/tooltip/tooltip.h b/src/libs/utils/tooltip/tooltip.h
index c8ca4f51a4..180c06383c 100644
--- a/src/libs/utils/tooltip/tooltip.h
+++ b/src/libs/utils/tooltip/tooltip.h
@@ -60,28 +60,24 @@ class TipContent;
class QTCREATOR_UTILS_EXPORT ToolTip : public QObject
{
Q_OBJECT
-private:
- ToolTip();
public:
- virtual ~ToolTip();
-
- static ToolTip *instance();
+ ~ToolTip();
- void show(const QPoint &pos, const TipContent &content, QWidget *w = 0);
- void show(const QPoint &pos, const TipContent &content, QWidget *w, const QRect &rect);
- void hide();
- bool isVisible() const;
+ bool eventFilter(QObject *o, QEvent *event);
- QFont font() const;
- void setFont(const QFont &font);
+ static ToolTip *instance();
- virtual bool eventFilter(QObject *o, QEvent *event);
+ static void show(const QPoint &pos, const TipContent &content, QWidget *w = 0);
+ static void show(const QPoint &pos, const TipContent &content, QWidget *w, const QRect &rect);
+ static void hide();
+ static bool isVisible();
private slots:
void hideTipImmediately();
private:
+ ToolTip();
bool acceptShow(const TipContent &content, const QPoint &pos, QWidget *w, const QRect &rect);
bool validateContent(const TipContent &content);
void setUp(const QPoint &pos, const TipContent &content, QWidget *w, const QRect &rect);
diff --git a/src/libs/utils/unixutils.cpp b/src/libs/utils/unixutils.cpp
index 07e85701a0..f049a8645c 100644
--- a/src/libs/utils/unixutils.cpp
+++ b/src/libs/utils/unixutils.cpp
@@ -75,15 +75,15 @@ QString UnixUtils::substituteFileBrowserParameters(const QString &pre, const QSt
if (c == QLatin1Char('%') && i < pre.size()-1) {
c = pre.at(++i);
QString s;
- if (c == QLatin1Char('d'))
+ if (c == QLatin1Char('d')) {
s = QLatin1Char('"') + QFileInfo(file).path() + QLatin1Char('"');
- else if (c == QLatin1Char('f'))
+ } else if (c == QLatin1Char('f')) {
s = QLatin1Char('"') + file + QLatin1Char('"');
- else if (c == QLatin1Char('n'))
+ } else if (c == QLatin1Char('n')) {
s = QLatin1Char('"') + QFileInfo(file).fileName() + QLatin1Char('"');
- else if (c == QLatin1Char('%'))
+ } else if (c == QLatin1Char('%')) {
s = c;
- else {
+ } else {
s = QLatin1Char('%');
s += c;
}
diff --git a/src/libs/utils/utils-lib.pri b/src/libs/utils/utils-lib.pri
index 138c65bf45..97833eb8e7 100644
--- a/src/libs/utils/utils-lib.pri
+++ b/src/libs/utils/utils-lib.pri
@@ -4,7 +4,6 @@ dll {
DEFINES += QTCREATOR_UTILS_STATIC_LIB
}
-INCLUDEPATH += $$PWD
QT += script network
CONFIG += exceptions # used by portlist.cpp, textfileformat.cpp, and ssh/*
@@ -74,6 +73,7 @@ SOURCES += $$PWD/environment.cpp \
$$PWD/portlist.cpp \
$$PWD/tcpportsgatherer.cpp \
$$PWD/appmainwindow.cpp \
+ $$PWD/sleep.cpp \
$$PWD/basetreeview.cpp \
$$PWD/qtcassert.cpp \
$$PWD/elfreader.cpp \
@@ -84,7 +84,9 @@ SOURCES += $$PWD/environment.cpp \
$$PWD/tooltip/tooltip.cpp \
$$PWD/tooltip/tips.cpp \
$$PWD/tooltip/tipcontents.cpp \
- $$PWD/unixutils.cpp
+ $$PWD/unixutils.cpp \
+ $$PWD/function.cpp \
+ $$PWD/ansiescapecodehandler.cpp
win32 {
SOURCES += \
@@ -162,11 +164,13 @@ HEADERS += \
$$PWD/portlist.h \
$$PWD/tcpportsgatherer.h \
$$PWD/appmainwindow.h \
+ $$PWD/sleep.h \
$$PWD/basetreeview.h \
$$PWD/elfreader.h \
$$PWD/bracematcher.h \
$$PWD/proxyaction.h \
$$PWD/hostosinfo.h \
+ $$PWD/osspecificaspects.h \
$$PWD/elidinglabel.h \
$$PWD/tooltip/tooltip.h \
$$PWD/tooltip/tips.h \
@@ -174,7 +178,9 @@ HEADERS += \
$$PWD/tooltip/reuse.h \
$$PWD/tooltip/effects.h \
$$PWD/unixutils.h \
- $$PWD/qtcoverride.h
+ $$PWD/qtcoverride.h \
+ $$PWD/function.h \
+ $$PWD/ansiescapecodehandler.h
FORMS += $$PWD/filewizardpage.ui \
$$PWD/projectintropage.ui \
diff --git a/src/libs/utils/utils.qbs b/src/libs/utils/utils.qbs
index 61f3bba82d..f3b058936f 100644
--- a/src/libs/utils/utils.qbs
+++ b/src/libs/utils/utils.qbs
@@ -25,6 +25,8 @@ QtcLibrary {
files: [
"annotateditemdelegate.cpp",
"annotateditemdelegate.h",
+ "ansiescapecodehandler.cpp",
+ "ansiescapecodehandler.h",
"appmainwindow.cpp",
"appmainwindow.h",
"basetreeview.cpp",
@@ -87,6 +89,8 @@ QtcLibrary {
"filterlineedit.h",
"flowlayout.cpp",
"flowlayout.h",
+ "function.cpp",
+ "function.h",
"historycompleter.cpp",
"historycompleter.h",
"hostosinfo.h",
@@ -110,6 +114,7 @@ QtcLibrary {
"newclasswidget.cpp",
"newclasswidget.h",
"newclasswidget.ui",
+ "osspecificaspects.h",
"outputformat.h",
"outputformatter.cpp",
"outputformatter.h",
@@ -146,6 +151,8 @@ QtcLibrary {
"settingsselector.cpp",
"settingsselector.h",
"settingsutils.h",
+ "sleep.cpp",
+ "sleep.h",
"statuslabel.cpp",
"statuslabel.h",
"stringutils.cpp",
@@ -214,7 +221,6 @@ QtcLibrary {
}
Export {
- cpp.includePaths: [ ".." ]
Depends { name: "Qt"; submodules: ["concurrent", "widgets" ] }
}
}
diff --git a/src/libs/utils/winutils.cpp b/src/libs/utils/winutils.cpp
index 01ed4d2a0c..cf54a24d4f 100644
--- a/src/libs/utils/winutils.cpp
+++ b/src/libs/utils/winutils.cpp
@@ -177,12 +177,6 @@ QTCREATOR_UTILS_EXPORT QString normalizePathName(const QString &name)
return canonicalName;
}
-QTCREATOR_UTILS_EXPORT unsigned long winQPidToPid(const Q_PID qpid)
-{
- const PROCESS_INFORMATION *processInfo = reinterpret_cast<const PROCESS_INFORMATION*>(qpid);
- return processInfo->dwProcessId;
-}
-
QTCREATOR_UTILS_EXPORT bool winIs64BitSystem()
{
SYSTEM_INFO systemInfo;
diff --git a/src/libs/utils/winutils.h b/src/libs/utils/winutils.h
index b50f73c6cc..c69a1c6b15 100644
--- a/src/libs/utils/winutils.h
+++ b/src/libs/utils/winutils.h
@@ -59,8 +59,6 @@ QTCREATOR_UTILS_EXPORT QString getLongPathName(const QString &name);
// Returns long name with canonical capitalization.
QTCREATOR_UTILS_EXPORT QString normalizePathName(const QString &name);
-QTCREATOR_UTILS_EXPORT unsigned long winQPidToPid(const Q_PID qpid);
-
QTCREATOR_UTILS_EXPORT bool winIs64BitSystem();
// Check for a 64bit binary.
diff --git a/src/libs/zeroconf/servicebrowser.cpp b/src/libs/zeroconf/servicebrowser.cpp
index ea26ccd166..0e6f26eeab 100644
--- a/src/libs/zeroconf/servicebrowser.cpp
+++ b/src/libs/zeroconf/servicebrowser.cpp
@@ -336,7 +336,7 @@ bool Service::operator==(const Service &o) const {
&& m_name == o.m_name && m_type == o.m_type
&& m_domain == o.m_domain && m_port == o.m_port
&& m_txtRecord == o.m_txtRecord && m_interfaceNr == o.m_interfaceNr
- && m_outdated == m_outdated;
+ && m_outdated == o.m_outdated;
if (eq) {
if (m_host != o.m_host) {
if (m_host == 0 || o.m_host == 0)
diff --git a/src/pluginjsonmetadata.xsl b/src/pluginjsonmetadata.xsl
index dff00332b7..bd85083a00 100644
--- a/src/pluginjsonmetadata.xsl
+++ b/src/pluginjsonmetadata.xsl
@@ -15,6 +15,9 @@
<xsl:template match="vendor">
"Vendor" : "<xsl:apply-templates/>",
</xsl:template>
+<xsl:template match="platform">
+"Platform" : "<xsl:apply-templates/>",
+</xsl:template>
<xsl:template match="category">
"Category" : "<xsl:apply-templates/>",
</xsl:template>
diff --git a/src/plugins/QtcPlugin.qbs b/src/plugins/QtcPlugin.qbs
index fcd6533e99..fd78073cde 100644
--- a/src/plugins/QtcPlugin.qbs
+++ b/src/plugins/QtcPlugin.qbs
@@ -1,6 +1,6 @@
import qbs.base 1.0
import qbs.FileInfo
-import "../../qbs/defaults.js" as Defaults
+import "../../qbs/functions.js" as QtcFunctions
Product {
type: ["dynamiclibrary", "pluginSpec"]
@@ -8,25 +8,32 @@ Product {
property var pluginspecreplacements
property var pluginRecommends: []
- targetName: Defaults.qtLibraryName(qbs, name)
+ Depends { name: "Qt.core" }
+ property string minimumQtVersion: "4.8"
+ condition: QtcFunctions.versionIsAtLeast(Qt.core.version, minimumQtVersion)
+
+ targetName: QtcFunctions.qtLibraryName(qbs, name)
+ destinationDirectory: project.ide_plugin_path + '/' + provider
Depends { name: "ExtensionSystem" }
Depends { name: "pluginspec" }
Depends { name: "cpp" }
Depends {
- condition: Defaults.testsEnabled(qbs)
+ condition: project.testsEnabled
name: "Qt.test"
}
- cpp.defines: Defaults.defines(qbs).concat([name.toUpperCase() + "_LIBRARY"])
+ cpp.defines: project.generalDefines.concat([name.toUpperCase() + "_LIBRARY"])
cpp.installNamePrefix: "@rpath/PlugIns/" + provider + "/"
cpp.rpaths: qbs.targetOS.contains("osx") ? ["@loader_path/../..", "@executable_path/.."]
: ["$ORIGIN", "$ORIGIN/..", "$ORIGIN/../.."]
cpp.linkerFlags: {
if (qbs.buildVariant == "release" && (qbs.toolchain.contains("gcc") || qbs.toolchain.contains("mingw")))
return ["-Wl,-s"]
+ else if (qbs.buildVariant == "debug" && qbs.toolchain.contains("msvc"))
+ return ["/INCREMENTAL:NO"] // Speed up startup time when debugging with cdb
}
- cpp.includePaths: [ ".", ".." ]
+ cpp.includePaths: [path]
Group {
name: "PluginSpec"
@@ -47,5 +54,7 @@ Product {
Export {
Depends { name: "ExtensionSystem" }
+ Depends { name: "cpp" }
+ cpp.includePaths: [path]
}
}
diff --git a/src/plugins/analyzerbase/AnalyzerBase.pluginspec.in b/src/plugins/analyzerbase/AnalyzerBase.pluginspec.in
index 8af44ee37e..f552de7c6a 100644
--- a/src/plugins/analyzerbase/AnalyzerBase.pluginspec.in
+++ b/src/plugins/analyzerbase/AnalyzerBase.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"AnalyzerBase\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"AnalyzerBase\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/analyzerbase/analyzerbase.pro b/src/plugins/analyzerbase/analyzerbase.pro
index d768b6e5a6..e734ffcb1c 100644
--- a/src/plugins/analyzerbase/analyzerbase.pro
+++ b/src/plugins/analyzerbase/analyzerbase.pro
@@ -7,28 +7,22 @@ QT += network
# AnalyzerBase files
SOURCES += \
- ianalyzerengine.cpp \
ianalyzertool.cpp \
analyzerplugin.cpp \
analyzerruncontrol.cpp \
analyzermanager.cpp \
- analyzersettings.cpp \
- analyzeroptionspage.cpp \
analyzerrunconfigwidget.cpp \
analyzerutils.cpp \
startremotedialog.cpp
HEADERS += \
- ianalyzerengine.h \
ianalyzertool.h \
analyzerbase_global.h \
analyzerconstants.h \
analyzerplugin.h \
analyzerruncontrol.h \
analyzermanager.h \
- analyzersettings.h \
analyzerstartparameters.h \
- analyzeroptionspage.h \
analyzerrunconfigwidget.h \
analyzerutils.h \
startremotedialog.h
diff --git a/src/plugins/analyzerbase/analyzerbase.qbs b/src/plugins/analyzerbase/analyzerbase.qbs
index 44658b96ab..47216b5aa4 100644
--- a/src/plugins/analyzerbase/analyzerbase.qbs
+++ b/src/plugins/analyzerbase/analyzerbase.qbs
@@ -18,21 +18,15 @@ QtcPlugin {
"analyzerconstants.h",
"analyzermanager.cpp",
"analyzermanager.h",
- "analyzeroptionspage.cpp",
- "analyzeroptionspage.h",
"analyzerplugin.cpp",
"analyzerplugin.h",
"analyzerrunconfigwidget.cpp",
"analyzerrunconfigwidget.h",
"analyzerruncontrol.cpp",
"analyzerruncontrol.h",
- "analyzersettings.cpp",
- "analyzersettings.h",
"analyzerstartparameters.h",
"analyzerutils.cpp",
"analyzerutils.h",
- "ianalyzerengine.cpp",
- "ianalyzerengine.h",
"ianalyzertool.cpp",
"ianalyzertool.h",
"startremotedialog.cpp",
diff --git a/src/plugins/analyzerbase/analyzerconstants.h b/src/plugins/analyzerbase/analyzerconstants.h
index 5034e5531d..c346670f52 100644
--- a/src/plugins/analyzerbase/analyzerconstants.h
+++ b/src/plugins/analyzerbase/analyzerconstants.h
@@ -43,9 +43,7 @@ namespace Analyzer {
enum StartMode
{
StartLocal = -1,
- StartRemote = -2,
- StartQml = -3,
- StartQmlRemote = -4 // TODO: remove this enum and make it generic
+ StartRemote = -2
};
namespace Constants {
diff --git a/src/plugins/analyzerbase/analyzermanager.cpp b/src/plugins/analyzerbase/analyzermanager.cpp
index 5101e20854..6fe2f45a9f 100644
--- a/src/plugins/analyzerbase/analyzermanager.cpp
+++ b/src/plugins/analyzerbase/analyzermanager.cpp
@@ -32,7 +32,6 @@
#include "analyzerplugin.h"
#include "ianalyzertool.h"
-#include "analyzersettings.h"
#include <coreplugin/coreconstants.h>
#include <coreplugin/findplaceholder.h>
@@ -49,6 +48,7 @@
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/project.h>
#include <projectexplorer/buildconfiguration.h>
+#include <projectexplorer/session.h>
#include <projectexplorer/target.h>
#include <utils/fancymainwindow.h>
@@ -72,6 +72,7 @@
#include <QPushButton>
using namespace Core;
+using namespace Utils;
using namespace Core::Constants;
using namespace Analyzer::Internal;
using namespace Analyzer::Constants;
@@ -146,18 +147,16 @@ public:
void activateDock(Qt::DockWidgetArea area, QDockWidget *dockWidget);
void deactivateDock(QDockWidget *dockWidget);
- void addTool(IAnalyzerTool *tool, const StartModes &modes);
+ void addAction(AnalyzerAction *action);
void selectSavedTool();
- void selectTool(IAnalyzerTool *tool, StartMode mode);
+ void selectAction(AnalyzerAction *action);
void handleToolStarted();
void handleToolFinished();
- void saveToolSettings(IAnalyzerTool *tool, StartMode mode);
- void loadToolSettings(IAnalyzerTool *tool);
- QAction *actionFromToolAndMode(IAnalyzerTool *tool, StartMode mode);
+ void saveToolSettings(AnalyzerAction *action);
+ void loadToolSettings(AnalyzerAction *action);
// Convenience.
- void startLocalTool(IAnalyzerTool *tool);
- bool isActionRunnable(QAction *action) const;
+ bool isActionRunnable(AnalyzerAction *action) const;
public slots:
void startTool();
@@ -171,20 +170,15 @@ public:
AnalyzerManager *q;
AnalyzerMode *m_mode;
bool m_isRunning;
- Utils::FancyMainWindow *m_mainWindow;
- IAnalyzerTool *m_currentTool;
- StartMode m_currentMode;
- QAction *m_currentAction;
- QHash<QAction *, IAnalyzerTool *> m_toolFromAction;
- QHash<QAction *, StartMode> m_modeFromAction;
- QList<IAnalyzerTool *> m_tools;
- QList<QAction *> m_actions;
+ FancyMainWindow *m_mainWindow;
+ AnalyzerAction *m_currentAction;
+ QList<AnalyzerAction *> m_actions;
QAction *m_startAction;
QAction *m_stopAction;
ActionContainer *m_menu;
QComboBox *m_toolBox;
QStackedWidget *m_controlsStackWidget;
- Utils::StatusLabel *m_statusLabel;
+ StatusLabel *m_statusLabel;
typedef QMap<IAnalyzerTool *, FancyMainWindowSettings> MainWindowSettingsMap;
QHash<IAnalyzerTool *, QList<QDockWidget *> > m_toolWidgets;
QHash<IAnalyzerTool *, QWidget *> m_controlsWidgetFromTool;
@@ -200,15 +194,13 @@ AnalyzerManagerPrivate::AnalyzerManagerPrivate(AnalyzerManager *qq):
m_mode(0),
m_isRunning(false),
m_mainWindow(0),
- m_currentTool(0),
- m_currentMode(),
m_currentAction(0),
m_startAction(0),
m_stopAction(0),
m_menu(0),
m_toolBox(new QComboBox),
m_controlsStackWidget(new QStackedWidget),
- m_statusLabel(new Utils::StatusLabel)
+ m_statusLabel(new StatusLabel)
{
m_toolBox->setObjectName(QLatin1String("AnalyzerManagerToolBox"));
connect(m_toolBox, SIGNAL(activated(int)), SLOT(selectToolboxAction(int)));
@@ -297,19 +289,19 @@ void AnalyzerManagerPrivate::delayedInit()
Context analyzerContext(C_ANALYZEMODE);
ActionContainer *viewsMenu = Core::ActionManager::actionContainer(Id(M_WINDOW_VIEWS));
Command *cmd = Core::ActionManager::registerAction(m_mainWindow->menuSeparator1(),
- Id("Analyzer.Views.Separator1"), analyzerContext);
+ "Analyzer.Views.Separator1", analyzerContext);
cmd->setAttribute(Command::CA_Hide);
viewsMenu->addAction(cmd, G_DEFAULT_THREE);
cmd = Core::ActionManager::registerAction(m_mainWindow->toggleLockedAction(),
- Id("Analyzer.Views.ToggleLocked"), analyzerContext);
+ "Analyzer.Views.ToggleLocked", analyzerContext);
cmd->setAttribute(Command::CA_Hide);
viewsMenu->addAction(cmd, G_DEFAULT_THREE);
cmd = Core::ActionManager::registerAction(m_mainWindow->menuSeparator2(),
- Id("Analyzer.Views.Separator2"), analyzerContext);
+ "Analyzer.Views.Separator2", analyzerContext);
cmd->setAttribute(Command::CA_Hide);
viewsMenu->addAction(cmd, G_DEFAULT_THREE);
cmd = Core::ActionManager::registerAction(m_mainWindow->resetLayoutAction(),
- Id("Analyzer.Views.ResetSimple"), analyzerContext);
+ "Analyzer.Views.ResetSimple", analyzerContext);
cmd->setAttribute(Command::CA_Hide);
viewsMenu->addAction(cmd, G_DEFAULT_THREE);
}
@@ -323,7 +315,7 @@ static QToolButton *toolButton(QAction *action)
void AnalyzerManagerPrivate::createModeMainWindow()
{
- m_mainWindow = new Utils::FancyMainWindow();
+ m_mainWindow = new FancyMainWindow();
m_mainWindow->setObjectName(QLatin1String("AnalyzerManagerMainWindow"));
m_mainWindow->setDocumentMode(true);
m_mainWindow->setDockNestingEnabled(true);
@@ -345,14 +337,14 @@ void AnalyzerManagerPrivate::createModeMainWindow()
documentAndRightPane->setStretchFactor(0, 1);
documentAndRightPane->setStretchFactor(1, 0);
- Utils::StyledBar *analyzeToolBar = new Utils::StyledBar;
+ StyledBar *analyzeToolBar = new StyledBar;
analyzeToolBar->setProperty("topBorder", true);
QHBoxLayout *analyzeToolBarLayout = new QHBoxLayout(analyzeToolBar);
analyzeToolBarLayout->setMargin(0);
analyzeToolBarLayout->setSpacing(0);
analyzeToolBarLayout->addWidget(toolButton(m_startAction));
analyzeToolBarLayout->addWidget(toolButton(m_stopAction));
- analyzeToolBarLayout->addWidget(new Utils::StyledSeparator);
+ analyzeToolBarLayout->addWidget(new StyledSeparator);
analyzeToolBarLayout->addWidget(m_toolBox);
analyzeToolBarLayout->addWidget(m_controlsStackWidget);
analyzeToolBarLayout->addWidget(m_statusLabel);
@@ -409,26 +401,10 @@ void AnalyzerManagerPrivate::deactivateDock(QDockWidget *dockWidget)
dockWidget->setParent(0);
}
-bool buildTypeAccepted(IAnalyzerTool::ToolMode toolMode,
- BuildConfiguration::BuildType buildType)
-{
- if (toolMode == IAnalyzerTool::AnyMode)
- return true;
- if (buildType == BuildConfiguration::Unknown)
- return true;
- if (buildType == BuildConfiguration::Debug
- && toolMode == IAnalyzerTool::DebugMode)
- return true;
- if (buildType == BuildConfiguration::Release
- && toolMode == IAnalyzerTool::ReleaseMode)
- return true;
- return false;
-}
-
bool AnalyzerManagerPrivate::showPromptDialog(const QString &title, const QString &text,
const QString &stopButtonText, const QString &cancelButtonText) const
{
- Utils::CheckableMessageBox messageBox(ICore::mainWindow());
+ CheckableMessageBox messageBox(ICore::mainWindow());
messageBox.setWindowTitle(title);
messageBox.setText(text);
messageBox.setStandardButtons(QDialogButtonBox::Yes|QDialogButtonBox::Cancel);
@@ -438,102 +414,25 @@ bool AnalyzerManagerPrivate::showPromptDialog(const QString &title, const QStrin
messageBox.button(QDialogButtonBox::Cancel)->setText(cancelButtonText);
messageBox.setDefaultButton(QDialogButtonBox::Yes);
messageBox.setCheckBoxVisible(false);
- messageBox.exec();;
+ messageBox.exec();
return messageBox.clickedStandardButton() == QDialogButtonBox::Yes;
}
-void AnalyzerManagerPrivate::startLocalTool(IAnalyzerTool *tool)
-{
- int index = m_tools.indexOf(tool);
- QTC_ASSERT(index >= 0, return);
- QTC_ASSERT(index < m_tools.size(), return);
- QTC_ASSERT(tool == m_currentTool, return);
-
- // Make sure mode is shown.
- q->showMode();
-
- ProjectExplorerPlugin *pe = ProjectExplorerPlugin::instance();
-
- // ### not sure if we're supposed to check if the RunConFiguration isEnabled
- Project *pro = pe->startupProject();
- BuildConfiguration::BuildType buildType = BuildConfiguration::Unknown;
- if (pro) {
- if (const Target *target = pro->activeTarget()) {
- // Build configuration is 0 for QML projects.
- if (const BuildConfiguration *buildConfig = target->activeBuildConfiguration())
- buildType = buildConfig->buildType();
- }
- }
-
- IAnalyzerTool::ToolMode toolMode = tool->toolMode();
-
- // Check the project for whether the build config is in the correct mode
- // if not, notify the user and urge him to use the correct mode.
- if (!buildTypeAccepted(toolMode, buildType)) {
- const QString toolName = tool->displayName();
- const QString currentMode =
- buildType == BuildConfiguration::Debug ? tr("Debug") : tr("Release");
-
- QSettings *settings = ICore::settings();
- const QString configKey = QLatin1String("Analyzer.AnalyzeCorrectMode");
- int ret;
- if (settings->contains(configKey)) {
- ret = settings->value(configKey, QDialog::Accepted).toInt();
- } else {
- QString toolModeString;
- switch (toolMode) {
- case IAnalyzerTool::DebugMode:
- toolModeString = tr("Debug");
- break;
- case IAnalyzerTool::ReleaseMode:
- toolModeString = tr("Release");
- break;
- default:
- QTC_CHECK(false);
- }
- const QString title = tr("Run %1 in %2 Mode?").arg(toolName).arg(currentMode);
- const QString message = tr("<html><head/><body><p>You are trying "
- "to run the tool \"%1\" on an application in %2 mode. "
- "The tool is designed to be used in %3 mode.</p><p>"
- "Debug and Release mode run-time characteristics differ "
- "significantly, analytical findings for one mode may or "
- "may not be relevant for the other.</p><p>"
- "Do you want to continue and run the tool in %2 mode?</p></body></html>")
- .arg(toolName).arg(currentMode).arg(toolModeString);
- const QString checkBoxText = tr("&Do not ask again");
- bool checkBoxSetting = false;
- const QDialogButtonBox::StandardButton button =
- Utils::CheckableMessageBox::question(ICore::mainWindow(),
- title, message, checkBoxText,
- &checkBoxSetting, QDialogButtonBox::Yes|QDialogButtonBox::Cancel,
- QDialogButtonBox::Cancel);
- ret = button == QDialogButtonBox::Yes ? QDialog::Accepted : QDialog::Rejected;
-
- if (checkBoxSetting && ret == QDialog::Accepted)
- settings->setValue(configKey, ret);
- }
- if (ret == QDialog::Rejected)
- return;
- }
-
- pe->runProject(pro, tool->runMode());
-}
-
-bool AnalyzerManagerPrivate::isActionRunnable(QAction *action) const
+bool AnalyzerManagerPrivate::isActionRunnable(AnalyzerAction *action) const
{
if (!action || m_isRunning)
return false;
- if (m_modeFromAction.value(action) == StartRemote)
+ if (action->startMode() == StartRemote)
return true;
- IAnalyzerTool *tool = m_toolFromAction.value(action);
ProjectExplorerPlugin *pe = ProjectExplorerPlugin::instance();
- return pe->canRun(pe->startupProject(), tool->runMode());
+ return pe->canRun(SessionManager::startupProject(), action->tool()->runMode());
}
void AnalyzerManagerPrivate::startTool()
{
- m_currentTool->startTool(m_currentMode);
+ QTC_ASSERT(m_currentAction, return);
+ m_currentAction->tool()->startTool(m_currentAction->startMode());
}
void AnalyzerManagerPrivate::modeChanged(IMode *mode)
@@ -550,78 +449,57 @@ void AnalyzerManagerPrivate::modeChanged(IMode *mode)
}
}
-QAction *AnalyzerManagerPrivate::actionFromToolAndMode(IAnalyzerTool *tool, StartMode mode)
-{
- foreach (QAction *action, m_actions)
- if (m_toolFromAction.value(action) == tool && m_modeFromAction[action] == mode)
- return action;
- QTC_CHECK(false);
- return 0;
-}
-
void AnalyzerManagerPrivate::selectSavedTool()
{
const QSettings *settings = ICore::settings();
if (settings->contains(QLatin1String(LAST_ACTIVE_TOOL))) {
- const Id lastActiveAction = Id::fromSetting(settings->value(QLatin1String(LAST_ACTIVE_TOOL)));
- foreach (QAction *action, m_actions) {
- IAnalyzerTool *tool = m_toolFromAction.value(action);
- StartMode mode = m_modeFromAction.value(action);
- if (tool->actionId(mode) == lastActiveAction) {
- selectTool(tool, mode);
+ const Id lastAction = Id::fromSetting(settings->value(QLatin1String(LAST_ACTIVE_TOOL)));
+ foreach (AnalyzerAction *action, m_actions) {
+ if (action->id() == lastAction) {
+ selectAction(action);
return;
}
}
}
// fallback to first available tool
- if (!m_actions.isEmpty()) {
- IAnalyzerTool *tool = m_toolFromAction.value(m_actions.first());
- StartMode mode = m_modeFromAction.value(m_actions.first());
- selectTool(tool, mode);
- }
+ if (!m_actions.isEmpty())
+ selectAction(m_actions.first());
}
void AnalyzerManagerPrivate::selectMenuAction()
{
- QAction *action = qobject_cast<QAction *>(sender());
- QTC_ASSERT(action, return);
- IAnalyzerTool *tool = m_toolFromAction.value(action);
- StartMode mode = m_modeFromAction.value(action);
-
AnalyzerManager::showMode();
- selectTool(tool, mode);
- tool->startTool(mode);
+ AnalyzerAction *action = qobject_cast<AnalyzerAction *>(sender());
+ QTC_ASSERT(action, return);
+ selectAction(action);
+ startTool();
}
void AnalyzerManagerPrivate::selectToolboxAction(int index)
{
- QAction *action = m_actions[index];
- selectTool(m_toolFromAction.value(action), m_modeFromAction.value(action));
+ selectAction(m_actions[index]);
}
-void AnalyzerManagerPrivate::selectTool(IAnalyzerTool *tool, StartMode mode)
+void AnalyzerManagerPrivate::selectAction(AnalyzerAction *action)
{
- if (m_currentTool == tool && m_currentMode == mode)
+ if (m_currentAction == action)
return;
- QAction *action = actionFromToolAndMode(tool, mode);
const int actionIndex = m_actions.indexOf(action);
QTC_ASSERT(actionIndex >= 0, return);
// Clean up old tool.
- if (m_currentTool) {
- saveToolSettings(m_currentTool, m_currentMode);
- foreach (QDockWidget *widget, m_toolWidgets.value(m_currentTool))
+ if (m_currentAction) {
+ saveToolSettings(m_currentAction);
+ foreach (QDockWidget *widget, m_toolWidgets.value(m_currentAction->tool()))
deactivateDock(widget);
- m_currentTool->toolDeselected();
}
// Now change the tool.
- m_currentTool = tool;
- m_currentMode = mode;
m_currentAction = action;
+ IAnalyzerTool *tool = action->tool();
if (!m_defaultSettings.contains(tool)) {
QWidget *widget = tool->createWidgets();
QTC_CHECK(widget);
@@ -633,7 +511,7 @@ void AnalyzerManagerPrivate::selectTool(IAnalyzerTool *tool, StartMode mode)
foreach (QDockWidget *widget, m_toolWidgets.value(tool))
activateDock(Qt::DockWidgetArea(widget->property(INITIAL_DOCK_AREA).toInt()), widget);
- loadToolSettings(tool);
+ loadToolSettings(action);
QTC_CHECK(m_controlsWidgetFromTool.contains(tool));
m_controlsStackWidget->setCurrentWidget(m_controlsWidgetFromTool.value(tool));
@@ -642,30 +520,22 @@ void AnalyzerManagerPrivate::selectTool(IAnalyzerTool *tool, StartMode mode)
updateRunActions();
}
-void AnalyzerManagerPrivate::addTool(IAnalyzerTool *tool, const StartModes &modes)
+void AnalyzerManagerPrivate::addAction(AnalyzerAction *action)
{
delayedInit(); // Make sure that there is a valid IMode instance.
const bool blocked = m_toolBox->blockSignals(true); // Do not make current.
- foreach (StartMode mode, modes) {
- QString actionName = tool->actionName(mode);
- Id menuGroup = tool->menuGroup(mode);
- Id actionId = tool->actionId(mode);
- QAction *action = new QAction(actionName, this);
- Command *command = Core::ActionManager::registerAction(action, actionId, Context(C_GLOBAL));
+
+ Id menuGroup = action->menuGroup();
+ if (menuGroup.isValid()) {
+ Command *command = ActionManager::registerAction(action, action->id(), Context(C_GLOBAL));
m_menu->addAction(command, menuGroup);
- command->action()->setData(int(StartLocal));
- // Assuming this happens before project loading.
- if (mode == StartLocal)
- command->action()->setEnabled(false);
- m_actions.append(action);
- m_toolFromAction[action] = tool;
- m_modeFromAction[action] = mode;
- m_toolBox->addItem(actionName);
- m_toolBox->blockSignals(blocked);
- connect(action, SIGNAL(triggered()), SLOT(selectMenuAction()));
}
- m_tools.append(tool);
+
+ m_actions.append(action);
+ m_toolBox->addItem(action->text());
+ m_toolBox->blockSignals(blocked);
+ connect(action, SIGNAL(triggered()), SLOT(selectMenuAction()));
m_toolBox->setEnabled(true);
}
@@ -681,52 +551,49 @@ void AnalyzerManagerPrivate::handleToolFinished()
updateRunActions();
}
-void AnalyzerManagerPrivate::loadToolSettings(IAnalyzerTool *tool)
+void AnalyzerManagerPrivate::loadToolSettings(AnalyzerAction *action)
{
QTC_ASSERT(m_mainWindow, return);
QSettings *settings = ICore::settings();
- settings->beginGroup(QLatin1String("AnalyzerViewSettings_") + tool->id().toString());
+ settings->beginGroup(QLatin1String("AnalyzerViewSettings_") + action->id().toString());
if (settings->value(QLatin1String("ToolSettingsSaved"), false).toBool())
m_mainWindow->restoreSettings(settings);
else
- m_mainWindow->restoreSettings(m_defaultSettings.value(tool));
+ m_mainWindow->restoreSettings(m_defaultSettings.value(action->tool()));
settings->endGroup();
}
-void AnalyzerManagerPrivate::saveToolSettings(IAnalyzerTool *tool, StartMode mode)
+void AnalyzerManagerPrivate::saveToolSettings(AnalyzerAction *action)
{
- if (!tool)
- return; // no active tool, do nothing
+ QTC_ASSERT(action, return);
QTC_ASSERT(m_mainWindow, return);
QSettings *settings = ICore::settings();
- settings->beginGroup(QLatin1String("AnalyzerViewSettings_") + tool->id().toString());
+ settings->beginGroup(QLatin1String("AnalyzerViewSettings_") + action->id().toString());
m_mainWindow->saveSettings(settings);
settings->setValue(QLatin1String("ToolSettingsSaved"), true);
settings->endGroup();
- settings->setValue(QLatin1String(LAST_ACTIVE_TOOL), tool->actionId(mode).toString());
+ settings->setValue(QLatin1String(LAST_ACTIVE_TOOL), action->id().toString());
}
void AnalyzerManagerPrivate::updateRunActions()
{
ProjectExplorerPlugin *pe = ProjectExplorerPlugin::instance();
- Project *project = pe->startupProject();
-
- bool startEnabled = isActionRunnable(m_currentAction);
+ Project *project = SessionManager::startupProject();
QString disabledReason;
if (m_isRunning)
disabledReason = tr("An analysis is still in progress.");
- else if (!m_currentTool)
+ else if (!m_currentAction)
disabledReason = tr("No analyzer tool selected.");
else
- disabledReason = pe->cannotRunReason(project, m_currentTool->runMode());
+ disabledReason = pe->cannotRunReason(project, m_currentAction->tool()->runMode());
- m_startAction->setEnabled(startEnabled);
+ m_startAction->setEnabled(isActionRunnable(m_currentAction));
m_startAction->setToolTip(disabledReason);
m_toolBox->setEnabled(!m_isRunning);
m_stopAction->setEnabled(m_isRunning);
- foreach (QAction *action, m_actions)
+ foreach (AnalyzerAction *action, m_actions)
action->setEnabled(isActionRunnable(action));
}
@@ -736,45 +603,37 @@ void AnalyzerManagerPrivate::updateRunActions()
//
////////////////////////////////////////////////////////////////////
-static AnalyzerManager *m_instance = 0;
+static AnalyzerManagerPrivate *d = 0;
AnalyzerManager::AnalyzerManager(QObject *parent)
- : QObject(parent),
- d(new AnalyzerManagerPrivate(this))
+ : QObject(parent)
{
- m_instance = this;
+ QTC_CHECK(d == 0);
+ d = new AnalyzerManagerPrivate(this);
}
AnalyzerManager::~AnalyzerManager()
{
+ QTC_CHECK(d);
delete d;
-}
-
-void AnalyzerManager::extensionsInitialized()
-{
- if (m_instance->d->m_tools.isEmpty())
- return;
-
- foreach (IAnalyzerTool *tool, m_instance->d->m_tools)
- tool->extensionsInitialized();
+ d = 0;
}
void AnalyzerManager::shutdown()
{
- m_instance->d->saveToolSettings(m_instance->d->m_currentTool, m_instance->d->m_currentMode);
+ if (d->m_currentAction)
+ d->saveToolSettings(d->m_currentAction);
}
-void AnalyzerManager::addTool(IAnalyzerTool *tool, const StartModes &modes)
+void AnalyzerManager::addAction(AnalyzerAction *action)
{
- m_instance->d->addTool(tool, modes);
- AnalyzerGlobalSettings::instance()->registerTool(tool);
+ d->addAction(action);
}
QDockWidget *AnalyzerManager::createDockWidget(IAnalyzerTool *tool, const QString &title,
QWidget *widget, Qt::DockWidgetArea area)
{
QTC_ASSERT(!widget->objectName().isEmpty(), return 0);
- AnalyzerManagerPrivate *d = m_instance->d;
QDockWidget *dockWidget = d->m_mainWindow->addDockForWidget(widget);
dockWidget->setProperty(INITIAL_DOCK_AREA, int(area));
d->m_dockWidgets.append(AnalyzerManagerPrivate::DockPtr(dockWidget));
@@ -783,40 +642,32 @@ QDockWidget *AnalyzerManager::createDockWidget(IAnalyzerTool *tool, const QStrin
return dockWidget;
}
-IAnalyzerTool *AnalyzerManager::currentSelectedTool()
-{
- return m_instance->d->m_currentTool;
-}
-
-QList<IAnalyzerTool *> AnalyzerManager::tools()
-{
- return m_instance->d->m_tools;
-}
-
void AnalyzerManager::selectTool(IAnalyzerTool *tool, StartMode mode)
{
- m_instance->d->selectTool(tool, mode);
+ foreach (AnalyzerAction *action, d->m_actions)
+ if (action->tool() == tool && action->startMode() == mode)
+ d->selectAction(action);
}
-void AnalyzerManager::startTool(IAnalyzerTool *tool, StartMode mode)
+void AnalyzerManager::startTool()
{
- QTC_ASSERT(tool == m_instance->d->m_currentTool, return);
- tool->startTool(mode);
+ d->startTool();
}
-Utils::FancyMainWindow *AnalyzerManager::mainWindow()
+FancyMainWindow *AnalyzerManager::mainWindow()
{
- return m_instance->d->m_mainWindow;
+ return d->m_mainWindow;
}
void AnalyzerManagerPrivate::resetLayout()
{
- m_mainWindow->restoreSettings(m_defaultSettings.value(m_currentTool));
+ QTC_ASSERT(m_currentAction, return);
+ m_mainWindow->restoreSettings(m_defaultSettings.value(m_currentAction->tool()));
}
void AnalyzerManager::showStatusMessage(const QString &message, int timeoutMS)
{
- m_instance->d->m_statusLabel->showStatusMessage(message, timeoutMS);
+ d->m_statusLabel->showStatusMessage(message, timeoutMS);
}
void AnalyzerManager::showPermanentStatusMessage(const QString &message)
@@ -824,22 +675,10 @@ void AnalyzerManager::showPermanentStatusMessage(const QString &message)
showStatusMessage(message, -1);
}
-QString AnalyzerManager::msgToolStarted(const QString &name)
-{
- return tr("Tool \"%1\" started...").arg(name);
-}
-
-QString AnalyzerManager::msgToolFinished(const QString &name, int issuesFound)
-{
- return issuesFound ?
- tr("Tool \"%1\" finished, %n issues were found.", 0, issuesFound).arg(name) :
- tr("Tool \"%1\" finished, no issues were found.").arg(name);
-}
-
void AnalyzerManager::showMode()
{
- if (m_instance->d->m_mode)
- ModeManager::activateMode(m_instance->d->m_mode->id());
+ if (d->m_mode)
+ ModeManager::activateMode(d->m_mode->id());
}
void AnalyzerManager::stopTool()
@@ -847,31 +686,30 @@ void AnalyzerManager::stopTool()
stopAction()->trigger();
}
-void AnalyzerManager::startLocalTool(IAnalyzerTool *tool)
-{
- m_instance->d->startLocalTool(tool);
-}
-
QAction *AnalyzerManager::stopAction()
{
- return m_instance->d->m_stopAction;
+ return d->m_stopAction;
}
void AnalyzerManager::handleToolStarted()
{
- m_instance->d->handleToolStarted();
+ d->handleToolStarted();
}
void AnalyzerManager::handleToolFinished()
{
- m_instance->d->handleToolFinished();
+ d->handleToolFinished();
}
-IAnalyzerTool *AnalyzerManager::toolFromRunMode(RunMode runMode)
+AnalyzerRunControl *AnalyzerManager::createRunControl(
+ const AnalyzerStartParameters &sp, RunConfiguration *runConfiguration)
{
- foreach (IAnalyzerTool *tool, m_instance->d->m_tools)
- if (tool->runMode() == runMode)
- return tool;
+ foreach (AnalyzerAction *action, d->m_actions) {
+ IAnalyzerTool *tool = action->tool();
+ if (tool->runMode() == sp.runMode && action->startMode() == sp.startMode)
+ return tool->createRunControl(sp, runConfiguration);
+ }
+ QTC_CHECK(false);
return 0;
}
diff --git a/src/plugins/analyzerbase/analyzermanager.h b/src/plugins/analyzerbase/analyzermanager.h
index 7c34066feb..7ea42c0b18 100644
--- a/src/plugins/analyzerbase/analyzermanager.h
+++ b/src/plugins/analyzerbase/analyzermanager.h
@@ -43,16 +43,15 @@ class QDockWidget;
class QAction;
QT_END_NAMESPACE
-namespace Utils {
-class FancyMainWindow;
-}
+namespace Utils { class FancyMainWindow; }
+namespace ProjectExplorer { class RunConfiguration; }
namespace Analyzer {
-typedef QList<StartMode> StartModes;
-
class IAnalyzerTool;
-class AnalyzerManagerPrivate;
+class AnalyzerAction;
+class AnalyzerRunControl;
+class AnalyzerStartParameters;
// FIXME: Merge with AnalyzerPlugin.
@@ -64,12 +63,10 @@ public:
explicit AnalyzerManager(QObject *parent);
~AnalyzerManager();
- static void extensionsInitialized();
static void shutdown();
- // Register a tool and initialize it.
- static void addTool(IAnalyzerTool *tool, const StartModes &mode);
- static IAnalyzerTool *toolFromRunMode(ProjectExplorer::RunMode runMode);
+ // Register a tool for a given start mode.
+ static void addAction(AnalyzerAction *action);
// Dockwidgets are registered to the main window.
static QDockWidget *createDockWidget(IAnalyzerTool *tool, const QString &title,
@@ -78,18 +75,11 @@ public:
static Utils::FancyMainWindow *mainWindow();
static void showMode();
- static IAnalyzerTool *currentSelectedTool();
- static QList<IAnalyzerTool *> tools();
static void selectTool(IAnalyzerTool *tool, StartMode mode);
- static void startTool(IAnalyzerTool *tool, StartMode mode);
+ static void startTool();
static void stopTool();
// Convenience functions.
- static void startLocalTool(IAnalyzerTool *tool);
-
- static QString msgToolStarted(const QString &name);
- static QString msgToolFinished(const QString &name, int issuesFound);
-
static void showStatusMessage(const QString &message, int timeoutMS = 10000);
static void showPermanentStatusMessage(const QString &message);
@@ -97,9 +87,8 @@ public:
static void handleToolFinished();
static QAction *stopAction();
-private:
- friend class AnalyzerManagerPrivate;
- AnalyzerManagerPrivate *const d;
+ static AnalyzerRunControl *createRunControl(const AnalyzerStartParameters &sp,
+ ProjectExplorer::RunConfiguration *runConfiguration);
};
} // namespace Analyzer
diff --git a/src/plugins/analyzerbase/analyzerplugin.cpp b/src/plugins/analyzerbase/analyzerplugin.cpp
index ba8b86e0cc..621e5f6d99 100644
--- a/src/plugins/analyzerbase/analyzerplugin.cpp
+++ b/src/plugins/analyzerbase/analyzerplugin.cpp
@@ -66,17 +66,11 @@ bool AnalyzerPlugin::initialize(const QStringList &arguments, QString *errorStri
// Task integration.
//: Category under which Analyzer tasks are listed in Issues view
- ProjectExplorer::ProjectExplorerPlugin::instance()->taskHub()
- ->addCategory(Core::Id(Constants::ANALYZERTASK_ID), tr("Analyzer"));
+ ProjectExplorer::TaskHub::addCategory(Constants::ANALYZERTASK_ID, tr("Analyzer"));
return true;
}
-void AnalyzerPlugin::extensionsInitialized()
-{
- AnalyzerManager::extensionsInitialized();
-}
-
ExtensionSystem::IPlugin::ShutdownFlag AnalyzerPlugin::aboutToShutdown()
{
AnalyzerManager::shutdown();
diff --git a/src/plugins/analyzerbase/analyzerplugin.h b/src/plugins/analyzerbase/analyzerplugin.h
index add489b73a..2afaf12df1 100644
--- a/src/plugins/analyzerbase/analyzerplugin.h
+++ b/src/plugins/analyzerbase/analyzerplugin.h
@@ -48,7 +48,7 @@ public:
virtual ~AnalyzerPlugin();
bool initialize(const QStringList &arguments, QString *errorString);
- void extensionsInitialized();
+ void extensionsInitialized() {}
ShutdownFlag aboutToShutdown();
};
diff --git a/src/plugins/analyzerbase/analyzerrunconfigwidget.cpp b/src/plugins/analyzerbase/analyzerrunconfigwidget.cpp
index 196cb41c41..65a24e6041 100644
--- a/src/plugins/analyzerbase/analyzerrunconfigwidget.cpp
+++ b/src/plugins/analyzerbase/analyzerrunconfigwidget.cpp
@@ -30,6 +30,7 @@
#include "analyzerrunconfigwidget.h"
+#include <utils/detailswidget.h>
#include <utils/qtcassert.h>
#include <QDebug>
@@ -40,32 +41,16 @@
#include <QPushButton>
namespace Analyzer {
-namespace Internal {
-AnalyzerToolDetailWidget::AnalyzerToolDetailWidget(AbstractAnalyzerSubConfig *config, QWidget *parent)
- : Utils::DetailsWidget(parent)
+AnalyzerRunConfigWidget::AnalyzerRunConfigWidget(ProjectExplorer::IRunConfigurationAspect *aspect)
{
- QTC_ASSERT(config!=0, return);
-
- // update summary text
- setSummaryText(tr("<strong>%1</strong> settings").arg(config->displayName()));
-
- // create config widget
- QWidget *configWidget = config->createConfigWidget(this);
- setWidget(configWidget);
-}
-
-AnalyzerRunConfigWidget::AnalyzerRunConfigWidget()
-{
- QVBoxLayout *layout = new QVBoxLayout(this);
- layout->setContentsMargins(0, 0, 0, 0);
+ m_aspect = aspect;
+ m_config = aspect->projectSettings();
- QWidget *globalSetting = new QWidget(this);
+ QWidget *globalSetting = new QWidget;
QHBoxLayout *globalSettingLayout = new QHBoxLayout(globalSetting);
globalSettingLayout->setContentsMargins(0, 0, 0, 0);
- layout->addWidget(globalSetting);
- QLabel *label = new QLabel(tr("Analyzer settings:"), globalSetting);
- globalSettingLayout->addWidget(label);
+
m_settingsCombo = new QComboBox(globalSetting);
m_settingsCombo->addItems(QStringList()
<< QApplication::translate("ProjectExplorer::Internal::EditorSettingsPropertiesPage", "Global")
@@ -80,52 +65,47 @@ AnalyzerRunConfigWidget::AnalyzerRunConfigWidget()
connect(m_restoreButton, SIGNAL(clicked()), this, SLOT(restoreGlobal()));
globalSettingLayout->addStretch(2);
- m_subConfigWidget = new QWidget(this);
- QVBoxLayout *subConfigLayout = new QVBoxLayout(m_subConfigWidget);
- subConfigLayout->setContentsMargins(0, 0, 0, 0);
- layout->addWidget(m_subConfigWidget);
-}
+ QWidget *innerPane = new QWidget;
+ m_configWidget = m_config->createConfigWidget(innerPane);
-QString AnalyzerRunConfigWidget::displayName() const
-{
- return tr("Analyzer Settings");
-}
+ QVBoxLayout *layout = new QVBoxLayout(innerPane);
+ layout->setContentsMargins(0, 0, 0, 0);
+ layout->addWidget(globalSetting);
+ layout->addWidget(m_configWidget);
-void AnalyzerRunConfigWidget::setRunConfigurationAspect(AnalyzerRunConfigurationAspect *aspect)
-{
- QTC_ASSERT(aspect, return);
- m_aspect = aspect;
+ m_details = new Utils::DetailsWidget;
+ m_details->setWidget(innerPane);
- // add config widget for each sub config
- foreach (AbstractAnalyzerSubConfig *config, m_aspect->customSubConfigs()) {
- QWidget *widget = new AnalyzerToolDetailWidget(config);
- m_subConfigWidget->layout()->addWidget(widget);
- }
- setDetailEnabled(!m_aspect->isUsingGlobalSettings());
- m_settingsCombo->setCurrentIndex(m_aspect->isUsingGlobalSettings() ? 0 : 1);
- m_restoreButton->setEnabled(!m_aspect->isUsingGlobalSettings());
+ QVBoxLayout *outerLayout = new QVBoxLayout(this);
+ outerLayout->addWidget(m_details);
+ outerLayout->setContentsMargins(0, 0, 0, 0);
+
+ chooseSettings(m_aspect->isUsingGlobalSettings() ? 0 : 1);
}
-void AnalyzerRunConfigWidget::setDetailEnabled(bool value)
+QString AnalyzerRunConfigWidget::displayName() const
{
- QList<AnalyzerToolDetailWidget*> details = findChildren<AnalyzerToolDetailWidget*>();
- foreach (AnalyzerToolDetailWidget *detail, details)
- detail->widget()->setEnabled(value);
+ return m_aspect->displayName();
}
void AnalyzerRunConfigWidget::chooseSettings(int setting)
{
QTC_ASSERT(m_aspect, return);
- setDetailEnabled(setting != 0);
- m_aspect->setUsingGlobalSettings(setting == 0);
- m_restoreButton->setEnabled(!m_aspect->isUsingGlobalSettings());
+ bool isCustom = (setting == 1);
+
+ m_settingsCombo->setCurrentIndex(setting);
+ m_aspect->setUsingGlobalSettings(!isCustom);
+ m_configWidget->setEnabled(isCustom);
+ m_restoreButton->setEnabled(isCustom);
+ m_details->setSummaryText(isCustom
+ ? tr("Use <strong>Customized Settings<strong>")
+ : tr("Use <strong>Global Settings<strong>"));
}
void AnalyzerRunConfigWidget::restoreGlobal()
{
QTC_ASSERT(m_aspect, return);
- m_aspect->resetCustomToGlobalSettings();
+ m_aspect->resetProjectToGlobalSettings();
}
-} // namespace Internal
} // namespace Analyzer
diff --git a/src/plugins/analyzerbase/analyzerrunconfigwidget.h b/src/plugins/analyzerbase/analyzerrunconfigwidget.h
index 09af6ee2ae..8db6670172 100644
--- a/src/plugins/analyzerbase/analyzerrunconfigwidget.h
+++ b/src/plugins/analyzerbase/analyzerrunconfigwidget.h
@@ -28,63 +28,44 @@
**
****************************************************************************/
-#ifndef ANALYZER_INTERNAL_ANALYZERRUNCONFIGWIDGET_H
-#define ANALYZER_INTERNAL_ANALYZERRUNCONFIGWIDGET_H
+#ifndef ANALYZERRUNCONFIGWIDGET_H
+#define ANALYZERRUNCONFIGWIDGET_H
-#include "analyzersettings.h"
+#include "analyzerbase_global.h"
-#include <utils/detailswidget.h>
+#include <projectexplorer/runconfiguration.h>
QT_BEGIN_NAMESPACE
class QComboBox;
class QPushButton;
QT_END_NAMESPACE
-namespace Utils {
-class DetailsWidget;
-}
+namespace Utils { class DetailsWidget; }
namespace Analyzer {
-class AnalyzerSettings;
-class AbstractAnalyzerSubConfig;
-
-namespace Internal {
-
-class AnalyzerToolDetailWidget : public Utils::DetailsWidget
+class ANALYZER_EXPORT AnalyzerRunConfigWidget : public ProjectExplorer::RunConfigWidget
{
Q_OBJECT
public:
- explicit AnalyzerToolDetailWidget(AbstractAnalyzerSubConfig *config, QWidget *parent=0);
-};
-
-class AnalyzerRunConfigWidget : public ProjectExplorer::RunConfigWidget
-{
- Q_OBJECT
+ AnalyzerRunConfigWidget(ProjectExplorer::IRunConfigurationAspect *aspect);
-public:
- AnalyzerRunConfigWidget();
-
- virtual QString displayName() const;
-
- void setRunConfigurationAspect(AnalyzerRunConfigurationAspect *aspect);
-
-private:
- void setDetailEnabled(bool value);
+ QString displayName() const;
private slots:
void chooseSettings(int setting);
void restoreGlobal();
private:
- QWidget *m_subConfigWidget;
- AnalyzerRunConfigurationAspect *m_aspect;
+ QWidget *m_configWidget;
+ ProjectExplorer::IRunConfigurationAspect *m_aspect;
+ ProjectExplorer::ISettingsAspect *m_config;
QComboBox *m_settingsCombo;
QPushButton *m_restoreButton;
+ Utils::DetailsWidget *m_details;
};
-} // namespace Internal
} // namespace Analyzer
-#endif // ANALYZER_INTERNAL_ANALYZERRUNCONFIGWIDGET_H
+#endif // ANALYZERRUNCONFIGWIDGET_H
diff --git a/src/plugins/analyzerbase/analyzerruncontrol.cpp b/src/plugins/analyzerbase/analyzerruncontrol.cpp
index f7197126a7..bd8f9190d1 100644
--- a/src/plugins/analyzerbase/analyzerruncontrol.cpp
+++ b/src/plugins/analyzerbase/analyzerruncontrol.cpp
@@ -29,14 +29,10 @@
****************************************************************************/
#include "analyzerruncontrol.h"
-#include "ianalyzerengine.h"
#include "ianalyzertool.h"
#include "analyzermanager.h"
#include "analyzerstartparameters.h"
-#include <projectexplorer/projectexplorer.h>
-#include <projectexplorer/taskhub.h>
-
#include <QDebug>
#include <QAction>
@@ -44,117 +40,63 @@ using namespace ProjectExplorer;
//////////////////////////////////////////////////////////////////////////
//
-// AnalyzerRunControl::Private
+// AnalyzerRunControl
//
//////////////////////////////////////////////////////////////////////////
namespace Analyzer {
-class AnalyzerRunControl::Private
-{
-public:
- Private();
-
- bool m_isRunning;
- IAnalyzerEngine *m_engine;
-};
-
-AnalyzerRunControl::Private::Private()
- : m_isRunning(false), m_engine(0)
-{}
-
-
-//////////////////////////////////////////////////////////////////////////
-//
-// AnalyzerRunControl
-//
-//////////////////////////////////////////////////////////////////////////
-
-AnalyzerRunControl::AnalyzerRunControl(IAnalyzerTool *tool,
- const AnalyzerStartParameters &sp, RunConfiguration *runConfiguration)
- : RunControl(runConfiguration, tool->runMode()),
- d(new Private)
+AnalyzerRunControl::AnalyzerRunControl(const AnalyzerStartParameters &sp,
+ ProjectExplorer::RunConfiguration *runConfiguration)
+ : RunControl(runConfiguration, sp.runMode)
{
- d->m_engine = tool->createEngine(sp, runConfiguration);
-
- if (!d->m_engine)
- return;
-
- connect(d->m_engine, SIGNAL(outputReceived(QString,Utils::OutputFormat)),
- SLOT(receiveOutput(QString,Utils::OutputFormat)));
- connect(d->m_engine, SIGNAL(taskToBeAdded(ProjectExplorer::Task::TaskType,QString,QString,int)),
- SLOT(addTask(ProjectExplorer::Task::TaskType,QString,QString,int)));
- connect(d->m_engine, SIGNAL(finished()),
- SLOT(engineFinished()));
+ m_runConfig = runConfiguration;
+ m_sp = sp;
+ connect(this, SIGNAL(finished()), SLOT(runControlFinished()));
connect(AnalyzerManager::stopAction(), SIGNAL(triggered()), SLOT(stopIt()));
}
-AnalyzerRunControl::~AnalyzerRunControl()
+void AnalyzerRunControl::stopIt()
{
- if (d->m_isRunning)
- stop();
+ if (stop() == RunControl::StoppedSynchronously)
+ AnalyzerManager::handleToolFinished();
+}
- delete d->m_engine;
- d->m_engine = 0;
- delete d;
+void AnalyzerRunControl::runControlFinished()
+{
+ m_isRunning = false;
+ AnalyzerManager::handleToolFinished();
}
void AnalyzerRunControl::start()
{
- if (!d->m_engine) {
- emit finished();
- return;
- }
-
AnalyzerManager::handleToolStarted();
- // Clear about-to-be-outdated tasks.
- ProjectExplorerPlugin::instance()->taskHub()
- ->clearTasks(Core::Id(Constants::ANALYZERTASK_ID));
-
- if (d->m_engine->start()) {
- d->m_isRunning = true;
+ if (startEngine()) {
+ m_isRunning = true;
emit started();
}
}
RunControl::StopResult AnalyzerRunControl::stop()
{
- if (!d->m_engine || !d->m_isRunning)
+ if (!m_isRunning)
return StoppedSynchronously;
- d->m_engine->stop();
- d->m_isRunning = false;
+ stopEngine();
+ m_isRunning = false;
return AsynchronousStop;
}
-void AnalyzerRunControl::stopIt()
-{
- if (stop() == RunControl::StoppedSynchronously)
- AnalyzerManager::handleToolFinished();
-}
-
-void AnalyzerRunControl::engineFinished()
-{
- d->m_isRunning = false;
- AnalyzerManager::handleToolFinished();
- emit finished();
-}
-
bool AnalyzerRunControl::isRunning() const
{
- return d->m_isRunning;
+ return m_isRunning;
}
QString AnalyzerRunControl::displayName() const
{
- if (!d->m_engine)
- return QString();
- if (d->m_engine->runConfiguration())
- return d->m_engine->runConfiguration()->displayName();
- else
- return d->m_engine->startParameters().displayName;
+ return m_runConfig ? m_runConfig->displayName() : m_sp.displayName;
}
QIcon AnalyzerRunControl::icon() const
@@ -162,23 +104,4 @@ QIcon AnalyzerRunControl::icon() const
return QIcon(QLatin1String(":/images/analyzer_start_small.png"));
}
-IAnalyzerEngine *AnalyzerRunControl::engine() const
-{
- return d->m_engine;
-}
-
-void AnalyzerRunControl::receiveOutput(const QString &text, Utils::OutputFormat format)
-{
- appendMessage(text, format);
-}
-
-void AnalyzerRunControl::addTask(Task::TaskType type, const QString &description,
- const QString &file, int line)
-{
- TaskHub *hub = ProjectExplorerPlugin::instance()->taskHub();
- hub->addTask(Task(type, description, Utils::FileName::fromUserInput(file), line,
- Core::Id(Constants::ANALYZERTASK_ID)));
- hub->requestPopup();
-}
-
} // namespace Analyzer
diff --git a/src/plugins/analyzerbase/analyzerruncontrol.h b/src/plugins/analyzerbase/analyzerruncontrol.h
index bf5a27e4d9..f831e97379 100644
--- a/src/plugins/analyzerbase/analyzerruncontrol.h
+++ b/src/plugins/analyzerbase/analyzerruncontrol.h
@@ -36,20 +36,55 @@
#include <projectexplorer/runconfiguration.h>
#include <projectexplorer/task.h>
-namespace Analyzer {
+#include "analyzerbase_global.h"
+#include "analyzerstartparameters.h"
+
+#include <projectexplorer/task.h>
+#include <projectexplorer/runconfiguration.h>
+#include <utils/outputformat.h>
-class AnalyzerStartParameters;
-class IAnalyzerTool;
-class IAnalyzerEngine;
+#include <QObject>
+#include <QString>
+namespace ProjectExplorer { class RunConfiguration; }
+
+namespace Analyzer {
+
+/**
+ * An AnalyzerRunControl instance handles the launch of an analyzation tool.
+ *
+ * It gets created for each launch and deleted when the launch is stopped or ended.
+ */
class ANALYZER_EXPORT AnalyzerRunControl : public ProjectExplorer::RunControl
{
Q_OBJECT
public:
- AnalyzerRunControl(IAnalyzerTool *tool, const AnalyzerStartParameters &sp,
+ AnalyzerRunControl(const AnalyzerStartParameters &sp,
ProjectExplorer::RunConfiguration *runConfiguration);
- ~AnalyzerRunControl();
+
+ /// Start analyzation process.
+ virtual bool startEngine() = 0;
+ /// Trigger async stop of the analyzation process.
+ virtual void stopEngine() = 0;
+
+ /// Controller actions.
+ virtual bool canPause() const { return false; }
+ virtual void pause() {}
+ virtual void unpause() {}
+
+ /// The active run configuration for this engine, might be zero.
+ ProjectExplorer::RunConfiguration *runConfiguration() const { return m_runConfig; }
+
+ /// The start parameters for this engine.
+ const AnalyzerStartParameters &startParameters() const { return m_sp; }
+
+ StartMode mode() const { return m_sp.startMode; }
+
+ virtual void notifyRemoteSetupDone(quint16) {}
+ virtual void notifyRemoteFinished(bool) {}
+
+ bool m_isRunning;
// ProjectExplorer::RunControl
void start();
@@ -58,22 +93,21 @@ public:
QString displayName() const;
QIcon icon() const;
- IAnalyzerEngine *engine() const;
+public slots:
+ virtual void logApplicationMessage(const QString &, Utils::OutputFormat) {}
private slots:
void stopIt();
- void receiveOutput(const QString &, Utils::OutputFormat format);
+ void runControlFinished();
- void addTask(ProjectExplorer::Task::TaskType type, const QString &description,
- const QString &file, int line);
-
- void engineFinished();
+signals:
+ /// Must be emitted when the engine is starting.
+ void starting(const Analyzer::AnalyzerRunControl *);
private:
- class Private;
- Private *d;
+ ProjectExplorer::RunConfiguration *m_runConfig;
+ AnalyzerStartParameters m_sp;
};
-
} // namespace Analyzer
#endif // ANALYZERRUNCONTROL_H
diff --git a/src/plugins/analyzerbase/analyzersettings.cpp b/src/plugins/analyzerbase/analyzersettings.cpp
deleted file mode 100644
index 6ce78412f8..0000000000
--- a/src/plugins/analyzerbase/analyzersettings.cpp
+++ /dev/null
@@ -1,239 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
-** Contact: http://www.qt-project.org/legal
-** Author: Milian Wolff, KDAB (milian.wolff@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 "analyzersettings.h"
-
-#include "analyzermanager.h"
-#include "analyzerrunconfigwidget.h"
-#include "ianalyzertool.h"
-#include "analyzerplugin.h"
-#include "analyzeroptionspage.h"
-
-#include <coreplugin/icore.h>
-#include <utils/qtcassert.h>
-
-#include <QSettings>
-
-using namespace Analyzer::Internal;
-
-static const char groupC[] = "Analyzer";
-static const char useGlobalC[] = "Analyzer.Project.UseGlobal";
-
-namespace Analyzer {
-
-AnalyzerGlobalSettings *AnalyzerGlobalSettings::m_instance = 0;
-
-AnalyzerSettings::AnalyzerSettings(QObject *parent)
- : QObject(parent)
-{
-}
-
-AnalyzerSettings::AnalyzerSettings(const AnalyzerSettings *other)
-{
- Q_UNUSED(other);
-}
-
-QVariantMap AnalyzerSettings::defaults() const
-{
- QVariantMap map;
- foreach (AbstractAnalyzerSubConfig *config, subConfigs()) {
- map.unite(config->defaults());
- }
- return map;
-}
-
-void AnalyzerSettings::fromMap(const QVariantMap &map)
-{
- fromMap(map, &m_subConfigs);
-}
-
-void AnalyzerSettings::fromMap(const QVariantMap &map, QList<AbstractAnalyzerSubConfig *> *subConfigs)
-{
- foreach (AbstractAnalyzerSubConfig *config, *subConfigs)
- config->fromMap(map);
-}
-
-QVariantMap AnalyzerSettings::toMap() const
-{
- return toMap(m_subConfigs);
-}
-
-QVariantMap AnalyzerSettings::toMap(const QList<AbstractAnalyzerSubConfig *> &subConfigs) const
-{
- QVariantMap map;
- foreach (AbstractAnalyzerSubConfig *config, subConfigs) {
- map.unite(config->toMap());
- }
- return map;
-}
-
-
-AnalyzerGlobalSettings::AnalyzerGlobalSettings(QObject *parent)
-: AnalyzerSettings(parent)
-{
- QTC_ASSERT(!m_instance, return);
- m_instance = this;
-}
-
-AnalyzerGlobalSettings *AnalyzerGlobalSettings::instance()
-{
- if (!m_instance)
- m_instance = new AnalyzerGlobalSettings(AnalyzerPlugin::instance());
-
- return m_instance;
-}
-
-AnalyzerGlobalSettings::~AnalyzerGlobalSettings()
-{
- m_instance = 0;
- qDeleteAll(m_subConfigs);
-}
-
-void AnalyzerGlobalSettings::readSettings()
-{
- QSettings *settings = Core::ICore::settings();
-
- QVariantMap map;
-
- settings->beginGroup(QLatin1String(groupC));
- // read the values from config, using the keys from the defaults value map
- const QVariantMap def = defaults();
- for (QVariantMap::ConstIterator it = def.constBegin(); it != def.constEnd(); ++it)
- map.insert(it.key(), settings->value(it.key(), it.value()));
- settings->endGroup();
-
- // apply the values to our member variables
- fromMap(map);
-}
-
-void AnalyzerGlobalSettings::writeSettings() const
-{
- QSettings *settings = Core::ICore::settings();
- settings->beginGroup(QLatin1String(groupC));
- const QVariantMap map = toMap();
- for (QVariantMap::ConstIterator it = map.begin(); it != map.end(); ++it)
- settings->setValue(it.key(), it.value());
- settings->endGroup();
-}
-
-void AnalyzerGlobalSettings::registerTool(IAnalyzerTool *tool)
-{
- AbstractAnalyzerSubConfig *config = tool->createGlobalSettings();
- if (config) {
- m_subConfigs.append(config);
- AnalyzerPlugin::instance()->addAutoReleasedObject(new AnalyzerOptionsPage(config));
- readSettings();
- }
-}
-
-
-AnalyzerRunConfigurationAspect::AnalyzerRunConfigurationAspect()
- : AnalyzerSettings((QObject *)0), m_useGlobalSettings(true)
-{
- QList<IAnalyzerTool*> tools = AnalyzerManager::tools();
- // add sub configs
- foreach (IAnalyzerTool *tool, tools) {
- AbstractAnalyzerSubConfig *config = tool->createProjectSettings();
- if (config)
- m_customConfigurations.append(config);
- }
-
- m_subConfigs = AnalyzerGlobalSettings::instance()->subConfigs();
- resetCustomToGlobalSettings();
-}
-
-AnalyzerRunConfigurationAspect::AnalyzerRunConfigurationAspect(const 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);
-}
-
-QString AnalyzerRunConfigurationAspect::displayName() const
-{
- return tr("Analyzer Settings");
-}
-
-void AnalyzerRunConfigurationAspect::fromMap(const QVariantMap &map)
-{
- AnalyzerSettings::fromMap(map, &m_customConfigurations);
- m_useGlobalSettings = map.value(QLatin1String(useGlobalC), true).toBool();
-}
-
-QVariantMap AnalyzerRunConfigurationAspect::toMap() const
-{
- QVariantMap map = AnalyzerSettings::toMap(m_customConfigurations);
- map.insert(QLatin1String(useGlobalC), m_useGlobalSettings);
- return map;
-}
-
-AnalyzerRunConfigurationAspect *AnalyzerRunConfigurationAspect::clone(
- ProjectExplorer::RunConfiguration *parent) const
-{
- Q_UNUSED(parent)
- return new AnalyzerRunConfigurationAspect(this);
-}
-
-void AnalyzerRunConfigurationAspect::setUsingGlobalSettings(bool value)
-{
- if (value == m_useGlobalSettings)
- return;
- m_useGlobalSettings = value;
- if (m_useGlobalSettings)
- m_subConfigs = AnalyzerGlobalSettings::instance()->subConfigs();
- else
- m_subConfigs = m_customConfigurations;
-}
-
-void AnalyzerRunConfigurationAspect::resetCustomToGlobalSettings()
-{
- AnalyzerGlobalSettings *gs = AnalyzerGlobalSettings::instance();
- AnalyzerSettings::fromMap(gs->toMap(), &m_customConfigurations);
-}
-
-ProjectExplorer::RunConfigWidget *AnalyzerRunConfigurationAspect::createConfigurationWidget()
-{
- AnalyzerRunConfigWidget *ret = new AnalyzerRunConfigWidget;
- ret->setRunConfigurationAspect(this);
- return ret;
-}
-
-} // namespace Analyzer
diff --git a/src/plugins/analyzerbase/analyzersettings.h b/src/plugins/analyzerbase/analyzersettings.h
deleted file mode 100644
index 328b0dc335..0000000000
--- a/src/plugins/analyzerbase/analyzersettings.h
+++ /dev/null
@@ -1,192 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
-** Contact: http://www.qt-project.org/legal
-** Author: Milian Wolff, KDAB (milian.wolff@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 ANALYZER_INTERNAL_ANALYZERSETTINGS_H
-#define ANALYZER_INTERNAL_ANALYZERSETTINGS_H
-
-#include <QObject>
-
-#include "analyzerbase_global.h"
-
-#include <projectexplorer/runconfiguration.h>
-
-namespace Analyzer {
-
-class IAnalyzerTool;
-
-/**
- * Utility function to set @p val if @p key is present in @p map.
- */
-template <typename T> void setIfPresent(const QVariantMap &map, const QString &key, T *val)
-{
- if (!map.contains(key))
- return;
- *val = map.value(key).template value<T>();
-}
-
-/**
- * Subclass this to add configuration to your analyzer tool.
- *
- * If global and project-specific settings differ for your tool,
- * create one subclass for each.
- */
-class ANALYZER_EXPORT AbstractAnalyzerSubConfig : public QObject
-{
- Q_OBJECT
-
-public:
- AbstractAnalyzerSubConfig() {}
-
- /// return a list of default values
- virtual QVariantMap defaults() const = 0;
- /// convert current configuration into map for storage
- virtual QVariantMap toMap() const = 0;
- /// read configuration from @p map
- virtual void fromMap(const QVariantMap &map) = 0;
-
- /// unique ID for this configuration
- 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;
-};
-
-/**
- * Shared interface for the global and per-project settings.
- *
- * Use this to get the subConfig for your tool.
- */
-class ANALYZER_EXPORT AnalyzerSettings : public QObject
-{
- Q_OBJECT
-
-public:
- template<class T>
- T *subConfig() const
- {
- foreach (AbstractAnalyzerSubConfig *subConfig, subConfigs()) {
- if (T *config = qobject_cast<T *>(subConfig))
- return config;
- }
- return 0;
- }
-
- QList<AbstractAnalyzerSubConfig *> subConfigs() const
- {
- return m_subConfigs;
- }
-
- QVariantMap defaults() const;
- virtual QVariantMap toMap() const;
-
-protected:
- virtual void fromMap(const QVariantMap &map);
-
- QVariantMap toMap(const QList<AbstractAnalyzerSubConfig *> &subConfigs) const;
- void fromMap(const QVariantMap &map, QList<AbstractAnalyzerSubConfig *> *subConfigs);
-
- AnalyzerSettings(QObject *parent);
- AnalyzerSettings(const AnalyzerSettings *other);
- QList<AbstractAnalyzerSubConfig *> m_subConfigs;
-};
-
-
-// global and local settings are loaded and saved differently, and they also handle suppressions
-// differently.
-/**
- * Global settings
- *
- * To access your custom configuration use:
- * @code
- * AnalyzerGlobalSettings::instance()->subConfig<YourGlobalConfig>()->...
- * @endcode
- */
-class ANALYZER_EXPORT AnalyzerGlobalSettings : public AnalyzerSettings
-{
- Q_OBJECT
-
-public:
- static AnalyzerGlobalSettings *instance();
- ~AnalyzerGlobalSettings();
-
- void writeSettings() const;
- void readSettings();
-
- void registerTool(IAnalyzerTool *tool);
-
-private:
- AnalyzerGlobalSettings(QObject *parent);
- static AnalyzerGlobalSettings *m_instance;
-};
-
-/**
- * Settings associated with a single project/run configuration
- *
- * To access your custom configuration use:
- * @code
- * ProjectExplorer::RunConfiguration *rc = ...;
- * rc->extraAspect<AnalyzerRunConfigurationAspect>()->subConfig<YourProjectConfig>()->...
- * @endcode
- */
-class ANALYZER_EXPORT AnalyzerRunConfigurationAspect
- : public AnalyzerSettings, public ProjectExplorer::IRunConfigurationAspect
-{
- Q_OBJECT
-
-public:
- AnalyzerRunConfigurationAspect();
- AnalyzerRunConfigurationAspect(const AnalyzerRunConfigurationAspect *other);
- ~AnalyzerRunConfigurationAspect();
-
- QString displayName() const;
- virtual QVariantMap toMap() const;
- AnalyzerRunConfigurationAspect *clone(ProjectExplorer::RunConfiguration *parent) const;
-
- bool isUsingGlobalSettings() const { return m_useGlobalSettings; }
- void setUsingGlobalSettings(bool value);
- void resetCustomToGlobalSettings();
-
- QList<AbstractAnalyzerSubConfig *> customSubConfigs() const { return m_customConfigurations; }
- ProjectExplorer::RunConfigWidget *createConfigurationWidget();
-
-protected:
- virtual void fromMap(const QVariantMap &map);
-
-private:
- bool m_useGlobalSettings;
- QList<AbstractAnalyzerSubConfig *> m_customConfigurations;
-};
-
-} // namespace Analyzer
-
-#endif // ANALYZER_INTERNAL_ANALYZERSETTINGS_H
diff --git a/src/plugins/analyzerbase/analyzerstartparameters.h b/src/plugins/analyzerbase/analyzerstartparameters.h
index fc0fc57ae7..034f962f74 100644
--- a/src/plugins/analyzerbase/analyzerstartparameters.h
+++ b/src/plugins/analyzerbase/analyzerstartparameters.h
@@ -35,9 +35,9 @@
#include <QMetaType>
-#include <coreplugin/id.h>
#include <ssh/sshconnection.h>
#include <utils/environment.h>
+#include <projectexplorer/projectexplorerconstants.h>
namespace Analyzer {
@@ -47,13 +47,13 @@ namespace Analyzer {
class ANALYZER_EXPORT AnalyzerStartParameters
{
public:
- AnalyzerStartParameters()
+ AnalyzerStartParameters() : analyzerPort(0)
{}
StartMode startMode;
+ ProjectExplorer::RunMode runMode;
QSsh::SshConnectionParameters connParams;
- Core::Id toolId;
QString debuggee;
QString debuggeeArgs;
QString analyzerCmdPrefix;
diff --git a/src/plugins/analyzerbase/analyzerutils.cpp b/src/plugins/analyzerbase/analyzerutils.cpp
index 05d71b6d90..2b142ccab7 100644
--- a/src/plugins/analyzerbase/analyzerutils.cpp
+++ b/src/plugins/analyzerbase/analyzerutils.cpp
@@ -85,7 +85,7 @@ CPlusPlus::Symbol *AnalyzerUtils::findSymbolUnderCursor()
editorWidget->convertPosition(pos, &line, &column);
const CPlusPlus::Snapshot &snapshot = CppTools::CppModelManagerInterface::instance()->snapshot();
- CPlusPlus::Document::Ptr doc = snapshot.document(editor->document()->fileName());
+ CPlusPlus::Document::Ptr doc = snapshot.document(editor->document()->filePath());
QTC_ASSERT(doc, return 0);
// fetch the expression's code
diff --git a/src/plugins/analyzerbase/ianalyzerengine.h b/src/plugins/analyzerbase/ianalyzerengine.h
deleted file mode 100644
index deea4638ce..0000000000
--- a/src/plugins/analyzerbase/ianalyzerengine.h
+++ /dev/null
@@ -1,112 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
-** Contact: http://www.qt-project.org/legal
-** Author: Nicolas Arnaud-Cormos, KDAB (nicolas.arnaud-cormos@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 IANALYZERENGINE_H
-#define IANALYZERENGINE_H
-
-#include "analyzerbase_global.h"
-#include "analyzerstartparameters.h"
-
-#include <projectexplorer/task.h>
-#include <utils/outputformat.h>
-
-#include <QObject>
-#include <QString>
-
-namespace ProjectExplorer {
-class RunConfiguration;
-}
-
-namespace Analyzer {
-
-class IAnalyzerTool;
-
-/**
- * An IAnalyzerEngine instance handles the launch of an analyzation tool.
- *
- * It gets created for each launch and deleted when the launch is stopped or ended.
- */
-class ANALYZER_EXPORT IAnalyzerEngine : public QObject
-{
- Q_OBJECT
-
-public:
- IAnalyzerEngine(IAnalyzerTool *tool, const AnalyzerStartParameters &sp,
- ProjectExplorer::RunConfiguration *runConfiguration = 0);
- IAnalyzerEngine(IAnalyzerTool *tool,
- ProjectExplorer::RunConfiguration *runConfiguration);
-
- /// Start analyzation process.
- virtual bool start() = 0;
- /// Trigger async stop of the analyzation process.
- virtual void stop() = 0;
-
- /// Controller actions.
- virtual bool canPause() const { return false; }
- virtual void pause() {}
- virtual void unpause() {}
-
- /// The active run configuration for this engine, might be zero.
- ProjectExplorer::RunConfiguration *runConfiguration() const { return m_runConfig; }
-
- /// The start parameters for this engine.
- const AnalyzerStartParameters &startParameters() const { return m_sp; }
-
- /// The tool this engine is associated with.
- IAnalyzerTool *tool() const { return m_tool; }
- StartMode mode() const { return m_sp.startMode; }
-
- virtual void notifyRemoteSetupDone(quint16) {}
- virtual void notifyRemoteFinished(bool) {}
-
-public slots:
- virtual void logApplicationMessage(const QString &, Utils::OutputFormat) {}
-
-signals:
- /// Should be emitted when the debuggee outputted something.
- void outputReceived(const QString &, Utils::OutputFormat format);
- /// Can be emitted when you want to show a task, e.g. to display an error.
- void taskToBeAdded(ProjectExplorer::Task::TaskType type, const QString &description,
- const QString &file, int line);
-
- /// Must be emitted when the engine finished.
- void finished();
- /// Must be emitted when the engine is starting.
- void starting(const Analyzer::IAnalyzerEngine *);
-
-private:
- ProjectExplorer::RunConfiguration *m_runConfig;
- AnalyzerStartParameters m_sp;
- IAnalyzerTool *m_tool;
-};
-
-} // namespace Analyzer
-
-#endif // IANALYZERENGINE_H
diff --git a/src/plugins/analyzerbase/ianalyzertool.cpp b/src/plugins/analyzerbase/ianalyzertool.cpp
index e29e3681c9..ca12ab7318 100644
--- a/src/plugins/analyzerbase/ianalyzertool.cpp
+++ b/src/plugins/analyzerbase/ianalyzertool.cpp
@@ -30,52 +30,14 @@
#include "ianalyzertool.h"
-using namespace Core;
-
namespace Analyzer {
IAnalyzerTool::IAnalyzerTool(QObject *parent)
: QObject(parent)
{}
-Id IAnalyzerTool::defaultMenuGroup(StartMode mode)
-{
- if (mode == StartRemote)
- return Id(Constants::G_ANALYZER_REMOTE_TOOLS);
- return Id(Constants::G_ANALYZER_TOOLS);
-}
-
-Id IAnalyzerTool::defaultActionId(const IAnalyzerTool *tool, StartMode mode)
-{
- Id id = Id("Analyzer").withSuffix(tool->id().toString());
- switch (mode) {
- case StartLocal:
- return id.withSuffix(".Local");
- case StartRemote:
- return id.withSuffix(".Remote");
- case StartQml:
- case StartQmlRemote:
- return id.withSuffix(".Qml");
- }
- return Id();
-}
-
-QString IAnalyzerTool::defaultActionName(const IAnalyzerTool *tool, StartMode mode)
-{
- QString base = tool->displayName();
- if (mode == StartRemote)
- return base + tr(" (External)");
- return base;
-}
-
-AbstractAnalyzerSubConfig *IAnalyzerTool::createGlobalSettings()
-{
- return 0;
-}
-
-AbstractAnalyzerSubConfig *IAnalyzerTool::createProjectSettings()
-{
- return 0;
-}
+AnalyzerAction::AnalyzerAction(QObject *parent)
+ : QAction(parent)
+{}
} // namespace Analyzer
diff --git a/src/plugins/analyzerbase/ianalyzertool.h b/src/plugins/analyzerbase/ianalyzertool.h
index 3c1a46df52..ae45212820 100644
--- a/src/plugins/analyzerbase/ianalyzertool.h
+++ b/src/plugins/analyzerbase/ianalyzertool.h
@@ -34,9 +34,11 @@
#include "analyzerbase_global.h"
#include "analyzerstartparameters.h"
+#include <coreplugin/id.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <QObject>
+#include <QAction>
namespace ProjectExplorer {
class RunConfiguration;
@@ -44,9 +46,7 @@ class RunConfiguration;
namespace Analyzer {
-class IAnalyzerOutputPaneAdapter;
-class IAnalyzerEngine;
-class AbstractAnalyzerSubConfig;
+class AnalyzerRunControl;
/**
@@ -69,23 +69,8 @@ class ANALYZER_EXPORT IAnalyzerTool : public QObject
public:
explicit IAnalyzerTool(QObject *parent = 0);
- /// Returns a unique ID for this tool.
- virtual Core::Id id() const = 0;
/// Returns the run mode for this tool.
virtual ProjectExplorer::RunMode runMode() const = 0;
- /// Returns a short user readable display name for this tool.
- virtual QString displayName() const = 0;
- /// Returns a user readable description name for this tool.
- virtual QString description() const = 0;
- /// Returns an id for the start action.
- virtual Core::Id actionId(StartMode mode) const
- { return defaultActionId(this, mode); }
- /// Returns the menu group the start action should go to.
- virtual Core::Id menuGroup(StartMode mode) const
- { return defaultMenuGroup(mode); }
- /// Returns a short user readable action name for this tool.
- virtual QString actionName(StartMode mode) const
- { return defaultActionName(this, mode); }
/**
* The mode in which this tool should preferably be run
@@ -101,14 +86,6 @@ public:
};
virtual ToolMode toolMode() const = 0;
- /// Convenience implementation.
- static Core::Id defaultMenuGroup(StartMode mode);
- static Core::Id defaultActionId(const IAnalyzerTool *tool, StartMode mode);
- static QString defaultActionName(const IAnalyzerTool *tool, StartMode mode);
-
- /// This gets called after all analyzation tools where initialized.
- virtual void extensionsInitialized() = 0;
-
/// Creates all widgets used by the tool.
/// Returns a control widget which will be shown in the status bar when
/// this tool is selected. Must be non-zero.
@@ -116,33 +93,45 @@ public:
/// Returns a new engine for the given start parameters.
/// Called each time the tool is launched.
- virtual IAnalyzerEngine *createEngine(const AnalyzerStartParameters &sp,
- ProjectExplorer::RunConfiguration *runConfiguration = 0) = 0;
+ virtual AnalyzerRunControl *createRunControl(const AnalyzerStartParameters &sp,
+ ProjectExplorer::RunConfiguration *runConfiguration) = 0;
- /// Returns true if the tool can be run
- virtual bool canRun(ProjectExplorer::RunConfiguration *runConfiguration,
- ProjectExplorer::RunMode mode) const = 0;
+ virtual void startTool(StartMode mode) = 0;
+};
- /// Create the start parameters for the run control factory
- virtual AnalyzerStartParameters createStartParameters(
- ProjectExplorer::RunConfiguration *runConfiguration,
- ProjectExplorer::RunMode mode) const = 0;
+/**
+ * This class represents an analyzation action, i.e. a tool that runs in a specific mode.
+ *
+*/
- virtual void startTool(StartMode mode) = 0;
+class ANALYZER_EXPORT AnalyzerAction : public QAction
+{
+ Q_OBJECT
- /// Called when tools gets selected.
- virtual void toolSelected() const {}
+public:
+ explicit AnalyzerAction(QObject *parent = 0);
- /// Called when tools gets deselected.
- virtual void toolDeselected() const {}
+public:
+ IAnalyzerTool *tool() const { return m_tool; }
+ void setTool(IAnalyzerTool *tool) { m_tool = tool; }
- /// Factory method to create the global tool setting
- virtual AbstractAnalyzerSubConfig *createGlobalSettings();
+ StartMode startMode() const { return m_startMode; }
+ void setStartMode(StartMode startMode) { m_startMode = startMode; }
- /// Factory method to create the project tool setting
- virtual AbstractAnalyzerSubConfig *createProjectSettings();
+ Core::Id menuGroup() const { return m_menuGroup; }
+ void setMenuGroup(Core::Id menuGroup) { m_menuGroup = menuGroup; }
+
+ Core::Id id() const { return m_id; }
+ void setId(Core::Id id) { m_id = id; }
+
+protected:
+ IAnalyzerTool *m_tool;
+ StartMode m_startMode;
+ Core::Id m_menuGroup;
+ Core::Id m_id;
};
+
} // namespace Analyzer
#endif // IANALYZERTOOL_H
diff --git a/src/plugins/android/Android.pluginspec.in b/src/plugins/android/Android.pluginspec.in
index acd7b6f6c7..b828f07f1a 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\">
+<plugin name=\"Android\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>KDE Necessitas</vendor>
<copyright>(C) 2013 BogDan Vatra</copyright>
<license>
diff --git a/src/plugins/android/addnewavddialog.ui b/src/plugins/android/addnewavddialog.ui
index 6c57b31c6a..598a754c10 100644
--- a/src/plugins/android/addnewavddialog.ui
+++ b/src/plugins/android/addnewavddialog.ui
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
- <class>AddNewAVDDialog</class>
- <widget class="QDialog" name="AddNewAVDDialog">
+ <class>Android::Internal::AddNewAVDDialog</class>
+ <widget class="QDialog" name="Android::Internal::AddNewAVDDialog">
<property name="geometry">
<rect>
<x>0</x>
@@ -16,33 +16,27 @@
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<layout class="QGridLayout" name="gridLayout">
- <item row="0" column="0">
- <widget class="QLabel" name="label">
+ <item row="1" column="0">
+ <widget class="QLabel" name="label_2">
<property name="text">
- <string>Name:</string>
+ <string>Target API:</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
- <item row="0" column="1">
- <widget class="QLineEdit" name="nameLineEdit"/>
- </item>
- <item row="1" column="0">
- <widget class="QLabel" name="label_2">
+ <item row="0" column="0">
+ <widget class="QLabel" name="label">
<property name="text">
- <string>Kit:</string>
+ <string>Name:</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
- <item row="1" column="1">
- <widget class="QComboBox" name="targetComboBox"/>
- </item>
- <item row="2" column="0">
+ <item row="3" column="0">
<widget class="QLabel" name="label_3">
<property name="text">
<string>SD card size:</string>
@@ -52,7 +46,10 @@
</property>
</widget>
</item>
- <item row="2" column="1">
+ <item row="0" column="1">
+ <widget class="QLineEdit" name="nameLineEdit"/>
+ </item>
+ <item row="3" column="1">
<widget class="QSpinBox" name="sizeSpinBox">
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
@@ -68,6 +65,22 @@
</property>
</widget>
</item>
+ <item row="1" column="1">
+ <widget class="QComboBox" name="targetComboBox"/>
+ </item>
+ <item row="2" column="0">
+ <widget class="QLabel" name="label_4">
+ <property name="text">
+ <string>ABI:</string>
+ </property>
+ <property name="alignment">
+ <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="1">
+ <widget class="QComboBox" name="abiComboBox"/>
+ </item>
</layout>
</item>
<item>
@@ -100,7 +113,7 @@
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
- <receiver>AddNewAVDDialog</receiver>
+ <receiver>Android::Internal::AddNewAVDDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
@@ -116,7 +129,7 @@
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
- <receiver>AddNewAVDDialog</receiver>
+ <receiver>Android::Internal::AddNewAVDDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
diff --git a/src/plugins/android/android.pro b/src/plugins/android/android.pro
index 68dcc23245..3cb2e1de1e 100644
--- a/src/plugins/android/android.pro
+++ b/src/plugins/android/android.pro
@@ -23,6 +23,7 @@ HEADERS += \
androiddeploystep.h \
androiddeploystepwidget.h \
androiddeploystepfactory.h \
+ androiderrormessage.h \
androidglobal.h \
androidrunner.h \
androiddebugsupport.h \
@@ -40,7 +41,11 @@ HEADERS += \
androidmanifesteditorfactory.h \
androidmanifesteditor.h \
androidmanifesteditorwidget.h \
- androidmanifestdocument.h
+ androidmanifestdocument.h \
+ androiddevicedialog.h \
+ androiddeployqtstep.h \
+ certificatesmodel.h \
+ androiddeployqtwidget.h
SOURCES += \
androidconfigurations.cpp \
@@ -59,6 +64,7 @@ SOURCES += \
androiddeploystep.cpp \
androiddeploystepwidget.cpp \
androiddeploystepfactory.cpp \
+ androiderrormessage.cpp \
androidrunner.cpp \
androiddebugsupport.cpp \
androidqtversionfactory.cpp \
@@ -75,14 +81,28 @@ SOURCES += \
androidmanifesteditorfactory.cpp \
androidmanifesteditor.cpp \
androidmanifesteditorwidget.cpp \
- androidmanifestdocument.cpp
+ androidmanifestdocument.cpp \
+ androiddevicedialog.cpp \
+ androiddeployqtstep.cpp \
+ certificatesmodel.cpp \
+ androiddeployqtwidget.cpp
FORMS += \
androidsettingswidget.ui \
androidpackagecreationwidget.ui \
androiddeploystepwidget.ui \
addnewavddialog.ui \
- androidcreatekeystorecertificate.ui
+ androidcreatekeystorecertificate.ui \
+ androiddevicedialog.ui \
+ androiddeployqtwidget.ui
+
+exists(../../shared/qbs/qbs.pro) {
+ HEADERS += \
+ androidqbspropertyprovider.h
+ SOURCES += \
+ androidqbspropertyprovider.cpp
+ DEFINES += HAVE_QBS
+}
RESOURCES = android.qrc
DEFINES += ANDROID_LIBRARY
diff --git a/src/plugins/android/android.qbs b/src/plugins/android/android.qbs
index aa6f64237d..13a4c91058 100644
--- a/src/plugins/android/android.qbs
+++ b/src/plugins/android/android.qbs
@@ -8,17 +8,22 @@ QtcPlugin {
Depends { name: "Core" }
Depends { name: "ProjectExplorer" }
Depends { name: "Qt4ProjectManager" }
+ Depends {
+ name: "QbsProjectManager"
+ condition: project.buildQbsProjectManager
+ }
Depends { name: "Debugger" }
Depends { name: "QmlDebug" }
Depends { name: "QtSupport" }
Depends { name: "TextEditor" }
Depends { name: "AnalyzerBase" }
+ Depends { name: "Utils" }
Depends { name: "Qt"; submodules: ["widgets", "xml", "network"] }
property bool enable: false
pluginspecreplacements: ({"ANDROID_EXPERIMENTAL_STR": (enable ? "false": "true")})
- cpp.includePaths: base.concat("../../shared")
+ cpp.defines: base.concat(project.buildQbsProjectManager ? ['HAVE_QBS'] : [])
files: [
"addnewavddialog.ui",
@@ -31,8 +36,13 @@ QtcPlugin {
"androidcreatekeystorecertificate.cpp",
"androidcreatekeystorecertificate.h",
"androidcreatekeystorecertificate.ui",
+ "androiddeployqtstep.cpp",
+ "androiddeployqtstep.h",
"androiddebugsupport.cpp",
"androiddebugsupport.h",
+ "androiddevicedialog.cpp",
+ "androiddevicedialog.h",
+ "androiddevicedialog.ui",
"androiddeployconfiguration.cpp",
"androiddeployconfiguration.h",
"androiddeploystep.cpp",
@@ -42,10 +52,15 @@ QtcPlugin {
"androiddeploystepwidget.cpp",
"androiddeploystepwidget.h",
"androiddeploystepwidget.ui",
+ "androiddeployqtwidget.cpp",
+ "androiddeployqtwidget.h",
+ "androiddeployqtwidget.ui",
"androiddevice.cpp",
"androiddevice.h",
"androiddevicefactory.cpp",
"androiddevicefactory.h",
+ "androiderrormessage.h",
+ "androiderrormessage.cpp",
"androidgdbserverkitinformation.cpp",
"androidgdbserverkitinformation.h",
"androidglobal.h",
@@ -93,7 +108,18 @@ QtcPlugin {
"androidsettingswidget.ui",
"androidtoolchain.cpp",
"androidtoolchain.h",
+ "certificatesmodel.cpp",
+ "certificatesmodel.h",
"javaparser.cpp",
"javaparser.h",
]
+
+ Group {
+ name: "Qbs Support"
+ condition: project.buildQbsProjectManager
+ files: [
+ "androidqbspropertyprovider.cpp",
+ "androidqbspropertyprovider.h",
+ ]
+ }
}
diff --git a/src/plugins/android/android_dependencies.pri b/src/plugins/android/android_dependencies.pri
index 5fe7ef6bee..c21226f6f2 100644
--- a/src/plugins/android/android_dependencies.pri
+++ b/src/plugins/android/android_dependencies.pri
@@ -7,3 +7,10 @@ QTC_PLUGIN_DEPENDS += \
qtsupport \
texteditor \
analyzerbase
+
+QTC_LIB_DEPENDS += \
+ utils
+
+exists(../../shared/qbs/qbs.pro): \
+ QTC_PLUGIN_DEPENDS += \
+ qbsprojectmanager
diff --git a/src/plugins/android/androidanalyzesupport.cpp b/src/plugins/android/androidanalyzesupport.cpp
index 852075e6cf..f514537ec4 100644
--- a/src/plugins/android/androidanalyzesupport.cpp
+++ b/src/plugins/android/androidanalyzesupport.cpp
@@ -33,7 +33,6 @@
#include "androidmanager.h"
#include <analyzerbase/ianalyzertool.h>
-#include <analyzerbase/ianalyzerengine.h>
#include <analyzerbase/analyzermanager.h>
#include <analyzerbase/analyzerruncontrol.h>
#include <analyzerbase/analyzerstartparameters.h>
@@ -52,18 +51,11 @@ namespace Android {
namespace Internal {
RunControl *AndroidAnalyzeSupport::createAnalyzeRunControl(AndroidRunConfiguration *runConfig,
- RunMode runMode, QString *errorMessage)
+ RunMode runMode)
{
- IAnalyzerTool *tool = AnalyzerManager::toolFromRunMode(runMode);
- if (!tool) {
- if (errorMessage)
- *errorMessage = tr("No analyzer tool selected.");
- return 0;
- }
-
- AnalyzerStartParameters params;
- params.toolId = tool->id();
Target *target = runConfig->target();
+ AnalyzerStartParameters params;
+ params.runMode = runMode;
params.displayName = AndroidManager::packageName(target);
params.sysroot = SysRootKitInformation::sysRoot(target->kit()).toString();
// TODO: Not sure if these are the right paths.
@@ -73,26 +65,24 @@ RunControl *AndroidAnalyzeSupport::createAnalyzeRunControl(AndroidRunConfigurati
QTC_ASSERT(server.listen(QHostAddress::LocalHost)
|| server.listen(QHostAddress::LocalHostIPv6), return 0);
params.analyzerHost = server.serverAddress().toString();
- params.startMode = StartQmlRemote;
+ params.startMode = StartLocal;
}
- AnalyzerRunControl * const analyzerRunControl = new AnalyzerRunControl(tool, params, runConfig);
- new AndroidAnalyzeSupport(runConfig, analyzerRunControl);
+ AnalyzerRunControl *analyzerRunControl = AnalyzerManager::createRunControl(params, runConfig);
+ (void) new AndroidAnalyzeSupport(runConfig, analyzerRunControl);
return analyzerRunControl;
}
AndroidAnalyzeSupport::AndroidAnalyzeSupport(AndroidRunConfiguration *runConfig,
AnalyzerRunControl *runControl)
: AndroidRunSupport(runConfig, runControl),
- m_engine(0),
+ m_runControl(0),
m_qmlPort(0)
{
if (runControl) {
- m_engine = runControl->engine();
- if (m_engine) {
- connect(m_engine, SIGNAL(starting(const Analyzer::IAnalyzerEngine*)),
- m_runner, SLOT(start()));
- }
+ m_runControl = runControl;
+ connect(m_runControl, SIGNAL(starting(const Analyzer::AnalyzerRunControl*)),
+ m_runner, SLOT(start()));
}
connect(&m_outputParser, SIGNAL(waitingForConnectionOnPort(quint16)),
SLOT(remoteIsRunning()));
@@ -115,8 +105,8 @@ void AndroidAnalyzeSupport::handleRemoteProcessStarted(int qmlPort)
void AndroidAnalyzeSupport::handleRemoteOutput(const QByteArray &output)
{
const QString msg = QString::fromUtf8(output);
- if (m_engine)
- m_engine->logApplicationMessage(msg, Utils::StdOutFormatSameLine);
+ if (m_runControl)
+ m_runControl->logApplicationMessage(msg, Utils::StdOutFormatSameLine);
else
AndroidRunSupport::handleRemoteOutput(output);
m_outputParser.processOutput(msg);
@@ -124,16 +114,16 @@ void AndroidAnalyzeSupport::handleRemoteOutput(const QByteArray &output)
void AndroidAnalyzeSupport::handleRemoteErrorOutput(const QByteArray &output)
{
- if (m_engine)
- m_engine->logApplicationMessage(QString::fromUtf8(output), Utils::StdErrFormatSameLine);
+ if (m_runControl)
+ m_runControl->logApplicationMessage(QString::fromUtf8(output), Utils::StdErrFormatSameLine);
else
AndroidRunSupport::handleRemoteErrorOutput(output);
}
void AndroidAnalyzeSupport::remoteIsRunning()
{
- if (m_engine)
- m_engine->notifyRemoteSetupDone(m_qmlPort);
+ if (m_runControl)
+ m_runControl->notifyRemoteSetupDone(m_qmlPort);
}
} // namespace Internal
diff --git a/src/plugins/android/androidanalyzesupport.h b/src/plugins/android/androidanalyzesupport.h
index 2c7aa0e065..0f0f86f4bb 100644
--- a/src/plugins/android/androidanalyzesupport.h
+++ b/src/plugins/android/androidanalyzesupport.h
@@ -33,10 +33,7 @@
#include "androidrunsupport.h"
#include <qmldebug/qmloutputparser.h>
-namespace Analyzer {
-class IAnalyzerEngine;
-class AnalyzerRunControl;
-}
+namespace Analyzer { class AnalyzerRunControl; }
namespace ProjectExplorer { class RunControl; }
namespace Android {
@@ -51,8 +48,7 @@ class AndroidAnalyzeSupport : public AndroidRunSupport
public:
static ProjectExplorer::RunControl *createAnalyzeRunControl(AndroidRunConfiguration *runConfig,
- ProjectExplorer::RunMode runMode,
- QString *errorMessage);
+ ProjectExplorer::RunMode runMode);
AndroidAnalyzeSupport(AndroidRunConfiguration *runConfig,
Analyzer::AnalyzerRunControl *runControl);
@@ -66,7 +62,7 @@ private slots:
void remoteIsRunning();
private:
- Analyzer::IAnalyzerEngine *m_engine;
+ Analyzer::AnalyzerRunControl *m_runControl;
QmlDebug::QmlOutputParser m_outputParser;
int m_qmlPort;
};
diff --git a/src/plugins/android/androidconfigurations.cpp b/src/plugins/android/androidconfigurations.cpp
index 718d96061a..fa71d84f90 100644
--- a/src/plugins/android/androidconfigurations.cpp
+++ b/src/plugins/android/androidconfigurations.cpp
@@ -33,6 +33,8 @@
#include "androiddevice.h"
#include "androidgdbserverkitinformation.h"
#include "ui_addnewavddialog.h"
+#include "androidqtversion.h"
+#include "androiddevicedialog.h"
#include <coreplugin/icore.h>
#include <utils/hostosinfo.h>
@@ -41,11 +43,13 @@
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/devicesupport/devicemanager.h>
#include <projectexplorer/toolchainmanager.h>
+#include <projectexplorer/session.h>
#include <debugger/debuggerkitinformation.h>
#include <qtsupport/baseqtversion.h>
#include <qtsupport/qtkitinformation.h>
#include <qtsupport/qtversionmanager.h>
#include <utils/environment.h>
+#include <utils/sleep.h>
#include <QDateTime>
#include <QSettings>
@@ -58,14 +62,6 @@
#include <QStringListModel>
#include <QMessageBox>
-#if defined(_WIN32)
-#include <iostream>
-#include <windows.h>
-#define sleep(_n) Sleep(1000 * (_n))
-#else
-#include <unistd.h>
-#endif
-
using namespace ProjectExplorer;
using namespace Utils;
@@ -82,6 +78,7 @@ namespace {
const QLatin1String KeystoreLocationKey("KeystoreLocation");
const QLatin1String AutomaticKitCreationKey("AutomatiKitCreation");
const QLatin1String MakeExtraSearchDirectory("MakeExtraSearchDirectory");
+ const QLatin1String DefaultDevice("DefaultDevice");
const QLatin1String PartitionSizeKey("PartitionSize");
const QLatin1String ToolchainHostKey("ToolchainHost");
const QLatin1String ArmToolchainPrefix("arm-linux-androideabi");
@@ -103,7 +100,14 @@ namespace {
bool androidDevicesLessThan(const AndroidDeviceInfo &dev1, const AndroidDeviceInfo &dev2)
{
- return dev1.sdk < dev2.sdk;
+ if (dev1.serialNumber.contains(QLatin1String("????")) == dev2.serialNumber.contains(QLatin1String("????")))
+ return !dev1.serialNumber.contains(QLatin1String("????"));
+ if (dev1.type != dev2.type)
+ return dev1.type == AndroidDeviceInfo::Hardware;
+ if (dev1.sdk != dev2.sdk)
+ return dev1.sdk < dev2.sdk;
+
+ return dev1.serialNumber < dev2.serialNumber;
}
}
@@ -334,13 +338,13 @@ void AndroidConfigurations::detectToolchainHost()
{
QStringList hostPatterns;
switch (HostOsInfo::hostOs()) {
- case HostOsInfo::HostOsLinux:
+ case OsTypeLinux:
hostPatterns << QLatin1String("linux*");
break;
- case HostOsInfo::HostOsWindows:
+ case OsTypeWindows:
hostPatterns << QLatin1String("windows*");
break;
- case HostOsInfo::HostOsMac:
+ case OsTypeMac:
hostPatterns << QLatin1String("darwin*");
break;
default: /* unknown host */ return;
@@ -374,101 +378,144 @@ FileName AndroidConfigurations::jarsignerPath() const
FileName AndroidConfigurations::zipalignPath() const
{
- Utils::FileName path = m_config.sdkLocation;
+ FileName path = m_config.sdkLocation;
return path.appendPath(QLatin1String("tools/zipalign" QTC_HOST_EXE_SUFFIX));
}
-QString AndroidConfigurations::getDeployDeviceSerialNumber(int *apiLevel, const QString &abi) const
+AndroidDeviceInfo AndroidConfigurations::showDeviceDialog(ProjectExplorer::Project *project, int apiLevel, const QString &abi)
{
- QVector<AndroidDeviceInfo> devices = connectedDevices();
+ QString serialNumber = defaultDevice(project, abi);
+ if (!serialNumber.isEmpty()) {
+ // search for that device
+ foreach (const AndroidDeviceInfo &info, AndroidConfigurations::instance().connectedDevices())
+ if (info.serialNumber == serialNumber
+ && info.sdk >= apiLevel)
+ return info;
- foreach (AndroidDeviceInfo device, devices) {
- if (device.sdk >= *apiLevel && device.cpuABI.contains(abi)) {
- *apiLevel = device.sdk;
- return device.serialNumber;
+ foreach (const AndroidDeviceInfo &info, AndroidConfigurations::instance().androidVirtualDevices())
+ if (info.serialNumber == serialNumber
+ && info.sdk >= apiLevel)
+ return info;
+ }
+
+ AndroidDeviceDialog dialog(apiLevel, abi);
+ if (dialog.exec() == QDialog::Accepted) {
+ AndroidDeviceInfo info = dialog.device();
+ if (dialog.saveDeviceSelection()) {
+ if (!info.serialNumber.isEmpty())
+ AndroidConfigurations::instance().setDefaultDevice(project, abi, info.serialNumber);
}
+ return info;
}
- return startAVD(apiLevel);
+ return AndroidDeviceInfo();
}
-QVector<AndroidDeviceInfo> AndroidConfigurations::connectedDevices(int apiLevel) const
+void AndroidConfigurations::clearDefaultDevices(ProjectExplorer::Project *project)
+{
+ if (m_defaultDeviceForAbi.contains(project))
+ m_defaultDeviceForAbi.remove(project);
+}
+
+void AndroidConfigurations::setDefaultDevice(ProjectExplorer::Project *project, const QString &abi, const QString &serialNumber)
+{
+ m_defaultDeviceForAbi[project][abi] = serialNumber;
+}
+
+QString AndroidConfigurations::defaultDevice(Project *project, const QString &abi) const
+{
+ if (!m_defaultDeviceForAbi.contains(project))
+ return QString();
+ const QMap<QString, QString> &map = m_defaultDeviceForAbi.value(project);
+ if (!map.contains(abi))
+ return QString();
+ return map.value(abi);
+}
+
+QVector<AndroidDeviceInfo> AndroidConfigurations::connectedDevices(QString *error) const
{
QVector<AndroidDeviceInfo> devices;
QProcess adbProc;
adbProc.start(adbToolPath().toString(), QStringList() << QLatin1String("devices"));
if (!adbProc.waitForFinished(-1)) {
adbProc.kill();
+ if (error)
+ *error = tr("Could not run: %1").arg(adbToolPath().toString() + QLatin1String(" devices"));
return devices;
}
QList<QByteArray> adbDevs = adbProc.readAll().trimmed().split('\n');
adbDevs.removeFirst();
- AndroidDeviceInfo dev;
// workaround for '????????????' serial numbers:
// can use "adb -d" when only one usb device attached
- int usbDevicesNum = 0;
- QStringList serialNumbers;
foreach (const QByteArray &device, adbDevs) {
- const QString serialNo = QString::fromLatin1(device.left(device.indexOf('\t')).trimmed());;
- if (!serialNo.startsWith(QLatin1String("emulator")))
- ++usbDevicesNum;
- serialNumbers << serialNo;
- }
-
- foreach (const QString &serialNo, serialNumbers) {
- if (serialNo.contains(QLatin1String("????")) && usbDevicesNum > 1)
- continue;
-
+ const QString serialNo = QString::fromLatin1(device.left(device.indexOf('\t')).trimmed());
+ const QString deviceType = QString::fromLatin1(device.mid(device.indexOf('\t'))).trimmed();
+ AndroidDeviceInfo dev;
dev.serialNumber = serialNo;
+ dev.type = serialNo.startsWith(QLatin1String("emulator")) ? AndroidDeviceInfo::Emulator : AndroidDeviceInfo::Hardware;
dev.sdk = getSDKVersion(dev.serialNumber);
- dev.cpuABI = getAbis(dev.serialNumber);
- if (apiLevel != -1 && dev.sdk != apiLevel)
- continue;
+ dev.cpuAbi = getAbis(dev.serialNumber);
+ dev.unauthorized = (deviceType == QLatin1String("unauthorized"));
devices.push_back(dev);
}
+
qSort(devices.begin(), devices.end(), androidDevicesLessThan);
+ if (devices.isEmpty() && error)
+ *error = tr("No devices found in output of: %1").arg(adbToolPath().toString() + QLatin1String(" devices"));
return devices;
}
-bool AndroidConfigurations::createAVD(int minApiLevel) const
+QString AndroidConfigurations::createAVD(int minApiLevel, QString targetArch) const
{
QDialog d;
Ui::AddNewAVDDialog avdDialog;
avdDialog.setupUi(&d);
- QStringListModel model(sdkTargets(minApiLevel));
- avdDialog.targetComboBox->setModel(&model);
- if (!model.rowCount()) {
+ avdDialog.targetComboBox->addItems(sdkTargets(minApiLevel));
+
+ if (targetArch.isEmpty())
+ avdDialog.abiComboBox->addItems(QStringList()
+ << QLatin1String("armeabi-v7a")
+ << QLatin1String("armeabi")
+ << QLatin1String("x86")
+ << QLatin1String("mips"));
+ else
+ avdDialog.abiComboBox->addItems(QStringList(targetArch));
+
+ if (!avdDialog.targetComboBox->count()) {
QMessageBox::critical(0, tr("Error Creating AVD"),
tr("Cannot create a new AVD. No sufficiently recent Android SDK available.\n"
"Please install an SDK of at least API version %1.").
arg(minApiLevel));
- return false;
+ return QString();
}
QRegExp rx(QLatin1String("\\S+"));
QRegExpValidator v(rx, 0);
avdDialog.nameLineEdit->setValidator(&v);
if (d.exec() != QDialog::Accepted)
- return false;
- return createAVD(avdDialog.targetComboBox->currentText(), avdDialog.nameLineEdit->text(), avdDialog.sizeSpinBox->value());
+ return QString();
+ return createAVD(avdDialog.targetComboBox->currentText(), avdDialog.nameLineEdit->text(), avdDialog.abiComboBox->currentText(), avdDialog.sizeSpinBox->value());
}
-bool AndroidConfigurations::createAVD(const QString &target, const QString &name, int sdcardSize ) const
+QString AndroidConfigurations::createAVD(const QString &target, const QString &name, const QString &abi, int sdcardSize ) const
{
QProcess proc;
proc.start(androidToolPath().toString(),
QStringList() << QLatin1String("create") << QLatin1String("avd")
<< QLatin1String("-a") << QLatin1String("-t") << target
<< QLatin1String("-n") << name
+ << QLatin1String("-b") << abi
<< QLatin1String("-c") << QString::fromLatin1("%1M").arg(sdcardSize));
if (!proc.waitForStarted())
- return false;
+ return QString();
proc.write(QByteArray("no\n"));
if (!proc.waitForFinished(-1)) {
proc.terminate();
- return false;
+ return QString();
}
- return !proc.exitCode();
+ if (proc.exitCode()) // error!
+ return QString();
+ return name;
}
bool AndroidConfigurations::removeAVD(const QString &name) const
@@ -511,8 +558,13 @@ QVector<AndroidDeviceInfo> AndroidConfigurations::androidVirtualDevices() const
if (line.contains(QLatin1String("Target:")))
dev.sdk = line.mid(line.lastIndexOf(QLatin1Char(' '))).remove(QLatin1Char(')')).toInt();
if (line.contains(QLatin1String("ABI:")))
- dev.cpuABI = QStringList() << line.mid(line.lastIndexOf(QLatin1Char(' '))).trimmed();
+ dev.cpuAbi = QStringList() << line.mid(line.lastIndexOf(QLatin1Char(' '))).trimmed();
}
+ // armeabi-v7a devices can also run armeabi code
+ if (dev.cpuAbi == QStringList(QLatin1String("armeabi-v7a")))
+ dev.cpuAbi << QLatin1String("armeabi");
+ dev.unauthorized = false;
+ dev.type = AndroidDeviceInfo::Emulator;
devices.push_back(dev);
}
qSort(devices.begin(), devices.end(), androidDevicesLessThan);
@@ -520,72 +572,57 @@ QVector<AndroidDeviceInfo> AndroidConfigurations::androidVirtualDevices() const
return devices;
}
-QString AndroidConfigurations::startAVD(int *apiLevel, const QString &name) const
+QString AndroidConfigurations::startAVD(const QString &name, int apiLevel, QString cpuAbi) const
+{
+ if (startAVDAsync(name))
+ return waitForAvd(apiLevel, cpuAbi);
+ return QString();
+}
+
+bool AndroidConfigurations::startAVDAsync(const QString &avdName) const
{
QProcess *avdProcess = new QProcess();
connect(this, SIGNAL(destroyed()), avdProcess, SLOT(deleteLater()));
connect(avdProcess, SIGNAL(finished(int)), avdProcess, SLOT(deleteLater()));
- QString avdName = name;
- QVector<AndroidDeviceInfo> devices;
- bool createAVDOnce = false;
- while (true) {
- if (avdName.isEmpty()) {
- devices = androidVirtualDevices();
- foreach (const AndroidDeviceInfo &device, devices)
- if (device.sdk >= *apiLevel) { // take first emulator how supports this package
- *apiLevel = device.sdk;
- avdName = device.serialNumber;
- break;
- }
- }
- // if no emulators found try to create one once
- if (avdName.isEmpty() && !createAVDOnce) {
- createAVDOnce = true;
- QMetaObject::invokeMethod(const_cast<QObject*>(static_cast<const QObject*>(this)), "createAVD", Qt::AutoConnection,
- Q_ARG(int, *apiLevel));
- } else {
- break;
- }
- }
-
- if (avdName.isEmpty())// stop here if no emulators found
- return avdName;
-
// start the emulator
avdProcess->start(emulatorToolPath().toString(),
QStringList() << QLatin1String("-partition-size") << QString::number(config().partitionSize)
<< QLatin1String("-avd") << avdName);
if (!avdProcess->waitForStarted(-1)) {
delete avdProcess;
- return QString();
+ return false;
}
+ return true;
+}
- // wait until the emulator is online
- QProcess proc;
- proc.start(adbToolPath().toString(), QStringList() << QLatin1String("-e") << QLatin1String("wait-for-device"));
- while (!proc.waitForFinished(500)) {
- if (avdProcess->waitForFinished(0)) {
- proc.kill();
- proc.waitForFinished(-1);
+QString AndroidConfigurations::waitForAvd(int apiLevel, const QString &cpuAbi) const
+{
+ // we cannot use adb -e wait-for-device, since that doesn't work if a emulator is already running
+
+ // 15 rounds of 8s sleeping, a minute for the avd to start
+ QString serialNumber;
+ for (int i = 0; i < 15; ++i) {
+ QVector<AndroidDeviceInfo> devices = connectedDevices();
+ foreach (AndroidDeviceInfo device, devices) {
+ if (!device.serialNumber.startsWith(QLatin1String("emulator")))
+ continue;
+ if (!device.cpuAbi.contains(cpuAbi))
+ continue;
+ if (device.sdk != apiLevel)
+ continue;
+ serialNumber = device.serialNumber;
+ // found a serial number, now wait until it's done booting...
+ for (int i = 0; i < 15; ++i) {
+ if (hasFinishedBooting(serialNumber))
+ return serialNumber;
+ else
+ Utils::sleep(8000);
+ }
return QString();
}
+ Utils::sleep(8000);
}
- sleep(5);// wait for pm to start
-
- // workaround for stupid adb bug
- proc.start(adbToolPath().toString(), QStringList() << QLatin1String("devices"));
- if (!proc.waitForFinished(-1)) {
- proc.kill();
- return QString();
- }
-
- // get connected devices
- devices = connectedDevices(*apiLevel);
- foreach (AndroidDeviceInfo device, devices)
- if (device.sdk == *apiLevel)
- return device.serialNumber;
- // this should not happen, but ...
return QString();
}
@@ -605,6 +642,52 @@ int AndroidConfigurations::getSDKVersion(const QString &device) const
return adbProc.readAll().trimmed().toInt();
}
+//!
+//! \brief AndroidConfigurations::getProductModel
+//! \param device serial number
+//! \return the produce model of the device or if that cannot be read the serial number
+//!
+QString AndroidConfigurations::getProductModel(const QString &device) const
+{
+ if (m_serialNumberToDeviceName.contains(device))
+ return m_serialNumberToDeviceName.value(device);
+ // workaround for '????????????' serial numbers
+ QStringList arguments = AndroidDeviceInfo::adbSelector(device);
+ arguments << QLatin1String("shell") << QLatin1String("getprop")
+ << QLatin1String("ro.product.model");
+
+ QProcess adbProc;
+ adbProc.start(adbToolPath().toString(), arguments);
+ if (!adbProc.waitForFinished(-1)) {
+ adbProc.kill();
+ return device;
+ }
+ QString model = QString::fromLocal8Bit(adbProc.readAll().trimmed());
+ if (model.isEmpty())
+ return device;
+ if (!device.startsWith(QLatin1String("????")))
+ m_serialNumberToDeviceName.insert(device, model);
+ return model;
+}
+
+bool AndroidConfigurations::hasFinishedBooting(const QString &device) const
+{
+ QStringList arguments = AndroidDeviceInfo::adbSelector(device);
+ arguments << QLatin1String("shell") << QLatin1String("getprop")
+ << QLatin1String("init.svc.bootanim");
+
+ QProcess adbProc;
+ adbProc.start(adbToolPath().toString(), arguments);
+ if (!adbProc.waitForFinished(-1)) {
+ adbProc.kill();
+ return false;
+ }
+ QString value = QString::fromLocal8Bit(adbProc.readAll().trimmed());
+ if (value == QLatin1String("stopped"))
+ return true;
+ return false;
+}
+
QStringList AndroidConfigurations::getAbis(const QString &device) const
{
QStringList result;
@@ -632,6 +715,13 @@ QStringList AndroidConfigurations::getAbis(const QString &device) const
return result;
}
+QString AndroidConfigurations::highestAvailableAndroidPlatform() const
+{
+ if (m_availablePlatforms.isEmpty())
+ return QString();
+ return QLatin1String("android-") + QString::number(m_availablePlatforms.first());
+}
+
QString AndroidConfigurations::bestMatch(const QString &targetAPI) const
{
int target = targetAPI.mid(targetAPI.lastIndexOf(QLatin1Char('-')) + 1).toInt();
@@ -647,7 +737,7 @@ QStringList AndroidConfigurations::makeExtraSearchDirectories() const
return m_config.makeExtraSearchDirectories;
}
-bool equalKits(Kit *a, Kit *b)
+static bool equalKits(Kit *a, Kit *b)
{
return ToolChainKitInformation::toolChain(a) == ToolChainKitInformation::toolChain(b)
&& QtSupport::QtKitInformation::qtVersion(a) == QtSupport::QtKitInformation::qtVersion(b);
@@ -659,7 +749,7 @@ void AndroidConfigurations::updateAutomaticKitList()
if (AndroidConfigurations::instance().config().automaticKitCreation) {
// having a empty toolchains list will remove all autodetected kits for android
// exactly what we want in that case
- foreach (ProjectExplorer::ToolChain *tc, ProjectExplorer::ToolChainManager::instance()->toolChains()) {
+ foreach (ToolChain *tc, ToolChainManager::toolChains()) {
if (!tc->isAutoDetected())
continue;
if (tc->type() != QLatin1String(Constants::ANDROID_TOOLCHAIN_TYPE))
@@ -670,8 +760,8 @@ void AndroidConfigurations::updateAutomaticKitList()
QList<Kit *> existingKits;
- foreach (ProjectExplorer::Kit *k, ProjectExplorer::KitManager::instance()->kits()) {
- if (ProjectExplorer::DeviceKitInformation::deviceId(k) != Core::Id(Constants::ANDROID_DEVICE_ID))
+ foreach (Kit *k, KitManager::kits()) {
+ if (DeviceKitInformation::deviceId(k) != Core::Id(Constants::ANDROID_DEVICE_ID))
continue;
if (!k->isAutoDetected())
continue;
@@ -681,17 +771,17 @@ void AndroidConfigurations::updateAutomaticKitList()
existingKits << k;
}
- QMap<ProjectExplorer::Abi::Architecture, QList<QtSupport::BaseQtVersion *> > qtVersionsForArch;
- foreach (QtSupport::BaseQtVersion *qtVersion, QtSupport::QtVersionManager::instance()->versions()) {
+ QMap<Abi::Architecture, QList<QtSupport::BaseQtVersion *> > qtVersionsForArch;
+ foreach (QtSupport::BaseQtVersion *qtVersion, QtSupport::QtVersionManager::versions()) {
if (qtVersion->type() != QLatin1String(Constants::ANDROIDQT))
continue;
- QList<ProjectExplorer::Abi> qtAbis = qtVersion->qtAbis();
+ QList<Abi> qtAbis = qtVersion->qtAbis();
if (qtAbis.empty())
continue;
qtVersionsForArch[qtAbis.first().architecture()].append(qtVersion);
}
- ProjectExplorer::DeviceManager *dm = ProjectExplorer::DeviceManager::instance();
+ DeviceManager *dm = DeviceManager::instance();
IDevice::ConstPtr device = dm->find(Core::Id(Constants::ANDROID_DEVICE_ID)); // should always exist
// register new kits
@@ -699,18 +789,18 @@ void AndroidConfigurations::updateAutomaticKitList()
foreach (AndroidToolChain *tc, toolchains) {
QList<QtSupport::BaseQtVersion *> qtVersions = qtVersionsForArch.value(tc->targetAbi().architecture());
foreach (QtSupport::BaseQtVersion *qt, qtVersions) {
+ if (tc->secondaryToolChain())
+ continue;
Kit *newKit = new Kit;
newKit->setAutoDetected(true);
- newKit->setIconPath(QLatin1String(Constants::ANDROID_SETTINGS_CATEGORY_ICON));
+ newKit->setIconPath(Utils::FileName::fromString(QLatin1String(Constants::ANDROID_SETTINGS_CATEGORY_ICON)));
DeviceTypeKitInformation::setDeviceTypeId(newKit, Core::Id(Constants::ANDROID_DEVICE_TYPE));
ToolChainKitInformation::setToolChain(newKit, tc);
QtSupport::QtKitInformation::setQtVersion(newKit, qt);
DeviceKitInformation::setDevice(newKit, device);
- Debugger::DebuggerKitInformation::DebuggerItem item;
- item.engineType = Debugger::GdbEngineType;
- item.binary = tc->suggestedDebugger();
- Debugger::DebuggerKitInformation::setDebuggerItem(newKit, item);
+ Debugger::DebuggerKitInformation::setDebugger(newKit, tc->suggestedDebugger());
AndroidGdbServerKitInformation::setGdbSever(newKit, tc->suggestedGdbServer());
+ newKit->makeSticky();
newKits << newKit;
}
}
@@ -722,6 +812,7 @@ void AndroidConfigurations::updateAutomaticKitList()
if (equalKits(existingKit, newKit)) {
// Kit is already registered, nothing to do
newKits.removeAt(j);
+ existingKits.at(i)->makeSticky();
existingKits.removeAt(i);
KitManager::deleteKit(newKit);
j = newKits.count();
@@ -729,18 +820,24 @@ void AndroidConfigurations::updateAutomaticKitList()
}
}
- foreach (Kit *k, existingKits)
- KitManager::instance()->deregisterKit(k);
+ foreach (Kit *k, existingKits) {
+ ProjectExplorer::ToolChain *tc = ToolChainKitInformation::toolChain(k);
+ if (tc && tc->type() == QLatin1String(Constants::ANDROID_TOOLCHAIN_TYPE)) {
+ k->makeUnSticky();
+ k->setAutoDetected(false);
+ } else {
+ KitManager::deregisterKit(k);
+ }
+ }
foreach (Kit *kit, newKits) {
AndroidToolChain *tc = static_cast<AndroidToolChain *>(ToolChainKitInformation::toolChain(kit));
- QString arch = ProjectExplorer::Abi::toString(tc->targetAbi().architecture());
- QtSupport::BaseQtVersion *qt = QtSupport::QtKitInformation::qtVersion(kit);
+ AndroidQtVersion *qt = static_cast<AndroidQtVersion *>(QtSupport::QtKitInformation::qtVersion(kit));
kit->setDisplayName(tr("Android for %1 (GCC %2, Qt %3)")
- .arg(arch)
+ .arg(qt->targetArch())
.arg(tc->ndkToolChainVersion())
.arg(qt->qtVersionString()));
- KitManager::instance()->registerKit(kit);
+ KitManager::registerKit(kit);
}
}
@@ -764,7 +861,7 @@ AndroidConfigurations &AndroidConfigurations::instance(QObject *parent)
void AndroidConfigurations::save()
{
- QSettings *settings = Core::ICore::instance()->settings();
+ QSettings *settings = Core::ICore::settings();
settings->beginGroup(SettingsGroup);
m_config.save(*settings);
settings->endGroup();
@@ -775,35 +872,38 @@ AndroidConfigurations::AndroidConfigurations(QObject *parent)
{
load();
updateAvailablePlatforms();
+
+ connect(ProjectExplorer::SessionManager::instance(), SIGNAL(projectRemoved(ProjectExplorer::Project*)),
+ this, SLOT(clearDefaultDevices(ProjectExplorer::Project*)));
}
void AndroidConfigurations::load()
{
bool saveSettings = false;
- QSettings *settings = Core::ICore::instance()->settings();
+ QSettings *settings = Core::ICore::settings();
settings->beginGroup(SettingsGroup);
m_config = AndroidConfig(*settings);
if (m_config.antLocation.isEmpty()) {
- Utils::Environment env = Utils::Environment::systemEnvironment();
+ Environment env = Environment::systemEnvironment();
QString location = env.searchInPath(QLatin1String("ant"));
QFileInfo fi(location);
if (fi.exists() && fi.isExecutable() && !fi.isDir()) {
- m_config.antLocation = Utils::FileName::fromString(location);
+ m_config.antLocation = FileName::fromString(location);
saveSettings = true;
}
}
if (m_config.openJDKLocation.isEmpty()) {
- Utils::Environment env = Utils::Environment::systemEnvironment();
+ Environment env = Environment::systemEnvironment();
QString location = env.searchInPath(QLatin1String("javac"));
QFileInfo fi(location);
if (fi.exists() && fi.isExecutable() && !fi.isDir()) {
QDir parentDirectory = fi.canonicalPath();
parentDirectory.cdUp(); // one up from bin
- m_config.openJDKLocation = Utils::FileName::fromString(parentDirectory.absolutePath());
+ m_config.openJDKLocation = FileName::fromString(parentDirectory.absolutePath());
saveSettings = true;
- } else if (Utils::HostOsInfo::isWindowsHost()) {
+ } else if (HostOsInfo::isWindowsHost()) {
QSettings settings(QLatin1String("HKEY_LOCAL_MACHINE\\SOFTWARE\\Javasoft\\Java Development Kit"), QSettings::NativeFormat);
QStringList allVersions = settings.childGroups();
QString javaHome;
@@ -833,7 +933,7 @@ void AndroidConfigurations::load()
}
}
if (!javaHome.isEmpty()) {
- m_config.openJDKLocation = Utils::FileName::fromString(javaHome);
+ m_config.openJDKLocation = FileName::fromString(javaHome);
saveSettings = true;
}
}
@@ -847,9 +947,9 @@ void AndroidConfigurations::load()
void AndroidConfigurations::updateAndroidDevice()
{
- ProjectExplorer::DeviceManager * const devMgr = ProjectExplorer::DeviceManager::instance();
+ DeviceManager * const devMgr = DeviceManager::instance();
if (adbToolPath().toFileInfo().exists())
- devMgr->addDevice(ProjectExplorer::IDevice::Ptr(new Internal::AndroidDevice));
+ devMgr->addDevice(IDevice::Ptr(new Internal::AndroidDevice));
else if (devMgr->find(Constants::ANDROID_DEVICE_ID))
devMgr->removeDevice(Core::Id(Constants::ANDROID_DEVICE_ID));
}
diff --git a/src/plugins/android/androidconfigurations.h b/src/plugins/android/androidconfigurations.h
index 17bf34bc6a..a8d044a205 100644
--- a/src/plugins/android/androidconfigurations.h
+++ b/src/plugins/android/androidconfigurations.h
@@ -34,6 +34,8 @@
#include <QString>
#include <QStringList>
#include <QVector>
+#include <QHash>
+#include <QMap>
#include <projectexplorer/abi.h>
#include <utils/fileutils.h>
@@ -41,6 +43,8 @@ QT_BEGIN_NAMESPACE
class QSettings;
QT_END_NAMESPACE
+namespace ProjectExplorer { class Project; }
+
namespace Android {
namespace Internal {
@@ -65,8 +69,11 @@ public:
struct AndroidDeviceInfo
{
QString serialNumber;
- QStringList cpuABI;
+ QStringList cpuAbi;
int sdk;
+ bool unauthorized;
+ enum AndroidDeviceType { Hardware, Emulator };
+ AndroidDeviceType type;
static QStringList adbSelector(const QString &serialNumber);
};
@@ -92,12 +99,14 @@ public:
Utils::FileName zipalignPath() const;
Utils::FileName stripPath(ProjectExplorer::Abi::Architecture architecture, const QString &ndkToolChainVersion) const;
Utils::FileName readelfPath(ProjectExplorer::Abi::Architecture architecture, const QString &ndkToolChainVersion) const;
- QString getDeployDeviceSerialNumber(int *apiLevel, const QString &abi) const;
- bool createAVD(const QString &target, const QString &name, int sdcardSize) const;
+ QString createAVD(int minApiLevel = 0, QString targetArch = QString()) const;
+ QString createAVD(const QString &target, const QString &name, const QString &abi, int sdcardSize) const;
bool removeAVD(const QString &name) const;
- QVector<AndroidDeviceInfo> connectedDevices(int apiLevel = -1) const;
+ QVector<AndroidDeviceInfo> connectedDevices(QString *error = 0) const;
QVector<AndroidDeviceInfo> androidVirtualDevices() const;
- QString startAVD(int *apiLevel, const QString &name = QString()) const;
+ QString startAVD(const QString &name, int apiLevel, QString cpuAbi) const;
+ bool startAVDAsync(const QString &avdName) const;
+ QString waitForAvd(int apiLevel, const QString &cpuAbi) const;
QString bestMatch(const QString &targetAPI) const;
QStringList makeExtraSearchDirectories() const;
@@ -109,11 +118,20 @@ public:
// called from AndroidPlugin
void updateAndroidDevice();
+ QString getProductModel(const QString &device) const;
+ bool hasFinishedBooting(const QString &device) const;
+
+ AndroidDeviceInfo showDeviceDialog(ProjectExplorer::Project *project, int apiLevel, const QString &abi);
+ void setDefaultDevice(ProjectExplorer::Project *project, const QString &abi, const QString &serialNumber); // serial number or avd name
+ QString defaultDevice(ProjectExplorer::Project *project, const QString &abi) const; // serial number or avd name
+ QString highestAvailableAndroidPlatform() const;
+public slots:
+ void clearDefaultDevices(ProjectExplorer::Project *project);
+
signals:
void updated();
public slots:
- bool createAVD(int minApiLevel = 0) const;
void updateAutomaticKitList();
private:
@@ -133,6 +151,9 @@ private:
static AndroidConfigurations *m_instance;
AndroidConfig m_config;
QVector<int> m_availablePlatforms;
+ mutable QHash<QString, QString> m_serialNumberToDeviceName;
+
+ QMap<ProjectExplorer::Project *, QMap<QString, QString> > m_defaultDeviceForAbi;
};
} // namespace Internal
diff --git a/src/plugins/android/androidcreatekeystorecertificate.cpp b/src/plugins/android/androidcreatekeystorecertificate.cpp
index bcce983e23..5fc5dc0285 100644
--- a/src/plugins/android/androidcreatekeystorecertificate.cpp
+++ b/src/plugins/android/androidcreatekeystorecertificate.cpp
@@ -46,6 +46,8 @@ AndroidCreateKeystoreCertificate::AndroidCreateKeystoreCertificate(QWidget *pare
connect(ui->keystoreRetypePassLineEdit, SIGNAL(textChanged(QString)), this, SLOT(checkKeystorePassword()));
connect(ui->certificatePassLineEdit, SIGNAL(textChanged(QString)), this, SLOT(checkCertificatePassword()));
connect(ui->certificateRetypePassLineEdit, SIGNAL(textChanged(QString)), this, SLOT(checkCertificatePassword()));
+ connect(ui->certificateAliasLineEdit, SIGNAL(textChanged(QString)), this, SLOT(checkCertificateAlias()));
+ connect(ui->countryLineEdit, SIGNAL(textChanged(QString)), this, SLOT(checkCountryCode()));
}
AndroidCreateKeystoreCertificate::~AndroidCreateKeystoreCertificate()
@@ -65,42 +67,71 @@ QString AndroidCreateKeystoreCertificate::keystorePassword()
QString AndroidCreateKeystoreCertificate::certificateAlias()
{
- return ui->aliasNameLineEdit->text();
+ return ui->certificateAliasLineEdit->text();
}
QString AndroidCreateKeystoreCertificate::certificatePassword()
{
- return ui->certificatePassLineEdit->text();
+ return (ui->samePasswordCheckBox->checkState() == Qt::Checked)
+ ? keystorePassword()
+ : ui->certificatePassLineEdit->text();
}
AndroidCreateKeystoreCertificate::PasswordStatus AndroidCreateKeystoreCertificate::checkKeystorePassword()
{
if (ui->keystorePassLineEdit->text().length() < 6) {
- ui->keystorePassInfoLabel->setText(tr("<span style=\" color:#ff0000;\">Password is too short</span>"));
+ ui->infoLabel->setText(tr("<span style=\" color:#ff0000;\">Keystore password is too short</span>"));
return Invalid;
}
if (ui->keystorePassLineEdit->text() != ui->keystoreRetypePassLineEdit->text()) {
- ui->keystorePassInfoLabel->setText(tr("<span style=\" color:#ff0000;\">Passwords don't match</span>"));
+ ui->infoLabel->setText(tr("<span style=\" color:#ff0000;\">Keystore passwords do not match</span>"));
return NoMatch;
}
- ui->keystorePassInfoLabel->setText(tr("<span style=\" color:#00ff00;\">Password is ok</span>"));
+
+ ui->infoLabel->clear();
return Match;
}
AndroidCreateKeystoreCertificate::PasswordStatus AndroidCreateKeystoreCertificate::checkCertificatePassword()
{
+ if (ui->samePasswordCheckBox->checkState() == Qt::Checked)
+ return Match;
+
if (ui->certificatePassLineEdit->text().length() < 6) {
- ui->certificatePassInfoLabel->setText(tr("<span style=\" color:#ff0000;\">Password is too short</span>"));
+ ui->infoLabel->setText(tr("<span style=\" color:#ff0000;\">Certificate password is too short</span>"));
return Invalid;
}
if (ui->certificatePassLineEdit->text() != ui->certificateRetypePassLineEdit->text()) {
- ui->certificatePassInfoLabel->setText(tr("<span style=\" color:#ff0000;\">Passwords don't match</span>"));
+ ui->infoLabel->setText(tr("<span style=\" color:#ff0000;\">Certificate passwords do not match</span>"));
return NoMatch;
}
- ui->certificatePassInfoLabel->setText(tr("<span style=\" color:#00ff00;\">Password is ok</span>"));
+
+ ui->infoLabel->clear();
return Match;
}
+bool AndroidCreateKeystoreCertificate::checkCertificateAlias()
+{
+ if (ui->certificateAliasLineEdit->text().length() == 0) {
+ ui->infoLabel->setText(tr("<span style=\" color:#ff0000;\">Certificate alias is missing</span>"));
+ return false;
+ }
+
+ ui->infoLabel->clear();
+ return true;
+}
+
+bool AndroidCreateKeystoreCertificate::checkCountryCode()
+{
+ if (!ui->countryLineEdit->text().contains(QRegExp(QLatin1String("[A-Z]{2}")))) {
+ ui->infoLabel->setText(tr("<span style=\" color:#ff0000;\">Invalid country code</span>"));
+ return false;
+ }
+
+ ui->infoLabel->clear();
+ return true;
+}
+
void AndroidCreateKeystoreCertificate::on_keystoreShowPassCheckBox_stateChanged(int state)
{
ui->keystorePassLineEdit->setEchoMode(state == Qt::Checked ? QLineEdit::Normal : QLineEdit::Password);
@@ -115,42 +146,8 @@ void AndroidCreateKeystoreCertificate::on_certificateShowPassCheckBox_stateChang
void AndroidCreateKeystoreCertificate::on_buttonBox_accepted()
{
- switch (checkKeystorePassword()) {
- case Invalid:
- ui->keystorePassLineEdit->setFocus();
- return;
- case NoMatch:
- ui->keystoreRetypePassLineEdit->setFocus();
- return;
- default:
- break;
- }
-
- switch (checkCertificatePassword()) {
- case Invalid:
- ui->certificatePassLineEdit->setFocus();
+ if (!validateUserInput())
return;
- case NoMatch:
- ui->certificateRetypePassLineEdit->setFocus();
- return;
- default:
- break;
- }
-
- if (!ui->aliasNameLineEdit->text().length())
- ui->aliasNameLineEdit->setFocus();
-
- if (!ui->commonNameLineEdit->text().length())
- ui->commonNameLineEdit->setFocus();
-
- if (!ui->organizationNameLineEdit->text().length())
- ui->organizationNameLineEdit->setFocus();
-
- if (!ui->localityNameLineEdit->text().length())
- ui->localityNameLineEdit->setFocus();
-
- if (!ui->countryLineEdit->text().length())
- ui->countryLineEdit->setFocus();
m_keystoreFilePath = Utils::FileName::fromString(QFileDialog::getSaveFileName(this, tr("Keystore file name"),
QDir::homePath() + QLatin1String("/android_release.keystore"),
@@ -172,11 +169,11 @@ void AndroidCreateKeystoreCertificate::on_buttonBox_accepted()
QStringList params;
params << QLatin1String("-genkey") << QLatin1String("-keyalg") << QLatin1String("RSA")
<< QLatin1String("-keystore") << m_keystoreFilePath.toString()
- << QLatin1String("-storepass") << ui->keystorePassLineEdit->text()
- << QLatin1String("-alias") << ui->aliasNameLineEdit->text()
+ << QLatin1String("-storepass") << keystorePassword()
+ << QLatin1String("-alias") << certificateAlias()
<< QLatin1String("-keysize") << ui->keySizeSpinBox->text()
<< QLatin1String("-validity") << ui->validitySpinBox->text()
- << QLatin1String("-keypass") << ui->certificatePassLineEdit->text()
+ << QLatin1String("-keypass") << certificatePassword()
<< QLatin1String("-dname") << distinguishedNames;
QProcess genKeyCertProc;
@@ -193,3 +190,57 @@ void AndroidCreateKeystoreCertificate::on_buttonBox_accepted()
}
accept();
}
+
+void AndroidCreateKeystoreCertificate::on_samePasswordCheckBox_stateChanged(int state)
+{
+ if (state == Qt::Checked) {
+ ui->certificatePassLineEdit->setDisabled(true);
+ ui->certificateRetypePassLineEdit->setDisabled(true);
+ ui->certificateShowPassCheckBox->setDisabled(true);
+ }
+
+ if (state == Qt::Unchecked) {
+ ui->certificatePassLineEdit->setEnabled(true);
+ ui->certificateRetypePassLineEdit->setEnabled(true);
+ ui->certificateShowPassCheckBox->setEnabled(true);
+ }
+
+ validateUserInput();
+}
+
+bool AndroidCreateKeystoreCertificate::validateUserInput()
+{
+ switch (checkKeystorePassword()) {
+ case Invalid:
+ ui->keystorePassLineEdit->setFocus();
+ return false;
+ case NoMatch:
+ ui->keystoreRetypePassLineEdit->setFocus();
+ return false;
+ default:
+ break;
+ }
+
+ if (!checkCertificateAlias()) {
+ ui->certificateAliasLineEdit->setFocus();
+ return false;
+ }
+
+ switch (checkCertificatePassword()) {
+ case Invalid:
+ ui->certificatePassLineEdit->setFocus();
+ return false;
+ case NoMatch:
+ ui->certificateRetypePassLineEdit->setFocus();
+ return false;
+ default:
+ break;
+ }
+
+ if (!checkCountryCode()) {
+ ui->countryLineEdit->setFocus();
+ return false;
+ }
+
+ return true;
+}
diff --git a/src/plugins/android/androidcreatekeystorecertificate.h b/src/plugins/android/androidcreatekeystorecertificate.h
index 5df88bef8b..021a52b188 100644
--- a/src/plugins/android/androidcreatekeystorecertificate.h
+++ b/src/plugins/android/androidcreatekeystorecertificate.h
@@ -62,11 +62,15 @@ public:
private slots:
PasswordStatus checkKeystorePassword();
PasswordStatus checkCertificatePassword();
+ bool checkCertificateAlias();
+ bool checkCountryCode();
void on_keystoreShowPassCheckBox_stateChanged(int state);
void on_certificateShowPassCheckBox_stateChanged(int state);
void on_buttonBox_accepted();
+ void on_samePasswordCheckBox_stateChanged(int state);
private:
+ bool validateUserInput();
Ui::AndroidCreateKeystoreCertificate *ui;
Utils::FileName m_keystoreFilePath;
};
diff --git a/src/plugins/android/androidcreatekeystorecertificate.ui b/src/plugins/android/androidcreatekeystorecertificate.ui
index ed0d4ecf8b..51c66939f5 100644
--- a/src/plugins/android/androidcreatekeystorecertificate.ui
+++ b/src/plugins/android/androidcreatekeystorecertificate.ui
@@ -7,23 +7,23 @@
<x>0</x>
<y>0</y>
<width>638</width>
- <height>429</height>
+ <height>473</height>
</rect>
</property>
<property name="windowTitle">
<string>Create a keystore and a certificate</string>
</property>
<layout class="QGridLayout" name="gridLayout_4">
- <item row="0" column="0">
- <widget class="QGroupBox" name="groupBox">
+ <item row="2" column="0" colspan="2">
+ <widget class="QGroupBox" name="groupBox_2">
<property name="title">
- <string>Keystore</string>
+ <string>Certificate Distinguished Names</string>
</property>
- <layout class="QGridLayout" name="gridLayout">
+ <layout class="QGridLayout" name="gridLayout_3">
<item row="0" column="0">
- <widget class="QLabel" name="label">
+ <widget class="QLabel" name="label_5">
<property name="text">
- <string>Password:</string>
+ <string>First and last name:</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
@@ -31,16 +31,12 @@
</widget>
</item>
<item row="0" column="1">
- <widget class="QLineEdit" name="keystorePassLineEdit">
- <property name="echoMode">
- <enum>QLineEdit::Password</enum>
- </property>
- </widget>
+ <widget class="QLineEdit" name="commonNameLineEdit"/>
</item>
<item row="1" column="0">
- <widget class="QLabel" name="label_2">
+ <widget class="QLabel" name="label_6">
<property name="text">
- <string>Retype password:</string>
+ <string>Organizational unit (e.g. Necessitas):</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
@@ -48,78 +44,97 @@
</widget>
</item>
<item row="1" column="1">
- <widget class="QLineEdit" name="keystoreRetypePassLineEdit">
- <property name="echoMode">
- <enum>QLineEdit::Password</enum>
- </property>
- </widget>
+ <widget class="QLineEdit" name="organizationUnitLineEdit"/>
</item>
<item row="2" column="0">
- <widget class="QCheckBox" name="keystoreShowPassCheckBox">
+ <widget class="QLabel" name="label_7">
<property name="text">
- <string>Show password</string>
+ <string>Organization (e.g. KDE):</string>
+ </property>
+ <property name="alignment">
+ <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item row="2" column="1">
- <widget class="QLabel" name="keystorePassInfoLabel">
+ <widget class="QLineEdit" name="organizationNameLineEdit"/>
+ </item>
+ <item row="3" column="0">
+ <widget class="QLabel" name="label_8">
<property name="text">
- <string>&lt;span style=&quot; color:#ff0000;&quot;&gt;Password is too short&lt;/span&gt;</string>
+ <string>City or locality:</string>
</property>
- <property name="textFormat">
- <enum>Qt::RichText</enum>
+ <property name="alignment">
+ <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
+ </property>
+ </widget>
+ </item>
+ <item row="3" column="1">
+ <widget class="QLineEdit" name="localityNameLineEdit"/>
+ </item>
+ <item row="4" column="0">
+ <widget class="QLabel" name="label_9">
+ <property name="text">
+ <string>State or province:</string>
</property>
<property name="alignment">
- <set>Qt::AlignCenter</set>
+ <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
- </layout>
- </widget>
- </item>
- <item row="0" column="1">
- <widget class="QGroupBox" name="groupBox_3">
- <property name="title">
- <string>Certificate</string>
- </property>
- <layout class="QGridLayout" name="gridLayout_2">
- <item row="0" column="0">
- <widget class="QLabel" name="label_11">
+ <item row="4" column="1">
+ <widget class="QLineEdit" name="stateNameLineEdit"/>
+ </item>
+ <item row="5" column="0">
+ <widget class="QLabel" name="label_10">
<property name="text">
- <string>Alias name:</string>
+ <string>Two-letter country code for this unit (e.g. RO):</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
- <item row="0" column="1">
- <widget class="QLineEdit" name="aliasNameLineEdit">
+ <item row="5" column="1">
+ <widget class="QLineEdit" name="countryLineEdit">
<property name="inputMask">
- <string>Aaaaaaaa; </string>
+ <string/>
</property>
<property name="maxLength">
- <number>8</number>
+ <number>2</number>
</property>
</widget>
</item>
- <item row="1" column="0">
- <widget class="QLabel" name="label_12">
- <property name="text">
- <string>Keysize:</string>
+ </layout>
+ </widget>
+ </item>
+ <item row="1" column="1">
+ <widget class="QGroupBox" name="groupBox_3">
+ <property name="title">
+ <string>Certificate</string>
+ </property>
+ <layout class="QGridLayout" name="gridLayout_2">
+ <item row="4" column="1">
+ <widget class="QLineEdit" name="certificateRetypePassLineEdit">
+ <property name="echoMode">
+ <enum>QLineEdit::Password</enum>
</property>
- <property name="alignment">
- <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
+ </widget>
+ </item>
+ <item row="5" column="1">
+ <widget class="QCheckBox" name="certificateShowPassCheckBox">
+ <property name="text">
+ <string>Show password</string>
</property>
</widget>
</item>
- <item row="1" column="1">
- <widget class="QSpinBox" name="keySizeSpinBox">
+ <item row="2" column="1">
+ <widget class="QSpinBox" name="validitySpinBox">
<property name="minimum">
- <number>2048</number>
+ <number>10000</number>
</property>
<property name="maximum">
- <number>2097152</number>
+ <number>100000</number>
</property>
</widget>
</item>
@@ -133,13 +148,13 @@
</property>
</widget>
</item>
- <item row="2" column="1">
- <widget class="QSpinBox" name="validitySpinBox">
- <property name="minimum">
- <number>10000</number>
+ <item row="0" column="0">
+ <widget class="QLabel" name="label_11">
+ <property name="text">
+ <string>Alias name:</string>
</property>
- <property name="maximum">
- <number>100000</number>
+ <property name="alignment">
+ <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
@@ -153,148 +168,127 @@
</property>
</widget>
</item>
- <item row="3" column="1">
- <widget class="QLineEdit" name="certificatePassLineEdit">
- <property name="echoMode">
- <enum>QLineEdit::Password</enum>
+ <item row="0" column="1">
+ <widget class="QLineEdit" name="certificateAliasLineEdit">
+ <property name="inputMask">
+ <string notr="true"/>
+ </property>
+ <property name="maxLength">
+ <number>8</number>
</property>
</widget>
</item>
- <item row="4" column="0">
- <widget class="QLabel" name="label_18">
+ <item row="1" column="0">
+ <widget class="QLabel" name="label_12">
<property name="text">
- <string>Retype password:</string>
+ <string>Keysize:</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
- <item row="4" column="1">
- <widget class="QLineEdit" name="certificateRetypePassLineEdit">
+ <item row="3" column="1">
+ <widget class="QLineEdit" name="certificatePassLineEdit">
<property name="echoMode">
<enum>QLineEdit::Password</enum>
</property>
</widget>
</item>
- <item row="5" column="0">
- <widget class="QCheckBox" name="certificateShowPassCheckBox">
- <property name="text">
- <string>Show password</string>
- </property>
- </widget>
- </item>
- <item row="5" column="1">
- <widget class="QLabel" name="certificatePassInfoLabel">
- <property name="text">
- <string>&lt;span style=&quot; color:#ff0000;&quot;&gt;Password is too short&lt;/span&gt;</string>
- </property>
- <property name="textFormat">
- <enum>Qt::RichText</enum>
+ <item row="1" column="1">
+ <widget class="QSpinBox" name="keySizeSpinBox">
+ <property name="minimum">
+ <number>2048</number>
</property>
- <property name="alignment">
- <set>Qt::AlignCenter</set>
+ <property name="maximum">
+ <number>2097152</number>
</property>
</widget>
</item>
- </layout>
- </widget>
- </item>
- <item row="1" column="0" colspan="2">
- <widget class="QGroupBox" name="groupBox_2">
- <property name="title">
- <string>Certificate Distinguished Names</string>
- </property>
- <layout class="QGridLayout" name="gridLayout_3">
- <item row="0" column="0">
- <widget class="QLabel" name="label_5">
+ <item row="4" column="0">
+ <widget class="QLabel" name="label_18">
<property name="text">
- <string>First and last name:</string>
+ <string>Retype password:</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
- <item row="0" column="1">
- <widget class="QLineEdit" name="commonNameLineEdit"/>
- </item>
- <item row="1" column="0">
- <widget class="QLabel" name="label_6">
+ <item row="5" column="0">
+ <widget class="QCheckBox" name="samePasswordCheckBox">
<property name="text">
- <string>Organizational unit (e.g. Necessitas):</string>
- </property>
- <property name="alignment">
- <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
+ <string>Use Keystore password</string>
</property>
</widget>
</item>
+ </layout>
+ </widget>
+ </item>
+ <item row="1" column="0">
+ <widget class="QGroupBox" name="groupBox">
+ <property name="title">
+ <string>Keystore</string>
+ </property>
+ <layout class="QGridLayout" name="gridLayout">
<item row="1" column="1">
- <widget class="QLineEdit" name="organizationUnitLineEdit"/>
- </item>
- <item row="2" column="0">
- <widget class="QLabel" name="label_7">
- <property name="text">
- <string>Organization (e.g. KDE):</string>
- </property>
- <property name="alignment">
- <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
+ <widget class="QLineEdit" name="keystorePassLineEdit">
+ <property name="echoMode">
+ <enum>QLineEdit::Password</enum>
</property>
</widget>
</item>
<item row="2" column="1">
- <widget class="QLineEdit" name="organizationNameLineEdit"/>
+ <widget class="QLineEdit" name="keystoreRetypePassLineEdit">
+ <property name="echoMode">
+ <enum>QLineEdit::Password</enum>
+ </property>
+ </widget>
</item>
<item row="3" column="0">
- <widget class="QLabel" name="label_8">
+ <widget class="QCheckBox" name="keystoreShowPassCheckBox">
<property name="text">
- <string>City or locality:</string>
- </property>
- <property name="alignment">
- <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
+ <string>Show password</string>
</property>
</widget>
</item>
- <item row="3" column="1">
- <widget class="QLineEdit" name="localityNameLineEdit"/>
- </item>
- <item row="4" column="0">
- <widget class="QLabel" name="label_9">
+ <item row="1" column="0">
+ <widget class="QLabel" name="label">
<property name="text">
- <string>State or province:</string>
+ <string>Password:</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
- <item row="4" column="1">
- <widget class="QLineEdit" name="stateNameLineEdit"/>
- </item>
- <item row="5" column="0">
- <widget class="QLabel" name="label_10">
+ <item row="2" column="0">
+ <widget class="QLabel" name="label_2">
<property name="text">
- <string>Two-letter country code for this unit (e.g. RO):</string>
+ <string>Retype password:</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
- <item row="5" column="1">
- <widget class="QLineEdit" name="countryLineEdit">
- <property name="inputMask">
- <string>&gt;AA; </string>
- </property>
- <property name="maxLength">
- <number>2</number>
- </property>
- </widget>
+ <item row="0" column="0" colspan="2">
+ <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>
</widget>
</item>
- <item row="2" column="0" colspan="2">
+ <item row="3" column="1">
<widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation">
<enum>Qt::Horizontal</enum>
@@ -304,12 +298,22 @@
</property>
</widget>
</item>
+ <item row="3" column="0">
+ <widget class="QLabel" name="infoLabel">
+ <property name="text">
+ <string/>
+ </property>
+ <property name="alignment">
+ <set>Qt::AlignCenter</set>
+ </property>
+ </widget>
+ </item>
</layout>
</widget>
<tabstops>
<tabstop>keystorePassLineEdit</tabstop>
<tabstop>keystoreRetypePassLineEdit</tabstop>
- <tabstop>aliasNameLineEdit</tabstop>
+ <tabstop>certificateAliasLineEdit</tabstop>
<tabstop>keySizeSpinBox</tabstop>
<tabstop>validitySpinBox</tabstop>
<tabstop>certificatePassLineEdit</tabstop>
@@ -321,7 +325,6 @@
<tabstop>stateNameLineEdit</tabstop>
<tabstop>countryLineEdit</tabstop>
<tabstop>keystoreShowPassCheckBox</tabstop>
- <tabstop>certificateShowPassCheckBox</tabstop>
<tabstop>buttonBox</tabstop>
</tabstops>
<resources/>
diff --git a/src/plugins/android/androiddeployconfiguration.cpp b/src/plugins/android/androiddeployconfiguration.cpp
index 9c8305e3ab..ab1227d9c2 100644
--- a/src/plugins/android/androiddeployconfiguration.cpp
+++ b/src/plugins/android/androiddeployconfiguration.cpp
@@ -32,6 +32,7 @@
#include "androiddeploystep.h"
#include "androidpackageinstallationstep.h"
#include "androidpackagecreationstep.h"
+#include "androiddeployqtstep.h"
#include "androidmanager.h"
#include <projectexplorer/buildsteplist.h>
@@ -76,9 +77,15 @@ DeployConfiguration *AndroidDeployConfigurationFactory::create(Target *parent, c
AndroidDeployConfiguration *dc = new AndroidDeployConfiguration(parent, id);
if (!dc)
return 0;
- dc->stepList()->insertStep(0, new AndroidPackageInstallationStep(dc->stepList()));
- dc->stepList()->insertStep(1, new AndroidPackageCreationStep(dc->stepList()));
- dc->stepList()->insertStep(2, new AndroidDeployStep(dc->stepList()));
+
+ if (id == ANDROID_DEPLOYCONFIGURATION_ID) {
+ dc->stepList()->insertStep(0, new AndroidPackageInstallationStep(AndroidPackageInstallationStep::ProjectDirectory, dc->stepList()));
+ dc->stepList()->insertStep(1, new AndroidPackageCreationStep(dc->stepList()));
+ dc->stepList()->insertStep(2, new AndroidDeployStep(dc->stepList()));
+ } else {
+ dc->stepList()->insertStep(0, new AndroidPackageInstallationStep(AndroidPackageInstallationStep::BuildDirectory, dc->stepList()));
+ dc->stepList()->insertStep(1, new AndroidDeployQtStep(dc->stepList()));
+ }
return dc;
}
@@ -104,7 +111,7 @@ bool AndroidDeployConfigurationFactory::canClone(Target *parent, DeployConfigura
{
if (!AndroidManager::supportsAndroid(parent))
return false;
- return source->id() == ANDROID_DEPLOYCONFIGURATION_ID;
+ return canCreate(parent, source->id());
}
DeployConfiguration *AndroidDeployConfigurationFactory::clone(Target *parent, DeployConfiguration *source)
@@ -128,16 +135,20 @@ QList<Core::Id> AndroidDeployConfigurationFactory::availableCreationIds(Target *
if (!tc || tc->targetAbi().osFlavor() != Abi::AndroidLinuxFlavor)
return ids;
- if (QtSupport::QtKitInformation::qtVersion(parent->kit())->type() != QLatin1String(Constants::ANDROIDQT))
+ QtSupport::BaseQtVersion *qt = QtSupport::QtKitInformation::qtVersion(parent->kit());
+ if (qt->type() != QLatin1String(Constants::ANDROIDQT))
return ids;
-
- ids << Core::Id(ANDROID_DEPLOYCONFIGURATION_ID);
+ if (qt->qtVersion() < QtSupport::QtVersionNumber(5, 2, 0))
+ ids << Core::Id(ANDROID_DEPLOYCONFIGURATION_ID);
+ else
+ ids << Core::Id(ANDROID_DEPLOYCONFIGURATION2_ID);
return ids;
}
QString AndroidDeployConfigurationFactory::displayNameForId(const Core::Id id) const
{
- if (id.name().startsWith(ANDROID_DC_PREFIX))
+ if (id.name().startsWith(ANDROID_DC_PREFIX)
+ || id.name().startsWith(ANDROID_DC2_PREFIX))
return tr("Deploy on Android");
return QString();
}
diff --git a/src/plugins/android/androiddeployconfiguration.h b/src/plugins/android/androiddeployconfiguration.h
index e464415548..654c5843c8 100644
--- a/src/plugins/android/androiddeployconfiguration.h
+++ b/src/plugins/android/androiddeployconfiguration.h
@@ -38,6 +38,10 @@ namespace Internal {
const char ANDROID_DEPLOYCONFIGURATION_ID[] = "Qt4ProjectManager.AndroidDeployConfiguration";
const char ANDROID_DC_PREFIX[] = "Qt4ProjectManager.AndroidDeployConfiguration.";
+// Qt 5.2 has a new form of deployment
+const char ANDROID_DEPLOYCONFIGURATION2_ID[] = "Qt4ProjectManager.AndroidDeployConfiguration2";
+const char ANDROID_DC2_PREFIX[] = "Qt4ProjectManager.AndroidDeployConfiguration2.";
+
class AndroidDeployConfiguration : public ProjectExplorer::DeployConfiguration
{
Q_OBJECT
diff --git a/src/plugins/android/androiddeployqtstep.cpp b/src/plugins/android/androiddeployqtstep.cpp
new file mode 100644
index 0000000000..ea5d6eeac0
--- /dev/null
+++ b/src/plugins/android/androiddeployqtstep.cpp
@@ -0,0 +1,554 @@
+/**************************************************************************
+**
+** Copyright (c) 2013 BogDan Vatra <bog_dan_ro@yahoo.com>
+** 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 "androiddeployqtstep.h"
+#include "androiddeployqtwidget.h"
+#include "certificatesmodel.h"
+
+#include "javaparser.h"
+#include "androidmanager.h"
+
+#include <utils/qtcassert.h>
+#include <utils/qtcprocess.h>
+#include <coreplugin/fileutils.h>
+#include <coreplugin/icore.h>
+#include <coreplugin/messagemanager.h>
+#include <projectexplorer/buildsteplist.h>
+#include <projectexplorer/projectexplorerconstants.h>
+#include <projectexplorer/target.h>
+#include <projectexplorer/project.h>
+#include <qtsupport/qtkitinformation.h>
+#include <qt4projectmanager/qt4buildconfiguration.h>
+#include <qt4projectmanager/qt4project.h>
+#include <qt4projectmanager/qt4nodes.h>
+#include <QInputDialog>
+#include <QMessageBox>
+
+using namespace Android;
+using namespace Android::Internal;
+
+const QLatin1String DeployActionKey("Qt4ProjectManager.AndroidDeployQtStep.DeployQtAction");
+const QLatin1String KeystoreLocationKey("KeystoreLocation");
+const QLatin1String SignPackageKey("SignPackage");
+const QLatin1String BuildTargetSdkKey("BuildTargetSdk");
+const QLatin1String VerboseOutputKey("VerboseOutput");
+const QLatin1String InputFile("InputFile");
+const Core::Id AndroidDeployQtStep::Id("Qt4ProjectManager.AndroidDeployQtStep");
+
+//////////////////
+// AndroidDeployQtStepFactory
+/////////////////
+
+AndroidDeployQtStepFactory::AndroidDeployQtStepFactory(QObject *parent)
+ : IBuildStepFactory(parent)
+{
+}
+
+QList<Core::Id> AndroidDeployQtStepFactory::availableCreationIds(ProjectExplorer::BuildStepList *parent) const
+{
+ if (parent->id() != ProjectExplorer::Constants::BUILDSTEPS_DEPLOY)
+ return QList<Core::Id>();
+ if (!AndroidManager::supportsAndroid(parent->target()))
+ return QList<Core::Id>();
+ if (parent->contains(AndroidDeployQtStep::Id))
+ return QList<Core::Id>();
+ return QList<Core::Id>() << AndroidDeployQtStep::Id;
+}
+
+QString AndroidDeployQtStepFactory::displayNameForId(const Core::Id id) const
+{
+ if (id == AndroidDeployQtStep::Id)
+ return tr("Deploy to Android device or emulator");
+ return QString();
+}
+
+bool AndroidDeployQtStepFactory::canCreate(ProjectExplorer::BuildStepList *parent, const Core::Id id) const
+{
+ return availableCreationIds(parent).contains(id);
+}
+
+ProjectExplorer::BuildStep *AndroidDeployQtStepFactory::create(ProjectExplorer::BuildStepList *parent, const Core::Id id)
+{
+ Q_ASSERT(canCreate(parent, id));
+ Q_UNUSED(id);
+ return new AndroidDeployQtStep(parent);
+}
+
+bool AndroidDeployQtStepFactory::canRestore(ProjectExplorer::BuildStepList *parent, const QVariantMap &map) const
+{
+ return canCreate(parent, ProjectExplorer::idFromMap(map));
+}
+
+ProjectExplorer::BuildStep *AndroidDeployQtStepFactory::restore(ProjectExplorer::BuildStepList *parent, const QVariantMap &map)
+{
+ Q_ASSERT(canRestore(parent, map));
+ AndroidDeployQtStep * const step = new AndroidDeployQtStep(parent);
+ if (!step->fromMap(map)) {
+ delete step;
+ return 0;
+ }
+ return step;
+}
+
+bool AndroidDeployQtStepFactory::canClone(ProjectExplorer::BuildStepList *parent, ProjectExplorer::BuildStep *product) const
+{
+ return canCreate(parent, product->id());
+}
+
+ProjectExplorer::BuildStep *AndroidDeployQtStepFactory::clone(ProjectExplorer::BuildStepList *parent, ProjectExplorer::BuildStep *product)
+{
+ Q_ASSERT(canClone(parent, product));
+ return new AndroidDeployQtStep(parent, static_cast<AndroidDeployQtStep *>(product));
+}
+
+//////////////////
+// AndroidDeployQtStep
+/////////////////
+
+AndroidDeployQtStep::AndroidDeployQtStep(ProjectExplorer::BuildStepList *parent)
+ : ProjectExplorer::AbstractProcessStep(parent, Id)
+{
+ ctor();
+}
+
+AndroidDeployQtStep::AndroidDeployQtStep(ProjectExplorer::BuildStepList *parent,
+ AndroidDeployQtStep *other)
+ : ProjectExplorer::AbstractProcessStep(parent, other)
+{
+ ctor();
+}
+
+void AndroidDeployQtStep::ctor()
+{
+ //: AndroidDeployQtStep default display name
+ setDefaultDisplayName(tr("Deploy to Android device"));
+ m_deployAction = BundleLibrariesDeployment;
+ m_signPackage = false;
+ m_openPackageLocation = false;
+ m_verbose = false;
+
+ // will be overwriten by settings if the user choose something different
+ m_buildTargetSdk = AndroidConfigurations::instance().highestAvailableAndroidPlatform();
+
+ connect(project(), SIGNAL(proFilesEvaluated()),
+ this, SLOT(updateInputFile()));
+}
+
+bool AndroidDeployQtStep::init()
+{
+ if (AndroidManager::checkForQt51Files(project()->projectDirectory()))
+ emit addOutput(tr("Found old android folder in source directory. Qt 5.2 does not use that folder by default."), ErrorOutput);
+
+ m_targetArch = AndroidManager::targetArch(target());
+ m_deviceAPILevel = AndroidManager::minimumSDK(target());
+ AndroidDeviceInfo info = AndroidConfigurations::instance().showDeviceDialog(project(), m_deviceAPILevel, m_targetArch);
+ if (info.serialNumber.isEmpty()) // aborted
+ return false;
+
+ if (info.type == AndroidDeviceInfo::Emulator) {
+ m_avdName = info.serialNumber;
+ m_serialNumber.clear();
+ m_deviceAPILevel = info.sdk;
+ } else {
+ m_avdName.clear();
+ m_serialNumber = info.serialNumber;
+ }
+
+ Qt4ProjectManager::Qt4BuildConfiguration *bc
+ = static_cast<Qt4ProjectManager::Qt4BuildConfiguration *>(target()->activeBuildConfiguration());
+
+ if (m_signPackage) {
+ // check keystore and certificate passwords
+ while (!AndroidManager::checkKeystorePassword(m_keystorePath.toString(), m_keystorePasswd)) {
+ if (!keystorePassword())
+ return false; // user canceled
+ }
+
+ while (!AndroidManager::checkCertificatePassword(m_keystorePath.toString(), m_keystorePasswd, m_certificateAlias, m_certificatePasswd)) {
+ if (!certificatePassword())
+ return false; // user canceled
+ }
+
+
+ if ((bc->qmakeBuildConfiguration() & QtSupport::BaseQtVersion::DebugBuild))
+ emit addOutput(tr("Warning: Signing a debug package."), BuildStep::ErrorMessageOutput);
+ }
+
+ QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(target()->kit());
+ if (!version)
+ return false;
+
+ ProjectExplorer::Project *project = target()->project();
+ JavaParser *parser = new JavaParser;
+ parser->setProjectFileList(project->files(ProjectExplorer::Project::AllFiles));
+ setOutputParser(parser);
+
+ QString command = version->qmakeProperty("QT_HOST_BINS");
+ if (!command.endsWith(QLatin1Char('/')))
+ command += QLatin1Char('/');
+ command += QLatin1String("androiddeployqt");
+ if (Utils::HostOsInfo::isWindowsHost())
+ command += QLatin1String(".exe");
+
+ QString deploymentMethod;
+ if (m_deployAction == MinistroDeployment)
+ deploymentMethod = QLatin1String("ministro");
+ else if (m_deployAction == DebugDeployment)
+ deploymentMethod = QLatin1String("debug");
+ else if (m_deployAction == BundleLibrariesDeployment)
+ deploymentMethod = QLatin1String("bundled");
+
+ QString outputDir = bc->buildDirectory().appendPath(QLatin1String("android")).toString();
+
+ QStringList arguments;
+ arguments << QLatin1String("--input")
+ << m_inputFile
+ << QLatin1String("--output")
+ << outputDir
+ << QLatin1String("--deployment")
+ << deploymentMethod
+ << QLatin1String("--install")
+ << QLatin1String("--ant")
+ << AndroidConfigurations::instance().antToolPath().toString()
+ << QLatin1String("--android-platform")
+ << m_buildTargetSdk
+ << QLatin1String("--jdk")
+ << AndroidConfigurations::instance().openJDKPath().toString();
+
+ if (m_verbose)
+ arguments << QLatin1String("--verbose");
+ if (m_avdName.isEmpty())
+ arguments << QLatin1String("--device")
+ << info.serialNumber;
+
+ if (m_signPackage) {
+ arguments << QLatin1String("--sign")
+ << m_keystorePath.toString()
+ << m_certificateAlias
+ << QLatin1String("--storepass")
+ << m_keystorePasswd;
+ if (!m_certificatePasswd.isEmpty())
+ arguments << QLatin1String("--keypass")
+ << m_certificatePasswd;
+ }
+
+ ProjectExplorer::ProcessParameters *pp = processParameters();
+ pp->setMacroExpander(bc->macroExpander());
+ pp->setWorkingDirectory(bc->buildDirectory().toString());
+ Utils::Environment env = bc->environment();
+ // Force output to english for the parsers. Do this here and not in the toolchain's
+ // addToEnvironment() to not screw up the users run environment.
+ env.set(QLatin1String("LC_ALL"), QLatin1String("C"));
+ pp->setEnvironment(env);
+ pp->setCommand(command);
+ pp->setArguments(Utils::QtcProcess::joinArgs(arguments));
+ pp->resolveAll();
+
+ m_openPackageLocationForRun = m_openPackageLocation;
+ m_apkPath = AndroidManager::apkPath(target(), m_signPackage ? AndroidManager::ReleaseBuildSigned
+ : AndroidManager::DebugBuild).toString();
+ m_buildDirectory = bc->buildDirectory().toString();
+
+ bool result = AbstractProcessStep::init();
+ if (!result)
+ return false;
+
+ AndroidConfigurations::instance().startAVDAsync(m_avdName);
+ return true;
+}
+
+void AndroidDeployQtStep::run(QFutureInterface<bool> &fi)
+{
+ if (!m_avdName.isEmpty()) {
+ QString serialNumber = AndroidConfigurations::instance().waitForAvd(m_deviceAPILevel, m_targetArch);
+ if (serialNumber.isEmpty()) {
+ fi.reportResult(false);
+ return;
+ }
+ m_serialNumber = serialNumber;
+ QString args = processParameters()->arguments();
+ Utils::QtcProcess::addArg(&args, QLatin1String("--device"));
+ Utils::QtcProcess::addArg(&args, serialNumber);
+ processParameters()->setArguments(args);
+ }
+
+ AbstractProcessStep::run(fi);
+
+ emit addOutput(tr("Pulling files necessary for debugging."), MessageOutput);
+ runCommand(AndroidConfigurations::instance().adbToolPath().toString(),
+ AndroidDeviceInfo::adbSelector(m_serialNumber)
+ << QLatin1String("pull") << QLatin1String("/system/bin/app_process")
+ << QString::fromLatin1("%1/app_process").arg(m_buildDirectory));
+ runCommand(AndroidConfigurations::instance().adbToolPath().toString(),
+ AndroidDeviceInfo::adbSelector(m_serialNumber) << QLatin1String("pull")
+ << QLatin1String("/system/lib/libc.so")
+ << QString::fromLatin1("%1/libc.so").arg(m_buildDirectory));
+}
+
+void AndroidDeployQtStep::runCommand(const QString &program, const QStringList &arguments)
+{
+ QProcess buildProc;
+ emit addOutput(tr("Package deploy: Running command '%1 %2'.").arg(program).arg(arguments.join(QLatin1String(" "))), BuildStep::MessageOutput);
+ buildProc.start(program, arguments);
+ if (!buildProc.waitForStarted()) {
+ emit addOutput(tr("Packaging error: Could not start command '%1 %2'. Reason: %3")
+ .arg(program).arg(arguments.join(QLatin1String(" "))).arg(buildProc.errorString()), BuildStep::ErrorMessageOutput);
+ return;
+ }
+ if (!buildProc.waitForFinished(2 * 60 * 1000)
+ || buildProc.error() != QProcess::UnknownError
+ || buildProc.exitCode() != 0) {
+ QString mainMessage = tr("Packaging Error: Command '%1 %2' failed.")
+ .arg(program).arg(arguments.join(QLatin1String(" ")));
+ if (buildProc.error() != QProcess::UnknownError)
+ mainMessage += tr(" Reason: %1").arg(buildProc.errorString());
+ else
+ mainMessage += tr("Exit code: %1").arg(buildProc.exitCode());
+ emit addOutput(mainMessage, BuildStep::ErrorMessageOutput);
+ }
+}
+
+void AndroidDeployQtStep::updateInputFile()
+{
+ Qt4ProjectManager::Qt4Project *pro = static_cast<Qt4ProjectManager::Qt4Project *>(project());
+ QList<Qt4ProjectManager::Qt4ProFileNode *> nodes = pro->applicationProFiles();
+
+ QStringList inputFiles;
+ foreach (Qt4ProjectManager::Qt4ProFileNode *node, nodes)
+ inputFiles << node->singleVariableValue(Qt4ProjectManager::AndroidDeploySettingsFile);
+
+ if (!inputFiles.contains(m_inputFile))
+ m_inputFile.clear();
+
+ if (m_inputFile.isEmpty()) {
+ // not yet selected one or no longer exists
+ if (!inputFiles.isEmpty())
+ m_inputFile = inputFiles.first();
+ }
+
+ emit inputFileChanged();
+}
+
+void AndroidDeployQtStep::showInGraphicalShell()
+{
+ Core::FileUtils::showInGraphicalShell(Core::ICore::instance()->mainWindow(), m_apkPath);
+}
+
+ProjectExplorer::BuildStepConfigWidget *AndroidDeployQtStep::createConfigWidget()
+{
+ return new AndroidDeployQtWidget(this);
+}
+
+void AndroidDeployQtStep::processFinished(int exitCode, QProcess::ExitStatus status)
+{
+ AbstractProcessStep::processFinished(exitCode, status);
+ if (m_openPackageLocationForRun)
+ QMetaObject::invokeMethod(this, "showInGraphicalShell", Qt::QueuedConnection);
+}
+
+bool AndroidDeployQtStep::fromMap(const QVariantMap &map)
+{
+ m_deployAction = AndroidDeployQtAction(map.value(QLatin1String(DeployActionKey),
+ BundleLibrariesDeployment).toInt());
+ m_keystorePath = Utils::FileName::fromString(map.value(KeystoreLocationKey).toString());
+ m_signPackage = map.value(SignPackageKey).toBool();
+ m_buildTargetSdk = map.value(BuildTargetSdkKey).toString();
+ m_verbose = map.value(VerboseOutputKey).toBool();
+ m_inputFile = map.value(InputFile).toString();
+ return ProjectExplorer::BuildStep::fromMap(map);
+}
+
+QVariantMap AndroidDeployQtStep::toMap() const
+{
+ QVariantMap map = ProjectExplorer::BuildStep::toMap();
+ map.insert(QLatin1String(DeployActionKey), m_deployAction);
+ map.insert(KeystoreLocationKey, m_keystorePath.toString());
+ map.insert(SignPackageKey, m_signPackage);
+ map.insert(BuildTargetSdkKey, m_buildTargetSdk);
+ map.insert(VerboseOutputKey, m_verbose);
+ map.insert(InputFile, m_inputFile);
+ return map;
+}
+
+void AndroidDeployQtStep::setBuildTargetSdk(const QString &sdk)
+{
+ m_buildTargetSdk = sdk;
+}
+
+QString AndroidDeployQtStep::buildTargetSdk() const
+{
+ return m_buildTargetSdk;
+}
+
+Utils::FileName AndroidDeployQtStep::keystorePath()
+{
+ return m_keystorePath;
+}
+
+AndroidDeployQtStep::AndroidDeployQtAction AndroidDeployQtStep::deployAction() const
+{
+ return m_deployAction;
+}
+
+void AndroidDeployQtStep::setDeployAction(AndroidDeployQtStep::AndroidDeployQtAction deploy)
+{
+ m_deployAction = deploy;
+}
+
+void AndroidDeployQtStep::setKeystorePath(const Utils::FileName &path)
+{
+ m_keystorePath = path;
+ m_certificatePasswd.clear();
+ m_keystorePasswd.clear();
+}
+
+void AndroidDeployQtStep::setKeystorePassword(const QString &pwd)
+{
+ m_keystorePasswd = pwd;
+}
+
+void AndroidDeployQtStep::setCertificateAlias(const QString &alias)
+{
+ m_certificateAlias = alias;
+}
+
+void AndroidDeployQtStep::setCertificatePassword(const QString &pwd)
+{
+ m_certificatePasswd = pwd;
+}
+
+bool AndroidDeployQtStep::signPackage() const
+{
+ return m_signPackage;
+}
+
+void AndroidDeployQtStep::setSignPackage(bool b)
+{
+ m_signPackage = b;
+}
+
+QString AndroidDeployQtStep::deviceSerialNumber()
+{
+ return m_serialNumber;
+}
+
+bool AndroidDeployQtStep::openPackageLocation() const
+{
+ return m_openPackageLocation;
+}
+
+void AndroidDeployQtStep::setOpenPackageLocation(bool open)
+{
+ m_openPackageLocation = open;
+}
+
+void AndroidDeployQtStep::setVerboseOutput(bool verbose)
+{
+ m_verbose = verbose;
+}
+
+QString AndroidDeployQtStep::inputFile() const
+{
+ return m_inputFile;
+}
+
+void AndroidDeployQtStep::setInputFile(const QString &file)
+{
+ m_inputFile = file;
+}
+
+bool AndroidDeployQtStep::verboseOutput() const
+{
+ return m_verbose;
+}
+
+// Note this functions is duplicated between AndroidDeployStep and AndroidDeployQtStep
+// since it does modify the stored password in AndroidDeployQtStep it's not easily
+// extractable. The situation will clean itself up once AndroidDeployStep is no longer
+// necessary
+QAbstractItemModel *AndroidDeployQtStep::keystoreCertificates()
+{
+ QString rawCerts;
+ QProcess keytoolProc;
+ while (!rawCerts.length() || !m_keystorePasswd.length()) {
+ QStringList params;
+ params << QLatin1String("-list") << QLatin1String("-v") << QLatin1String("-keystore") << m_keystorePath.toUserOutput() << QLatin1String("-storepass");
+ if (!m_keystorePasswd.length())
+ keystorePassword();
+ if (!m_keystorePasswd.length())
+ return 0;
+ params << m_keystorePasswd;
+ Utils::Environment env = Utils::Environment::systemEnvironment();
+ env.set(QLatin1String("LANG"), QLatin1String("C"));
+ keytoolProc.setProcessEnvironment(env.toProcessEnvironment());
+ keytoolProc.start(AndroidConfigurations::instance().keytoolPath().toString(), params);
+ if (!keytoolProc.waitForStarted() || !keytoolProc.waitForFinished()) {
+ QMessageBox::critical(0, tr("Error"),
+ tr("Failed to run keytool"));
+ return 0;
+ }
+
+ if (keytoolProc.exitCode()) {
+ QMessageBox::critical(0, tr("Error"),
+ tr("Invalid password"));
+ m_keystorePasswd.clear();
+ }
+ rawCerts = QString::fromLatin1(keytoolProc.readAllStandardOutput());
+ }
+ return new CertificatesModel(rawCerts, this);
+}
+
+bool AndroidDeployQtStep::keystorePassword()
+{
+ m_keystorePasswd.clear();
+ bool ok;
+ QString text = QInputDialog::getText(0, tr("Keystore"),
+ tr("Keystore password:"), QLineEdit::Password,
+ QString(), &ok);
+ if (ok && !text.isEmpty()) {
+ m_keystorePasswd = text;
+ return true;
+ }
+ return false;
+}
+
+bool AndroidDeployQtStep::certificatePassword()
+{
+ m_certificatePasswd.clear();
+ bool ok;
+ QString text = QInputDialog::getText(0, tr("Certificate"),
+ tr("Certificate password (%1):").arg(m_certificateAlias), QLineEdit::Password,
+ QString(), &ok);
+ if (ok && !text.isEmpty()) {
+ m_certificatePasswd = text;
+ return true;
+ }
+ return false;
+}
diff --git a/src/plugins/android/androiddeployqtstep.h b/src/plugins/android/androiddeployqtstep.h
new file mode 100644
index 0000000000..d51a46e60e
--- /dev/null
+++ b/src/plugins/android/androiddeployqtstep.h
@@ -0,0 +1,160 @@
+/**************************************************************************
+**
+** Copyright (c) 2013 BogDan Vatra <bog_dan_ro@yahoo.com>
+** 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 ANDROIDDEPLOYQTSTEP_H
+#define ANDROIDDEPLOYQTSTEP_H
+
+#include "androidconfigurations.h"
+
+#include <projectexplorer/abstractprocessstep.h>
+#include <qtsupport/baseqtversion.h>
+
+QT_BEGIN_NAMESPACE
+class QAbstractItemModel;
+QT_END_NAMESPACE
+
+namespace Android {
+namespace Internal {
+
+class AndroidDeployQtStepFactory : public ProjectExplorer::IBuildStepFactory
+{
+ Q_OBJECT
+public:
+ explicit AndroidDeployQtStepFactory(QObject *parent = 0);
+
+ QList<Core::Id> availableCreationIds(ProjectExplorer::BuildStepList *parent) const;
+ QString displayNameForId(const Core::Id id) const;
+
+ bool canCreate(ProjectExplorer::BuildStepList *parent,
+ const Core::Id id) const;
+ ProjectExplorer::BuildStep *create(ProjectExplorer::BuildStepList *parent, const Core::Id id);
+
+ bool canRestore(ProjectExplorer::BuildStepList *parent, const QVariantMap &map) const;
+ ProjectExplorer::BuildStep *restore(ProjectExplorer::BuildStepList *parent, const QVariantMap &map);
+
+ bool canClone(ProjectExplorer::BuildStepList *parent,
+ ProjectExplorer::BuildStep *product) const;
+ ProjectExplorer::BuildStep *clone(ProjectExplorer::BuildStepList *parent,
+ ProjectExplorer::BuildStep *product);
+};
+
+class AndroidDeployQtStep : public ProjectExplorer::AbstractProcessStep
+{
+ Q_OBJECT
+ friend class AndroidDeployQtStepFactory;
+public:
+ AndroidDeployQtStep(ProjectExplorer::BuildStepList *bc);
+
+ enum AndroidDeployQtAction
+ {
+ MinistroDeployment, // use ministro
+ DebugDeployment,
+ BundleLibrariesDeployment
+ };
+
+ bool fromMap(const QVariantMap &map);
+ QVariantMap toMap() const;
+
+ AndroidDeployQtStep::AndroidDeployQtAction deployAction() const;
+ QString deviceSerialNumber();
+
+ void setBuildTargetSdk(const QString &sdk);
+ QString buildTargetSdk() const;
+
+ // signing
+ Utils::FileName keystorePath();
+ void setKeystorePath(const Utils::FileName &path);
+ void setKeystorePassword(const QString &pwd);
+ void setCertificateAlias(const QString &alias);
+ void setCertificatePassword(const QString &pwd);
+
+ QAbstractItemModel *keystoreCertificates();
+ bool signPackage() const;
+ void setSignPackage(bool b);
+
+ bool openPackageLocation() const;
+ void setOpenPackageLocation(bool open);
+ bool verboseOutput() const;
+ void setVerboseOutput(bool verbose);
+
+ QString inputFile() const;
+ void setInputFile(const QString &file);
+
+signals:
+ // also on purpose emitted if the possible values of this changed
+ void inputFileChanged();
+
+public slots:
+ void setDeployAction(AndroidDeployQtAction deploy); // slot?
+
+private slots:
+ void showInGraphicalShell();
+
+ void updateInputFile();
+private:
+ AndroidDeployQtStep(ProjectExplorer::BuildStepList *bc,
+ AndroidDeployQtStep *other);
+ void ctor();
+ bool keystorePassword();
+ bool certificatePassword();
+ void runCommand(const QString &program, const QStringList &arguments);
+
+ bool init();
+ void run(QFutureInterface<bool> &fi);
+ ProjectExplorer::BuildStepConfigWidget *createConfigWidget();
+ bool immutable() const { return true; }
+ void processFinished(int exitCode, QProcess::ExitStatus status);
+
+ QString m_buildTargetSdk;
+ QString m_serialNumber;
+ AndroidDeployQtAction m_deployAction;
+ bool m_signPackage;
+ bool m_verbose;
+ bool m_openPackageLocation;
+ bool m_openPackageLocationForRun;
+ QString m_buildDirectory;
+
+ Utils::FileName m_keystorePath;
+ QString m_keystorePasswd;
+ QString m_certificateAlias;
+ QString m_certificatePasswd;
+ QString m_avdName;
+ QString m_apkPath;
+ QString m_targetArch;
+ QString m_inputFile;
+ int m_deviceAPILevel;
+
+ static const Core::Id Id;
+};
+
+}
+}
+
+#endif // ANDROIDDEPLOYQTSTEP_H
diff --git a/src/plugins/android/androiddeployqtwidget.cpp b/src/plugins/android/androiddeployqtwidget.cpp
new file mode 100644
index 0000000000..d610d51b46
--- /dev/null
+++ b/src/plugins/android/androiddeployqtwidget.cpp
@@ -0,0 +1,314 @@
+/**************************************************************************
+**
+** Copyright (c) 2013 BogDan Vatra <bog_dan_ro@yahoo.com>
+** 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 "androiddeployqtwidget.h"
+#include "ui_androiddeployqtwidget.h"
+
+#include "androidcreatekeystorecertificate.h"
+#include "androiddeployqtstep.h"
+#include "androidmanager.h"
+
+#include <projectexplorer/target.h>
+#include <qt4projectmanager/qt4buildconfiguration.h>
+#include <qt4projectmanager/qt4project.h>
+#include <qt4projectmanager/qt4nodes.h>
+
+#include <QFileDialog>
+
+#include <algorithm>
+
+
+using namespace Android;
+using namespace Internal;
+
+AndroidDeployQtWidget::AndroidDeployQtWidget(AndroidDeployQtStep *step)
+ : ProjectExplorer::BuildStepConfigWidget(),
+ m_ui(new Ui::AndroidDeployQtWidget),
+ m_step(step),
+ m_currentBuildConfiguration(0),
+ m_ignoreChange(false)
+{
+ m_ui->setupUi(this);
+
+ // Target sdk combobox
+ int minApiLevel = 9;
+ QStringList targets = AndroidConfigurations::instance().sdkTargets(minApiLevel);
+ m_ui->targetSDKComboBox->addItems(targets);
+ m_ui->targetSDKComboBox->setCurrentIndex(targets.indexOf(step->buildTargetSdk()));
+
+ // deployment option
+ switch (m_step->deployAction()) {
+ case AndroidDeployQtStep::MinistroDeployment:
+ m_ui->ministroOption->setChecked(true);
+ break;
+ case AndroidDeployQtStep::DebugDeployment:
+ m_ui->temporaryQtOption->setChecked(true);
+ break;
+ case AndroidDeployQtStep::BundleLibrariesDeployment:
+ m_ui->bundleQtOption->setChecked(true);
+ break;
+ default:
+ // can't happen
+ break;
+ }
+
+ // signing
+ m_ui->KeystoreLocationLineEdit->setText(m_step->keystorePath().toUserOutput());
+ m_ui->signingDebugWarningIcon->hide();
+ m_ui->signingDebugWarningLabel->hide();
+
+ m_ui->verboseOutputCheckBox->setChecked(m_step->verboseOutput());
+ m_ui->openPackageLocationCheckBox->setChecked(m_step->openPackageLocation());
+
+ bool oldFiles = AndroidManager::checkForQt51Files(m_step->project()->projectDirectory());
+ m_ui->oldFilesWarningIcon->setVisible(oldFiles);
+ m_ui->oldFilesWarningLabel->setVisible(oldFiles);
+
+ // target sdk
+ connect(m_ui->targetSDKComboBox, SIGNAL(activated(QString)), SLOT(setTargetSdk(QString)));
+
+ // deployment options
+ connect(m_ui->ministroOption, SIGNAL(clicked()), SLOT(setMinistro()));
+ connect(m_ui->temporaryQtOption, SIGNAL(clicked()), SLOT(setDeployLocalQtLibs()));
+ connect(m_ui->bundleQtOption, SIGNAL(clicked()), SLOT(setBundleQtLibs()));
+
+ connect(m_ui->installMinistroButton, SIGNAL(clicked()), SLOT(installMinistro()));
+ connect(m_ui->cleanLibsPushButton, SIGNAL(clicked()), SLOT(cleanLibsOnDevice()));
+ connect(m_ui->resetDefaultDevices, SIGNAL(clicked()), SLOT(resetDefaultDevices()));
+ connect(m_ui->openPackageLocationCheckBox, SIGNAL(toggled(bool)),
+ this, SLOT(openPackageLocationCheckBoxToggled(bool)));
+ connect(m_ui->verboseOutputCheckBox, SIGNAL(toggled(bool)),
+ this, SLOT(verboseOutputCheckBoxToggled(bool)));
+
+ //signing
+ connect(m_ui->signPackageCheckBox, SIGNAL(toggled(bool)),
+ this, SLOT(signPackageCheckBoxToggled(bool)));
+ connect(m_ui->KeystoreCreatePushButton, SIGNAL(clicked()),
+ this, SLOT(createKeyStore()));
+ connect(m_ui->KeystoreLocationPushButton, SIGNAL(clicked()),
+ this, SLOT(browseKeyStore()));
+ connect(m_ui->certificatesAliasComboBox, SIGNAL(activated(QString)),
+ this, SLOT(certificatesAliasComboBoxActivated(QString)));
+ connect(m_ui->certificatesAliasComboBox, SIGNAL(currentIndexChanged(QString)),
+ this, SLOT(certificatesAliasComboBoxCurrentIndexChanged(QString)));
+
+ activeBuildConfigurationChanged();
+ connect(m_step->target(), SIGNAL(activeBuildConfigurationChanged(ProjectExplorer::BuildConfiguration*)),
+ this, SLOT(activeBuildConfigurationChanged()));
+
+ connect(m_ui->inputFileComboBox, SIGNAL(currentIndexChanged(int)),
+ this, SLOT(inputFileComboBoxIndexChanged()));
+
+ updateInputFileUi();
+ connect(m_step, SIGNAL(inputFileChanged()),
+ this, SLOT(updateInputFileUi()));
+}
+
+AndroidDeployQtWidget::~AndroidDeployQtWidget()
+{
+ delete m_ui;
+}
+
+void AndroidDeployQtWidget::updateInputFileUi()
+{
+ Qt4ProjectManager::Qt4Project *project
+ = static_cast<Qt4ProjectManager::Qt4Project *>(m_step->project());
+ QList<Qt4ProjectManager::Qt4ProFileNode *> nodes = project->applicationProFiles();
+ int size = nodes.size();
+ if (size == 0 || size == 1) {
+ // there's nothing to select, e.g. before parsing
+ m_ui->inputFileLabel->setVisible(false);
+ m_ui->inputFileComboBox->setVisible(false);
+ } else {
+ m_ignoreChange = true;
+ m_ui->inputFileLabel->setVisible(true);
+ m_ui->inputFileComboBox->setVisible(true);
+
+ m_ui->inputFileComboBox->clear();
+ foreach (Qt4ProjectManager::Qt4ProFileNode *node, nodes) {
+ QString file = node->singleVariableValue(Qt4ProjectManager::AndroidDeploySettingsFile);
+ m_ui->inputFileComboBox->addItem(node->displayName(), file);
+ }
+
+ int index = m_ui->inputFileComboBox->findData(m_step->inputFile());
+ m_ui->inputFileComboBox->setCurrentIndex(index);
+ m_ignoreChange = false;
+ }
+}
+
+void AndroidDeployQtWidget::inputFileComboBoxIndexChanged()
+{
+ if (m_ignoreChange)
+ return;
+ QString text = m_ui->inputFileComboBox->itemData(m_ui->inputFileComboBox->currentIndex()).toString();
+ m_step->setInputFile(text);
+}
+
+QString AndroidDeployQtWidget::displayName() const
+{
+ return tr("<b>Deploy configurations</b>");
+}
+
+QString AndroidDeployQtWidget::summaryText() const
+{
+ return displayName();
+}
+
+void AndroidDeployQtWidget::setTargetSdk(const QString &sdk)
+{
+ m_step->setBuildTargetSdk(sdk);
+}
+
+void AndroidDeployQtWidget::setMinistro()
+{
+ m_step->setDeployAction(AndroidDeployQtStep::MinistroDeployment);
+}
+
+void AndroidDeployQtWidget::setDeployLocalQtLibs()
+{
+ m_step->setDeployAction(AndroidDeployQtStep::DebugDeployment);
+}
+
+void AndroidDeployQtWidget::setBundleQtLibs()
+{
+ m_step->setDeployAction(AndroidDeployQtStep::BundleLibrariesDeployment);
+}
+
+void AndroidDeployQtWidget::installMinistro()
+{
+ QString packagePath =
+ QFileDialog::getOpenFileName(this, tr("Qt Android Smart Installer"),
+ QDir::homePath(), tr("Android package (*.apk)"));
+ if (!packagePath.isEmpty())
+ AndroidManager::installQASIPackage(m_step->target(), packagePath);
+}
+
+void AndroidDeployQtWidget::cleanLibsOnDevice()
+{
+ AndroidManager::cleanLibsOnDevice(m_step->target());
+}
+
+void AndroidDeployQtWidget::resetDefaultDevices()
+{
+ AndroidConfigurations::instance().clearDefaultDevices(m_step->project());
+}
+
+void AndroidDeployQtWidget::signPackageCheckBoxToggled(bool checked)
+{
+ m_ui->certificatesAliasComboBox->setEnabled(checked);
+ m_step->setSignPackage(checked);
+ updateSigningWarning();
+ if (!checked)
+ return;
+ if (!m_step->keystorePath().isEmpty())
+ setCertificates();
+}
+
+void AndroidDeployQtWidget::createKeyStore()
+{
+ AndroidCreateKeystoreCertificate d;
+ if (d.exec() != QDialog::Accepted)
+ return;
+ m_ui->KeystoreLocationLineEdit->setText(d.keystoreFilePath().toUserOutput());
+ m_step->setKeystorePath(d.keystoreFilePath());
+ m_step->setKeystorePassword(d.keystorePassword());
+ m_step->setCertificateAlias(d.certificateAlias());
+ m_step->setCertificatePassword(d.certificatePassword());
+ setCertificates();
+}
+
+void AndroidDeployQtWidget::setCertificates()
+{
+ QAbstractItemModel *certificates = m_step->keystoreCertificates();
+ m_ui->signPackageCheckBox->setChecked(certificates);
+ m_ui->certificatesAliasComboBox->setModel(certificates);
+}
+
+void AndroidDeployQtWidget::browseKeyStore()
+{
+ Utils::FileName keystorePath = m_step->keystorePath();
+ if (keystorePath.isEmpty())
+ keystorePath = Utils::FileName::fromString(QDir::homePath());
+ Utils::FileName file = Utils::FileName::fromString(QFileDialog::getOpenFileName(this, tr("Select keystore file"), keystorePath.toString(), tr("Keystore files (*.keystore *.jks)")));
+ if (file.isEmpty())
+ return;
+ m_ui->KeystoreLocationLineEdit->setText(file.toUserOutput());
+ m_step->setKeystorePath(file);
+ m_ui->signPackageCheckBox->setChecked(false);
+}
+
+void AndroidDeployQtWidget::certificatesAliasComboBoxActivated(const QString &alias)
+{
+ if (alias.length())
+ m_step->setCertificateAlias(alias);
+}
+
+void AndroidDeployQtWidget::certificatesAliasComboBoxCurrentIndexChanged(const QString &alias)
+{
+ if (alias.length())
+ m_step->setCertificateAlias(alias);
+}
+
+void AndroidDeployQtWidget::openPackageLocationCheckBoxToggled(bool checked)
+{
+ m_step->setOpenPackageLocation(checked);
+}
+
+void AndroidDeployQtWidget::verboseOutputCheckBoxToggled(bool checked)
+{
+ m_step->setVerboseOutput(checked);
+}
+
+void AndroidDeployQtWidget::activeBuildConfigurationChanged()
+{
+ if (m_currentBuildConfiguration)
+ disconnect(m_currentBuildConfiguration, SIGNAL(qmakeBuildConfigurationChanged()),
+ this, SLOT(updateSigningWarning()));
+ updateSigningWarning();
+ Qt4ProjectManager::Qt4BuildConfiguration *bc
+ = qobject_cast<Qt4ProjectManager::Qt4BuildConfiguration *>(m_step->target()->activeBuildConfiguration());
+ m_currentBuildConfiguration = bc;
+ if (bc)
+ connect(bc, SIGNAL(qmakeBuildConfigurationChanged()), this, SLOT(updateSigningWarning()));
+ m_currentBuildConfiguration = bc;
+}
+
+void AndroidDeployQtWidget::updateSigningWarning()
+{
+ Qt4ProjectManager::Qt4BuildConfiguration *bc = qobject_cast<Qt4ProjectManager::Qt4BuildConfiguration *>(m_step->target()->activeBuildConfiguration());
+ bool debug = bc && (bc->qmakeBuildConfiguration() & QtSupport::BaseQtVersion::DebugBuild);
+ if (m_step->signPackage() && debug) {
+ m_ui->signingDebugWarningIcon->setVisible(true);
+ m_ui->signingDebugWarningLabel->setVisible(true);
+ } else {
+ m_ui->signingDebugWarningIcon->setVisible(false);
+ m_ui->signingDebugWarningLabel->setVisible(false);
+ }
+}
diff --git a/src/plugins/android/androiddeployqtwidget.h b/src/plugins/android/androiddeployqtwidget.h
new file mode 100644
index 0000000000..e8b652ffb5
--- /dev/null
+++ b/src/plugins/android/androiddeployqtwidget.h
@@ -0,0 +1,86 @@
+/**************************************************************************
+**
+** Copyright (c) 2013 BogDan Vatra <bog_dan_ro@yahoo.com>
+** 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 ANDROIDDEPLOYQTWIDGET_H
+#define ANDROIDDEPLOYQTWIDGET_H
+
+#include <projectexplorer/buildstep.h>
+
+#include <QWidget>
+
+QT_BEGIN_NAMESPACE
+namespace Ui { class AndroidDeployQtWidget; }
+QT_END_NAMESPACE
+
+namespace Qt4ProjectManager { class Qt4BuildConfiguration; }
+
+namespace Android {
+namespace Internal {
+class AndroidDeployQtStep;
+class AndroidDeployQtWidget : public ProjectExplorer::BuildStepConfigWidget
+{
+ Q_OBJECT
+
+public:
+ AndroidDeployQtWidget(AndroidDeployQtStep *step);
+ ~AndroidDeployQtWidget();
+
+private slots:
+ void setTargetSdk(const QString &sdk);
+ void setMinistro();
+ void setDeployLocalQtLibs();
+ void setBundleQtLibs();
+ void installMinistro();
+ void cleanLibsOnDevice();
+ void resetDefaultDevices();
+ void createKeyStore();
+ void certificatesAliasComboBoxCurrentIndexChanged(const QString &alias);
+ void certificatesAliasComboBoxActivated(const QString &alias);
+ void activeBuildConfigurationChanged();
+ void updateSigningWarning();
+ void openPackageLocationCheckBoxToggled(bool checked);
+ void verboseOutputCheckBoxToggled(bool checked);
+ void browseKeyStore();
+ void signPackageCheckBoxToggled(bool checked);
+ void updateInputFileUi();
+ void inputFileComboBoxIndexChanged();
+private:
+ virtual QString summaryText() const;
+ virtual QString displayName() const;
+ void setCertificates();
+
+ Ui::AndroidDeployQtWidget *m_ui;
+ AndroidDeployQtStep *m_step;
+ Qt4ProjectManager::Qt4BuildConfiguration *m_currentBuildConfiguration;
+ bool m_ignoreChange;
+};
+
+}
+}
+#endif // ANDROIDDEPLOYQTWIDGET_H
diff --git a/src/plugins/android/androiddeployqtwidget.ui b/src/plugins/android/androiddeployqtwidget.ui
new file mode 100644
index 0000000000..d1f1461909
--- /dev/null
+++ b/src/plugins/android/androiddeployqtwidget.ui
@@ -0,0 +1,295 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>AndroidDeployQtWidget</class>
+ <widget class="QWidget" name="AndroidDeployQtWidget">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>682</width>
+ <height>415</height>
+ </rect>
+ </property>
+ <property name="windowTitle">
+ <string>Form</string>
+ </property>
+ <layout class="QGridLayout" name="gridLayout_2">
+ <item row="2" column="0" colspan="2">
+ <widget class="QGroupBox" name="signPackage">
+ <property name="title">
+ <string>Sign package</string>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout_2">
+ <item>
+ <layout class="QHBoxLayout" name="horizontalLayout_2">
+ <item>
+ <widget class="QLabel" name="KeystoreLocationLabel">
+ <property name="text">
+ <string>Keystore:</string>
+ </property>
+ <property name="alignment">
+ <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLineEdit" name="KeystoreLocationLineEdit">
+ <property name="readOnly">
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="KeystoreCreatePushButton">
+ <property name="text">
+ <string>Create</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="KeystoreLocationPushButton">
+ <property name="text">
+ <string>Browse</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <layout class="QHBoxLayout" name="horizontalLayout_4">
+ <item>
+ <widget class="QCheckBox" name="signPackageCheckBox">
+ <property name="text">
+ <string>Sign package</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <layout class="QHBoxLayout" name="horizontalLayout_3">
+ <item>
+ <widget class="QLabel" name="signingDebugWarningIcon">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Fixed" vsizetype="Preferred">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text">
+ <string/>
+ </property>
+ <property name="pixmap">
+ <pixmap resource="../projectexplorer/projectexplorer.qrc">:/projectexplorer/images/compile_warning.png</pixmap>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="signingDebugWarningLabel">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Fixed" vsizetype="Preferred">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text">
+ <string>Signing a debug package</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="KeystoreLocationLabel_2">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text">
+ <string>Certificate alias:</string>
+ </property>
+ <property name="alignment">
+ <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QComboBox" name="certificatesAliasComboBox">
+ <property name="enabled">
+ <bool>false</bool>
+ </property>
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="minimumSize">
+ <size>
+ <width>300</width>
+ <height>0</height>
+ </size>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item row="3" column="0">
+ <widget class="QGroupBox" name="qtDeployment">
+ <property name="title">
+ <string>Qt Deployment</string>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout">
+ <item>
+ <widget class="QRadioButton" name="ministroOption">
+ <property name="toolTip">
+ <string>Use the external Ministro application to download and maintain Qt libraries.</string>
+ </property>
+ <property name="text">
+ <string>Use Ministro service to install Qt</string>
+ </property>
+ <property name="checked">
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QRadioButton" name="temporaryQtOption">
+ <property name="toolTip">
+ <string>Push local Qt libraries to device. You must have Qt libraries compiled for that platform.
+The APK will not be usable on any other device.</string>
+ </property>
+ <property name="text">
+ <string>Deploy local Qt libraries to temporary directory</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QRadioButton" name="bundleQtOption">
+ <property name="toolTip">
+ <string>Creates a standalone APK.</string>
+ </property>
+ <property name="text">
+ <string>Bundle Qt libraries in APK</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item row="3" column="1">
+ <widget class="QGroupBox" name="advancedActions">
+ <property name="title">
+ <string>Advanced Actions</string>
+ </property>
+ <layout class="QGridLayout" name="gridLayout">
+ <item row="3" column="0">
+ <widget class="QPushButton" name="cleanLibsPushButton">
+ <property name="text">
+ <string>Clean Temporary Libraries Directory on Device</string>
+ </property>
+ </widget>
+ </item>
+ <item row="4" column="0">
+ <widget class="QPushButton" name="installMinistroButton">
+ <property name="text">
+ <string>Install Ministro from APK</string>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="0">
+ <widget class="QPushButton" name="resetDefaultDevices">
+ <property name="text">
+ <string>Reset Default Devices</string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="0">
+ <widget class="QCheckBox" name="openPackageLocationCheckBox">
+ <property name="text">
+ <string>Open package location after is complete</string>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="0">
+ <widget class="QCheckBox" name="verboseOutputCheckBox">
+ <property name="text">
+ <string>Verbose Output</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item row="1" column="0" colspan="2">
+ <widget class="QGroupBox" name="application">
+ <property name="title">
+ <string>Application</string>
+ </property>
+ <layout class="QGridLayout" name="gridLayout_3">
+ <item row="1" column="1">
+ <widget class="QComboBox" name="targetSDKComboBox"/>
+ </item>
+ <item row="1" column="0">
+ <widget class="QLabel" name="targetSDKLabel">
+ <property name="text">
+ <string>Android target SDK:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="1">
+ <widget class="QComboBox" name="inputFileComboBox"/>
+ </item>
+ <item row="0" column="0">
+ <widget class="QLabel" name="inputFileLabel">
+ <property name="text">
+ <string>Android deploy Qt Input File:</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item row="0" column="0" colspan="2">
+ <layout class="QHBoxLayout" name="horizontalLayout">
+ <item>
+ <widget class="QLabel" name="oldFilesWarningIcon">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Fixed" vsizetype="Preferred">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text">
+ <string/>
+ </property>
+ <property name="pixmap">
+ <pixmap resource="../projectexplorer/projectexplorer.qrc">:/projectexplorer/images/compile_warning.png</pixmap>
+ </property>
+ <property name="alignment">
+ <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop</set>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="oldFilesWarningLabel">
+ <property name="text">
+ <string>Qt no longer uses the android folder in the project's source directory.</string>
+ </property>
+ <property name="wordWrap">
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ <resources>
+ <include location="../projectexplorer/projectexplorer.qrc"/>
+ </resources>
+ <connections/>
+</ui>
diff --git a/src/plugins/android/androiddeploystep.cpp b/src/plugins/android/androiddeploystep.cpp
index 04eeb91f02..2af881aff6 100644
--- a/src/plugins/android/androiddeploystep.cpp
+++ b/src/plugins/android/androiddeploystep.cpp
@@ -36,10 +36,13 @@
#include "androidrunconfiguration.h"
#include "androidmanager.h"
#include "androidtoolchain.h"
+#include "androiddevicedialog.h"
#include <coreplugin/messagemanager.h>
#include <projectexplorer/buildconfiguration.h>
+#include <projectexplorer/deployconfiguration.h>
#include <projectexplorer/projectexplorerconstants.h>
+#include <projectexplorer/buildsteplist.h>
#include <projectexplorer/target.h>
#include <qt4projectmanager/qt4buildconfiguration.h>
#include <qt4projectmanager/qt4project.h>
@@ -51,6 +54,7 @@
#define ASSERT_STATE(state) ASSERT_STATE_GENERIC(State, state, m_state)
+using namespace Core;
using namespace ProjectExplorer;
using namespace Qt4ProjectManager;
@@ -60,7 +64,7 @@ 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");
+const Id AndroidDeployStep::Id("Qt4ProjectManager.AndroidDeployStep");
AndroidDeployStep::AndroidDeployStep(ProjectExplorer::BuildStepList *parent)
: BuildStep(parent, Id)
@@ -96,17 +100,18 @@ void AndroidDeployStep::ctor()
bool AndroidDeployStep::init()
{
m_packageName = AndroidManager::packageName(target());
- const QString targetSDK = AndroidManager::targetSDK(target());
- const QString targetArch = AndroidManager::targetArch(target());
-
- writeOutput(tr("Please wait, searching for a suitable device for target:%1.").arg(targetSDK));
- m_deviceAPILevel = targetSDK.mid(targetSDK.indexOf(QLatin1Char('-')) + 1).toInt();
- m_deviceSerialNumber = AndroidConfigurations::instance().getDeployDeviceSerialNumber(&m_deviceAPILevel, targetArch);
- if (!m_deviceSerialNumber.length()) {
- m_deviceSerialNumber.clear();
- raiseError(tr("Cannot deploy: no devices or emulators found for your package."));
+ m_deviceAPILevel = AndroidManager::minimumSDK(target());
+ m_targetArch = AndroidManager::targetArch(target());
+
+ AndroidDeviceInfo info = AndroidConfigurations::instance().showDeviceDialog(project(), m_deviceAPILevel, m_targetArch);
+ if (info.serialNumber.isEmpty()) // aborted
return false;
- }
+
+ m_deviceAPILevel = info.sdk;
+ m_deviceSerialNumber = info.serialNumber;
+
+ if (info.type == AndroidDeviceInfo::Emulator)
+ m_avdName = m_deviceSerialNumber;
QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(target()->kit());
if (!version)
@@ -116,8 +121,16 @@ bool AndroidDeployStep::init()
if (!bc)
return false;
- m_qtVersionSourcePath = version->sourcePath().toString();
- m_qtVersionQMakeBuildConfig = bc->qmakeBuildConfiguration();
+ m_signPackage = false;
+ // find AndroidPackageCreationStep
+ foreach (BuildStep *step, target()->activeDeployConfiguration()->stepList()->steps()) {
+ if (AndroidPackageCreationStep *apcs = qobject_cast<AndroidPackageCreationStep *>(step)) {
+ m_signPackage = apcs->signPackage();
+ break;
+ }
+ }
+
+ m_qtVersionSourcePath = version->qmakeProperty("QT_INSTALL_PREFIX");
m_androidDirPath = AndroidManager::dirPath(target());
m_apkPathDebug = AndroidManager::apkPath(target(), AndroidManager::DebugBuild).toString();
m_apkPathRelease = AndroidManager::apkPath(target(), AndroidManager::ReleaseBuildSigned).toString();
@@ -180,40 +193,6 @@ QVariantMap AndroidDeployStep::toMap() const
return map;
}
-void AndroidDeployStep::cleanLibsOnDevice()
-{
- const QString targetSDK = AndroidManager::targetSDK(target());
- const QString targetArch = AndroidManager::targetArch(target());
-
- int deviceAPILevel = targetSDK.mid(targetSDK.indexOf(QLatin1Char('-')) + 1).toInt();
- QString deviceSerialNumber = AndroidConfigurations::instance().getDeployDeviceSerialNumber(&deviceAPILevel, targetArch);
- if (!deviceSerialNumber.length()) {
- Core::MessageManager::instance()->printToOutputPane(tr("Could not run adb. No device found."), Core::MessageManager::NoModeSwitch);
- return;
- }
- QProcess *process = new QProcess(this);
- QStringList arguments = AndroidDeviceInfo::adbSelector(deviceSerialNumber);
- arguments << QLatin1String("shell") << QLatin1String("rm") << QLatin1String("-r") << QLatin1String("/data/local/tmp/qt");
- connect(process, SIGNAL(finished(int)), this, SLOT(processFinished()));
- const QString adb = AndroidConfigurations::instance().adbToolPath().toString();
- Core::MessageManager::instance()->printToOutputPane(adb + QLatin1String(" ")
- + arguments.join(QLatin1String(" ")),
- Core::MessageManager::NoModeSwitch);
- process->start(adb, arguments);
- if (!process->waitForStarted(500))
- delete process;
-}
-
-void AndroidDeployStep::processFinished()
-{
- QProcess *process = qobject_cast<QProcess *>(sender());
- QTC_ASSERT(process, return);
- Core::MessageManager::instance()->printToOutputPane(QString::fromLocal8Bit(process->readAll()), Core::MessageManager::NoModeSwitch);
- Core::MessageManager::instance()->printToOutputPane(tr("adb finished with exit code %1.").arg(process->exitCode()),
- Core::MessageManager::NoModeSwitch);
- process->deleteLater();
-}
-
void AndroidDeployStep::kitUpdated(Kit *kit)
{
if (kit != target()->kit())
@@ -232,31 +211,6 @@ void AndroidDeployStep::kitUpdated(Kit *kit)
}
}
-void AndroidDeployStep::installQASIPackage(const QString &packagePath)
-{
- const QString targetArch = AndroidManager::targetArch(target());
- const QString targetSDK = AndroidManager::targetSDK(target());
- int deviceAPILevel = targetSDK.mid(targetSDK.indexOf(QLatin1Char('-')) + 1).toInt();
- QString deviceSerialNumber = AndroidConfigurations::instance().getDeployDeviceSerialNumber(&deviceAPILevel, targetArch);
- if (!deviceSerialNumber.length()) {
- Core::MessageManager::instance()->printToOutputPane(tr("Could not run adb. No device found."), Core::MessageManager::NoModeSwitch);
- return;
- }
-
- QProcess *process = new QProcess(this);
- QStringList arguments = AndroidDeviceInfo::adbSelector(deviceSerialNumber);
- arguments << QLatin1String("install") << QLatin1String("-r ") << packagePath;
-
- connect(process, SIGNAL(finished(int)), this, SLOT(processFinished()));
- const QString adb = AndroidConfigurations::instance().adbToolPath().toString();
- Core::MessageManager::instance()->printToOutputPane(adb + QLatin1String(" ")
- + arguments.join(QLatin1String(" ")),
- Core::MessageManager::NoModeSwitch);
- process->start(adb, arguments);
- if (!process->waitForFinished(500))
- delete process;
-}
-
bool AndroidDeployStep::bundleQtOptionAvailable()
{
return m_bundleQtAvailable;
@@ -279,8 +233,8 @@ bool AndroidDeployStep::runCommand(QProcess *buildProc,
.arg(program).arg(arguments.join(QLatin1String(" "))).arg(buildProc->errorString()), BuildStep::ErrorMessageOutput);
return false;
}
- buildProc->waitForFinished(-1);
- if (buildProc->error() != QProcess::UnknownError
+ if (!buildProc->waitForFinished(2 * 60 * 1000)
+ || buildProc->error() != QProcess::UnknownError
|| buildProc->exitCode() != 0) {
QString mainMessage = tr("Packaging Error: Command '%1 %2' failed.")
.arg(program).arg(arguments.join(QLatin1String(" ")));
@@ -317,11 +271,6 @@ QString AndroidDeployStep::deviceSerialNumber()
return m_deviceSerialNumber;
}
-int AndroidDeployStep::deviceAPILevel()
-{
- return m_deviceAPILevel;
-}
-
unsigned int AndroidDeployStep::remoteModificationTime(const QString &fullDestination, QHash<QString, unsigned int> *cache)
{
QString destination = QFileInfo(fullDestination).absolutePath();
@@ -439,6 +388,12 @@ void AndroidDeployStep::deployFiles(QProcess *process, const QList<DeployItem> &
bool AndroidDeployStep::deployPackage()
{
+ if (!m_avdName.isEmpty()) {
+ if (!AndroidConfigurations::instance().startAVDAsync(m_avdName))
+ return false;
+ m_deviceSerialNumber = AndroidConfigurations::instance().waitForAvd(m_deviceAPILevel, m_targetArch);
+ }
+
QProcess *const deployProc = new QProcess;
connect(deployProc, SIGNAL(readyReadStandardOutput()), this,
SLOT(handleBuildOutput()));
@@ -506,8 +461,7 @@ bool AndroidDeployStep::deployPackage()
AndroidDeviceInfo::adbSelector(m_deviceSerialNumber) << QLatin1String("uninstall") << m_packageName);
QString package = m_apkPathDebug;
- if (!(m_qtVersionQMakeBuildConfig & QtSupport::BaseQtVersion::DebugBuild)
- && QFile::exists(m_apkPathRelease))
+ if (m_signPackage && QFile::exists(m_apkPathRelease))
package = m_apkPathRelease;
if (!runCommand(deployProc, AndroidConfigurations::instance().adbToolPath().toString(),
@@ -535,7 +489,7 @@ bool AndroidDeployStep::deployPackage()
void AndroidDeployStep::raiseError(const QString &errorString)
{
emit addTask(Task(Task::Error, errorString, Utils::FileName::fromString(QString()), -1,
- ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM));
+ ProjectExplorer::Constants::TASK_CATEGORY_DEPLOYMENT));
}
void AndroidDeployStep::writeOutput(const QString &text, OutputFormat format)
diff --git a/src/plugins/android/androiddeploystep.h b/src/plugins/android/androiddeploystep.h
index 6725020a85..df7ebd7e2b 100644
--- a/src/plugins/android/androiddeploystep.h
+++ b/src/plugins/android/androiddeploystep.h
@@ -87,15 +87,12 @@ public:
virtual ~AndroidDeployStep();
QString deviceSerialNumber();
- int deviceAPILevel();
AndroidDeployAction deployAction();
bool fromMap(const QVariantMap &map);
QVariantMap toMap() const;
- void cleanLibsOnDevice();
- void installQASIPackage(const QString &packagePath);
bool bundleQtOptionAvailable();
public slots:
@@ -110,7 +107,6 @@ private slots:
bool deployPackage();
void handleBuildOutput();
void handleBuildError();
- void processFinished();
void kitUpdated(ProjectExplorer::Kit *kit);
private:
@@ -134,23 +130,24 @@ private:
void fetchRemoteModificationTimes(QList<DeployItem> *deployList);
void stripFiles(const QList<DeployItem> &deployList, ProjectExplorer::Abi::Architecture architecture, const QString &ndkToolchainVersion);
void deployFiles(QProcess *process, const QList<DeployItem> &deployList);
+ bool checkForQt51Files();
private:
QString m_deviceSerialNumber;
int m_deviceAPILevel;
+ QString m_targetArch;
- QString m_QASIPackagePath;
AndroidDeployAction m_deployAction;
// members to transfer data from init() to run
+ QString m_avdName;
QString m_packageName;
QString m_qtVersionSourcePath;
- QtSupport::BaseQtVersion::QmakeBuildConfigs m_qtVersionQMakeBuildConfig;
+ bool m_signPackage;
Utils::FileName m_androidDirPath;
QString m_apkPathDebug;
QString m_apkPathRelease;
QString m_buildDirectory;
- QString m_runQASIPackagePath;
AndroidDeployAction m_runDeployAction;
QString m_ndkToolChainVersion;
QString m_libgnustl;
diff --git a/src/plugins/android/androiddeploystepwidget.cpp b/src/plugins/android/androiddeploystepwidget.cpp
index 93140abf3c..68cb6b0c83 100644
--- a/src/plugins/android/androiddeploystepwidget.cpp
+++ b/src/plugins/android/androiddeploystepwidget.cpp
@@ -31,6 +31,7 @@
#include "ui_androiddeploystepwidget.h"
#include "androiddeploystep.h"
+#include "androidmanager.h"
#include "androidrunconfiguration.h"
#include <coreplugin/icore.h>
@@ -55,6 +56,7 @@ AndroidDeployStepWidget::AndroidDeployStepWidget(AndroidDeployStep *step) :
connect(ui->chooseButton, SIGNAL(clicked()), SLOT(setQASIPackagePath()));
connect(ui->cleanLibsPushButton, SIGNAL(clicked()), SLOT(cleanLibsOnDevice()));
+ connect(ui->resetDefaultDevices, SIGNAL(clicked()), SLOT(resetDefaultDevices()));
connect(m_step, SIGNAL(deployOptionsChanged()),
this, SLOT(deployOptionsChanged()));
@@ -115,14 +117,20 @@ void AndroidDeployStepWidget::setQASIPackagePath()
QString packagePath =
QFileDialog::getOpenFileName(this, tr("Qt Android Smart Installer"),
QDir::homePath(), tr("Android package (*.apk)"));
- if (!packagePath.isEmpty())
- m_step->installQASIPackage(packagePath);
+ if (!packagePath.isEmpty()) {
+ AndroidManager::installQASIPackage(m_step->target(), packagePath);
+ }
}
void AndroidDeployStepWidget::cleanLibsOnDevice()
{
- m_step->cleanLibsOnDevice();
+ AndroidManager::cleanLibsOnDevice(m_step->target());
+}
+
+void AndroidDeployStepWidget::resetDefaultDevices()
+{
+ AndroidConfigurations::instance().clearDefaultDevices(m_step->project());
}
} // namespace Internal
diff --git a/src/plugins/android/androiddeploystepwidget.h b/src/plugins/android/androiddeploystepwidget.h
index 94bea1c6de..00781658e9 100644
--- a/src/plugins/android/androiddeploystepwidget.h
+++ b/src/plugins/android/androiddeploystepwidget.h
@@ -55,6 +55,7 @@ private slots:
void setQASIPackagePath();
void cleanLibsOnDevice();
+ void resetDefaultDevices();
void deployOptionsChanged();
private:
diff --git a/src/plugins/android/androiddeploystepwidget.ui b/src/plugins/android/androiddeploystepwidget.ui
index 96ed9eb533..9db955796d 100644
--- a/src/plugins/android/androiddeploystepwidget.ui
+++ b/src/plugins/android/androiddeploystepwidget.ui
@@ -6,8 +6,8 @@
<rect>
<x>0</x>
<y>0</y>
- <width>678</width>
- <height>155</height>
+ <width>682</width>
+ <height>183</height>
</rect>
</property>
<property name="sizePolicy">
@@ -69,21 +69,21 @@ The APK will not be usable on any other device.</string>
<string>Advanced Actions</string>
</property>
<layout class="QGridLayout" name="gridLayout">
- <item row="0" column="0">
+ <item row="1" column="0">
<widget class="QPushButton" name="cleanLibsPushButton">
<property name="text">
<string>Clean Temporary Libraries Directory on Device</string>
</property>
</widget>
</item>
- <item row="1" column="0">
+ <item row="2" column="0">
<widget class="QPushButton" name="chooseButton">
<property name="text">
<string>Install Ministro from APK</string>
</property>
</widget>
</item>
- <item row="2" column="0">
+ <item row="3" column="0">
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
@@ -96,6 +96,13 @@ The APK will not be usable on any other device.</string>
</property>
</spacer>
</item>
+ <item row="0" column="0">
+ <widget class="QPushButton" name="resetDefaultDevices">
+ <property name="text">
+ <string>Reset Default Devices</string>
+ </property>
+ </widget>
+ </item>
</layout>
</widget>
</item>
diff --git a/src/plugins/android/androiddevice.cpp b/src/plugins/android/androiddevice.cpp
index 64cc451eee..8fd3d94e2d 100644
--- a/src/plugins/android/androiddevice.cpp
+++ b/src/plugins/android/androiddevice.cpp
@@ -78,7 +78,7 @@ QString AndroidDevice::displayNameForActionId(Core::Id actionId) const
return QString();
}
-void AndroidDevice::executeAction(Core::Id actionId, QWidget *parent) const
+void AndroidDevice::executeAction(Core::Id actionId, QWidget *parent)
{
Q_UNUSED(actionId)
Q_UNUSED(parent)
@@ -89,6 +89,11 @@ bool AndroidDevice::canAutoDetectPorts() const
return true;
}
+DeviceProcessSignalOperation::Ptr AndroidDevice::signalOperation() const
+{
+ return DeviceProcessSignalOperation::Ptr();
+}
+
IDevice::Ptr AndroidDevice::clone() const
{
return IDevice::Ptr(new AndroidDevice(*this));
diff --git a/src/plugins/android/androiddevice.h b/src/plugins/android/androiddevice.h
index a89d6357d3..1c08bca869 100644
--- a/src/plugins/android/androiddevice.h
+++ b/src/plugins/android/androiddevice.h
@@ -45,8 +45,9 @@ public:
ProjectExplorer::IDeviceWidget *createWidget();
QList<Core::Id> actionIds() const;
QString displayNameForActionId(Core::Id actionId) const;
- void executeAction(Core::Id actionId, QWidget *parent = 0) const;
+ void executeAction(Core::Id actionId, QWidget *parent = 0);
bool canAutoDetectPorts() const;
+ ProjectExplorer::DeviceProcessSignalOperation::Ptr signalOperation() const;
ProjectExplorer::IDevice::Ptr clone() const;
diff --git a/src/plugins/android/androiddevicedialog.cpp b/src/plugins/android/androiddevicedialog.cpp
new file mode 100644
index 0000000000..4f43954e8d
--- /dev/null
+++ b/src/plugins/android/androiddevicedialog.cpp
@@ -0,0 +1,471 @@
+/****************************************************************************
+**
+** 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 "androiddevicedialog.h"
+#include "androidmanager.h"
+#include "ui_androiddevicedialog.h"
+
+#include <QPainter>
+#include <QStyledItemDelegate>
+
+using namespace Android;
+using namespace Android::Internal;
+
+namespace Android {
+namespace Internal {
+
+// yeah, writing tree models is fun!
+class AndroidDeviceModelNode
+{
+public:
+ AndroidDeviceModelNode(AndroidDeviceModelNode *parent, const AndroidDeviceInfo &info, const QString &incompatibleReason = QString())
+ : m_parent(parent), m_info(info), m_incompatibleReason(incompatibleReason)
+ {
+ if (m_parent)
+ m_parent->m_children.append(this);
+ }
+
+ AndroidDeviceModelNode(AndroidDeviceModelNode *parent, const QString &displayName)
+ : m_parent(parent), m_displayName(displayName)
+ {
+ if (m_parent)
+ m_parent->m_children.append(this);
+ }
+
+ ~AndroidDeviceModelNode()
+ {
+ if (m_parent)
+ m_parent->m_children.removeOne(this);
+ QList<AndroidDeviceModelNode *> children = m_children;
+ qDeleteAll(children);
+ }
+
+ AndroidDeviceModelNode *parent() const
+ {
+ return m_parent;
+ }
+
+ QList<AndroidDeviceModelNode *> children() const
+ {
+ return m_children;
+ }
+
+ AndroidDeviceInfo deviceInfo() const
+ {
+ return m_info;
+ }
+
+ QString displayName() const
+ {
+ return m_displayName;
+ }
+
+ QString incompatibleReason() const
+ {
+ return m_incompatibleReason;
+ }
+
+private:
+ AndroidDeviceModelNode *m_parent;
+ AndroidDeviceInfo m_info;
+ QString m_incompatibleReason;
+ QString m_displayName;
+ QList<AndroidDeviceModelNode *> m_children;
+};
+
+class AndroidDeviceModelDelegate : public QStyledItemDelegate
+{
+public:
+ AndroidDeviceModelDelegate(QObject * parent = 0)
+ : QStyledItemDelegate(parent)
+ {
+
+ }
+
+ ~AndroidDeviceModelDelegate()
+ {
+ }
+
+ void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
+ {
+ QStyleOptionViewItemV4 opt = option;
+ initStyleOption(&opt, index);
+ painter->save();
+
+ AndroidDeviceModelNode *node = static_cast<AndroidDeviceModelNode *>(index.internalPointer());
+ AndroidDeviceInfo device = node->deviceInfo();
+
+ painter->setPen(Qt::NoPen);
+
+ // Paint Background
+ QPalette palette = opt.palette; // we always draw enabled
+ palette.setCurrentColorGroup(QPalette::Active);
+ bool selected = opt.state & QStyle::State_Selected;
+ QColor backgroundColor = selected ? palette.highlight().color()
+ : palette.background().color();
+ painter->setBrush(backgroundColor);
+
+ painter->drawRect(0, opt.rect.top(), opt.rect.width() + opt.rect.left(), opt.rect.height());
+
+ QColor textColor;
+ // Set Text Color
+ if (opt.state & QStyle::State_Selected)
+ textColor = palette.highlightedText().color();
+ else
+ textColor = palette.text().color();
+ painter->setPen(textColor);
+
+ if (!node->displayName().isEmpty()) {
+ QIcon icon(QLatin1String(":/core/images/darkarrowdown.png"));
+ int size = opt.rect.bottom() - opt.rect.top();
+ QPixmap pixmap = icon.pixmap(size, size);
+ painter->drawPixmap((size - pixmap.width()) / 2, opt.rect.top() + (size - pixmap.height()) / 2, pixmap);
+
+ // We have a top level node
+ QFont font = opt.font;
+ font.setPointSizeF(font.pointSizeF() * 1.2);
+ font.setBold(true);
+
+ QFontMetrics fm(font);
+ painter->setFont(font);
+ int top = (opt.rect.bottom() + opt.rect.top() - fm.height()) / 2 + fm.ascent();
+ painter->drawText(size, top, node->displayName());
+ } else {
+ QIcon icon(device.type == AndroidDeviceInfo::Hardware ? QLatin1String(":/projectexplorer/images/MaemoDevice.png")
+ : QLatin1String(":/projectexplorer/images/Simulator.png"));
+ int size = opt.rect.bottom() - opt.rect.top() - 12;
+ QPixmap pixmap = icon.pixmap(size, size);
+ painter->drawPixmap(6 + (size - pixmap.width()) / 2, opt.rect.top() + 6 + (size - pixmap.width()) / 2, pixmap);
+
+ QFontMetrics fm(opt.font);
+ // TopLeft
+ QString topLeft = device.serialNumber;
+ if (device.type == AndroidDeviceInfo::Hardware)
+ topLeft = AndroidConfigurations::instance().getProductModel(device.serialNumber);
+ painter->drawText(size + 12, 2 + opt.rect.top() + fm.ascent(), topLeft);
+
+ QString topRight = device.serialNumber;
+ // topRight
+ if (device.type == AndroidDeviceInfo::Hardware) // otherwise it's not very informative
+ painter->drawText(opt.rect.right() - fm.width(topRight) - 6 , 2 + opt.rect.top() + fm.ascent(), topRight);
+
+ // Directory
+ QColor mix;
+ mix.setRgbF(0.7 * textColor.redF() + 0.3 * backgroundColor.redF(),
+ 0.7 * textColor.greenF() + 0.3 * backgroundColor.greenF(),
+ 0.7 * textColor.blueF() + 0.3 * backgroundColor.blueF());
+ painter->setPen(mix);
+
+ QString lineText;
+ if (node->incompatibleReason().isEmpty()) {
+ lineText = AndroidManager::androidNameForApiLevel(device.sdk) + QLatin1String(" ");
+ lineText += AndroidDeviceDialog::tr("ABI:") + device.cpuAbi.join(QLatin1String(" "));
+ } else {
+ lineText = node->incompatibleReason();
+ }
+ painter->drawText(size + 12, opt.rect.top() + fm.ascent() + fm.height() + 6, lineText);
+ }
+
+ // Separator lines
+ painter->setPen(QColor::fromRgb(150,150,150));
+ painter->drawLine(0, opt.rect.bottom(), opt.rect.right(), opt.rect.bottom());
+ painter->restore();
+ }
+
+ QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
+ {
+ QStyleOptionViewItemV4 opt = option;
+ initStyleOption(&opt, index);
+
+ QFontMetrics fm(option.font);
+ QSize s;
+ s.setWidth(option.rect.width());
+ s.setHeight(fm.height() * 2 + 10);
+ return s;
+ }
+};
+
+class AndroidDeviceModel : public QAbstractItemModel
+{
+public:
+ AndroidDeviceModel(int apiLevel, const QString &abi);
+ QModelIndex index(int row, int column,
+ const QModelIndex &parent = QModelIndex()) const;
+ QModelIndex parent(const QModelIndex &child) 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;
+ Qt::ItemFlags flags(const QModelIndex &index) const;
+
+ AndroidDeviceInfo device(QModelIndex index);
+ void setDevices(const QVector<AndroidDeviceInfo> &devices);
+
+ QModelIndex indexFor(const QString &serial);
+private:
+ int m_apiLevel;
+ QString m_abi;
+ AndroidDeviceModelNode *m_root;
+};
+
+}
+}
+/////////////////
+// AndroidDeviceModel
+/////////////////
+AndroidDeviceModel::AndroidDeviceModel(int apiLevel, const QString &abi)
+ : m_apiLevel(apiLevel), m_abi(abi), m_root(0)
+{
+}
+
+QModelIndex AndroidDeviceModel::index(int row, int column, const QModelIndex &parent) const
+{
+ if (column != 0)
+ return QModelIndex();
+
+ if (!m_root)
+ return QModelIndex();
+
+ if (!parent.isValid()) {
+ if (row < 0 || row >= m_root->children().count())
+ return QModelIndex();
+ return createIndex(row, column, m_root->children().at(row));
+ }
+
+ AndroidDeviceModelNode *node = static_cast<AndroidDeviceModelNode *>(parent.internalPointer());
+ if (row < node->children().count())
+ return createIndex(row, column, node->children().at(row));
+
+ return QModelIndex();
+}
+
+QModelIndex AndroidDeviceModel::parent(const QModelIndex &child) const
+{
+ if (!child.isValid())
+ return QModelIndex();
+ if (!m_root)
+ return QModelIndex();
+ AndroidDeviceModelNode *node = static_cast<AndroidDeviceModelNode *>(child.internalPointer());
+ if (node == m_root)
+ return QModelIndex();
+ AndroidDeviceModelNode *parent = node->parent();
+
+ if (parent == m_root)
+ return QModelIndex();
+
+ AndroidDeviceModelNode *grandParent = parent->parent();
+ return createIndex(grandParent->children().indexOf(parent), 0, parent);
+}
+
+int AndroidDeviceModel::rowCount(const QModelIndex &parent) const
+{
+ if (!m_root)
+ return 0;
+ if (!parent.isValid())
+ return m_root->children().count();
+ AndroidDeviceModelNode *node = static_cast<AndroidDeviceModelNode *>(parent.internalPointer());
+ return node->children().count();
+}
+
+int AndroidDeviceModel::columnCount(const QModelIndex &parent) const
+{
+ Q_UNUSED(parent);
+ return 1;
+}
+
+QVariant AndroidDeviceModel::data(const QModelIndex &index, int role) const
+{
+ if (role != Qt::DisplayRole)
+ return QVariant();
+ AndroidDeviceModelNode *node = static_cast<AndroidDeviceModelNode *>(index.internalPointer());
+ if (!node)
+ return QVariant();
+ return node->deviceInfo().serialNumber;
+}
+
+Qt::ItemFlags AndroidDeviceModel::flags(const QModelIndex &index) const
+{
+ AndroidDeviceModelNode *node = static_cast<AndroidDeviceModelNode *>(index.internalPointer());
+ if (node)
+ if (node->displayName().isEmpty() && node->incompatibleReason().isEmpty())
+ return Qt::ItemIsSelectable | Qt::ItemIsEnabled;
+
+ return Qt::NoItemFlags;
+}
+
+AndroidDeviceInfo AndroidDeviceModel::device(QModelIndex index)
+{
+ AndroidDeviceModelNode *node = static_cast<AndroidDeviceModelNode *>(index.internalPointer());
+ if (!node)
+ return AndroidDeviceInfo();
+ return node->deviceInfo();
+}
+
+void AndroidDeviceModel::setDevices(const QVector<AndroidDeviceInfo> &devices)
+{
+ beginResetModel();
+ delete m_root;
+ m_root = new AndroidDeviceModelNode(0, QString());
+
+ AndroidDeviceModelNode *compatibleDevices = new AndroidDeviceModelNode(m_root, AndroidDeviceDialog::tr("Compatible devices"));
+ AndroidDeviceModelNode *incompatibleDevices = 0; // created on demand
+ foreach (const AndroidDeviceInfo &device, devices) {
+ QString error;
+ if (device.unauthorized) {
+ error = AndroidDeviceDialog::tr("Unauthorized. Please check the confirmation dialog on your device %1.")
+ .arg(device.serialNumber);
+ } else if (!device.cpuAbi.contains(m_abi)) {
+ error = AndroidDeviceDialog::tr("ABI is incompatible, device supports ABIs: %1.")
+ .arg(device.cpuAbi.join(QLatin1String(" ")));
+ } else if (device.sdk < m_apiLevel) {
+ error = AndroidDeviceDialog::tr("API Level of device is: %1.")
+ .arg(device.sdk);
+ } else {
+ new AndroidDeviceModelNode(compatibleDevices, device);
+ continue;
+ }
+ if (!incompatibleDevices)
+ incompatibleDevices = new AndroidDeviceModelNode(m_root, AndroidDeviceDialog::tr("Incompatible devices"));
+ new AndroidDeviceModelNode(incompatibleDevices, device, error);
+ }
+ endResetModel();
+}
+
+QModelIndex AndroidDeviceModel::indexFor(const QString &serial)
+{
+ foreach (AndroidDeviceModelNode *topLevelNode, m_root->children()) {
+ QList<AndroidDeviceModelNode *> deviceNodes = topLevelNode->children();
+ for (int i = 0; i < deviceNodes.size(); ++i) {
+ if (deviceNodes.at(i)->deviceInfo().serialNumber == serial)
+ return createIndex(i, 0, deviceNodes.at(i));
+ }
+ }
+ return QModelIndex();
+}
+
+/////////////////
+// AndroidDeviceDialog
+/////////////////
+AndroidDeviceDialog::AndroidDeviceDialog(int apiLevel, const QString &abi, QWidget *parent) :
+ QDialog(parent),
+ m_model(new AndroidDeviceModel(apiLevel, abi)),
+ m_ui(new Ui::AndroidDeviceDialog),
+ m_apiLevel(apiLevel),
+ m_abi(abi)
+{
+ m_ui->setupUi(this);
+ m_ui->deviceView->setModel(m_model);
+ m_ui->deviceView->setItemDelegate(new AndroidDeviceModelDelegate(m_ui->deviceView));
+ m_ui->deviceView->setHeaderHidden(true);
+ m_ui->deviceView->setRootIsDecorated(false);
+ m_ui->deviceView->setUniformRowHeights(true);
+
+ m_ui->defaultDeviceCheckBox->setText(tr("Always use this device for architecture %1").arg(abi));
+
+ connect(m_ui->refreshDevicesButton, SIGNAL(clicked()),
+ this, SLOT(refreshDeviceList()));
+
+ connect(m_ui->createAVDButton, SIGNAL(clicked()),
+ this, SLOT(createAvd()));
+
+ refreshDeviceList();
+}
+
+AndroidDeviceDialog::~AndroidDeviceDialog()
+{
+ delete m_ui;
+}
+
+AndroidDeviceInfo AndroidDeviceDialog::device()
+{
+ if (result() == QDialog::Accepted)
+ return m_model->device(m_ui->deviceView->currentIndex());
+ return AndroidDeviceInfo();
+}
+
+void AndroidDeviceDialog::accept()
+{
+ QDialog::accept();
+}
+
+bool AndroidDeviceDialog::saveDeviceSelection()
+{
+ return m_ui->defaultDeviceCheckBox->isChecked();
+}
+
+void AndroidDeviceDialog::refreshDeviceList()
+{
+ QString serialNumber;
+ QModelIndex currentIndex = m_ui->deviceView->currentIndex();
+ if (currentIndex.isValid())
+ serialNumber = m_model->device(currentIndex).serialNumber;
+
+ QVector<AndroidDeviceInfo> devices;
+ foreach (const AndroidDeviceInfo &info, AndroidConfigurations::instance().connectedDevices())
+ if (info.type == AndroidDeviceInfo::Hardware)
+ devices << info;
+
+ devices += AndroidConfigurations::instance().androidVirtualDevices();
+ m_model->setDevices(devices);
+
+ m_ui->deviceView->expand(m_model->index(0, 0));
+
+ // Smartly select a index
+ QModelIndex newIndex;
+ if (!serialNumber.isEmpty())
+ newIndex = m_model->indexFor(serialNumber);
+
+ if (!newIndex.isValid() && !devices.isEmpty())
+ newIndex = m_model->indexFor(devices.first().serialNumber);
+
+ m_ui->deviceView->setCurrentIndex(newIndex);
+}
+
+void AndroidDeviceDialog::createAvd()
+{
+ QString avd = AndroidConfigurations::instance().createAVD(m_apiLevel, m_abi);
+ if (avd.isEmpty())
+ return;
+ refreshDeviceList();
+ QModelIndex index = m_model->indexFor(avd);
+ m_ui->deviceView->setCurrentIndex(index);
+}
+
+// Does not work.
+void AndroidDeviceDialog::clickedOnView(const QModelIndex &idx)
+{
+ if (idx.isValid()) {
+ AndroidDeviceModelNode *node = static_cast<AndroidDeviceModelNode *>(idx.internalPointer());
+ if (!node->displayName().isEmpty()) {
+ if (m_ui->deviceView->isExpanded(idx))
+ m_ui->deviceView->collapse(idx);
+ else
+ m_ui->deviceView->expand(idx);
+ }
+ }
+}
diff --git a/src/plugins/android/androiddevicedialog.h b/src/plugins/android/androiddevicedialog.h
new file mode 100644
index 0000000000..2b8a15ba0a
--- /dev/null
+++ b/src/plugins/android/androiddevicedialog.h
@@ -0,0 +1,75 @@
+/****************************************************************************
+**
+** 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 ANDROIDDEVICEDIALOG_H
+#define ANDROIDDEVICEDIALOG_H
+
+#include "androidconfigurations.h"
+
+#include <QVector>
+#include <QDialog>
+
+QT_BEGIN_NAMESPACE
+class QModelIndex;
+QT_END_NAMESPACE
+
+namespace Android {
+namespace Internal {
+
+class AndroidDeviceModel;
+namespace Ui { class AndroidDeviceDialog; }
+
+class AndroidDeviceDialog : public QDialog
+{
+ Q_OBJECT
+
+public:
+ explicit AndroidDeviceDialog(int apiLevel, const QString &abi, QWidget *parent = 0);
+ ~AndroidDeviceDialog();
+
+ AndroidDeviceInfo device();
+ void accept();
+
+ bool saveDeviceSelection();
+
+private slots:
+ void refreshDeviceList();
+ void createAvd();
+ void clickedOnView(const QModelIndex &idx);
+private:
+ AndroidDeviceModel *m_model;
+ Ui::AndroidDeviceDialog *m_ui;
+ int m_apiLevel;
+ QString m_abi;
+};
+
+}
+}
+
+#endif // ANDROIDDEVICEDIALOG_H
diff --git a/src/plugins/android/androiddevicedialog.ui b/src/plugins/android/androiddevicedialog.ui
new file mode 100644
index 0000000000..c64465e143
--- /dev/null
+++ b/src/plugins/android/androiddevicedialog.ui
@@ -0,0 +1,95 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>Android::Internal::AndroidDeviceDialog</class>
+ <widget class="QDialog" name="Android::Internal::AndroidDeviceDialog">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>618</width>
+ <height>400</height>
+ </rect>
+ </property>
+ <property name="windowTitle">
+ <string>Select Android Device</string>
+ </property>
+ <layout class="QGridLayout" name="gridLayout">
+ <item row="1" column="0">
+ <widget class="QPushButton" name="refreshDevicesButton">
+ <property name="text">
+ <string>Refresh Device List</string>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="1">
+ <widget class="QPushButton" name="createAVDButton">
+ <property name="text">
+ <string>Create Android Virtual Device</string>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="0" colspan="2">
+ <widget class="QCheckBox" name="defaultDeviceCheckBox">
+ <property name="text">
+ <string>Always use this device for architecture %1</string>
+ </property>
+ </widget>
+ </item>
+ <item row="3" column="2">
+ <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" colspan="3">
+ <widget class="QTreeView" name="deviceView">
+ <property name="minimumSize">
+ <size>
+ <width>600</width>
+ <height>300</height>
+ </size>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections>
+ <connection>
+ <sender>buttonBox</sender>
+ <signal>accepted()</signal>
+ <receiver>Android::Internal::AndroidDeviceDialog</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>Android::Internal::AndroidDeviceDialog</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/android/androiderrormessage.cpp b/src/plugins/android/androiderrormessage.cpp
new file mode 100644
index 0000000000..cbbd06b21a
--- /dev/null
+++ b/src/plugins/android/androiderrormessage.cpp
@@ -0,0 +1,74 @@
+/****************************************************************************
+**
+** 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 "androiderrormessage.h"
+
+#include <QObject>
+
+namespace Android {
+namespace Internal {
+
+QString AndroidErrorMessage::getMessage(ErrorCode errorCode, const QVariantList &parameters)
+{
+ Q_UNUSED(parameters);
+ switch (errorCode) {
+ case SDKInstallationError:
+ return tr("Android: SDK installation error 0x%1").arg(errorCode, 0, 16);
+
+ case NDKInstallationError:
+ return tr("Android: NDK installation error 0x%1").arg(errorCode, 0, 16);
+
+ case JavaInstallationError:
+ return tr("Android: Java installation error 0x%1").arg(errorCode, 0, 16);
+
+ case AntInstallationError:
+ return tr("Android: ant installation error 0x%1").arg(errorCode, 0, 16);
+
+ case AdbInstallationError:
+ return tr("Android: adb installation error 0x%1").arg(errorCode, 0, 16);
+
+ case DeviceConnectionError:
+ return tr("Android: Device connection error 0x%1").arg(errorCode, 0, 16);
+
+ case DevicePermissionError:
+ return tr("Android: Device permission error 0x%1").arg(errorCode, 0, 16);
+
+ case DeviceAuthorizationError:
+ return tr("Android: Device authorization error 0x%1").arg(errorCode, 0, 16);
+
+ case DeviceAPILevelError:
+ return tr("Android: Device API level not supported: error 0x%1").arg(errorCode, 0, 16);
+
+ default:
+ return tr("Android: Unknown error 0x%1").arg(errorCode, 0, 16);
+ }
+}
+
+} // namespace Internal
+} // namespace Android
diff --git a/src/plugins/debugger/gdb/abstractplaingdbadapter.h b/src/plugins/android/androiderrormessage.h
index 9178c1afba..fc7cf9be11 100644
--- a/src/plugins/debugger/gdb/abstractplaingdbadapter.h
+++ b/src/plugins/android/androiderrormessage.h
@@ -27,34 +27,35 @@
**
****************************************************************************/
-#ifndef ABSTRACTPLAINGDBADAPTER_H
-#define ABSTRACTPLAINGDBADAPTER_H
+#ifndef ANDROIDERRORMESSAGE_H
+#define ANDROIDERRORMESSAGE_H
-#include "gdbengine.h"
+#include <QVariantList>
+#include <QCoreApplication>
-namespace Debugger {
+namespace Android {
namespace Internal {
-class GdbAbstractPlainEngine : public GdbEngine
+class AndroidErrorMessage
{
- // Needs tr - context
- Q_OBJECT
-
+ Q_DECLARE_TR_FUNCTIONS(Android::Internal::AndroidErrorMessage)
public:
- explicit GdbAbstractPlainEngine(const DebuggerStartParameters &startParameters);
-
- void setupInferior();
- void runEngine();
-
-private:
- virtual QByteArray execFilePath() const = 0;
- virtual QByteArray toLocalEncoding(const QString &str) const = 0;
- virtual QString fromLocalEncoding(const QByteArray &ba) const = 0;
- void handleExecRun(const GdbResponse &response);
- void handleFileExecAndSymbols(const GdbResponse &response);
+ enum ErrorCode {
+ UnknownError = 0x3000,
+ SDKInstallationError,
+ NDKInstallationError,
+ JavaInstallationError,
+ AntInstallationError,
+ AdbInstallationError,
+ DeviceConnectionError,
+ DevicePermissionError,
+ DeviceAuthorizationError,
+ DeviceAPILevelError
+ };
+ static QString getMessage(ErrorCode errorCode, const QVariantList &parameters = QVariantList());
};
-} // namespace Debugger
} // namespace Internal
+} // namespace Android
-#endif // ABSTRACTPLAINGDBADAPTER_H
+#endif // ANDROIDERRORMESSAGE_H
diff --git a/src/plugins/android/androidgdbserverkitinformation.cpp b/src/plugins/android/androidgdbserverkitinformation.cpp
index 190a4abb20..0224453d40 100644
--- a/src/plugins/android/androidgdbserverkitinformation.cpp
+++ b/src/plugins/android/androidgdbserverkitinformation.cpp
@@ -42,64 +42,73 @@
#include <QVBoxLayout>
#include <QFormLayout>
-using namespace Android;
-using namespace Android::Internal;
+#include <qtsupport/baseqtversion.h>
+#include <qtsupport/qtkitinformation.h>
-namespace {
-static const char ANDROIDGDBSERVER_INFORMATION[] = "Android.GdbServer.Information";
-}
+using namespace ProjectExplorer;
+using namespace Utils;
+
+namespace Android {
+namespace Internal {
AndroidGdbServerKitInformation::AndroidGdbServerKitInformation()
{
+ setId(AndroidGdbServerKitInformation::id());
+ setPriority(27999); // Just one less than Debugger!
}
-Core::Id AndroidGdbServerKitInformation::dataId() const
+QVariant AndroidGdbServerKitInformation::defaultValue(Kit *kit) const
{
- return Core::Id(ANDROIDGDBSERVER_INFORMATION);
+ return autoDetect(kit).toString();
}
-unsigned int AndroidGdbServerKitInformation::priority() const
+QList<Task> AndroidGdbServerKitInformation::validate(const Kit *) const
{
- return 27999; // Just one less than Debugger!
+ return QList<Task>();
}
-QVariant AndroidGdbServerKitInformation::defaultValue(ProjectExplorer::Kit *kit) const
+KitInformation::ItemList AndroidGdbServerKitInformation::toUserOutput(const Kit *kit) const
{
- return autoDetect(kit).toString();
+ return KitInformation::ItemList()
+ << qMakePair(tr("GDB server"), AndroidGdbServerKitInformation::gdbServer(kit).toUserOutput());
}
-QList<ProjectExplorer::Task> AndroidGdbServerKitInformation::validate(const ProjectExplorer::Kit *) const
+KitConfigWidget *AndroidGdbServerKitInformation::createConfigWidget(Kit *kit) const
{
- return QList<ProjectExplorer::Task>();
+ return new AndroidGdbServerKitInformationWidget(kit, this);
}
-ProjectExplorer::KitInformation::ItemList AndroidGdbServerKitInformation::toUserOutput(const ProjectExplorer::Kit *kit) const
+Core::Id AndroidGdbServerKitInformation::id()
{
- return ProjectExplorer::KitInformation::ItemList()
- << qMakePair(tr("GDB server"), AndroidGdbServerKitInformation::gdbServer(kit).toUserOutput());
+ return "Android.GdbServer.Information";
}
-ProjectExplorer::KitConfigWidget *AndroidGdbServerKitInformation::createConfigWidget(ProjectExplorer::Kit *kit) const
+bool AndroidGdbServerKitInformation::isAndroidKit(const Kit *kit)
{
- return new AndroidGdbServerKitInformationWidget(kit, isSticky(kit));
+ QtSupport::BaseQtVersion *qt = QtSupport::QtKitInformation::qtVersion(kit);
+ ToolChain *tc = ToolChainKitInformation::toolChain(kit);
+ if (qt && tc)
+ return qt->type() == QLatin1String(Constants::ANDROIDQT)
+ && tc->type() == QLatin1String(Constants::ANDROID_TOOLCHAIN_TYPE);
+ return false;
+
}
-Utils::FileName AndroidGdbServerKitInformation::gdbServer(const ProjectExplorer::Kit *kit)
+FileName AndroidGdbServerKitInformation::gdbServer(const Kit *kit)
{
- return Utils::FileName::fromString(kit->value(Core::Id(ANDROIDGDBSERVER_INFORMATION)).toString());
+ return FileName::fromString(kit->value(AndroidGdbServerKitInformation::id()).toString());
}
-void AndroidGdbServerKitInformation::setGdbSever(ProjectExplorer::Kit *kit, const Utils::FileName &gdbServerCommand)
+void AndroidGdbServerKitInformation::setGdbSever(Kit *kit, const FileName &gdbServerCommand)
{
- kit->setValue(Core::Id(ANDROIDGDBSERVER_INFORMATION),
- gdbServerCommand.toString());
+ kit->setValue(AndroidGdbServerKitInformation::id(), gdbServerCommand.toString());
}
-Utils::FileName AndroidGdbServerKitInformation::autoDetect(ProjectExplorer::Kit *kit)
+FileName AndroidGdbServerKitInformation::autoDetect(Kit *kit)
{
- ProjectExplorer::ToolChain *tc = ProjectExplorer::ToolChainKitInformation::toolChain(kit);
+ ToolChain *tc = ToolChainKitInformation::toolChain(kit);
if (!tc || tc->type() != QLatin1String(Constants::ANDROID_TOOLCHAIN_TYPE))
- return Utils::FileName();
+ return FileName();
AndroidToolChain *atc = static_cast<AndroidToolChain *>(tc);
return atc->suggestedGdbServer();
}
@@ -109,9 +118,9 @@ Utils::FileName AndroidGdbServerKitInformation::autoDetect(ProjectExplorer::Kit
///////////////
-AndroidGdbServerKitInformationWidget::AndroidGdbServerKitInformationWidget(ProjectExplorer::Kit *kit, bool sticky)
- : ProjectExplorer::KitConfigWidget(kit, sticky),
- m_label(new Utils::ElidingLabel),
+AndroidGdbServerKitInformationWidget::AndroidGdbServerKitInformationWidget(Kit *kit, const KitInformation *ki)
+ : KitConfigWidget(kit, ki),
+ m_label(new ElidingLabel),
m_button(new QPushButton(tr("Manage...")))
{
// ToolButton with Menu, defaulting to 'Autodetect'.
@@ -125,6 +134,12 @@ AndroidGdbServerKitInformationWidget::AndroidGdbServerKitInformationWidget(Proje
refresh();
}
+AndroidGdbServerKitInformationWidget::~AndroidGdbServerKitInformationWidget()
+{
+ delete m_button;
+ delete m_label;
+}
+
QString AndroidGdbServerKitInformationWidget::displayName() const
{
return tr("Android GDB server");
@@ -147,7 +162,7 @@ void AndroidGdbServerKitInformationWidget::refresh()
bool AndroidGdbServerKitInformationWidget::visibleInKit()
{
- return ProjectExplorer::DeviceKitInformation::deviceId(m_kit) == Core::Id(Constants::ANDROID_DEVICE_ID);
+ return DeviceKitInformation::deviceId(m_kit) == Constants::ANDROID_DEVICE_ID;
}
QWidget *AndroidGdbServerKitInformationWidget::mainWidget() const
@@ -173,8 +188,8 @@ void AndroidGdbServerKitInformationWidget::showDialog()
formLayout->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow);
QLabel *binaryLabel = new QLabel(tr("&Binary:"));
- Utils::PathChooser *chooser = new Utils::PathChooser;
- chooser->setExpectedKind(Utils::PathChooser::ExistingCommand);
+ PathChooser *chooser = new PathChooser;
+ chooser->setExpectedKind(PathChooser::ExistingCommand);
chooser->setPath(AndroidGdbServerKitInformation::gdbServer(m_kit).toString());
binaryLabel->setBuddy(chooser);
formLayout->addRow(binaryLabel, chooser);
@@ -190,3 +205,6 @@ void AndroidGdbServerKitInformationWidget::showDialog()
if (dialog.exec() == QDialog::Accepted)
AndroidGdbServerKitInformation::setGdbSever(m_kit, chooser->fileName());
}
+
+} // namespace Internal
+} // namespace Android
diff --git a/src/plugins/android/androidgdbserverkitinformation.h b/src/plugins/android/androidgdbserverkitinformation.h
index d3f8b77fbc..8b196276fc 100644
--- a/src/plugins/android/androidgdbserverkitinformation.h
+++ b/src/plugins/android/androidgdbserverkitinformation.h
@@ -33,11 +33,10 @@
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/kitconfigwidget.h>
-QT_FORWARD_DECLARE_CLASS(QLabel);
-QT_FORWARD_DECLARE_CLASS(QPushButton);
-
-namespace ProjectExplorer {
-}
+QT_BEGIN_NAMESPACE
+class QLabel;
+class QPushButton;
+QT_END_NAMESPACE
namespace Android {
namespace Internal {
@@ -46,7 +45,9 @@ class AndroidGdbServerKitInformationWidget : public ProjectExplorer::KitConfigWi
{
Q_OBJECT
public:
- AndroidGdbServerKitInformationWidget(ProjectExplorer::Kit *kit, bool sticky);
+ AndroidGdbServerKitInformationWidget(ProjectExplorer::Kit *kit,
+ const ProjectExplorer::KitInformation *ki);
+ ~AndroidGdbServerKitInformationWidget();
QString displayName() const;
QString toolTip() const;
@@ -69,10 +70,7 @@ class AndroidGdbServerKitInformation : public ProjectExplorer::KitInformation
{
Q_OBJECT
public:
- explicit AndroidGdbServerKitInformation();
- Core::Id dataId() const;
-
- unsigned int priority() const; // the higher the closer to the top.
+ AndroidGdbServerKitInformation();
QVariant defaultValue(ProjectExplorer::Kit *) const;
@@ -82,6 +80,8 @@ public:
ProjectExplorer::KitConfigWidget *createConfigWidget(ProjectExplorer::Kit *) const;
+ static Core::Id id();
+ static bool isAndroidKit(const ProjectExplorer::Kit *kit);
static Utils::FileName gdbServer(const ProjectExplorer::Kit *kit);
static void setGdbSever(ProjectExplorer::Kit *kit, const Utils::FileName &gdbServerCommand);
static Utils::FileName autoDetect(ProjectExplorer::Kit *kit);
diff --git a/src/plugins/android/androidmanager.cpp b/src/plugins/android/androidmanager.cpp
index 38cfe6eece..e87e972e84 100644
--- a/src/plugins/android/androidmanager.cpp
+++ b/src/plugins/android/androidmanager.cpp
@@ -35,8 +35,10 @@
#include "androidglobal.h"
#include "androidpackagecreationstep.h"
#include "androidtoolchain.h"
+#include "androiddeployqtstep.h"
#include <coreplugin/documentmanager.h>
+#include <coreplugin/messagemanager.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/session.h>
#include <projectexplorer/target.h>
@@ -196,16 +198,43 @@ QString AndroidManager::activityName(ProjectExplorer::Target *target)
return activityElem.attribute(QLatin1String("android:name"));
}
-QString AndroidManager::targetSDK(ProjectExplorer::Target *target)
+int AndroidManager::minimumSDK(ProjectExplorer::Target *target)
{
+ QDomDocument doc;
+ if (!openManifest(target, doc))
+ return 0;
+ QDomElement manifestElem = doc.documentElement();
+ QDomElement usesSdk = manifestElem.firstChildElement(QLatin1String("uses-sdk"));
+ if (usesSdk.isNull())
+ return 0;
+ if (usesSdk.hasAttribute(QLatin1String("android:minSdkVersion"))) {
+ bool ok;
+ int tmp = usesSdk.attribute(QLatin1String("android:minSdkVersion")).toInt(&ok);
+ if (ok)
+ return tmp;
+ }
+ return 0;
+}
+
+QString AndroidManager::buildTargetSDK(ProjectExplorer::Target *target)
+{
+ QtSupport::BaseQtVersion *qt = QtSupport::QtKitInformation::qtVersion(target->kit());
+ if (qt && qt->qtVersion() >= QtSupport::QtVersionNumber(5, 2, 0)) {
+ if (!target->activeDeployConfiguration())
+ return QLatin1String("android-9");
+ AndroidDeployQtStep *step = AndroidGlobal::buildStep<AndroidDeployQtStep>(target->activeDeployConfiguration());
+ if (step)
+ return step->buildTargetSdk();
+ return QLatin1String("android-9");
+ }
+
QVariant v = target->namedSettings(QLatin1String("AndroidManager.TargetSdk"));
if (v.isValid())
return v.toString();
QString fallback = QLatin1String("android-8");
- if (QtSupport::BaseQtVersion *qt = QtSupport::QtKitInformation::qtVersion(target->kit()))
- if (qt->qtVersion() >= QtSupport::QtVersionNumber(5, 0, 0))
- fallback = QLatin1String("android-9");
+ if (qt && qt->qtVersion() >= QtSupport::QtVersionNumber(5, 0, 0))
+ fallback = QLatin1String("android-9");
if (!createAndroidTemplatesIfNecessary(target))
return AndroidConfigurations::instance().bestMatch(fallback);
@@ -221,7 +250,7 @@ QString AndroidManager::targetSDK(ProjectExplorer::Target *target)
return AndroidConfigurations::instance().bestMatch(fallback);
}
-bool AndroidManager::setTargetSDK(ProjectExplorer::Target *target, const QString &sdk)
+bool AndroidManager::setBuildTargetSDK(ProjectExplorer::Target *target, const QString &sdk)
{
updateTarget(target, sdk, applicationName(target));
target->setNamedSettings(QLatin1String("AndroidManager.TargetSdk"), sdk);
@@ -241,6 +270,9 @@ QString AndroidManager::targetArch(ProjectExplorer::Target *target)
Utils::FileName AndroidManager::dirPath(ProjectExplorer::Target *target)
{
+ QtSupport::BaseQtVersion *qtVersion = QtSupport::QtKitInformation::qtVersion(target->kit());
+ if (qtVersion && qtVersion->qtVersion() >= QtSupport::QtVersionNumber(5, 2, 0))
+ return target->activeBuildConfiguration()->buildDirectory().appendPath(AndroidDirName);
return Utils::FileName::fromString(target->project()->projectDirectory()).appendPath(AndroidDirName);
}
@@ -271,21 +303,36 @@ Utils::FileName AndroidManager::srcPath(ProjectExplorer::Target *target)
Utils::FileName AndroidManager::apkPath(ProjectExplorer::Target *target, BuildType buildType)
{
+ QString packageName = QLatin1String("QtApp");
+ QString buildTypeName;
+ if (buildType == DebugBuild)
+ buildTypeName = QLatin1String("debug");
+ else if (buildType == ReleaseBuildUnsigned)
+ buildTypeName =QLatin1String("release-unsigned");
+ else
+ buildTypeName = QLatin1String("release");
+
+ QtSupport::BaseQtVersion *qt = QtSupport::QtKitInformation::qtVersion(target->kit());
+ if (!qt || qt->qtVersion() < QtSupport::QtVersionNumber(5, 2, 0)) {
+ // Qt 5.1 and earlier:
+ packageName = applicationName(target);
+ if (buildType == ReleaseBuildSigned)
+ buildTypeName = QLatin1String("signed");
+ }
+
return dirPath(target)
.appendPath(QLatin1String("bin"))
.appendPath(QString::fromLatin1("%1-%2.apk")
- .arg(applicationName(target))
- .arg(buildType == DebugBuild
- ? QLatin1String("debug")
- : (buildType == ReleaseBuildUnsigned)
- ? QLatin1String("release-unsigned")
- : QLatin1String("signed")));
+ .arg(packageName)
+ .arg(buildTypeName));
}
QStringList AndroidManager::availableTargetApplications(ProjectExplorer::Target *target)
{
QStringList apps;
Qt4ProjectManager::Qt4Project *qt4Project = qobject_cast<Qt4ProjectManager::Qt4Project *>(target->project());
+ if (!qt4Project)
+ return apps;
foreach (Qt4ProjectManager::Qt4ProFileNode *proFile, qt4Project->applicationProFiles()) {
if (proFile->projectType() == Qt4ProjectManager::ApplicationTemplate) {
if (proFile->targetInformation().target.startsWith(QLatin1String("lib"))
@@ -313,18 +360,59 @@ QString AndroidManager::targetApplication(ProjectExplorer::Target *target)
return QString();
}
+// Note, this could be implemented via a base class and a couple of virtuals
+// but I intend to remove the indirection once we drop support for qt 4.8
+// and qt 5.1.
bool AndroidManager::bundleQt(ProjectExplorer::Target *target)
{
- ProjectExplorer::RunConfiguration *runConfiguration = target->activeRunConfiguration();
- AndroidRunConfiguration *androidRunConfiguration = qobject_cast<AndroidRunConfiguration *>(runConfiguration);
- if (androidRunConfiguration != 0) {
- AndroidDeployStep *deployStep = androidRunConfiguration->deployStep();
- return deployStep->deployAction() == AndroidDeployStep::BundleLibraries;
+ AndroidDeployStep *androidDeployStep
+ = AndroidGlobal::buildStep<AndroidDeployStep>(target->activeDeployConfiguration());
+ if (androidDeployStep) {
+ return androidDeployStep->deployAction() == AndroidDeployStep::BundleLibraries;
+ }
+
+ AndroidDeployQtStep *androidDeployQtStep
+ = AndroidGlobal::buildStep<AndroidDeployQtStep>(target->activeDeployConfiguration());
+ if (androidDeployQtStep) {
+ return androidDeployQtStep->deployAction() == AndroidDeployQtStep::BundleLibrariesDeployment;
+ }
+
+ return false;
+}
+
+bool AndroidManager::useLocalLibs(ProjectExplorer::Target *target)
+{
+ AndroidDeployStep *androidDeployStep
+ = AndroidGlobal::buildStep<AndroidDeployStep>(target->activeDeployConfiguration());
+ if (androidDeployStep) {
+ return androidDeployStep->deployAction() == AndroidDeployStep::DeployLocal
+ || androidDeployStep->deployAction() == AndroidDeployStep::BundleLibraries;
+ }
+
+ AndroidDeployQtStep *androidDeployQtStep
+ = AndroidGlobal::buildStep<AndroidDeployQtStep>(target->activeDeployConfiguration());
+ if (androidDeployQtStep) {
+ return androidDeployQtStep->deployAction() == AndroidDeployQtStep::DebugDeployment
+ || androidDeployQtStep->deployAction() == AndroidDeployQtStep::BundleLibrariesDeployment;
}
return false;
}
+QString AndroidManager::deviceSerialNumber(ProjectExplorer::Target *target)
+{
+ AndroidDeployStep *androidDeployStep
+ = AndroidGlobal::buildStep<AndroidDeployStep>(target->activeDeployConfiguration());
+ if (androidDeployStep)
+ return androidDeployStep->deviceSerialNumber();
+
+ AndroidDeployQtStep *androidDeployQtStep
+ = AndroidGlobal::buildStep<AndroidDeployQtStep>(target->activeDeployConfiguration());
+ if (androidDeployQtStep)
+ return androidDeployQtStep->deviceSerialNumber();
+ return QString();
+}
+
bool AndroidManager::updateDeploymentSettings(ProjectExplorer::Target *target)
{
// For Qt 4, the "use local libs" options is handled by passing command line arguments to the
@@ -333,16 +421,16 @@ bool AndroidManager::updateDeploymentSettings(ProjectExplorer::Target *target)
if (baseQtVersion == 0 || baseQtVersion->qtVersion() < QtSupport::QtVersionNumber(5,0,0))
return true;
+ if (baseQtVersion->qtVersion() >= QtSupport::QtVersionNumber(5, 2, 0))
+ return true;
+
ProjectExplorer::RunConfiguration *runConfiguration = target->activeRunConfiguration();
AndroidRunConfiguration *androidRunConfiguration = qobject_cast<AndroidRunConfiguration *>(runConfiguration);
if (androidRunConfiguration == 0)
return false;
- AndroidDeployStep *deployStep = androidRunConfiguration->deployStep();
- AndroidDeployStep::AndroidDeployAction deployAction = deployStep->deployAction();
- bool useLocalLibs = deployAction == AndroidDeployStep::DeployLocal
- || deployAction == AndroidDeployStep::BundleLibraries;
- bool bundleQtLibs = deployAction == AndroidDeployStep::BundleLibraries;
+ bool useLocalLibs = AndroidManager::useLocalLibs(target);
+ bool bundleQtLibs = AndroidManager::bundleQt(target);
QDomDocument doc;
if (!openManifest(target, doc))
@@ -445,6 +533,10 @@ bool AndroidManager::createAndroidTemplatesIfNecessary(ProjectExplorer::Target *
if (!qt4Project || !qt4Project->rootProjectNode() || !version)
return false;
+ // TODO we should create the AndroidManifest.xml file for that version
+ if (version->qtVersion() >= QtSupport::QtVersionNumber(5, 2, 0))
+ return true;
+
Utils::FileName javaSrcPath
= Utils::FileName::fromString(version->qmakeProperty("QT_INSTALL_PREFIX"))
.appendPath(QLatin1String("src/android/java"));
@@ -515,7 +607,7 @@ bool AndroidManager::createAndroidTemplatesIfNecessary(ProjectExplorer::Target *
}
}
if (!androidFiles.isEmpty())
- qt4Project->rootProjectNode()->addFiles(ProjectExplorer::UnknownFileType, androidFiles);
+ qt4Project->rootProjectNode()->addFiles(androidFiles);
int minApiLevel = 4;
if (QtSupport::BaseQtVersion *qt = QtSupport::QtKitInformation::qtVersion(target->kit()))
@@ -548,6 +640,10 @@ bool AndroidManager::createAndroidTemplatesIfNecessary(ProjectExplorer::Target *
void AndroidManager::updateTarget(ProjectExplorer::Target *target, const QString &targetSDK, const QString &name)
{
+ QtSupport::BaseQtVersion *qtVersion = QtSupport::QtKitInformation::qtVersion(target->kit());
+ if (qtVersion && qtVersion->qtVersion() >= QtSupport::QtVersionNumber(5,2,0))
+ return;
+
QString androidDir = dirPath(target).toString();
Utils::Environment env = Utils::Environment::systemEnvironment();
@@ -647,6 +743,57 @@ QString AndroidManager::loadLocalJarsInitClasses(ProjectExplorer::Target *target
return loadLocal(target, apiLevel, type, QLatin1String("initClass"));
}
+QPair<int, int> AndroidManager::apiLevelRange(ProjectExplorer::Target *target)
+{
+ // 4 is the minimum version on which qt is supported
+ // 19 and 20 are not yet released, but allow the user
+ // to set them
+ int minApiLevel = 4;
+ QtSupport::BaseQtVersion *qt;
+ if (target && (qt = QtSupport::QtKitInformation::qtVersion(target->kit())))
+ if (qt->qtVersion() >= QtSupport::QtVersionNumber(5, 0, 0))
+ minApiLevel = 9;
+ return qMakePair(minApiLevel, 20);
+}
+
+QString AndroidManager::androidNameForApiLevel(int x)
+{
+ switch (x) {
+ case 4:
+ return QLatin1String("Android 1.6");
+ case 5:
+ return QLatin1String("Android 2.0");
+ case 6:
+ return QLatin1String("Android 2.0.1");
+ case 7:
+ return QLatin1String("Android 2.1.x");
+ case 8:
+ return QLatin1String("Android 2.2.x");
+ case 9:
+ return QLatin1String("Android 2.3, 2.3.1, 2.3.2");
+ case 10:
+ return QLatin1String("Android 2.3.3, 2.3.4");
+ case 11:
+ return QLatin1String("Android 3.0.x");
+ case 12:
+ return QLatin1String("Android 3.1.x");
+ case 13:
+ return QLatin1String("Android 3.2");
+ case 14:
+ return QLatin1String("Android 4.0, 4.0.1, 4.0.2");
+ case 15:
+ return QLatin1String("Android 4.0.3, 4.0.4");
+ case 16:
+ return QLatin1String("Android 4.1, 4.1.1");
+ case 17:
+ return QLatin1String("Android 4.2, 4.2.2");
+ case 18:
+ return QLatin1String("Android 4.3");
+ default:
+ return QLatin1String("Unknown Android version.");
+ }
+}
+
QVector<AndroidManager::Library> AndroidManager::availableQtLibsWithDependencies(ProjectExplorer::Target *target)
{
QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(target->kit());
@@ -683,7 +830,7 @@ QVector<AndroidManager::Library> AndroidManager::availableQtLibsWithDependencies
}
const QString library = libgnustl.mid(libgnustl.lastIndexOf(QLatin1Char('/')) + 1);
- mapLibs[library] = Library();;
+ mapLibs[library] = Library();
// clean dependencies
const LibrariesMap::Iterator lend = mapLibs.end();
@@ -843,7 +990,9 @@ QString AndroidManager::loadLocal(ProjectExplorer::Target *target, int apiLevel,
while (!libElement.isNull()) {
if (libElement.attribute(QLatin1String("bundling")).toInt() == (item == BundledJar ? 1 : 0)) {
if (libElement.hasAttribute(attribute)) {
- QString dependencyLib = libElement.attribute(attribute).arg(apiLevel);
+ QString dependencyLib = libElement.attribute(attribute);
+ if (dependencyLib.contains(QLatin1String("%1")))
+ dependencyLib = dependencyLib.arg(apiLevel);
if (libElement.hasAttribute(QLatin1String("extends"))) {
const QString extends = libElement.attribute(QLatin1String("extends"));
if (libs.contains(extends)) {
@@ -855,7 +1004,9 @@ QString AndroidManager::loadLocal(ProjectExplorer::Target *target, int apiLevel,
}
if (libElement.hasAttribute(QLatin1String("replaces"))) {
- QString replacedLib = libElement.attribute(QLatin1String("replaces")).arg(apiLevel);
+ QString replacedLib = libElement.attribute(QLatin1String("replaces"));
+ if (replacedLib.contains(QLatin1String("%1")))
+ replacedLib = replacedLib.arg(apiLevel);
if (!replacedLibs.contains(replacedLib))
replacedLibs << replacedLib;
}
@@ -1040,5 +1191,126 @@ QString AndroidManager::libraryPrefix()
return AndroidLibraryPrefix;
}
+
+void AndroidManager::cleanLibsOnDevice(ProjectExplorer::Target *target)
+{
+ const QString targetArch = AndroidManager::targetArch(target);
+ int deviceAPILevel = AndroidManager::minimumSDK(target);
+ AndroidDeviceInfo info = AndroidConfigurations::instance().showDeviceDialog(target->project(), deviceAPILevel, targetArch);
+ if (info.serialNumber.isEmpty()) // aborted
+ return;
+
+ deviceAPILevel = info.sdk;
+ QString deviceSerialNumber = info.serialNumber;
+
+ if (info.type == AndroidDeviceInfo::Emulator) {
+ deviceSerialNumber = AndroidConfigurations::instance().startAVD(deviceSerialNumber, deviceAPILevel, targetArch);
+ if (deviceSerialNumber.isEmpty())
+ Core::MessageManager::write(tr("Starting android virtual device failed."));
+ }
+
+ QProcess *process = new QProcess();
+ QStringList arguments = AndroidDeviceInfo::adbSelector(deviceSerialNumber);
+ arguments << QLatin1String("shell") << QLatin1String("rm") << QLatin1String("-r") << QLatin1String("/data/local/tmp/qt");
+ process->connect(process, SIGNAL(finished(int)), process, SLOT(deleteLater()));
+ const QString adb = AndroidConfigurations::instance().adbToolPath().toString();
+ Core::MessageManager::write(adb + QLatin1Char(' ') + arguments.join(QLatin1String(" ")));
+ process->start(adb, arguments);
+ if (!process->waitForStarted(500))
+ delete process;
+}
+
+void AndroidManager::installQASIPackage(ProjectExplorer::Target *target, const QString &packagePath)
+{
+ const QString targetArch = AndroidManager::targetArch(target);
+ int deviceAPILevel = AndroidManager::minimumSDK(target);
+ AndroidDeviceInfo info = AndroidConfigurations::instance().showDeviceDialog(target->project(), deviceAPILevel, targetArch);
+ if (info.serialNumber.isEmpty()) // aborted
+ return;
+
+ deviceAPILevel = info.sdk;
+ QString deviceSerialNumber = info.serialNumber;
+ if (info.type == AndroidDeviceInfo::Emulator) {
+ deviceSerialNumber = AndroidConfigurations::instance().startAVD(deviceSerialNumber, deviceAPILevel, targetArch);
+ if (deviceSerialNumber.isEmpty())
+ Core::MessageManager::write(tr("Starting android virtual device failed."));
+ }
+
+ QProcess *process = new QProcess();
+ QStringList arguments = AndroidDeviceInfo::adbSelector(deviceSerialNumber);
+ arguments << QLatin1String("install") << QLatin1String("-r ") << packagePath;
+
+ process->connect(process, SIGNAL(finished(int)), process, SLOT(deleteLater()));
+ const QString adb = AndroidConfigurations::instance().adbToolPath().toString();
+ Core::MessageManager::write(adb + QLatin1Char(' ') + arguments.join(QLatin1String(" ")));
+ process->start(adb, arguments);
+ if (!process->waitForFinished(500))
+ delete process;
+
+}
+
+bool AndroidManager::checkKeystorePassword(const QString &keystorePath, const QString &keystorePasswd)
+{
+ if (keystorePasswd.isEmpty())
+ return false;
+ QStringList arguments;
+ arguments << QLatin1String("-list")
+ << QLatin1String("-keystore")
+ << keystorePath
+ << QLatin1String("--storepass")
+ << keystorePasswd;
+ QProcess proc;
+ proc.start(AndroidConfigurations::instance().keytoolPath().toString(), arguments);
+ if (!proc.waitForStarted(500))
+ return false;
+ if (!proc.waitForFinished(500)) {
+ proc.kill();
+ proc.waitForFinished();
+ return false;
+ }
+ return proc.exitCode() == 0;
+}
+
+bool AndroidManager::checkCertificatePassword(const QString &keystorePath, const QString &keystorePasswd, const QString &alias, const QString &certificatePasswd)
+{
+ // assumes that the keystore password is correct
+ QStringList arguments;
+ arguments << QLatin1String("-certreq")
+ << QLatin1String("-keystore")
+ << keystorePath
+ << QLatin1String("--storepass")
+ << keystorePasswd
+ << QLatin1String("-alias")
+ << alias
+ << QLatin1String("-keypass");
+ if (certificatePasswd.isEmpty())
+ arguments << keystorePasswd;
+ else
+ arguments << certificatePasswd;
+
+ QProcess proc;
+ proc.start(AndroidConfigurations::instance().keytoolPath().toString(), arguments);
+ if (!proc.waitForStarted(500))
+ return false;
+ if (!proc.waitForFinished(500)) {
+ proc.kill();
+ proc.waitForFinished();
+ return false;
+ }
+ return proc.exitCode() == 0;
+}
+
+bool AndroidManager::checkForQt51Files(const QString &projectDirectory)
+{
+ Utils::FileName fileName = Utils::FileName::fromString(projectDirectory);
+ fileName.appendPath(QLatin1String("android")).appendPath(QLatin1String("version.xml"));
+ if (!fileName.toFileInfo().exists())
+ return false;
+ QDomDocument dstVersionDoc;
+ if (!AndroidManager::openXmlFile(dstVersionDoc, fileName))
+ return false;
+ return dstVersionDoc.documentElement().attribute(QLatin1String("value")).toDouble() < 5.2;
+}
+
} // namespace Internal
} // namespace Qt4ProjectManager
diff --git a/src/plugins/android/androidmanager.h b/src/plugins/android/androidmanager.h
index 4d454adbfc..df81322e53 100644
--- a/src/plugins/android/androidmanager.h
+++ b/src/plugins/android/androidmanager.h
@@ -33,6 +33,7 @@
#include <utils/fileutils.h>
#include <QDomDocument>
+#include <QPair>
#include <QObject>
#include <QStringList>
@@ -71,9 +72,12 @@ public:
static bool updateDeploymentSettings(ProjectExplorer::Target *target);
static bool bundleQt(ProjectExplorer::Target *target);
+ static bool useLocalLibs(ProjectExplorer::Target *target);
+ static QString deviceSerialNumber(ProjectExplorer::Target *target);
- static QString targetSDK(ProjectExplorer::Target *target);
- static bool setTargetSDK(ProjectExplorer::Target *target, const QString &sdk);
+ static QString buildTargetSDK(ProjectExplorer::Target *target);
+ static bool setBuildTargetSDK(ProjectExplorer::Target *target, const QString &sdk);
+ static int minimumSDK(ProjectExplorer::Target *target);
static QString targetArch(ProjectExplorer::Target *target);
@@ -86,7 +90,7 @@ public:
static Utils::FileName apkPath(ProjectExplorer::Target *target, BuildType buildType);
static bool createAndroidTemplatesIfNecessary(ProjectExplorer::Target *target);
- static void updateTarget(ProjectExplorer::Target *target, const QString &targetSDK,
+ static void updateTarget(ProjectExplorer::Target *target, const QString &buildTargetSDK,
const QString &name = QString());
static Utils::FileName localLibsRulesFilePath(ProjectExplorer::Target *target);
@@ -95,6 +99,9 @@ public:
static QString loadLocalBundledFiles(ProjectExplorer::Target *target, int apiLevel = -1);
static QString loadLocalJarsInitClasses(ProjectExplorer::Target *target, int apiLevel = -1);
+ static QPair<int, int> apiLevelRange(ProjectExplorer::Target *target);
+ static QString androidNameForApiLevel(int x);
+
class Library
{
public:
@@ -123,6 +130,12 @@ public:
static QString libGnuStl(const QString &arch, const QString &ndkToolChainVersion);
static QString libraryPrefix();
+ static void cleanLibsOnDevice(ProjectExplorer::Target *target);
+ static void installQASIPackage(ProjectExplorer::Target *target, const QString &packagePath);
+
+ static bool checkKeystorePassword(const QString &keystorePath, const QString &keystorePasswd);
+ static bool checkCertificatePassword(const QString &keystorePath, const QString &keystorePasswd, const QString &alias, const QString &certificatePasswd);
+ static bool checkForQt51Files(const QString &projectDirectory);
private:
static void raiseError(const QString &reason);
static bool openXmlFile(QDomDocument &doc, const Utils::FileName &fileName);
diff --git a/src/plugins/android/androidmanifestdocument.cpp b/src/plugins/android/androidmanifestdocument.cpp
index bf93f1cba5..dc6468742a 100644
--- a/src/plugins/android/androidmanifestdocument.cpp
+++ b/src/plugins/android/androidmanifestdocument.cpp
@@ -54,13 +54,13 @@ bool AndroidManifestDocument::save(QString *errorString, const QString &fileName
QString AndroidManifestDocument::defaultPath() const
{
- QFileInfo fi(fileName());
+ QFileInfo fi(filePath());
return fi.absolutePath();
}
QString AndroidManifestDocument::suggestedFileName() const
{
- QFileInfo fi(fileName());
+ QFileInfo fi(filePath());
return fi.fileName();
}
diff --git a/src/plugins/android/androidmanifesteditor.cpp b/src/plugins/android/androidmanifesteditor.cpp
index 4b5b340bb1..5f1bc1e8a3 100644
--- a/src/plugins/android/androidmanifesteditor.cpp
+++ b/src/plugins/android/androidmanifesteditor.cpp
@@ -73,11 +73,6 @@ Core::Id AndroidManifestEditor::id() const
return Constants::ANDROID_MANIFEST_EDITOR_ID;
}
-bool AndroidManifestEditor::isTemporary() const
-{
- return false;
-}
-
void AndroidManifestEditor::changeEditorPage(QAction *action)
{
AndroidManifestEditorWidget *editorWidget = static_cast<AndroidManifestEditorWidget *>(widget());
diff --git a/src/plugins/android/androidmanifesteditor.h b/src/plugins/android/androidmanifesteditor.h
index b6073d9005..a51acefe1b 100644
--- a/src/plugins/android/androidmanifesteditor.h
+++ b/src/plugins/android/androidmanifesteditor.h
@@ -51,7 +51,6 @@ public:
explicit AndroidManifestEditor(AndroidManifestEditorWidget *editorWidget);
Core::Id id() const;
- bool isTemporary() const;
private slots:
void changeEditorPage(QAction *action);
diff --git a/src/plugins/android/androidmanifesteditorfactory.cpp b/src/plugins/android/androidmanifesteditorfactory.cpp
index 965ca6af0d..ba80296bd7 100644
--- a/src/plugins/android/androidmanifesteditorfactory.cpp
+++ b/src/plugins/android/androidmanifesteditorfactory.cpp
@@ -44,26 +44,14 @@ AndroidManifestEditorFactory::AndroidManifestEditorFactory(QObject *parent)
: Core::IEditorFactory(parent),
m_actionHandler(new TextEditor::TextEditorActionHandler(Constants::ANDROID_MANIFEST_EDITOR_CONTEXT))
{
-}
-
-QStringList AndroidManifestEditorFactory::mimeTypes() const
-{
- return QStringList() << QLatin1String(Constants::ANDROID_MANIFEST_MIME_TYPE);
-}
-
-Core::Id AndroidManifestEditorFactory::id() const
-{
- return Constants::ANDROID_MANIFEST_EDITOR_ID;
-}
-
-QString AndroidManifestEditorFactory::displayName() const
-{
- return tr("Android Manifest editor");
+ setId(Constants::ANDROID_MANIFEST_EDITOR_ID);
+ setDisplayName(tr("Android Manifest editor"));
+ addMimeType(Constants::ANDROID_MANIFEST_MIME_TYPE);
}
Core::IEditor *AndroidManifestEditorFactory::createEditor(QWidget *parent)
{
AndroidManifestEditorWidget *editor = new AndroidManifestEditorWidget(parent, m_actionHandler);
- TextEditor::TextEditorSettings::instance()->initializeEditor(editor);
+ TextEditor::TextEditorSettings::initializeEditor(editor);
return editor->editor();
}
diff --git a/src/plugins/android/androidmanifesteditorfactory.h b/src/plugins/android/androidmanifesteditorfactory.h
index 1c1470c108..3a1fa07844 100644
--- a/src/plugins/android/androidmanifesteditorfactory.h
+++ b/src/plugins/android/androidmanifesteditorfactory.h
@@ -40,14 +40,12 @@ namespace Internal {
class AndroidManifestEditorFactory : public Core::IEditorFactory
{
Q_OBJECT
+
public:
explicit AndroidManifestEditorFactory(QObject *parent = 0);
- QStringList mimeTypes() const;
- Core::Id id() const;
- QString displayName() const;
-
Core::IEditor *createEditor(QWidget *parent);
+
private:
TextEditor::TextEditorActionHandler *m_actionHandler;
};
diff --git a/src/plugins/android/androidmanifesteditorwidget.cpp b/src/plugins/android/androidmanifesteditorwidget.cpp
index 3737519e9e..751e703e15 100644
--- a/src/plugins/android/androidmanifesteditorwidget.cpp
+++ b/src/plugins/android/androidmanifesteditorwidget.cpp
@@ -31,13 +31,20 @@
#include "androidmanifesteditor.h"
#include "androidconstants.h"
#include "androidmanifestdocument.h"
+#include "androidmanager.h"
#include <coreplugin/icore.h>
#include <coreplugin/infobar.h>
#include <texteditor/plaintexteditor.h>
+#include <projectexplorer/project.h>
#include <projectexplorer/projectwindow.h>
#include <projectexplorer/iprojectproperties.h>
+#include <projectexplorer/session.h>
+#include <projectexplorer/target.h>
+#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/kitinformation.h>
#include <texteditor/texteditoractionhandler.h>
+#include <qt4projectmanager/qt4project.h>
#include <QLineEdit>
#include <QFileInfo>
@@ -58,6 +65,10 @@
#include <QFileDialog>
#include <QTimer>
+using namespace ProjectExplorer;
+using namespace Android;
+using namespace Android::Internal;
+
namespace {
const QLatin1String packageNameRegExp("^([a-z_]{1}[a-z0-9_]+(\\.[a-zA-Z_]{1}[a-zA-Z0-9_]*)*)$");
const char infoBarId[] = "Android.AndroidManifestEditor.InfoBar";
@@ -67,11 +78,22 @@ bool checkPackageName(const QString &packageName)
{
return QRegExp(packageNameRegExp).exactMatch(packageName);
}
-} // anonymous namespace
+Project *androidProject(const QString &file)
+{
+ Utils::FileName fileName = Utils::FileName::fromString(file);
+ foreach (Project *project, SessionManager::projects()) {
+ if (!project->activeTarget())
+ continue;
+ Kit *kit = project->activeTarget()->kit();
+ if (DeviceTypeKitInformation::deviceTypeId(kit) == Android::Constants::ANDROID_DEVICE_TYPE
+ && fileName.isChildOf(Utils::FileName::fromString(project->projectDirectory())))
+ return project;
+ }
+ return 0;
+}
-using namespace Android;
-using namespace Android::Internal;
+} // anonymous namespace
AndroidManifestEditorWidget::AndroidManifestEditorWidget(QWidget *parent, TextEditor::TextEditorActionHandler *ah)
: TextEditor::PlainTextEditorWidget(parent),
@@ -107,6 +129,7 @@ TextEditor::BaseTextEditor *AndroidManifestEditorWidget::createEditor()
return new AndroidManifestEditor(this);
}
+
void AndroidManifestEditorWidget::initializePage()
{
QWidget *mainWidget = new QWidget(this);
@@ -137,7 +160,7 @@ void AndroidManifestEditorWidget::initializePage()
"with levels in the hierarchy separated by periods (.) (pronounced \"dot\").</p>"
"<p align=\"justify\">In general, a package name begins with the top level domain name"
" of the organization and then the organization's domain and then any subdomains listed"
- "in reverse order. The organization can then choose a specific name for their package."
+ " in reverse order. The organization can then choose a specific name for their package."
" Package names should be all lowercase characters whenever possible.</p>"
"<p align=\"justify\">Complete conventions for disambiguating package names and rules for"
" naming packages when the Internet domain name cannot be directly used as a package name"
@@ -170,6 +193,21 @@ void AndroidManifestEditorWidget::initializePage()
m_versionNameLinedit = new QLineEdit(packageGroupBox);
formLayout->addRow(tr("Version name:"), m_versionNameLinedit);
+ m_androidMinSdkVersion = new QComboBox(packageGroupBox);
+ m_androidMinSdkVersion->setToolTip(
+ tr("Sets the minimum required version on which this application can be run."));
+ m_androidMinSdkVersion->addItem(tr("Not set"), 0);
+
+ formLayout->addRow(tr("Minimum required SDK:"), m_androidMinSdkVersion);
+
+ m_androidTargetSdkVersion = new QComboBox(packageGroupBox);
+ m_androidTargetSdkVersion->setToolTip(
+ tr("Sets the targe SDK, set this to the highest tested version."
+ "This disables compatibility behavior of the system for your application."));
+ m_androidTargetSdkVersion->addItem(tr("Not set"), 0);
+
+ formLayout->addRow(tr("Target SDK:"), m_androidTargetSdkVersion);
+
packageGroupBox->setLayout(formLayout);
connect(m_packageNameLineEdit, SIGNAL(textEdited(QString)),
@@ -178,6 +216,10 @@ void AndroidManifestEditorWidget::initializePage()
this, SLOT(setDirty()));
connect(m_versionNameLinedit, SIGNAL(textEdited(QString)),
this, SLOT(setDirty()));
+ connect(m_androidMinSdkVersion, SIGNAL(currentIndexChanged(int)),
+ this, SLOT(setDirty()));
+ connect(m_androidTargetSdkVersion, SIGNAL(currentIndexChanged(int)),
+ this, SLOT(setDirty()));
}
@@ -192,7 +234,10 @@ void AndroidManifestEditorWidget::initializePage()
m_appNameLineEdit = new QLineEdit(applicationGroupBox);
formLayout->addRow(tr("Application name:"), m_appNameLineEdit);
- m_targetLineEdit = new QLineEdit(applicationGroupBox);
+ m_targetLineEdit = new QComboBox(applicationGroupBox);
+ m_targetLineEdit->setEditable(true);
+ m_targetLineEdit->setDuplicatesEnabled(true);
+ m_targetLineEdit->installEventFilter(this);
formLayout->addRow(tr("Run:"), m_targetLineEdit);
QHBoxLayout *iconLayout = new QHBoxLayout();
@@ -224,7 +269,7 @@ void AndroidManifestEditorWidget::initializePage()
connect(m_appNameLineEdit, SIGNAL(textEdited(QString)),
this, SLOT(setAppName()));
- connect(m_targetLineEdit, SIGNAL(textEdited(QString)),
+ connect(m_targetLineEdit, SIGNAL(currentTextChanged(QString)),
this, SLOT(setDirty()));
connect(m_lIconButton, SIGNAL(clicked()), SLOT(setLDPIIcon()));
@@ -407,6 +452,41 @@ void AndroidManifestEditorWidget::initializePage()
m_overlayWidget = mainWidget;
}
+bool AndroidManifestEditorWidget::eventFilter(QObject *obj, QEvent *event)
+{
+ if (obj == m_targetLineEdit) {
+ if (event->type() == QEvent::FocusIn) {
+ QTimer::singleShot(0, this, SLOT(updateTargetComboBox()));
+ }
+ }
+
+ return TextEditor::PlainTextEditorWidget::eventFilter(obj, event);
+}
+
+void AndroidManifestEditorWidget::updateTargetComboBox()
+{
+ const QString docPath(static_cast<AndroidManifestDocument *>(editor()->document())->filePath());
+ ProjectExplorer::Project *project = androidProject(docPath);
+ QStringList items;
+ if (project) {
+ ProjectExplorer::Kit *kit = project->activeTarget()->kit();
+ if (ProjectExplorer::DeviceTypeKitInformation::deviceTypeId(kit) == Constants::ANDROID_DEVICE_TYPE)
+ items = AndroidManager::availableTargetApplications(project->activeTarget());
+ }
+
+ // QComboBox randomly resets what the user has entered
+ // if all rows are removed, thus we ensure that the current text
+ // is not removed by first adding it and then removing all old rows
+ // and then adding the new rows
+ QString text = m_targetLineEdit->currentText();
+ m_targetLineEdit->addItem(text);
+ while (m_targetLineEdit->count() > 1)
+ m_targetLineEdit->removeItem(0);
+ items.removeDuplicates();
+ items.removeAll(text);
+ m_targetLineEdit->addItems(items);
+}
+
void AndroidManifestEditorWidget::resizeEvent(QResizeEvent *event)
{
PlainTextEditorWidget::resizeEvent(event);
@@ -434,6 +514,7 @@ bool AndroidManifestEditorWidget::open(QString *errorString, const QString &file
}
// some error occured
updateInfoBar(error, errorLine, errorColumn);
+ updateSdkVersions();
setActivePage(Source);
return true;
@@ -500,7 +581,7 @@ void AndroidManifestEditorWidget::preSave()
syncToEditor();
if (m_setAppName) {
- QString baseDir = QFileInfo(static_cast<AndroidManifestDocument *>(editor()->document())->fileName()).absolutePath();
+ QString baseDir = QFileInfo(static_cast<AndroidManifestDocument *>(editor()->document())->filePath()).absolutePath();
QString fileName = baseDir + QLatin1String("/res/values/strings.xml");
QFile f(fileName);
if (f.open(QIODevice::ReadOnly)) {
@@ -524,7 +605,7 @@ void AndroidManifestEditorWidget::preSave()
m_setAppName = false;
}
- QString baseDir = QFileInfo(static_cast<AndroidManifestDocument *>(editor()->document())->fileName()).absolutePath();
+ QString baseDir = QFileInfo(static_cast<AndroidManifestDocument *>(editor()->document())->filePath()).absolutePath();
if (!m_lIconPath.isEmpty()) {
copyIcon(LowDPI, baseDir, m_lIconPath);
m_lIconPath.clear();
@@ -569,7 +650,7 @@ bool AndroidManifestEditorWidget::checkDocument(QDomDocument doc, QString *error
return false;
} else if (manifest.firstChildElement(QLatin1String("application")).firstChildElement(QLatin1String("activity")).isNull()) {
// missing either application or activity element
- *errorMessage = tr("The structure of the android manifest file is corrupt. Expected a 'application' and 'activity' sub node.");
+ *errorMessage = tr("The structure of the Android manifest file is corrupt. Expected an 'application' and 'activity' sub node.");
*errorLine = -1;
*errorColumn = -1;
return false;
@@ -606,6 +687,23 @@ void AndroidManifestEditorWidget::updateInfoBar()
updateInfoBar(errorMessage, errorLine, errorColumn);
}
+void AndroidManifestEditorWidget::updateSdkVersions()
+{
+ const QString docPath(static_cast<AndroidManifestDocument *>(editor()->document())->filePath());
+ QPair<int, int> apiLevels = AndroidManager::apiLevelRange(androidProject(docPath)->activeTarget());
+ for (int i = apiLevels.first; i < apiLevels.second + 1; ++i)
+ m_androidMinSdkVersion->addItem(tr("API %1: %2")
+ .arg(i)
+ .arg(AndroidManager::androidNameForApiLevel(i)),
+ i);
+
+ for (int i = apiLevels.first; i < apiLevels.second + 1; ++i)
+ m_androidTargetSdkVersion->addItem(tr("API %1: %2")
+ .arg(i)
+ .arg(AndroidManager::androidNameForApiLevel(i)),
+ i);
+}
+
void AndroidManifestEditorWidget::updateInfoBar(const QString &errorMessage, int line, int column)
{
Core::InfoBar *infoBar = editorDocument()->infoBar();
@@ -636,6 +734,23 @@ void AndroidManifestEditorWidget::gotoError()
gotoLine(m_errorLine, m_errorColumn);
}
+void setApiLevel(QComboBox *box, const QDomElement &element, const QString &attribute)
+{
+ if (!element.isNull() && element.hasAttribute(attribute)) {
+ bool ok;
+ int tmp = element.attribute(attribute).toInt(&ok);
+ if (ok) {
+ int index = box->findData(tmp);
+ if (index != -1) {
+ box->setCurrentIndex(index);
+ return;
+ }
+ }
+ }
+ int index = box->findData(0);
+ box->setCurrentIndex(index);
+}
+
void AndroidManifestEditorWidget::syncToWidgets(const QDomDocument &doc)
{
m_stayClean = true;
@@ -644,7 +759,11 @@ void AndroidManifestEditorWidget::syncToWidgets(const QDomDocument &doc)
m_versionCode->setValue(manifest.attribute(QLatin1String("android:versionCode")).toInt());
m_versionNameLinedit->setText(manifest.attribute(QLatin1String("android:versionName")));
- QString baseDir = QFileInfo(static_cast<AndroidManifestDocument *>(editor()->document())->fileName()).absolutePath();
+ QDomElement usesSdkElement = manifest.firstChildElement(QLatin1String("uses-sdk"));
+ setApiLevel(m_androidMinSdkVersion, usesSdkElement, QLatin1String("android:minSdkVersion"));
+ setApiLevel(m_androidTargetSdkVersion, usesSdkElement, QLatin1String("android:targetSdkVersion"));
+
+ QString baseDir = QFileInfo(static_cast<AndroidManifestDocument *>(editor()->document())->filePath()).absolutePath();
QString fileName = baseDir + QLatin1String("/res/values/strings.xml");
QFile f(fileName);
@@ -665,7 +784,7 @@ void AndroidManifestEditorWidget::syncToWidgets(const QDomDocument &doc)
QDomElement metadataElem = manifest.firstChildElement(QLatin1String("application")).firstChildElement(QLatin1String("activity")).firstChildElement(QLatin1String("meta-data"));
while (!metadataElem.isNull()) {
if (metadataElem.attribute(QLatin1String("android:name")) == QLatin1String("android.app.lib_name")) {
- m_targetLineEdit->setText(metadataElem.attribute(QLatin1String("android:value")));
+ m_targetLineEdit->setEditText(metadataElem.attribute(QLatin1String("android:value")));
break;
}
metadataElem = metadataElem.nextSiblingElement(QLatin1String("meta-data"));
@@ -692,6 +811,53 @@ void AndroidManifestEditorWidget::syncToWidgets(const QDomDocument &doc)
m_dirty = false;
}
+void setUsesSdk(QDomDocument &doc, QDomElement &manifest, int minimumSdk, int targetSdk)
+{
+ QDomElement usesSdk = manifest.firstChildElement(QLatin1String("uses-sdk"));
+ if (usesSdk.isNull()) { // doesn't exist yet
+ if (minimumSdk == 0 && targetSdk == 0) {
+ // and doesn't need to exist
+ } else {
+ usesSdk = doc.createElement(QLatin1String("uses-sdk"));
+ if (minimumSdk != 0)
+ usesSdk.setAttribute(QLatin1String("android:minSdkVersion"), minimumSdk);
+ if (targetSdk != 0)
+ usesSdk.setAttribute(QLatin1String("android:targetSdkVersion"), targetSdk);
+ manifest.appendChild(usesSdk);
+ }
+ } else {
+ if (minimumSdk == 0 && targetSdk == 0) {
+ // We might be able to remove the whole element
+ // check if there are other attributes
+ QDomNamedNodeMap usesSdkAttributes = usesSdk.attributes();
+ bool keepNode = false;
+ for (int i = 0; i < usesSdkAttributes.size(); ++i) {
+ if (usesSdkAttributes.item(i).nodeName() != QLatin1String("android:minSdkVersion")
+ && usesSdkAttributes.item(i).nodeName() != QLatin1String("android:targetSdkVersion")) {
+ keepNode = true;
+ break;
+ }
+ }
+ if (keepNode) {
+ usesSdk.removeAttribute(QLatin1String("android:minSdkVersion"));
+ usesSdk.removeAttribute(QLatin1String("android:targetSdkVersion"));
+ } else {
+ manifest.removeChild(usesSdk);
+ }
+ } else {
+ if (minimumSdk == 0)
+ usesSdk.removeAttribute(QLatin1String("android:minSdkVersion"));
+ else
+ usesSdk.setAttribute(QLatin1String("android:minSdkVersion"), minimumSdk);
+
+ if (targetSdk == 0)
+ usesSdk.removeAttribute(QLatin1String("android:targetSdkVersion"));
+ else
+ usesSdk.setAttribute(QLatin1String("android:targetSdkVersion"), targetSdk);
+ }
+ }
+}
+
void AndroidManifestEditorWidget::syncToEditor()
{
QDomDocument doc;
@@ -706,7 +872,12 @@ void AndroidManifestEditorWidget::syncToEditor()
manifest.setAttribute(QLatin1String("android:versionCode"), m_versionCode->value());
manifest.setAttribute(QLatin1String("android:versionName"), m_versionNameLinedit->text());
- setAndroidAppLibName(doc, manifest.firstChildElement(QLatin1String("application")).firstChildElement(QLatin1String("activity")), m_targetLineEdit->text());
+ setUsesSdk(doc, manifest, m_androidMinSdkVersion->currentText().toInt(),
+ m_androidTargetSdkVersion->currentText().toInt());
+
+ setAndroidAppLibName(doc, manifest.firstChildElement(QLatin1String("application"))
+ .firstChildElement(QLatin1String("activity")),
+ m_targetLineEdit->currentText());
// permissions
QDomElement permissionElem = manifest.firstChildElement(QLatin1String("uses-permission"));
diff --git a/src/plugins/android/androidmanifesteditorwidget.h b/src/plugins/android/androidmanifesteditorwidget.h
index b47d2d4239..72c3d3a4ee 100644
--- a/src/plugins/android/androidmanifesteditorwidget.h
+++ b/src/plugins/android/androidmanifesteditorwidget.h
@@ -103,7 +103,7 @@ public slots:
protected:
TextEditor::BaseTextEditor *createEditor();
void resizeEvent(QResizeEvent *event);
-
+ bool eventFilter(QObject *obj, QEvent *event);
private slots:
void setLDPIIcon();
void setMDPIIcon();
@@ -115,6 +115,7 @@ private slots:
void setPackageName();
void gotoError();
void updateInfoBar();
+ void updateSdkVersions();
void startParseCheck();
void delayedParseCheck();
private:
@@ -132,6 +133,7 @@ private:
void updateInfoBar(const QString &errorMessage, int line, int column);
void hideInfoBar();
+ Q_SLOT void updateTargetComboBox();
bool m_dirty; // indicates that we need to call syncToEditor()
bool m_stayClean;
@@ -144,10 +146,12 @@ private:
QLabel *m_packageNameWarning;
QSpinBox *m_versionCode;
QLineEdit *m_versionNameLinedit;
+ QComboBox *m_androidMinSdkVersion;
+ QComboBox *m_androidTargetSdkVersion;
// Application
QLineEdit *m_appNameLineEdit;
- QLineEdit *m_targetLineEdit;
+ QComboBox *m_targetLineEdit;
QToolButton *m_lIconButton;
QToolButton *m_mIconButton;
QToolButton *m_hIconButton;
diff --git a/src/plugins/android/androidpackagecreationstep.cpp b/src/plugins/android/androidpackagecreationstep.cpp
index 651cba1c84..26d4f70306 100644
--- a/src/plugins/android/androidpackagecreationstep.cpp
+++ b/src/plugins/android/androidpackagecreationstep.cpp
@@ -36,6 +36,7 @@
#include "androidmanager.h"
#include "androidgdbserverkitinformation.h"
#include "androidtoolchain.h"
+#include "certificatesmodel.h"
#include <projectexplorer/buildsteplist.h>
#include <projectexplorer/projectexplorerconstants.h>
@@ -66,53 +67,13 @@ namespace Internal {
namespace {
const QLatin1String KeystoreLocationKey("KeystoreLocation");
+ const QLatin1String SignPackageKey("SignPackage");
const QLatin1String AliasString("Alias name:");
const QLatin1String CertificateSeparator("*******************************************");
}
using namespace Qt4ProjectManager;
-class CertificatesModel: public QAbstractListModel
-{
-public:
- CertificatesModel(const QString &rowCertificates, QObject *parent)
- : QAbstractListModel(parent)
- {
- int from = rowCertificates.indexOf(AliasString);
- QPair<QString, QString> item;
- while (from > -1) {
- from += 11;// strlen(AliasString);
- const int eol = rowCertificates.indexOf(QLatin1Char('\n'), from);
- item.first = rowCertificates.mid(from, eol - from).trimmed();
- const int eoc = rowCertificates.indexOf(CertificateSeparator, eol);
- item.second = rowCertificates.mid(eol + 1, eoc - eol - 2).trimmed();
- from = rowCertificates.indexOf(AliasString, eoc);
- m_certs.push_back(item);
- }
- }
-
-protected:
- int rowCount(const QModelIndex &parent = QModelIndex()) const
- {
- if (parent.isValid())
- return 0;
- return m_certs.size();
- }
-
- QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const
- {
- if (!index.isValid() || (role != Qt::DisplayRole && role != Qt::ToolTipRole))
- return QVariant();
- if (role == Qt::DisplayRole)
- return m_certs[index.row()].first;
- return m_certs[index.row()].second;
- }
-
-private:
- QVector<QPair<QString, QString> > m_certs;
-};
-
-
AndroidPackageCreationStep::AndroidPackageCreationStep(BuildStepList *bsl)
: BuildStep(bsl, CreatePackageId)
{
@@ -131,6 +92,7 @@ void AndroidPackageCreationStep::ctor()
setDefaultDisplayName(tr("Packaging for Android"));
m_openPackageLocation = true;
m_bundleQt = false;
+ m_signPackage = false;
connect(&m_outputParser, SIGNAL(addTask(ProjectExplorer::Task)), this, SIGNAL(addTask(ProjectExplorer::Task)));
}
@@ -156,15 +118,15 @@ bool AndroidPackageCreationStep::init()
Utils::FileName androidLibPath = path.appendPath(QLatin1String("libs/") + androidTargetArch);
m_gdbServerDestination = androidLibPath.appendPath(QLatin1String("gdbserver"));
m_gdbServerSource = AndroidGdbServerKitInformation::gdbServer(target()->kit());
- m_debugBuild = bc->qmakeBuildConfiguration() & QtSupport::BaseQtVersion::DebugBuild;
if (!AndroidManager::createAndroidTemplatesIfNecessary(target()))
return false;
- AndroidManager::updateTarget(target(), AndroidManager::targetSDK(target()), AndroidManager::applicationName(target()));
+ AndroidManager::updateTarget(target(), AndroidManager::buildTargetSDK(target()), AndroidManager::applicationName(target()));
m_antToolPath = AndroidConfigurations::instance().antToolPath();
m_apkPathUnsigned = AndroidManager::apkPath(target(), AndroidManager::ReleaseBuildUnsigned);
m_apkPathSigned = AndroidManager::apkPath(target(), AndroidManager::ReleaseBuildSigned);
+ m_signPackageForRun = m_signPackage;
m_keystorePathForRun = m_keystorePath;
m_certificatePasswdForRun = m_certificatePasswd;
m_jarSigner = AndroidConfigurations::instance().jarsignerPath();
@@ -176,6 +138,10 @@ bool AndroidPackageCreationStep::init()
return false;
initCheckRequiredLibrariesForRun();
+
+ if (m_signPackage && (bc->qmakeBuildConfiguration() & QtSupport::BaseQtVersion::DebugBuild))
+ emit addOutput(tr("Warning: Signing a debug package."), BuildStep::ErrorMessageOutput);
+
return true;
}
@@ -418,11 +384,22 @@ QAbstractItemModel *AndroidPackageCreationStep::keystoreCertificates()
return new CertificatesModel(rawCerts, this);
}
+bool AndroidPackageCreationStep::signPackage() const
+{
+ return m_signPackage;
+}
+
+void AndroidPackageCreationStep::setSignPackage(bool b)
+{
+ m_signPackage = b;
+}
+
bool AndroidPackageCreationStep::fromMap(const QVariantMap &map)
{
if (!BuildStep::fromMap(map))
return false;
m_keystorePath = Utils::FileName::fromString(map.value(KeystoreLocationKey).toString());
+ m_signPackage = map.value(SignPackageKey).toBool();
return true;
}
@@ -430,6 +407,7 @@ QVariantMap AndroidPackageCreationStep::toMap() const
{
QVariantMap map(BuildStep::toMap());
map.insert(KeystoreLocationKey, m_keystorePath.toString());
+ map.insert(SignPackageKey, m_signPackage);
return map;
}
@@ -560,7 +538,7 @@ void AndroidPackageCreationStep::collectFiles(QList<DeployItem> *deployList,
}
}
-void AndroidPackageCreationStep::removeManagedFilesFromPackage()
+void AndroidPackageCreationStep::removeManagedFilesFromPackage(const Utils::FileName &qtLibraryDir)
{
// Clean up all files managed by Qt Creator
{
@@ -574,6 +552,12 @@ void AndroidPackageCreationStep::removeManagedFilesFromPackage()
&& dirIt.fileName().startsWith(QLatin1String("libQt5"))
&& dirIt.fileName().endsWith(QLatin1String(".so"));
+ if (isQtLibrary) {
+ Utils::FileName qtLibraryFile = qtLibraryDir;
+ qtLibraryFile.appendPath(dirIt.fileName());
+ isQtLibrary = qtLibraryFile.toFileInfo().exists();
+ }
+
if (dirIt.filePath().contains(AndroidManager::libraryPrefix()) || isQtLibrary)
QFile::remove(dirIt.filePath());
}
@@ -629,9 +613,12 @@ bool AndroidPackageCreationStep::createPackage()
emit addOutput(tr("Copy Qt app & libs to Android package ..."), MessageOutput);
QStringList build;
+ build << QLatin1String("-quiet");
build << QLatin1String("clean");
QFile::remove(m_gdbServerDestination.toString());
- if (m_debugBuild || !m_certificateAlias.length()) {
+ if (m_signPackageForRun) {
+ build << QLatin1String("release");
+ } else {
build << QLatin1String("debug");
QDir dir;
dir.mkpath(m_gdbServerDestination.toFileInfo().absolutePath());
@@ -640,8 +627,6 @@ bool AndroidPackageCreationStep::createPackage()
.arg(m_gdbServerDestination.toUserOutput()));
return false;
}
- } else {
- build << QLatin1String("release");
}
QList<DeployItem> deployFiles;
@@ -659,7 +644,7 @@ bool AndroidPackageCreationStep::createPackage()
collectFiles(&deployFiles, &importsAndPlugins);
// Remove files from package if they are not needed
- removeManagedFilesFromPackage();
+ removeManagedFilesFromPackage(version->libraryPath());
// Deploy files to package
if (bundleQt) {
@@ -705,7 +690,7 @@ bool AndroidPackageCreationStep::createPackage()
return false;
}
- if (!(m_debugBuild) && m_certificateAlias.length()) {
+ if (m_signPackageForRun) {
emit addOutput(tr("Signing package ..."), MessageOutput);
while (true) {
if (m_certificatePasswdForRun.isEmpty())
@@ -719,7 +704,9 @@ bool AndroidPackageCreationStep::createPackage()
QByteArray keyPass = m_certificatePasswdForRun.toUtf8();
build.clear();
- build << QLatin1String("-verbose") << QLatin1String("-keystore") << m_keystorePathForRun.toUserOutput()
+ build << QLatin1String("-verbose") << QLatin1String("-digestalg") << QLatin1String("SHA1")
+ << QLatin1String("-sigalg") << QLatin1String("MD5withRSA")
+ << QLatin1String("-keystore") << m_keystorePathForRun.toUserOutput()
<< QLatin1String("-storepass") << m_keystorePasswd
<< m_apkPathUnsigned.toUserOutput()
<< m_certificateAlias;
@@ -881,7 +868,7 @@ void AndroidPackageCreationStep::certificatePassword()
void AndroidPackageCreationStep::showInGraphicalShell()
{
- Core::FileUtils::showInGraphicalShell(Core::ICore::instance()->mainWindow(), m_apkPathSigned.toString());
+ Core::FileUtils::showInGraphicalShell(Core::ICore::mainWindow(), m_apkPathSigned.toString());
}
void AndroidPackageCreationStep::raiseError(const QString &shortMsg,
@@ -889,7 +876,7 @@ void AndroidPackageCreationStep::raiseError(const QString &shortMsg,
{
emit addOutput(detailedMsg.isNull() ? shortMsg : detailedMsg, BuildStep::ErrorOutput);
emit addTask(Task(Task::Error, shortMsg, Utils::FileName::fromString(QString()), -1,
- TASK_CATEGORY_BUILDSYSTEM));
+ TASK_CATEGORY_DEPLOYMENT));
}
const Core::Id AndroidPackageCreationStep::CreatePackageId("Qt4ProjectManager.AndroidPackageCreationStep");
diff --git a/src/plugins/android/androidpackagecreationstep.h b/src/plugins/android/androidpackagecreationstep.h
index bc7336cd2a..5563134df4 100644
--- a/src/plugins/android/androidpackagecreationstep.h
+++ b/src/plugins/android/androidpackagecreationstep.h
@@ -72,6 +72,8 @@ public:
void setCertificatePassword(const QString &pwd);
void setOpenPackageLocation(bool open);
QAbstractItemModel *keystoreCertificates();
+ bool signPackage() const;
+ void setSignPackage(bool b);
protected:
bool fromMap(const QVariantMap &map);
@@ -107,7 +109,7 @@ private:
QStringList collectRelativeFilePaths(const QString &parentPath);
void collectFiles(QList<DeployItem> *deployList, QList<DeployItem> *pluginsAndImports);
- void removeManagedFilesFromPackage();
+ void removeManagedFilesFromPackage(const Utils::FileName &qtLibraryDir);
void copyFilesIntoPackage(const QList<DeployItem> &deployList);
void stripFiles(const QList<DeployItem> &deployList);
@@ -115,6 +117,7 @@ private:
private:
void handleProcessOutput(QProcess *process, bool stdErr);
+ bool m_signPackage;
Utils::FileName m_keystorePath;
QString m_keystorePasswd;
QString m_certificateAlias;
@@ -126,10 +129,10 @@ private:
Utils::FileName m_androidDir;
Utils::FileName m_gdbServerSource;
Utils::FileName m_gdbServerDestination;
- bool m_debugBuild;
Utils::FileName m_antToolPath;
Utils::FileName m_apkPathUnsigned;
Utils::FileName m_apkPathSigned;
+ bool m_signPackageForRun;
Utils::FileName m_keystorePathForRun;
QString m_certificatePasswdForRun;
Utils::FileName m_jarSigner;
diff --git a/src/plugins/android/androidpackagecreationwidget.cpp b/src/plugins/android/androidpackagecreationwidget.cpp
index 5bb2876955..66f5691035 100644
--- a/src/plugins/android/androidpackagecreationwidget.cpp
+++ b/src/plugins/android/androidpackagecreationwidget.cpp
@@ -55,6 +55,7 @@
namespace Android {
namespace Internal {
+using namespace ProjectExplorer;
using namespace Qt4ProjectManager;
///////////////////////////// CheckModel /////////////////////////////
@@ -139,12 +140,15 @@ AndroidPackageCreationWidget::AndroidPackageCreationWidget(AndroidPackageCreatio
: ProjectExplorer::BuildStepConfigWidget(),
m_step(step),
m_ui(new Ui::AndroidPackageCreationWidget),
- m_fileSystemWatcher(new QFileSystemWatcher(this))
+ m_fileSystemWatcher(new QFileSystemWatcher(this)),
+ m_currentBuildConfiguration(0)
{
m_qtLibsModel = new CheckModel(this);
m_prebundledLibs = new CheckModel(this);
m_ui->setupUi(this);
+ m_ui->signingDebugWarningIcon->hide();
+ m_ui->signingDebugWarningLabel->hide();
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
QTimer::singleShot(50, this, SLOT(initGui()));
connect(m_step, SIGNAL(updateRequiredLibrariesModels()), SLOT(updateRequiredLibrariesModels()));
@@ -184,6 +188,36 @@ void AndroidPackageCreationWidget::initGui()
bool use = bc->useSystemEnvironment();
bc->setUseSystemEnvironment(!use);
bc->setUseSystemEnvironment(use);
+
+ activeBuildConfigurationChanged();
+ connect(m_step->target(), SIGNAL(activeBuildConfigurationChanged(ProjectExplorer::BuildConfiguration*)),
+ this, SLOT(activeBuildConfigurationChanged()));
+}
+
+void AndroidPackageCreationWidget::updateSigningWarning()
+{
+ Qt4BuildConfiguration *bc = qobject_cast<Qt4BuildConfiguration *>(m_step->target()->activeBuildConfiguration());
+ bool debug = bc && (bc->qmakeBuildConfiguration() & QtSupport::BaseQtVersion::DebugBuild);
+ if (m_step->signPackage() && debug) {
+ m_ui->signingDebugWarningIcon->setVisible(true);
+ m_ui->signingDebugWarningLabel->setVisible(true);
+ } else {
+ m_ui->signingDebugWarningIcon->setVisible(false);
+ m_ui->signingDebugWarningLabel->setVisible(false);
+ }
+}
+
+void AndroidPackageCreationWidget::activeBuildConfigurationChanged()
+{
+ if (m_currentBuildConfiguration)
+ disconnect(m_currentBuildConfiguration, SIGNAL(qmakeBuildConfigurationChanged()),
+ this, SLOT(updateSigningWarning()));
+ updateSigningWarning();
+ Qt4BuildConfiguration *bc = qobject_cast<Qt4BuildConfiguration *>(m_step->target()->activeBuildConfiguration());
+ m_currentBuildConfiguration = bc;
+ if (bc)
+ connect(bc, SIGNAL(qmakeBuildConfigurationChanged()), this, SLOT(updateSigningWarning()));
+ m_currentBuildConfiguration = bc;
}
void AndroidPackageCreationWidget::updateAndroidProjectInfo()
@@ -198,7 +232,7 @@ void AndroidPackageCreationWidget::updateAndroidProjectInfo()
QStringList targets = AndroidConfigurations::instance().sdkTargets(minApiLevel);
m_ui->targetSDKComboBox->addItems(targets);
- m_ui->targetSDKComboBox->setCurrentIndex(targets.indexOf(AndroidManager::targetSDK(target)));
+ m_ui->targetSDKComboBox->setCurrentIndex(targets.indexOf(AndroidManager::buildTargetSDK(target)));
m_qtLibsModel->setAvailableItems(AndroidManager::availableQtLibs(target));
m_qtLibsModel->setCheckedItems(AndroidManager::qtLibs(target));
@@ -208,7 +242,7 @@ void AndroidPackageCreationWidget::updateAndroidProjectInfo()
void AndroidPackageCreationWidget::setTargetSDK(const QString &sdk)
{
- AndroidManager::setTargetSDK(m_step->target(), sdk);
+ AndroidManager::setBuildTargetSDK(m_step->target(), sdk);
Qt4BuildConfiguration *bc = qobject_cast<Qt4BuildConfiguration *>(m_step->target()->activeBuildConfiguration());
if (!bc)
return;
@@ -218,10 +252,9 @@ void AndroidPackageCreationWidget::setTargetSDK(const QString &sdk)
qs->setForced(true);
- ProjectExplorer::BuildManager *bm = ProjectExplorer::ProjectExplorerPlugin::instance()->buildManager();
- bm->buildList(bc->stepList(Core::Id(ProjectExplorer::Constants::BUILDSTEPS_CLEAN)),
- ProjectExplorer::ProjectExplorerPlugin::displayNameForStepId(Core::Id(ProjectExplorer::Constants::BUILDSTEPS_CLEAN)));
- bm->appendStep(qs, ProjectExplorer::ProjectExplorerPlugin::displayNameForStepId(Core::Id(ProjectExplorer::Constants::BUILDSTEPS_CLEAN)));
+ BuildManager::buildList(bc->stepList(ProjectExplorer::Constants::BUILDSTEPS_CLEAN),
+ ProjectExplorerPlugin::displayNameForStepId(ProjectExplorer::Constants::BUILDSTEPS_CLEAN));
+ BuildManager::appendStep(qs, ProjectExplorerPlugin::displayNameForStepId(ProjectExplorer::Constants::BUILDSTEPS_CLEAN));
bc->setSubNodeBuild(0);
// Make the buildconfiguration emit a evironmentChanged() signal
// TODO find a better way
@@ -304,6 +337,8 @@ void AndroidPackageCreationWidget::setCertificates()
void AndroidPackageCreationWidget::on_signPackageCheckBox_toggled(bool checked)
{
+ m_step->setSignPackage(checked);
+ updateSigningWarning();
if (!checked)
return;
if (!m_step->keystorePath().isEmpty())
diff --git a/src/plugins/android/androidpackagecreationwidget.h b/src/plugins/android/androidpackagecreationwidget.h
index 229f412192..9362ba54e5 100644
--- a/src/plugins/android/androidpackagecreationwidget.h
+++ b/src/plugins/android/androidpackagecreationwidget.h
@@ -41,6 +41,8 @@ class QFileSystemWatcher;
namespace Ui { class AndroidPackageCreationWidget; }
QT_END_NAMESPACE
+namespace Qt4ProjectManager { class Qt4BuildConfiguration; }
+
namespace Android {
namespace Internal {
class AndroidPackageCreationStep;
@@ -102,12 +104,15 @@ private slots:
void on_openPackageLocationCheckBox_toggled(bool checked);
+ void updateSigningWarning();
+ void activeBuildConfigurationChanged();
private:
AndroidPackageCreationStep *const m_step;
Ui::AndroidPackageCreationWidget *const m_ui;
CheckModel *m_qtLibsModel;
CheckModel *m_prebundledLibs;
QFileSystemWatcher *m_fileSystemWatcher;
+ Qt4ProjectManager::Qt4BuildConfiguration *m_currentBuildConfiguration;
};
} // namespace Internal
diff --git a/src/plugins/android/androidpackagecreationwidget.ui b/src/plugins/android/androidpackagecreationwidget.ui
index fcd31b3189..5f27b1d6e9 100644
--- a/src/plugins/android/androidpackagecreationwidget.ui
+++ b/src/plugins/android/androidpackagecreationwidget.ui
@@ -37,7 +37,7 @@
</widget>
</item>
<item>
- <widget class="QGroupBox" name="groupBox_2">
+ <widget class="QGroupBox" name="librariesGroupBox">
<property name="title">
<string>Libraries</string>
</property>
@@ -161,9 +161,9 @@
<property name="title">
<string>Sign package</string>
</property>
- <layout class="QGridLayout" name="gridLayout_3">
- <item row="0" column="0" colspan="2">
- <layout class="QHBoxLayout" name="horizontalLayout_4">
+ <layout class="QVBoxLayout" name="verticalLayout_2">
+ <item>
+ <layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QLabel" name="KeystoreLocationLabel">
<property name="text">
@@ -197,46 +197,103 @@
</item>
</layout>
</item>
- <item row="1" column="0">
- <widget class="QCheckBox" name="signPackageCheckBox">
- <property name="text">
- <string>Sign package</string>
- </property>
- </widget>
- </item>
- <item row="1" column="1">
- <widget class="QCheckBox" name="openPackageLocationCheckBox">
- <property name="text">
- <string>Open package location after is complete</string>
- </property>
- <property name="checked">
- <bool>true</bool>
- </property>
- </widget>
- </item>
- <item row="2" column="0">
- <widget class="QLabel" name="KeystoreLocationLabel_2">
- <property name="text">
- <string>Certificate alias:</string>
- </property>
- <property name="alignment">
- <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
- </property>
- </widget>
+ <item>
+ <layout class="QHBoxLayout" name="horizontalLayout_4">
+ <item>
+ <widget class="QCheckBox" name="signPackageCheckBox">
+ <property name="text">
+ <string>Sign package</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QCheckBox" name="openPackageLocationCheckBox">
+ <property name="text">
+ <string>Open package location after is complete</string>
+ </property>
+ <property name="checked">
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ </layout>
</item>
- <item row="2" column="1">
- <widget class="QComboBox" name="certificatesAliasComboBox">
- <property name="enabled">
- <bool>false</bool>
- </property>
- </widget>
+ <item>
+ <layout class="QHBoxLayout" name="horizontalLayout_3">
+ <item>
+ <widget class="QLabel" name="signingDebugWarningIcon">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Fixed" vsizetype="Preferred">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text">
+ <string/>
+ </property>
+ <property name="pixmap">
+ <pixmap resource="../projectexplorer/projectexplorer.qrc">:/projectexplorer/images/compile_warning.png</pixmap>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="signingDebugWarningLabel">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Fixed" vsizetype="Preferred">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text">
+ <string>Signing a debug package</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="KeystoreLocationLabel_2">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text">
+ <string>Certificate alias:</string>
+ </property>
+ <property name="alignment">
+ <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QComboBox" name="certificatesAliasComboBox">
+ <property name="enabled">
+ <bool>false</bool>
+ </property>
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="minimumSize">
+ <size>
+ <width>300</width>
+ <height>0</height>
+ </size>
+ </property>
+ </widget>
+ </item>
+ </layout>
</item>
</layout>
</widget>
</item>
</layout>
</widget>
- <resources/>
+ <resources>
+ <include location="../projectexplorer/projectexplorer.qrc"/>
+ </resources>
<connections>
<connection>
<sender>signPackageCheckBox</sender>
diff --git a/src/plugins/android/androidpackageinstallationfactory.cpp b/src/plugins/android/androidpackageinstallationfactory.cpp
index e3f86b0e59..e054f903c8 100644
--- a/src/plugins/android/androidpackageinstallationfactory.cpp
+++ b/src/plugins/android/androidpackageinstallationfactory.cpp
@@ -50,13 +50,8 @@ AndroidPackageInstallationFactory::AndroidPackageInstallationFactory(QObject *pa
QList<Core::Id> AndroidPackageInstallationFactory::availableCreationIds(BuildStepList *parent) const
{
- if (parent->id() != ProjectExplorer::Constants::BUILDSTEPS_DEPLOY)
- return QList<Core::Id>();
- if (!AndroidManager::supportsAndroid(parent->target()))
- return QList<Core::Id>();
- if (parent->contains(AndroidPackageInstallationStep::Id))
- return QList<Core::Id>();
- return QList<Core::Id>() << AndroidPackageInstallationStep::Id;
+ Q_UNUSED(parent);
+ return QList<Core::Id>();
}
QString AndroidPackageInstallationFactory::displayNameForId(const Core::Id id) const
@@ -68,25 +63,33 @@ QString AndroidPackageInstallationFactory::displayNameForId(const Core::Id id) c
bool AndroidPackageInstallationFactory::canCreate(BuildStepList *parent, const Core::Id id) const
{
- return availableCreationIds(parent).contains(id);
+ Q_UNUSED(parent);
+ Q_UNUSED(id);
+ return false;
}
BuildStep *AndroidPackageInstallationFactory::create(BuildStepList *parent, const Core::Id id)
{
- Q_ASSERT(canCreate(parent, id));
+ Q_UNUSED(parent);
Q_UNUSED(id);
- return new AndroidPackageInstallationStep(parent);
+ return 0;
}
bool AndroidPackageInstallationFactory::canRestore(BuildStepList *parent, const QVariantMap &map) const
{
- return canCreate(parent, idFromMap(map));
+ if (parent->id() != ProjectExplorer::Constants::BUILDSTEPS_DEPLOY)
+ return false;
+ if (!AndroidManager::supportsAndroid(parent->target()))
+ return false;
+ if (parent->contains(AndroidPackageInstallationStep::Id))
+ return false;
+ return ProjectExplorer::idFromMap(map) == AndroidPackageInstallationStep::Id;
}
BuildStep *AndroidPackageInstallationFactory::restore(BuildStepList *parent, const QVariantMap &map)
{
Q_ASSERT(canRestore(parent, map));
- AndroidPackageInstallationStep * const step = new AndroidPackageInstallationStep(parent);
+ AndroidPackageInstallationStep * const step = new AndroidPackageInstallationStep(AndroidPackageInstallationStep::ProjectDirectory, parent);
if (!step->fromMap(map)) {
delete step;
return 0;
diff --git a/src/plugins/android/androidpackageinstallationstep.cpp b/src/plugins/android/androidpackageinstallationstep.cpp
index 7b69ac3467..8541c3ef02 100644
--- a/src/plugins/android/androidpackageinstallationstep.cpp
+++ b/src/plugins/android/androidpackageinstallationstep.cpp
@@ -40,9 +40,12 @@
using namespace Android::Internal;
const Core::Id AndroidPackageInstallationStep::Id = Core::Id("Qt4ProjectManager.AndroidPackageInstallationStep");
+namespace {
+const char ANDROIDDIRECTORY[] = "Android.AndroidPackageInstallationStep.AndroidDirectory";
+}
-AndroidPackageInstallationStep::AndroidPackageInstallationStep(ProjectExplorer::BuildStepList *bsl)
- : MakeStep(bsl, Id)
+AndroidPackageInstallationStep::AndroidPackageInstallationStep(AndroidDirectory mode,ProjectExplorer::BuildStepList *bsl)
+ : MakeStep(bsl, Id), m_androidDirectory(mode)
{
const QString name = tr("Copy application data");
setDefaultDisplayName(name);
@@ -58,7 +61,11 @@ bool AndroidPackageInstallationStep::init()
ProjectExplorer::BuildConfiguration *bc = buildConfiguration();
if (!bc)
bc = target()->activeBuildConfiguration();
- QString dirPath = AndroidManager::dirPath(target()).toString();
+ QString dirPath;
+ if (m_androidDirectory == ProjectDirectory)
+ dirPath = AndroidManager::dirPath(target()).toString();
+ else
+ dirPath = bc->buildDirectory().appendPath((QLatin1String("android"))).toString();
if (Utils::HostOsInfo::isWindowsHost())
if (bc->environment().searchInPath(QLatin1String("sh.exe")).isEmpty())
dirPath = QDir::toNativeSeparators(dirPath);
@@ -66,3 +73,18 @@ bool AndroidPackageInstallationStep::init()
return MakeStep::init();
}
+
+bool AndroidPackageInstallationStep::fromMap(const QVariantMap &map)
+{
+ if (!MakeStep::fromMap(map))
+ return false;
+ m_androidDirectory = AndroidDirectory(map.value(QLatin1String(ANDROIDDIRECTORY)).toInt());
+ return true;
+}
+
+QVariantMap AndroidPackageInstallationStep::toMap() const
+{
+ QVariantMap map = MakeStep::toMap();
+ map.insert(QLatin1String(ANDROIDDIRECTORY), m_androidDirectory);
+ return map;
+}
diff --git a/src/plugins/android/androidpackageinstallationstep.h b/src/plugins/android/androidpackageinstallationstep.h
index 6763ef138e..2ccbc7ad69 100644
--- a/src/plugins/android/androidpackageinstallationstep.h
+++ b/src/plugins/android/androidpackageinstallationstep.h
@@ -41,12 +41,17 @@ class AndroidPackageInstallationStep : public Qt4ProjectManager::MakeStep
friend class AndroidPackageInstallationFactory;
public:
- explicit AndroidPackageInstallationStep(ProjectExplorer::BuildStepList *bsl);
+ enum AndroidDirectory { ProjectDirectory, BuildDirectory };
+ explicit AndroidPackageInstallationStep(AndroidDirectory mode, ProjectExplorer::BuildStepList *bsl);
bool init();
+ bool fromMap(const QVariantMap &map);
+ QVariantMap toMap() const;
+
private:
AndroidPackageInstallationStep(ProjectExplorer::BuildStepList *bc,
AndroidPackageInstallationStep *other);
+ AndroidDirectory m_androidDirectory;
static const Core::Id Id;
};
diff --git a/src/plugins/android/androidplugin.cpp b/src/plugins/android/androidplugin.cpp
index d71dbc5272..41ebb56134 100644
--- a/src/plugins/android/androidplugin.cpp
+++ b/src/plugins/android/androidplugin.cpp
@@ -32,6 +32,7 @@
#include "androidconstants.h"
#include "androidconfigurations.h"
#include "androiddeploystepfactory.h"
+#include "androiddeployqtstep.h"
#include "androiddevice.h"
#include "androiddevicefactory.h"
#include "androidmanager.h"
@@ -44,6 +45,9 @@
#include "androiddeployconfiguration.h"
#include "androidgdbserverkitinformation.h"
#include "androidmanifesteditorfactory.h"
+#ifdef HAVE_QBS
+# include "androidqbspropertyprovider.h"
+#endif
#include <coreplugin/mimedatabase.h>
#include <coreplugin/icore.h>
@@ -71,12 +75,13 @@ bool AndroidPlugin::initialize(const QStringList &arguments, QString *errorMessa
addAutoReleasedObject(new Internal::AndroidPackageInstallationFactory);
addAutoReleasedObject(new Internal::AndroidPackageCreationFactory);
addAutoReleasedObject(new Internal::AndroidDeployStepFactory);
+ addAutoReleasedObject(new Internal::AndroidDeployQtStepFactory);
addAutoReleasedObject(new Internal::AndroidSettingsPage);
addAutoReleasedObject(new Internal::AndroidQtVersionFactory);
addAutoReleasedObject(new Internal::AndroidToolChainFactory);
addAutoReleasedObject(new Internal::AndroidDeployConfigurationFactory);
addAutoReleasedObject(new Internal::AndroidDeviceFactory);
- ProjectExplorer::KitManager::instance()->registerKitInformation(new Internal::AndroidGdbServerKitInformation);
+ ProjectExplorer::KitManager::registerKitInformation(new Internal::AndroidGdbServerKitInformation);
// AndroidManifest.xml editor
Core::MimeGlobPattern androidManifestGlobPattern(QLatin1String("AndroidManifest.xml"), Core::MimeGlobPattern::MaxWeight);
@@ -86,7 +91,7 @@ bool AndroidPlugin::initialize(const QStringList &arguments, QString *errorMessa
androidManifestMimeType.setGlobPatterns(QList<Core::MimeGlobPattern>() << androidManifestGlobPattern);
androidManifestMimeType.setSubClassesOf(QStringList() << QLatin1String("application/xml"));
- if (!Core::ICore::mimeDatabase()->addMimeType(androidManifestMimeType)) {
+ if (!Core::MimeDatabase::addMimeType(androidManifestMimeType)) {
*errorMessage = tr("Could not add mime-type for AndroidManifest.xml editor.");
return false;
}
@@ -97,7 +102,9 @@ bool AndroidPlugin::initialize(const QStringList &arguments, QString *errorMessa
connect(ProjectExplorer::DeviceManager::instance(), SIGNAL(devicesLoaded()),
this, SLOT(updateDevice()));
-
+#ifdef HAVE_QBS
+ addAutoReleasedObject(new Internal::AndroidQBSPropertyProvider);
+#endif
return true;
}
diff --git a/src/plugins/android/androidqbspropertyprovider.cpp b/src/plugins/android/androidqbspropertyprovider.cpp
new file mode 100644
index 0000000000..b5a05d5113
--- /dev/null
+++ b/src/plugins/android/androidqbspropertyprovider.cpp
@@ -0,0 +1,80 @@
+/**************************************************************************
+**
+** Copyright (c) 2013 BogDan Vatra <bog_dan_ro@yahoo.com>
+** 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 "androidqbspropertyprovider.h"
+
+#include "androidconfigurations.h"
+#include "androidconstants.h"
+#include "androidgdbserverkitinformation.h"
+#include "androidtoolchain.h"
+
+#include <qbsprojectmanager/qbsconstants.h>
+
+namespace Android {
+namespace Internal {
+
+// QBS Android specific settings:
+const QLatin1String CPP_ANDROID_SDK_PATH("cpp.androidSdkPath");
+const QLatin1String CPP_ANDROID_NDK_PATH("cpp.androidNdkPath");
+const QLatin1String CPP_ANDROID_TOOLCHAIN_VERSION("cpp.androidToolchainVersion");
+const QLatin1String CPP_ANDROID_TOOLCHAIN_HOST("cpp.androidToolchainHost");
+const QLatin1String CPP_ANDROID_TOOLCHAIN_PREFIX("cpp.androidToolchainPrefix");
+const QLatin1String CPP_ANDROID_GDBSERVER("cpp.androidGdbServer");
+
+bool AndroidQBSPropertyProvider::canHandle(const ProjectExplorer::Kit *kit) const
+{
+ return AndroidGdbServerKitInformation::isAndroidKit(kit);
+}
+
+QVariantMap AndroidQBSPropertyProvider::properties(const ProjectExplorer::Kit *kit, const QVariantMap &defaultData) const
+{
+ Q_ASSERT(AndroidGdbServerKitInformation::isAndroidKit(kit));
+
+ QVariantMap qbsProperties = defaultData;
+ QStringList targetOSs(defaultData[QLatin1String(QbsProjectManager::Constants::QBS_TARGETOS)].toStringList());
+ if (!targetOSs.contains(QLatin1String("android")))
+ qbsProperties[QLatin1String(QbsProjectManager::Constants::QBS_TARGETOS)] = QStringList() << QLatin1String("android")
+ << targetOSs;
+
+ const AndroidConfig &config = AndroidConfigurations::instance().config();
+ AndroidToolChain *tc = static_cast<AndroidToolChain*>(ProjectExplorer::ToolChainKitInformation::toolChain(kit));
+ qbsProperties[CPP_ANDROID_SDK_PATH] = config.sdkLocation.toString();
+ qbsProperties[CPP_ANDROID_NDK_PATH] = config.ndkLocation.toString();
+ qbsProperties[CPP_ANDROID_TOOLCHAIN_VERSION] = tc->ndkToolChainVersion();
+ qbsProperties[CPP_ANDROID_TOOLCHAIN_HOST] = config.toolchainHost;
+ qbsProperties[CPP_ANDROID_TOOLCHAIN_PREFIX] = AndroidConfigurations::toolchainPrefix(tc->targetAbi().architecture());
+ qbsProperties[CPP_ANDROID_GDBSERVER] = tc->suggestedGdbServer().toString();
+ // TODO: Find a way to extract ANDROID_ARCHITECTURE from Qt mkspec
+// qbsProperties[QbsProjectManager::Constants::QBS_ARCHITECTURE] = ...
+
+ return qbsProperties;
+}
+
+} // namespace Internal
+} // namespace Android
diff --git a/src/plugins/qnx/blackberryutils.h b/src/plugins/android/androidqbspropertyprovider.h
index 9bc17b8c84..cebd638665 100644
--- a/src/plugins/qnx/blackberryutils.h
+++ b/src/plugins/android/androidqbspropertyprovider.h
@@ -1,9 +1,7 @@
/**************************************************************************
**
-** Copyright (C) 2011 - 2013 Research In Motion
-**
-** Contact: Research In Motion (blackberry-qt@qnx.com)
-** Contact: KDAB (info@kdab.com)
+** Copyright (c) 2013 BogDan Vatra <bog_dan_ro@yahoo.com>
+** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
@@ -29,27 +27,22 @@
**
****************************************************************************/
-#ifndef QNX_INTERNAL_BLACKBERRYUTILS_H
-#define QNX_INTERNAL_BLACKBERRYUTILS_H
-
-#include <QtGlobal>
+#ifndef ANDROIDQBSPROPERTYPROVIDER_H
+#define ANDROIDQBSPROPERTYPROVIDER_H
-QT_BEGIN_NAMESPACE
-class QString;
-QT_END_NAMESPACE
+#include <qbsprojectmanager/propertyprovider.h>
-namespace Qnx {
+namespace Android {
namespace Internal {
-class BlackBerryUtils
+class AndroidQBSPropertyProvider : public QbsProjectManager::PropertyProvider
{
public:
- static bool hasRegisteredKeys();
-
- static QString getCsjAuthor(const QString &fileName);
+ virtual bool canHandle(const ProjectExplorer::Kit *kit) const;
+ virtual QVariantMap properties(const ProjectExplorer::Kit *kit, const QVariantMap &defaultData) const;
};
} // namespace Internal
-} // namespace Qnx
+} // namespace Android
-#endif // QNX_INTERNAL_BLACKBERRYUTILS_H
+#endif // ANDROIDQBSPROPERTYPROVIDER_H
diff --git a/src/plugins/android/androidqtversion.cpp b/src/plugins/android/androidqtversion.cpp
index b4e82b6cd2..c329302ffd 100644
--- a/src/plugins/android/androidqtversion.cpp
+++ b/src/plugins/android/androidqtversion.cpp
@@ -46,6 +46,8 @@
#include <projectexplorer/kit.h>
#include <projectexplorer/projectexplorer.h>
+#include <proparser/profileevaluator.h>
+
using namespace Android::Internal;
using namespace ProjectExplorer;
using namespace Qt4ProjectManager;
@@ -120,7 +122,7 @@ void AndroidQtVersion::addToEnvironment(const ProjectExplorer::Kit *k, Utils::En
return;
env.set(QLatin1String("ANDROID_NDK_PLATFORM"),
- AndroidConfigurations::instance().bestMatch(AndroidManager::targetSDK(target)));
+ AndroidConfigurations::instance().bestMatch(AndroidManager::buildTargetSDK(target)));
}
@@ -130,6 +132,18 @@ QString AndroidQtVersion::description() const
return tr("Android");
}
+QString AndroidQtVersion::targetArch() const
+{
+ ensureMkSpecParsed();
+ return m_targetArch;
+}
+
+void AndroidQtVersion::parseMkSpec(ProFileEvaluator *evaluator) const
+{
+ m_targetArch = evaluator->value(QLatin1String("ANDROID_TARGET_ARCH"));
+ BaseQtVersion::parseMkSpec(evaluator);
+}
+
Core::FeatureSet AndroidQtVersion::availableFeatures() const
{
Core::FeatureSet features = QtSupport::BaseQtVersion::availableFeatures();
diff --git a/src/plugins/android/androidqtversion.h b/src/plugins/android/androidqtversion.h
index a29235d8c0..6ac95f00d5 100644
--- a/src/plugins/android/androidqtversion.h
+++ b/src/plugins/android/androidqtversion.h
@@ -59,6 +59,11 @@ public:
QString platformDisplayName() const;
QString description() const;
+ QString targetArch() const;
+protected:
+ virtual void parseMkSpec(ProFileEvaluator *) const;
+private:
+ mutable QString m_targetArch;
};
} // namespace Internal
diff --git a/src/plugins/android/androidrunconfiguration.cpp b/src/plugins/android/androidrunconfiguration.cpp
index 45e9e091b9..d84bce54b8 100644
--- a/src/plugins/android/androidrunconfiguration.cpp
+++ b/src/plugins/android/androidrunconfiguration.cpp
@@ -84,16 +84,6 @@ AndroidConfig AndroidRunConfiguration::config() const
return AndroidConfigurations::instance().config();
}
-AndroidDeployStep *AndroidRunConfiguration::deployStep() const
-{
- AndroidDeployStep * const step
- = AndroidGlobal::buildStep<AndroidDeployStep>(target()->activeDeployConfiguration());
- Q_ASSERT_X(step, Q_FUNC_INFO,
- "Impossible: Android build configuration without deploy step.");
- return step;
-}
-
-
const QString AndroidRunConfiguration::remoteChannel() const
{
return QLatin1String(":5039");
diff --git a/src/plugins/android/androidrunconfiguration.h b/src/plugins/android/androidrunconfiguration.h
index 947d44a385..9e0fd50cd7 100644
--- a/src/plugins/android/androidrunconfiguration.h
+++ b/src/plugins/android/androidrunconfiguration.h
@@ -52,8 +52,6 @@ public:
QWidget *createConfigurationWidget();
Utils::OutputFormatter *createOutputFormatter() const;
- AndroidDeployStep *deployStep() const;
-
void setArguments(const QString &args);
AndroidConfig config() const;
QString proFilePath() const;
diff --git a/src/plugins/android/androidrunfactories.cpp b/src/plugins/android/androidrunfactories.cpp
index 65c6237739..a76656c33a 100644
--- a/src/plugins/android/androidrunfactories.cpp
+++ b/src/plugins/android/androidrunfactories.cpp
@@ -168,7 +168,7 @@ RunControl *AndroidRunControlFactory::create(RunConfiguration *runConfig,
case DebugRunMode:
return AndroidDebugSupport::createDebugRunControl(rc, errorMessage);
case QmlProfilerRunMode:
- return AndroidAnalyzeSupport::createAnalyzeRunControl(rc, mode, errorMessage);
+ return AndroidAnalyzeSupport::createAnalyzeRunControl(rc, mode);
case NoRunMode:
case DebugRunModeWithBreakOnMain:
case CallgrindRunMode:
diff --git a/src/plugins/android/androidrunner.cpp b/src/plugins/android/androidrunner.cpp
index ef467d2bca..e00cb95e68 100644
--- a/src/plugins/android/androidrunner.cpp
+++ b/src/plugins/android/androidrunner.cpp
@@ -30,6 +30,7 @@
#include "androidrunner.h"
#include "androiddeploystep.h"
+#include "androiddeployqtstep.h"
#include "androidconfigurations.h"
#include "androidglobal.h"
#include "androidrunconfiguration.h"
@@ -73,17 +74,17 @@ AndroidRunner::AndroidRunner(QObject *parent,
m_qmlPort = server.serverPort();
}
ProjectExplorer::Target *target = runConfig->target();
- AndroidDeployStep *ds = runConfig->deployStep();
- m_useLocalQtLibs = ds->deployAction() == AndroidDeployStep::DeployLocal
- || ds->deployAction() == AndroidDeployStep::BundleLibraries;
+ m_useLocalQtLibs = AndroidManager::useLocalLibs(target);
if (m_useLocalQtLibs) {
- m_localLibs = AndroidManager::loadLocalLibs(target, ds->deviceAPILevel());
- m_localJars = AndroidManager::loadLocalJars(target, ds->deviceAPILevel());
- m_localJarsInitClasses = AndroidManager::loadLocalJarsInitClasses(target, ds->deviceAPILevel());
+ int deviceApiLevel = AndroidManager::minimumSDK(target);
+ m_localLibs = AndroidManager::loadLocalLibs(target, deviceApiLevel);
+ m_localJars = AndroidManager::loadLocalJars(target, deviceApiLevel);
+ m_localJarsInitClasses = AndroidManager::loadLocalJarsInitClasses(target, deviceApiLevel);
}
m_intentName = AndroidManager::intentName(target);
m_packageName = m_intentName.left(m_intentName.indexOf(QLatin1Char('/')));
- m_deviceSerialNumber = ds->deviceSerialNumber();
+
+ m_deviceSerialNumber = AndroidManager::deviceSerialNumber(target);
m_processPID = -1;
m_adb = AndroidConfigurations::instance().adbToolPath().toString();
m_selector = AndroidDeviceInfo::adbSelector(m_deviceSerialNumber);
diff --git a/src/plugins/android/androidsettingspage.cpp b/src/plugins/android/androidsettingspage.cpp
index 28722c3e30..95cb4af425 100644
--- a/src/plugins/android/androidsettingspage.cpp
+++ b/src/plugins/android/androidsettingspage.cpp
@@ -36,6 +36,8 @@
#include <QCoreApplication>
+using namespace ProjectExplorer;
+
namespace Android {
namespace Internal {
@@ -67,9 +69,9 @@ void AndroidSettingsPage::apply()
{
m_widget->saveSettings();
- QList<ProjectExplorer::ToolChain *> existingToolChains = ProjectExplorer::ToolChainManager::instance()->toolChains();
- QList<ProjectExplorer::ToolChain *> toolchains = AndroidToolChainFactory::createToolChainsForNdk(AndroidConfigurations::instance().config().ndkLocation);
- foreach (ProjectExplorer::ToolChain *tc, toolchains) {
+ QList<ToolChain *> existingToolChains = ToolChainManager::toolChains();
+ QList<ToolChain *> toolchains = AndroidToolChainFactory::createToolChainsForNdk(AndroidConfigurations::instance().config().ndkLocation);
+ foreach (ToolChain *tc, toolchains) {
bool found = false;
for (int i = 0; i < existingToolChains.count(); ++i) {
if (*(existingToolChains.at(i)) == *tc) {
@@ -80,15 +82,13 @@ void AndroidSettingsPage::apply()
if (found)
delete tc;
else
- ProjectExplorer::ToolChainManager::instance()->registerToolChain(tc);
+ ToolChainManager::registerToolChain(tc);
}
- for (int i = 0; i < existingToolChains.count(); ++i) {
- ProjectExplorer::ToolChain *tc = existingToolChains.at(i);
+ foreach (ToolChain *tc, existingToolChains) {
if (tc->type() == QLatin1String(Constants::ANDROID_TOOLCHAIN_TYPE)) {
- if (!tc->isValid()) {
- ProjectExplorer::ToolChainManager::instance()->deregisterToolChain(tc);
- }
+ if (!tc->isValid())
+ ToolChainManager::deregisterToolChain(tc);
}
}
diff --git a/src/plugins/android/androidsettingswidget.cpp b/src/plugins/android/androidsettingswidget.cpp
index 66322d8e37..01d3318e79 100644
--- a/src/plugins/android/androidsettingswidget.cpp
+++ b/src/plugins/android/androidsettingswidget.cpp
@@ -75,7 +75,7 @@ QVariant AvdModel::data(const QModelIndex &index, int role) const
case 1:
return QString::fromLatin1("API %1").arg(m_list[index.row()].sdk);
case 2:
- return m_list[index.row()].cpuABI;
+ return m_list[index.row()].cpuAbi.first();
}
return QVariant();
}
@@ -176,8 +176,11 @@ void AndroidSettingsWidget::saveSettings(bool saveNow)
bool AndroidSettingsWidget::checkSDK(const Utils::FileName &location)
{
- if (location.isEmpty())
+ if (location.isEmpty()) {
+ m_ui->sdkWarningIconLabel->setVisible(false);
+ m_ui->sdkWarningLabel->setVisible(false);
return false;
+ }
Utils::FileName adb = location;
Utils::FileName androidExe = location;
Utils::FileName androidBat = location;
@@ -245,7 +248,7 @@ bool AndroidSettingsWidget::checkNDK(const Utils::FileName &location)
toolchainsForArch.insert(ati.architecture);
QSet<ProjectExplorer::Abi::Architecture> qtVersionsForArch;
- foreach (QtSupport::BaseQtVersion *qtVersion, QtSupport::QtVersionManager::instance()->versions()) {
+ foreach (QtSupport::BaseQtVersion *qtVersion, QtSupport::QtVersionManager::versions()) {
if (qtVersion->type() != QLatin1String(Constants::ANDROIDQT) || qtVersion->qtAbis().isEmpty())
continue;
qtVersionsForArch.insert(qtVersion->qtAbis().first().architecture());
@@ -398,8 +401,7 @@ void AndroidSettingsWidget::removeAVD()
void AndroidSettingsWidget::startAVD()
{
- int tempApiLevel = -1;
- AndroidConfigurations::instance().startAVD(&tempApiLevel, m_AVDModel.avdName(m_ui->AVDTableView->currentIndex()));
+ AndroidConfigurations::instance().startAVDAsync(m_AVDModel.avdName(m_ui->AVDTableView->currentIndex()));
}
void AndroidSettingsWidget::avdActivated(QModelIndex index)
diff --git a/src/plugins/android/androidtoolchain.cpp b/src/plugins/android/androidtoolchain.cpp
index 4af393143e..1b3bd7260b 100644
--- a/src/plugins/android/androidtoolchain.cpp
+++ b/src/plugins/android/androidtoolchain.cpp
@@ -32,6 +32,8 @@
#include "androidconfigurations.h"
#include "androidqtversion.h"
+#include <extensionsystem/pluginmanager.h>
+
#include <qtsupport/qtkitinformation.h>
#include <qtsupport/qtversionmanager.h>
@@ -61,9 +63,12 @@ using namespace Utils;
static const char ANDROID_QT_VERSION_KEY[] = "Qt4ProjectManager.Android.QtVersion";
static const char ANDROID_NDK_TC_VERION[] = "Qt4ProjectManager.Android.NDK_TC_VERION";
-AndroidToolChain::AndroidToolChain(Abi::Architecture arch, const QString &ndkToolChainVersion, bool autodetected)
- : GccToolChain(QLatin1String(Constants::ANDROID_TOOLCHAIN_ID), autodetected),
- m_ndkToolChainVersion(ndkToolChainVersion)
+QMap<ProjectExplorer::Abi::Architecture, QList<int> > AndroidToolChainFactory::m_newestVersionForArch;
+Utils::FileName AndroidToolChainFactory::m_ndkLocation;
+
+AndroidToolChain::AndroidToolChain(Abi::Architecture arch, const QString &ndkToolChainVersion, Detection d)
+ : GccToolChain(QLatin1String(Constants::ANDROID_TOOLCHAIN_ID), d),
+ m_ndkToolChainVersion(ndkToolChainVersion), m_secondaryToolChain(false)
{
ProjectExplorer::Abi abi = ProjectExplorer::Abi(arch, ProjectExplorer::Abi::LinuxOS,
ProjectExplorer::Abi::AndroidLinuxFlavor, ProjectExplorer::Abi::ElfFormat,
@@ -76,12 +81,14 @@ AndroidToolChain::AndroidToolChain(Abi::Architecture arch, const QString &ndkToo
// for fromMap
AndroidToolChain::AndroidToolChain()
- : GccToolChain(QLatin1String(Constants::ANDROID_TOOLCHAIN_ID), false)
+ : GccToolChain(QLatin1String(Constants::ANDROID_TOOLCHAIN_ID), ToolChain::ManualDetection),
+ m_secondaryToolChain(false)
{
}
AndroidToolChain::AndroidToolChain(const AndroidToolChain &tc) :
- GccToolChain(tc), m_ndkToolChainVersion(tc.m_ndkToolChainVersion)
+ GccToolChain(tc), m_ndkToolChainVersion(tc.m_ndkToolChainVersion),
+ m_secondaryToolChain(tc.m_secondaryToolChain)
{ }
AndroidToolChain::~AndroidToolChain()
@@ -89,7 +96,7 @@ AndroidToolChain::~AndroidToolChain()
QString AndroidToolChain::type() const
{
- return QLatin1String(Android::Constants::ANDROID_TOOLCHAIN_TYPE);
+ return QLatin1String(Constants::ANDROID_TOOLCHAIN_TYPE);
}
QString AndroidToolChain::typeDisplayName() const
@@ -194,6 +201,9 @@ bool AndroidToolChain::fromMap(const QVariantMap &data)
m_ndkToolChainVersion = data.value(QLatin1String(ANDROID_NDK_TC_VERION)).toString();
}
+ ProjectExplorer::Abi::Architecture arch = targetAbi().architecture();
+ m_secondaryToolChain = AndroidToolChainFactory::versionCompareLess(AndroidToolChainFactory::versionNumberFromString(m_ndkToolChainVersion),
+ AndroidToolChainFactory::newestToolChainVersionForArch(arch));
return isValid();
}
@@ -223,6 +233,16 @@ QString AndroidToolChain::ndkToolChainVersion()
return m_ndkToolChainVersion;
}
+bool AndroidToolChain::secondaryToolChain() const
+{
+ return m_secondaryToolChain;
+}
+
+void AndroidToolChain::setSecondaryToolChain(bool b)
+{
+ m_secondaryToolChain = b;
+}
+
QList<Abi> AndroidToolChain::detectSupportedAbis() const
{
return QList<Abi>() << targetAbi();
@@ -243,18 +263,10 @@ AndroidToolChainConfigWidget::AndroidToolChainConfigWidget(AndroidToolChain *tc)
// ToolChainFactory
// --------------------------------------------------------------------------
-AndroidToolChainFactory::AndroidToolChainFactory() :
- ToolChainFactory()
-{ }
-
-QString AndroidToolChainFactory::displayName() const
+AndroidToolChainFactory::AndroidToolChainFactory()
{
- return tr("Android GCC");
-}
-
-QString AndroidToolChainFactory::id() const
-{
- return QLatin1String(Constants::ANDROID_TOOLCHAIN_ID);
+ setId(Constants::ANDROID_TOOLCHAIN_ID);
+ setDisplayName(tr("Android GCC"));
}
QList<ToolChain *> AndroidToolChainFactory::autoDetect()
@@ -305,6 +317,51 @@ QList<AndroidToolChainFactory::AndroidToolChainInformation> AndroidToolChainFact
return result;
}
+QList<int> AndroidToolChainFactory::versionNumberFromString(const QString &version)
+{
+ QList<int> result;
+ int start = 0;
+ int end = version.length();
+ while (start <= end) {
+ int index = version.indexOf(QLatin1Char('.'), start);
+ if (index == -1)
+ index = end;
+
+ bool ok;
+ int v = version.mid(start, index - start).toInt(&ok);
+ if (!ok) // unparseable, return what we have
+ return result;
+
+ result << v;
+ start = index + 1;
+ }
+ return result;
+}
+
+bool AndroidToolChainFactory::versionCompareLess(const QList<int> &a, const QList<int> &b)
+{
+ int aend = a.length();
+ int bend = b.length();
+ int end = qMax(aend, bend);
+ for (int i = 0; i < end; ++i) {
+ int an = i < aend ? a.at(i) : 0;
+ int bn = i < bend ? b.at(i) : 0;
+ if (an < bn)
+ return true;
+ if (bn < an)
+ return false;
+ }
+ return false;
+}
+
+bool AndroidToolChainFactory::versionCompareLess(AndroidToolChain *atc, AndroidToolChain *btc)
+{
+ QList<int> a = versionNumberFromString(atc->ndkToolChainVersion());
+ QList<int> b = versionNumberFromString(btc->ndkToolChainVersion());
+
+ return versionCompareLess(a, b);
+}
+
QList<ToolChain *> AndroidToolChainFactory::createToolChainsForNdk(const Utils::FileName &ndkPath)
{
QList<ToolChain *> result;
@@ -314,6 +371,8 @@ QList<ToolChain *> AndroidToolChainFactory::createToolChainsForNdk(const Utils::
FileName path = ndkPath;
QDirIterator it(path.appendPath(QLatin1String("toolchains")).toString(),
QStringList() << QLatin1String("*"), QDir::Dirs);
+ QMap<Abi::Architecture, AndroidToolChain *> newestToolChainForArch;
+
while (it.hasNext()) {
const QString &fileName = QFileInfo(it.next()).fileName();
int idx = versionRegExp.indexIn(fileName);
@@ -324,13 +383,57 @@ QList<ToolChain *> AndroidToolChainFactory::createToolChainsForNdk(const Utils::
Abi::Architecture arch = AndroidConfigurations::architectureForToolChainPrefix(platform);
if (arch == Abi::UnknownArchitecture) // e.g. mipsel which is not yet supported
continue;
- AndroidToolChain *tc = new AndroidToolChain(arch, version, true);
+ AndroidToolChain *tc = new AndroidToolChain(arch, version, ToolChain::AutoDetection);
FileName compilerPath = AndroidConfigurations::instance().gccPath(arch, version);
tc->setCompilerCommand(compilerPath);
result.append(tc);
+
+ QMap<Abi::Architecture, AndroidToolChain *>::const_iterator it
+ = newestToolChainForArch.constFind(arch);
+ if (it == newestToolChainForArch.constEnd())
+ newestToolChainForArch.insert(arch, tc);
+ else if (versionCompareLess(it.value(), tc))
+ newestToolChainForArch[arch] = tc;
}
+
+ foreach (ToolChain *tc, result) {
+ AndroidToolChain *atc = static_cast<AndroidToolChain *>(tc);
+ if (newestToolChainForArch.value(atc->targetAbi().architecture()) != atc)
+ atc->setSecondaryToolChain(true);
+ }
+
return result;
}
+QList<int> AndroidToolChainFactory::newestToolChainVersionForArch(Abi::Architecture arch)
+{
+ if (m_newestVersionForArch.isEmpty()
+ || m_ndkLocation != AndroidConfigurations::instance().config().ndkLocation) {
+ QRegExp versionRegExp(NDKGccVersionRegExp);
+ m_ndkLocation = AndroidConfigurations::instance().config().ndkLocation;
+ FileName path = m_ndkLocation;
+ QDirIterator it(path.appendPath(QLatin1String("toolchains")).toString(),
+ QStringList() << QLatin1String("*"), QDir::Dirs);
+ while (it.hasNext()) {
+ const QString &fileName = QFileInfo(it.next()).fileName();
+ int idx = versionRegExp.indexIn(fileName);
+ if (idx == -1)
+ continue;
+ QList<int> version = versionNumberFromString(fileName.mid(idx + 1));
+ QString platform = fileName.left(idx);
+ Abi::Architecture arch = AndroidConfigurations::architectureForToolChainPrefix(platform);
+ if (arch == Abi::UnknownArchitecture) // e.g. mipsel which is not yet supported
+ continue;
+ QMap<Abi::Architecture, QList<int> >::const_iterator it
+ = m_newestVersionForArch.constFind(arch);
+ if (it == m_newestVersionForArch.constEnd())
+ m_newestVersionForArch.insert(arch, version);
+ else if (versionCompareLess(it.value(), version))
+ m_newestVersionForArch[arch] = version;
+ }
+ }
+ return m_newestVersionForArch.value(arch);
+}
+
} // namespace Internal
} // namespace Android
diff --git a/src/plugins/android/androidtoolchain.h b/src/plugins/android/androidtoolchain.h
index 918db4ad3f..0f60da4372 100644
--- a/src/plugins/android/androidtoolchain.h
+++ b/src/plugins/android/androidtoolchain.h
@@ -61,15 +61,20 @@ public:
QString ndkToolChainVersion();
+ bool secondaryToolChain() const;
+ void setSecondaryToolChain(bool b);
+
protected:
QList<ProjectExplorer::Abi> detectSupportedAbis() const;
private:
- AndroidToolChain(ProjectExplorer::Abi::Architecture arch, const QString &ndkToolChainVersion, bool autodetected);
+ explicit AndroidToolChain(ProjectExplorer::Abi::Architecture arch, const QString &ndkToolChainVersion, Detection d);
AndroidToolChain();
AndroidToolChain(const AndroidToolChain &);
QString m_ndkToolChainVersion;
+ bool m_secondaryToolChain;
+
friend class AndroidToolChainFactory;
};
@@ -96,9 +101,6 @@ class AndroidToolChainFactory : public ProjectExplorer::ToolChainFactory
public:
AndroidToolChainFactory();
- QString displayName() const;
- QString id() const;
-
QList<ProjectExplorer::ToolChain *> autoDetect();
bool canRestore(const QVariantMap &data);
ProjectExplorer::ToolChain *restore(const QVariantMap &data);
@@ -113,6 +115,14 @@ public:
static QList<ProjectExplorer::ToolChain *> createToolChainsForNdk(const Utils::FileName &ndkPath);
static QList<AndroidToolChainInformation> toolchainPathsForNdk(const Utils::FileName &ndkPath);
+
+ static QList<int> versionNumberFromString(const QString &version);
+ static bool versionCompareLess(const QList<int> &a, const QList<int> &b);
+ static bool versionCompareLess(AndroidToolChain *atc, AndroidToolChain *btc);
+ static QList<int> newestToolChainVersionForArch(ProjectExplorer::Abi::Architecture arch);
+private:
+ static QMap<ProjectExplorer::Abi::Architecture, QList<int> > m_newestVersionForArch;
+ static Utils::FileName m_ndkLocation;
};
} // namespace Internal
diff --git a/src/plugins/android/certificatesmodel.cpp b/src/plugins/android/certificatesmodel.cpp
new file mode 100644
index 0000000000..e43b36008f
--- /dev/null
+++ b/src/plugins/android/certificatesmodel.cpp
@@ -0,0 +1,73 @@
+/****************************************************************************
+**
+** Copyright (c) 2013 BogDan Vatra <bog_dan_ro@yahoo.com>
+** 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 "certificatesmodel.h"
+
+#include <QComboBox>
+
+using namespace Android;
+using namespace Android::Internal;
+
+namespace {
+const QLatin1String AliasString("Alias name:");
+const QLatin1String CertificateSeparator("*******************************************");
+}
+
+CertificatesModel::CertificatesModel(const QString &rowCertificates, QObject *parent)
+ : QAbstractListModel(parent)
+{
+ int from = rowCertificates.indexOf(AliasString);
+ QPair<QString, QString> item;
+ while (from > -1) {
+ from += 11;// strlen(AliasString);
+ const int eol = rowCertificates.indexOf(QLatin1Char('\n'), from);
+ item.first = rowCertificates.mid(from, eol - from).trimmed();
+ const int eoc = rowCertificates.indexOf(CertificateSeparator, eol);
+ item.second = rowCertificates.mid(eol + 1, eoc - eol - 2).trimmed();
+ from = rowCertificates.indexOf(AliasString, eoc);
+ m_certs.push_back(item);
+ }
+}
+
+int CertificatesModel::rowCount(const QModelIndex &parent) const
+{
+ if (parent.isValid())
+ return 0;
+ return m_certs.size();
+}
+
+QVariant CertificatesModel::data(const QModelIndex &index, int role) const
+{
+ if (!index.isValid() || (role != Qt::DisplayRole && role != Qt::ToolTipRole))
+ return QVariant();
+ if (role == Qt::DisplayRole)
+ return m_certs[index.row()].first;
+ return m_certs[index.row()].second;
+}
diff --git a/src/plugins/android/certificatesmodel.h b/src/plugins/android/certificatesmodel.h
new file mode 100644
index 0000000000..f712433aa8
--- /dev/null
+++ b/src/plugins/android/certificatesmodel.h
@@ -0,0 +1,58 @@
+/****************************************************************************
+**
+** Copyright (c) 2013 BogDan Vatra <bog_dan_ro@yahoo.com>
+** 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 CERTIFICATESMODEL_H
+#define CERTIFICATESMODEL_H
+
+#include <QAbstractListModel>
+#include <QVector>
+#include <QPair>
+
+namespace Android {
+namespace Internal {
+
+class CertificatesModel: public QAbstractListModel
+{
+public:
+ CertificatesModel(const QString &rowCertificates, QObject *parent);
+
+protected:
+ int rowCount(const QModelIndex &parent = QModelIndex()) const;
+
+ QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
+
+private:
+ QVector<QPair<QString, QString> > m_certs;
+};
+
+}
+}
+
+#endif // CERTIFICATESMODEL_H
diff --git a/src/plugins/autotoolsprojectmanager/AutotoolsProjectManager.pluginspec.in b/src/plugins/autotoolsprojectmanager/AutotoolsProjectManager.pluginspec.in
index 657d0d1ce1..1607b135d9 100644
--- a/src/plugins/autotoolsprojectmanager/AutotoolsProjectManager.pluginspec.in
+++ b/src/plugins/autotoolsprojectmanager/AutotoolsProjectManager.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"AutotoolsProjectManager\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\" experimental=\"true\">
+<plugin name=\"AutotoolsProjectManager\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\" experimental=\"true\">
<vendor>Openismus GmbH</vendor>
<copyright>(C) 2013 Openismus GmbH</copyright>
<license>
diff --git a/src/plugins/autotoolsprojectmanager/autogenstep.cpp b/src/plugins/autotoolsprojectmanager/autogenstep.cpp
index f8afd63a02..06071a228e 100644
--- a/src/plugins/autotoolsprojectmanager/autogenstep.cpp
+++ b/src/plugins/autotoolsprojectmanager/autogenstep.cpp
@@ -158,7 +158,7 @@ bool AutogenStep::init()
ProcessParameters *pp = processParameters();
pp->setMacroExpander(bc->macroExpander());
pp->setEnvironment(bc->environment());
- pp->setWorkingDirectory(bc->buildDirectory());
+ pp->setWorkingDirectory(bc->buildDirectory().toString());
pp->setCommand(QLatin1String("autogen.sh"));
pp->setArguments(additionalArguments());
pp->resolveAll();
@@ -171,9 +171,10 @@ void AutogenStep::run(QFutureInterface<bool> &interface)
BuildConfiguration *bc = buildConfiguration();
// Check whether we need to run autogen.sh
- const QFileInfo configureInfo(bc->buildDirectory() + QLatin1String("/configure"));
- const QFileInfo configureAcInfo(bc->buildDirectory() + QLatin1String("/configure.ac"));
- const QFileInfo makefileAmInfo(bc->buildDirectory() + QLatin1String("/Makefile.am"));
+ const QString buildDir = bc->buildDirectory().toString();
+ const QFileInfo configureInfo(buildDir + QLatin1String("/configure"));
+ const QFileInfo configureAcInfo(buildDir + QLatin1String("/configure.ac"));
+ const QFileInfo makefileAmInfo(buildDir + QLatin1String("/Makefile.am"));
if (!configureInfo.exists()
|| configureInfo.lastModified() < configureAcInfo.lastModified()
@@ -275,7 +276,7 @@ void AutogenStepConfigWidget::updateDetails()
ProcessParameters param;
param.setMacroExpander(bc->macroExpander());
param.setEnvironment(bc->environment());
- param.setWorkingDirectory(bc->buildDirectory());
+ param.setWorkingDirectory(bc->buildDirectory().toString());
param.setCommand(QLatin1String("autogen.sh"));
param.setArguments(m_autogenStep->additionalArguments());
m_summaryText = param.summary(displayName());
diff --git a/src/plugins/autotoolsprojectmanager/autoreconfstep.cpp b/src/plugins/autotoolsprojectmanager/autoreconfstep.cpp
index adcb7b0096..1b8d7b8990 100644
--- a/src/plugins/autotoolsprojectmanager/autoreconfstep.cpp
+++ b/src/plugins/autotoolsprojectmanager/autoreconfstep.cpp
@@ -157,7 +157,7 @@ bool AutoreconfStep::init()
ProcessParameters *pp = processParameters();
pp->setMacroExpander(bc->macroExpander());
pp->setEnvironment(bc->environment());
- pp->setWorkingDirectory(bc->buildDirectory());
+ pp->setWorkingDirectory(bc->buildDirectory().toString());
pp->setCommand(QLatin1String("autoreconf"));
pp->setArguments(additionalArguments());
pp->resolveAll();
@@ -170,7 +170,8 @@ void AutoreconfStep::run(QFutureInterface<bool> &interface)
BuildConfiguration *bc = buildConfiguration();
// Check whether we need to run autoreconf
- const QFileInfo configureInfo(bc->buildDirectory() + QLatin1String("/configure"));
+ const QString buildDir = bc->buildDirectory().toString();
+ const QFileInfo configureInfo(buildDir + QLatin1String("/configure"));
if (!configureInfo.exists())
m_runAutoreconf = true;
@@ -269,7 +270,7 @@ void AutoreconfStepConfigWidget::updateDetails()
ProcessParameters param;
param.setMacroExpander(bc->macroExpander());
param.setEnvironment(bc->environment());
- param.setWorkingDirectory(bc->buildDirectory());
+ param.setWorkingDirectory(bc->buildDirectory().toString());
param.setCommand(QLatin1String("autoreconf"));
param.setArguments(m_autoreconfStep->additionalArguments());
m_summaryText = param.summary(displayName());
diff --git a/src/plugins/autotoolsprojectmanager/autotoolsbuildconfiguration.cpp b/src/plugins/autotoolsprojectmanager/autotoolsbuildconfiguration.cpp
index bf07d5c593..b09a1b156f 100644
--- a/src/plugins/autotoolsprojectmanager/autotoolsbuildconfiguration.cpp
+++ b/src/plugins/autotoolsprojectmanager/autotoolsbuildconfiguration.cpp
@@ -38,6 +38,9 @@
#include "autoreconfstep.h"
#include "configurestep.h"
+#include <coreplugin/icore.h>
+#include <coreplugin/mimedatabase.h>
+#include <projectexplorer/buildinfo.h>
#include <projectexplorer/buildsteplist.h>
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/projectexplorerconstants.h>
@@ -46,6 +49,7 @@
#include <qtsupport/customexecutablerunconfiguration.h>
#include <utils/qtcassert.h>
+#include <QFileInfo>
#include <QInputDialog>
using namespace AutotoolsProjectManager;
@@ -59,11 +63,7 @@ using namespace ProjectExplorer::Constants;
//////////////////////////////////////
AutotoolsBuildConfiguration::AutotoolsBuildConfiguration(ProjectExplorer::Target *parent)
: BuildConfiguration(parent, Core::Id(AUTOTOOLS_BC_ID))
-{
- AutotoolsProject *project = qobject_cast<AutotoolsProject *>(parent->project());
- if (project)
- m_buildDirectory = project->defaultBuildDirectory();
-}
+{ }
NamedWidget *AutotoolsBuildConfiguration::createConfigWidget()
{
@@ -72,46 +72,15 @@ NamedWidget *AutotoolsBuildConfiguration::createConfigWidget()
AutotoolsBuildConfiguration::AutotoolsBuildConfiguration(ProjectExplorer::Target *parent, const Core::Id id)
: BuildConfiguration(parent, id)
-{
-}
+{ }
AutotoolsBuildConfiguration::AutotoolsBuildConfiguration(ProjectExplorer::Target *parent,
AutotoolsBuildConfiguration *source)
- : BuildConfiguration(parent, source),
- m_buildDirectory(source->m_buildDirectory)
+ : BuildConfiguration(parent, source)
{
cloneSteps(source);
}
-QVariantMap AutotoolsBuildConfiguration::toMap() const
-{
- QVariantMap map = BuildConfiguration::toMap();
- map.insert(QLatin1String(BUILD_DIRECTORY_KEY), m_buildDirectory);
- return map;
-}
-
-bool AutotoolsBuildConfiguration::fromMap(const QVariantMap &map)
-{
- if (!BuildConfiguration::fromMap(map))
- return false;
-
- m_buildDirectory = map.value(QLatin1String(BUILD_DIRECTORY_KEY)).toString();
- return true;
-}
-
-QString AutotoolsBuildConfiguration::buildDirectory() const
-{
- return m_buildDirectory;
-}
-
-void AutotoolsBuildConfiguration::setBuildDirectory(const QString &buildDirectory)
-{
- if (m_buildDirectory == buildDirectory)
- return;
- m_buildDirectory = buildDirectory;
- emit buildDirectoryChanged();
-}
-
//////////////////////////////////////
// AutotoolsBuildConfiguration class
//////////////////////////////////////
@@ -120,59 +89,56 @@ AutotoolsBuildConfigurationFactory::AutotoolsBuildConfigurationFactory(QObject *
{
}
-QList<Core::Id> AutotoolsBuildConfigurationFactory::availableCreationIds(const Target *parent) const
+bool AutotoolsBuildConfigurationFactory::canCreate(const Target *parent) const
{
- if (!canHandle(parent))
- return QList<Core::Id>();
- return QList<Core::Id>() << Core::Id(AUTOTOOLS_BC_ID);
+ return canHandle(parent);
}
-QString AutotoolsBuildConfigurationFactory::displayNameForId(const Core::Id id) const
+QList<BuildInfo *> AutotoolsBuildConfigurationFactory::availableBuilds(const Target *parent) const
{
- if (id == AUTOTOOLS_BC_ID)
- return tr("Build");
- return QString();
+ QList<BuildInfo *> result;
+ QTC_ASSERT(canCreate(parent), return result);
+
+ result << createBuildInfo(parent->kit(),
+ Utils::FileName::fromString(parent->project()->projectDirectory()));
+ return result;
}
-bool AutotoolsBuildConfigurationFactory::canCreate(const Target *parent, const Core::Id id) const
+bool AutotoolsBuildConfigurationFactory::canSetup(const Kit *k, const QString &projectPath) const
{
- if (!canHandle(parent))
- return false;
- if (id == AUTOTOOLS_BC_ID)
- return true;
- return false;
+ return k && Core::MimeDatabase::findByFile(QFileInfo(projectPath))
+ .matchesType(QLatin1String(Constants::MAKEFILE_MIMETYPE));
}
-AutotoolsBuildConfiguration *AutotoolsBuildConfigurationFactory::create(Target *parent, const Core::Id id, const QString &name)
+QList<BuildInfo *> AutotoolsBuildConfigurationFactory::availableSetups(const Kit *k, const QString &projectPath) const
{
- if (!canCreate(parent, id))
- return 0;
-
- bool ok = true;
- QString buildConfigurationName = name;
- if (buildConfigurationName.isNull())
- buildConfigurationName = QInputDialog::getText(0,
- tr("New Configuration"),
- tr("New configuration name:"),
- QLineEdit::Normal,
- QString(), &ok);
- buildConfigurationName = buildConfigurationName.trimmed();
- if (!ok || buildConfigurationName.isEmpty())
- return 0;
-
- AutotoolsBuildConfiguration *bc = createDefaultConfiguration(parent);
- bc->setDisplayName(buildConfigurationName);
- return bc;
+ QList<BuildInfo *> result;
+ QTC_ASSERT(canSetup(k, projectPath), return result);
+ BuildInfo *info = createBuildInfo(k,
+ Utils::FileName::fromString(AutotoolsProject::defaultBuildDirectory(projectPath)));
+ //: The name of the build configuration created by default for a autotools project.
+ info->displayName = tr("Default");
+ result << info;
+ return result;
}
-AutotoolsBuildConfiguration *AutotoolsBuildConfigurationFactory::createDefaultConfiguration(ProjectExplorer::Target *target)
+BuildConfiguration *AutotoolsBuildConfigurationFactory::create(Target *parent, const BuildInfo *info) const
{
- AutotoolsBuildConfiguration *bc = new AutotoolsBuildConfiguration(target);
+ QTC_ASSERT(parent, return 0);
+ QTC_ASSERT(info->factory() == this, return 0);
+ QTC_ASSERT(info->kitId == parent->kit()->id(), return 0);
+ QTC_ASSERT(!info->displayName.isEmpty(), return 0);
+
+ AutotoolsBuildConfiguration *bc = new AutotoolsBuildConfiguration(parent);
+ bc->setDisplayName(info->displayName);
+ bc->setDefaultDisplayName(info->displayName);
+ bc->setBuildDirectory(info->buildDirectory);
+
BuildStepList *buildSteps = bc->stepList(Core::Id(BUILDSTEPS_BUILD));
// ### Build Steps Build ###
// autogen.sh or autoreconf
- QFile autogenFile(target->project()->projectDirectory() + QLatin1String("/autogen.sh"));
+ QFile autogenFile(parent->project()->projectDirectory() + QLatin1String("/autogen.sh"));
if (autogenFile.exists()) {
AutogenStep *autogenStep = new AutogenStep(buildSteps);
buildSteps->insertStep(0, autogenStep);
@@ -203,14 +169,30 @@ AutotoolsBuildConfiguration *AutotoolsBuildConfigurationFactory::createDefaultCo
bool AutotoolsBuildConfigurationFactory::canHandle(const Target *t) const
{
+ QTC_ASSERT(t, return false);
+
if (!t->project()->supportsKit(t->kit()))
return false;
return t->project()->id() == Constants::AUTOTOOLS_PROJECT_ID;
}
+BuildInfo *AutotoolsBuildConfigurationFactory::createBuildInfo(const ProjectExplorer::Kit *k,
+ const Utils::FileName &buildDir) const
+{
+ BuildInfo *info = new BuildInfo(this);
+ info->typeName = tr("Build");
+ info->buildDirectory = buildDir;
+ info->kitId = k->id();
+ info->supportsShadowBuild = true; // Works sometimes...
+
+ return info;
+}
+
bool AutotoolsBuildConfigurationFactory::canClone(const Target *parent, BuildConfiguration *source) const
{
- return canCreate(parent, source->id());
+ if (!canHandle(parent))
+ return false;
+ return source->id() == AUTOTOOLS_BC_ID;
}
AutotoolsBuildConfiguration *AutotoolsBuildConfigurationFactory::clone(Target *parent, BuildConfiguration *source)
@@ -224,7 +206,9 @@ AutotoolsBuildConfiguration *AutotoolsBuildConfigurationFactory::clone(Target *p
bool AutotoolsBuildConfigurationFactory::canRestore(const Target *parent, const QVariantMap &map) const
{
- return canCreate(parent, idFromMap(map));
+ if (!canHandle(parent))
+ return false;
+ return idFromMap(map) == AUTOTOOLS_BC_ID;
}
AutotoolsBuildConfiguration *AutotoolsBuildConfigurationFactory::restore(Target *parent, const QVariantMap &map)
diff --git a/src/plugins/autotoolsprojectmanager/autotoolsbuildconfiguration.h b/src/plugins/autotoolsprojectmanager/autotoolsbuildconfiguration.h
index 639efc305d..3375cd3428 100644
--- a/src/plugins/autotoolsprojectmanager/autotoolsbuildconfiguration.h
+++ b/src/plugins/autotoolsprojectmanager/autotoolsbuildconfiguration.h
@@ -34,11 +34,14 @@
#include <projectexplorer/buildconfiguration.h>
+namespace Utils { class FileName; }
+
namespace AutotoolsProjectManager {
namespace Internal {
class AutotoolsTarget;
class AutotoolsBuildConfigurationFactory;
+class AutotoolsBuildSettingsWidget;
class AutotoolsBuildConfiguration : public ProjectExplorer::BuildConfiguration
{
@@ -50,19 +53,13 @@ public:
ProjectExplorer::NamedWidget *createConfigWidget();
- QString buildDirectory() const;
- void setBuildDirectory(const QString &buildDirectory);
- QVariantMap toMap() const;
BuildType buildType() const;
protected:
AutotoolsBuildConfiguration(ProjectExplorer::Target *parent, const Core::Id id);
AutotoolsBuildConfiguration(ProjectExplorer::Target *parent, AutotoolsBuildConfiguration *source);
- bool fromMap(const QVariantMap &map);
-
-private:
- QString m_buildDirectory;
+ friend class AutotoolsBuildSettingsWidget;
};
class AutotoolsBuildConfigurationFactory : public ProjectExplorer::IBuildConfigurationFactory
@@ -72,20 +69,22 @@ class AutotoolsBuildConfigurationFactory : public ProjectExplorer::IBuildConfigu
public:
explicit AutotoolsBuildConfigurationFactory(QObject *parent = 0);
- QList<Core::Id> availableCreationIds(const ProjectExplorer::Target *parent) const;
- QString displayNameForId(const Core::Id id) const;
+ bool canCreate(const ProjectExplorer::Target *parent) const;
+ QList<ProjectExplorer::BuildInfo *> availableBuilds(const ProjectExplorer::Target *parent) const;
+ bool canSetup(const ProjectExplorer::Kit *k, const QString &projectPath) const;
+ QList<ProjectExplorer::BuildInfo *> availableSetups(const ProjectExplorer::Kit *k,
+ const QString &projectPath) const;
+ ProjectExplorer::BuildConfiguration *create(ProjectExplorer::Target *parent,
+ const ProjectExplorer::BuildInfo *info) const;
- bool canCreate(const ProjectExplorer::Target *parent, const Core::Id id) const;
- AutotoolsBuildConfiguration *create(ProjectExplorer::Target *parent, const Core::Id id, const QString &name = QString());
bool canClone(const ProjectExplorer::Target *parent, ProjectExplorer::BuildConfiguration *source) const;
AutotoolsBuildConfiguration *clone(ProjectExplorer::Target *parent, ProjectExplorer::BuildConfiguration *source);
bool canRestore(const ProjectExplorer::Target *parent, const QVariantMap &map) const;
AutotoolsBuildConfiguration *restore(ProjectExplorer::Target *parent, const QVariantMap &map);
- static AutotoolsBuildConfiguration *createDefaultConfiguration(ProjectExplorer::Target *target);
-
private:
bool canHandle(const ProjectExplorer::Target *t) const;
+ ProjectExplorer::BuildInfo *createBuildInfo(const ProjectExplorer::Kit *k, const Utils::FileName &buildDir) const;
};
} // namespace Internal
diff --git a/src/plugins/autotoolsprojectmanager/autotoolsbuildsettingswidget.cpp b/src/plugins/autotoolsprojectmanager/autotoolsbuildsettingswidget.cpp
index e55079283b..627510bb46 100644
--- a/src/plugins/autotoolsprojectmanager/autotoolsbuildsettingswidget.cpp
+++ b/src/plugins/autotoolsprojectmanager/autotoolsbuildsettingswidget.cpp
@@ -59,15 +59,24 @@ AutotoolsBuildSettingsWidget::AutotoolsBuildSettingsWidget(AutotoolsBuildConfigu
m_pathChooser = new Utils::PathChooser(this);
m_pathChooser->setEnabled(true);
m_pathChooser->setExpectedKind(Utils::PathChooser::Directory);
+ m_pathChooser->setBaseDirectory(bc->target()->project()->projectDirectory());
+ m_pathChooser->setEnvironment(bc->environment());
fl->addRow(tr("Build directory:"), m_pathChooser);
connect(m_pathChooser, SIGNAL(changed(QString)), this, SLOT(buildDirectoryChanged()));
m_pathChooser->setBaseDirectory(bc->target()->project()->projectDirectory());
- m_pathChooser->setPath(m_buildConfiguration->buildDirectory());
+ m_pathChooser->setPath(m_buildConfiguration->rawBuildDirectory().toString());
setDisplayName(tr("Autotools Manager"));
+
+ connect(bc, SIGNAL(environmentChanged()), this, SLOT(environmentHasChanged()));
}
void AutotoolsBuildSettingsWidget::buildDirectoryChanged()
{
- m_buildConfiguration->setBuildDirectory(m_pathChooser->rawPath());
+ m_buildConfiguration->setBuildDirectory(Utils::FileName::fromString(m_pathChooser->rawPath()));
+}
+
+void AutotoolsBuildSettingsWidget::environmentHasChanged()
+{
+ m_pathChooser->setEnvironment(m_buildConfiguration->environment());
}
diff --git a/src/plugins/autotoolsprojectmanager/autotoolsbuildsettingswidget.h b/src/plugins/autotoolsprojectmanager/autotoolsbuildsettingswidget.h
index 459fb2e234..183c2e4300 100644
--- a/src/plugins/autotoolsprojectmanager/autotoolsbuildsettingswidget.h
+++ b/src/plugins/autotoolsprojectmanager/autotoolsbuildsettingswidget.h
@@ -61,6 +61,7 @@ public:
private slots:
void buildDirectoryChanged();
+ void environmentHasChanged();
private:
Utils::PathChooser *m_pathChooser;
diff --git a/src/plugins/autotoolsprojectmanager/autotoolsproject.cpp b/src/plugins/autotoolsprojectmanager/autotoolsproject.cpp
index 4cffc35127..06c9fbb51c 100644
--- a/src/plugins/autotoolsprojectmanager/autotoolsproject.cpp
+++ b/src/plugins/autotoolsprojectmanager/autotoolsproject.cpp
@@ -125,7 +125,12 @@ IProjectManager *AutotoolsProject::projectManager() const
QString AutotoolsProject::defaultBuildDirectory() const
{
- return projectDirectory();
+ return defaultBuildDirectory(projectFilePath());
+}
+
+QString AutotoolsProject::defaultBuildDirectory(const QString &projectPath)
+{
+ return QFileInfo(projectPath).absolutePath();
}
ProjectNode *AutotoolsProject::rootProjectNode() const
@@ -152,7 +157,7 @@ bool AutotoolsProject::fromMap(const QVariantMap &map)
// Load the project tree structure.
loadProjectTree();
- Kit *defaultKit = KitManager::instance()->defaultKit();
+ Kit *defaultKit = KitManager::defaultKit();
if (!activeTarget() && defaultKit)
addTarget(createTarget(defaultKit));
diff --git a/src/plugins/autotoolsprojectmanager/autotoolsproject.h b/src/plugins/autotoolsprojectmanager/autotoolsproject.h
index 9da7c6a1dd..f5304358c5 100644
--- a/src/plugins/autotoolsprojectmanager/autotoolsproject.h
+++ b/src/plugins/autotoolsprojectmanager/autotoolsproject.h
@@ -34,6 +34,8 @@
#include <projectexplorer/project.h>
+#include <utils/fileutils.h>
+
QT_FORWARD_DECLARE_CLASS(QDir)
namespace Utils {
@@ -77,6 +79,7 @@ public:
ProjectExplorer::ProjectNode *rootProjectNode() const;
QStringList files(FilesMode fileMode) const;
QString defaultBuildDirectory() const;
+ static QString defaultBuildDirectory(const QString &projectPath);
QStringList buildTargets() const;
protected:
diff --git a/src/plugins/autotoolsprojectmanager/autotoolsprojectconstants.h b/src/plugins/autotoolsprojectmanager/autotoolsprojectconstants.h
index 382737e709..44a0c21f6d 100644
--- a/src/plugins/autotoolsprojectmanager/autotoolsprojectconstants.h
+++ b/src/plugins/autotoolsprojectmanager/autotoolsprojectconstants.h
@@ -41,7 +41,6 @@ namespace Constants {
//BuildConfiguration
const char AUTOTOOLS_BC_ID[] = "AutotoolsProjectManager.AutotoolsBuildConfiguration";
- const char BUILD_DIRECTORY_KEY[] = "AutotoolsProjectManager.AutotoolsBuildConfiguration.BuildDirectory";
//Project
const char AUTOTOOLS_PROJECT_ID[] = "AutotoolsProjectManager.AutotoolsProject";
diff --git a/src/plugins/autotoolsprojectmanager/autotoolsprojectfile.cpp b/src/plugins/autotoolsprojectmanager/autotoolsprojectfile.cpp
index f1d51367b3..feca2cc241 100644
--- a/src/plugins/autotoolsprojectmanager/autotoolsprojectfile.cpp
+++ b/src/plugins/autotoolsprojectmanager/autotoolsprojectfile.cpp
@@ -38,9 +38,9 @@ using namespace AutotoolsProjectManager::Internal;
AutotoolsProjectFile::AutotoolsProjectFile(AutotoolsProject *project, const QString &fileName) :
Core::IDocument(project),
- m_project(project),
- m_fileName(fileName)
+ m_project(project)
{
+ setFilePath(fileName);
}
bool AutotoolsProjectFile::save(QString *errorString, const QString &fileName, bool autoSave)
@@ -52,11 +52,6 @@ bool AutotoolsProjectFile::save(QString *errorString, const QString &fileName, b
return false;
}
-QString AutotoolsProjectFile::fileName() const
-{
- return m_fileName;
-}
-
QString AutotoolsProjectFile::defaultPath() const
{
return QString();
@@ -90,8 +85,3 @@ bool AutotoolsProjectFile::reload(QString *errorString, ReloadFlag flag, ChangeT
return false;
}
-
-void AutotoolsProjectFile::rename(const QString &newName)
-{
- Q_UNUSED(newName);
-}
diff --git a/src/plugins/autotoolsprojectmanager/autotoolsprojectfile.h b/src/plugins/autotoolsprojectmanager/autotoolsprojectfile.h
index 4c69c7472c..74babf0962 100644
--- a/src/plugins/autotoolsprojectmanager/autotoolsprojectfile.h
+++ b/src/plugins/autotoolsprojectmanager/autotoolsprojectfile.h
@@ -57,18 +57,15 @@ public:
AutotoolsProjectFile(AutotoolsProject *project, const QString &fileName);
bool save(QString *errorString, const QString &fileName, bool autoSave);
- QString fileName() const;
QString defaultPath() const;
QString suggestedFileName() const;
QString mimeType() const;
bool isModified() const;
bool isSaveAsAllowed() const;
bool reload(QString *errorString, ReloadFlag flag, ChangeType type);
- void rename(const QString &newName);
private:
AutotoolsProject *m_project;
- QString m_fileName;
};
} // namespace Internal
diff --git a/src/plugins/autotoolsprojectmanager/autotoolsprojectnode.cpp b/src/plugins/autotoolsprojectmanager/autotoolsprojectnode.cpp
index 10df22e2ae..8bca0724de 100644
--- a/src/plugins/autotoolsprojectmanager/autotoolsprojectnode.cpp
+++ b/src/plugins/autotoolsprojectmanager/autotoolsprojectnode.cpp
@@ -39,7 +39,7 @@ using namespace AutotoolsProjectManager::Internal;
using namespace ProjectExplorer;
AutotoolsProjectNode::AutotoolsProjectNode(AutotoolsProject *project, Core::IDocument *projectFile) :
- ProjectNode(projectFile->fileName()),
+ ProjectNode(projectFile->filePath()),
m_project(project),
m_projectFile(projectFile)
{
@@ -74,39 +74,31 @@ bool AutotoolsProjectNode::removeSubProjects(const QStringList &proFilePaths)
return false;
}
-bool AutotoolsProjectNode::addFiles(const FileType fileType,
- const QStringList &filePaths,
+bool AutotoolsProjectNode::addFiles( const QStringList &filePaths,
QStringList *notAdded)
{
- Q_UNUSED(fileType);
Q_UNUSED(filePaths);
Q_UNUSED(notAdded);
return false;
}
-bool AutotoolsProjectNode::removeFiles(const FileType fileType,
- const QStringList &filePaths,
+bool AutotoolsProjectNode::removeFiles(const QStringList &filePaths,
QStringList *notRemoved)
{
- Q_UNUSED(fileType);
Q_UNUSED(filePaths);
Q_UNUSED(notRemoved);
return false;
}
-bool AutotoolsProjectNode::deleteFiles(const FileType fileType,
- const QStringList &filePaths)
+bool AutotoolsProjectNode::deleteFiles(const QStringList &filePaths)
{
- Q_UNUSED(fileType);
Q_UNUSED(filePaths);
return false;
}
-bool AutotoolsProjectNode::renameFile(const FileType fileType,
- const QString &filePath,
+bool AutotoolsProjectNode::renameFile(const QString &filePath,
const QString &newFilePath)
{
- Q_UNUSED(fileType);
Q_UNUSED(filePath);
Q_UNUSED(newFilePath);
return false;
diff --git a/src/plugins/autotoolsprojectmanager/autotoolsprojectnode.h b/src/plugins/autotoolsprojectmanager/autotoolsprojectnode.h
index a443ad94d3..4257e2ad7f 100644
--- a/src/plugins/autotoolsprojectmanager/autotoolsprojectnode.h
+++ b/src/plugins/autotoolsprojectmanager/autotoolsprojectnode.h
@@ -64,17 +64,11 @@ public:
bool canAddSubProject(const QString &proFilePath) const;
bool addSubProjects(const QStringList &proFilePaths);
bool removeSubProjects(const QStringList &proFilePaths);
- bool addFiles(const ProjectExplorer::FileType fileType,
- const QStringList &filePaths,
- QStringList *notAdded = 0);
- bool removeFiles(const ProjectExplorer::FileType fileType,
- const QStringList &filePaths,
- QStringList *notRemoved = 0);
- bool deleteFiles(const ProjectExplorer::FileType fileType,
- const QStringList &filePaths);
- bool renameFile(const ProjectExplorer::FileType fileType,
- const QString &filePath,
- const QString &newFilePath);
+ bool addFiles(const QStringList &filePaths, QStringList *notAdded = 0);
+ bool removeFiles(const QStringList &filePaths, QStringList *notRemoved = 0);
+ bool deleteFiles(const QStringList &filePaths);
+ bool renameFile(const QString &filePath,
+ const QString &newFilePath);
QList<ProjectExplorer::RunConfiguration *> runConfigurationsFor(Node *node);
private:
diff --git a/src/plugins/autotoolsprojectmanager/autotoolsprojectplugin.cpp b/src/plugins/autotoolsprojectmanager/autotoolsprojectplugin.cpp
index 9e4865e3ec..fbf9d48ddd 100644
--- a/src/plugins/autotoolsprojectmanager/autotoolsprojectplugin.cpp
+++ b/src/plugins/autotoolsprojectmanager/autotoolsprojectplugin.cpp
@@ -38,7 +38,6 @@
#include "configurestep.h"
#include "autotoolsprojectconstants.h"
-#include <coreplugin/icore.h>
#include <coreplugin/mimedatabase.h>
#include <QStringList>
@@ -59,7 +58,7 @@ bool AutotoolsProjectPlugin::initialize(const QStringList &arguments,
{
Q_UNUSED(arguments);
- if (!Core::ICore::mimeDatabase()->addMimeTypes(QLatin1String(":autotoolsproject/AutotoolsProjectManager.mimetypes.xml"), errorString))
+ if (!Core::MimeDatabase::addMimeTypes(QLatin1String(":autotoolsproject/AutotoolsProjectManager.mimetypes.xml"), errorString))
return false;
addAutoReleasedObject(new AutotoolsBuildConfigurationFactory);
diff --git a/src/plugins/autotoolsprojectmanager/configurestep.cpp b/src/plugins/autotoolsprojectmanager/configurestep.cpp
index 687fcc924e..8f0b13d818 100644
--- a/src/plugins/autotoolsprojectmanager/configurestep.cpp
+++ b/src/plugins/autotoolsprojectmanager/configurestep.cpp
@@ -158,7 +158,7 @@ bool ConfigureStep::init()
ProcessParameters *pp = processParameters();
pp->setMacroExpander(bc->macroExpander());
pp->setEnvironment(bc->environment());
- pp->setWorkingDirectory(bc->buildDirectory());
+ pp->setWorkingDirectory(bc->buildDirectory().toString());
pp->setCommand(QLatin1String("configure"));
pp->setArguments(additionalArguments());
pp->resolveAll();
@@ -171,8 +171,9 @@ void ConfigureStep::run(QFutureInterface<bool>& interface)
BuildConfiguration *bc = buildConfiguration();
//Check whether we need to run configure
- const QFileInfo configureInfo(bc->buildDirectory() + QLatin1String("/configure"));
- const QFileInfo configStatusInfo(bc->buildDirectory() + QLatin1String("/config.status"));
+ QString buildDir = bc->buildDirectory().toString();
+ const QFileInfo configureInfo(buildDir +QLatin1String("/configure"));
+ const QFileInfo configStatusInfo(buildDir + QLatin1String("/config.status"));
if (!configStatusInfo.exists()
|| configStatusInfo.lastModified() < configureInfo.lastModified()) {
@@ -273,7 +274,7 @@ void ConfigureStepConfigWidget::updateDetails()
ProcessParameters param;
param.setMacroExpander(bc->macroExpander());
param.setEnvironment(bc->environment());
- param.setWorkingDirectory(bc->buildDirectory());
+ param.setWorkingDirectory(bc->buildDirectory().toString());
param.setCommand(QLatin1String("configure"));
param.setArguments(m_configureStep->additionalArguments());
m_summaryText = param.summary(displayName());
diff --git a/src/plugins/autotoolsprojectmanager/makestep.cpp b/src/plugins/autotoolsprojectmanager/makestep.cpp
index 2485779999..51206624c4 100644
--- a/src/plugins/autotoolsprojectmanager/makestep.cpp
+++ b/src/plugins/autotoolsprojectmanager/makestep.cpp
@@ -186,7 +186,7 @@ bool MakeStep::init()
// addToEnvironment() to not screw up the users run environment.
env.set(QLatin1String("LC_ALL"), QLatin1String("C"));
pp->setEnvironment(env);
- pp->setWorkingDirectory(bc->buildDirectory());
+ pp->setWorkingDirectory(bc->buildDirectory().toString());
pp->setCommand(tc ? tc->makeCommand(bc->environment()) : QLatin1String("make"));
pp->setArguments(arguments);
pp->resolveAll();
@@ -321,7 +321,7 @@ void MakeStepConfigWidget::updateDetails()
ProcessParameters param;
param.setMacroExpander(bc->macroExpander());
param.setEnvironment(bc->environment());
- param.setWorkingDirectory(bc->buildDirectory());
+ param.setWorkingDirectory(bc->buildDirectory().toString());
param.setCommand(tc->makeCommand(bc->environment()));
param.setArguments(arguments);
m_summaryText = param.summary(displayName());
diff --git a/src/plugins/baremetal/BareMetal.pluginspec.in b/src/plugins/baremetal/BareMetal.pluginspec.in
new file mode 100644
index 0000000000..fb4d476f93
--- /dev/null
+++ b/src/plugins/baremetal/BareMetal.pluginspec.in
@@ -0,0 +1,17 @@
+<plugin name=\"BareMetal\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\" experimental=\"true\">
+ <vendor>Tim Sander</vendor>
+ <copyright>Copyright (C) 2013 Tim Sander</copyright>
+ <license>
+ Commercial Usage
+
+ 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>
+ <description>This plugin adds a target for bare metal development.</description>
+ <category>Device Support</category>
+ <url></url>
+ $$dependencyList
+</plugin>
diff --git a/src/plugins/baremetal/baremetal.pro b/src/plugins/baremetal/baremetal.pro
new file mode 100644
index 0000000000..421ad0d69c
--- /dev/null
+++ b/src/plugins/baremetal/baremetal.pro
@@ -0,0 +1,34 @@
+QT += network
+PROVIDER = Sander
+include(../../qtcreatorplugin.pri)
+
+# BareMetal files
+
+SOURCES += baremetalplugin.cpp \
+ baremetaldevice.cpp \
+ baremetalrunconfigurationfactory.cpp \
+ baremetalrunconfiguration.cpp \
+ baremetalrunconfigurationwidget.cpp \
+ baremetalgdbcommandsdeploystep.cpp \
+ baremetalruncontrolfactory.cpp \
+ baremetaldeviceconfigurationwizardpages.cpp \
+ baremetaldeviceconfigurationwizard.cpp \
+ baremetaldeviceconfigurationwidget.cpp \
+ baremetaldeviceconfigurationfactory.cpp
+
+HEADERS += baremetalplugin.h \
+ baremetalconstants.h \
+ baremetaldevice.h \
+ baremetalrunconfigurationfactory.h \
+ baremetalrunconfiguration.h \
+ baremetalrunconfigurationwidget.h \
+ baremetalgdbcommandsdeploystep.h \
+ baremetalruncontrolfactory.h \
+ baremetaldeviceconfigurationfactory.h \
+ baremetaldeviceconfigurationwidget.h \
+ baremetaldeviceconfigurationwizard.h \
+ baremetaldeviceconfigurationwizardpages.h
+
+FORMS += \
+ baremetaldeviceconfigurationwizardsetuppage.ui \
+ baremetaldeviceconfigurationwidget.ui
diff --git a/src/plugins/baremetal/baremetal.qbs b/src/plugins/baremetal/baremetal.qbs
new file mode 100644
index 0000000000..d72987025c
--- /dev/null
+++ b/src/plugins/baremetal/baremetal.qbs
@@ -0,0 +1,30 @@
+import qbs
+
+import "../QtcPlugin.qbs" as QtcPlugin
+
+QtcPlugin {
+ name: "BareMetal"
+ provider: "Sander"
+
+ Depends { name: "Core" }
+ Depends { name: "Debugger" }
+ Depends { name: "ProjectExplorer" }
+ Depends { name: "QtSupport" }
+ Depends { name: "Qt"; submodules: ["network", "widgets"]; }
+
+ files: [
+ "baremetalconstants.h",
+ "baremetaldevice.cpp", "baremetaldevice.h",
+ "baremetaldeviceconfigurationfactory.cpp", "baremetaldeviceconfigurationfactory.h",
+ "baremetaldeviceconfigurationwidget.cpp", "baremetaldeviceconfigurationwidget.h",
+ "baremetaldeviceconfigurationwizard.cpp", "baremetaldeviceconfigurationwizard.h",
+ "baremetaldeviceconfigurationwizardpages.cpp", "baremetaldeviceconfigurationwizardpages.h",
+ "baremetaldeviceconfigurationwizardsetuppage.ui",
+ "baremetalgdbcommandsdeploystep.cpp", "baremetalgdbcommandsdeploystep.h",
+ "baremetalplugin.cpp", "baremetalplugin.h",
+ "baremetalrunconfiguration.cpp", "baremetalrunconfiguration.h",
+ "baremetalrunconfigurationfactory.cpp", "baremetalrunconfigurationfactory.h",
+ "baremetalrunconfigurationwidget.cpp", "baremetalrunconfigurationwidget.h", "baremetaldeviceconfigurationwidget.ui",
+ "baremetalruncontrolfactory.cpp", "baremetalruncontrolfactory.h",
+ ]
+}
diff --git a/src/plugins/baremetal/baremetal_dependencies.pri b/src/plugins/baremetal/baremetal_dependencies.pri
new file mode 100644
index 0000000000..557e8047e6
--- /dev/null
+++ b/src/plugins/baremetal/baremetal_dependencies.pri
@@ -0,0 +1,13 @@
+QTC_PLUGIN_NAME = BareMetal
+QTC_LIB_DEPENDS += \
+ # nothing here at this time
+
+QTC_PLUGIN_DEPENDS += \
+ coreplugin \
+ debugger \
+ projectexplorer \
+ qtsupport
+
+QTC_PLUGIN_RECOMMENDS += \
+ # optional plugin dependencies. nothing here at this time
+
diff --git a/src/plugins/baremetal/baremetalconstants.h b/src/plugins/baremetal/baremetalconstants.h
new file mode 100644
index 0000000000..8e6483dd8f
--- /dev/null
+++ b/src/plugins/baremetal/baremetalconstants.h
@@ -0,0 +1,45 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Tim Sander <tim@krieglstein.org>
+** 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 BAREMETALCONSTANTS_H
+#define BAREMETALCONSTANTS_H
+
+namespace BareMetal {
+namespace Constants {
+
+const char BareMetalOsType[] = "BareMetalOsType";
+
+const char ACTION_ID[] = "BareMetal.Action";
+const char MENU_ID[] = "BareMetal.Menu";
+
+} // namespace BareMetal
+} // namespace Constants
+
+#endif // BAREMETALCONSTANTS_H
+
diff --git a/src/plugins/baremetal/baremetaldeploystepfactory.cpp b/src/plugins/baremetal/baremetaldeploystepfactory.cpp
new file mode 100644
index 0000000000..65d6c33976
--- /dev/null
+++ b/src/plugins/baremetal/baremetaldeploystepfactory.cpp
@@ -0,0 +1,104 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Tim Sander <tim@krieglstein.org>
+** 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 "baremetaldeploystepfactory.h"
+
+#include "baremetaldeployconfiguration.h"
+#include "baremetalgdbcommandsdeploystep.h"
+
+#include <utils/qtcassert.h>
+
+using namespace ProjectExplorer;
+
+namespace BareMetal {
+namespace Internal {
+BareMetalDeployStepFactory::BareMetalDeployStepFactory(QObject *parent) :
+ IBuildStepFactory(parent)
+{
+}
+
+QList<Core::Id> BareMetalDeployStepFactory::availableCreationIds(BuildStepList *parent) const
+{
+ QList<Core::Id> ids;
+ if (!qobject_cast<BareMetalDeployConfiguration *>(parent->parent()))
+ return ids;
+ ids << BareMetalGdbCommandsDeployStep::stepId();
+ return ids;
+}
+
+QString BareMetalDeployStepFactory::displayNameForId(const Core::Id id) const
+{
+ if (id == BareMetalGdbCommandsDeployStep::stepId())
+ return BareMetalGdbCommandsDeployStep::displayName();
+ return QString();
+}
+
+bool BareMetalDeployStepFactory::canCreate(BuildStepList *parent, const Core::Id id) const
+{
+ return availableCreationIds(parent).contains(id);
+}
+
+BuildStep *BareMetalDeployStepFactory::create(BuildStepList *parent, const Core::Id id)
+{
+ QTC_ASSERT(canCreate(parent, id), return 0);
+ if (id == BareMetalGdbCommandsDeployStep::stepId())
+ return new BareMetalGdbCommandsDeployStep(parent, id);
+ return 0;
+}
+
+bool BareMetalDeployStepFactory::canRestore(BuildStepList *parent, const QVariantMap &map) const
+{
+ return canCreate(parent, idFromMap(map));
+}
+
+BuildStep *BareMetalDeployStepFactory::restore(BuildStepList *parent, const QVariantMap &map)
+{
+ QTC_ASSERT(canRestore(parent, map), return 0);
+ BuildStep * const step = create(parent, idFromMap(map));
+ if (!step->fromMap(map)) {
+ delete step;
+ return 0;
+ }
+ return step;
+}
+
+bool BareMetalDeployStepFactory::canClone(BuildStepList *parent, BuildStep *product) const
+{
+ return canCreate(parent, product->id());
+}
+
+BuildStep *BareMetalDeployStepFactory::clone(BuildStepList *parent, BuildStep *product)
+{
+ if (BareMetalGdbCommandsDeployStep * const other = qobject_cast<BareMetalGdbCommandsDeployStep *>(product))
+ return new BareMetalGdbCommandsDeployStep(parent, other);
+ return 0;
+}
+
+} // namespace Internal
+} // namepsace BareMetal
diff --git a/src/plugins/baremetal/baremetaldevice.cpp b/src/plugins/baremetal/baremetaldevice.cpp
new file mode 100644
index 0000000000..3b9a785547
--- /dev/null
+++ b/src/plugins/baremetal/baremetaldevice.cpp
@@ -0,0 +1,121 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Tim Sander <tim@krieglstein.org>
+** 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 "baremetaldevice.h"
+#include "baremetaldeviceconfigurationwidget.h"
+#include <coreplugin/id.h>
+#include <utils/qtcassert.h>
+#include <QCoreApplication>
+
+using namespace ProjectExplorer;
+
+namespace BareMetal {
+namespace Internal {
+
+const char GdbCommandsKey[] = "GdbCommands";
+
+BareMetalDevice::Ptr BareMetalDevice::create()
+{
+ return Ptr(new BareMetalDevice);
+}
+
+BareMetalDevice::Ptr BareMetalDevice::create(const QString &name, Core::Id type, MachineType machineType, Origin origin, Core::Id id)
+{
+ return Ptr(new BareMetalDevice(name, type, machineType, origin, id));
+}
+
+BareMetalDevice::Ptr BareMetalDevice::create(const BareMetalDevice &other)
+{
+ return Ptr(new BareMetalDevice(other));
+}
+
+void BareMetalDevice::fromMap(const QVariantMap &map)
+{
+ IDevice::fromMap(map);
+ setGdbInitCommands(map.value(QLatin1String(GdbCommandsKey)).toString());
+}
+
+QVariantMap BareMetalDevice::toMap() const
+{
+ QVariantMap map = IDevice::toMap();
+ map.insert(QLatin1String(GdbCommandsKey), getGdbInitCommands());
+ return map;
+}
+
+BareMetalDevice::IDevice::Ptr BareMetalDevice::clone() const
+{
+ return Ptr(new BareMetalDevice(*this));
+}
+
+DeviceProcessSignalOperation::Ptr BareMetalDevice::signalOperation() const
+{
+ return ProjectExplorer::DeviceProcessSignalOperation::Ptr();
+}
+
+QString BareMetalDevice::displayType() const
+{
+ return QCoreApplication::translate("BareMetal::Internal::BareMetalDevice", "Bare Metal");
+}
+
+ProjectExplorer::IDeviceWidget *BareMetalDevice::createWidget()
+{
+ return new BareMetalDeviceConfigurationWidget(sharedFromThis());
+}
+
+QList<Core::Id> BareMetalDevice::actionIds() const
+{
+ return QList<Core::Id>(); // no actions
+}
+
+QString BareMetalDevice::displayNameForActionId(Core::Id actionId) const
+{
+ QTC_ASSERT(actionIds().contains(actionId), return QString());
+ return QString();
+}
+
+void BareMetalDevice::executeAction(Core::Id actionId, QWidget *parent)
+{
+ QTC_ASSERT(actionIds().contains(actionId), return);
+ Q_UNUSED(parent);
+}
+
+BareMetalDevice::BareMetalDevice(const QString &name, Core::Id type, MachineType machineType, Origin origin, Core::Id id)
+ : IDevice(type, origin, machineType, id)
+{
+ setDisplayName(name);
+}
+
+BareMetalDevice::BareMetalDevice(const BareMetalDevice &other)
+ : IDevice(other)
+{
+ setGdbInitCommands(other.getGdbInitCommands());
+}
+
+} //namespace Internal
+} //namespace BareMetal
diff --git a/src/plugins/baremetal/baremetaldevice.h b/src/plugins/baremetal/baremetaldevice.h
new file mode 100644
index 0000000000..b7f2a62bd9
--- /dev/null
+++ b/src/plugins/baremetal/baremetaldevice.h
@@ -0,0 +1,75 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Tim Sander <tim@krieglstein.org>
+** 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 BAREMETALDEVICE_H
+#define BAREMETALDEVICE_H
+
+#include <projectexplorer/devicesupport/idevice.h>
+#include <QCoreApplication>
+
+namespace BareMetal {
+namespace Internal {
+
+class BareMetalDevice : public ProjectExplorer::IDevice
+{
+public:
+ typedef QSharedPointer<BareMetalDevice> Ptr;
+ typedef QSharedPointer<const BareMetalDevice> ConstPtr;
+
+ static Ptr create();
+ static Ptr create(const QString &name, Core::Id type, MachineType machineType,
+ Origin origin = ManuallyAdded, Core::Id id = Core::Id());
+ static Ptr create(const BareMetalDevice &other);
+ QString displayType() const;
+ ProjectExplorer::IDeviceWidget *createWidget();
+ QList<Core::Id> actionIds() const;
+ QString displayNameForActionId(Core::Id actionId) const;
+ void executeAction(Core::Id actionId, QWidget *parent);
+ ProjectExplorer::IDevice::Ptr clone() const;
+
+ ProjectExplorer::DeviceProcessSignalOperation::Ptr signalOperation() const;
+
+ QString getGdbInitCommands() const {return m_gdbInitCommands;}
+ void setGdbInitCommands(const QString &gdbCommands) { m_gdbInitCommands=gdbCommands; }
+
+ virtual void fromMap(const QVariantMap &map);
+ virtual QVariantMap toMap() const;
+protected:
+ BareMetalDevice() {}
+ BareMetalDevice(const QString &name, Core::Id type,
+ MachineType machineType, Origin origin, Core::Id id);
+ BareMetalDevice(const BareMetalDevice &other);
+private:
+ BareMetalDevice &operator=(const BareMetalDevice &);
+ QString m_gdbInitCommands;
+};
+
+} //namespace Internal
+} //namespace BareMetal
+#endif // BAREMETALDEVICE_H
diff --git a/src/plugins/baremetal/baremetaldeviceconfigurationfactory.cpp b/src/plugins/baremetal/baremetaldeviceconfigurationfactory.cpp
new file mode 100644
index 0000000000..c92e861590
--- /dev/null
+++ b/src/plugins/baremetal/baremetaldeviceconfigurationfactory.cpp
@@ -0,0 +1,80 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Tim Sander <tim@krieglstein.org>
+** 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 "baremetaldeviceconfigurationfactory.h"
+
+#include "baremetaldeviceconfigurationwizard.h"
+#include "baremetalconstants.h"
+#include "baremetaldevice.h"
+
+#include <utils/qtcassert.h>
+
+using namespace ProjectExplorer;
+
+namespace BareMetal {
+
+BareMetalDeviceConfigurationFactory::BareMetalDeviceConfigurationFactory(QObject *parent)
+ : IDeviceFactory(parent)
+{
+}
+
+QString BareMetalDeviceConfigurationFactory::displayNameForId(Core::Id type) const
+{
+ QTC_ASSERT(type == Constants::BareMetalOsType, return QString());
+ return tr("Bare Metal Device");
+}
+
+QList<Core::Id> BareMetalDeviceConfigurationFactory::availableCreationIds() const
+{
+ return QList<Core::Id>() << Core::Id(Constants::BareMetalOsType);
+}
+
+IDevice::Ptr BareMetalDeviceConfigurationFactory::create(Core::Id id) const
+{
+ QTC_ASSERT(id == Constants::BareMetalOsType, return IDevice::Ptr());
+ BareMetalDeviceConfigurationWizard wizard;
+ if (wizard.exec() != QDialog::Accepted)
+ return IDevice::Ptr();
+ return wizard.device();
+}
+
+bool BareMetalDeviceConfigurationFactory::canRestore(const QVariantMap &map) const
+{
+ return IDevice::typeFromMap(map) == Constants::BareMetalOsType;
+}
+
+IDevice::Ptr BareMetalDeviceConfigurationFactory::restore(const QVariantMap &map) const
+{
+ QTC_ASSERT(canRestore(map), return IDevice::Ptr());
+ const IDevice::Ptr device = Internal::BareMetalDevice::create();
+ device->fromMap(map);
+ return device;
+}
+
+} // namespace BareMetal
diff --git a/src/plugins/baremetal/baremetaldeviceconfigurationfactory.h b/src/plugins/baremetal/baremetaldeviceconfigurationfactory.h
new file mode 100644
index 0000000000..cc07581450
--- /dev/null
+++ b/src/plugins/baremetal/baremetaldeviceconfigurationfactory.h
@@ -0,0 +1,54 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Tim Sander <tim@krieglstein.org>
+** 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 BAREMETALDEVICECONFIGURATIONFACTORY_H
+#define BAREMETALDEVICECONFIGURATIONFACTORY_H
+
+#include <projectexplorer/devicesupport/idevicefactory.h>
+
+namespace BareMetal {
+
+class BareMetalDeviceConfigurationFactory
+ : public ProjectExplorer::IDeviceFactory
+{
+ Q_OBJECT
+
+public:
+ BareMetalDeviceConfigurationFactory(QObject *parent = 0);
+
+ QString displayNameForId(Core::Id type) const;
+ QList<Core::Id> availableCreationIds() const;
+
+ ProjectExplorer::IDevice::Ptr create(Core::Id id) const;
+ bool canRestore(const QVariantMap &map) const;
+ ProjectExplorer::IDevice::Ptr restore(const QVariantMap &map) const;
+};
+
+} // namespace BareMetal
+#endif // BAREMETALDEVICECONFIGURATIONFACTORY_H
diff --git a/src/plugins/baremetal/baremetaldeviceconfigurationwidget.cpp b/src/plugins/baremetal/baremetaldeviceconfigurationwidget.cpp
new file mode 100644
index 0000000000..d22dae4d73
--- /dev/null
+++ b/src/plugins/baremetal/baremetaldeviceconfigurationwidget.cpp
@@ -0,0 +1,97 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Tim Sander <tim@krieglstein.org>
+** 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 "baremetaldeviceconfigurationwidget.h"
+
+#include "ui_baremetaldeviceconfigurationwidget.h"
+#include "baremetaldevice.h"
+
+#include <ssh/sshconnection.h>
+#include <utils/qtcassert.h>
+#include <QLabel>
+
+using namespace QSsh;
+namespace BareMetal {
+using namespace Internal;
+
+BareMetalDeviceConfigurationWidget::BareMetalDeviceConfigurationWidget(
+ const ProjectExplorer::IDevice::Ptr &deviceConfig, QWidget *parent) :
+ IDeviceWidget(deviceConfig, parent),
+ m_ui(new Ui::BareMetalDeviceConfigurationWidget)
+{
+ m_ui->setupUi(this);
+ connect(m_ui->gdbHostLineEdit, SIGNAL(editingFinished()), SLOT(hostnameChanged()));
+ connect(m_ui->gdbPortSpinBox, SIGNAL(valueChanged(int)), SLOT(portChanged()));
+ connect(m_ui->gdbCommandsTextEdit, SIGNAL(textChanged()), SLOT(gdbInitCommandsChanged()));
+ initGui();
+}
+
+BareMetalDeviceConfigurationWidget::~BareMetalDeviceConfigurationWidget()
+{
+ delete m_ui;
+}
+
+void BareMetalDeviceConfigurationWidget::hostnameChanged()
+{
+ SshConnectionParameters sshParams = device()->sshParameters();
+ sshParams.host = m_ui->gdbHostLineEdit->text().trimmed();
+ device()->setSshParameters(sshParams);
+}
+
+void BareMetalDeviceConfigurationWidget::portChanged()
+{
+ SshConnectionParameters sshParams = device()->sshParameters();
+ sshParams.port = m_ui->gdbPortSpinBox->value();
+ device()->setSshParameters(sshParams);
+}
+
+void BareMetalDeviceConfigurationWidget::gdbInitCommandsChanged()
+{
+ QSharedPointer<BareMetalDevice> p = qSharedPointerCast<BareMetalDevice>(device());
+ QTC_ASSERT(!p.isNull(), return);
+ p->setGdbInitCommands(m_ui->gdbCommandsTextEdit->toPlainText());
+}
+
+void BareMetalDeviceConfigurationWidget::updateDeviceFromUi() {
+ hostnameChanged();
+ portChanged();
+ gdbInitCommandsChanged();
+}
+
+void BareMetalDeviceConfigurationWidget::initGui()
+{
+ SshConnectionParameters sshParams = device()->sshParameters();
+ m_ui->gdbHostLineEdit->setText(sshParams.host);
+ m_ui->gdbPortSpinBox->setValue(sshParams.port);
+ QSharedPointer<BareMetalDevice> p = qSharedPointerCast<BareMetalDevice>(device());
+ QTC_ASSERT(!p.isNull(), return);
+ m_ui->gdbCommandsTextEdit->setPlainText(p->getGdbInitCommands());
+}
+
+} //namespace BareMetal
diff --git a/src/plugins/baremetal/baremetaldeviceconfigurationwidget.h b/src/plugins/baremetal/baremetaldeviceconfigurationwidget.h
new file mode 100644
index 0000000000..2953f21c2a
--- /dev/null
+++ b/src/plugins/baremetal/baremetaldeviceconfigurationwidget.h
@@ -0,0 +1,61 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Tim Sander <tim@krieglstein.org>
+** 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 BAREMETALDEVICECONFIGURATIONWIDGET_H
+#define BAREMETALDEVICECONFIGURATIONWIDGET_H
+
+#include <projectexplorer/devicesupport/idevicewidget.h>
+
+namespace BareMetal {
+
+namespace Ui {
+class BareMetalDeviceConfigurationWidget;
+}
+
+class BareMetalDeviceConfigurationWidget
+ : public ProjectExplorer::IDeviceWidget
+{
+ Q_OBJECT
+public:
+ explicit BareMetalDeviceConfigurationWidget(
+ const ProjectExplorer::IDevice::Ptr &deviceConfig, QWidget *parent = 0);
+ ~BareMetalDeviceConfigurationWidget();
+private slots:
+ void hostnameChanged();
+ void portChanged();
+ void gdbInitCommandsChanged();
+
+private:
+ void updateDeviceFromUi();
+ void initGui();
+ Ui::BareMetalDeviceConfigurationWidget *m_ui;
+};
+
+} //namespace BareMetal
+#endif // BAREMETALDEVICECONFIGURATIONWIDGET_H
diff --git a/src/plugins/baremetal/baremetaldeviceconfigurationwidget.ui b/src/plugins/baremetal/baremetaldeviceconfigurationwidget.ui
new file mode 100644
index 0000000000..6abfdb57d8
--- /dev/null
+++ b/src/plugins/baremetal/baremetaldeviceconfigurationwidget.ui
@@ -0,0 +1,82 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>BareMetal::BareMetalDeviceConfigurationWidget</class>
+ <widget class="QWidget" name="BareMetal::BareMetalDeviceConfigurationWidget">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>496</width>
+ <height>251</height>
+ </rect>
+ </property>
+ <property name="minimumSize">
+ <size>
+ <width>100</width>
+ <height>100</height>
+ </size>
+ </property>
+ <property name="windowTitle">
+ <string>Form</string>
+ </property>
+ <property name="locale">
+ <locale language="English" country="UnitedStates"/>
+ </property>
+ <layout class="QFormLayout" name="formLayout">
+ <property name="fieldGrowthPolicy">
+ <enum>QFormLayout::ExpandingFieldsGrow</enum>
+ </property>
+ <item row="0" column="0">
+ <widget class="QLabel" name="gdbHostLabel">
+ <property name="locale">
+ <locale language="English" country="UnitedStates"/>
+ </property>
+ <property name="text">
+ <string>GDB Host:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="1">
+ <widget class="QLineEdit" name="gdbHostLineEdit"/>
+ </item>
+ <item row="1" column="0">
+ <widget class="QLabel" name="gdbPortLabel">
+ <property name="locale">
+ <locale language="English" country="UnitedStates"/>
+ </property>
+ <property name="text">
+ <string>GDB Port:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="1">
+ <widget class="QSpinBox" name="gdbPortSpinBox">
+ <property name="minimum">
+ <number>1</number>
+ </property>
+ <property name="maximum">
+ <number>65535</number>
+ </property>
+ <property name="value">
+ <number>3333</number>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="0">
+ <widget class="QLabel" name="gdbCommandsLabel">
+ <property name="locale">
+ <locale language="English" country="UnitedStates"/>
+ </property>
+ <property name="text">
+ <string>GDB commands:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="1">
+ <widget class="QPlainTextEdit" name="gdbCommandsTextEdit"/>
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/src/plugins/baremetal/baremetaldeviceconfigurationwizard.cpp b/src/plugins/baremetal/baremetaldeviceconfigurationwizard.cpp
new file mode 100644
index 0000000000..cee788b316
--- /dev/null
+++ b/src/plugins/baremetal/baremetaldeviceconfigurationwizard.cpp
@@ -0,0 +1,85 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Tim Sander <tim@krieglstein.org>
+** 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 "baremetaldeviceconfigurationwizard.h"
+#include "baremetaldeviceconfigurationwizardpages.h"
+#include "baremetaldevice.h"
+#include "baremetalconstants.h"
+#include "ssh/sshconnection.h"
+
+using namespace ProjectExplorer;
+
+namespace BareMetal {
+namespace Internal {
+namespace {
+enum PageId { SetupPageId };
+} // anonymous namespace
+
+
+class BareMetalDeviceConfigrationWizardPrivate
+{
+public:
+ BareMetalDeviceConfigrationWizardPrivate(QWidget *parent):
+ m_setupPage(parent)
+ { }
+
+ BareMetalDeviceConfigurationWizardSetupPage m_setupPage;
+};
+
+} //namespace Internal
+
+BareMetalDeviceConfigurationWizard::BareMetalDeviceConfigurationWizard(QWidget *parent) :
+ QWizard(parent),
+ d(new Internal::BareMetalDeviceConfigrationWizardPrivate(this))
+{
+ setWindowTitle(tr("New Bare Metal Device Configuration Setup"));
+ setPage(Internal::SetupPageId, &d->m_setupPage);
+ d->m_setupPage.setCommitPage(true);
+}
+
+BareMetalDeviceConfigurationWizard::~BareMetalDeviceConfigurationWizard()
+{
+ delete d;
+}
+
+IDevice::Ptr BareMetalDeviceConfigurationWizard::device() const
+{
+ //sshParams is not really used as ssh parameters but as debugger parameters
+ QSsh::SshConnectionParameters sshParams;
+ sshParams.host = d->m_setupPage.gdbHostname();
+ sshParams.port = d->m_setupPage.gdbPort();
+ Internal::BareMetalDevice::Ptr device = Internal::BareMetalDevice::create(d->m_setupPage.configurationName(),
+ Core::Id(Constants::BareMetalOsType),
+ IDevice::Hardware);
+ device->setSshParameters(sshParams);
+ device->setGdbInitCommands(d->m_setupPage.gdbInitCommands());
+ return device;
+}
+
+} //namespace BareMetal
diff --git a/src/plugins/baremetal/baremetaldeviceconfigurationwizard.h b/src/plugins/baremetal/baremetaldeviceconfigurationwizard.h
new file mode 100644
index 0000000000..3b63d9fa54
--- /dev/null
+++ b/src/plugins/baremetal/baremetaldeviceconfigurationwizard.h
@@ -0,0 +1,58 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Tim Sander <tim@krieglstein.org>
+** 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 BAREMETALDEVICECONFIGURATIONWIZARD_H
+#define BAREMETALDEVICECONFIGURATIONWIZARD_H
+
+#include <projectexplorer/devicesupport/idevice.h>
+
+#include <QWizard>
+
+namespace BareMetal {
+namespace Internal {
+ class BareMetalDeviceConfigrationWizardPrivate;
+} // namespace Internal
+
+class BareMetalDeviceConfigurationWizard : public QWizard
+{
+ Q_OBJECT
+public:
+ BareMetalDeviceConfigurationWizard(QWidget *parent = 0);
+ ~BareMetalDeviceConfigurationWizard();
+
+ ProjectExplorer::IDevice::Ptr device() const;
+
+private:
+ Internal::BareMetalDeviceConfigrationWizardPrivate * const d;
+
+};
+
+} //namespace BareMetal
+
+#endif // BAREMETALDEVICECONFIGURATIONWIZARD_H
diff --git a/src/plugins/baremetal/baremetaldeviceconfigurationwizardpages.cpp b/src/plugins/baremetal/baremetaldeviceconfigurationwizardpages.cpp
new file mode 100644
index 0000000000..84f039c85b
--- /dev/null
+++ b/src/plugins/baremetal/baremetaldeviceconfigurationwizardpages.cpp
@@ -0,0 +1,93 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Tim Sander <tim@krieglstein.org>
+** 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 "baremetaldeviceconfigurationwizardpages.h"
+#include "ui_baremetaldeviceconfigurationwizardsetuppage.h"
+
+#include <projectexplorer/devicesupport/idevice.h>
+
+namespace BareMetal {
+namespace Internal {
+class BareMetalDeviceConfigurationWizardSetupPagePrivate;
+} // namespace Internal
+
+BareMetalDeviceConfigurationWizardSetupPage::BareMetalDeviceConfigurationWizardSetupPage(QWidget *parent) :
+ QWizardPage(parent), d(new Internal::BareMetalDeviceConfigurationWizardSetupPagePrivate)
+{
+ d->ui.setupUi(this);
+ setTitle(tr("Gdbserver/hardware debugger setup"));
+ setSubTitle(QLatin1String(" ")); // For Qt bug (background color)
+ connect(d->ui.hostNameLineEdit,SIGNAL(textChanged(QString)),SIGNAL(completeChanged()));
+ connect(d->ui.nameLineEdit,SIGNAL(textChanged(QString)),SIGNAL(completeChanged()));
+ connect(d->ui.portSpinBox,SIGNAL(valueChanged(int)),SIGNAL(completeChanged()));
+ connect(d->ui.gdbInitCommandsPlainTextEdit,SIGNAL(textChanged()),SIGNAL(completeChanged()));
+}
+
+BareMetalDeviceConfigurationWizardSetupPage::~BareMetalDeviceConfigurationWizardSetupPage()
+{
+ delete d;
+}
+
+void BareMetalDeviceConfigurationWizardSetupPage::initializePage()
+{
+ d->ui.nameLineEdit->setText(defaultConfigurationName());
+
+}
+
+bool BareMetalDeviceConfigurationWizardSetupPage::isComplete() const
+{
+ return !configurationName().isEmpty();
+}
+
+QString BareMetalDeviceConfigurationWizardSetupPage::configurationName() const
+{
+ return d->ui.nameLineEdit->text().trimmed();
+}
+
+QString BareMetalDeviceConfigurationWizardSetupPage::gdbHostname() const
+{
+ return d->ui.hostNameLineEdit->text().trimmed();
+}
+
+quint16 BareMetalDeviceConfigurationWizardSetupPage::gdbPort() const
+{
+ return quint16(d->ui.portSpinBox->value());
+}
+
+QString BareMetalDeviceConfigurationWizardSetupPage::gdbInitCommands() const
+{
+ return d->ui.gdbInitCommandsPlainTextEdit->toPlainText();
+}
+
+QString BareMetalDeviceConfigurationWizardSetupPage::defaultConfigurationName() const
+{
+ return tr("Bare Metal Device");
+}
+
+} // namespace BareMetal
diff --git a/src/plugins/baremetal/baremetaldeviceconfigurationwizardpages.h b/src/plugins/baremetal/baremetaldeviceconfigurationwizardpages.h
new file mode 100644
index 0000000000..3d35e6ed01
--- /dev/null
+++ b/src/plugins/baremetal/baremetaldeviceconfigurationwizardpages.h
@@ -0,0 +1,69 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Tim Sander <tim@krieglstein.org>
+** 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 BAREMETALDEVICECONFIGURATIONWIZARDPAGES_H
+#define BAREMETALDEVICECONFIGURATIONWIZARDPAGES_H
+
+#include "ui_baremetaldeviceconfigurationwizardsetuppage.h"
+#include <QWizardPage>
+
+namespace BareMetal {
+
+namespace Internal {
+
+class BareMetalDeviceConfigurationWizardSetupPagePrivate
+{
+public:
+ Ui::BareMetalDeviceConfigurationWizardSetupPage ui;
+};
+
+} // namespace Internal
+
+class BareMetalDeviceConfigurationWizardSetupPage : public QWizardPage
+{
+ Q_OBJECT
+public:
+ explicit BareMetalDeviceConfigurationWizardSetupPage(QWidget *parent = 0);
+ ~BareMetalDeviceConfigurationWizardSetupPage();
+
+ void initializePage();
+ bool isComplete() const;
+ QString configurationName() const;
+ QString gdbHostname() const;
+ quint16 gdbPort() const;
+ QString gdbInitCommands() const;
+
+ virtual QString defaultConfigurationName() const;
+private:
+ Internal::BareMetalDeviceConfigurationWizardSetupPagePrivate * const d;
+};
+
+} // namespace BareMetal
+
+#endif // BAREMETALDEVICECONFIGURATIONWIZARDPAGES_H
diff --git a/src/plugins/baremetal/baremetaldeviceconfigurationwizardsetuppage.ui b/src/plugins/baremetal/baremetaldeviceconfigurationwizardsetuppage.ui
new file mode 100644
index 0000000000..c3e7201dae
--- /dev/null
+++ b/src/plugins/baremetal/baremetaldeviceconfigurationwizardsetuppage.ui
@@ -0,0 +1,83 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>BareMetal::Internal::BareMetalDeviceConfigurationWizardSetupPage</class>
+ <widget class="QWidget" name="BareMetal::Internal::BareMetalDeviceConfigurationWizardSetupPage">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>517</width>
+ <height>301</height>
+ </rect>
+ </property>
+ <property name="windowTitle">
+ <string>Form</string>
+ </property>
+ <property name="locale">
+ <locale language="English" country="UnitedStates"/>
+ </property>
+ <layout class="QFormLayout" name="formLayout">
+ <item row="0" column="0">
+ <widget class="QLabel" name="namelabel">
+ <property name="text">
+ <string>Name:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="1">
+ <widget class="QLineEdit" name="nameLineEdit"/>
+ </item>
+ <item row="3" column="1">
+ <widget class="QLineEdit" name="hostNameLineEdit">
+ <property name="text">
+ <string>localhost</string>
+ </property>
+ </widget>
+ </item>
+ <item row="6" column="0">
+ <widget class="QLabel" name="HostPortLabel">
+ <property name="text">
+ <string>GDB port:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="3" column="0">
+ <widget class="QLabel" name="hostLabel">
+ <property name="text">
+ <string>GDB host:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="6" column="1">
+ <widget class="QSpinBox" name="portSpinBox">
+ <property name="minimum">
+ <number>1</number>
+ </property>
+ <property name="maximum">
+ <number>65535</number>
+ </property>
+ <property name="value">
+ <number>3333</number>
+ </property>
+ </widget>
+ </item>
+ <item row="7" column="0">
+ <widget class="QLabel" name="gdbInitLabel">
+ <property name="text">
+ <string>GDB commands:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="7" column="1">
+ <widget class="QPlainTextEdit" name="gdbInitCommandsPlainTextEdit">
+ <property name="plainText">
+ <string>load
+monitor reset</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/src/plugins/baremetal/baremetalgdbcommandsdeploystep.cpp b/src/plugins/baremetal/baremetalgdbcommandsdeploystep.cpp
new file mode 100644
index 0000000000..71ca7c9ef9
--- /dev/null
+++ b/src/plugins/baremetal/baremetalgdbcommandsdeploystep.cpp
@@ -0,0 +1,142 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Tim Sander <tim@krieglstein.org>
+** 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 "baremetalgdbcommandsdeploystep.h"
+
+using namespace BareMetal::Internal;
+
+namespace BareMetal {
+namespace Internal {
+
+BareMetalGdbCommandsDeployStepWidget::BareMetalGdbCommandsDeployStepWidget(BareMetalGdbCommandsDeployStep &step)
+ : m_step(step)
+{
+ QFormLayout *fl = new QFormLayout(this);
+ fl->setMargin(0);
+ fl->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow);
+ setLayout(fl);
+ m_commands = new QPlainTextEdit(this);
+ fl->addRow(tr("GDB commands:"),m_commands);
+ m_commands->setPlainText(m_step.gdbCommands());
+ if (!connect(m_commands,SIGNAL(textChanged()),SLOT(update()))) {
+ qDebug()<<"BareMetalGdbCommandsDeployStepWidget connect failed.";
+ }
+}
+
+void BareMetalGdbCommandsDeployStepWidget::update()
+{
+ m_step.updateGdbCommands(m_commands->toPlainText());
+}
+
+QString BareMetalGdbCommandsDeployStepWidget::displayName() const
+{
+ return QLatin1String("<b>") + m_step.displayName() + QLatin1String("</b>");
+}
+
+QString BareMetalGdbCommandsDeployStepWidget::summaryText() const
+{
+ return displayName();
+}
+
+} // namespace Internal
+
+BareMetalGdbCommandsDeployStep::BareMetalGdbCommandsDeployStep(BuildStepList *bsl,
+ const Core::Id id)
+ : BuildStep(bsl, id)
+{
+ ctor();
+}
+
+BareMetalGdbCommandsDeployStep::BareMetalGdbCommandsDeployStep(BuildStepList *bsl,
+ BareMetalGdbCommandsDeployStep *other)
+ : BuildStep(bsl, other)
+{
+ ctor();
+}
+
+void BareMetalGdbCommandsDeployStep::ctor()
+{
+ setDefaultDisplayName(displayName());
+}
+
+BareMetalGdbCommandsDeployStep::~BareMetalGdbCommandsDeployStep()
+{
+}
+
+void BareMetalGdbCommandsDeployStep::run(QFutureInterface<bool> &fi)
+{
+ fi.reportResult(true);
+ emit finished();
+}
+
+bool BareMetalGdbCommandsDeployStep::fromMap(const QVariantMap &map) {
+ if (!BuildStep::fromMap(map))
+ return false;
+ m_gdbCommands = map.value(QLatin1String(Internal::GdbCommandsKey)).toString();
+ return true;
+}
+
+QVariantMap BareMetalGdbCommandsDeployStep::toMap() const
+{
+ QVariantMap map = BuildStep::toMap();
+ map.insert(QLatin1String(Internal::GdbCommandsKey),m_gdbCommands);
+ return map;
+}
+
+ProjectExplorer::BuildStepConfigWidget *BareMetalGdbCommandsDeployStep::createConfigWidget()
+{
+ return new Internal::BareMetalGdbCommandsDeployStepWidget(*this);
+}
+
+Core::Id BareMetalGdbCommandsDeployStep::stepId()
+{
+ return Core::Id("BareMetal.GdbCommandsDeployStep");
+}
+
+QString BareMetalGdbCommandsDeployStep::displayName()
+{
+ return tr("GDB commands");
+}
+
+void BareMetalGdbCommandsDeployStep::updateGdbCommands(const QString &newCommands)
+{
+ m_gdbCommands = newCommands;
+}
+
+QString BareMetalGdbCommandsDeployStep::gdbCommands() const
+{
+ return m_gdbCommands;
+}
+
+bool BareMetalGdbCommandsDeployStep::init()
+{
+ return true;
+}
+
+} // namespace BareMetal
diff --git a/src/plugins/baremetal/baremetalgdbcommandsdeploystep.h b/src/plugins/baremetal/baremetalgdbcommandsdeploystep.h
new file mode 100644
index 0000000000..8c7184413b
--- /dev/null
+++ b/src/plugins/baremetal/baremetalgdbcommandsdeploystep.h
@@ -0,0 +1,91 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Tim Sander <tim@krieglstein.org>
+** 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 BAREMETALGDBCOMMANDSDEPLOYSTEP_H
+#define BAREMETALGDBCOMMANDSDEPLOYSTEP_H
+
+#include <projectexplorer/buildstep.h>
+
+#include <QVariantMap>
+#include <QFormLayout>
+#include <QPlainTextEdit>
+
+
+using namespace ProjectExplorer;
+namespace BareMetal {
+
+class BareMetalGdbCommandsDeployStep : public ProjectExplorer::BuildStep
+{
+ Q_OBJECT
+public:
+ BareMetalGdbCommandsDeployStep(ProjectExplorer::BuildStepList *bsl, const Core::Id id);
+ BareMetalGdbCommandsDeployStep(ProjectExplorer::BuildStepList *bsl,
+ BareMetalGdbCommandsDeployStep *other);
+ ~BareMetalGdbCommandsDeployStep();
+
+ bool init();
+ void run(QFutureInterface<bool> &fi);
+ bool runInGuiThread() const { return true;}
+
+ bool fromMap(const QVariantMap &map);
+ QVariantMap toMap() const;
+
+ ProjectExplorer::BuildStepConfigWidget *createConfigWidget();
+
+ static Core::Id stepId();
+ static QString displayName();
+
+ void updateGdbCommands(const QString &newCommands);
+ QString gdbCommands() const;
+private:
+ void ctor();
+ QString m_gdbCommands;
+};
+
+namespace Internal {
+const char GdbCommandsKey[] = "BareMetal.GdbCommandsStep.Commands";
+
+class BareMetalGdbCommandsDeployStepWidget: public ProjectExplorer::BuildStepConfigWidget
+{
+ Q_OBJECT
+public:
+ explicit BareMetalGdbCommandsDeployStepWidget(BareMetal::BareMetalGdbCommandsDeployStep &step);
+public slots:
+ void update();
+private:
+ QString displayName() const;
+ QString summaryText() const;
+ BareMetal::BareMetalGdbCommandsDeployStep &m_step;
+ QPlainTextEdit *m_commands;
+};
+
+} // Internal namespace
+
+} // namespace BareMetal
+#endif // BAREMETALGDBCOMMANDSDEPLOYSTEP_H
diff --git a/src/plugins/baremetal/baremetalplugin.cpp b/src/plugins/baremetal/baremetalplugin.cpp
new file mode 100644
index 0000000000..e3e3084dd8
--- /dev/null
+++ b/src/plugins/baremetal/baremetalplugin.cpp
@@ -0,0 +1,77 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Tim Sander <tim@krieglstein.org>
+** 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 "baremetalplugin.h"
+#include "baremetalconstants.h"
+#include "baremetaldeviceconfigurationfactory.h"
+#include "baremetalruncontrolfactory.h"
+#include "baremetalrunconfigurationfactory.h"
+
+#include <coreplugin/icore.h>
+#include <coreplugin/icontext.h>
+#include <coreplugin/actionmanager/actionmanager.h>
+#include <coreplugin/actionmanager/command.h>
+#include <coreplugin/actionmanager/actioncontainer.h>
+#include <coreplugin/coreconstants.h>
+
+#include <QAction>
+#include <QMessageBox>
+#include <QMainWindow>
+#include <QMenu>
+#include <QtPlugin>
+
+namespace BareMetal {
+namespace Internal {
+
+BareMetalPlugin::BareMetalPlugin()
+{
+ setObjectName(QLatin1String("BareMetalPlugin"));
+}
+
+BareMetalPlugin::~BareMetalPlugin()
+{
+}
+
+bool BareMetalPlugin::initialize(const QStringList &arguments, QString *errorString)
+{
+ Q_UNUSED(arguments)
+ Q_UNUSED(errorString)
+
+ addAutoReleasedObject(new BareMetalDeviceConfigurationFactory);
+ addAutoReleasedObject(new BareMetalRunControlFactory);
+ addAutoReleasedObject(new BareMetalRunConfigurationFactory);
+
+ return true;
+}
+
+} // namespace Internal
+} // namespace BareMetal
+
+Q_EXPORT_PLUGIN(BareMetal::Internal::BareMetalPlugin)
+
diff --git a/src/plugins/qnx/blackberrydeviceprocesssupport.h b/src/plugins/baremetal/baremetalplugin.h
index e79f647305..512b0cbbc7 100644
--- a/src/plugins/qnx/blackberrydeviceprocesssupport.h
+++ b/src/plugins/baremetal/baremetalplugin.h
@@ -1,9 +1,7 @@
-/**************************************************************************
+/****************************************************************************
**
-** Copyright (C) 2011 - 2013 Research In Motion
-**
-** Contact: Research In Motion (blackberry-qt@qnx.com)
-** Contact: KDAB (info@kdab.com)
+** Copyright (C) 2013 Tim Sander <tim@krieglstein.org>
+** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
@@ -29,21 +27,29 @@
**
****************************************************************************/
-#ifndef QNX_INTERNAL_BLACKBERRYDEVICEPROCESSSUPPORT_H
-#define QNX_INTERNAL_BLACKBERRYDEVICEPROCESSSUPPORT_H
+#ifndef BAREMETAL_H
+#define BAREMETAL_H
-#include <remotelinux/linuxdevice.h>
+#include <extensionsystem/iplugin.h>
-namespace Qnx {
+namespace BareMetal {
namespace Internal {
-class BlackBerryDeviceProcessSupport : public RemoteLinux::LinuxDeviceProcessSupport
+class BareMetalPlugin : public ExtensionSystem::IPlugin
{
+ Q_OBJECT
+ Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QtCreatorPlugin" FILE "BareMetal.json")
+
public:
- QString killProcessByNameCommandLine(const QString &filePath) const;
+ BareMetalPlugin();
+ ~BareMetalPlugin();
+
+ bool initialize(const QStringList &arguments, QString *errorString);
+ void extensionsInitialized() { }
};
} // namespace Internal
-} // namespace Qnx
+} // namespace BareMetal
+
+#endif // BAREMETAL_H
-#endif // QNX_INTERNAL_BLACKBERRYDEVICEPROCESSSUPPORT_H
diff --git a/src/plugins/baremetal/baremetalrunconfiguration.cpp b/src/plugins/baremetal/baremetalrunconfiguration.cpp
new file mode 100644
index 0000000000..14e0c6abf6
--- /dev/null
+++ b/src/plugins/baremetal/baremetalrunconfiguration.cpp
@@ -0,0 +1,210 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Tim Sander <tim@krieglstein.org>
+** 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 "baremetalrunconfiguration.h"
+
+#include "baremetalrunconfigurationwidget.h"
+
+#include <debugger/debuggerrunconfigurationaspect.h>
+#include <projectexplorer/buildtargetinfo.h>
+#include <projectexplorer/deploymentdata.h>
+#include <projectexplorer/project.h>
+#include <projectexplorer/target.h>
+#include <qtsupport/qtoutputformatter.h>
+
+using namespace ProjectExplorer;
+using namespace Utils;
+
+namespace BareMetal {
+namespace Internal {
+
+const char ArgumentsKey[] = "Qt4ProjectManager.MaemoRunConfiguration.Arguments";
+const char ProFileKey[] = "Qt4ProjectManager.MaemoRunConfiguration.ProFile";
+const char WorkingDirectoryKey[] = "BareMetal.RunConfig.WorkingDirectory";
+
+class BareMetalRunConfigurationPrivate
+{
+public:
+ BareMetalRunConfigurationPrivate(const QString &projectFilePath)
+ : projectFilePath(projectFilePath)
+ {
+ }
+
+ BareMetalRunConfigurationPrivate(const BareMetalRunConfigurationPrivate *other)
+ : projectFilePath(other->projectFilePath),
+ gdbPath(other->gdbPath),
+ arguments(other->arguments),
+ workingDirectory(other->workingDirectory)
+ {
+ }
+
+ QString projectFilePath;
+ QString gdbPath;
+ QString arguments;
+ QString disabledReason;
+ QString workingDirectory;
+};
+
+} // namespace Internal
+
+using namespace Internal;
+
+BareMetalRunConfiguration::BareMetalRunConfiguration(Target *parent, BareMetalRunConfiguration *source)
+ : RunConfiguration(parent, source),
+ d(new BareMetalRunConfigurationPrivate(source->d))
+{
+ init();
+}
+
+BareMetalRunConfiguration::BareMetalRunConfiguration(Target *parent,
+ const Core::Id id,
+ const QString &projectFilePath)
+ : RunConfiguration(parent,id),
+ d(new BareMetalRunConfigurationPrivate(projectFilePath))
+{
+ init();
+}
+
+BareMetalRunConfiguration::~BareMetalRunConfiguration()
+{
+ delete d;
+}
+
+void BareMetalRunConfiguration::init()
+{
+ setDefaultDisplayName(defaultDisplayName());
+
+ connect(target(), SIGNAL(deploymentDataChanged()), SLOT(handleBuildSystemDataUpdated()));
+ connect(target(), SIGNAL(applicationTargetsChanged()), SLOT(handleBuildSystemDataUpdated()));
+ connect(target(), SIGNAL(kitChanged()),
+ this, SLOT(handleBuildSystemDataUpdated())); // Handles device changes, etc.
+}
+
+bool BareMetalRunConfiguration::isEnabled() const
+{
+ d->disabledReason.clear();
+ return true;
+}
+
+QString BareMetalRunConfiguration::disabledReason() const
+{
+ return d->disabledReason;
+}
+
+QWidget *BareMetalRunConfiguration::createConfigurationWidget()
+{
+ return new BareMetalRunConfigurationWidget(this);
+}
+
+OutputFormatter *BareMetalRunConfiguration::createOutputFormatter() const
+{
+ return new QtSupport::QtOutputFormatter(target()->project());
+}
+
+QVariantMap BareMetalRunConfiguration::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->projectFilePath));
+ map.insert(QLatin1String(WorkingDirectoryKey), d->workingDirectory);
+ return map;
+}
+
+bool BareMetalRunConfiguration::fromMap(const QVariantMap &map)
+{
+ if (!RunConfiguration::fromMap(map))
+ return false;
+
+ d->arguments = map.value(QLatin1String(ArgumentsKey)).toString();
+ const QDir dir = QDir(target()->project()->projectDirectory());
+ d->projectFilePath
+ = QDir::cleanPath(dir.filePath(map.value(QLatin1String(ProFileKey)).toString()));
+ d->workingDirectory = map.value(QLatin1String(WorkingDirectoryKey)).toString();
+
+ setDefaultDisplayName(defaultDisplayName());
+
+ return true;
+}
+
+QString BareMetalRunConfiguration::defaultDisplayName()
+{
+ if (!d->projectFilePath.isEmpty())
+ //: %1 is the name of the project run via hardware debugger
+ return tr("%1 (via gdbserver/hardware debugger)").arg(QFileInfo(d->projectFilePath).completeBaseName());
+ //: Bare Metal run configuration default run name
+ return tr("Run on gdbserver/hardware debugger");
+}
+
+QString BareMetalRunConfiguration::localExecutableFilePath() const
+{
+ return target()->applicationTargets()
+ .targetForProject(Utils::FileName::fromString(d->projectFilePath)).toString();
+}
+
+QString BareMetalRunConfiguration::arguments() const
+{
+ return d->arguments;
+}
+
+void BareMetalRunConfiguration::setArguments(const QString &args)
+{
+ d->arguments = args;
+}
+
+QString BareMetalRunConfiguration::workingDirectory() const
+{
+ return d->workingDirectory;
+}
+
+void BareMetalRunConfiguration::setWorkingDirectory(const QString &wd)
+{
+ d->workingDirectory = wd;
+}
+
+QString BareMetalRunConfiguration::projectFilePath() const
+{
+ return d->projectFilePath;
+}
+
+void BareMetalRunConfiguration::setDisabledReason(const QString &reason) const
+{
+ d->disabledReason = reason;
+}
+
+void BareMetalRunConfiguration::handleBuildSystemDataUpdated()
+{
+ emit targetInformationChanged();
+ updateEnableState();
+}
+
+const char *BareMetalRunConfiguration::IdPrefix = "BareMetalRunConfiguration";
+
+} // namespace BareMetal
+
diff --git a/src/plugins/baremetal/baremetalrunconfiguration.h b/src/plugins/baremetal/baremetalrunconfiguration.h
new file mode 100644
index 0000000000..eca894257b
--- /dev/null
+++ b/src/plugins/baremetal/baremetalrunconfiguration.h
@@ -0,0 +1,94 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Tim Sander <tim@krieglstein.org>
+** 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 BAREMETALRUNCONFIGURATION_H
+#define BAREMETALRUNCONFIGURATION_H
+
+#include <projectexplorer/runconfiguration.h>
+
+namespace Utils { class PortList; }
+
+namespace BareMetal {
+class BareMetalRunConfigurationWidget;
+namespace Internal {
+class BareMetalRunConfigurationPrivate;
+class BareMetalRunConfigurationFactory;
+} // namespace Internal
+class BareMetalRunConfiguration : public ProjectExplorer::RunConfiguration
+{
+ Q_OBJECT
+ Q_DISABLE_COPY(BareMetalRunConfiguration)
+ friend class Internal::BareMetalRunConfigurationFactory;
+ friend class BareMetalRunConfigurationWidget;
+
+public:
+ explicit BareMetalRunConfiguration(ProjectExplorer::Target *parent, const Core::Id id,
+ const QString &projectFilePath);
+ ~BareMetalRunConfiguration();
+
+ bool isEnabled() const;
+ QString disabledReason() const;
+ QWidget *createConfigurationWidget();
+ Utils::OutputFormatter *createOutputFormatter() const;
+
+ QString localExecutableFilePath() const;
+ QString arguments() const;
+ void setArguments(const QString &args);
+ QString workingDirectory() const;
+ void setWorkingDirectory(const QString &wd);
+
+ QVariantMap toMap() const;
+
+ QString projectFilePath() const;
+
+ static const char *IdPrefix;
+signals:
+ void deploySpecsChanged();
+ void targetInformationChanged() const;
+
+protected:
+ BareMetalRunConfiguration(ProjectExplorer::Target *parent, BareMetalRunConfiguration *source);
+ bool fromMap(const QVariantMap &map);
+ QString defaultDisplayName();
+ void setDisabledReason(const QString &reason) const;
+
+protected slots:
+ void updateEnableState() { emit enabledChanged(); }
+
+private slots:
+ void handleBuildSystemDataUpdated();
+
+private:
+ void init();
+
+ Internal::BareMetalRunConfigurationPrivate * const d;
+};
+
+} // namespace BareMetal
+#endif // BAREMETALRUNCONFIGURATION_H
diff --git a/src/plugins/baremetal/baremetalrunconfigurationfactory.cpp b/src/plugins/baremetal/baremetalrunconfigurationfactory.cpp
new file mode 100644
index 0000000000..96700490d6
--- /dev/null
+++ b/src/plugins/baremetal/baremetalrunconfigurationfactory.cpp
@@ -0,0 +1,133 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Tim Sander <tim@krieglstein.org>
+** 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 "baremetalrunconfigurationfactory.h"
+#include "baremetalconstants.h"
+#include "baremetalrunconfiguration.h"
+
+#include <projectexplorer/buildtargetinfo.h>
+#include <projectexplorer/kitinformation.h>
+#include <projectexplorer/project.h>
+#include <projectexplorer/target.h>
+#include <utils/qtcassert.h>
+
+#include <QFileInfo>
+#include <QString>
+
+using namespace ProjectExplorer;
+
+namespace BareMetal {
+namespace Internal {
+
+static QString pathFromId(Core::Id id)
+{
+ QByteArray idStr = id.name();
+ if (!idStr.startsWith(BareMetalRunConfiguration::IdPrefix))
+ return QString();
+ return QString::fromUtf8(idStr.mid(strlen(BareMetalRunConfiguration::IdPrefix)));
+}
+
+BareMetalRunConfigurationFactory::BareMetalRunConfigurationFactory(QObject *parent) :
+ ProjectExplorer::IRunConfigurationFactory(parent)
+{
+ setObjectName(QLatin1String("BareMetalRunConfigurationFactory"));
+}
+
+BareMetalRunConfigurationFactory::~BareMetalRunConfigurationFactory()
+{
+}
+
+bool BareMetalRunConfigurationFactory::canCreate(Target *parent, const Core::Id id) const
+{
+ if (!canHandle(parent))
+ return false;
+ return !parent->applicationTargets().targetForProject(pathFromId(id)).isEmpty();
+}
+
+bool BareMetalRunConfigurationFactory::canRestore(Target *parent, const QVariantMap &map) const
+{
+ if (!canHandle(parent))
+ return false;
+ return idFromMap(map).name().startsWith(BareMetalRunConfiguration::IdPrefix);
+}
+
+bool BareMetalRunConfigurationFactory::canClone(Target *parent, RunConfiguration *source) const
+{
+ const BareMetalRunConfiguration * const bmrc
+ = qobject_cast<BareMetalRunConfiguration *>(source);
+ return bmrc && canCreate(parent, source->id());
+}
+
+QList<Core::Id> BareMetalRunConfigurationFactory::availableCreationIds(Target *parent) const
+{
+ QList<Core::Id> result;
+ if (!canHandle(parent))
+ return result;
+
+ const Core::Id base = Core::Id(BareMetalRunConfiguration::IdPrefix);
+ foreach (const BuildTargetInfo &bti, parent->applicationTargets().list)
+ result << base.withSuffix(bti.projectFilePath.toString());
+ return result;
+}
+
+QString BareMetalRunConfigurationFactory::displayNameForId(const Core::Id id) const
+{
+ return tr("%1 (on gdbserver/Hardware Debugger)")
+ .arg(QFileInfo(pathFromId(id)).completeBaseName());
+}
+
+RunConfiguration *BareMetalRunConfigurationFactory::doCreate(Target *parent, const Core::Id id)
+{
+ Q_UNUSED(id);
+ return new BareMetalRunConfiguration(parent, id, pathFromId(id));
+}
+
+RunConfiguration *BareMetalRunConfigurationFactory::doRestore(Target *parent, const QVariantMap &map)
+{
+ Q_UNUSED(map);
+ return doCreate(parent,Core::Id(BareMetalRunConfiguration::IdPrefix));
+}
+
+RunConfiguration *BareMetalRunConfigurationFactory::clone(Target *parent, RunConfiguration *source)
+{
+ QTC_ASSERT(canClone(parent, source), return 0);
+ BareMetalRunConfiguration *old = static_cast<BareMetalRunConfiguration*>(source);
+ return new BareMetalRunConfiguration(parent,old);
+}
+
+bool BareMetalRunConfigurationFactory::canHandle(const Target *target) const
+{
+ if (!target->project()->supportsKit(target->kit()))
+ return false;
+ const Core::Id deviceType = DeviceTypeKitInformation::deviceTypeId(target->kit());
+ return deviceType == BareMetal::Constants::BareMetalOsType;
+}
+
+} // namespace Internal
+} // namespace BareMetal
diff --git a/src/plugins/baremetal/baremetalrunconfigurationfactory.h b/src/plugins/baremetal/baremetalrunconfigurationfactory.h
new file mode 100644
index 0000000000..ce98c94e47
--- /dev/null
+++ b/src/plugins/baremetal/baremetalrunconfigurationfactory.h
@@ -0,0 +1,65 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Tim Sander <tim@krieglstein.org>
+** 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 BAREMETALRUNCONFIGURATIONFACTORY_H
+#define BAREMETALRUNCONFIGURATIONFACTORY_H
+
+#include <projectexplorer/runconfiguration.h>
+
+namespace BareMetal {
+namespace Internal {
+class BareMetalRunConfigurationFactory : public ProjectExplorer::IRunConfigurationFactory
+{
+ Q_OBJECT
+public:
+ explicit BareMetalRunConfigurationFactory(QObject *parent = 0);
+ ~BareMetalRunConfigurationFactory();
+
+ QString displayNameForId(const Core::Id id) const;
+ QList<Core::Id> availableCreationIds(ProjectExplorer::Target *parent) const;
+
+ bool canCreate(ProjectExplorer::Target *parent, const Core::Id id) const;
+
+ bool canRestore(ProjectExplorer::Target *parent, const QVariantMap &map) const;
+
+ bool canClone(ProjectExplorer::Target *parent, ProjectExplorer::RunConfiguration *source) const;
+ ProjectExplorer::RunConfiguration *clone(ProjectExplorer::Target *parent,
+ ProjectExplorer::RunConfiguration *source);
+private:
+ bool canHandle(const ProjectExplorer::Target *target) const;
+
+ ProjectExplorer::RunConfiguration *doCreate(ProjectExplorer::Target *parent, const Core::Id id);
+ ProjectExplorer::RunConfiguration *doRestore(ProjectExplorer::Target *parent,
+ const QVariantMap &map);
+};
+
+} // namespace Internal
+} // namespace RemoteLinux
+
+#endif // BAREMETALRUNCONFIGURATIONFACTORY_H
diff --git a/src/plugins/baremetal/baremetalrunconfigurationwidget.cpp b/src/plugins/baremetal/baremetalrunconfigurationwidget.cpp
new file mode 100644
index 0000000000..fac674faec
--- /dev/null
+++ b/src/plugins/baremetal/baremetalrunconfigurationwidget.cpp
@@ -0,0 +1,161 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Tim Sander <tim@krieglstein.org>
+** 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 "baremetalrunconfigurationwidget.h"
+#include "baremetalrunconfiguration.h"
+#include <utils/detailswidget.h>
+
+#include <QLineEdit>
+#include <QFormLayout>
+#include <QLabel>
+#include <QCoreApplication>
+#include <QDir>
+
+namespace BareMetal {
+namespace Internal {
+
+class BareMetalRunConfigurationWidgetPrivate
+{
+public:
+ BareMetalRunConfigurationWidgetPrivate(BareMetalRunConfiguration *runConfig)
+ : runConfiguration(runConfig)
+ { }
+
+ BareMetalRunConfiguration * const runConfiguration;
+ QWidget topWidget;
+ QLabel disabledIcon;
+ QLabel disabledReason;
+ QLineEdit argsLineEdit;
+ QLineEdit workingDirLineEdit;
+ QLabel localExecutableLabel;
+ QFormLayout genericWidgetsLayout;
+};
+
+} // namespace Internal
+
+using namespace Internal;
+
+BareMetalRunConfigurationWidget::BareMetalRunConfigurationWidget(BareMetalRunConfiguration *runConfiguration,
+ QWidget *parent)
+ : QWidget(parent),d(new BareMetalRunConfigurationWidgetPrivate(runConfiguration))
+{
+ QVBoxLayout *topLayout = new QVBoxLayout(this);
+ topLayout->setMargin(0);
+ addDisabledLabel(topLayout);
+ topLayout->addWidget(&d->topWidget);
+ QVBoxLayout *mainLayout = new QVBoxLayout(&d->topWidget);
+ mainLayout->setMargin(0);
+ addGenericWidgets(mainLayout);
+
+ connect(d->runConfiguration, SIGNAL(enabledChanged()),SLOT(runConfigurationEnabledChange()));
+ runConfigurationEnabledChange();
+}
+
+BareMetalRunConfigurationWidget::~BareMetalRunConfigurationWidget()
+{
+ delete d;
+}
+
+void BareMetalRunConfigurationWidget::addDisabledLabel(QVBoxLayout *topLayout)
+{
+ QHBoxLayout * const hl = new QHBoxLayout;
+ hl->addStretch();
+ d->disabledIcon.setPixmap(QPixmap(QLatin1String(":/projectexplorer/images/compile_warning.png")));
+ hl->addWidget(&d->disabledIcon);
+ d->disabledReason.setVisible(false);
+ hl->addWidget(&d->disabledReason);
+ hl->addStretch();
+ topLayout->addLayout(hl);
+}
+
+void BareMetalRunConfigurationWidget::addGenericWidgets(QVBoxLayout *mainLayout)
+{
+ Utils::DetailsWidget *detailsContainer = new Utils::DetailsWidget(this);
+ detailsContainer->setState(Utils::DetailsWidget::NoSummary);
+
+ QWidget *details = new QWidget(this);
+ details->setLayout(&d->genericWidgetsLayout);
+ detailsContainer->setWidget(details);
+
+ mainLayout->addWidget(detailsContainer);
+
+ d->genericWidgetsLayout.setFormAlignment(Qt::AlignLeft | Qt::AlignVCenter);
+
+ d->localExecutableLabel.setText(d->runConfiguration->localExecutableFilePath());
+ d->genericWidgetsLayout.addRow(tr("Executable:"),&d->localExecutableLabel);
+
+ //d->genericWidgetsLayout.addRow(tr("Debugger host:"),d->runConfiguration);
+ //d->genericWidgetsLayout.addRow(tr("Debugger port:"),d->runConfiguration);
+ d->argsLineEdit.setText(d->runConfiguration->arguments());
+ d->genericWidgetsLayout.addRow(tr("Arguments:"), &d->argsLineEdit);
+
+ d->workingDirLineEdit.setPlaceholderText(tr("<default>"));
+ d->workingDirLineEdit.setText(d->runConfiguration->workingDirectory());
+ d->genericWidgetsLayout.addRow(tr("Working directory:"), &d->workingDirLineEdit);
+ connect(&d->argsLineEdit, SIGNAL(textEdited(QString)), SLOT(argumentsEdited(QString)));
+ connect(d->runConfiguration, SIGNAL(targetInformationChanged()), this,
+ SLOT(updateTargetInformation()));
+ connect(&d->workingDirLineEdit, SIGNAL(textEdited(QString)),
+ SLOT(handleWorkingDirectoryChanged()));
+}
+
+void BareMetalRunConfigurationWidget::argumentsEdited(const QString &args)
+{
+ d->runConfiguration->setArguments(args);
+}
+
+void BareMetalRunConfigurationWidget::updateTargetInformation()
+{
+ setLabelText(d->localExecutableLabel,
+ QDir::toNativeSeparators(d->runConfiguration->localExecutableFilePath()),
+ tr("Unknown"));
+}
+
+void BareMetalRunConfigurationWidget::handleWorkingDirectoryChanged()
+{
+ d->runConfiguration->setWorkingDirectory(d->workingDirLineEdit.text().trimmed());
+}
+
+void BareMetalRunConfigurationWidget::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 BareMetalRunConfigurationWidget::runConfigurationEnabledChange()
+{
+ bool enabled = d->runConfiguration->isEnabled();
+ d->topWidget.setEnabled(enabled);
+ d->disabledIcon.setVisible(!enabled);
+ d->disabledReason.setVisible(!enabled);
+ d->disabledReason.setText(d->runConfiguration->disabledReason());
+}
+
+} // namespace BareMetal
diff --git a/src/plugins/baremetal/baremetalrunconfigurationwidget.h b/src/plugins/baremetal/baremetalrunconfigurationwidget.h
new file mode 100644
index 0000000000..9174b9cf95
--- /dev/null
+++ b/src/plugins/baremetal/baremetalrunconfigurationwidget.h
@@ -0,0 +1,71 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Tim Sander <tim@krieglstein.org>
+** 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 BAREMETALRUNCONFIGURATIONWIDGET_H
+#define BAREMETALRUNCONFIGURATIONWIDGET_H
+
+#include <QWidget>
+
+QT_BEGIN_NAMESPACE
+class QLabel;
+class QVBoxLayout;
+QT_END_NAMESPACE
+
+namespace BareMetal {
+class BareMetalRunConfiguration;
+
+namespace Internal {
+class BareMetalRunConfigurationWidgetPrivate;
+} // namespace Internal
+
+class BareMetalRunConfigurationWidget : public QWidget
+{
+ Q_OBJECT
+public:
+ explicit BareMetalRunConfigurationWidget(BareMetalRunConfiguration *runConfiguration,
+ QWidget *parent = 0);
+ ~BareMetalRunConfigurationWidget();
+ void addDisabledLabel(QVBoxLayout *topLayout);
+
+ Q_SLOT void runConfigurationEnabledChange();
+
+private slots:
+ void argumentsEdited(const QString &args);
+ void updateTargetInformation();
+ void handleWorkingDirectoryChanged();
+
+private:
+ void addGenericWidgets(QVBoxLayout *mainLayout);
+ void setLabelText(QLabel &label, const QString &regularText, const QString &errorText);
+
+ Internal::BareMetalRunConfigurationWidgetPrivate * const d;
+};
+
+} // namespace BareMetal
+#endif // BAREMETALRUNCONFIGURATIONWIDGET_H
diff --git a/src/plugins/baremetal/baremetalruncontrolfactory.cpp b/src/plugins/baremetal/baremetalruncontrolfactory.cpp
new file mode 100644
index 0000000000..3ba17b73bf
--- /dev/null
+++ b/src/plugins/baremetal/baremetalruncontrolfactory.cpp
@@ -0,0 +1,138 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Tim Sander <tim@krieglstein.org>
+** 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 "baremetalruncontrolfactory.h"
+#include "baremetalgdbcommandsdeploystep.h"
+#include "baremetalrunconfiguration.h"
+#include "baremetaldevice.h"
+
+#include <debugger/debuggerplugin.h>
+#include <debugger/debuggerrunner.h>
+#include <debugger/debuggerstartparameters.h>
+#include <debugger/debuggerkitinformation.h>
+#include <projectexplorer/buildsteplist.h>
+#include <projectexplorer/toolchain.h>
+#include <projectexplorer/project.h>
+#include <projectexplorer/buildconfiguration.h>
+#include <analyzerbase/analyzerstartparameters.h>
+#include <analyzerbase/analyzermanager.h>
+#include <analyzerbase/analyzerruncontrol.h>
+#include <projectexplorer/kitinformation.h>
+#include <projectexplorer/target.h>
+#include <utils/portlist.h>
+#include <utils/qtcassert.h>
+
+using namespace Analyzer;
+using namespace Debugger;
+using namespace ProjectExplorer;
+
+namespace BareMetal {
+namespace Internal {
+
+BareMetalRunControlFactory::BareMetalRunControlFactory(QObject *parent) :
+ ProjectExplorer::IRunControlFactory(parent)
+{
+}
+
+BareMetalRunControlFactory::~BareMetalRunControlFactory()
+{
+}
+
+bool BareMetalRunControlFactory::canRun(RunConfiguration *runConfiguration, RunMode mode) const
+{
+ if (mode != NormalRunMode && mode != DebugRunMode && mode != DebugRunModeWithBreakOnMain
+ && mode != QmlProfilerRunMode) {
+ return false;
+ }
+
+ const QByteArray idStr = runConfiguration->id().name();
+ return runConfiguration->isEnabled() && idStr.startsWith(BareMetalRunConfiguration::IdPrefix);
+}
+
+DebuggerStartParameters BareMetalRunControlFactory::startParameters(const BareMetalRunConfiguration *runConfig)
+{
+ DebuggerStartParameters params;
+ Target *target = runConfig->target();
+ Kit *k = target->kit();
+ const BareMetalDevice::ConstPtr device = qSharedPointerCast<const BareMetalDevice>(DeviceKitInformation::device(k));
+ QTC_ASSERT(device, return params);
+ params.sysRoot = SysRootKitInformation::sysRoot(k).toString();
+ params.debuggerCommand = DebuggerKitInformation::debuggerCommand(k).toString();
+ if (ToolChain *tc = ToolChainKitInformation::toolChain(k))
+ params.toolChainAbi = tc->targetAbi();
+ params.languages |= CppLanguage;
+ params.processArgs = runConfig->arguments();
+ params.startMode = AttachToRemoteServer;
+ params.executable = Utils::HostOsInfo::withExecutableSuffix(runConfig->localExecutableFilePath());
+ params.remoteSetupNeeded = false; //FIXME probably start debugserver with that, how?
+ params.displayName = runConfig->displayName();
+ if (const Project *project = target->project()) {
+ params.projectSourceDirectory = project->projectDirectory();
+ if (const BuildConfiguration *buildConfig = target->activeBuildConfiguration())
+ params.projectBuildDirectory = buildConfig->buildDirectory().toString();
+ params.projectSourceFiles = project->files(Project::ExcludeGeneratedFiles);
+ }
+ params.remoteChannel = device->sshParameters().host + QLatin1String(":") + QString::number(device->sshParameters().port);
+ params.remoteSetupNeeded = false; // qml stuff, not needed
+ params.commandsAfterConnect = device->getGdbInitCommands().toLatin1();
+ BuildConfiguration *bc = target->activeBuildConfiguration();
+ BuildStepList *bsl = bc->stepList(BareMetalGdbCommandsDeployStep::stepId());
+ if (bsl) {
+ foreach (BuildStep *bs,bsl->steps()) {
+ BareMetalGdbCommandsDeployStep *ds = qobject_cast<BareMetalGdbCommandsDeployStep *>(bs);
+ if (ds) {
+ if (!params.commandsAfterConnect.endsWith("\n"))
+ params.commandsAfterConnect.append("\n");
+ params.commandsAfterConnect.append(ds->gdbCommands().toLocal8Bit());
+ }
+ }
+ }
+ params.useContinueInsteadOfRun = true; //we can't execute as its always running
+ return params;
+}
+
+RunControl *BareMetalRunControlFactory::create(RunConfiguration *runConfiguration,
+ RunMode mode,
+ QString *errorMessage)
+{
+ QTC_ASSERT(canRun(runConfiguration, mode), return 0);
+
+ BareMetalRunConfiguration *rc = qobject_cast<BareMetalRunConfiguration *>(runConfiguration);
+ QTC_ASSERT(rc, return 0);
+ IDevice::ConstPtr dev = DeviceKitInformation::device(rc->target()->kit());
+ if (!dev) {
+ *errorMessage = tr("Cannot debug: Kit has no device.");
+ return 0;
+ }
+ DebuggerStartParameters sp = startParameters(rc);
+ return DebuggerPlugin::createDebugger(sp,runConfiguration,errorMessage);
+}
+
+} // namespace Internal
+} // namespace BareMetal
diff --git a/src/plugins/baremetal/baremetalruncontrolfactory.h b/src/plugins/baremetal/baremetalruncontrolfactory.h
new file mode 100644
index 0000000000..12fc316a00
--- /dev/null
+++ b/src/plugins/baremetal/baremetalruncontrolfactory.h
@@ -0,0 +1,55 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Tim Sander <tim@krieglstein.org>
+** 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 BAREMETALRUNCONTROLFACTORY_H
+#define BAREMETALRUNCONTROLFACTORY_H
+#include "baremetalrunconfiguration.h"
+#include <projectexplorer/runconfiguration.h>
+#include <debugger/debuggerstartparameters.h>
+
+namespace BareMetal {
+namespace Internal {
+
+class BareMetalRunControlFactory : public ProjectExplorer::IRunControlFactory
+{
+ Q_OBJECT
+public:
+ explicit BareMetalRunControlFactory(QObject *parent = 0);
+ ~BareMetalRunControlFactory();
+ Debugger::DebuggerStartParameters startParameters(const BareMetalRunConfiguration *runConfig);
+ bool canRun(ProjectExplorer::RunConfiguration *runConfiguration, ProjectExplorer::RunMode mode) const;
+ ProjectExplorer::RunControl *create(ProjectExplorer::RunConfiguration *runConfiguration,
+ ProjectExplorer::RunMode mode,
+ QString *errorMessage);
+};
+
+} // namespace Internal
+} // namespace BareMetal
+
+#endif // BAREMETALRUNCONTROLFACTORY_H
diff --git a/src/plugins/bazaar/Bazaar.pluginspec.in b/src/plugins/bazaar/Bazaar.pluginspec.in
index 28f7d0f059..cc6cc68b75 100644
--- a/src/plugins/bazaar/Bazaar.pluginspec.in
+++ b/src/plugins/bazaar/Bazaar.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"Bazaar\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"Bazaar\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Hugues Delorme</vendor>
<copyright>(C) 2013 Hugues Delorme</copyright>
<license>
diff --git a/src/plugins/bazaar/annotationhighlighter.cpp b/src/plugins/bazaar/annotationhighlighter.cpp
index 7fcbc2a124..0d8aaac4eb 100644
--- a/src/plugins/bazaar/annotationhighlighter.cpp
+++ b/src/plugins/bazaar/annotationhighlighter.cpp
@@ -33,9 +33,8 @@ using namespace Bazaar::Internal;
using namespace Bazaar;
BazaarAnnotationHighlighter::BazaarAnnotationHighlighter(const ChangeNumbers &changeNumbers,
- const QColor &bg,
QTextDocument *document)
- : VcsBase::BaseAnnotationHighlighter(changeNumbers, bg, document),
+ : VcsBase::BaseAnnotationHighlighter(changeNumbers, document),
m_changeset(QLatin1String(Constants::ANNOTATE_CHANGESET_ID))
{
}
diff --git a/src/plugins/bazaar/annotationhighlighter.h b/src/plugins/bazaar/annotationhighlighter.h
index ff39440286..5c55eff87b 100644
--- a/src/plugins/bazaar/annotationhighlighter.h
+++ b/src/plugins/bazaar/annotationhighlighter.h
@@ -38,7 +38,7 @@ namespace Internal {
class BazaarAnnotationHighlighter : public VcsBase::BaseAnnotationHighlighter
{
public:
- explicit BazaarAnnotationHighlighter(const ChangeNumbers &changeNumbers, const QColor &bg,
+ explicit BazaarAnnotationHighlighter(const ChangeNumbers &changeNumbers,
QTextDocument *document = 0);
private:
diff --git a/src/plugins/bazaar/bazaarclient.cpp b/src/plugins/bazaar/bazaarclient.cpp
index 18d5415f83..ceb56b5ca6 100644
--- a/src/plugins/bazaar/bazaarclient.cpp
+++ b/src/plugins/bazaar/bazaarclient.cpp
@@ -31,6 +31,7 @@
#include <vcsbase/vcsbaseplugin.h>
#include <vcsbase/vcsbaseeditorparameterwidget.h>
+#include <utils/synchronousprocess.h>
#include <QDir>
#include <QFileInfo>
@@ -40,6 +41,22 @@
namespace Bazaar {
namespace Internal {
+class BazaarDiffExitCodeInterpreter : public Utils::ExitCodeInterpreter
+{
+ Q_OBJECT
+public:
+ BazaarDiffExitCodeInterpreter(QObject *parent) : Utils::ExitCodeInterpreter(parent) {}
+ Utils::SynchronousProcessResponse::Result interpretExitCode(int code) const;
+
+};
+
+Utils::SynchronousProcessResponse::Result BazaarDiffExitCodeInterpreter::interpretExitCode(int code) const
+{
+ if (code < 0 || code > 2)
+ return Utils::SynchronousProcessResponse::FinishedError;
+ return Utils::SynchronousProcessResponse::Finished;
+}
+
BazaarClient::BazaarClient(BazaarSettings *settings) :
VcsBase::VcsBaseClient(settings)
{
@@ -142,6 +159,16 @@ QString BazaarClient::vcsCommandString(VcsCommand cmd) const
}
}
+Utils::ExitCodeInterpreter *BazaarClient::exitCodeInterpreter(VcsCommand cmd, QObject *parent) const
+{
+ switch (cmd) {
+ case DiffCommand:
+ return new BazaarDiffExitCodeInterpreter(parent);
+ default:
+ return 0;
+ }
+}
+
QStringList BazaarClient::revisionSpec(const QString &revision) const
{
QStringList args;
diff --git a/src/plugins/bazaar/bazaarclient.h b/src/plugins/bazaar/bazaarclient.h
index 0bc49c2306..d0b1f4a216 100644
--- a/src/plugins/bazaar/bazaarclient.h
+++ b/src/plugins/bazaar/bazaarclient.h
@@ -61,6 +61,7 @@ public:
protected:
Core::Id vcsEditorKind(VcsCommand cmd) const;
QString vcsCommandString(VcsCommand cmd) const;
+ Utils::ExitCodeInterpreter *exitCodeInterpreter(VcsCommand cmd, QObject *parent) const;
QStringList revisionSpec(const QString &revision) const;
VcsBase::VcsBaseEditorParameterWidget *createDiffEditor(const QString &workingDir,
const QStringList &files,
diff --git a/src/plugins/bazaar/bazaarcommitwidget.cpp b/src/plugins/bazaar/bazaarcommitwidget.cpp
index 34e075c3d4..3b25d4f08b 100644
--- a/src/plugins/bazaar/bazaarcommitwidget.cpp
+++ b/src/plugins/bazaar/bazaarcommitwidget.cpp
@@ -49,8 +49,7 @@ namespace Internal {
// Retrieve the comment char format from the text editor.
static QTextCharFormat commentFormat()
{
- const TextEditor::FontSettings settings = TextEditor::TextEditorSettings::instance()->fontSettings();
- return settings.toTextCharFormat(TextEditor::C_COMMENT);
+ return TextEditor::TextEditorSettings::fontSettings().toTextCharFormat(TextEditor::C_COMMENT);
}
// Highlighter for Bazaar submit messages. Make the first line bold, indicates
diff --git a/src/plugins/bazaar/bazaareditor.cpp b/src/plugins/bazaar/bazaareditor.cpp
index 917f819dd3..70acb54038 100644
--- a/src/plugins/bazaar/bazaareditor.cpp
+++ b/src/plugins/bazaar/bazaareditor.cpp
@@ -35,7 +35,6 @@
#include <QRegExp>
#include <QString>
#include <QTextCursor>
-#include <QDebug>
#define BZR_CHANGE_PATTERN "[0-9]+"
@@ -107,8 +106,7 @@ QString BazaarEditor::changeUnderCursor(const QTextCursor &cursorIn) const
return QString();
}
-VcsBase::BaseAnnotationHighlighter *BazaarEditor::createAnnotationHighlighter(const QSet<QString> &changes,
- const QColor &bg) const
+VcsBase::BaseAnnotationHighlighter *BazaarEditor::createAnnotationHighlighter(const QSet<QString> &changes) const
{
- return new BazaarAnnotationHighlighter(changes, bg);
+ return new BazaarAnnotationHighlighter(changes);
}
diff --git a/src/plugins/bazaar/bazaareditor.h b/src/plugins/bazaar/bazaareditor.h
index 50dca61e04..5cff890d69 100644
--- a/src/plugins/bazaar/bazaareditor.h
+++ b/src/plugins/bazaar/bazaareditor.h
@@ -46,7 +46,7 @@ public:
private:
QSet<QString> annotationChanges() const;
QString changeUnderCursor(const QTextCursor &cursor) const;
- VcsBase::BaseAnnotationHighlighter *createAnnotationHighlighter(const QSet<QString> &changes, const QColor &bg) const;
+ VcsBase::BaseAnnotationHighlighter *createAnnotationHighlighter(const QSet<QString> &changes) const;
mutable QRegExp m_changesetId;
mutable QRegExp m_exactChangesetId;
diff --git a/src/plugins/bazaar/bazaarplugin.cpp b/src/plugins/bazaar/bazaarplugin.cpp
index 3614e74529..6253dad0b4 100644
--- a/src/plugins/bazaar/bazaarplugin.cpp
+++ b/src/plugins/bazaar/bazaarplugin.cpp
@@ -536,7 +536,7 @@ void BazaarPlugin::showCommitWidget(const QList<VcsBase::VcsBaseClient::StatusIt
// Keep the file alive, else it removes self and forgets its name
saver.setAutoRemove(false);
if (!saver.finalize()) {
- VcsBase::VcsBaseOutputWindow::instance()->append(saver.errorString());
+ VcsBase::VcsBaseOutputWindow::instance()->appendError(saver.errorString());
return;
}
@@ -561,7 +561,7 @@ void BazaarPlugin::showCommitWidget(const QList<VcsBase::VcsBaseClient::StatusIt
const QString msg = tr("Commit changes for \"%1\".").
arg(QDir::toNativeSeparators(m_submitRepository));
- commitEditor->setDisplayName(msg);
+ commitEditor->document()->setDisplayName(msg);
const BranchInfo branch = m_client->synchronousBranchQuery(m_submitRepository);
commitEditor->setFields(m_submitRepository, branch,
@@ -637,7 +637,7 @@ void BazaarPlugin::commitFromEditor()
{
// Close the submit editor
m_submitActionTriggered = true;
- Core::ICore::editorManager()->closeEditor();
+ Core::EditorManager::closeEditor();
}
bool BazaarPlugin::submitEditorAboutToClose()
@@ -690,7 +690,7 @@ bool BazaarPlugin::submitEditorAboutToClose()
// Whether local commit or not
if (commitWidget->isLocalOptionEnabled())
extraOptions += QLatin1String("--local");
- m_client->commit(m_submitRepository, files, editorDocument->fileName(), extraOptions);
+ m_client->commit(m_submitRepository, files, editorDocument->filePath(), extraOptions);
}
return true;
}
diff --git a/src/plugins/bazaar/clonewizard.cpp b/src/plugins/bazaar/clonewizard.cpp
index 6809cfb84a..8b4ec5309c 100644
--- a/src/plugins/bazaar/clonewizard.cpp
+++ b/src/plugins/bazaar/clonewizard.cpp
@@ -35,7 +35,7 @@
#include "bazaarsettings.h"
#include <coreplugin/iversioncontrol.h>
-#include <vcsbase/checkoutjobs.h>
+#include <vcsbase/command.h>
#include <vcsbase/vcsbaseconstants.h>
#include <vcsbase/vcsconfigurationpage.h>
@@ -43,26 +43,13 @@
using namespace Bazaar::Internal;
-CloneWizard::CloneWizard(QObject *parent)
- : VcsBase::BaseCheckoutWizard(parent),
- m_icon(QIcon(QLatin1String(":/bazaar/images/bazaar.png")))
+CloneWizard::CloneWizard()
{
setId(QLatin1String(VcsBase::Constants::VCS_ID_BAZAAR));
-}
-
-QIcon CloneWizard::icon() const
-{
- return m_icon;
-}
-
-QString CloneWizard::description() const
-{
- return tr("Clones a Bazaar branch and tries to load the contained project.");
-}
-
-QString CloneWizard::displayName() const
-{
- return tr("Bazaar Clone (Or Branch)");
+ setCustomLabels(tr("Cloning"), tr("Cloning started..."));
+ setIcon(QIcon(QLatin1String(":/bazaar/images/bazaar.png")));
+ setDescription(tr("Clones a Bazaar branch and tries to load the contained project."));
+ setDisplayName(tr("Bazaar Clone (Or Branch)"));
}
QList<QWizardPage *> CloneWizard::createParameterPages(const QString &path)
@@ -77,13 +64,13 @@ QList<QWizardPage *> CloneWizard::createParameterPages(const QString &path)
return wizardPageList;
}
-QSharedPointer<VcsBase::AbstractCheckoutJob> CloneWizard::createJob(const QList<QWizardPage *> &parameterPages,
- QString *checkoutPath)
+VcsBase::Command *CloneWizard::createCommand(const QList<QWizardPage *> &parameterPages,
+ QString *checkoutPath)
{
const CloneWizardPage *page = qobject_cast<const CloneWizardPage *>(parameterPages.front());
if (!page)
- return QSharedPointer<VcsBase::AbstractCheckoutJob>();
+ return 0;
const BazaarSettings &settings = BazaarPlugin::instance()->settings();
*checkoutPath = page->path() + QLatin1Char('/') + page->directory();
@@ -111,7 +98,8 @@ QSharedPointer<VcsBase::AbstractCheckoutJob> CloneWizard::createJob(const QList<
args << client->vcsCommandString(BazaarClient::CloneCommand)
<< extraOptions << page->repository() << page->directory();
- VcsBase::ProcessCheckoutJob *job = new VcsBase::ProcessCheckoutJob;
- job->addStep(settings.binaryPath(), args, page->path());
- return QSharedPointer<VcsBase::AbstractCheckoutJob>(job);
+ VcsBase::Command *command = new VcsBase::Command(settings.binaryPath(), page->path(),
+ client->processEnvironment());
+ command->addJob(args, -1);
+ return command;
}
diff --git a/src/plugins/bazaar/clonewizard.h b/src/plugins/bazaar/clonewizard.h
index 06d5f9c1ac..fcc0cc81cf 100644
--- a/src/plugins/bazaar/clonewizard.h
+++ b/src/plugins/bazaar/clonewizard.h
@@ -42,19 +42,12 @@ class CloneWizard : public VcsBase::BaseCheckoutWizard
Q_OBJECT
public:
- CloneWizard(QObject *parent = 0);
-
- QIcon icon() const;
- QString description() const;
- QString displayName() const;
-
-protected:
- QList<QWizardPage *> createParameterPages(const QString &path);
- QSharedPointer<VcsBase::AbstractCheckoutJob> createJob(const QList<QWizardPage *> &parameterPages,
- QString *checkoutPath);
+ CloneWizard();
private:
- const QIcon m_icon;
+ QList<QWizardPage *> createParameterPages(const QString &path);
+ VcsBase::Command *createCommand(const QList<QWizardPage *> &parameterPages,
+ QString *checkoutPath);
};
} // namespace Internal
diff --git a/src/plugins/bazaar/commiteditor.cpp b/src/plugins/bazaar/commiteditor.cpp
index b41a04012f..ea7fef2372 100644
--- a/src/plugins/bazaar/commiteditor.cpp
+++ b/src/plugins/bazaar/commiteditor.cpp
@@ -30,6 +30,7 @@
#include "branchinfo.h"
#include "bazaarcommitwidget.h"
+#include <coreplugin/idocument.h>
#include <vcsbase/submitfilemodel.h>
#include <QDebug>
@@ -40,7 +41,7 @@ CommitEditor::CommitEditor(const VcsBase::VcsBaseSubmitEditorParameters *paramet
: VcsBase::VcsBaseSubmitEditor(parameters, new BazaarCommitWidget(parent)),
m_fileModel(0)
{
- setDisplayName(tr("Commit Editor"));
+ document()->setDisplayName(tr("Commit Editor"));
}
BazaarCommitWidget *CommitEditor::commitWidget()
diff --git a/src/plugins/bineditor/BinEditor.pluginspec.in b/src/plugins/bineditor/BinEditor.pluginspec.in
index 7af26deb24..c32482e342 100644
--- a/src/plugins/bineditor/BinEditor.pluginspec.in
+++ b/src/plugins/bineditor/BinEditor.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"BinEditor\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"BinEditor\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/bineditor/bineditor.cpp b/src/plugins/bineditor/bineditor.cpp
index 25b12f0cc6..2c0d7c0a36 100644
--- a/src/plugins/bineditor/bineditor.cpp
+++ b/src/plugins/bineditor/bineditor.cpp
@@ -109,9 +109,9 @@ BinEditorWidget::BinEditorWidget(QWidget *parent)
setFrameStyle(QFrame::Plain);
// Font settings
- TextEditor::TextEditorSettings *settings = TextEditor::TextEditorSettings::instance();
- setFontSettings(settings->fontSettings());
- connect(settings, SIGNAL(fontSettingsChanged(TextEditor::FontSettings)),
+ setFontSettings(TextEditor::TextEditorSettings::fontSettings());
+ connect(TextEditor::TextEditorSettings::instance(),
+ SIGNAL(fontSettingsChanged(TextEditor::FontSettings)),
this, SLOT(setFontSettings(TextEditor::FontSettings)));
}
@@ -582,6 +582,8 @@ int BinEditorWidget::dataLastIndexOf(const QByteArray &pattern, int from, bool c
buffer.resize(m_blockSize + trailing);
char *b = buffer.data();
+ if (from == -1)
+ from = m_size;
int block = from / m_blockSize;
const int lowerBound = qMax(0, from - SearchStride);
while (from > lowerBound) {
@@ -842,7 +844,7 @@ void BinEditorWidget::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));
@@ -1088,17 +1090,17 @@ QString BinEditorWidget::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 + 1;
- if (byteCount <= 1) {
+ int byteCount = selEnd - selStart;
+ if (byteCount < 1) {
selStart = posAt(helpEvent->pos());
- selEnd = selStart;
+ selEnd = selStart + 1;
byteCount = 1;
}
if (m_hexCursor == 0 || byteCount > 8)
return QString();
const QPoint &startPoint = offsetToPos(selStart);
- const QPoint &endPoint = offsetToPos(selEnd + 1);
+ const QPoint &endPoint = offsetToPos(selEnd);
QRect selRect(startPoint, endPoint);
selRect.setHeight(m_lineHeight);
if (!selRect.contains(helpEvent->pos()))
@@ -1383,10 +1385,10 @@ void BinEditorWidget::copy(bool raw)
{
int selStart = selectionStart();
int selEnd = selectionEnd();
- if (selStart >= selEnd)
+ if (selStart > selEnd)
qSwap(selStart, selEnd);
- const int selectionLength = selEnd - selStart + 1;
+ const int selectionLength = selEnd - selStart;
if (selectionLength >> 22) {
QMessageBox::warning(this, tr("Copying Failed"),
tr("You cannot copy more than 4 MB of binary data."));
@@ -1494,7 +1496,7 @@ void BinEditorWidget::redo()
void BinEditorWidget::contextMenuEvent(QContextMenuEvent *event)
{
const int selStart = selectionStart();
- const int byteCount = selectionEnd() - selStart + 1;
+ const int byteCount = selectionEnd() - selStart;
QPointer<QMenu> contextMenu(new QMenu(this));
@@ -1623,11 +1625,6 @@ void BinEditorWidget::asIntegers(int offset, int count, quint64 &bigEndianValue,
}
}
-bool BinEditorWidget::isMemoryView() const
-{
- return editor()->property("MemoryView").toBool();
-}
-
void BinEditorWidget::setMarkup(const QList<Markup> &markup)
{
m_markup = markup;
diff --git a/src/plugins/bineditor/bineditor.h b/src/plugins/bineditor/bineditor.h
index 81b4b33045..d02402da61 100644
--- a/src/plugins/bineditor/bineditor.h
+++ b/src/plugins/bineditor/bineditor.h
@@ -119,8 +119,6 @@ public:
QString addressString(quint64 address);
- bool isMemoryView() const; // Is a debugger memory view without file?
-
static const int SearchStride = 1024 * 1024;
QList<Markup> markup() const { return m_markup; }
diff --git a/src/plugins/bineditor/bineditorplugin.cpp b/src/plugins/bineditor/bineditorplugin.cpp
index 3998c3d2e3..b9f9c87a64 100644
--- a/src/plugins/bineditor/bineditorplugin.cpp
+++ b/src/plugins/bineditor/bineditorplugin.cpp
@@ -37,7 +37,6 @@
#include <QDir>
#include <QFile>
#include <QFileInfo>
-#include <QDebug>
#include <QRegExp>
#include <QVariant>
@@ -74,6 +73,7 @@ public:
{
m_widget = widget;
m_incrementalStartPos = m_contPos = -1;
+ m_incrementalWrappedState = false;
}
bool supportsReplace() const { return false; }
@@ -88,6 +88,7 @@ public:
void resetIncrementalSearch()
{
m_incrementalStartPos = m_contPos = -1;
+ m_incrementalWrappedState = false;
}
virtual void highlightAll(const QString &txt, Find::FindFlags findFlags)
@@ -100,14 +101,25 @@ public:
m_widget->highlightSearchResults(QByteArray());
}
- int find(const QByteArray &pattern, int pos, Find::FindFlags findFlags)
+ int find(const QByteArray &pattern, int pos, Find::FindFlags findFlags, bool *wrapped)
{
+ if (wrapped)
+ *wrapped = false;
if (pattern.isEmpty()) {
m_widget->setCursorPosition(pos);
return pos;
}
- return m_widget->find(pattern, pos, Find::textDocumentFlagsForFindFlags(findFlags));
+ int res = m_widget->find(pattern, pos, Find::textDocumentFlagsForFindFlags(findFlags));
+ if (res < 0) {
+ pos = (findFlags & Find::FindBackward) ? -1 : 0;
+ res = m_widget->find(pattern, pos, Find::textDocumentFlagsForFindFlags(findFlags));
+ if (res < 0)
+ return res;
+ if (wrapped)
+ *wrapped = true;
+ }
+ return res;
}
Result findIncremental(const QString &txt, Find::FindFlags findFlags) {
@@ -119,7 +131,12 @@ public:
m_incrementalStartPos = m_widget->selectionStart();
if (m_contPos == -1)
m_contPos = m_incrementalStartPos;
- int found = find(pattern, m_contPos, findFlags);
+ bool wrapped;
+ int found = find(pattern, m_contPos, findFlags, &wrapped);
+ if (wrapped != m_incrementalWrappedState && (found >= 0)) {
+ m_incrementalWrappedState = wrapped;
+ showWrapIndicator(m_widget);
+ }
Result result;
if (found >= 0) {
result = Found;
@@ -148,7 +165,10 @@ public:
if (findFlags & Find::FindBackward)
m_contPos = m_widget->selectionStart()-1;
}
- int found = find(pattern, m_contPos, findFlags);
+ bool wrapped;
+ int found = find(pattern, m_contPos, findFlags, &wrapped);
+ if (wrapped)
+ showWrapIndicator(m_widget);
Result result;
if (found >= 0) {
result = Found;
@@ -172,6 +192,7 @@ private:
BinEditorWidget *m_widget;
int m_incrementalStartPos;
int m_contPos; // Only valid if last result was NotYetFound.
+ bool m_incrementalWrappedState;
QByteArray m_lastPattern;
};
@@ -195,27 +216,27 @@ public:
return QLatin1String(Constants::C_BINEDITOR_MIMETYPE);
}
- bool save(QString *errorString, const QString &fileName, bool autoSave)
+ bool setContents(const QByteArray &contents)
+ {
+ if (!contents.isEmpty())
+ return false;
+ m_widget->clear();
+ return true;
+ }
+
+ bool save(QString *errorString, const QString &fn, bool autoSave)
{
QTC_ASSERT(!autoSave, return true); // bineditor does not support autosave - it would be a bit expensive
const QString fileNameToUse
- = fileName.isEmpty() ? m_fileName : fileName;
- if (m_widget->save(errorString, m_fileName, fileNameToUse)) {
- m_fileName = fileNameToUse;
- m_widget->editor()->setDisplayName(QFileInfo(fileNameToUse).fileName());
- emit changed();
+ = fn.isEmpty() ? filePath() : fn;
+ if (m_widget->save(errorString, filePath(), fileNameToUse)) {
+ setFilePath(fileNameToUse);
return true;
} else {
return false;
}
}
- void rename(const QString &newName) {
- m_fileName = newName;
- m_widget->editor()->setDisplayName(QFileInfo(fileName()).fileName());
- emit changed();
- }
-
bool open(QString *errorString, const QString &fileName, quint64 offset = 0) {
QFile file(fileName);
quint64 size = static_cast<quint64>(file.size());
@@ -231,9 +252,8 @@ public:
return false;
if (file.open(QIODevice::ReadOnly)) {
file.close();
- m_fileName = fileName;
+ setFilePath(fileName);
m_widget->setSizes(offset, file.size());
- m_widget->editor()->setDisplayName(QFileInfo(fileName).fileName());
return true;
}
QString errStr = tr("Cannot open %1: %2").arg(
@@ -248,9 +268,10 @@ public:
private slots:
void provideData(quint64 block)
{
- if (m_fileName.isEmpty())
+ const QString fn = filePath();
+ if (fn.isEmpty())
return;
- QFile file(m_fileName);
+ QFile file(fn);
if (file.open(QIODevice::ReadOnly)) {
int blockSize = m_widget->dataBlockSize();
file.seek(block * blockSize);
@@ -263,33 +284,29 @@ private slots:
} else {
QMessageBox::critical(Core::ICore::mainWindow(), tr("File Error"),
tr("Cannot open %1: %2").arg(
- QDir::toNativeSeparators(m_fileName), file.errorString()));
+ QDir::toNativeSeparators(fn), file.errorString()));
}
}
void provideNewRange(quint64 offset)
{
- open(0, m_fileName, offset);
+ open(0, filePath(), offset);
}
public:
- void setFilename(const QString &filename) {
- m_fileName = filename;
- }
-
- QString fileName() const { return m_fileName; }
-
QString defaultPath() const { return QString(); }
QString suggestedFileName() const { return QString(); }
- bool isModified() const { return m_widget->isMemoryView() ? false : m_widget->isModified(); }
+ bool isModified() const { return isTemporary()/*e.g. memory view*/ ? false
+ : m_widget->isModified(); }
bool isFileReadOnly() const {
- if (m_widget->isMemoryView() || m_fileName.isEmpty())
+ const QString fn = filePath();
+ if (fn.isEmpty())
return false;
- const QFileInfo fi(m_fileName);
+ const QFileInfo fi(fn);
return !fi.isWritable();
}
@@ -302,7 +319,7 @@ public:
emit changed();
} else {
emit aboutToReload();
- const bool success = open(errorString, m_fileName);
+ const bool success = open(errorString, filePath());
emit reloadFinished(success);
return success;
}
@@ -311,7 +328,6 @@ public:
private:
BinEditorWidget *m_widget;
- QString m_fileName;
};
class BinEditor : public Core::IEditor
@@ -346,9 +362,8 @@ public:
widget->setEditor(this);
connect(m_widget, SIGNAL(cursorPositionChanged(int)), SLOT(updateCursorPosition(int)));
- connect(m_file, SIGNAL(changed()), SIGNAL(changed()));
connect(m_addressEdit, SIGNAL(editingFinished()), SLOT(jumpToAddress()));
- connect(m_widget, SIGNAL(modificationChanged(bool)), SIGNAL(changed()));
+ connect(m_widget, SIGNAL(modificationChanged(bool)), m_file, SIGNAL(changed()));
updateCursorPosition(m_widget->cursorPosition());
}
@@ -356,24 +371,15 @@ public:
delete m_widget;
}
- bool createNew(const QString & /* contents */ = QString()) {
- m_widget->clear();
- m_file->setFilename(QString());
- return true;
- }
bool open(QString *errorString, const QString &fileName, const QString &realFileName) {
QTC_ASSERT(fileName == realFileName, return false); // The bineditor can do no autosaving
return m_file->open(errorString, fileName);
}
Core::IDocument *document() { return m_file; }
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(); }
QWidget *toolBar() { return m_toolBar; }
- bool isTemporary() const { return m_widget->isMemoryView(); }
-
private slots:
void updateCursorPosition(int position) {
m_addressEdit->setText(QString::number(m_widget->baseAddress() + position, 16));
@@ -386,7 +392,6 @@ private slots:
private:
BinEditorWidget *m_widget;
- QString m_displayName;
BinEditorDocument *m_file;
QToolBar *m_toolBar;
QLineEdit *m_addressEdit;
@@ -397,19 +402,11 @@ private:
///////////////////////////////// BinEditorFactory //////////////////////////////////
BinEditorFactory::BinEditorFactory(BinEditorPlugin *owner) :
- m_mimeTypes(QLatin1String(Constants::C_BINEDITOR_MIMETYPE)),
m_owner(owner)
{
-}
-
-Core::Id BinEditorFactory::id() const
-{
- return Core::Id(Core::Constants::K_DEFAULT_BINARY_EDITOR_ID);
-}
-
-QString BinEditorFactory::displayName() const
-{
- return qApp->translate("OpenWith::Editors", Constants::C_BINEDITOR_DISPLAY_NAME);
+ setId(Core::Constants::K_DEFAULT_BINARY_EDITOR_ID);
+ setDisplayName(qApp->translate("OpenWith::Editors", Constants::C_BINEDITOR_DISPLAY_NAME));
+ addMimeType(Constants::C_BINEDITOR_MIMETYPE);
}
Core::IEditor *BinEditorFactory::createEditor(QWidget *parent)
@@ -421,10 +418,6 @@ Core::IEditor *BinEditorFactory::createEditor(QWidget *parent)
return editor;
}
-QStringList BinEditorFactory::mimeTypes() const
-{
- return m_mimeTypes;
-}
/*!
\class BINEditor::BinEditorWidgetFactory
diff --git a/src/plugins/bineditor/bineditorplugin.h b/src/plugins/bineditor/bineditorplugin.h
index 0adf0f62b4..46864d6bb0 100644
--- a/src/plugins/bineditor/bineditorplugin.h
+++ b/src/plugins/bineditor/bineditorplugin.h
@@ -102,13 +102,9 @@ class BinEditorFactory : public Core::IEditorFactory
public:
explicit BinEditorFactory(BinEditorPlugin *owner);
- QStringList mimeTypes() const;
Core::IEditor *createEditor(QWidget *parent);
- Core::Id id() const;
- QString displayName() const;
private:
- const QStringList m_mimeTypes;
BinEditorPlugin *m_owner;
};
diff --git a/src/plugins/bookmarks/Bookmarks.pluginspec.in b/src/plugins/bookmarks/Bookmarks.pluginspec.in
index 6c659ed184..8221ed55e3 100644
--- a/src/plugins/bookmarks/Bookmarks.pluginspec.in
+++ b/src/plugins/bookmarks/Bookmarks.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"Bookmarks\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"Bookmarks\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/bookmarks/bookmarkmanager.cpp b/src/plugins/bookmarks/bookmarkmanager.cpp
index 79ba85d943..4c09532671 100644
--- a/src/plugins/bookmarks/bookmarkmanager.cpp
+++ b/src/plugins/bookmarks/bookmarkmanager.cpp
@@ -61,6 +61,7 @@ using namespace Bookmarks;
using namespace Bookmarks::Internal;
using namespace ProjectExplorer;
using namespace Core;
+using namespace Utils;
BookmarkDelegate::BookmarkDelegate(QObject *parent)
: QStyledItemDelegate(parent), m_normalPixmap(0), m_selectedPixmap(0)
@@ -219,6 +220,8 @@ BookmarkView::BookmarkView(QWidget *parent) :
connect(this, SIGNAL(clicked(QModelIndex)),
this, SLOT(gotoBookmark(QModelIndex)));
+ connect(this, SIGNAL(activated(QModelIndex)),
+ this, SLOT(gotoBookmark(QModelIndex)));
ICore::addContextObject(m_bookmarkContext);
@@ -280,6 +283,16 @@ void BookmarkView::removeBookmark(const QModelIndex& index)
m_manager->removeBookmark(bm);
}
+void BookmarkView::keyPressEvent(QKeyEvent *event)
+{
+ if (event->key() == Qt::Key_Delete) {
+ removeBookmark(currentIndex());
+ event->accept();
+ return;
+ }
+ QListView::keyPressEvent(event);
+}
+
void BookmarkView::removeAll()
{
const QString key = QLatin1String("Bookmarks.DontAskAgain");
@@ -343,7 +356,7 @@ BookmarkManager::BookmarkManager() :
connect(Core::ICore::instance(), SIGNAL(contextChanged(QList<Core::IContext*>,Core::Context)),
this, SLOT(updateActionStatus()));
- connect(ProjectExplorerPlugin::instance()->session(), SIGNAL(sessionLoaded(QString)),
+ connect(SessionManager::instance(), SIGNAL(sessionLoaded(QString)),
this, SLOT(loadBookmarks()));
updateActionStatus();
@@ -426,7 +439,7 @@ void BookmarkManager::toggleBookmark()
if (!editor)
return;
- toggleBookmark(editor->document()->fileName(), editor->currentLine());
+ toggleBookmark(editor->document()->filePath(), editor->currentLine());
}
void BookmarkManager::toggleBookmark(const QString &fileName, int lineNumber)
@@ -545,7 +558,7 @@ void BookmarkManager::documentPrevNext(bool next)
{
TextEditor::ITextEditor *editor = currentTextEditor();
int editorLine = editor->currentLine();
- QFileInfo fi(editor->document()->fileName());
+ QFileInfo fi(editor->document()->filePath());
if (!m_bookmarksMap.contains(fi.path()))
return;
@@ -567,8 +580,7 @@ void BookmarkManager::documentPrevNext(bool next)
nextLine = markLine;
}
- Core::EditorManager *em = Core::EditorManager::instance();
- em->addCurrentPositionToNavigationHistory();
+ EditorManager::addCurrentPositionToNavigationHistory();
if (next) {
if (nextLine == -1)
editor->gotoLine(firstLine);
@@ -634,12 +646,6 @@ TextEditor::ITextEditor *BookmarkManager::currentTextEditor() const
return qobject_cast<TextEditor::ITextEditor *>(currEditor);
}
-/* Returns the current session. */
-SessionManager *BookmarkManager::sessionManager() const
-{
- return ProjectExplorerPlugin::instance()->session();
-}
-
BookmarkManager::State BookmarkManager::state() const
{
if (m_bookmarksMap.empty())
@@ -649,7 +655,7 @@ BookmarkManager::State BookmarkManager::state() const
if (!editor)
return HasBookMarks;
- const QFileInfo fi(editor->document()->fileName());
+ const QFileInfo fi(editor->document()->filePath());
const DirectoryFileBookmarksMap::const_iterator dit = m_bookmarksMap.constFind(fi.path());
if (dit == m_bookmarksMap.constEnd())
@@ -815,7 +821,7 @@ void BookmarkManager::saveBookmarks()
foreach (const Bookmark *bookmark, m_bookmarksList)
list << bookmarkToString(bookmark);
- sessionManager()->setValue(QLatin1String("Bookmarks"), list);
+ SessionManager::setValue(QLatin1String("Bookmarks"), list);
}
void BookmarkManager::operateTooltip(TextEditor::ITextEditor *textEditor, const QPoint &pos, Bookmark *mark)
@@ -824,16 +830,16 @@ void BookmarkManager::operateTooltip(TextEditor::ITextEditor *textEditor, const
return;
if (mark->note().isEmpty())
- Utils::ToolTip::instance()->hide();
+ ToolTip::hide();
else
- Utils::ToolTip::instance()->show(pos, Utils::TextContent(mark->note()), textEditor->widget());
+ ToolTip::show(pos, TextContent(mark->note()), textEditor->widget());
}
/* Loads the bookmarks from the session settings. */
void BookmarkManager::loadBookmarks()
{
removeAllBookmarks();
- const QStringList &list = sessionManager()->value(QLatin1String("Bookmarks")).toStringList();
+ const QStringList &list = SessionManager::value(QLatin1String("Bookmarks")).toStringList();
foreach (const QString &bookmarkString, list)
addBookmark(bookmarkString);
@@ -845,14 +851,14 @@ void BookmarkManager::handleBookmarkRequest(TextEditor::ITextEditor *textEditor,
TextEditor::ITextEditor::MarkRequestKind kind)
{
if (kind == TextEditor::ITextEditor::BookmarkRequest && textEditor->document())
- toggleBookmark(textEditor->document()->fileName(), line);
+ toggleBookmark(textEditor->document()->filePath(), line);
}
void BookmarkManager::handleBookmarkTooltipRequest(TextEditor::ITextEditor *textEditor, const QPoint &pos,
int line)
{
if (textEditor->document()) {
- const QFileInfo fi(textEditor->document()->fileName());
+ const QFileInfo fi(textEditor->document()->filePath());
Bookmark *mark = findBookmark(fi.path(), fi.fileName(), line);
operateTooltip(textEditor, pos, mark);
}
@@ -877,7 +883,7 @@ int BookmarkViewFactory::priority() const
Id BookmarkViewFactory::id() const
{
- return Id("Bookmarks");
+ return "Bookmarks";
}
QKeySequence BookmarkViewFactory::activationSequence() const
diff --git a/src/plugins/bookmarks/bookmarkmanager.h b/src/plugins/bookmarks/bookmarkmanager.h
index 6bf8d6d7c1..65ac7f2191 100644
--- a/src/plugins/bookmarks/bookmarkmanager.h
+++ b/src/plugins/bookmarks/bookmarkmanager.h
@@ -42,14 +42,6 @@
#include <QPixmap>
#include <QStyledItemDelegate>
-namespace ProjectExplorer {
-class SessionManager;
-}
-
-namespace Core {
-class IEditor;
-}
-
namespace Bookmarks {
namespace Internal {
@@ -124,7 +116,6 @@ private slots:
private:
TextEditor::ITextEditor *currentTextEditor() const;
- ProjectExplorer::SessionManager* sessionManager() const;
void documentPrevNext(bool next);
@@ -161,6 +152,7 @@ protected slots:
protected:
void contextMenuEvent(QContextMenuEvent *event);
void removeBookmark(const QModelIndex &index);
+ void keyPressEvent(QKeyEvent *event);
private:
BookmarkContext *m_bookmarkContext;
QModelIndex m_contextMenuIndex;
diff --git a/src/plugins/bookmarks/bookmarksplugin.cpp b/src/plugins/bookmarks/bookmarksplugin.cpp
index a98656981e..256121c92d 100644
--- a/src/plugins/bookmarks/bookmarksplugin.cpp
+++ b/src/plugins/bookmarks/bookmarksplugin.cpp
@@ -128,10 +128,9 @@ bool BookmarksPlugin::initialize(const QStringList & /*arguments*/, QString *)
this, SLOT(bookmarkMarginActionTriggered()));
// EditorManager
- QObject *editorManager = Core::ICore::editorManager();
- connect(editorManager, SIGNAL(editorAboutToClose(Core::IEditor*)),
+ connect(Core::EditorManager::instance(), SIGNAL(editorAboutToClose(Core::IEditor*)),
this, SLOT(editorAboutToClose(Core::IEditor*)));
- connect(editorManager, SIGNAL(editorOpened(Core::IEditor*)),
+ connect(Core::EditorManager::instance(), SIGNAL(editorOpened(Core::IEditor*)),
this, SLOT(editorOpened(Core::IEditor*)));
return true;
@@ -185,7 +184,7 @@ void BookmarksPlugin::requestContextMenu(TextEditor::ITextEditor *editor,
int lineNumber, QMenu *menu)
{
m_bookmarkMarginActionLineNumber = lineNumber;
- m_bookmarkMarginActionFileName = editor->document()->fileName();
+ m_bookmarkMarginActionFileName = editor->document()->filePath();
menu->addAction(m_bookmarkMarginAction);
if (m_bookmarkManager->hasBookmarkInPosition(m_bookmarkMarginActionFileName, m_bookmarkMarginActionLineNumber))
diff --git a/src/plugins/classview/ClassView.pluginspec.in b/src/plugins/classview/ClassView.pluginspec.in
index 3adf67fcae..82266c27c2 100644
--- a/src/plugins/classview/ClassView.pluginspec.in
+++ b/src/plugins/classview/ClassView.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"ClassView\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"ClassView\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Denis Mingulov</copyright>
<license>
diff --git a/src/plugins/classview/classviewmanager.cpp b/src/plugins/classview/classviewmanager.cpp
index 73ea0ff6db..5a87ff70db 100644
--- a/src/plugins/classview/classviewmanager.cpp
+++ b/src/plugins/classview/classviewmanager.cpp
@@ -38,7 +38,6 @@
#include <projectexplorer/session.h>
#include <cpptools/cppmodelmanagerinterface.h>
#include <cpptools/cpptoolsconstants.h>
-#include <coreplugin/icore.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/editormanager/ieditor.h>
@@ -48,6 +47,8 @@
#include <QMutex>
#include <QMutexLocker>
+using namespace Core;
+
namespace ClassView {
namespace Internal {
@@ -57,11 +58,89 @@ namespace Internal {
static Manager *managerInstance = 0;
/*!
- \struct ManagerPrivate
+ \class ClassView::Internal::Manager
+
+ \brief The Manager class implements a class view manager that interacts with
+ other \QC plugins and acts as a proxy between them and the parser.
+
+ The parser is moved to a separate thread and is connected to the manager by
+ using signals and slots. Manager's signals starting with 'request' are for
+ the parser.
+*/
+
+/*!
+ \fn explicit ClassView::Internal::Manager(QObject *parent = 0)
+
+ Creates a shared instance of a \a parent object.
+*/
+
+/*!
+ \fn void ClassView::Internal::Manager::stateChanged(bool state)
+
+ Changes the internal manager state. \a state returns true if manager is
+ enabled, otherwise false.
+
+ \sa setState, state
+*/
+
+/*!
+ \fn void ClassView::Internal::Manager::treeDataUpdate(QSharedPointer<QStandardItem> result)
+
+ Emits a signal about a tree data update (to tree view). \a result holds the
+ item with the current tree.
+*/
+
+/*!
+ \fn void ClassView::Internal::Manager::requestTreeDataUpdate()
+
+ Emits a signal that a request for sending the tree view has to be handled by
+ listeners (the parser).
+
+ \sa onRequestTreeDataUpdate
+*/
+
+/*!
+ \fn void ClassView::Internal::Manager::requestDocumentUpdated(CPlusPlus::Document::Ptr doc)
+
+ Emits a signal that \a doc was updated and has to be reparsed.
+
+ \sa onDocumentUpdated
+*/
+
+/*!
+ \fn void ClassView::Internal::Manager::requestResetCurrentState()
+
+ Emits a signal that the parser has to reset its internal state to the
+ current state from the code manager.
+*/
+
+/*!
+ \fn void ClassView::Internal::Manager::requestClearCache()
+
+ Requests the parser to clear a cache.
+*/
+
+/*!
+ \fn void ClassView::Internal::Manager::requestClearCacheAll()
+
+ Requests the parser to clear a full cache.
+*/
+
+/*!
+ \fn void ClassView::Internal::Manager::requestSetFlatMode(bool flat)
+
+ Requests the manager to set the flat mode without subprojects. Set \a flat
+ to \c true to enable flat mode and to false to disable it.
+*/
+
+/*!
+ \class ManagerPrivate
\internal
- \brief Private class data for \a Manager
+ \brief The ManagerPrivate class contains private class data for the Manager
+ class.
\sa Manager
- */
+*/
+
class ManagerPrivate
{
public:
@@ -117,11 +196,20 @@ Manager *Manager::instance()
return managerInstance;
}
+/*!
+ Checks \a item for lazy data population of a QStandardItemModel.
+*/
+
bool Manager::canFetchMore(QStandardItem *item) const
{
return d->parser.canFetchMore(item);
}
+/*!
+ Checks \a item for lazy data population of a QStandardItemModel.
+ \a skipRoot item is needed for the manual update, call not from model.
+*/
+
void Manager::fetchMore(QStandardItem *item, bool skipRoot)
{
d->parser.fetchMore(item, skipRoot);
@@ -139,18 +227,17 @@ void Manager::initialize()
connect(this, SIGNAL(stateChanged(bool)), SLOT(onStateChanged(bool)), Qt::QueuedConnection);
// connections to enable/disable navi widget factory
- ProjectExplorer::SessionManager *sessionManager =
- ProjectExplorer::ProjectExplorerPlugin::instance()->session();
+ QObject *sessionManager = ProjectExplorer::SessionManager::instance();
connect(sessionManager, SIGNAL(projectAdded(ProjectExplorer::Project*)),
SLOT(onProjectListChanged()), Qt::QueuedConnection);
connect(sessionManager, SIGNAL(projectRemoved(ProjectExplorer::Project*)),
SLOT(onProjectListChanged()), Qt::QueuedConnection);
// connect to the progress manager for signals about Parsing tasks
- connect(Core::ICore::progressManager(), SIGNAL(taskStarted(QString)),
- SLOT(onTaskStarted(QString)), Qt::QueuedConnection);
- connect(Core::ICore::progressManager(), SIGNAL(allTasksFinished(QString)),
- SLOT(onAllTasksFinished(QString)), Qt::QueuedConnection);
+ connect(ProgressManager::instance(), SIGNAL(taskStarted(Core::Id)),
+ SLOT(onTaskStarted(Core::Id)), Qt::QueuedConnection);
+ connect(ProgressManager::instance(), SIGNAL(allTasksFinished(Core::Id)),
+ SLOT(onAllTasksFinished(Core::Id)), Qt::QueuedConnection);
// when we signals that really document is updated - sent it to the parser
connect(this, SIGNAL(requestDocumentUpdated(CPlusPlus::Document::Ptr)),
@@ -192,11 +279,27 @@ void Manager::initialize()
&d->parser, SLOT(removeFiles(QStringList)), Qt::QueuedConnection);
}
+/*!
+ Gets the internal manager state. If it is disabled, does not emit signals
+ about parsing requests. If enabled, does parsing in the background even if
+ the navigation pane is not visible. Returns true if the manager is enabled,
+ false otherwise.
+
+ \sa setState, stateChanged
+*/
+
bool Manager::state() const
{
return d->state;
}
+/*!
+ Sets the internal manager \a state to \c true if the manager has to be
+ enabled, otherwise sets it to \c false.
+
+ \sa state, stateChanged
+*/
+
void Manager::setState(bool state)
{
QMutexLocker locker(&d->mutexState);
@@ -210,11 +313,24 @@ void Manager::setState(bool state)
emit stateChanged(d->state);
}
+/*!
+ Reacts to the widget factory creating a widget.
+
+ \sa setState, state
+*/
+
void Manager::onWidgetIsCreated()
{
// do nothing - continue to sleep
}
+/*!
+ Reacts to the \a visibility of one navigation pane widget being changed
+ (there might be a lot of them).
+
+ \sa setState, state
+*/
+
void Manager::onWidgetVisibilityIsChanged(bool visibility)
{
// activate data handling - when 1st time 'Class View' will be open
@@ -222,6 +338,13 @@ void Manager::onWidgetVisibilityIsChanged(bool visibility)
setState(true);
}
+/*!
+ Reacts to the state changed signal for the current manager \a state.
+ For example, requests the currect code snapshot if needed.
+
+ \sa setState, state, stateChanged
+*/
+
void Manager::onStateChanged(bool state)
{
if (state) {
@@ -233,6 +356,11 @@ void Manager::onStateChanged(bool state)
}
}
+/*!
+ Reacts to the project list being changed by updating the navigation pane
+ visibility if necessary.
+*/
+
void Manager::onProjectListChanged()
{
// do nothing if Manager is disabled
@@ -243,18 +371,32 @@ void Manager::onProjectListChanged()
requestTreeDataUpdate();
}
-void Manager::onTaskStarted(const QString &type)
+/*!
+ Handles parse tasks started by the progress manager. \a type holds the
+ task index, which should be \c CppTools::Constants::TASK_INDEX.
+
+ \sa CppTools::Constants::TASK_INDEX
+*/
+
+void Manager::onTaskStarted(Core::Id type)
{
- if (type != QLatin1String(CppTools::Constants::TASK_INDEX))
+ if (type != CppTools::Constants::TASK_INDEX)
return;
// disable tree updates to speed up
d->disableCodeParser = true;
}
-void Manager::onAllTasksFinished(const QString &type)
+/*!
+ Handles parse tasks finished by the progress manager.\a type holds the
+ task index, which should be \c CppTools::Constants::TASK_INDEX.
+
+ \sa CppTools::Constants::TASK_INDEX
+*/
+
+void Manager::onAllTasksFinished(Core::Id type)
{
- if (type != QLatin1String(CppTools::Constants::TASK_INDEX))
+ if (type != CppTools::Constants::TASK_INDEX)
return;
// parsing is finished, enable tree updates
@@ -271,6 +413,13 @@ void Manager::onAllTasksFinished(const QString &type)
emit requestResetCurrentState();
}
+/*!
+ Emits the signal \c documentUpdated when the code model manager state is
+ changed for \a doc.
+
+ \sa documentUpdated
+*/
+
void Manager::onDocumentUpdated(CPlusPlus::Document::Ptr doc)
{
// do nothing if Manager is disabled
@@ -284,11 +433,22 @@ void Manager::onDocumentUpdated(CPlusPlus::Document::Ptr doc)
emit requestDocumentUpdated(doc);
}
+/*!
+ Opens the text editor for the file \a fileName on \a line (1-based) and
+ \a column (1-based).
+*/
+
void Manager::gotoLocation(const QString &fileName, int line, int column)
{
- Core::EditorManager::openEditorAt(fileName, line, column);
+ EditorManager::openEditorAt(fileName, line, column);
}
+/*!
+ Opens the text editor for any of the symbol locations in the \a list.
+
+ \sa Manager::gotoLocations
+*/
+
void Manager::gotoLocations(const QList<QVariant> &list)
{
QSet<SymbolLocation> locations = Utils::roleToLocations(list);
@@ -302,10 +462,10 @@ void Manager::gotoLocations(const QList<QVariant> &list)
bool currentPositionAvailable = false;
// what is open now?
- if (Core::IEditor *editor = Core::EditorManager::currentEditor()) {
+ if (IEditor *editor = EditorManager::currentEditor()) {
// get current file name
- if (Core::IDocument *document = editor->document())
- fileName = document->fileName();
+ if (IDocument *document = editor->document())
+ fileName = document->filePath();
// if text file - what is current position?
TextEditor::ITextEditor *textEditor = qobject_cast<TextEditor::ITextEditor *>(editor);
@@ -340,6 +500,13 @@ void Manager::gotoLocations(const QList<QVariant> &list)
gotoLocation(loc.fileName(), loc.line(), loc.column());
}
+/*!
+ Emits the signal \c requestTreeDataUpdate if the latest tree info is
+ requested and if parsing is enabled.
+
+ \sa requestTreeDataUpdate, NavigationWidget::requestDataUpdate
+*/
+
void Manager::onRequestTreeDataUpdate()
{
// do nothing if Manager is disabled
@@ -349,11 +516,20 @@ void Manager::onRequestTreeDataUpdate()
emit requestTreeDataUpdate();
}
+/*!
+ Switches to flat mode (without subprojects) if \a flat is set to \c true.
+*/
+
void Manager::setFlatMode(bool flat)
{
emit requestSetFlatMode(flat);
}
+/*!
+ Sends a new tree data update to a tree view. \a result holds the item with
+ the current tree.
+*/
+
void Manager::onTreeDataUpdate(QSharedPointer<QStandardItem> result)
{
// do nothing if Manager is disabled
diff --git a/src/plugins/classview/classviewmanager.h b/src/plugins/classview/classviewmanager.h
index 51a922d0a3..b91dd80313 100644
--- a/src/plugins/classview/classviewmanager.h
+++ b/src/plugins/classview/classviewmanager.h
@@ -34,6 +34,7 @@
#include <QSharedPointer>
#include <QStandardItem>
+#include <coreplugin/id.h>
#include <cplusplus/CppDocument.h>
namespace ClassView {
@@ -41,25 +42,11 @@ namespace Internal {
class ManagerPrivate;
-/*!
- \class Manager
- \brief Class View manager
-
- Class View Manager. Interacts with other Qt Creator plugins - this is a proxy between them and
- parser.
- \a Parser is moved to a separate thread and is connected to \a Manager by signal/slots.
- Manager's signals starting with 'request' are for Parser.
- */
-
class Manager : public QObject
{
Q_OBJECT
public:
- /*!
- \brief Creates shared instance
- \param parent Parent object
- */
explicit Manager(QObject *parent = 0);
virtual ~Manager();
@@ -67,169 +54,52 @@ public:
//! Get an instance of Manager
static Manager *instance();
- /*!
- \brief Lazy data population for a \a QStandardItemModel
- \param item Item with has to be checked
- */
bool canFetchMore(QStandardItem *item) const;
- /*!
- \brief Lazy data population for a \a QStandardItemModel
- \param item Item with has to be checked
- \param skipRoot Skip root item (is needed for the manual update, call not from model)
- */
void fetchMore(QStandardItem *item, bool skipRoot = false);
signals:
- /*!
- \brief Internal Manager state is changed.
- \param state true if Manager is enabled, false otherwise
- \sa setState, state
- */
void stateChanged(bool state);
- /*!
- \brief Signal about a tree data update (to tree view).
- \param result Item with the current tree
- */
void treeDataUpdate(QSharedPointer<QStandardItem> result);
- /*!
- \brief Signal that a request for sending tree view has to be handled by listeners (parser).
- \sa onRequestTreeDataUpdate
- */
void requestTreeDataUpdate();
- /*!
- \brief Signal that document is updated (and has to be reparsed)
- \param doc Updated document
- \sa onDocumentUpdated
- */
void requestDocumentUpdated(CPlusPlus::Document::Ptr doc);
- /*!
- \brief Signal that parser has to reset its internal state to the current (from code manager).
- */
void requestResetCurrentState();
- /*!
- \brief Request to clear a cache by parser.
- */
void requestClearCache();
- /*!
- \brief Request to clear a full cache by parser.
- */
void requestClearCacheAll();
- /*!
- \brief Request to set the flat mode (without subprojects)
- \param flat True to enable flat mode, false to disable
- */
void requestSetFlatMode(bool flat);
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 line Line number, 1-based
- \param column Column, 1-based
- */
void gotoLocation(const QString &fileName, int line = 0, int column = 0);
- /*!
- \brief Open text editor for any of location in the list (correctly)
- \param locations Symbol locations
- \sa Manager::gotoLocations
- */
void gotoLocations(const QList<QVariant> &locations);
- /*!
- \brief If somebody wants to receive the latest tree info, if a parsing is enabled then
- a signal \a requestTreeDataUpdate will be emitted.
- \sa requestTreeDataUpdate, NavigationWidget::requestDataUpdate
- */
void onRequestTreeDataUpdate();
- /*!
- \brief Switch to flat mode (without subprojects)
- \param flat True to enable flat mode, false to disable
- */
void setFlatMode(bool flat);
protected slots:
- /*!
- \brief Widget factory creates a widget, handle this situation.
- \sa setState, state
- */
void onWidgetIsCreated();
-
- /*!
- \brief Widget visibility is changed
- \param visibility Visibility (for just 1 navi pane widget, there might be a lot of them)
- \sa setState, state
- */
void onWidgetVisibilityIsChanged(bool visibility);
-
- /*!
- \brief Reacts to the state changed signal, e.g. request currect code snapshot if needed etc.
- \param state Current Manager state
- \sa setState, state, stateChanged
- */
void onStateChanged(bool state);
-
- /*!
- \brief Project list is changed (navigation pane visibility might be needed to update).
- */
void onProjectListChanged();
-
- /*!
- \brief This slot should called when the code model manager state is changed for \a doc.
- It will emit a signal \a documentUpdated if
- \param doc Updated document.
- \sa documentUpdated
- */
void onDocumentUpdated(CPlusPlus::Document::Ptr doc);
-
- /*!
- \brief Progress manager started a task. Do what is needed if it is a parse task.
- \param type Task index, should be CppTools::Constants::TASK_INDEX for us
- \sa CppTools::Constants::TASK_INDEX
- */
- void onTaskStarted(const QString &type);
-
- /*!
- \brief Progress manager finished all task with specified type.
- Do what is needed if it is a parse task.
- \param type Task index, should be CppTools::Constants::TASK_INDEX for us
- \sa CppTools::Constants::TASK_INDEX
- */
- void onAllTasksFinished(const QString &type);
-
- /*!
- \brief New tree data update (has to be sent to a tree view).
- \param result Item with the current tree
- */
+ void onTaskStarted(Core::Id type);
+ void onAllTasksFinished(Core::Id type);
void onTreeDataUpdate(QSharedPointer<QStandardItem> result);
protected:
//! Perform an initialization
void initialize();
- /*!
- \brief Get internal Manager state. If it is disabled, signals about parsing request has not
- to be emitted at all, if enabled - do parsing in the background even if navi pane
- is not visible.
- \return true if Manager is enabled, false otherwise
- \sa setState, stateChanged
- */
inline bool state() const;
- /*!
- \brief Set internal Manager state.
- \param state true if Manager has to be enabled, false otherwise
- \sa state, stateChanged
- */
void setState(bool state);
private:
diff --git a/src/plugins/classview/classviewnavigationwidget.cpp b/src/plugins/classview/classviewnavigationwidget.cpp
index 9dbedd3934..846a210281 100644
--- a/src/plugins/classview/classviewnavigationwidget.cpp
+++ b/src/plugins/classview/classviewnavigationwidget.cpp
@@ -49,8 +49,10 @@ namespace Internal {
///////////////////////////////// NavigationWidgetPrivate //////////////////////////////////
/*!
- \struct NavigationWidgetPrivate
- \brief Internal data structures / methods for NavigationWidget
+ \class NavigationWidgetPrivate
+
+ The NavigationWidgetPrivate class provides internal data structures and
+ methods for NavigationWidget.
*/
class NavigationWidgetPrivate
@@ -70,6 +72,47 @@ public:
///////////////////////////////// NavigationWidget //////////////////////////////////
+/*!
+ \class NavigationWidget
+
+ The NavigationWidget class is a widget for the class view tree.
+*/
+
+
+/*!
+ \fn void NavigationWidget::visibilityChanged(bool visibility)
+
+ Emits a signal when the widget visibility is changed. \a visibility returns
+ true if plugin becames visible, otherwise it returns false.
+*/
+
+/*!
+ \fn void NavigationWidget::requestGotoLocation(const QString &name,
+ int line,
+ int column)
+
+ Emits a signal that requests to open the file with \a name at \a line
+ and \a column.
+
+ \sa Manager::gotoLocation
+*/
+
+/*!
+ \fn void NavigationWidget::requestGotoLocations(const QList<QVariant> &locations)
+
+ Emits a signal to request to go to any of the Symbol \a locations in the
+ list.
+
+ \sa Manager::gotoLocations
+*/
+
+/*!
+ \fn void NavigationWidget::requestTreeDataUpdate()
+
+ Emits a signal that the widget wants to receive the latest tree info.
+
+ \sa Manager::onRequestTreeDataUpdate
+*/
NavigationWidget::NavigationWidget(QWidget *parent) :
QWidget(parent),
@@ -128,6 +171,14 @@ void NavigationWidget::showEvent(QShowEvent *event)
QWidget::showEvent(event);
}
+/*!
+ Creates QToolbuttons for the Navigation Pane widget.
+
+ Returns the list of created QToolButtons.
+
+ \sa NavigationWidgetFactory::createWidget
+*/
+
QList<QToolButton *> NavigationWidget::createToolButtons()
{
QList<QToolButton *> list;
@@ -154,6 +205,10 @@ QList<QToolButton *> NavigationWidget::createToolButtons()
return list;
}
+/*!
+ Returns flat mode state.
+*/
+
bool NavigationWidget::flatMode() const
{
QTC_ASSERT(d->fullProjectsModeButton, return false);
@@ -162,6 +217,10 @@ bool NavigationWidget::flatMode() const
return !d->fullProjectsModeButton->isChecked();
}
+/*!
+ Sets the flat mode state to \a flatMode.
+*/
+
void NavigationWidget::setFlatMode(bool flatMode)
{
QTC_ASSERT(d->fullProjectsModeButton, return);
@@ -170,12 +229,21 @@ void NavigationWidget::setFlatMode(bool flatMode)
d->fullProjectsModeButton->setChecked(!flatMode);
}
+/*!
+ Full projects mode button has been toggled. \a state holds the full
+ projects mode.
+*/
+
void NavigationWidget::onFullProjectsModeToggled(bool state)
{
// button is 'full projects mode' - so it has to be inverted
Manager::instance()->setFlatMode(!state);
}
+/*!
+ Activates the item with the \a index in the tree view.
+*/
+
void NavigationWidget::onItemActivated(const QModelIndex &index)
{
if (!index.isValid())
@@ -186,6 +254,11 @@ void NavigationWidget::onItemActivated(const QModelIndex &index)
emit requestGotoLocations(list);
}
+/*!
+ Receives new data for the tree. \a result is a pointer to the Class View
+ model root item. The method does nothing if null is passed.
+*/
+
void NavigationWidget::onDataUpdate(QSharedPointer<QStandardItem> result)
{
if (result.isNull())
@@ -213,6 +286,11 @@ void NavigationWidget::onDataUpdate(QSharedPointer<QStandardItem> result)
<< "TreeView is updated in" << timer.elapsed() << "msecs";
}
+/*!
+ Fetches data for expanded items to make sure that the content will exist.
+ \a item and \a target do nothing if null is passed.
+*/
+
void NavigationWidget::fetchExpandedItems(QStandardItem *item, const QStandardItem *target) const
{
if (!item || !target)
diff --git a/src/plugins/classview/classviewnavigationwidget.h b/src/plugins/classview/classviewnavigationwidget.h
index 9b64aec103..98cc9ce649 100644
--- a/src/plugins/classview/classviewnavigationwidget.h
+++ b/src/plugins/classview/classviewnavigationwidget.h
@@ -42,11 +42,6 @@ namespace Internal {
class NavigationWidgetPrivate;
-/*!
- \class NavigationWidget
- \brief A widget for the class view tree
- */
-
class NavigationWidget : public QWidget
{
Q_OBJECT
@@ -55,79 +50,29 @@ public:
explicit NavigationWidget(QWidget *parent = 0);
~NavigationWidget();
- /*!
- \brief Create QToolbuttons for Navigation Pane Widget
- \return List with created QToolButtons
- \sa NavigationWidgetFactory::createWidget
- */
QList<QToolButton *> createToolButtons();
- /*!
- \brief Get flat mode state
- \return Flat mode state
- */
bool flatMode() const;
- /*!
- \brief Set flat mode state
- \param flatMode Flat mode state
- */
void setFlatMode(bool flatMode);
signals:
- /*!
- \brief Widget visibility is changed
- \param visibility true is plugin becames visible, false otherwise
- */
void visibilityChanged(bool visibility);
- /*!
- \brief Signal to request to go to location
- \param name File which has to be open
- \param line Line
- \param column Column
- \sa Manager::gotoLocation
- */
void requestGotoLocation(const QString &name, int line, int column);
- /*!
- \brief Signal to request to go to any of location in the list
- \param locations Symbol locations
- \sa Manager::gotoLocations
- */
void requestGotoLocations(const QList<QVariant> &locations);
- /*!
- \brief Signal that the widget wants to receive the latest tree info
- \sa Manager::onRequestTreeDataUpdate
- */
void requestTreeDataUpdate();
public slots:
- /*!
- \brief Item is activated in the tree view
- \param index Item index
- */
void onItemActivated(const QModelIndex &index);
- /*!
- \brief Receive a new data for the tree
- \param result Pointer to the Class View model root item, method does nothing if null passed
- */
void onDataUpdate(QSharedPointer<QStandardItem> result);
- /*!
- \brief Full projects' mode button has been toggled
- \param state Full projects' mode
- */
void onFullProjectsModeToggled(bool state);
protected:
- /*!
- \brief Fetch data for expanded items - to be sure that content will exist
- \param item - does nothing if null
- \param target - does nothing if null
- */
void fetchExpandedItems(QStandardItem *item, const QStandardItem *target) const;
//! implements QWidget::hideEvent
diff --git a/src/plugins/classview/classviewnavigationwidgetfactory.cpp b/src/plugins/classview/classviewnavigationwidgetfactory.cpp
index b3a4fb7e63..39f8b15afb 100644
--- a/src/plugins/classview/classviewnavigationwidgetfactory.cpp
+++ b/src/plugins/classview/classviewnavigationwidgetfactory.cpp
@@ -45,6 +45,23 @@ static NavigationWidgetFactory *factoryInstance;
///////////////////////////////// NavigationWidgetFactory //////////////////////////////////
+/*!
+ \class NavigationWidgetFactory
+ \brief The NavigationWidgetFactory class implements a singleton instance of
+ the INavigationWidgetFactory for the Class View.
+
+ Supports the \c setState public slot for adding the widget factory to or
+ removing it from \c ExtensionSystem::PluginManager.
+
+ Also supports the \c widgetIsCreated and \c stateChanged signals.
+*/
+
+/*!
+ \fn void NavigationWidgetFactory::widgetIsCreated()
+
+ Informs that the widget factory created a widget.
+*/
+
NavigationWidgetFactory::NavigationWidgetFactory()
{
factoryInstance = this;
@@ -72,7 +89,7 @@ int NavigationWidgetFactory::priority() const
Core::Id NavigationWidgetFactory::id() const
{
- return Core::Id("Class View");
+ return "Class View";
}
QKeySequence NavigationWidgetFactory::activationSequence() const
@@ -92,10 +109,8 @@ Core::NavigationView NavigationWidgetFactory::createWidget()
/*!
- \brief Get a settings prefix for the specified position
- \param position Position
- \return Settings prefix
- */
+ Returns a settings prefix for \a position.
+*/
static QString settingsPrefix(int position)
{
return QString::fromLatin1("ClassView/Treewidget.%1/FlatMode").arg(position);
diff --git a/src/plugins/classview/classviewnavigationwidgetfactory.h b/src/plugins/classview/classviewnavigationwidgetfactory.h
index 5d623e8f3b..5ee1314fba 100644
--- a/src/plugins/classview/classviewnavigationwidgetfactory.h
+++ b/src/plugins/classview/classviewnavigationwidgetfactory.h
@@ -35,15 +35,6 @@
namespace ClassView {
namespace Internal {
-/*!
- \class NavigationWidgetFactory
- \brief INavigationWidgetFactory implementation for Class View
-
- INavigationWidgetFactory implementation for Class View. Singleton instance.
- Supports \a setState publc slot to add/remove factory to \a ExtensionSystem::PluginManager.
- Also supports some additional signals, \a widgetIsCreated and \a stateChanged.
- */
-
class NavigationWidgetFactory : public Core::INavigationWidgetFactory
{
Q_OBJECT
@@ -81,9 +72,6 @@ public:
void restoreSettings(int position, QWidget *widget);
signals:
- /*!
- \brief Signal which informs that the widget factory creates a widget.
- */
void widgetIsCreated();
};
diff --git a/src/plugins/classview/classviewparser.cpp b/src/plugins/classview/classviewparser.cpp
index e312696faa..a7dea53b66 100644
--- a/src/plugins/classview/classviewparser.cpp
+++ b/src/plugins/classview/classviewparser.cpp
@@ -45,7 +45,6 @@
#include <projectexplorer/session.h>
#include <projectexplorer/project.h>
#include <projectexplorer/projectnodes.h>
-#include <coreplugin/idocument.h>
#include <utils/qtcassert.h>
#include <QStandardItem>
@@ -59,16 +58,39 @@
enum { debug = false };
+using namespace ProjectExplorer;
+
namespace ClassView {
namespace Internal {
// ----------------------------- ParserPrivate ---------------------------------
/*!
- \struct ParserPrivate
- \brief Private class data for \a Parser
+ \class ParserPrivate
+ \brief The ParserPrivate class defines private class data for the Parser
+ class.
\sa Parser
*/
+
+/*!
+ \class Parser
+ \brief The Parser class parses C++ information. Multithreading is supported.
+*/
+
+/*!
+ \fn void Parser::treeDataUpdate(QSharedPointer<QStandardItem> result)
+
+ Emits a signal about a tree data update.
+*/
+
+/*!
+ \fn void Parser::resetDataDone()
+
+ Emits a signal that internal data is reset.
+
+ \sa resetData, resetDataToCurrentState
+*/
+
class ParserPrivate
{
public:
@@ -132,6 +154,10 @@ CPlusPlus::Document::Ptr ParserPrivate::document(const QString &fileName) const
// ----------------------------- Parser ---------------------------------
+/*!
+ Constructs the parser object.
+*/
+
Parser::Parser(QObject *parent)
: QObject(parent),
d(new ParserPrivate())
@@ -147,11 +173,19 @@ Parser::Parser(QObject *parent)
connect(d->timer, SIGNAL(timeout()), SLOT(requestCurrentState()), Qt::QueuedConnection);
}
+/*!
+ Destructs the parser object.
+*/
+
Parser::~Parser()
{
delete d;
}
+/*!
+ Checks \a item for lazy data population of a QStandardItemModel.
+*/
+
bool Parser::canFetchMore(QStandardItem *item) const
{
ParserTreeItem::ConstPtr ptr = findItemByRoot(item);
@@ -160,6 +194,11 @@ bool Parser::canFetchMore(QStandardItem *item) const
return ptr->canFetchMore(item);
}
+/*!
+ Checks \a item for lazy data population of a QStandardItemModel.
+ \a skipRoot skips the root item.
+*/
+
void Parser::fetchMore(QStandardItem *item, bool skipRoot) const
{
ParserTreeItem::ConstPtr ptr = findItemByRoot(item, skipRoot);
@@ -168,6 +207,10 @@ void Parser::fetchMore(QStandardItem *item, bool skipRoot) const
ptr->fetchMore(item);
}
+/*!
+ Switches to flat mode (without subprojects) if \a flat returns \c true.
+*/
+
void Parser::setFlatMode(bool flatMode)
{
if (flatMode == d->flatMode)
@@ -180,6 +223,11 @@ void Parser::setFlatMode(bool flatMode)
emitCurrentTree();
}
+/*!
+ Returns the internal tree item for \a item. \a skipRoot skips the root
+ item.
+*/
+
ParserTreeItem::ConstPtr Parser::findItemByRoot(const QStandardItem *item, bool skipRoot) const
{
if (!item)
@@ -213,6 +261,12 @@ ParserTreeItem::ConstPtr Parser::findItemByRoot(const QStandardItem *item, bool
return internal;
}
+/*!
+ Parses the class and produces a new tree.
+
+ \sa addProject
+*/
+
ParserTreeItem::ConstPtr Parser::parse()
{
QTime time;
@@ -222,8 +276,7 @@ ParserTreeItem::ConstPtr Parser::parse()
ParserTreeItem::Ptr rootItem(new ParserTreeItem());
// check all projects
- QList<ProjectExplorer::Project *> projects = getProjectList();
- foreach (const ProjectExplorer::Project *prj, projects) {
+ foreach (const Project *prj, SessionManager::projects()) {
if (!prj)
continue;
@@ -234,14 +287,14 @@ ParserTreeItem::ConstPtr Parser::parse()
QString prjName(prj->displayName());
QString prjType(prjName);
if (prj->document())
- prjType = prj->document()->fileName();
+ prjType = prj->projectFilePath();
SymbolInformation inf(prjName, prjType);
QStringList projectList = addProjectNode(item, prj->rootProjectNode());
if (d->flatMode) {
// use prj path (prjType) as a project id
-// addProject(item, prj->files(ProjectExplorer::Project::ExcludeGeneratedFiles), prjType);
+// addProject(item, prj->files(Project::ExcludeGeneratedFiles), prjType);
//! \todo return back, works too long
ParserTreeItem::Ptr flatItem = createFlatTree(projectList);
item.swap(flatItem);
@@ -257,6 +310,11 @@ ParserTreeItem::ConstPtr Parser::parse()
return rootItem;
}
+/*!
+ Parses the project with the \a projectId and adds the documents
+ from the \a fileList to the tree item \a item.
+*/
+
void Parser::addProject(const ParserTreeItem::Ptr &item, const QStringList &fileList,
const QString &projectId)
{
@@ -269,6 +327,10 @@ void Parser::addProject(const ParserTreeItem::Ptr &item, const QStringList &file
item->copy(prj);
}
+/*!
+ Parses \a symbol and adds the results to \a item (as a parent).
+*/
+
void Parser::addSymbol(const ParserTreeItem::Ptr &item, const CPlusPlus::Symbol *symbol)
{
if (item.isNull() || !symbol)
@@ -350,6 +412,10 @@ void Parser::addSymbol(const ParserTreeItem::Ptr &item, const CPlusPlus::Symbol
item->appendChild(itemAdd, information);
}
+/*!
+ Creates a flat tree from the list of projects specified by \a projectList.
+*/
+
ParserTreeItem::Ptr Parser::createFlatTree(const QStringList &projectList)
{
QReadLocker locker(&d->prjLocker);
@@ -364,6 +430,12 @@ ParserTreeItem::Ptr Parser::createFlatTree(const QStringList &projectList)
return item;
}
+/*!
+ Parses the project with the \a projectId and adds the documents from the
+ \a fileList to the project. Updates the internal cached tree for this
+ project.
+*/
+
ParserTreeItem::Ptr Parser::getParseProjectTree(const QStringList &fileList,
const QString &projectId)
{
@@ -397,6 +469,12 @@ ParserTreeItem::Ptr Parser::getParseProjectTree(const QStringList &fileList,
return item;
}
+/*!
+ Gets the project with \a projectId from the cache if it is valid or parses
+ the project and adds the documents from the \a fileList to the project.
+ Updates the internal cached tree for this project.
+*/
+
ParserTreeItem::Ptr Parser::getCachedOrParseProjectTree(const QStringList &fileList,
const QString &projectId)
{
@@ -424,6 +502,13 @@ ParserTreeItem::Ptr Parser::getCachedOrParseProjectTree(const QStringList &fileL
return getParseProjectTree(fileList, projectId);
}
+/*!
+ Parses the document \a doc if it is in the project files and adds a tree to
+ the internal storage. Updates the internal cached tree for this document.
+
+ \sa parseDocument
+*/
+
ParserTreeItem::ConstPtr Parser::getParseDocumentTree(const CPlusPlus::Document::Ptr &doc)
{
if (doc.isNull())
@@ -448,6 +533,13 @@ ParserTreeItem::ConstPtr Parser::getParseDocumentTree(const CPlusPlus::Document:
return itemPtr;
}
+/*!
+ Gets the document \a doc from the cache or parses it if it is in the project
+ files and adds a tree to the internal storage.
+
+ \sa parseDocument
+*/
+
ParserTreeItem::ConstPtr Parser::getCachedOrParseDocumentTree(const CPlusPlus::Document::Ptr &doc)
{
if (doc.isNull())
@@ -465,6 +557,11 @@ ParserTreeItem::ConstPtr Parser::getCachedOrParseDocumentTree(const CPlusPlus::D
return getParseDocumentTree(doc);
}
+/*!
+ Parses the document \a doc if it is in the project files and adds a tree to
+ the internal storage.
+*/
+
void Parser::parseDocument(const CPlusPlus::Document::Ptr &doc)
{
if (doc.isNull())
@@ -485,6 +582,10 @@ void Parser::parseDocument(const CPlusPlus::Document::Ptr &doc)
return;
}
+/*!
+ Requests to clear full internal stored data.
+*/
+
void Parser::clearCacheAll()
{
d->docLocker.lockForWrite();
@@ -498,6 +599,11 @@ void Parser::clearCacheAll()
clearCache();
}
+/*!
+ Requests to clear internal stored data. The data has to be regenerated on
+ the next request.
+*/
+
void Parser::clearCache()
{
QWriteLocker locker(&d->prjLocker);
@@ -511,12 +617,21 @@ void Parser::clearCache()
d->cachedPrjTreesRevision.clear();
}
+/*!
+ Specifies the files that must be allowed for the parsing as a \a fileList.
+ Files outside of this list will not be in any tree.
+*/
+
void Parser::setFileList(const QStringList &fileList)
{
d->fileList.clear();
d->fileList = QSet<QString>::fromList(fileList);
}
+/*!
+ Removes the files defined in the \a fileList from the parsing.
+*/
+
void Parser::removeFiles(const QStringList &fileList)
{
if (fileList.count() == 0)
@@ -536,6 +651,10 @@ void Parser::removeFiles(const QStringList &fileList)
emit filesAreRemoved();
}
+/*!
+ Fully resets the internal state of the code parser to \a snapshot.
+*/
+
void Parser::resetData(const CPlusPlus::Snapshot &snapshot)
{
// clear internal cache
@@ -555,16 +674,21 @@ void Parser::resetData(const CPlusPlus::Snapshot &snapshot)
QStringList fileList;
// check all projects
- QList<ProjectExplorer::Project *> projects = getProjectList();
- foreach (const ProjectExplorer::Project *prj, projects) {
+ foreach (const Project *prj, SessionManager::projects()) {
if (prj)
- fileList += prj->files(ProjectExplorer::Project::ExcludeGeneratedFiles);
+ fileList += prj->files(Project::ExcludeGeneratedFiles);
}
setFileList(fileList);
emit resetDataDone();
}
+/*!
+ Fully resets the internal state of the code parser to the current state.
+
+ \sa resetData
+*/
+
void Parser::resetDataToCurrentState()
{
// get latest data
@@ -573,17 +697,31 @@ void Parser::resetDataToCurrentState()
resetData(codeModel->snapshot());
}
+/*!
+ Regenerates the tree when internal data changes.
+
+ \sa resetDataDone
+*/
+
void Parser::onResetDataDone()
{
// internal data is reset, update a tree and send it back
emitCurrentTree();
}
+/*!
+ Requests to emit a signal with the current tree state.
+*/
+
void Parser::requestCurrentState()
{
emitCurrentTree();
}
+/*!
+ Sends the current tree to listeners.
+*/
+
void Parser::emitCurrentTree()
{
// stop timer if it is active right now
@@ -601,6 +739,10 @@ void Parser::emitCurrentTree()
emit treeDataUpdate(std);
}
+/*!
+ Generates a project node file list for the root node \a node.
+*/
+
QStringList Parser::projectNodeFileList(const ProjectExplorer::FolderNode *node) const
{
QStringList list;
@@ -627,6 +769,13 @@ QStringList Parser::projectNodeFileList(const ProjectExplorer::FolderNode *node)
return list;
}
+/*!
+ Generates projects like the Project Explorer.
+ \a item specifies the item and \a node specifies the root node.
+
+ Returns a list of projects which were added to the item.
+*/
+
QStringList Parser::addProjectNode(const ParserTreeItem::Ptr &item,
const ProjectExplorer::ProjectNode *node)
{
@@ -670,18 +819,5 @@ QStringList Parser::addProjectNode(const ParserTreeItem::Ptr &item,
return projectList;
}
-QList<ProjectExplorer::Project *> Parser::getProjectList() const
-{
- QList<ProjectExplorer::Project *> list;
-
- // check all projects
- ProjectExplorer::SessionManager *sessionManager
- = ProjectExplorer::ProjectExplorerPlugin::instance()->session();
-
- list = sessionManager->projects();
-
- return list;
-}
-
} // namespace Internal
} // namespace ClassView
diff --git a/src/plugins/classview/classviewparser.h b/src/plugins/classview/classviewparser.h
index b8ab34dde8..84ae7a84c1 100644
--- a/src/plugins/classview/classviewparser.h
+++ b/src/plugins/classview/classviewparser.h
@@ -50,208 +50,74 @@ namespace Internal {
class ParserPrivate;
-/*!
- \class Parser
- \brief Parse cpp information. Multithreading is supported.
- */
-
class Parser : public QObject
{
Q_OBJECT
public:
- /*!
- \brief Constructor
- */
explicit Parser(QObject *parent = 0);
~Parser();
- /*!
- \brief Lazy data population for a \a QStandardItemModel
- \param item Item which has to be checked
- */
bool canFetchMore(QStandardItem *item) const;
- /*!
- \brief Lazy data population for a \a QStandardItemModel
- \param item Item which will be populated (if needed)
- \param skipRoot Skip root item
- */
void fetchMore(QStandardItem *item, bool skipRoot = false) const;
signals:
//! File list is changed
void filesAreRemoved();
- /*!
- \brief Signal about a tree data update
- */
void treeDataUpdate(QSharedPointer<QStandardItem> result);
- /*!
- \brief Signal that internal data
- \sa resetData, resetDataToCurrentState
- */
void resetDataDone();
public slots:
- /*!
- \brief Request to clear full internal stored data.
- */
void clearCacheAll();
- /*!
- \brief Request to clear internal stored data, it has to be regenerated on the next request.
- */
void clearCache();
- /*!
- \brief Request to emit a signal with the current tree state
- */
void requestCurrentState();
- /*!
- \brief Set file list for the parsing, files outside of this list will not be in any tree.
- \param fileList Files which must be allowed for the parsing
- */
void setFileList(const QStringList &fileList);
- /*!
- \brief Remove some files from the file list for the parsing.
- \param fileList Files which must be removed from the parsing
- */
void removeFiles(const QStringList &fileList);
- /*!
- \brief Fully reset internal state
- \param snapshot Code parser snapshot
- */
void resetData(const CPlusPlus::Snapshot &snapshot);
- /*!
- \brief Fully reset internal state - to the current state
- \sa resetData
- */
void resetDataToCurrentState();
- /*!
- \brief Parse document if it is in the project files and add a tree to the internal storage
- \param doc Document which has to be parsed
- */
void parseDocument(const CPlusPlus::Document::Ptr &doc);
- /*!
- \brief Switch to flat mode (without subprojects)
- \param flat True to enable flat mode, false to disable
- */
void setFlatMode(bool flat);
protected slots:
- /*!
- \brief Internal data is changed, regenerate the tree
- \sa resetDataDone
- */
void onResetDataDone();
protected:
- /*!
- \brief Parse one particular project and add result to the tree item
- \param item Item where parsed project has to be stored
- \param fileList Files
- \param projectId Project id, is needed for prj cache
- */
void addProject(const ParserTreeItem::Ptr &item, const QStringList &fileList,
const QString &projectId = QString());
- /*!
- \brief Parse one particular symbol and add result to the tree item (as a parent)
- \param item Item where parsed symbol has to be stored
- \param symbol Symbol which has to be used as a source
- */
void addSymbol(const ParserTreeItem::Ptr &item, const CPlusPlus::Symbol *symbol);
- /*!
- \brief Parse document if it is in the project files and add a tree to the internal storage.
- Update internal cached tree for this document.
- \param doc Document which has to be parsed
- \return A tree
- \sa parseDocument
- */
ParserTreeItem::ConstPtr getParseDocumentTree(const CPlusPlus::Document::Ptr &doc);
- /*!
- \brief Get from the cache or parse document if it is in the project files
- and add a tree to the internal storage
- \param doc Document which has to be parsed
- \return A tree
- \sa parseDocument
- */
ParserTreeItem::ConstPtr getCachedOrParseDocumentTree(const CPlusPlus::Document::Ptr &doc);
- /*!
- \brief Parse project and add a tree to the internal storage.
- Update internal cached tree for this project.
- \param fileList Documents which has to be added to the project
- \param projectId Project id
- \return A tree
- */
ParserTreeItem::Ptr getParseProjectTree(const QStringList &fileList, const QString &projectId);
- /*!
- \brief Get from the cache (if valid) or parse project and add a tree to the internal storage.
- Update internal cached tree for this project.
- \param fileList Documents which has to be added to the project
- \param projectId Project id
- \return A tree
- */
ParserTreeItem::Ptr getCachedOrParseProjectTree(const QStringList &fileList,
const QString &projectId);
- /*!
- \brief Send a current tree to listeners
- */
void emitCurrentTree();
- /*!
- \brief Parse the class and produce a new tree
- \sa addProject
- */
ParserTreeItem::ConstPtr parse();
- /*!
- \brief Find internal node for the specified UI item
- \param item Item which has to be found
- \param skipRoot Skip root item
- \return Found internal node
- */
ParserTreeItem::ConstPtr findItemByRoot(const QStandardItem *item, bool skipRoot = false) const;
- /*!
- \brief Generate projects like Project Explorer
- \param item Item
- \param node Root node
- \return List of projects which were added to the item
- */
QStringList addProjectNode(const ParserTreeItem::Ptr &item,
const ProjectExplorer::ProjectNode *node);
- /*!
- \brief Generate project node file list
- \param node Root node
- */
QStringList projectNodeFileList(const ProjectExplorer::FolderNode *node) const;
- /*!
- \brief Get the current project list
- \return Project list
- */
- QList<ProjectExplorer::Project *> getProjectList() const;
-
- /*!
- \brief Create flat tree from different projects
- \param projectList List of projects
- \return Flat tree
- */
ParserTreeItem::Ptr createFlatTree(const QStringList &projectList);
private:
diff --git a/src/plugins/classview/classviewparsertreeitem.cpp b/src/plugins/classview/classviewparsertreeitem.cpp
index 5c73e263b4..f46a5ce130 100644
--- a/src/plugins/classview/classviewparsertreeitem.cpp
+++ b/src/plugins/classview/classviewparsertreeitem.cpp
@@ -49,8 +49,9 @@ namespace Internal {
///////////////////////////////// ParserTreeItemPrivate //////////////////////////////////
/*!
- \struct ParserTreeItemPrivate
- \brief Private class data for \a ParserTreeItem
+ \class ParserTreeItemPrivate
+ \brief The ParserTreeItemPrivate class defines private class data for
+ the ParserTreeItem class.
\sa ParserTreeItem
*/
class ParserTreeItemPrivate
@@ -68,6 +69,13 @@ public:
///////////////////////////////// ParserTreeItem //////////////////////////////////
+/*!
+ \class ParserTreeItem
+ \brief The ParserTreeItem class is an item for the internal Class View tree.
+
+ Not virtual - to speed up its work.
+*/
+
ParserTreeItem::ParserTreeItem() :
d(new ParserTreeItemPrivate())
{
@@ -86,6 +94,11 @@ ParserTreeItem &ParserTreeItem::operator=(const ParserTreeItem &other)
return *this;
}
+/*!
+ Copies a parser tree item from the location specified by \a from to this
+ item.
+*/
+
void ParserTreeItem::copy(const ParserTreeItem::ConstPtr &from)
{
if (from.isNull())
@@ -96,6 +109,12 @@ void ParserTreeItem::copy(const ParserTreeItem::ConstPtr &from)
d->symbolInformations = from->d->symbolInformations;
}
+/*!
+ \fn void copyTree(const ParserTreeItem::ConstPtr &from)
+ Copies a parser tree item with children from the location specified by
+ \a from to this item.
+*/
+
void ParserTreeItem::copyTree(const ParserTreeItem::ConstPtr &target)
{
if (target.isNull())
@@ -123,31 +142,60 @@ void ParserTreeItem::copyTree(const ParserTreeItem::ConstPtr &target)
}
}
+/*!
+ Adds information about symbol location from a \location.
+ \sa SymbolLocation, removeSymbolLocation, symbolLocations
+*/
+
void ParserTreeItem::addSymbolLocation(const SymbolLocation &location)
{
d->symbolLocations.insert(location);
}
+/*!
+ Adds information about symbol locations from \a locations.
+ \sa SymbolLocation, removeSymbolLocation, symbolLocations
+*/
+
void ParserTreeItem::addSymbolLocation(const QSet<SymbolLocation> &locations)
{
d->symbolLocations.unite(locations);
}
+/*!
+ Removes information about \a location.
+ \sa SymbolLocation, addSymbolLocation, symbolLocations
+*/
+
void ParserTreeItem::removeSymbolLocation(const SymbolLocation &location)
{
d->symbolLocations.remove(location);
}
+/*!
+ Removes information about \a locations.
+ \sa SymbolLocation, addSymbolLocation, symbolLocations
+*/
+
void ParserTreeItem::removeSymbolLocations(const QSet<SymbolLocation> &locations)
{
d->symbolLocations.subtract(locations);
}
+/*!
+ Gets information about symbol positions.
+ \sa SymbolLocation, addSymbolLocation, removeSymbolLocation
+*/
+
QSet<SymbolLocation> ParserTreeItem::symbolLocations() const
{
return d->symbolLocations;
}
+/*!
+ Appends the child item \a item to \a inf symbol information.
+*/
+
void ParserTreeItem::appendChild(const ParserTreeItem::Ptr &item, const SymbolInformation &inf)
{
// removeChild must be used to remove an item
@@ -157,11 +205,19 @@ void ParserTreeItem::appendChild(const ParserTreeItem::Ptr &item, const SymbolIn
d->symbolInformations[inf] = item;
}
+/*!
+ Removes the \a inf symbol information.
+*/
+
void ParserTreeItem::removeChild(const SymbolInformation &inf)
{
d->symbolInformations.remove(inf);
}
+/*!
+ Returns the child item specified by \a inf symbol information.
+*/
+
ParserTreeItem::Ptr ParserTreeItem::child(const SymbolInformation &inf) const
{
if (!d->symbolInformations.contains(inf))
@@ -169,21 +225,38 @@ ParserTreeItem::Ptr ParserTreeItem::child(const SymbolInformation &inf) const
return d->symbolInformations[inf];
}
+/*!
+ Returns the amount of children of the tree item.
+*/
+
int ParserTreeItem::childCount() const
{
return d->symbolInformations.count();
}
+/*!
+ \property QIcon::icon
+ \brief the icon assigned to the tree item
+*/
+
QIcon ParserTreeItem::icon() const
{
return d->icon;
}
+/*!
+ Sets the \a icon for the tree item.
+ */
void ParserTreeItem::setIcon(const QIcon &icon)
{
d->icon = icon;
}
+/*!
+ Adds an internal state with \a target, which contains the correct current
+ state.
+*/
+
void ParserTreeItem::add(const ParserTreeItem::ConstPtr &target)
{
if (target.isNull())
@@ -221,6 +294,10 @@ void ParserTreeItem::add(const ParserTreeItem::ConstPtr &target)
}
}
+/*!
+ Subtracts an internal state with \a target, which contains the subtrahend.
+*/
+
void ParserTreeItem::subtract(const ParserTreeItem::ConstPtr &target)
{
if (target.isNull())
@@ -246,6 +323,12 @@ void ParserTreeItem::subtract(const ParserTreeItem::ConstPtr &target)
}
}
+/*!
+ Appends this item to the QStandardIten item \a item.
+ \a recursive does it recursively for the tree items (might be needed for
+ lazy data population.
+*/
+
void ParserTreeItem::convertTo(QStandardItem *item, bool recursive) const
{
if (!item)
@@ -288,6 +371,10 @@ void ParserTreeItem::convertTo(QStandardItem *item, bool recursive) const
}
}
+/*!
+ Checks \a item in a QStandardItemModel for lazy data population.
+*/
+
bool ParserTreeItem::canFetchMore(QStandardItem *item) const
{
if (!item)
@@ -327,6 +414,10 @@ bool ParserTreeItem::canFetchMore(QStandardItem *item) const
return false;
}
+/*!
+ Performs lazy data population for \a item in a QStandardItemModel if needed.
+*/
+
void ParserTreeItem::fetchMore(QStandardItem *item) const
{
if (!item)
@@ -353,6 +444,10 @@ void ParserTreeItem::fetchMore(QStandardItem *item) const
}
}
+/*!
+ Debug dump.
+*/
+
void ParserTreeItem::debugDump(int ident) const
{
QHash<SymbolInformation, ParserTreeItem::Ptr>::const_iterator curHash =
diff --git a/src/plugins/classview/classviewparsertreeitem.h b/src/plugins/classview/classviewparsertreeitem.h
index bda9c8609f..cbdb9a277b 100644
--- a/src/plugins/classview/classviewparsertreeitem.h
+++ b/src/plugins/classview/classviewparsertreeitem.h
@@ -42,14 +42,6 @@ namespace Internal {
class ParserTreeItemPrivate;
-/*!
- \class ParserTreeItem
- \brief Item for the internal Class View Tree
-
- Item for Class View Tree.
- Not virtual - to speed up its work.
- */
-
class ParserTreeItem
{
public:
@@ -60,85 +52,28 @@ public:
ParserTreeItem();
~ParserTreeItem();
- /*!
- \brief Copy content of \a from item with children to this one.
- \param from 'From' item
- */
void copyTree(const ParserTreeItem::ConstPtr &from);
- /*!
- \brief Copy of \a from item to this one.
- \param from 'From' item
- */
void copy(const ParserTreeItem::ConstPtr &from);
- /*!
- \brief Add information about symbol location
- \param location Filled \a SymbolLocation struct with a correct information
- \sa SymbolLocation, removeSymbolLocation, symbolLocations
- */
void addSymbolLocation(const SymbolLocation &location);
- /*!
- \brief Add information about symbol locations
- \param locations Filled \a SymbolLocation struct with a correct information
- \sa SymbolLocation, removeSymbolLocation, symbolLocations
- */
void addSymbolLocation(const QSet<SymbolLocation> &locations);
- /*!
- \brief Remove information about symbol location
- \param location Filled \a SymbolLocation struct with a correct information
- \sa SymbolLocation, addSymbolLocation, symbolLocations
- */
void removeSymbolLocation(const SymbolLocation &location);
- /*!
- \brief Remove information about symbol locations
- \param locations Filled \a SymbolLocation struct with a correct information
- \sa SymbolLocation, addSymbolLocation, symbolLocations
- */
void removeSymbolLocations(const QSet<SymbolLocation> &locations);
- /*!
- \brief Get information about symbol positions
- \sa SymbolLocation, addSymbolLocation, removeSymbolLocation
- */
QSet<SymbolLocation> symbolLocations() const;
- /*!
- \brief Append child
- \param item Child item
- \param inf Symbol information
- */
void appendChild(const ParserTreeItem::Ptr &item, const SymbolInformation &inf);
- /*!
- \brief Remove child
- \param inf SymbolInformation which has to be removed
- */
void removeChild(const SymbolInformation &inf);
- /*!
- \brief Get an item
- \param inf Symbol information about needed child
- \return Found child
- */
ParserTreeItem::Ptr child(const SymbolInformation &inf) const;
- /*!
- \brief How many children
- \return Amount of chilren
- */
int childCount() const;
- /*!
- \brief Append this item to the \a QStandardIten item
- \param item QStandardItem
- \param recursive Do it recursively for the tree items or not (might be needed for
- the lazy data population
-
- */
void convertTo(QStandardItem *item, bool recursive = true) const;
// additional properties
@@ -148,33 +83,14 @@ public:
//! Set an icon for this tree node
void setIcon(const QIcon &icon);
- /*!
- \brief Add an internal state with \a target.
- \param target Item which contains the correct current state
- */
void add(const ParserTreeItem::ConstPtr &target);
- /*!
- \brief Subtract an internal state with \a target.
- \param target Item which contains the subtrahend
- */
void subtract(const ParserTreeItem::ConstPtr &target);
- /*!
- \brief Lazy data population for a \a QStandardItemModel
- \param item Item which has to be checked
- */
bool canFetchMore(QStandardItem *item) const;
- /*!
- \brief Lazy data population for a \a QStandardItemModel
- \param item Item which will be populated (if needed)
- */
void fetchMore(QStandardItem *item) const;
- /*!
- \brief Debug dump
- */
void debugDump(int ident = 0) const;
protected:
diff --git a/src/plugins/classview/classviewplugin.cpp b/src/plugins/classview/classviewplugin.cpp
index d5f552f7a6..db233e7954 100644
--- a/src/plugins/classview/classviewplugin.cpp
+++ b/src/plugins/classview/classviewplugin.cpp
@@ -38,6 +38,14 @@ namespace Internal {
///////////////////////////////// Plugin //////////////////////////////////
+/*!
+ \class Plugin
+ \brief The Plugin class is the base class for the Class View plugin.
+
+ The Class View shows the namespace and class hierarchy of the currently open
+ projects in the sidebar.
+*/
+
bool Plugin::initialize(const QStringList &arguments, QString *errorMessage)
{
Q_UNUSED(arguments)
diff --git a/src/plugins/classview/classviewplugin.h b/src/plugins/classview/classviewplugin.h
index b3898d30f2..ea6dd39bba 100644
--- a/src/plugins/classview/classviewplugin.h
+++ b/src/plugins/classview/classviewplugin.h
@@ -35,11 +35,6 @@
namespace ClassView {
namespace Internal {
-/*!
- \class Plugin
- \brief Base class for Class View plugin (class/namespaces in the navigation pane)
- */
-
class Plugin : public ExtensionSystem::IPlugin
{
Q_OBJECT
diff --git a/src/plugins/classview/classviewsymbolinformation.cpp b/src/plugins/classview/classviewsymbolinformation.cpp
index a38997ce91..3eb9e1efc8 100644
--- a/src/plugins/classview/classviewsymbolinformation.cpp
+++ b/src/plugins/classview/classviewsymbolinformation.cpp
@@ -36,6 +36,12 @@
namespace ClassView {
namespace Internal {
+/*!
+ \class SymbolInformation
+ \brief The SymbolInformation class provides the name, type, and icon for a
+ single item in the Class View tree.
+*/
+
SymbolInformation::SymbolInformation() :
m_iconType(INT_MIN),
m_hash(0)
@@ -52,6 +58,11 @@ SymbolInformation::SymbolInformation(const QString &valueName, const QString &va
m_hash = qHash(qMakePair(m_iconType, qMakePair(m_name, m_type)));
}
+/*!
+ Returns an icon type sort order number. It is not pre-calculated, as it is
+ needed for converting to standard item only.
+*/
+
int SymbolInformation::iconTypeSortOrder() const
{
return Utils::iconTypeSortOrder(m_iconType);
diff --git a/src/plugins/classview/classviewsymbolinformation.h b/src/plugins/classview/classviewsymbolinformation.h
index d7331347a6..ecae8c8110 100644
--- a/src/plugins/classview/classviewsymbolinformation.h
+++ b/src/plugins/classview/classviewsymbolinformation.h
@@ -38,11 +38,6 @@
namespace ClassView {
namespace Internal {
-/*!
- \class SymbolInformation
- \brief Provides name, type and icon for single item in Class View tree
- */
-
class SymbolInformation
{
public:
@@ -61,11 +56,6 @@ public:
&& type() == other.type();
}
- /*!
- \brief Get an icon type sort order. Not pre-calculated - is needed for converting
- to Standard Item only.
- \return Sort order number.
- */
int iconTypeSortOrder() const;
private:
diff --git a/src/plugins/classview/classviewsymbollocation.cpp b/src/plugins/classview/classviewsymbollocation.cpp
index c1fb4bd8ae..8db565577e 100644
--- a/src/plugins/classview/classviewsymbollocation.cpp
+++ b/src/plugins/classview/classviewsymbollocation.cpp
@@ -34,6 +34,14 @@
namespace ClassView {
namespace Internal {
+/*!
+ \class SymbolLocation
+ \brief The SymbolLocation class stores information about symbol location
+ to know the exact location to open when the user clicks on a tree item.
+
+ This class might be used in QSet and QHash.
+*/
+
SymbolLocation::SymbolLocation() :
m_line(0),
m_column(0),
diff --git a/src/plugins/classview/classviewsymbollocation.h b/src/plugins/classview/classviewsymbollocation.h
index 121b2ef3f6..8bc4c95b94 100644
--- a/src/plugins/classview/classviewsymbollocation.h
+++ b/src/plugins/classview/classviewsymbollocation.h
@@ -36,11 +36,6 @@
namespace ClassView {
namespace Internal {
-/*!
- \class SymbolLocation
- \brief Special struct to store information about symbol location (to find which exactly location
- has to be open when the user clicks on any tree item. It might be used in QSet/QHash.
- */
class SymbolLocation
{
public:
diff --git a/src/plugins/classview/classviewtreeitemmodel.cpp b/src/plugins/classview/classviewtreeitemmodel.cpp
index 1cfc1a1dad..7d8dc1ebc2 100644
--- a/src/plugins/classview/classviewtreeitemmodel.cpp
+++ b/src/plugins/classview/classviewtreeitemmodel.cpp
@@ -40,8 +40,9 @@ namespace Internal {
///////////////////////////////// TreeItemModelPrivate //////////////////////////////////
/*!
- \struct TreeItemModelPrivate
- \brief Private class data for \a TreeItemModel
+ \class TreeItemModelPrivate
+ \brief The TreeItemModelPrivate class contains private class data for
+ the TreeItemModel class.
\sa TreeItemModel
*/
class TreeItemModelPrivate
@@ -53,6 +54,11 @@ public:
///////////////////////////////// TreeItemModel //////////////////////////////////
+/*!
+ \class TreeItemModel
+ \brief The TreeItemModel class provides a model for the Class View tree.
+*/
+
TreeItemModel::TreeItemModel(QObject *parent)
: QStandardItemModel(parent),
d(new TreeItemModelPrivate())
@@ -118,6 +124,10 @@ void TreeItemModel::fetchMore(const QModelIndex &parent)
return Manager::instance()->fetchMore(itemFromIndex(parent));
}
+/*!
+ Moves the root item to the \a target item.
+*/
+
void TreeItemModel::moveRootToTarget(const QStandardItem *target)
{
emit layoutAboutToBeChanged();
diff --git a/src/plugins/classview/classviewtreeitemmodel.h b/src/plugins/classview/classviewtreeitemmodel.h
index 59e911bd8e..b4a8407f67 100644
--- a/src/plugins/classview/classviewtreeitemmodel.h
+++ b/src/plugins/classview/classviewtreeitemmodel.h
@@ -37,11 +37,6 @@ namespace Internal {
class TreeItemModelPrivate;
-/*!
- \class TreeItemModel
- \brief Model for Class View Tree
- */
-
class TreeItemModel : public QStandardItemModel
{
Q_OBJECT
@@ -50,10 +45,6 @@ public:
explicit TreeItemModel(QObject *parent=0);
virtual ~TreeItemModel();
- /*!
- \brief move root item to the target
- \param target Target item
- */
void moveRootToTarget(const QStandardItem *target);
//! \implements QStandardItemModel::data
diff --git a/src/plugins/classview/classviewutils.cpp b/src/plugins/classview/classviewutils.cpp
index 70d7e12f01..efa13edb05 100644
--- a/src/plugins/classview/classviewutils.cpp
+++ b/src/plugins/classview/classviewutils.cpp
@@ -40,6 +40,11 @@
namespace ClassView {
namespace Constants {
+/*!
+ \class Utils
+ \brief The Utils class provides some common utilities.
+*/
+
//! Default icon sort order
const int IconSortOrder[] = {
CPlusPlus::Icons::NamespaceIconType,
@@ -69,6 +74,13 @@ Utils::Utils()
{
}
+/*!
+ Converts internal location container to QVariant compatible.
+ \a locations specifies a set of symbol locations.
+ Returns a list of variant locations that can be added to the data of an
+ item.
+*/
+
QList<QVariant> Utils::locationsToRole(const QSet<SymbolLocation> &locations)
{
QList<QVariant> locationsVar;
@@ -78,6 +90,13 @@ QList<QVariant> Utils::locationsToRole(const QSet<SymbolLocation> &locations)
return locationsVar;
}
+/*!
+ Converts QVariant location container to internal.
+ \a locationsVar contains a list of variant locations from the data of an
+ item.
+ Returns a set of symbol locations.
+ */
+
QSet<SymbolLocation> Utils::roleToLocations(const QList<QVariant> &locationsVar)
{
QSet<SymbolLocation> locations;
@@ -89,6 +108,10 @@ QSet<SymbolLocation> Utils::roleToLocations(const QList<QVariant> &locationsVar)
return locations;
}
+/*!
+ Returns sort order value for the \a icon.
+*/
+
int Utils::iconTypeSortOrder(int icon)
{
static QHash<int, int> sortOrder;
@@ -107,6 +130,12 @@ int Utils::iconTypeSortOrder(int icon)
return sortOrder[icon];
}
+/*!
+ Sets symbol information specified by \a information to \a item.
+ \a information provides the name, type, and icon for the item.
+ Returns the filled item.
+*/
+
QStandardItem *Utils::setSymbolInformationToItem(const SymbolInformation &information,
QStandardItem *item)
{
@@ -119,6 +148,10 @@ QStandardItem *Utils::setSymbolInformationToItem(const SymbolInformation &inform
return item;
}
+/*!
+ Returns symbol information for \a item.
+*/
+
SymbolInformation Utils::symbolInformationFromItem(const QStandardItem *item)
{
Q_ASSERT(item);
@@ -141,6 +174,10 @@ SymbolInformation Utils::symbolInformationFromItem(const QStandardItem *item)
return SymbolInformation(name, type, iconType);
}
+/*!
+ Updates \a item to \a target, so that it is sorted and can be fetched.
+*/
+
void Utils::fetchItemToTarget(QStandardItem *item, const QStandardItem *target)
{
if (!item || !target)
@@ -178,6 +215,9 @@ void Utils::fetchItemToTarget(QStandardItem *item, const QStandardItem *target)
}
}
+/*!
+ Moves \a item to \a target (sorted).
+*/
void Utils::moveItemToTarget(QStandardItem *item, const QStandardItem *target)
{
if (!item || !target)
diff --git a/src/plugins/classview/classviewutils.h b/src/plugins/classview/classviewutils.h
index 78bc793a2a..789a51bece 100644
--- a/src/plugins/classview/classviewutils.h
+++ b/src/plugins/classview/classviewutils.h
@@ -41,66 +41,25 @@ QT_FORWARD_DECLARE_CLASS(QStandardItem)
namespace ClassView {
namespace Internal {
-/*!
- \class Utils
- \brief Some common utils
- */
-
class Utils
{
//! Private constructor
Utils();
public:
- /*!
- \brief convert internal location container to QVariant compatible
- \param locations Set of SymbolLocations
- \return List of variant locations (can be added to an item's data)
- */
static QList<QVariant> locationsToRole(const QSet<SymbolLocation> &locations);
- /*!
- \brief convert QVariant location container to internal
- \param locations List of variant locations (from an item's data)
- \return Set of SymbolLocations
- */
static QSet<SymbolLocation> roleToLocations(const QList<QVariant> &locations);
- /*!
- \brief Returns sort order value for the icon type
- \param iconType Icon type
- \return Sort order value for the provided icon type
- */
static int iconTypeSortOrder(int iconType);
- /*!
- \brief Get symbol information for the \a QStandardItem
- \param item Item
- \return Filled symbol information.
- */
static SymbolInformation symbolInformationFromItem(const QStandardItem *item);
- /*!
- \brief Set symbol information to the \a QStandardItem
- \param information Provides name, type and icon
- \param item Item
- \return Filled item
- */
static QStandardItem *setSymbolInformationToItem(const SymbolInformation &information,
QStandardItem *item);
- /*!
- \brief Update an item to the target. (sorted, for fetching)
- \param item Source item
- \param target Target item
- */
static void fetchItemToTarget(QStandardItem *item, const QStandardItem *target);
- /*!
- \brief Move an item to the target. (sorted)
- \param item Source item
- \param target Target item
- */
static void moveItemToTarget(QStandardItem *item, const QStandardItem *target);
};
diff --git a/src/plugins/clearcase/ClearCase.pluginspec.in b/src/plugins/clearcase/ClearCase.pluginspec.in
index 13558fa3da..32a13f66df 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\">
+<plugin name=\"ClearCase\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\" disabledByDefault=\"$$CLEARCASE_DISABLED_STR\">
<vendor>AudioCodes</vendor>
<copyright>(C) 2013 AudioCodes Ltd.</copyright>
<license>
diff --git a/src/plugins/clearcase/annotationhighlighter.cpp b/src/plugins/clearcase/annotationhighlighter.cpp
index 89ba548993..81de1b9079 100644
--- a/src/plugins/clearcase/annotationhighlighter.cpp
+++ b/src/plugins/clearcase/annotationhighlighter.cpp
@@ -34,9 +34,8 @@ using namespace ClearCase;
using namespace ClearCase::Internal;
ClearCaseAnnotationHighlighter::ClearCaseAnnotationHighlighter(const ChangeNumbers &changeNumbers,
- const QColor &bg,
QTextDocument *document) :
- VcsBase::BaseAnnotationHighlighter(changeNumbers, bg, document),
+ VcsBase::BaseAnnotationHighlighter(changeNumbers, document),
m_separator(QLatin1Char('|'))
{
}
diff --git a/src/plugins/clearcase/annotationhighlighter.h b/src/plugins/clearcase/annotationhighlighter.h
index 9792e2492e..f7e2740d3d 100644
--- a/src/plugins/clearcase/annotationhighlighter.h
+++ b/src/plugins/clearcase/annotationhighlighter.h
@@ -41,7 +41,7 @@ class ClearCaseAnnotationHighlighter : public VcsBase::BaseAnnotationHighlighter
{
Q_OBJECT
public:
- explicit ClearCaseAnnotationHighlighter(const ChangeNumbers &changeNumbers, const QColor &bg,
+ explicit ClearCaseAnnotationHighlighter(const ChangeNumbers &changeNumbers,
QTextDocument *document = 0);
private:
diff --git a/src/plugins/clearcase/clearcase.pro b/src/plugins/clearcase/clearcase.pro
index d4fa42c38b..21afe71021 100644
--- a/src/plugins/clearcase/clearcase.pro
+++ b/src/plugins/clearcase/clearcase.pro
@@ -1,5 +1,8 @@
# PROVIDER = AudioCodes
+macx: CLEARCASE_DISABLED_STR = "true"
+else: CLEARCASE_DISABLED_STR = "false"
+
include(../../qtcreatorplugin.pri)
HEADERS += activityselector.h \
diff --git a/src/plugins/clearcase/clearcase.qbs b/src/plugins/clearcase/clearcase.qbs
index bc8934029f..dcd94ac24c 100644
--- a/src/plugins/clearcase/clearcase.qbs
+++ b/src/plugins/clearcase/clearcase.qbs
@@ -6,7 +6,7 @@ QtcPlugin {
name: "ClearCase"
// provider: "AudioCodes"
- condition: !qbs.targetOS.contains("osx")
+ pluginspecreplacements: ({"CLEARCASE_DISABLED_STR": (qbs.targetOS.contains("osx") ? "true": "false")})
Depends { name: "Qt.widgets" }
Depends { name: "Core" }
diff --git a/src/plugins/clearcase/clearcasecontrol.cpp b/src/plugins/clearcase/clearcasecontrol.cpp
index 45d04b5b43..79f81242a1 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 Core::Id(ClearCase::Constants::VCS_ID_CLEARCASE);
+ return Constants::VCS_ID_CLEARCASE;
}
bool ClearCaseControl::isConfigured() const
diff --git a/src/plugins/clearcase/clearcaseeditor.cpp b/src/plugins/clearcase/clearcaseeditor.cpp
index 99324d7ab5..04e60dfe27 100644
--- a/src/plugins/clearcase/clearcaseeditor.cpp
+++ b/src/plugins/clearcase/clearcaseeditor.cpp
@@ -36,7 +36,6 @@
#include <utils/qtcassert.h>
#include <vcsbase/diffhighlighter.h>
-#include <QDebug>
#include <QDir>
#include <QFileInfo>
#include <QTextBlock>
@@ -94,8 +93,7 @@ QString ClearCaseEditor::changeUnderCursor(const QTextCursor &c) const
return QString();
}
-VcsBase::BaseAnnotationHighlighter *ClearCaseEditor::createAnnotationHighlighter(const QSet<QString> &changes,
- const QColor &bg) const
+VcsBase::BaseAnnotationHighlighter *ClearCaseEditor::createAnnotationHighlighter(const QSet<QString> &changes) const
{
- return new ClearCaseAnnotationHighlighter(changes, bg);
+ return new ClearCaseAnnotationHighlighter(changes);
}
diff --git a/src/plugins/clearcase/clearcaseeditor.h b/src/plugins/clearcase/clearcaseeditor.h
index c9dd8c88e3..14d7031b86 100644
--- a/src/plugins/clearcase/clearcaseeditor.h
+++ b/src/plugins/clearcase/clearcaseeditor.h
@@ -49,7 +49,7 @@ public:
private:
QSet<QString> annotationChanges() const;
QString changeUnderCursor(const QTextCursor &) const;
- VcsBase::BaseAnnotationHighlighter *createAnnotationHighlighter(const QSet<QString> &changes, const QColor &bg) const;
+ VcsBase::BaseAnnotationHighlighter *createAnnotationHighlighter(const QSet<QString> &changes) const;
QRegExp m_versionNumberPattern;
};
diff --git a/src/plugins/clearcase/clearcaseplugin.cpp b/src/plugins/clearcase/clearcaseplugin.cpp
index ee881e3e4b..0ad3228d7a 100644
--- a/src/plugins/clearcase/clearcaseplugin.cpp
+++ b/src/plugins/clearcase/clearcaseplugin.cpp
@@ -100,6 +100,9 @@
#include <QTest>
#endif
+using namespace Core;
+using namespace ProjectExplorer;
+
namespace ClearCase {
namespace Internal {
@@ -348,10 +351,10 @@ QString ClearCasePlugin::findTopLevel(const QString &directory) const
}
static const VcsBase::VcsBaseSubmitEditorParameters submitParameters = {
- ClearCase::Constants::CLEARCASE_SUBMIT_MIMETYPE,
- ClearCase::Constants::CLEARCASECHECKINEDITOR_ID,
- ClearCase::Constants::CLEARCASECHECKINEDITOR_DISPLAY_NAME,
- ClearCase::Constants::CLEARCASECHECKINEDITOR,
+ Constants::CLEARCASE_SUBMIT_MIMETYPE,
+ Constants::CLEARCASECHECKINEDITOR_ID,
+ Constants::CLEARCASECHECKINEDITOR_DISPLAY_NAME,
+ Constants::CLEARCASECHECKINEDITOR,
VcsBase::VcsBaseSubmitEditorParameters::DiffFiles
};
@@ -367,17 +370,17 @@ bool ClearCasePlugin::initialize(const QStringList & /*arguments */, QString *er
initializeVcs(new ClearCaseControl(this));
m_clearcasePluginInstance = this;
- connect(Core::ICore::instance(), SIGNAL(coreAboutToClose()), this, SLOT(closing()));
- connect(Core::ICore::progressManager(), SIGNAL(allTasksFinished(QString)),
- this, SLOT(tasksFinished(QString)));
+ connect(ICore::instance(), SIGNAL(coreAboutToClose()), this, SLOT(closing()));
+ connect(ProgressManager::instance(), SIGNAL(allTasksFinished(Core::Id)),
+ this, SLOT(tasksFinished(Core::Id)));
- if (!Core::ICore::mimeDatabase()->addMimeTypes(QLatin1String(":/clearcase/ClearCase.mimetypes.xml"), errorMessage))
+ if (!MimeDatabase::addMimeTypes(QLatin1String(":/clearcase/ClearCase.mimetypes.xml"), errorMessage))
return false;
- m_settings.fromSettings(Core::ICore::settings());
+ m_settings.fromSettings(ICore::settings());
// update view name when changing active project
- if (ProjectExplorer::ProjectExplorerPlugin *pe = ProjectExplorer::ProjectExplorerPlugin::instance())
+ if (ProjectExplorerPlugin *pe = ProjectExplorerPlugin::instance())
connect(pe, SIGNAL(currentProjectChanged(ProjectExplorer::Project*)),
this, SLOT(projectChanged(ProjectExplorer::Project*)));
@@ -398,44 +401,44 @@ bool ClearCasePlugin::initialize(const QStringList & /*arguments */, QString *er
addAutoReleasedObject(m_commandLocator);
//register actions
- Core::ActionContainer *toolsContainer = Core::ActionManager::actionContainer(M_TOOLS);
+ ActionContainer *toolsContainer = ActionManager::actionContainer(M_TOOLS);
- Core::ActionContainer *clearcaseMenu = Core::ActionManager::createMenu(Core::Id(CMD_ID_CLEARCASE_MENU));
+ ActionContainer *clearcaseMenu = ActionManager::createMenu(CMD_ID_CLEARCASE_MENU);
clearcaseMenu->menu()->setTitle(tr("C&learCase"));
toolsContainer->addMenu(clearcaseMenu);
m_menuAction = clearcaseMenu->menu()->menuAction();
- Core::Context globalcontext(C_GLOBAL);
- Core::Command *command;
+ Context globalcontext(C_GLOBAL);
+ Command *command;
m_checkOutAction = new Utils::ParameterAction(tr("Check Out..."), tr("Check &Out \"%1\"..."), Utils::ParameterAction::AlwaysEnabled, this);
- command = Core::ActionManager::registerAction(m_checkOutAction, CMD_ID_CHECKOUT,
+ command = ActionManager::registerAction(m_checkOutAction, CMD_ID_CHECKOUT,
globalcontext);
- command->setAttribute(Core::Command::CA_UpdateText);
- command->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+L,Meta+O") : tr("Alt+L,Alt+O")));
+ command->setAttribute(Command::CA_UpdateText);
+ command->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+L,Meta+O") : tr("Alt+L,Alt+O")));
connect(m_checkOutAction, SIGNAL(triggered()), this, SLOT(checkOutCurrentFile()));
clearcaseMenu->addAction(command);
m_commandLocator->appendCommand(command);
m_checkInCurrentAction = new Utils::ParameterAction(tr("Check &In..."), tr("Check &In \"%1\"..."), Utils::ParameterAction::AlwaysEnabled, this);
- command = Core::ActionManager::registerAction(m_checkInCurrentAction, CMD_ID_CHECKIN, globalcontext);
- command->setAttribute(Core::Command::CA_UpdateText);
- command->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+L,Meta+I") : tr("Alt+L,Alt+I")));
+ command = ActionManager::registerAction(m_checkInCurrentAction, CMD_ID_CHECKIN, globalcontext);
+ command->setAttribute(Command::CA_UpdateText);
+ command->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+L,Meta+I") : tr("Alt+L,Alt+I")));
connect(m_checkInCurrentAction, SIGNAL(triggered()), this, SLOT(startCheckInCurrentFile()));
clearcaseMenu->addAction(command);
m_commandLocator->appendCommand(command);
m_undoCheckOutAction = new Utils::ParameterAction(tr("Undo Check Out"), tr("&Undo Check Out \"%1\""), Utils::ParameterAction::AlwaysEnabled, this);
- command = Core::ActionManager::registerAction(m_undoCheckOutAction, CMD_ID_UNDOCHECKOUT, globalcontext);
- command->setAttribute(Core::Command::CA_UpdateText);
- command->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+L,Meta+U") : tr("Alt+L,Alt+U")));
+ command = ActionManager::registerAction(m_undoCheckOutAction, CMD_ID_UNDOCHECKOUT, globalcontext);
+ command->setAttribute(Command::CA_UpdateText);
+ command->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+L,Meta+U") : tr("Alt+L,Alt+U")));
connect(m_undoCheckOutAction, SIGNAL(triggered()), this, SLOT(undoCheckOutCurrent()));
clearcaseMenu->addAction(command);
m_commandLocator->appendCommand(command);
m_undoHijackAction = new Utils::ParameterAction(tr("Undo Hijack"), tr("Undo Hi&jack \"%1\""), Utils::ParameterAction::AlwaysEnabled, this);
- command = Core::ActionManager::registerAction(m_undoHijackAction, CMD_ID_UNDOHIJACK, globalcontext);
- command->setAttribute(Core::Command::CA_UpdateText);
- command->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+L,Meta+R") : tr("Alt+L,Alt+R")));
+ command = ActionManager::registerAction(m_undoHijackAction, CMD_ID_UNDOHIJACK, globalcontext);
+ command->setAttribute(Command::CA_UpdateText);
+ command->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+L,Meta+R") : tr("Alt+L,Alt+R")));
connect(m_undoHijackAction, SIGNAL(triggered()), this, SLOT(undoHijackCurrent()));
clearcaseMenu->addAction(command);
m_commandLocator->appendCommand(command);
@@ -443,100 +446,100 @@ bool ClearCasePlugin::initialize(const QStringList & /*arguments */, QString *er
clearcaseMenu->addSeparator(globalcontext);
m_diffCurrentAction = new Utils::ParameterAction(tr("Diff Current File"), tr("&Diff \"%1\""), Utils::ParameterAction::EnabledWithParameter, this);
- command = Core::ActionManager::registerAction(m_diffCurrentAction,
+ command = ActionManager::registerAction(m_diffCurrentAction,
CMD_ID_DIFF_CURRENT, globalcontext);
- command->setAttribute(Core::Command::CA_UpdateText);
- command->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+L,Meta+D") : tr("Alt+L,Alt+D")));
+ command->setAttribute(Command::CA_UpdateText);
+ command->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+L,Meta+D") : tr("Alt+L,Alt+D")));
connect(m_diffCurrentAction, SIGNAL(triggered()), this, SLOT(diffCurrentFile()));
clearcaseMenu->addAction(command);
m_commandLocator->appendCommand(command);
m_historyCurrentAction = new Utils::ParameterAction(tr("History Current File"), tr("&History \"%1\""), Utils::ParameterAction::EnabledWithParameter, this);
- command = Core::ActionManager::registerAction(m_historyCurrentAction,
+ command = ActionManager::registerAction(m_historyCurrentAction,
CMD_ID_HISTORY_CURRENT, globalcontext);
- command->setAttribute(Core::Command::CA_UpdateText);
- command->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+L,Meta+H") : tr("Alt+L,Alt+H")));
+ command->setAttribute(Command::CA_UpdateText);
+ command->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+L,Meta+H") : tr("Alt+L,Alt+H")));
connect(m_historyCurrentAction, SIGNAL(triggered()), this,
SLOT(historyCurrentFile()));
clearcaseMenu->addAction(command);
m_commandLocator->appendCommand(command);
m_annotateCurrentAction = new Utils::ParameterAction(tr("Annotate Current File"), tr("&Annotate \"%1\""), Utils::ParameterAction::EnabledWithParameter, this);
- command = Core::ActionManager::registerAction(m_annotateCurrentAction,
+ command = ActionManager::registerAction(m_annotateCurrentAction,
CMD_ID_ANNOTATE, globalcontext);
- command->setAttribute(Core::Command::CA_UpdateText);
- command->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+L,Meta+A") : tr("Alt+L,Alt+A")));
+ command->setAttribute(Command::CA_UpdateText);
+ command->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+L,Meta+A") : tr("Alt+L,Alt+A")));
connect(m_annotateCurrentAction, SIGNAL(triggered()), this,
SLOT(annotateCurrentFile()));
clearcaseMenu->addAction(command);
m_commandLocator->appendCommand(command);
m_addFileAction = new Utils::ParameterAction(tr("Add File..."), tr("Add File \"%1\""), Utils::ParameterAction::EnabledWithParameter, this);
- command = Core::ActionManager::registerAction(m_addFileAction, CMD_ID_ADD_FILE, globalcontext);
- command->setAttribute(Core::Command::CA_UpdateText);
+ command = ActionManager::registerAction(m_addFileAction, CMD_ID_ADD_FILE, globalcontext);
+ command->setAttribute(Command::CA_UpdateText);
connect(m_addFileAction, SIGNAL(triggered()), this, SLOT(addCurrentFile()));
clearcaseMenu->addAction(command);
clearcaseMenu->addSeparator(globalcontext);
m_diffActivityAction = new QAction(tr("Diff A&ctivity..."), this);
- command = Core::ActionManager::registerAction(m_diffActivityAction, CMD_ID_DIFF_ACTIVITY, globalcontext);
+ command = ActionManager::registerAction(m_diffActivityAction, CMD_ID_DIFF_ACTIVITY, globalcontext);
connect(m_diffActivityAction, SIGNAL(triggered()), this, SLOT(diffActivity()));
clearcaseMenu->addAction(command);
m_commandLocator->appendCommand(command);
m_checkInActivityAction = new Utils::ParameterAction(tr("Ch&eck In Activity"), tr("Chec&k In Activity \"%1\"..."), Utils::ParameterAction::EnabledWithParameter, this);
- command = Core::ActionManager::registerAction(m_checkInActivityAction, CMD_ID_CHECKIN_ACTIVITY, globalcontext);
+ command = ActionManager::registerAction(m_checkInActivityAction, CMD_ID_CHECKIN_ACTIVITY, globalcontext);
connect(m_checkInActivityAction, SIGNAL(triggered()), this, SLOT(startCheckInActivity()));
- command->setAttribute(Core::Command::CA_UpdateText);
+ command->setAttribute(Command::CA_UpdateText);
clearcaseMenu->addAction(command);
m_commandLocator->appendCommand(command);
clearcaseMenu->addSeparator(globalcontext);
m_updateIndexAction = new QAction(tr("Update Index"), this);
- command = Core::ActionManager::registerAction(m_updateIndexAction, CMD_ID_UPDATEINDEX, globalcontext);
+ command = ActionManager::registerAction(m_updateIndexAction, CMD_ID_UPDATEINDEX, globalcontext);
connect(m_updateIndexAction, SIGNAL(triggered()), this, SLOT(updateIndex()));
clearcaseMenu->addAction(command);
m_updateViewAction = new Utils::ParameterAction(tr("Update View"), tr("U&pdate View \"%1\""), Utils::ParameterAction::EnabledWithParameter, this);
- command = Core::ActionManager::registerAction(m_updateViewAction, CMD_ID_UPDATE_VIEW, globalcontext);
+ command = ActionManager::registerAction(m_updateViewAction, CMD_ID_UPDATE_VIEW, globalcontext);
connect(m_updateViewAction, SIGNAL(triggered()), this, SLOT(updateView()));
- command->setAttribute(Core::Command::CA_UpdateText);
+ command->setAttribute(Command::CA_UpdateText);
clearcaseMenu->addAction(command);
clearcaseMenu->addSeparator(globalcontext);
m_checkInAllAction = new QAction(tr("Check In All &Files..."), this);
- command = Core::ActionManager::registerAction(m_checkInAllAction, CMD_ID_CHECKIN_ALL, globalcontext);
- command->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+L,Meta+F") : tr("Alt+L,Alt+F")));
+ command = ActionManager::registerAction(m_checkInAllAction, CMD_ID_CHECKIN_ALL, globalcontext);
+ command->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+L,Meta+F") : tr("Alt+L,Alt+F")));
connect(m_checkInAllAction, SIGNAL(triggered()), this, SLOT(startCheckInAll()));
clearcaseMenu->addAction(command);
m_commandLocator->appendCommand(command);
m_statusAction = new QAction(tr("View &Status"), this);
- command = Core::ActionManager::registerAction(m_statusAction, CMD_ID_STATUS, globalcontext);
- command->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+L,Meta+S") : tr("Alt+L,Alt+S")));
+ command = ActionManager::registerAction(m_statusAction, CMD_ID_STATUS, globalcontext);
+ command->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+L,Meta+S") : tr("Alt+L,Alt+S")));
connect(m_statusAction, SIGNAL(triggered()), this, SLOT(viewStatus()));
clearcaseMenu->addAction(command);
m_commandLocator->appendCommand(command);
// Actions of the submit editor
- Core::Context clearcasecheckincontext(Constants::CLEARCASECHECKINEDITOR);
+ Context clearcasecheckincontext(Constants::CLEARCASECHECKINEDITOR);
m_checkInSelectedAction = new QAction(VcsBase::VcsBaseSubmitEditor::submitIcon(), tr("Check In"), this);
- command = Core::ActionManager::registerAction(m_checkInSelectedAction, Constants::CHECKIN_SELECTED, clearcasecheckincontext);
- command->setAttribute(Core::Command::CA_UpdateText);
+ command = ActionManager::registerAction(m_checkInSelectedAction, Constants::CHECKIN_SELECTED, clearcasecheckincontext);
+ command->setAttribute(Command::CA_UpdateText);
connect(m_checkInSelectedAction, SIGNAL(triggered()), this, SLOT(checkInSelected()));
m_checkInDiffAction = new QAction(VcsBase::VcsBaseSubmitEditor::diffIcon(), tr("Diff Selected Files"), this);
- command = Core::ActionManager::registerAction(m_checkInDiffAction , Constants::DIFF_SELECTED, clearcasecheckincontext);
+ command = ActionManager::registerAction(m_checkInDiffAction , Constants::DIFF_SELECTED, clearcasecheckincontext);
m_submitUndoAction = new QAction(tr("&Undo"), this);
- command = Core::ActionManager::registerAction(m_submitUndoAction, Core::Constants::UNDO, clearcasecheckincontext);
+ command = ActionManager::registerAction(m_submitUndoAction, Core::Constants::UNDO, clearcasecheckincontext);
m_submitRedoAction = new QAction(tr("&Redo"), this);
- command = Core::ActionManager::registerAction(m_submitRedoAction, Core::Constants::REDO, clearcasecheckincontext);
+ command = ActionManager::registerAction(m_submitRedoAction, Core::Constants::REDO, clearcasecheckincontext);
return true;
}
@@ -549,12 +552,12 @@ bool ClearCasePlugin::submitEditorAboutToClose()
ClearCaseSubmitEditor *editor = qobject_cast<ClearCaseSubmitEditor *>(submitEditor());
QTC_ASSERT(editor, return true);
- Core::IDocument *editorDocument = editor->document();
+ IDocument *editorDocument = editor->document();
QTC_ASSERT(editorDocument, return true);
// Submit editor closing. Make it write out the check in message
// and retrieve files
- const QFileInfo editorFile(editorDocument->fileName());
+ const QFileInfo editorFile(editorDocument->filePath());
const QFileInfo changeFile(m_checkInMessageFileName);
if (editorFile.absoluteFilePath() != changeFile.absoluteFilePath())
return true; // Oops?!
@@ -580,14 +583,14 @@ bool ClearCasePlugin::submitEditorAboutToClose()
// If user changed
if (prompt != m_settings.promptToCheckIn) {
m_settings.promptToCheckIn = prompt;
- m_settings.toSettings(Core::ICore::settings());
+ m_settings.toSettings(ICore::settings());
}
const QStringList fileList = editor->checkedFiles();
bool closeEditor = true;
if (!fileList.empty()) {
// get message & check in
- closeEditor = Core::DocumentManager::saveDocument(editorDocument);
+ closeEditor = DocumentManager::saveDocument(editorDocument);
if (closeEditor) {
ClearCaseSubmitEditorWidget *widget = editor->submitEditorWidget();
closeEditor = vcsCheckIn(m_checkInMessageFileName, fileList, widget->activity(),
@@ -609,7 +612,7 @@ void ClearCasePlugin::diffCheckInFiles(const QStringList &files)
ccDiffWithPred(m_checkInView, files);
}
-static inline void setDiffBaseDirectory(Core::IEditor *editor, const QString &db)
+static inline void setDiffBaseDirectory(IEditor *editor, const QString &db)
{
if (VcsBase::VcsBaseEditorWidget *ve = qobject_cast<VcsBase::VcsBaseEditorWidget*>(editor->widget()))
ve->setDiffBaseDirectory(db);
@@ -686,8 +689,8 @@ QString ClearCasePlugin::ccGetFileActivity(const QString &workingDir, const QStr
ClearCaseSubmitEditor *ClearCasePlugin::openClearCaseSubmitEditor(const QString &fileName, bool isUcm)
{
- Core::IEditor *editor =
- Core::EditorManager::openEditor(fileName, Constants::CLEARCASECHECKINEDITOR_ID);
+ IEditor *editor =
+ EditorManager::openEditor(fileName, Constants::CLEARCASECHECKINEDITOR_ID);
ClearCaseSubmitEditor *submitEditor = qobject_cast<ClearCaseSubmitEditor*>(editor);
QTC_CHECK(submitEditor);
submitEditor->registerActions(m_submitUndoAction, m_submitRedoAction, m_checkInSelectedAction, m_checkInDiffAction);
@@ -705,7 +708,7 @@ void ClearCasePlugin::updateStatusActions()
QString absoluteFileName = currentState().currentFile();
fileStatus = m_statusMap->value(absoluteFileName, FileStatus(FileStatus::Unknown));
- if (ClearCase::Constants::debug)
+ if (Constants::debug)
qDebug() << Q_FUNC_INFO << absoluteFileName << ", status = " << fileStatus.status;
}
@@ -799,10 +802,10 @@ void ClearCasePlugin::undoCheckOutCurrent()
bool ClearCasePlugin::vcsUndoCheckOut(const QString &workingDir, const QString &fileName, bool keep)
{
- if (ClearCase::Constants::debug)
+ if (Constants::debug)
qDebug() << Q_FUNC_INFO << workingDir << fileName << keep;
- Core::FileChangeBlocker fcb(fileName);
+ FileChangeBlocker fcb(fileName);
// revert
QStringList args(QLatin1String("uncheckout"));
@@ -831,7 +834,7 @@ bool ClearCasePlugin::vcsUndoCheckOut(const QString &workingDir, const QString &
*/
bool ClearCasePlugin::vcsUndoHijack(const QString &workingDir, const QString &fileName, bool keep)
{
- if (ClearCase::Constants::debug)
+ if (Constants::debug)
qDebug() << Q_FUNC_INFO << workingDir << fileName << keep;
QStringList args(QLatin1String("update"));
args << QLatin1String(keep ? "-rename" : "-overwrite");
@@ -877,7 +880,7 @@ void ClearCasePlugin::undoHijackCurrent()
keep = unhijackUi.chkKeep->isChecked();
}
- Core::FileChangeBlocker fcb(state.currentFile());
+ FileChangeBlocker fcb(state.currentFile());
// revert
if (vcsUndoHijack(state.currentFileTopLevel(), fileName, keep))
@@ -893,7 +896,7 @@ QString ClearCasePlugin::ccGetFileVersion(const QString &workingDir, const QStri
void ClearCasePlugin::ccDiffWithPred(const QString &workingDir, const QStringList &files)
{
- if (ClearCase::Constants::debug)
+ if (Constants::debug)
qDebug() << Q_FUNC_INFO << files;
const QString source = VcsBase::VcsBaseEditorWidget::getSource(workingDir, files);
QTextCodec *codec = source.isEmpty() ? static_cast<QTextCodec *>(0) : VcsBase::VcsBaseEditorWidget::getCodec(source);
@@ -928,16 +931,16 @@ void ClearCasePlugin::ccDiffWithPred(const QString &workingDir, const QStringLis
const QString tag = VcsBase::VcsBaseEditorWidget::editorTag(VcsBase::DiffOutput, workingDir, files);
if (files.count() == 1) {
// Show in the same editor if diff has been executed before
- if (Core::IEditor *existingEditor = VcsBase::VcsBaseEditorWidget::locateEditorByTag(tag)) {
- existingEditor->createNew(result);
- Core::EditorManager::activateEditor(existingEditor);
+ if (IEditor *existingEditor = VcsBase::VcsBaseEditorWidget::locateEditorByTag(tag)) {
+ existingEditor->document()->setContents(result.toUtf8());
+ EditorManager::activateEditor(existingEditor);
setDiffBaseDirectory(existingEditor, workingDir);
return;
}
diffname = QDir::toNativeSeparators(files.first());
}
const QString title = QString::fromLatin1("cc diff %1").arg(diffname);
- Core::IEditor *editor = showOutputInEditor(title, result, VcsBase::DiffOutput, source, codec);
+ IEditor *editor = showOutputInEditor(title, result, VcsBase::DiffOutput, source, codec);
setDiffBaseDirectory(editor, workingDir);
VcsBase::VcsBaseEditorWidget::tagEditor(editor, tag);
ClearCaseEditor *diffEditorWidget = qobject_cast<ClearCaseEditor *>(editor->widget());
@@ -978,7 +981,7 @@ void ClearCasePlugin::diffActivity()
const VcsBase::VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasTopLevel(), return);
- if (ClearCase::Constants::debug)
+ if (Constants::debug)
qDebug() << Q_FUNC_INFO;
if (!m_settings.extDiffAvailable) {
VcsBase::VcsBaseOutputWindow::instance()->appendError(
@@ -1033,7 +1036,7 @@ void ClearCasePlugin::diffActivity()
}
m_diffPrefix.clear();
const QString title = QString::fromLatin1("%1.patch").arg(activity);
- Core::IEditor *editor = showOutputInEditor(title, result, VcsBase::DiffOutput, activity, 0);
+ IEditor *editor = showOutputInEditor(title, result, VcsBase::DiffOutput, activity, 0);
setDiffBaseDirectory(editor, topLevel);
}
@@ -1188,13 +1191,13 @@ void ClearCasePlugin::history(const QString &workingDir,
const QString id = VcsBase::VcsBaseEditorWidget::getTitleId(workingDir, files);
const QString tag = VcsBase::VcsBaseEditorWidget::editorTag(VcsBase::LogOutput, workingDir, files);
- if (Core::IEditor *editor = VcsBase::VcsBaseEditorWidget::locateEditorByTag(tag)) {
- editor->createNew(response.stdOut);
- Core::EditorManager::activateEditor(editor);
+ if (IEditor *editor = VcsBase::VcsBaseEditorWidget::locateEditorByTag(tag)) {
+ editor->document()->setContents(response.stdOut.toUtf8());
+ EditorManager::activateEditor(editor);
} else {
const QString title = QString::fromLatin1("cc history %1").arg(id);
const QString source = VcsBase::VcsBaseEditorWidget::getSource(workingDir, files);
- Core::IEditor *newEditor = showOutputInEditor(title, response.stdOut, VcsBase::LogOutput, source, codec);
+ IEditor *newEditor = showOutputInEditor(title, response.stdOut, VcsBase::LogOutput, source, codec);
VcsBase::VcsBaseEditorWidget::tagEditor(newEditor, tag);
if (enableAnnotationContextMenu)
VcsBase::VcsBaseEditorWidget::getVcsBaseEditor(newEditor)->setFileLogAnnotateEnabled(true);
@@ -1262,7 +1265,7 @@ void ClearCasePlugin::vcsAnnotate(const QString &workingDir, const QString &file
const QString &revision /* = QString() */,
int lineNumber /* = -1 */) const
{
- if (ClearCase::Constants::debug)
+ if (Constants::debug)
qDebug() << Q_FUNC_INFO << file;
QTextCodec *codec = VcsBase::VcsBaseEditorWidget::getCodec(file);
@@ -1300,13 +1303,13 @@ void ClearCasePlugin::vcsAnnotate(const QString &workingDir, const QString &file
<< headerSep << QLatin1Char('\n') << response.stdOut.left(pos);
const QStringList files = QStringList(file);
const QString tag = VcsBase::VcsBaseEditorWidget::editorTag(VcsBase::AnnotateOutput, workingDir, files);
- if (Core::IEditor *editor = VcsBase::VcsBaseEditorWidget::locateEditorByTag(tag)) {
- editor->createNew(res);
+ if (IEditor *editor = VcsBase::VcsBaseEditorWidget::locateEditorByTag(tag)) {
+ editor->document()->setContents(res.toUtf8());
VcsBase::VcsBaseEditorWidget::gotoLineOfEditor(editor, lineNumber);
- Core::EditorManager::activateEditor(editor);
+ EditorManager::activateEditor(editor);
} else {
const QString title = QString::fromLatin1("cc annotate %1").arg(id);
- Core::IEditor *newEditor = showOutputInEditor(title, res, VcsBase::AnnotateOutput, source, codec);
+ IEditor *newEditor = showOutputInEditor(title, res, VcsBase::AnnotateOutput, source, codec);
VcsBase::VcsBaseEditorWidget::tagEditor(newEditor, tag);
VcsBase::VcsBaseEditorWidget::gotoLineOfEditor(newEditor, lineNumber);
}
@@ -1319,7 +1322,7 @@ void ClearCasePlugin::describe(const QString &source, const QString &changeNr)
const bool manages = managesDirectory(fi.isDir() ? source : fi.absolutePath(), &topLevel);
if (!manages || topLevel.isEmpty())
return;
- if (ClearCase::Constants::debug)
+ if (Constants::debug)
qDebug() << Q_FUNC_INFO << source << topLevel << changeNr;
QString description;
QString relPath = QDir::toNativeSeparators(QDir(topLevel).relativeFilePath(source));
@@ -1337,12 +1340,12 @@ void ClearCasePlugin::describe(const QString &source, const QString &changeNr)
// Re-use an existing view if possible to support
// the common usage pattern of continuously changing and diffing a file
const QString tag = VcsBase::VcsBaseEditorWidget::editorTag(VcsBase::DiffOutput, source, QStringList(), changeNr);
- if (Core::IEditor *editor = VcsBase::VcsBaseEditorWidget::locateEditorByTag(tag)) {
- editor->createNew(description);
- Core::EditorManager::activateEditor(editor);
+ if (IEditor *editor = VcsBase::VcsBaseEditorWidget::locateEditorByTag(tag)) {
+ editor->document()->setContents(description.toUtf8());
+ EditorManager::activateEditor(editor);
} else {
const QString title = QString::fromLatin1("cc describe %1").arg(id);
- Core::IEditor *newEditor = showOutputInEditor(title, description, VcsBase::DiffOutput, source, codec);
+ IEditor *newEditor = showOutputInEditor(title, description, VcsBase::DiffOutput, source, codec);
VcsBase::VcsBaseEditorWidget::tagEditor(newEditor, tag);
}
}
@@ -1350,7 +1353,7 @@ void ClearCasePlugin::describe(const QString &source, const QString &changeNr)
void ClearCasePlugin::checkInSelected()
{
m_submitActionTriggered = true;
- Core::EditorManager::instance()->closeEditor();
+ EditorManager::closeEditor();
}
QString ClearCasePlugin::runCleartoolSync(const QString &workingDir,
@@ -1376,7 +1379,8 @@ ClearCaseResponse
const Utils::SynchronousProcessResponse sp_resp =
VcsBase::VcsBasePlugin::runVcs(workingDir, executable,
- arguments, timeOut, flags, outputCodec);
+ arguments, timeOut,
+ flags, outputCodec);
response.error = sp_resp.result != Utils::SynchronousProcessResponse::Finished;
if (response.error)
@@ -1386,18 +1390,18 @@ ClearCaseResponse
return response;
}
-Core::IEditor *ClearCasePlugin::showOutputInEditor(const QString& title, const QString &output,
+IEditor *ClearCasePlugin::showOutputInEditor(const QString& title, const QString &output,
int editorType, const QString &source,
QTextCodec *codec) const
{
const VcsBase::VcsBaseEditorParameters *params = findType(editorType);
QTC_ASSERT(params, return 0);
- const Core::Id id = params->id;
- if (ClearCase::Constants::debug)
+ const Id id = params->id;
+ if (Constants::debug)
qDebug() << "ClearCasePlugin::showOutputInEditor" << title << id.name()
<< "Size= " << output.size() << " Type=" << editorType << debugCodec(codec);
QString s = title;
- Core::IEditor *editor = Core::EditorManager::openEditorWithContents(id, &s, output);
+ IEditor *editor = EditorManager::openEditorWithContents(id, &s, output.toUtf8());
connect(editor, SIGNAL(annotateRevisionRequested(QString,QString,int)),
this, SLOT(annotateVersion(QString,QString,int)));
ClearCaseEditor *e = qobject_cast<ClearCaseEditor*>(editor->widget());
@@ -1410,8 +1414,8 @@ Core::IEditor *ClearCasePlugin::showOutputInEditor(const QString& title, const Q
e->setSource(source);
if (codec)
e->setCodec(codec);
- Core::IEditor *ie = e->editor();
- Core::EditorManager::activateEditor(ie);
+ IEditor *ie = e->editor();
+ EditorManager::activateEditor(ie);
return ie;
}
@@ -1424,7 +1428,7 @@ void ClearCasePlugin::setSettings(const ClearCaseSettings &s)
{
if (s != m_settings) {
m_settings = s;
- m_settings.toSettings(Core::ICore::settings());
+ m_settings.toSettings(ICore::settings());
clearCaseControl()->emitConfigurationChanged();
}
}
@@ -1439,7 +1443,7 @@ bool ClearCasePlugin::vcsOpen(const QString &workingDir, const QString &fileName
{
QTC_ASSERT(currentState().hasTopLevel(), return false);
- if (ClearCase::Constants::debug)
+ if (Constants::debug)
qDebug() << Q_FUNC_INFO << workingDir << fileName;
QFileInfo fi(workingDir, fileName);
@@ -1466,7 +1470,7 @@ bool ClearCasePlugin::vcsOpen(const QString &workingDir, const QString &fileName
if (m_viewData.isUcm && !vcsSetActivity(topLevel, title, coDialog.activity()))
return false;
- Core::FileChangeBlocker fcb(absPath);
+ FileChangeBlocker fcb(absPath);
QStringList args(QLatin1String("checkout"));
QString comment = coDialog.comment();
if (comment.isEmpty())
@@ -1481,7 +1485,7 @@ bool ClearCasePlugin::vcsOpen(const QString &workingDir, const QString &fileName
if (coDialog.isPreserveTime())
args << QLatin1String("-ptime");
if (isHijacked) {
- if (ClearCase::Constants::debug)
+ if (Constants::debug)
qDebug() << Q_FUNC_INFO << file << " seems to be hijacked";
// A hijacked files means that the file is modified but was
@@ -1513,7 +1517,7 @@ bool ClearCasePlugin::vcsOpen(const QString &workingDir, const QString &fileName
} else {
VcsBase::VcsBaseOutputWindow *outputWindow = VcsBase::VcsBaseOutputWindow::instance();
outputWindow->append(response.stdOut);
- outputWindow->append(response.stdErr);
+ outputWindow->appendError(response.stdErr);
}
}
@@ -1549,12 +1553,12 @@ bool ClearCasePlugin::vcsSetActivity(const QString &workingDir, const QString &t
bool ClearCasePlugin::vcsCheckIn(const QString &messageFile, const QStringList &files, const QString &activity,
bool isIdentical, bool isPreserve, bool replaceActivity)
{
- if (ClearCase::Constants::debug)
+ if (Constants::debug)
qDebug() << Q_FUNC_INFO << messageFile << files << activity;
if (files.isEmpty())
return true;
const QString title = QString::fromLatin1("Checkin %1").arg(files.join(QLatin1String("; ")));
- typedef QSharedPointer<Core::FileChangeBlocker> FCBPointer;
+ typedef QSharedPointer<FileChangeBlocker> FCBPointer;
replaceActivity &= (activity != QLatin1String(Constants::KEEP_ACTIVITY));
if (replaceActivity && !vcsSetActivity(m_checkInView, title, activity))
return false;
@@ -1575,7 +1579,7 @@ bool ClearCasePlugin::vcsCheckIn(const QString &messageFile, const QStringList &
args << files;
QList<FCBPointer> blockers;
foreach (const QString &fileName, files) {
- FCBPointer fcb(new Core::FileChangeBlocker(QFileInfo(m_checkInView, fileName).canonicalFilePath()));
+ FCBPointer fcb(new FileChangeBlocker(QFileInfo(m_checkInView, fileName).canonicalFilePath()));
blockers.append(fcb);
}
const ClearCaseResponse response =
@@ -1879,51 +1883,50 @@ void ClearCasePlugin::updateStreamAndView()
m_updateViewAction->setParameter(m_viewData.isDynamic ? QString() : m_viewData.name);
}
-void ClearCasePlugin::projectChanged(ProjectExplorer::Project *project)
+void ClearCasePlugin::projectChanged(Project *project)
{
if (m_viewData.name == ccGetView(m_topLevel).name) // New project on same view as old project
return;
m_viewData = ViewData();
m_stream.clear();
m_intStream.clear();
- disconnect(Core::ICore::mainWindow(), SIGNAL(windowActivated()), this, SLOT(syncSlot()));
- Core::ICore::progressManager()->cancelTasks(QLatin1String(ClearCase::Constants::TASK_INDEX));
+ disconnect(ICore::mainWindow(), SIGNAL(windowActivated()), this, SLOT(syncSlot()));
+ ProgressManager::cancelTasks(ClearCase::Constants::TASK_INDEX);
if (project) {
QString projDir = project->projectDirectory();
QString topLevel = findTopLevel(projDir);
m_topLevel = topLevel;
if (topLevel.isEmpty())
return;
- connect(Core::ICore::mainWindow(), SIGNAL(windowActivated()), this, SLOT(syncSlot()));
+ connect(ICore::mainWindow(), SIGNAL(windowActivated()), this, SLOT(syncSlot()));
updateStreamAndView();
if (m_viewData.name.isEmpty())
return;
updateIndex();
}
- if ( ClearCase::Constants::debug )
+ if (Constants::debug)
qDebug() << "stream: " << m_stream << "; intStream: " << m_intStream << "view: " << m_viewData.name;
}
-void ClearCasePlugin::tasksFinished(const QString &type)
+void ClearCasePlugin::tasksFinished(Core::Id type)
{
- if (type == QLatin1String(ClearCase::Constants::TASK_INDEX))
+ if (type == ClearCase::Constants::TASK_INDEX)
m_checkInAllAction->setEnabled(true);
}
void ClearCasePlugin::updateIndex()
{
QTC_ASSERT(currentState().hasTopLevel(), return);
- Core::ICore::progressManager()->cancelTasks(QLatin1String(ClearCase::Constants::TASK_INDEX));
- ProjectExplorer::Project *project = ProjectExplorer::ProjectExplorerPlugin::currentProject();
+ ProgressManager::cancelTasks(ClearCase::Constants::TASK_INDEX);
+ Project *project = ProjectExplorerPlugin::currentProject();
if (!project)
return;
m_checkInAllAction->setEnabled(false);
m_statusMap->clear();
QFuture<void> result = QtConcurrent::run(&sync,
- project->files(ProjectExplorer::Project::ExcludeGeneratedFiles));
+ project->files(Project::ExcludeGeneratedFiles));
if (!m_settings.disableIndexer)
- Core::ICore::progressManager()->addTask(result, tr("CC Indexing"),
- QLatin1String(ClearCase::Constants::TASK_INDEX));
+ ProgressManager::addTask(result, tr("CC Indexing"), ClearCase::Constants::TASK_INDEX);
}
/*! retrieve a \a file (usually of the form path\to\filename.cpp@@\main\ver)
@@ -1947,7 +1950,7 @@ QString ClearCasePlugin::getFile(const QString &nativeFile, const QString &prefi
tempDir.mkpath(file.left(slash));
tempFile = tempDir.absoluteFilePath(file);
}
- if (ClearCase::Constants::debug)
+ if (Constants::debug)
qDebug() << Q_FUNC_INFO << nativeFile;
if ((atatpos != -1) && (nativeFile.indexOf(QLatin1String("CHECKEDOUT"), atatpos) != -1)) {
bool res = QFile::copy(QDir(m_topLevel).absoluteFilePath(file), tempFile);
@@ -2065,8 +2068,8 @@ void ClearCasePlugin::syncSlot()
void ClearCasePlugin::closing()
{
// prevent syncSlot from being called on shutdown
- Core::ICore::progressManager()->cancelTasks(QLatin1String(ClearCase::Constants::TASK_INDEX));
- disconnect(Core::ICore::mainWindow(), SIGNAL(windowActivated()), this, SLOT(syncSlot()));
+ ProgressManager::cancelTasks(ClearCase::Constants::TASK_INDEX);
+ disconnect(ICore::mainWindow(), SIGNAL(windowActivated()), this, SLOT(syncSlot()));
}
void ClearCasePlugin::sync(QFutureInterface<void> &future, QStringList files)
diff --git a/src/plugins/clearcase/clearcaseplugin.h b/src/plugins/clearcase/clearcaseplugin.h
index 6ce6674af3..fb011182da 100644
--- a/src/plugins/clearcase/clearcaseplugin.h
+++ b/src/plugins/clearcase/clearcaseplugin.h
@@ -33,7 +33,9 @@
#include "clearcasesettings.h"
+#include <coreplugin/id.h>
#include <vcsbase/vcsbaseplugin.h>
+
#include <QFile>
#include <QPair>
#include <QStringList>
@@ -191,7 +193,7 @@ private slots:
void updateIndex();
void updateView();
void projectChanged(ProjectExplorer::Project *project);
- void tasksFinished(const QString &type);
+ void tasksFinished(Core::Id type);
void syncSlot();
void closing();
void updateStatusActions();
diff --git a/src/plugins/clearcase/clearcasesettings.cpp b/src/plugins/clearcase/clearcasesettings.cpp
index bafaa02f5b..019b733723 100644
--- a/src/plugins/clearcase/clearcasesettings.cpp
+++ b/src/plugins/clearcase/clearcasesettings.cpp
@@ -42,7 +42,6 @@ static const char historyCountKeyC[] = "HistoryCount";
static const char timeOutKeyC[] = "TimeOut";
static const char autoCheckOutKeyC[] = "AutoCheckOut";
static const char diffTypeKeyC[] = "DiffType";
-static const char extDiffCommandKeyC[] = "ExternalDiffCommand";
static const char diffArgsKeyC[] = "DiffArgs";
static const char autoAssignActivityKeyC[] = "AutoAssignActivityName";
static const char promptToCheckInKeyC[] = "PromptToCheckIn";
diff --git a/src/plugins/clearcase/clearcasesubmiteditor.cpp b/src/plugins/clearcase/clearcasesubmiteditor.cpp
index ac24ec80b0..3d886a1b48 100644
--- a/src/plugins/clearcase/clearcasesubmiteditor.cpp
+++ b/src/plugins/clearcase/clearcasesubmiteditor.cpp
@@ -31,6 +31,7 @@
#include "clearcasesubmiteditor.h"
#include "clearcasesubmiteditorwidget.h"
+#include <coreplugin/idocument.h>
#include <vcsbase/submiteditorwidget.h>
#include <vcsbase/submitfilemodel.h>
@@ -40,7 +41,7 @@ ClearCaseSubmitEditor::ClearCaseSubmitEditor(const VcsBase::VcsBaseSubmitEditorP
QWidget *parentWidget) :
VcsBase::VcsBaseSubmitEditor(parameters, new ClearCaseSubmitEditorWidget(parentWidget))
{
- setDisplayName(tr("ClearCase Check In"));
+ document()->setDisplayName(tr("ClearCase Check In"));
}
ClearCaseSubmitEditorWidget *ClearCaseSubmitEditor::submitEditorWidget()
diff --git a/src/plugins/cmakeprojectmanager/CMakeProjectManager.pluginspec.in b/src/plugins/cmakeprojectmanager/CMakeProjectManager.pluginspec.in
index e51e6eebdb..6388460f83 100644
--- a/src/plugins/cmakeprojectmanager/CMakeProjectManager.pluginspec.in
+++ b/src/plugins/cmakeprojectmanager/CMakeProjectManager.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"CMakeProjectManager\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"CMakeProjectManager\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/cmakeprojectmanager/cmakebuildconfiguration.cpp b/src/plugins/cmakeprojectmanager/cmakebuildconfiguration.cpp
index 77e03a45be..9d7179dc6c 100644
--- a/src/plugins/cmakeprojectmanager/cmakebuildconfiguration.cpp
+++ b/src/plugins/cmakeprojectmanager/cmakebuildconfiguration.cpp
@@ -29,22 +29,26 @@
#include "cmakebuildconfiguration.h"
+#include "cmakebuildinfo.h"
#include "cmakeopenprojectwizard.h"
#include "cmakeproject.h"
#include "cmakeprojectconstants.h"
+#include <coreplugin/icore.h>
+#include <coreplugin/mimedatabase.h>
#include <projectexplorer/buildsteplist.h>
#include <projectexplorer/kit.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/target.h>
+#include <utils/qtcassert.h>
+
#include <QInputDialog>
using namespace CMakeProjectManager;
using namespace Internal;
namespace {
-const char BUILD_DIRECTORY_KEY[] = "CMakeProjectManager.CMakeBuildConfiguration.BuildDirectory";
const char USE_NINJA_KEY[] = "CMakeProjectManager.CMakeBuildConfiguration.UseNinja";
} // namespace
@@ -52,15 +56,14 @@ CMakeBuildConfiguration::CMakeBuildConfiguration(ProjectExplorer::Target *parent
BuildConfiguration(parent, Core::Id(Constants::CMAKE_BC_ID)), m_useNinja(false)
{
CMakeProject *project = static_cast<CMakeProject *>(parent->project());
- m_buildDirectory = project->shadowBuildDirectory(project->document()->fileName(),
- parent->kit(),
- displayName());
+ setBuildDirectory(Utils::FileName::fromString(project->shadowBuildDirectory(project->projectFilePath(),
+ parent->kit(),
+ displayName())));
}
CMakeBuildConfiguration::CMakeBuildConfiguration(ProjectExplorer::Target *parent,
CMakeBuildConfiguration *source) :
BuildConfiguration(parent, source),
- m_buildDirectory(source->m_buildDirectory),
m_msvcVersion(source->m_msvcVersion),
m_useNinja(false)
{
@@ -71,7 +74,6 @@ CMakeBuildConfiguration::CMakeBuildConfiguration(ProjectExplorer::Target *parent
QVariantMap CMakeBuildConfiguration::toMap() const
{
QVariantMap map(ProjectExplorer::BuildConfiguration::toMap());
- map.insert(QLatin1String(BUILD_DIRECTORY_KEY), m_buildDirectory);
map.insert(QLatin1String(USE_NINJA_KEY), m_useNinja);
return map;
}
@@ -81,7 +83,6 @@ bool CMakeBuildConfiguration::fromMap(const QVariantMap &map)
if (!BuildConfiguration::fromMap(map))
return false;
- m_buildDirectory = map.value(QLatin1String(BUILD_DIRECTORY_KEY)).toString();
m_useNinja = map.value(QLatin1String(USE_NINJA_KEY), false).toBool();
return true;
@@ -108,20 +109,6 @@ ProjectExplorer::NamedWidget *CMakeBuildConfiguration::createConfigWidget()
return new CMakeBuildSettingsWidget(this);
}
-QString CMakeBuildConfiguration::buildDirectory() const
-{
- return m_buildDirectory;
-}
-
-void CMakeBuildConfiguration::setBuildDirectory(const QString &buildDirectory)
-{
- if (m_buildDirectory == buildDirectory)
- return;
- m_buildDirectory = buildDirectory;
- emit buildDirectoryChanged();
- emit environmentChanged();
-}
-
/*!
\class CMakeBuildConfigurationFactory
*/
@@ -135,64 +122,68 @@ CMakeBuildConfigurationFactory::~CMakeBuildConfigurationFactory()
{
}
-QList<Core::Id> CMakeBuildConfigurationFactory::availableCreationIds(const ProjectExplorer::Target *parent) const
+bool CMakeBuildConfigurationFactory::canCreate(const ProjectExplorer::Target *parent) const
{
- if (!canHandle(parent))
- return QList<Core::Id>();
- return QList<Core::Id>() << Core::Id(Constants::CMAKE_BC_ID);
+ return canHandle(parent);
}
-QString CMakeBuildConfigurationFactory::displayNameForId(const Core::Id id) const
+QList<ProjectExplorer::BuildInfo *> CMakeBuildConfigurationFactory::availableBuilds(const ProjectExplorer::Target *parent) const
{
- if (id == Constants::CMAKE_BC_ID)
- return tr("Build");
- return QString();
+ QList<ProjectExplorer::BuildInfo *> result;
+ QTC_ASSERT(canCreate(parent), return result);
+
+ CMakeBuildInfo *info = createBuildInfo(parent->kit(),
+ parent->project()->projectDirectory());
+ result << info;
+ return result;
}
-bool CMakeBuildConfigurationFactory::canCreate(const ProjectExplorer::Target *parent, const Core::Id id) const
+bool CMakeBuildConfigurationFactory::canSetup(const ProjectExplorer::Kit *k, const QString &projectPath) const
{
- if (!canHandle(parent))
- return false;
- if (id == Constants::CMAKE_BC_ID)
- return true;
- return false;
+ return k && Core::MimeDatabase::findByFile(QFileInfo(projectPath))
+ .matchesType(QLatin1String(Constants::CMAKEMIMETYPE));
}
-CMakeBuildConfiguration *CMakeBuildConfigurationFactory::create(ProjectExplorer::Target *parent, const Core::Id id, const QString &name)
+QList<ProjectExplorer::BuildInfo *> CMakeBuildConfigurationFactory::availableSetups(const ProjectExplorer::Kit *k,
+ const QString &projectPath) const
{
- if (!canCreate(parent, id))
- return 0;
+ QList<ProjectExplorer::BuildInfo *> result;
+ QTC_ASSERT(canSetup(k, projectPath), return result);
+
+ CMakeBuildInfo *info = createBuildInfo(k, ProjectExplorer::Project::projectDirectory(projectPath));
+ //: The name of the build configuration created by default for a cmake project.
+ info->displayName = tr("Default");
+ info->buildDirectory
+ = Utils::FileName::fromString(CMakeProject::shadowBuildDirectory(projectPath, k,
+ info->displayName));
+ result << info;
+ return result;
+}
+
+ProjectExplorer::BuildConfiguration *CMakeBuildConfigurationFactory::create(ProjectExplorer::Target *parent,
+ const ProjectExplorer::BuildInfo *info) const
+{
+ QTC_ASSERT(canCreate(parent), return 0);
+ QTC_ASSERT(info->factory() == this, return 0);
+ QTC_ASSERT(info->kitId == parent->kit()->id(), return 0);
+ QTC_ASSERT(!info->displayName.isEmpty(), return 0);
+ CMakeBuildInfo copy(*static_cast<const CMakeBuildInfo *>(info));
CMakeProject *project = static_cast<CMakeProject *>(parent->project());
- bool ok = true;
- QString buildConfigurationName = name;
- if (buildConfigurationName.isNull())
- buildConfigurationName = QInputDialog::getText(0,
- tr("New Configuration"),
- tr("New configuration name:"),
- QLineEdit::Normal,
- QString(), &ok);
- buildConfigurationName = buildConfigurationName.trimmed();
- if (!ok || buildConfigurationName.isEmpty())
- return 0;
+ if (copy.buildDirectory.isEmpty())
+ copy.buildDirectory
+ = Utils::FileName::fromString(project->shadowBuildDirectory(project->projectFilePath(),
+ parent->kit(),
+ copy.displayName));
- CMakeOpenProjectWizard::BuildInfo info;
- info.sourceDirectory = project->projectDirectory();
- info.environment = Utils::Environment::systemEnvironment();
- parent->kit()->addToEnvironment(info.environment);
- info.buildDirectory = project->shadowBuildDirectory(project->document()->fileName(),
- parent->kit(),
- buildConfigurationName);
- info.kit = parent->kit();
- info.useNinja = false; // This is ignored anyway
-
- CMakeOpenProjectWizard copw(project->projectManager(), CMakeOpenProjectWizard::ChangeDirectory, info);
+ CMakeOpenProjectWizard copw(project->projectManager(), CMakeOpenProjectWizard::ChangeDirectory, &copy);
if (copw.exec() != QDialog::Accepted)
return 0;
CMakeBuildConfiguration *bc = new CMakeBuildConfiguration(parent);
- bc->setDisplayName(buildConfigurationName);
+ bc->setDisplayName(copy.displayName);
+ bc->setDefaultDisplayName(copy.displayName);
ProjectExplorer::BuildStepList *buildSteps = bc->stepList(ProjectExplorer::Constants::BUILDSTEPS_BUILD);
ProjectExplorer::BuildStepList *cleanSteps = bc->stepList(ProjectExplorer::Constants::BUILDSTEPS_CLEAN);
@@ -205,7 +196,7 @@ CMakeBuildConfiguration *CMakeBuildConfigurationFactory::create(ProjectExplorer:
cleanMakeStep->setAdditionalArguments(QLatin1String("clean"));
cleanMakeStep->setClean(true);
- bc->setBuildDirectory(copw.buildDirectory());
+ bc->setBuildDirectory(Utils::FileName::fromString(copw.buildDirectory()));
bc->setUseNinja(copw.useNinja());
// Default to all
@@ -217,7 +208,9 @@ CMakeBuildConfiguration *CMakeBuildConfigurationFactory::create(ProjectExplorer:
bool CMakeBuildConfigurationFactory::canClone(const ProjectExplorer::Target *parent, ProjectExplorer::BuildConfiguration *source) const
{
- return canCreate(parent, source->id());
+ if (!canHandle(parent))
+ return false;
+ return source->id() == Constants::CMAKE_BC_ID;
}
CMakeBuildConfiguration *CMakeBuildConfigurationFactory::clone(ProjectExplorer::Target *parent, ProjectExplorer::BuildConfiguration *source)
@@ -230,7 +223,9 @@ CMakeBuildConfiguration *CMakeBuildConfigurationFactory::clone(ProjectExplorer::
bool CMakeBuildConfigurationFactory::canRestore(const ProjectExplorer::Target *parent, const QVariantMap &map) const
{
- return canCreate(parent, ProjectExplorer::idFromMap(map));
+ if (!canHandle(parent))
+ return false;
+ return ProjectExplorer::idFromMap(map) == Constants::CMAKE_BC_ID;
}
CMakeBuildConfiguration *CMakeBuildConfigurationFactory::restore(ProjectExplorer::Target *parent, const QVariantMap &map)
@@ -246,15 +241,31 @@ CMakeBuildConfiguration *CMakeBuildConfigurationFactory::restore(ProjectExplorer
bool CMakeBuildConfigurationFactory::canHandle(const ProjectExplorer::Target *t) const
{
+ QTC_ASSERT(t, return false);
if (!t->project()->supportsKit(t->kit()))
return false;
return qobject_cast<CMakeProject *>(t->project());
}
+CMakeBuildInfo *CMakeBuildConfigurationFactory::createBuildInfo(const ProjectExplorer::Kit *k,
+ const QString &sourceDir) const
+{
+ CMakeBuildInfo *info = new CMakeBuildInfo(this);
+ info->typeName = tr("Build");
+ info->kitId = k->id();
+ info->environment = Utils::Environment::systemEnvironment();
+ k->addToEnvironment(info->environment);
+ info->useNinja = false;
+ info->sourceDirectory = sourceDir;
+ info->supportsShadowBuild = true;
+
+ return info;
+}
+
ProjectExplorer::BuildConfiguration::BuildType CMakeBuildConfiguration::buildType() const
{
QString cmakeBuildType;
- QFile cmakeCache(buildDirectory() + QLatin1String("/CMakeCache.txt"));
+ QFile cmakeCache(buildDirectory().toString() + QLatin1String("/CMakeCache.txt"));
if (cmakeCache.open(QIODevice::ReadOnly)) {
while (!cmakeCache.atEnd()) {
QByteArray line = cmakeCache.readLine();
diff --git a/src/plugins/cmakeprojectmanager/cmakebuildconfiguration.h b/src/plugins/cmakeprojectmanager/cmakebuildconfiguration.h
index 494c28ea2c..de7ab612d3 100644
--- a/src/plugins/cmakeprojectmanager/cmakebuildconfiguration.h
+++ b/src/plugins/cmakeprojectmanager/cmakebuildconfiguration.h
@@ -38,7 +38,10 @@ class ToolChain;
}
namespace CMakeProjectManager {
+class CMakeBuildInfo;
+
namespace Internal {
+class CMakeProject;
class CMakeBuildConfigurationFactory;
@@ -52,9 +55,6 @@ public:
~CMakeBuildConfiguration();
ProjectExplorer::NamedWidget *createConfigWidget();
- QString buildDirectory() const;
-
- void setBuildDirectory(const QString &buildDirectory);
QVariantMap toMap() const;
@@ -71,9 +71,10 @@ protected:
bool fromMap(const QVariantMap &map);
private:
- QString m_buildDirectory;
QString m_msvcVersion;
bool m_useNinja;
+
+ friend class CMakeProject;
};
class CMakeBuildConfigurationFactory : public ProjectExplorer::IBuildConfigurationFactory
@@ -84,11 +85,14 @@ public:
CMakeBuildConfigurationFactory(QObject *parent = 0);
~CMakeBuildConfigurationFactory();
- QList<Core::Id> availableCreationIds(const ProjectExplorer::Target *parent) const;
- QString displayNameForId(const Core::Id id) const;
+ bool canCreate(const ProjectExplorer::Target *parent) const;
+ QList<ProjectExplorer::BuildInfo *> availableBuilds(const ProjectExplorer::Target *parent) const;
+ bool canSetup(const ProjectExplorer::Kit *k, const QString &projectPath) const;
+ QList<ProjectExplorer::BuildInfo *> availableSetups(const ProjectExplorer::Kit *k,
+ const QString &projectPath) const;
+ ProjectExplorer::BuildConfiguration *create(ProjectExplorer::Target *parent,
+ const ProjectExplorer::BuildInfo *info) const;
- bool canCreate(const ProjectExplorer::Target *parent, const Core::Id id) const;
- CMakeBuildConfiguration *create(ProjectExplorer::Target *parent, const Core::Id id, const QString &name = QString());
bool canClone(const ProjectExplorer::Target *parent, ProjectExplorer::BuildConfiguration *source) const;
CMakeBuildConfiguration *clone(ProjectExplorer::Target *parent, ProjectExplorer::BuildConfiguration *source);
bool canRestore(const ProjectExplorer::Target *parent, const QVariantMap &map) const;
@@ -96,6 +100,7 @@ public:
private:
bool canHandle(const ProjectExplorer::Target *t) const;
+ CMakeBuildInfo *createBuildInfo(const ProjectExplorer::Kit *k, const QString &sourceDir) const;
};
} // namespace Internal
diff --git a/src/plugins/cmakeprojectmanager/cmakebuildinfo.h b/src/plugins/cmakeprojectmanager/cmakebuildinfo.h
new file mode 100644
index 0000000000..b352f95de9
--- /dev/null
+++ b/src/plugins/cmakeprojectmanager/cmakebuildinfo.h
@@ -0,0 +1,65 @@
+/****************************************************************************
+**
+** 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 CMAKEBUILDINFO_H
+#define CMAKEBUILDINFO_H
+
+#include "cmakebuildconfiguration.h"
+
+#include <projectexplorer/buildinfo.h>
+#include <projectexplorer/kit.h>
+#include <projectexplorer/target.h>
+#include <utils/environment.h>
+
+namespace CMakeProjectManager {
+
+class CMakeBuildInfo : public ProjectExplorer::BuildInfo
+{
+public:
+ CMakeBuildInfo(const ProjectExplorer::IBuildConfigurationFactory *f) :
+ ProjectExplorer::BuildInfo(f) { }
+
+ CMakeBuildInfo(const Internal::CMakeBuildConfiguration *bc) :
+ ProjectExplorer::BuildInfo(ProjectExplorer::IBuildConfigurationFactory::find(bc->target()))
+ {
+ displayName = bc->displayName();
+ buildDirectory = bc->buildDirectory();
+ kitId = bc->target()->kit()->id();
+ environment = bc->environment();
+ useNinja = bc->useNinja();
+ }
+
+ Utils::Environment environment;
+ QString sourceDirectory;
+ bool useNinja;
+};
+
+} // namespace CMakeProjectManager
+
+#endif // CMAKEBUILDINFO_H
diff --git a/src/plugins/cmakeprojectmanager/cmakeeditor.cpp b/src/plugins/cmakeprojectmanager/cmakeeditor.cpp
index f91450d541..f21f256a06 100644
--- a/src/plugins/cmakeprojectmanager/cmakeeditor.cpp
+++ b/src/plugins/cmakeprojectmanager/cmakeeditor.cpp
@@ -29,6 +29,7 @@
#include "cmakeeditor.h"
+#include "cmakefilecompletionassist.h"
#include "cmakehighlighter.h"
#include "cmakeeditorfactory.h"
#include "cmakeprojectconstants.h"
@@ -38,15 +39,16 @@
#include <coreplugin/infobar.h>
#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/actionmanager/actionmanager.h>
+#include <extensionsystem/pluginmanager.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/session.h>
-#include <texteditor/fontsettings.h>
#include <texteditor/texteditoractionhandler.h>
#include <texteditor/texteditorconstants.h>
#include <texteditor/texteditorsettings.h>
#include <QFileInfo>
#include <QSharedPointer>
+#include <QTextBlock>
using namespace CMakeProjectManager;
using namespace CMakeProjectManager::Internal;
@@ -60,7 +62,7 @@ CMakeEditor::CMakeEditor(CMakeEditorWidget *editor)
{
setContext(Core::Context(CMakeProjectManager::Constants::C_CMAKEEDITOR,
TextEditor::Constants::C_TEXTEDITOR));
- connect(this, SIGNAL(changed()), this, SLOT(markAsChanged()));
+ connect(document(), SIGNAL(changed()), this, SLOT(markAsChanged()));
}
Core::IEditor *CMakeEditor::duplicate(QWidget *parent)
@@ -68,7 +70,7 @@ Core::IEditor *CMakeEditor::duplicate(QWidget *parent)
CMakeEditorWidget *w = qobject_cast<CMakeEditorWidget*>(widget());
CMakeEditorWidget *ret = new CMakeEditorWidget(parent, w->factory(), w->actionHandler());
ret->duplicateFrom(w);
- TextEditor::TextEditorSettings::instance()->initializeEditor(ret);
+ TextEditor::TextEditorSettings::initializeEditor(ret);
return ret->editor();
}
@@ -77,6 +79,11 @@ Core::Id CMakeEditor::id() const
return Core::Id(CMakeProjectManager::Constants::CMAKE_EDITOR_ID);
}
+TextEditor::CompletionAssistProvider *CMakeEditor::completionAssistProvider()
+{
+ return ExtensionSystem::PluginManager::getObject<CMakeFileCompletionAssistProvider>();
+}
+
void CMakeEditor::markAsChanged()
{
if (!document()->isModified())
@@ -94,12 +101,10 @@ void CMakeEditor::markAsChanged()
void CMakeEditor::build()
{
- QList<ProjectExplorer::Project *> projects =
- ProjectExplorer::ProjectExplorerPlugin::instance()->session()->projects();
- foreach (ProjectExplorer::Project *p, projects) {
+ foreach (ProjectExplorer::Project *p, ProjectExplorer::SessionManager::projects()) {
CMakeProject *cmakeProject = qobject_cast<CMakeProject *>(p);
if (cmakeProject) {
- if (cmakeProject->isProjectFile(document()->fileName())) {
+ if (cmakeProject->isProjectFile(document()->filePath())) {
ProjectExplorer::ProjectExplorerPlugin::instance()->buildProject(cmakeProject);
break;
}
@@ -141,27 +146,6 @@ void CMakeEditorWidget::contextMenuEvent(QContextMenuEvent *e)
showDefaultContextMenu(e, Constants::M_CONTEXT);
}
-void CMakeEditorWidget::setFontSettings(const TextEditor::FontSettings &fs)
-{
- TextEditor::BaseTextEditorWidget::setFontSettings(fs);
- CMakeHighlighter *highlighter = qobject_cast<CMakeHighlighter*>(baseTextDocument()->syntaxHighlighter());
- if (!highlighter)
- return;
-
- static QVector<TextEditor::TextStyle> categories;
- if (categories.isEmpty()) {
- categories << TextEditor::C_LABEL // variables
- << TextEditor::C_KEYWORD // functions
- << TextEditor::C_COMMENT
- << TextEditor::C_STRING
- << TextEditor::C_VISUAL_WHITESPACE;
- }
-
- const QVector<QTextCharFormat> formats = fs.toTextCharFormats(categories);
- highlighter->setFormats(formats.constBegin(), formats.constEnd());
- highlighter->rehighlight();
-}
-
static bool isValidFileNameChar(const QChar &c)
{
if (c.isLetterOrNumber()
@@ -219,7 +203,7 @@ CMakeEditorWidget::Link CMakeEditorWidget::findLinkAt(const QTextCursor &cursor,
// TODO: Resolve variables
- QDir dir(QFileInfo(editorDocument()->fileName()).absolutePath());
+ QDir dir(QFileInfo(editorDocument()->filePath()).absolutePath());
QString fileName = dir.filePath(buffer);
QFileInfo fi(fileName);
if (fi.exists()) {
@@ -250,12 +234,12 @@ CMakeDocument::CMakeDocument()
QString CMakeDocument::defaultPath() const
{
- QFileInfo fi(fileName());
+ QFileInfo fi(filePath());
return fi.absolutePath();
}
QString CMakeDocument::suggestedFileName() const
{
- QFileInfo fi(fileName());
+ QFileInfo fi(filePath());
return fi.fileName();
}
diff --git a/src/plugins/cmakeprojectmanager/cmakeeditor.h b/src/plugins/cmakeprojectmanager/cmakeeditor.h
index 3a27b9b1cd..c35eebb26d 100644
--- a/src/plugins/cmakeprojectmanager/cmakeeditor.h
+++ b/src/plugins/cmakeprojectmanager/cmakeeditor.h
@@ -34,6 +34,7 @@
#include <texteditor/basetextdocument.h>
#include <texteditor/basetexteditor.h>
+#include <texteditor/codeassist/completionassistprovider.h>
#include <utils/uncommentselection.h>
@@ -58,7 +59,7 @@ public:
bool duplicateSupported() const { return true; }
Core::IEditor *duplicate(QWidget *parent);
Core::Id id() const;
- bool isTemporary() const { return false; }
+ TextEditor::CompletionAssistProvider *completionAssistProvider();
private slots:
void markAsChanged();
@@ -86,7 +87,6 @@ protected:
public slots:
void unCommentSelection();
- void setFontSettings(const TextEditor::FontSettings &);
private:
CMakeEditorFactory *m_factory;
diff --git a/src/plugins/cmakeprojectmanager/cmakeeditorfactory.cpp b/src/plugins/cmakeprojectmanager/cmakeeditorfactory.cpp
index 8bebdfaade..7b7b32ae5a 100644
--- a/src/plugins/cmakeprojectmanager/cmakeeditorfactory.cpp
+++ b/src/plugins/cmakeprojectmanager/cmakeeditorfactory.cpp
@@ -43,12 +43,15 @@ using namespace CMakeProjectManager;
using namespace CMakeProjectManager::Internal;
CMakeEditorFactory::CMakeEditorFactory(CMakeManager *manager)
- : m_mimeTypes(QStringList() << QLatin1String(CMakeProjectManager::Constants::CMAKEMIMETYPE)),
- m_manager(manager)
+ : m_manager(manager)
{
using namespace Core;
using namespace TextEditor;
+ setId(CMakeProjectManager::Constants::CMAKE_EDITOR_ID);
+ setDisplayName(tr(CMakeProjectManager::Constants::CMAKE_EDITOR_DISPLAY_NAME));
+ addMimeType(CMakeProjectManager::Constants::CMAKEMIMETYPE);
+
m_actionHandler =
new TextEditorActionHandler(Constants::C_CMAKEEDITOR,
TextEditorActionHandler::UnCommentSelection
@@ -67,24 +70,9 @@ CMakeEditorFactory::CMakeEditorFactory(CMakeManager *manager)
contextMenu->addAction(cmd);
}
-Core::Id CMakeEditorFactory::id() const
-{
- return Core::Id(CMakeProjectManager::Constants::CMAKE_EDITOR_ID);
-}
-
-QString CMakeEditorFactory::displayName() const
-{
- return tr(CMakeProjectManager::Constants::CMAKE_EDITOR_DISPLAY_NAME);
-}
-
Core::IEditor *CMakeEditorFactory::createEditor(QWidget *parent)
{
CMakeEditorWidget *rc = new CMakeEditorWidget(parent, this, m_actionHandler);
- TextEditor::TextEditorSettings::instance()->initializeEditor(rc);
+ TextEditor::TextEditorSettings::initializeEditor(rc);
return rc->editor();
}
-
-QStringList CMakeEditorFactory::mimeTypes() const
-{
- return m_mimeTypes;
-}
diff --git a/src/plugins/cmakeprojectmanager/cmakeeditorfactory.h b/src/plugins/cmakeprojectmanager/cmakeeditorfactory.h
index 279a99e10f..aafa5a4875 100644
--- a/src/plugins/cmakeprojectmanager/cmakeeditorfactory.h
+++ b/src/plugins/cmakeprojectmanager/cmakeeditorfactory.h
@@ -34,11 +34,7 @@
#include <coreplugin/editormanager/ieditorfactory.h>
-#include <QStringList>
-
-namespace TextEditor {
-class TextEditorActionHandler;
-}
+namespace TextEditor { class TextEditorActionHandler; }
namespace CMakeProjectManager {
namespace Internal {
@@ -49,11 +45,6 @@ class CMakeEditorFactory : public Core::IEditorFactory
public:
CMakeEditorFactory(CMakeManager *parent);
-
- // IEditorFactory
- QStringList mimeTypes() const;
- Core::Id id() const;
- QString displayName() const;
Core::IEditor *createEditor(QWidget *parent);
private:
diff --git a/src/plugins/cmakeprojectmanager/cmakefilecompletionassist.h b/src/plugins/cmakeprojectmanager/cmakefilecompletionassist.h
index 3f261d594a..5d0c3d76a1 100644
--- a/src/plugins/cmakeprojectmanager/cmakefilecompletionassist.h
+++ b/src/plugins/cmakeprojectmanager/cmakefilecompletionassist.h
@@ -39,6 +39,8 @@ class CMakeSettingsPage;
class CMakeFileCompletionAssistProvider : public TextEditor::CompletionAssistProvider
{
+ Q_OBJECT
+
public:
CMakeFileCompletionAssistProvider(CMakeSettingsPage *settingsPage);
~CMakeFileCompletionAssistProvider();
diff --git a/src/plugins/cmakeprojectmanager/cmakehighlighter.cpp b/src/plugins/cmakeprojectmanager/cmakehighlighter.cpp
index 0a7c59ad96..8231f402f4 100644
--- a/src/plugins/cmakeprojectmanager/cmakehighlighter.cpp
+++ b/src/plugins/cmakeprojectmanager/cmakehighlighter.cpp
@@ -30,9 +30,7 @@
#include "cmakehighlighter.h"
#include <QRegExp>
-#include <QColor>
#include <QTextDocument>
-#include <QTextEdit>
using namespace CMakeProjectManager::Internal;
@@ -48,6 +46,15 @@ static bool isVariable(const QByteArray &word)
CMakeHighlighter::CMakeHighlighter(QTextDocument *document) :
TextEditor::SyntaxHighlighter(document)
{
+ static QVector<TextEditor::TextStyle> categories;
+ if (categories.isEmpty()) {
+ categories << TextEditor::C_LABEL // variables
+ << TextEditor::C_KEYWORD // functions
+ << TextEditor::C_COMMENT
+ << TextEditor::C_STRING
+ << TextEditor::C_VISUAL_WHITESPACE;
+ }
+ setTextFormatCategories(categories);
}
@@ -62,12 +69,12 @@ void CMakeHighlighter::highlightBlock(const QString &text)
for (i=0; i < text.length(); i++) {
char c = text.at(i).toLatin1();
if (inCommentMode) {
- setFormat(i, 1, m_formats[CMakeCommentFormat]);
+ setFormat(i, 1, formatForCategory(CMakeCommentFormat));
} else {
if (c == '#') {
if (!inStringMode) {
inCommentMode = true;
- setFormat(i, 1, m_formats[CMakeCommentFormat]);
+ setFormat(i, 1, formatForCategory(CMakeCommentFormat));
buf.clear();
} else {
buf += c;
@@ -75,7 +82,7 @@ void CMakeHighlighter::highlightBlock(const QString &text)
} else if (c == '(') {
if (!inStringMode) {
if (!buf.isEmpty())
- setFormat(i - buf.length(), buf.length(), m_formats[CMakeFunctionFormat]);
+ setFormat(i - buf.length(), buf.length(), formatForCategory(CMakeFunctionFormat));
buf.clear();
} else {
buf += c;
@@ -88,14 +95,13 @@ void CMakeHighlighter::highlightBlock(const QString &text)
} else if (c == '\"') {
buf += c;
if (inStringMode) {
- setFormat(i + 1 - buf.length(), buf.length(), m_formats[CMakeStringFormat]);
+ setFormat(i + 1 - buf.length(), buf.length(), formatForCategory(CMakeStringFormat));
buf.clear();
} else {
- setFormat(i, 1, m_formats[CMakeStringFormat]);
+ setFormat(i, 1, formatForCategory(CMakeStringFormat));
}
inStringMode = !inStringMode;
- }
- else if (c == '\\') {
+ } else if (c == '\\') {
setFormat(i, 1, emptyFormat);
buf += c;
i++;
@@ -106,14 +112,14 @@ void CMakeHighlighter::highlightBlock(const QString &text)
}
} else if (c == '$') {
if (inStringMode)
- setFormat(i - buf.length(), buf.length(), m_formats[CMakeStringFormat]);
+ setFormat(i - buf.length(), buf.length(), formatForCategory(CMakeStringFormat));
buf.clear();
buf += c;
setFormat(i, 1, emptyFormat);
} else if (c == '}') {
buf += c;
if (isVariable(buf)) {
- setFormat(i + 1 - buf.length(), buf.length(), m_formats[CMakeVariableFormat]);
+ setFormat(i + 1 - buf.length(), buf.length(), formatForCategory(CMakeVariableFormat));
buf.clear();
}
} else {
@@ -124,12 +130,12 @@ void CMakeHighlighter::highlightBlock(const QString &text)
}
if (inStringMode) {
- setFormat(i - buf.length(), buf.length(), m_formats[CMakeStringFormat]);
+ setFormat(i - buf.length(), buf.length(), formatForCategory(CMakeStringFormat));
setCurrentBlockState(1);
} else {
setCurrentBlockState(0);
}
- applyFormatToSpaces(text, m_formats[CMakeVisualWhiteSpaceFormat]);
+ applyFormatToSpaces(text, formatForCategory(CMakeVisualWhiteSpaceFormat));
}
diff --git a/src/plugins/cmakeprojectmanager/cmakehighlighter.h b/src/plugins/cmakeprojectmanager/cmakehighlighter.h
index ba6b31ac06..4cfef25a70 100644
--- a/src/plugins/cmakeprojectmanager/cmakehighlighter.h
+++ b/src/plugins/cmakeprojectmanager/cmakehighlighter.h
@@ -31,9 +31,6 @@
#define CMAKEHIGHLIGHTER_H
#include <texteditor/syntaxhighlighter.h>
-#include <QtAlgorithms>
-#include <QSyntaxHighlighter>
-#include <QTextCharFormat>
namespace CMakeProjectManager {
namespace Internal {
@@ -50,21 +47,11 @@ public:
CMakeFunctionFormat,
CMakeCommentFormat,
CMakeStringFormat,
- CMakeVisualWhiteSpaceFormat,
- NumCMakeFormats
+ CMakeVisualWhiteSpaceFormat
};
CMakeHighlighter(QTextDocument *document = 0);
virtual 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);
- }
-
-private:
- QTextCharFormat m_formats[NumCMakeFormats];
};
} // namespace Internal
diff --git a/src/plugins/cmakeprojectmanager/cmakehighlighterfactory.cpp b/src/plugins/cmakeprojectmanager/cmakehighlighterfactory.cpp
new file mode 100644
index 0000000000..1899afcf88
--- /dev/null
+++ b/src/plugins/cmakeprojectmanager/cmakehighlighterfactory.cpp
@@ -0,0 +1,45 @@
+/****************************************************************************
+**
+** 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 "cmakehighlighterfactory.h"
+#include "cmakeprojectconstants.h"
+#include "cmakehighlighter.h"
+
+using namespace CMakeProjectManager::Internal;
+
+CMakeHighlighterFactory::CMakeHighlighterFactory()
+{
+ setId(CMakeProjectManager::Constants::CMAKE_EDITOR_ID);
+ addMimeType(CMakeProjectManager::Constants::CMAKEMIMETYPE);
+}
+
+TextEditor::SyntaxHighlighter *CMakeHighlighterFactory::createHighlighter() const
+{
+ return new CMakeHighlighter;
+}
diff --git a/src/plugins/cmakeprojectmanager/cmakehighlighterfactory.h b/src/plugins/cmakeprojectmanager/cmakehighlighterfactory.h
new file mode 100644
index 0000000000..a6545022c6
--- /dev/null
+++ b/src/plugins/cmakeprojectmanager/cmakehighlighterfactory.h
@@ -0,0 +1,51 @@
+/****************************************************************************
+**
+** 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 CMAKEHIGHLIGHTERFACTORY_H
+#define CMAKEHIGHLIGHTERFACTORY_H
+
+#include <texteditor/ihighlighterfactory.h>
+
+namespace CMakeProjectManager {
+namespace Internal {
+
+class CMakeHighlighterFactory : public TextEditor::IHighlighterFactory
+{
+ Q_OBJECT
+
+public:
+ CMakeHighlighterFactory();
+
+ virtual TextEditor::SyntaxHighlighter *createHighlighter() const;
+};
+
+} // namespace Internal
+} // namespace CMakeProjectManager
+
+#endif // CMAKEHIGHLIGHTERFACTORY_H
diff --git a/src/plugins/cmakeprojectmanager/cmakelocatorfilter.cpp b/src/plugins/cmakeprojectmanager/cmakelocatorfilter.cpp
index 401fc90a38..ab059a0639 100644
--- a/src/plugins/cmakeprojectmanager/cmakelocatorfilter.cpp
+++ b/src/plugins/cmakeprojectmanager/cmakelocatorfilter.cpp
@@ -41,6 +41,7 @@
using namespace CMakeProjectManager;
using namespace CMakeProjectManager::Internal;
+using namespace ProjectExplorer;
using namespace Utils;
CMakeLocatorFilter::CMakeLocatorFilter()
@@ -49,10 +50,9 @@ CMakeLocatorFilter::CMakeLocatorFilter()
setDisplayName(tr("Build CMake target"));
setShortcutString(QLatin1String("cm"));
- ProjectExplorer::SessionManager *sm = ProjectExplorer::ProjectExplorerPlugin::instance()->session();
- connect(sm, SIGNAL(projectAdded(ProjectExplorer::Project*)),
+ connect(SessionManager::instance(), SIGNAL(projectAdded(ProjectExplorer::Project*)),
this, SLOT(slotProjectListUpdated()));
- connect(sm, SIGNAL(projectRemoved(ProjectExplorer::Project*)),
+ connect(SessionManager::instance(), SIGNAL(projectRemoved(ProjectExplorer::Project*)),
this, SLOT(slotProjectListUpdated()));
// Initialize the filter
@@ -69,16 +69,14 @@ QList<Locator::FilterEntry> CMakeLocatorFilter::matchesFor(QFutureInterface<Loca
Q_UNUSED(future)
QList<Locator::FilterEntry> result;
- QList<ProjectExplorer::Project *> projects =
- ProjectExplorer::ProjectExplorerPlugin::instance()->session()->projects();
- foreach (ProjectExplorer::Project *p, projects) {
+ foreach (Project *p, SessionManager::projects()) {
CMakeProject *cmakeProject = qobject_cast<CMakeProject *>(p);
if (cmakeProject) {
foreach (const CMakeBuildTarget &ct, cmakeProject->buildTargets()) {
if (ct.title.contains(entry)) {
- Locator::FilterEntry entry(this, ct.title, cmakeProject->document()->fileName());
+ Locator::FilterEntry entry(this, ct.title, cmakeProject->projectFilePath());
entry.extraInfo = FileUtils::shortNativePath(
- FileName::fromString(cmakeProject->document()->fileName()));
+ FileName::fromString(cmakeProject->projectFilePath()));
result.append(entry);
}
}
@@ -93,11 +91,9 @@ void CMakeLocatorFilter::accept(Locator::FilterEntry selection) const
// Get the project containing the target selected
CMakeProject *cmakeProject = 0;
- QList<ProjectExplorer::Project *> projects =
- ProjectExplorer::ProjectExplorerPlugin::instance()->session()->projects();
- foreach (ProjectExplorer::Project *p, projects) {
+ foreach (Project *p, SessionManager::projects()) {
cmakeProject = qobject_cast<CMakeProject *>(p);
- if (cmakeProject && cmakeProject->document()->fileName() == selection.internalData.toString())
+ if (cmakeProject && cmakeProject->projectFilePath() == selection.internalData.toString())
break;
cmakeProject = 0;
}
@@ -136,9 +132,7 @@ void CMakeLocatorFilter::slotProjectListUpdated()
{
CMakeProject *cmakeProject = 0;
- QList<ProjectExplorer::Project *> projects =
- ProjectExplorer::ProjectExplorerPlugin::instance()->session()->projects();
- foreach (ProjectExplorer::Project *p, projects) {
+ foreach (Project *p, SessionManager::projects()) {
cmakeProject = qobject_cast<CMakeProject *>(p);
if (cmakeProject)
break;
diff --git a/src/plugins/cmakeprojectmanager/cmakeopenprojectwizard.cpp b/src/plugins/cmakeprojectmanager/cmakeopenprojectwizard.cpp
index ab3f402fa6..477a180224 100644
--- a/src/plugins/cmakeprojectmanager/cmakeopenprojectwizard.cpp
+++ b/src/plugins/cmakeprojectmanager/cmakeopenprojectwizard.cpp
@@ -30,6 +30,7 @@
#include "cmakeopenprojectwizard.h"
#include "cmakeprojectmanager.h"
#include "cmakebuildconfiguration.h"
+#include "cmakebuildinfo.h"
#include <coreplugin/icore.h>
#include <utils/hostosinfo.h>
@@ -42,6 +43,7 @@
#include <projectexplorer/abi.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <texteditor/fontsettings.h>
+#include <remotelinux/remotelinux_constants.h>
#include <QVBoxLayout>
#include <QFormLayout>
@@ -179,7 +181,8 @@ QList<GeneratorInfo> GeneratorInfo::generatorInfosFor(ProjectExplorer::Kit *k, N
if (!tc)
return results;
Core::Id deviceType = ProjectExplorer::DeviceTypeKitInformation::deviceTypeId(k);
- if (deviceType != ProjectExplorer::Constants::DESKTOP_DEVICE_TYPE)
+ if (deviceType != ProjectExplorer::Constants::DESKTOP_DEVICE_TYPE
+ && deviceType != RemoteLinux::Constants::GenericLinuxOsType)
return results;
ProjectExplorer::Abi targetAbi = tc->targetAbi();
if (n != ForceNinja) {
@@ -238,13 +241,15 @@ CMakeOpenProjectWizard::CMakeOpenProjectWizard(CMakeManager *cmakeManager, const
}
CMakeOpenProjectWizard::CMakeOpenProjectWizard(CMakeManager *cmakeManager, CMakeOpenProjectWizard::Mode mode,
- const BuildInfo &info)
+ const CMakeBuildInfo *info)
: m_cmakeManager(cmakeManager),
- m_sourceDirectory(info.sourceDirectory),
- m_environment(info.environment),
- m_useNinja(info.useNinja),
- m_kit(info.kit)
+ m_sourceDirectory(info->sourceDirectory),
+ m_environment(info->environment),
+ m_useNinja(info->useNinja),
+ m_kit(0)
{
+ m_kit = ProjectExplorer::KitManager::find(info->kitId);
+
CMakeRunPage::Mode rmode;
if (mode == CMakeOpenProjectWizard::NeedToCreate)
rmode = CMakeRunPage::Recreate;
@@ -256,13 +261,13 @@ CMakeOpenProjectWizard::CMakeOpenProjectWizard(CMakeManager *cmakeManager, CMake
rmode = CMakeRunPage::ChangeDirectory;
if (mode == CMakeOpenProjectWizard::ChangeDirectory) {
- m_buildDirectory = info.buildDirectory;
+ m_buildDirectory = info->buildDirectory.toString();
addPage(new ShadowBuildPage(this, true));
}
if (!m_cmakeManager->isCMakeExecutableValid())
addPage(new ChooseCMakePage(this));
- addPage(new CMakeRunPage(this, rmode, info.buildDirectory));
+ addPage(new CMakeRunPage(this, rmode, info->buildDirectory.toString()));
init();
}
@@ -292,8 +297,7 @@ bool CMakeOpenProjectWizard::compatibleKitExist() const
bool hasNinjaGenerator = m_cmakeManager->hasCodeBlocksNinjaGenerator();
bool preferNinja = m_cmakeManager->preferNinja();
- QList<ProjectExplorer::Kit *> kitList =
- ProjectExplorer::KitManager::instance()->kits();
+ QList<ProjectExplorer::Kit *> kitList = ProjectExplorer::KitManager::kits();
foreach (ProjectExplorer::Kit *k, kitList) {
// OfferNinja and ForceNinja differ in what they return
@@ -617,7 +621,7 @@ QByteArray CMakeRunPage::cachedGeneratorFromFile(const QString &cache)
void CMakeRunPage::initializePage()
{
if (m_mode == Initial) {
- bool upToDateXmlFile = m_cmakeWizard->existsUpToDateXmlFile();;
+ bool upToDateXmlFile = m_cmakeWizard->existsUpToDateXmlFile();
m_buildDirectory = m_cmakeWizard->buildDirectory();
if (upToDateXmlFile) {
@@ -665,8 +669,7 @@ void CMakeRunPage::initializePage()
QByteArray cachedGenerator = cachedGeneratorFromFile(m_buildDirectory + QLatin1String("/CMakeCache.txt"));
m_generatorComboBox->show();
- QList<ProjectExplorer::Kit *> kitList =
- ProjectExplorer::KitManager::instance()->kits();
+ QList<ProjectExplorer::Kit *> kitList = ProjectExplorer::KitManager::kits();
int defaultIndex = 0;
foreach (ProjectExplorer::Kit *k, kitList) {
@@ -675,7 +678,7 @@ void CMakeRunPage::initializePage()
preferNinja,
hasCodeBlocksGenerator);
- if (k == ProjectExplorer::KitManager::instance()->defaultKit())
+ if (k == ProjectExplorer::KitManager::defaultKit())
defaultIndex = m_generatorComboBox->count();
foreach (const GeneratorInfo &info, infos)
diff --git a/src/plugins/cmakeprojectmanager/cmakeopenprojectwizard.h b/src/plugins/cmakeprojectmanager/cmakeopenprojectwizard.h
index 90db125212..793d635ab2 100644
--- a/src/plugins/cmakeprojectmanager/cmakeopenprojectwizard.h
+++ b/src/plugins/cmakeprojectmanager/cmakeopenprojectwizard.h
@@ -31,6 +31,7 @@
#define CMAKEOPENPROJECTWIZARD_H
#include "cmakebuildconfiguration.h"
+#include "cmakebuildinfo.h"
#include <utils/environment.h>
#include <utils/wizard.h>
@@ -70,34 +71,13 @@ public:
ChangeDirectory
};
- class BuildInfo
- {
- public:
- BuildInfo()
- {}
-
- BuildInfo(CMakeBuildConfiguration *bc)
- : sourceDirectory(bc->target()->project()->projectDirectory())
- , buildDirectory(bc->buildDirectory())
- , environment(bc->environment())
- , useNinja(bc->useNinja())
- , kit(bc->target()->kit())
- {}
-
- QString sourceDirectory;
- QString buildDirectory;
- Utils::Environment environment;
- bool useNinja;
- ProjectExplorer::Kit *kit;
- };
-
/// used at importing a project without a .user file
CMakeOpenProjectWizard(CMakeManager *cmakeManager, const QString &sourceDirectory, Utils::Environment env);
/// used to update if we have already a .user file
/// recreates or updates the cbp file
/// Also used to change the build directory of one buildconfiguration or create a new buildconfiguration
- CMakeOpenProjectWizard(CMakeManager *cmakeManager, Mode mode, const BuildInfo &info);
+ CMakeOpenProjectWizard(CMakeManager *cmakeManager, Mode mode, const CMakeBuildInfo *info);
QString buildDirectory() const;
QString sourceDirectory() const;
diff --git a/src/plugins/cmakeprojectmanager/cmakeparser.cpp b/src/plugins/cmakeprojectmanager/cmakeparser.cpp
new file mode 100644
index 0000000000..631b445be7
--- /dev/null
+++ b/src/plugins/cmakeprojectmanager/cmakeparser.cpp
@@ -0,0 +1,206 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Axonian LLC.
+** 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 "cmakeparser.h"
+
+#include <utils/qtcassert.h>
+
+#include <projectexplorer/gnumakeparser.h>
+#include <projectexplorer/projectexplorerconstants.h>
+
+using namespace CMakeProjectManager;
+using namespace Internal;
+using namespace ProjectExplorer;
+
+const char COMMON_ERROR_PATTERN[] = "^CMake Error at (.*):([0-9]*) \\((.*)\\):";
+const char NEXT_SUBERROR_PATTERN[] = "^CMake Error in (.*):";
+
+CMakeParser::CMakeParser() :
+ m_skippedFirstEmptyLine(false)
+{
+ m_commonError.setPattern(QLatin1String(COMMON_ERROR_PATTERN));
+ m_commonError.setMinimal(true);
+ QTC_CHECK(m_commonError.isValid());
+
+ m_nextSubError.setPattern(QLatin1String(NEXT_SUBERROR_PATTERN));
+ m_nextSubError.setMinimal(true);
+ QTC_CHECK(m_nextSubError.isValid());
+ appendOutputParser(new GnuMakeParser());
+}
+
+void CMakeParser::stdError(const QString &line)
+{
+ QString trimmedLine = rightTrimmed(line);
+ if (trimmedLine.isEmpty() && !m_lastTask.isNull()) {
+ if (m_skippedFirstEmptyLine) {
+ doFlush();
+ } else {
+ m_skippedFirstEmptyLine = true;
+ }
+ return;
+ }
+ if (m_skippedFirstEmptyLine)
+ m_skippedFirstEmptyLine= false;
+
+ if (m_commonError.indexIn(trimmedLine) != -1) {
+ m_lastTask = Task(Task::Error, QString(), Utils::FileName::fromUserInput(m_commonError.cap(1)),
+ m_commonError.cap(2).toInt(), Constants::TASK_CATEGORY_BUILDSYSTEM);
+ return;
+ } else if (m_nextSubError.indexIn(trimmedLine) != -1) {
+ m_lastTask = Task(Task::Error, QString(), Utils::FileName::fromUserInput(m_nextSubError.cap(1)), -1,
+ Constants::TASK_CATEGORY_BUILDSYSTEM);
+ return;
+ } else if (trimmedLine.startsWith(QLatin1String(" ")) && !m_lastTask.isNull()) {
+ if (!m_lastTask.description.isEmpty())
+ m_lastTask.description.append(QLatin1Char(' '));
+ m_lastTask.description.append(trimmedLine.trimmed());
+ return;
+ }
+
+ IOutputParser::stdError(line);
+}
+
+void CMakeParser::doFlush()
+{
+ if (m_lastTask.isNull())
+ return;
+ Task t = m_lastTask;
+ m_lastTask.clear();
+ emit addTask(t);
+}
+
+#ifdef WITH_TESTS
+#include "cmakeprojectplugin.h"
+
+#include <projectexplorer/outputparser_test.h>
+
+#include <QTest>
+
+void CMakeProjectPlugin::testCMakeParser_data()
+{
+ QTest::addColumn<QString>("input");
+ QTest::addColumn<OutputParserTester::Channel>("inputChannel");
+ QTest::addColumn<QString>("childStdOutLines");
+ QTest::addColumn<QString>("childStdErrLines");
+ QTest::addColumn<QList<ProjectExplorer::Task> >("tasks");
+ QTest::addColumn<QString>("outputLines");
+
+ const Core::Id categoryBuild = Constants::TASK_CATEGORY_BUILDSYSTEM;
+
+ // negative tests
+ QTest::newRow("pass-through stdout")
+ << QString::fromLatin1("Sometext") << OutputParserTester::STDOUT
+ << QString::fromLatin1("Sometext\n") << QString()
+ << QList<ProjectExplorer::Task>()
+ << QString();
+ QTest::newRow("pass-through stderr")
+ << QString::fromLatin1("Sometext") << OutputParserTester::STDERR
+ << QString() << QString::fromLatin1("Sometext\n")
+ << QList<ProjectExplorer::Task>()
+ << QString();
+
+ // positive tests
+ QTest::newRow("add custom target")
+ << QString::fromLatin1("CMake Error at src/1/app/CMakeLists.txt:70 (add_custom_target):\n"
+ " Cannot find source file:\n\n"
+ " unknownFile.qml\n\n"
+ " Tried extensions .c .C .c++ .cc .cpp .cxx .m .M .mm .h .hh .h++ .hm .hpp\n"
+ " .hxx .in .txx\n\n\n"
+ "CMake Error in src/1/app/CMakeLists.txt:\n"
+ " Cannot find source file:\n\n"
+ " CMakeLists.txt2\n\n"
+ " Tried extensions .c .C .c++ .cc .cpp .cxx .m .M .mm .h .hh .h++ .hm .hpp\n"
+ " .hxx .in .txx\n\n")
+ << OutputParserTester::STDERR
+ << QString() << QString()
+ << (QList<ProjectExplorer::Task>()
+ << Task(Task::Error,
+ QLatin1String("Cannot find source file: unknownFile.qml Tried extensions .c .C .c++ .cc .cpp .cxx .m .M .mm .h .hh .h++ .hm .hpp .hxx .in .txx"),
+ Utils::FileName::fromUserInput(QLatin1String("src/1/app/CMakeLists.txt")), 70,
+ categoryBuild)
+ << Task(Task::Error,
+ QLatin1String("Cannot find source file: CMakeLists.txt2 Tried extensions .c .C .c++ .cc .cpp .cxx .m .M .mm .h .hh .h++ .hm .hpp .hxx .in .txx"),
+ Utils::FileName::fromUserInput(QLatin1String("src/1/app/CMakeLists.txt")), -1,
+ categoryBuild))
+ << QString();
+
+ QTest::newRow("add subdirectory")
+ << QString::fromLatin1("CMake Error at src/1/CMakeLists.txt:8 (add_subdirectory):\n"
+ " add_subdirectory given source \"app1\" which is not an existing directory.\n\n")
+ << OutputParserTester::STDERR
+ << QString() << QString()
+ << (QList<ProjectExplorer::Task>()
+ << Task(Task::Error,
+ QLatin1String("add_subdirectory given source \"app1\" which is not an existing directory."),
+ Utils::FileName::fromUserInput(QLatin1String("src/1/CMakeLists.txt")), 8,
+ categoryBuild))
+ << QString();
+
+ QTest::newRow("unknown command")
+ << QString::fromLatin1("CMake Error at src/1/CMakeLists.txt:8 (i_am_wrong_command):\n"
+ " Unknown CMake command \"i_am_wrong_command\".\n\n")
+ << OutputParserTester::STDERR
+ << QString() << QString()
+ << (QList<ProjectExplorer::Task>()
+ << Task(Task::Error,
+ QLatin1String("Unknown CMake command \"i_am_wrong_command\"."),
+ Utils::FileName::fromUserInput(QLatin1String("src/1/CMakeLists.txt")), 8,
+ categoryBuild))
+ << QString();
+
+ QTest::newRow("incorrect arguments")
+ << QString::fromLatin1("CMake Error at src/1/CMakeLists.txt:8 (message):\n"
+ " message called with incorrect number of arguments\n\n")
+ << OutputParserTester::STDERR
+ << QString() << QString()
+ << (QList<ProjectExplorer::Task>()
+ << Task(Task::Error,
+ QLatin1String("message called with incorrect number of arguments"),
+ Utils::FileName::fromUserInput(QLatin1String("src/1/CMakeLists.txt")), 8,
+ categoryBuild))
+ << QString();
+}
+
+void CMakeProjectPlugin::testCMakeParser()
+{
+ OutputParserTester testbench;
+ testbench.appendOutputParser(new CMakeParser);
+ QFETCH(QString, input);
+ QFETCH(OutputParserTester::Channel, inputChannel);
+ QFETCH(QList<Task>, tasks);
+ QFETCH(QString, childStdOutLines);
+ QFETCH(QString, childStdErrLines);
+ QFETCH(QString, outputLines);
+
+ testbench.testParsing(input, inputChannel,
+ tasks, childStdOutLines, childStdErrLines,
+ outputLines);
+}
+
+#endif
diff --git a/src/plugins/cmakeprojectmanager/cmakeparser.h b/src/plugins/cmakeprojectmanager/cmakeparser.h
new file mode 100644
index 0000000000..24b61f9863
--- /dev/null
+++ b/src/plugins/cmakeprojectmanager/cmakeparser.h
@@ -0,0 +1,60 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Axonian LLC.
+** 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 CMAKEOUTPUTPARSER_H
+#define CMAKEOUTPUTPARSER_H
+
+#include <projectexplorer/ioutputparser.h>
+#include <projectexplorer/task.h>
+
+namespace CMakeProjectManager {
+namespace Internal {
+
+class CMakeParser : public ProjectExplorer::IOutputParser
+{
+ Q_OBJECT
+
+public:
+ explicit CMakeParser();
+ void stdError(const QString &line);
+
+protected:
+ void doFlush();
+
+private:
+ ProjectExplorer::Task m_lastTask;
+ QRegExp m_commonError;
+ QRegExp m_nextSubError;
+ bool m_skippedFirstEmptyLine;
+};
+
+} // namespace CMakeProjectManager
+} // namespace Internal
+
+#endif // CMAKEOUTPUTPARSER_H
diff --git a/src/plugins/cmakeprojectmanager/cmakeproject.cpp b/src/plugins/cmakeprojectmanager/cmakeproject.cpp
index bc6d5fc8a2..18fd8422e7 100644
--- a/src/plugins/cmakeprojectmanager/cmakeproject.cpp
+++ b/src/plugins/cmakeprojectmanager/cmakeproject.cpp
@@ -35,22 +35,24 @@
#include "cmakerunconfiguration.h"
#include "makestep.h"
#include "cmakeopenprojectwizard.h"
-#include "cmakeuicodemodelsupport.h"
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/headerpath.h>
#include <projectexplorer/buildsteplist.h>
#include <projectexplorer/buildmanager.h>
+#include <projectexplorer/buildtargetinfo.h>
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/kitmanager.h>
#include <projectexplorer/toolchain.h>
#include <projectexplorer/target.h>
#include <projectexplorer/deployconfiguration.h>
+#include <projectexplorer/deploymentdata.h>
#include <projectexplorer/projectmacroexpander.h>
#include <qtsupport/customexecutablerunconfiguration.h>
#include <qtsupport/baseqtversion.h>
#include <qtsupport/qtkitinformation.h>
+#include <qtsupport/uicodemodelsupport.h>
#include <cpptools/cppmodelmanagerinterface.h>
#include <extensionsystem/pluginmanager.h>
#include <utils/qtcassert.h>
@@ -62,13 +64,9 @@
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/variablemanager.h>
-#include <QMap>
#include <QDebug>
#include <QDir>
-#include <QDateTime>
-#include <QProcess>
#include <QFormLayout>
-#include <QInputDialog>
#include <QFileSystemWatcher>
using namespace CMakeProjectManager;
@@ -84,20 +82,6 @@ using namespace ProjectExplorer;
// Open Questions
// Who sets up the environment for cl.exe ? INCLUDEPATH and so on
-// Test for form editor (loosely coupled)
-static inline bool isFormWindowEditor(const QObject *o)
-{
- return o && !qstrcmp(o->metaObject()->className(), "Designer::FormWindowEditor");
-}
-
-// Return contents of form editor (loosely coupled)
-static inline QString formWindowEditorContents(const QObject *editor)
-{
- const QVariant contentV = editor->property("contents");
- QTC_ASSERT(contentV.isValid(), return QString());
- return contentV.toString();
-}
-
/*!
\class CMakeProject
*/
@@ -105,31 +89,24 @@ CMakeProject::CMakeProject(CMakeManager *manager, const QString &fileName)
: m_manager(manager),
m_activeTarget(0),
m_fileName(fileName),
- m_rootNode(new CMakeProjectNode(m_fileName)),
- m_lastEditor(0)
+ m_rootNode(new CMakeProjectNode(fileName)),
+ m_watcher(new QFileSystemWatcher(this))
{
setProjectContext(Core::Context(CMakeProjectManager::Constants::PROJECTCONTEXT));
setProjectLanguages(Core::Context(ProjectExplorer::Constants::LANG_CXX));
+ m_projectName = QFileInfo(fileName).absoluteDir().dirName();
+
m_file = new CMakeFile(this, fileName);
connect(this, SIGNAL(buildTargetsChanged()),
this, SLOT(updateRunConfigurations()));
+
+ connect(m_watcher, SIGNAL(fileChanged(QString)), this, SLOT(fileChanged(QString)));
}
CMakeProject::~CMakeProject()
{
- // Remove CodeModel support
- CppTools::CppModelManagerInterface *modelManager
- = CppTools::CppModelManagerInterface::instance();
- QMap<QString, CMakeUiCodeModelSupport *>::const_iterator it, end;
- it = m_uiCodeModelSupport.constBegin();
- end = m_uiCodeModelSupport.constEnd();
- for (; it!=end; ++it) {
- modelManager->removeEditorSupport(it.value());
- delete it.value();
- }
-
m_codeModelFuture.cancel();
delete m_rootNode;
}
@@ -149,7 +126,7 @@ void CMakeProject::changeActiveBuildConfiguration(ProjectExplorer::BuildConfigur
CMakeBuildConfiguration *cmakebc = static_cast<CMakeBuildConfiguration *>(bc);
// Pop up a dialog asking the user to rerun cmake
- QString cbpFile = CMakeManager::findCbpFile(QDir(bc->buildDirectory()));
+ QString cbpFile = CMakeManager::findCbpFile(QDir(bc->buildDirectory().toString()));
QFileInfo cbpFileFi(cbpFile);
CMakeOpenProjectWizard::Mode mode = CMakeOpenProjectWizard::Nothing;
if (!cbpFileFi.exists()) {
@@ -164,8 +141,8 @@ void CMakeProject::changeActiveBuildConfiguration(ProjectExplorer::BuildConfigur
}
if (mode != CMakeOpenProjectWizard::Nothing) {
- CMakeOpenProjectWizard copw(m_manager, mode,
- CMakeOpenProjectWizard::BuildInfo(cmakebc));
+ CMakeBuildInfo info(cmakebc);
+ CMakeOpenProjectWizard copw(m_manager, mode, &info);
if (copw.exec() == QDialog::Accepted)
cmakebc->setUseNinja(copw.useNinja()); // NeedToCreate can change the Ninja setting
}
@@ -194,7 +171,7 @@ void CMakeProject::activeTargetWasChanged(Target *target)
void CMakeProject::changeBuildDirectory(CMakeBuildConfiguration *bc, const QString &newBuildDirectory)
{
- bc->setBuildDirectory(newBuildDirectory);
+ bc->setBuildDirectory(Utils::FileName::fromString(newBuildDirectory));
parseCMakeLists();
}
@@ -219,12 +196,12 @@ 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(Core::Id("CMakeEditor.RunCMake"));
+ foreach (Core::IDocument *document, Core::EditorManager::documentModel()->openedDocuments())
+ if (isProjectFile(document->filePath()))
+ document->infoBar()->removeInfo("CMakeEditor.RunCMake");
// Find cbp file
- QString cbpFile = CMakeManager::findCbpFile(activeBC->buildDirectory());
+ QString cbpFile = CMakeManager::findCbpFile(activeBC->buildDirectory().toString());
if (cbpFile.isEmpty()) {
emit buildTargetsChanged();
@@ -286,20 +263,7 @@ bool CMakeProject::parseCMakeLists()
// qDebug()<<"";
// }
-
- // TOOD this code ain't very pretty ...
- m_uicCommand.clear();
- QFile cmakeCache(activeBC->buildDirectory() + QLatin1String("/CMakeCache.txt"));
- cmakeCache.open(QIODevice::ReadOnly);
- while (!cmakeCache.atEnd()) {
- QByteArray line = cmakeCache.readLine();
- if (line.startsWith("QT_UIC_EXECUTABLE")) {
- if (int pos = line.indexOf('='))
- m_uicCommand = QString::fromLocal8Bit(line.mid(pos + 1).trimmed());
- break;
- }
- }
- cmakeCache.close();
+ updateApplicationAndDeploymentTargets();
createUiCodeModelSupport();
@@ -587,7 +551,7 @@ bool CMakeProject::fromMap(const QVariantMap &map)
CMakeBuildConfiguration *bc(new CMakeBuildConfiguration(t));
bc->setDefaultDisplayName(QLatin1String("all"));
bc->setUseNinja(copw.useNinja());
- bc->setBuildDirectory(copw.buildDirectory());
+ bc->setBuildDirectory(Utils::FileName::fromString(copw.buildDirectory()));
ProjectExplorer::BuildStepList *buildSteps = bc->stepList(ProjectExplorer::Constants::BUILDSTEPS_BUILD);
ProjectExplorer::BuildStepList *cleanSteps = bc->stepList(ProjectExplorer::Constants::BUILDSTEPS_CLEAN);
@@ -601,9 +565,7 @@ bool CMakeProject::fromMap(const QVariantMap &map)
t->addBuildConfiguration(bc);
- DeployConfigurationFactory *fac = ExtensionSystem::PluginManager::instance()->getObject<DeployConfigurationFactory>();
- ProjectExplorer::DeployConfiguration *dc = fac->create(t, ProjectExplorer::Constants::DEFAULT_DEPLOYCONFIGURATION_ID);
- t->addDeployConfiguration(dc);
+ t->updateDefaultDeployConfigurations();
addTarget(t);
} else {
@@ -613,7 +575,7 @@ bool CMakeProject::fromMap(const QVariantMap &map)
CMakeBuildConfiguration *activeBC = qobject_cast<CMakeBuildConfiguration *>(activeTarget()->activeBuildConfiguration());
if (!activeBC)
return false;
- QString cbpFile = CMakeManager::findCbpFile(QDir(activeBC->buildDirectory()));
+ QString cbpFile = CMakeManager::findCbpFile(QDir(activeBC->buildDirectory().toString()));
QFileInfo cbpFileFi(cbpFile);
CMakeOpenProjectWizard::Mode mode = CMakeOpenProjectWizard::Nothing;
@@ -623,8 +585,8 @@ bool CMakeProject::fromMap(const QVariantMap &map)
mode = CMakeOpenProjectWizard::NeedToUpdate;
if (mode != CMakeOpenProjectWizard::Nothing) {
- CMakeOpenProjectWizard copw(m_manager, mode,
- CMakeOpenProjectWizard::BuildInfo(activeBC));
+ CMakeBuildInfo info(activeBC);
+ CMakeOpenProjectWizard copw(m_manager, mode, &info);
if (copw.exec() != QDialog::Accepted)
return false;
else
@@ -632,27 +594,8 @@ bool CMakeProject::fromMap(const QVariantMap &map)
}
}
- m_watcher = new QFileSystemWatcher(this);
- connect(m_watcher, SIGNAL(fileChanged(QString)), this, SLOT(fileChanged(QString)));
-
parseCMakeLists();
- if (!hasUserFile && hasBuildTarget(QLatin1String("all"))) {
- MakeStep *makeStep = qobject_cast<MakeStep *>(
- activeTarget()->activeBuildConfiguration()->stepList(ProjectExplorer::Constants::BUILDSTEPS_BUILD)->at(0));
- Q_ASSERT(makeStep);
- makeStep->setBuildTarget(QLatin1String("all"), true);
- }
-
- connect(Core::EditorManager::instance(), SIGNAL(editorAboutToClose(Core::IEditor*)),
- this, SLOT(editorAboutToClose(Core::IEditor*)));
-
- connect(Core::EditorManager::instance(), SIGNAL(currentEditorChanged(Core::IEditor*)),
- this, SLOT(editorChanged(Core::IEditor*)));
-
- connect(ProjectExplorer::ProjectExplorerPlugin::instance()->buildManager(), SIGNAL(buildStateChanged(ProjectExplorer::Project*)),
- this, SLOT(buildStateChanged(ProjectExplorer::Project*)));
-
m_activeTarget = activeTarget();
if (m_activeTarget)
connect(m_activeTarget, SIGNAL(activeBuildConfigurationChanged(ProjectExplorer::BuildConfiguration*)),
@@ -666,17 +609,9 @@ bool CMakeProject::fromMap(const QVariantMap &map)
bool CMakeProject::setupTarget(Target *t)
{
- CMakeBuildConfigurationFactory *factory
- = ExtensionSystem::PluginManager::instance()->getObject<CMakeBuildConfigurationFactory>();
- CMakeBuildConfiguration *bc = factory->create(t, Constants::CMAKE_BC_ID, QLatin1String("all"));
- if (!bc)
- return false;
+ t->updateDefaultBuildConfigurations();
+ t->updateDefaultDeployConfigurations();
- t->addBuildConfiguration(bc);
-
- DeployConfigurationFactory *fac = ExtensionSystem::PluginManager::instance()->getObject<DeployConfigurationFactory>();
- ProjectExplorer::DeployConfiguration *dc = fac->create(t, ProjectExplorer::Constants::DEFAULT_DEPLOYCONFIGURATION_ID);
- t->addDeployConfiguration(dc);
return true;
}
@@ -688,11 +623,6 @@ CMakeBuildTarget CMakeProject::buildTargetForTitle(const QString &title)
return CMakeBuildTarget();
}
-QString CMakeProject::uicCommand() const
-{
- return m_uicCommand;
-}
-
QString CMakeProject::uiHeaderFile(const QString &uiFile)
{
QFileInfo fi(uiFile);
@@ -711,7 +641,7 @@ QString CMakeProject::uiHeaderFile(const QString &uiFile)
QDir srcDirRoot = QDir(project.toString());
QString relativePath = srcDirRoot.relativeFilePath(baseDirectory.toString());
- QDir buildDir = QDir(activeTarget()->activeBuildConfiguration()->buildDirectory());
+ QDir buildDir = QDir(activeTarget()->activeBuildConfiguration()->buildDirectory().toString());
QString uiHeaderFilePath = buildDir.absoluteFilePath(relativePath);
uiHeaderFilePath += QLatin1String("/ui_");
uiHeaderFilePath += fi.completeBaseName();
@@ -783,119 +713,69 @@ void CMakeProject::updateRunConfigurations(Target *t)
}
}
-void CMakeProject::createUiCodeModelSupport()
+void CMakeProject::updateApplicationAndDeploymentTargets()
{
-// qDebug()<<"creatUiCodeModelSupport()";
- CppTools::CppModelManagerInterface *modelManager
- = CppTools::CppModelManagerInterface::instance();
-
- // First move all to
- QMap<QString, CMakeUiCodeModelSupport *> oldCodeModelSupport;
- oldCodeModelSupport = m_uiCodeModelSupport;
- m_uiCodeModelSupport.clear();
+ Target *t = activeTarget();
- // Find all ui files
- foreach (const QString &uiFile, m_files) {
- if (uiFile.endsWith(QLatin1String(".ui"))) {
- // UI file, not convert to
- QString uiHeaderFilePath = uiHeaderFile(uiFile);
- QMap<QString, CMakeUiCodeModelSupport *>::iterator it
- = oldCodeModelSupport.find(uiFile);
- if (it != oldCodeModelSupport.end()) {
- // qDebug()<<"updated old codemodelsupport";
- CMakeUiCodeModelSupport *cms = it.value();
- cms->setFileName(uiHeaderFilePath);
- m_uiCodeModelSupport.insert(it.key(), cms);
- oldCodeModelSupport.erase(it);
- } else {
- // qDebug()<<"adding new codemodelsupport";
- CMakeUiCodeModelSupport *cms = new CMakeUiCodeModelSupport(modelManager, this, uiFile, uiHeaderFilePath);
- m_uiCodeModelSupport.insert(uiFile, cms);
- modelManager->addEditorSupport(cms);
- }
- }
- }
+ QFile deploymentFile;
+ QTextStream deploymentStream;
+ QString deploymentPrefix;
+ QDir sourceDir;
- // Remove old
- QMap<QString, CMakeUiCodeModelSupport *>::const_iterator it, end;
- end = oldCodeModelSupport.constEnd();
- for (it = oldCodeModelSupport.constBegin(); it!=end; ++it) {
- modelManager->removeEditorSupport(it.value());
- delete it.value();
+ sourceDir.setPath(t->project()->projectDirectory());
+ deploymentFile.setFileName(sourceDir.filePath(QLatin1String("QtCreatorDeployment.txt")));
+ if (deploymentFile.open(QFile::ReadOnly | QFile::Text)) {
+ deploymentStream.setDevice(&deploymentFile);
+ deploymentPrefix = deploymentStream.readLine();
+ if (!deploymentPrefix.endsWith(QLatin1Char('/')))
+ deploymentPrefix.append(QLatin1Char('/'));
}
-}
-void CMakeProject::updateCodeModelSupportFromEditor(const QString &uiFileName,
- const QString &contents)
-{
- const QMap<QString, CMakeUiCodeModelSupport *>::const_iterator it =
- m_uiCodeModelSupport.constFind(uiFileName);
- if (it != m_uiCodeModelSupport.constEnd())
- it.value()->updateFromEditor(contents);
-}
+ BuildTargetInfoList appTargetList;
+ DeploymentData deploymentData;
+ QDir buildDir(t->activeBuildConfiguration()->buildDirectory().toString());
+ foreach (const CMakeBuildTarget &ct, m_buildTargets) {
+ if (ct.executable.isEmpty())
+ continue;
-void CMakeProject::editorChanged(Core::IEditor *editor)
-{
- // Handle old editor
- if (isFormWindowEditor(m_lastEditor)) {
- disconnect(m_lastEditor, SIGNAL(changed()), this, SLOT(uiEditorContentsChanged()));
- if (m_dirtyUic) {
- const QString contents = formWindowEditorContents(m_lastEditor);
- updateCodeModelSupportFromEditor(m_lastEditor->document()->fileName(), contents);
- m_dirtyUic = false;
+ deploymentData.addFile(ct.executable, deploymentPrefix + buildDir.relativeFilePath(QFileInfo(ct.executable).dir().path()), DeployableFile::TypeExecutable);
+ if (!ct.library) {
+ // TODO: Put a path to corresponding .cbp file into projectFilePath?
+ appTargetList.list << BuildTargetInfo(ct.executable, ct.executable);
}
}
- m_lastEditor = editor;
-
- // Handle new editor
- if (isFormWindowEditor(editor))
- connect(editor, SIGNAL(changed()), this, SLOT(uiEditorContentsChanged()));
-}
-
-void CMakeProject::editorAboutToClose(Core::IEditor *editor)
-{
- if (m_lastEditor == editor) {
- // Oh no our editor is going to be closed
- // get the content first
- if (isFormWindowEditor(m_lastEditor)) {
- disconnect(m_lastEditor, SIGNAL(changed()), this, SLOT(uiEditorContentsChanged()));
- if (m_dirtyUic) {
- const QString contents = formWindowEditorContents(m_lastEditor);
- updateCodeModelSupportFromEditor(m_lastEditor->document()->fileName(), contents);
- m_dirtyUic = false;
- }
- }
- m_lastEditor = 0;
+ QString absoluteSourcePath = sourceDir.absolutePath();
+ if (!absoluteSourcePath.endsWith(QLatin1Char('/')))
+ absoluteSourcePath.append(QLatin1Char('/'));
+ while (!deploymentStream.atEnd()) {
+ QStringList file = deploymentStream.readLine().split(QLatin1Char(':'));
+ deploymentData.addFile(absoluteSourcePath + file.at(0), deploymentPrefix + file.at(1));
}
-}
-void CMakeProject::uiEditorContentsChanged()
-{
- // cast sender, get filename
- if (!m_dirtyUic && isFormWindowEditor(sender()))
- m_dirtyUic = true;
+ t->setApplicationTargets(appTargetList);
+ t->setDeploymentData(deploymentData);
}
-void CMakeProject::buildStateChanged(ProjectExplorer::Project *project)
+void CMakeProject::createUiCodeModelSupport()
{
- if (project == this) {
- if (!ProjectExplorer::ProjectExplorerPlugin::instance()->buildManager()->isBuilding(this)) {
- QMap<QString, CMakeUiCodeModelSupport *>::const_iterator it, end;
- end = m_uiCodeModelSupport.constEnd();
- for (it = m_uiCodeModelSupport.constBegin(); it != end; ++it) {
- it.value()->updateFromBuild();
- }
- }
+ QHash<QString, QString> uiFileHash;
+
+ // Find all ui files
+ foreach (const QString &uiFile, m_files) {
+ if (uiFile.endsWith(QLatin1String(".ui")))
+ uiFileHash.insert(uiFile, uiHeaderFile(uiFile));
}
+
+ QtSupport::UiCodeModelManager::update(this, uiFileHash);
}
// CMakeFile
CMakeFile::CMakeFile(CMakeProject *parent, QString fileName)
- : Core::IDocument(parent), m_project(parent), m_fileName(fileName)
+ : Core::IDocument(parent), m_project(parent)
{
-
+ setFilePath(fileName);
}
bool CMakeFile::save(QString *errorString, const QString &fileName, bool autoSave)
@@ -908,11 +788,6 @@ bool CMakeFile::save(QString *errorString, const QString &fileName, bool autoSav
return false;
}
-QString CMakeFile::fileName() const
-{
- return m_fileName;
-}
-
QString CMakeFile::defaultPath() const
{
return QString();
@@ -939,13 +814,6 @@ bool CMakeFile::isSaveAsAllowed() const
return false;
}
-void CMakeFile::rename(const QString &newName)
-{
- Q_ASSERT(false);
- Q_UNUSED(newName);
- // Can't happen....
-}
-
Core::IDocument::ReloadBehavior CMakeFile::reloadBehavior(ChangeTrigger state, ChangeType type) const
{
Q_UNUSED(state)
@@ -987,8 +855,8 @@ CMakeBuildSettingsWidget::CMakeBuildSettingsWidget(CMakeBuildConfiguration *bc)
fl->addRow(tr("Build directory:"), hbox);
m_buildConfiguration = bc;
- m_pathLineEdit->setText(m_buildConfiguration->buildDirectory());
- if (m_buildConfiguration->buildDirectory() == bc->target()->project()->projectDirectory())
+ m_pathLineEdit->setText(m_buildConfiguration->rawBuildDirectory().toString());
+ if (m_buildConfiguration->buildDirectory().toString() == bc->target()->project()->projectDirectory())
m_changeButton->setEnabled(false);
else
m_changeButton->setEnabled(true);
@@ -999,12 +867,13 @@ CMakeBuildSettingsWidget::CMakeBuildSettingsWidget(CMakeBuildConfiguration *bc)
void CMakeBuildSettingsWidget::openChangeBuildDirectoryDialog()
{
CMakeProject *project = static_cast<CMakeProject *>(m_buildConfiguration->target()->project());
+ CMakeBuildInfo info(m_buildConfiguration);
CMakeOpenProjectWizard copw(project->projectManager(), CMakeOpenProjectWizard::ChangeDirectory,
- CMakeOpenProjectWizard::BuildInfo(m_buildConfiguration));
+ &info);
if (copw.exec() == QDialog::Accepted) {
project->changeBuildDirectory(m_buildConfiguration, copw.buildDirectory());
m_buildConfiguration->setUseNinja(copw.useNinja());
- m_pathLineEdit->setText(m_buildConfiguration->buildDirectory());
+ m_pathLineEdit->setText(m_buildConfiguration->rawBuildDirectory().toString());
}
}
@@ -1013,9 +882,9 @@ void CMakeBuildSettingsWidget::runCMake()
if (!ProjectExplorer::ProjectExplorerPlugin::instance()->saveModifiedFiles())
return;
CMakeProject *project = static_cast<CMakeProject *>(m_buildConfiguration->target()->project());
+ CMakeBuildInfo info(m_buildConfiguration);
CMakeOpenProjectWizard copw(project->projectManager(),
- CMakeOpenProjectWizard::WantToUpdate,
- CMakeOpenProjectWizard::BuildInfo(m_buildConfiguration));
+ CMakeOpenProjectWizard::WantToUpdate, &info);
if (copw.exec() == QDialog::Accepted)
project->parseCMakeLists();
}
@@ -1117,7 +986,7 @@ void CMakeCbpParser::parseBuildTargetOption()
if (attributes().hasAttribute(QLatin1String("output"))) {
m_buildTarget.executable = attributes().value(QLatin1String("output")).toString();
} else if (attributes().hasAttribute(QLatin1String("type"))) {
- const QString value = attributes().value(QLatin1String("type")).toString();
+ const QStringRef value = attributes().value(QLatin1String("type"));
if (value == QLatin1String("2") || value == QLatin1String("3"))
m_buildTarget.library = true;
} else if (attributes().hasAttribute(QLatin1String("working_dir"))) {
diff --git a/src/plugins/cmakeprojectmanager/cmakeproject.h b/src/plugins/cmakeprojectmanager/cmakeproject.h
index f19422dcfc..c950575e0f 100644
--- a/src/plugins/cmakeprojectmanager/cmakeproject.h
+++ b/src/plugins/cmakeprojectmanager/cmakeproject.h
@@ -58,7 +58,6 @@ namespace Internal {
class CMakeFile;
class CMakeBuildSettingsWidget;
-class CMakeUiCodeModelSupport;
struct CMakeBuildTarget
{
@@ -94,10 +93,8 @@ public:
CMakeBuildTarget buildTargetForTitle(const QString &title);
- QString shadowBuildDirectory(const QString &projectFilePath, const ProjectExplorer::Kit *k,
- const QString &bcName);
-
- QString uicCommand() const;
+ static QString shadowBuildDirectory(const QString &projectFilePath, const ProjectExplorer::Kit *k,
+ const QString &bcName);
bool isProjectFile(const QString &fileName);
@@ -119,27 +116,22 @@ private slots:
void activeTargetWasChanged(ProjectExplorer::Target *target);
void changeActiveBuildConfiguration(ProjectExplorer::BuildConfiguration*);
- void editorChanged(Core::IEditor *editor);
- void editorAboutToClose(Core::IEditor *editor);
- void uiEditorContentsChanged();
- void buildStateChanged(ProjectExplorer::Project *project);
void updateRunConfigurations();
private:
void buildTree(CMakeProjectNode *rootNode, QList<ProjectExplorer::FileNode *> list);
void gatherFileNodes(ProjectExplorer::FolderNode *parent, QList<ProjectExplorer::FileNode *> &list);
ProjectExplorer::FolderNode *findOrCreateFolder(CMakeProjectNode *rootNode, QString directory);
- void updateCodeModelSupportFromEditor(const QString &uiFileName, const QString &contents);
void createUiCodeModelSupport();
QString uiHeaderFile(const QString &uiFile);
void updateRunConfigurations(ProjectExplorer::Target *t);
+ void updateApplicationAndDeploymentTargets();
CMakeManager *m_manager;
ProjectExplorer::Target *m_activeTarget;
QString m_fileName;
CMakeFile *m_file;
QString m_projectName;
- QString m_uicCommand;
// TODO probably need a CMake specific node structure
CMakeProjectNode *m_rootNode;
@@ -148,10 +140,6 @@ private:
QFileSystemWatcher *m_watcher;
QSet<QString> m_watchedFiles;
QFuture<void> m_codeModelFuture;
-
- QMap<QString, CMakeUiCodeModelSupport *> m_uiCodeModelSupport;
- Core::IEditor *m_lastEditor;
- bool m_dirtyUic;
};
class CMakeCbpParser : public QXmlStreamReader
@@ -204,7 +192,6 @@ public:
CMakeFile(CMakeProject *parent, QString fileName);
bool save(QString *errorString, const QString &fileName, bool autoSave);
- QString fileName() const;
QString defaultPath() const;
QString suggestedFileName() const;
@@ -216,11 +203,8 @@ public:
ReloadBehavior reloadBehavior(ChangeTrigger state, ChangeType type) const;
bool reload(QString *errorString, ReloadFlag flag, ChangeType type);
- void rename(const QString &newName);
-
private:
CMakeProject *m_project;
- QString m_fileName;
};
class CMakeBuildSettingsWidget : public ProjectExplorer::NamedWidget
diff --git a/src/plugins/cmakeprojectmanager/cmakeprojectconstants.h b/src/plugins/cmakeprojectmanager/cmakeprojectconstants.h
index 040070d15b..19042982e1 100644
--- a/src/plugins/cmakeprojectmanager/cmakeprojectconstants.h
+++ b/src/plugins/cmakeprojectmanager/cmakeprojectconstants.h
@@ -40,6 +40,7 @@ const char CMAKE_EDITOR_DISPLAY_NAME[] = "CMake Editor";
const char C_CMAKEEDITOR[] = "CMakeProject.Context.CMakeEditor";
const char RUNCMAKE[] = "CMakeProject.RunCMake";
const char RUNCMAKECONTEXTMENU[] = "CMakeProject.RunCMakeContextMenu";
+const char CMAKE_SUPPORT_FEATURE[] = "CMake.CMakeSupport";
// Project
const char CMAKEPROJECT_ID[] = "CMakeProjectManager.CMakeProject";
diff --git a/src/plugins/cmakeprojectmanager/cmakeprojectmanager.cpp b/src/plugins/cmakeprojectmanager/cmakeprojectmanager.cpp
index 910d027ab8..b480c9b5db 100644
--- a/src/plugins/cmakeprojectmanager/cmakeprojectmanager.cpp
+++ b/src/plugins/cmakeprojectmanager/cmakeprojectmanager.cpp
@@ -121,8 +121,9 @@ void CMakeManager::runCMake(ProjectExplorer::Project *project)
CMakeBuildConfiguration *bc
= static_cast<CMakeBuildConfiguration *>(cmakeProject->activeTarget()->activeBuildConfiguration());
- CMakeOpenProjectWizard copw(this, CMakeOpenProjectWizard::WantToUpdate,
- CMakeOpenProjectWizard::BuildInfo(bc));
+ CMakeBuildInfo info(bc);
+
+ CMakeOpenProjectWizard copw(this, CMakeOpenProjectWizard::WantToUpdate, &info);
if (copw.exec() == QDialog::Accepted)
cmakeProject->parseCMakeLists();
}
diff --git a/src/plugins/cmakeprojectmanager/cmakeprojectmanager.pro b/src/plugins/cmakeprojectmanager/cmakeprojectmanager.pro
index 5a79a0676e..e0e8c8ce97 100644
--- a/src/plugins/cmakeprojectmanager/cmakeprojectmanager.pro
+++ b/src/plugins/cmakeprojectmanager/cmakeprojectmanager.pro
@@ -1,6 +1,7 @@
include(../../qtcreatorplugin.pri)
-HEADERS = cmakeproject.h \
+HEADERS = cmakebuildinfo.h \
+ cmakeproject.h \
cmakeprojectplugin.h \
cmakeprojectmanager.h \
cmakeprojectconstants.h \
@@ -12,10 +13,11 @@ HEADERS = cmakeproject.h \
cmakeeditorfactory.h \
cmakeeditor.h \
cmakehighlighter.h \
- cmakeuicodemodelsupport.h \
+ cmakehighlighterfactory.h \
cmakelocatorfilter.h \
cmakefilecompletionassist.h \
- cmakevalidator.h
+ cmakevalidator.h \
+ cmakeparser.h
SOURCES = cmakeproject.cpp \
cmakeprojectplugin.cpp \
@@ -28,9 +30,11 @@ SOURCES = cmakeproject.cpp \
cmakeeditorfactory.cpp \
cmakeeditor.cpp \
cmakehighlighter.cpp \
- cmakeuicodemodelsupport.cpp \
+ cmakehighlighterfactory.cpp \
cmakelocatorfilter.cpp \
cmakefilecompletionassist.cpp \
- cmakevalidator.cpp
+ cmakevalidator.cpp \
+ cmakeparser.cpp
+
RESOURCES += cmakeproject.qrc
diff --git a/src/plugins/cmakeprojectmanager/cmakeprojectmanager.qbs b/src/plugins/cmakeprojectmanager/cmakeprojectmanager.qbs
index 1d8ca15973..1734c6cc94 100644
--- a/src/plugins/cmakeprojectmanager/cmakeprojectmanager.qbs
+++ b/src/plugins/cmakeprojectmanager/cmakeprojectmanager.qbs
@@ -22,6 +22,7 @@ QtcPlugin {
"CMakeProjectManager.mimetypes.xml",
"cmakebuildconfiguration.cpp",
"cmakebuildconfiguration.h",
+ "cmakebuildinfo.h",
"cmakeeditor.cpp",
"cmakeeditor.h",
"cmakeeditorfactory.cpp",
@@ -30,10 +31,14 @@ QtcPlugin {
"cmakefilecompletionassist.h",
"cmakehighlighter.cpp",
"cmakehighlighter.h",
+ "cmakehighlighterfactory.cpp",
+ "cmakehighlighterfactory.h",
"cmakelocatorfilter.cpp",
"cmakelocatorfilter.h",
"cmakeopenprojectwizard.cpp",
"cmakeopenprojectwizard.h",
+ "cmakeparser.cpp",
+ "cmakeparser.h",
"cmakeproject.cpp",
"cmakeproject.h",
"cmakeproject.qrc",
@@ -46,8 +51,6 @@ QtcPlugin {
"cmakeprojectplugin.h",
"cmakerunconfiguration.cpp",
"cmakerunconfiguration.h",
- "cmakeuicodemodelsupport.cpp",
- "cmakeuicodemodelsupport.h",
"cmakevalidator.cpp",
"cmakevalidator.h",
"makestep.cpp",
diff --git a/src/plugins/cmakeprojectmanager/cmakeprojectnodes.cpp b/src/plugins/cmakeprojectmanager/cmakeprojectnodes.cpp
index 2d55f001e5..f4f35bd7e6 100644
--- a/src/plugins/cmakeprojectmanager/cmakeprojectnodes.cpp
+++ b/src/plugins/cmakeprojectmanager/cmakeprojectnodes.cpp
@@ -67,32 +67,28 @@ bool CMakeProjectNode::removeSubProjects(const QStringList &proFilePaths)
return false;
}
-bool CMakeProjectNode::addFiles(const ProjectExplorer::FileType fileType, const QStringList &filePaths, QStringList *notAdded)
+bool CMakeProjectNode::addFiles(const QStringList &filePaths, QStringList *notAdded)
{
- Q_UNUSED(fileType)
Q_UNUSED(filePaths)
Q_UNUSED(notAdded)
return false;
}
-bool CMakeProjectNode::removeFiles(const ProjectExplorer::FileType fileType, const QStringList &filePaths, QStringList *notRemoved)
+bool CMakeProjectNode::removeFiles(const QStringList &filePaths, QStringList *notRemoved)
{
- Q_UNUSED(fileType)
Q_UNUSED(filePaths)
Q_UNUSED(notRemoved)
return false;
}
-bool CMakeProjectNode::deleteFiles(const ProjectExplorer::FileType fileType, const QStringList &filePaths)
+bool CMakeProjectNode::deleteFiles(const QStringList &filePaths)
{
- Q_UNUSED(fileType)
Q_UNUSED(filePaths)
return false;
}
-bool CMakeProjectNode::renameFile(const ProjectExplorer::FileType fileType, const QString &filePath, const QString &newFilePath)
+bool CMakeProjectNode::renameFile(const QString &filePath, const QString &newFilePath)
{
- Q_UNUSED(fileType)
Q_UNUSED(filePath)
Q_UNUSED(newFilePath)
return false;
diff --git a/src/plugins/cmakeprojectmanager/cmakeprojectnodes.h b/src/plugins/cmakeprojectmanager/cmakeprojectnodes.h
index 68738baca9..ef81cfae49 100644
--- a/src/plugins/cmakeprojectmanager/cmakeprojectnodes.h
+++ b/src/plugins/cmakeprojectmanager/cmakeprojectnodes.h
@@ -48,17 +48,13 @@ public:
virtual bool addSubProjects(const QStringList &proFilePaths);
virtual bool removeSubProjects(const QStringList &proFilePaths);
- virtual bool addFiles(const ProjectExplorer::FileType fileType,
- const QStringList &filePaths,
+ virtual bool addFiles( const QStringList &filePaths,
QStringList *notAdded = 0);
- virtual bool removeFiles(const ProjectExplorer::FileType fileType,
- const QStringList &filePaths,
+ virtual bool removeFiles(const QStringList &filePaths,
QStringList *notRemoved = 0);
- virtual bool deleteFiles(const ProjectExplorer::FileType fileType,
- const QStringList &filePaths);
- virtual bool renameFile(const ProjectExplorer::FileType fileType,
- const QString &filePath,
- const QString &newFilePath);
+ virtual bool deleteFiles(const QStringList &filePaths);
+ virtual bool renameFile(const QString &filePath,
+ const QString &newFilePath);
virtual QList<ProjectExplorer::RunConfiguration *> runConfigurationsFor(Node *node);
};
diff --git a/src/plugins/cmakeprojectmanager/cmakeprojectplugin.cpp b/src/plugins/cmakeprojectmanager/cmakeprojectplugin.cpp
index 4022c4a99d..f72650ba4b 100644
--- a/src/plugins/cmakeprojectmanager/cmakeprojectplugin.cpp
+++ b/src/plugins/cmakeprojectmanager/cmakeprojectplugin.cpp
@@ -36,8 +36,9 @@
#include "cmakeprojectconstants.h"
#include "cmakelocatorfilter.h"
#include "cmakefilecompletionassist.h"
+#include "cmakehighlighterfactory.h"
-#include <coreplugin/icore.h>
+#include <coreplugin/featureprovider.h>
#include <coreplugin/mimedatabase.h>
#include <texteditor/texteditoractionhandler.h>
@@ -47,6 +48,16 @@
using namespace CMakeProjectManager::Internal;
+class CMakeFeatureProvider : public Core::IFeatureProvider
+{
+ Core::FeatureSet availableFeatures(const QString & /* platform */) const {
+ return Core::FeatureSet(Core::Id(CMakeProjectManager::Constants::CMAKE_SUPPORT_FEATURE));
+ }
+
+ QStringList availablePlatforms() const { return QStringList(); }
+ QString displayNameForPlatform(const QString & /* platform */) const { return QString(); }
+};
+
CMakeProjectPlugin::CMakeProjectPlugin()
{
}
@@ -57,7 +68,7 @@ CMakeProjectPlugin::~CMakeProjectPlugin()
bool CMakeProjectPlugin::initialize(const QStringList & /*arguments*/, QString *errorMessage)
{
- if (!Core::ICore::mimeDatabase()->addMimeTypes(QLatin1String(":cmakeproject/CMakeProjectManager.mimetypes.xml"), errorMessage))
+ if (!Core::MimeDatabase::addMimeTypes(QLatin1String(":cmakeproject/CMakeProjectManager.mimetypes.xml"), errorMessage))
return false;
CMakeSettingsPage *cmp = new CMakeSettingsPage();
addAutoReleasedObject(cmp);
@@ -70,6 +81,8 @@ bool CMakeProjectPlugin::initialize(const QStringList & /*arguments*/, QString *
addAutoReleasedObject(new CMakeEditorFactory(manager));
addAutoReleasedObject(new CMakeLocatorFilter);
addAutoReleasedObject(new CMakeFileCompletionAssistProvider(cmp));
+ addAutoReleasedObject(new CMakeFeatureProvider);
+ addAutoReleasedObject(new CMakeHighlighterFactory);
return true;
}
diff --git a/src/plugins/cmakeprojectmanager/cmakeprojectplugin.h b/src/plugins/cmakeprojectmanager/cmakeprojectplugin.h
index 855ec1abd7..f7a0e17553 100644
--- a/src/plugins/cmakeprojectmanager/cmakeprojectplugin.h
+++ b/src/plugins/cmakeprojectmanager/cmakeprojectplugin.h
@@ -50,6 +50,12 @@ public:
bool initialize(const QStringList &arguments, QString *errorMessage);
void extensionsInitialized();
+
+private slots:
+#ifdef WITH_TESTS
+ void testCMakeParser_data();
+ void testCMakeParser();
+#endif
};
} // namespace Internal
diff --git a/src/plugins/cmakeprojectmanager/cmakerunconfiguration.cpp b/src/plugins/cmakeprojectmanager/cmakerunconfiguration.cpp
index 0d9fa3dcfc..e256fbe4f0 100644
--- a/src/plugins/cmakeprojectmanager/cmakerunconfiguration.cpp
+++ b/src/plugins/cmakeprojectmanager/cmakerunconfiguration.cpp
@@ -283,7 +283,7 @@ CMakeRunConfigurationWidget::CMakeRunConfigurationWidget(CMakeRunConfiguration *
m_details->setLayout(fl);
QVBoxLayout *vbx = new QVBoxLayout(this);
- vbx->setMargin(0);;
+ vbx->setMargin(0);
vbx->addWidget(m_detailsContainer);
connect(m_workingDirectoryEdit, SIGNAL(changed(QString)),
diff --git a/src/plugins/cmakeprojectmanager/makestep.cpp b/src/plugins/cmakeprojectmanager/makestep.cpp
index c6be30d700..5059965132 100644
--- a/src/plugins/cmakeprojectmanager/makestep.cpp
+++ b/src/plugins/cmakeprojectmanager/makestep.cpp
@@ -29,16 +29,16 @@
#include "makestep.h"
+#include "cmakebuildconfiguration.h"
+#include "cmakeparser.h"
#include "cmakeprojectconstants.h"
#include "cmakeproject.h"
-#include "cmakebuildconfiguration.h"
#include <projectexplorer/buildsteplist.h>
#include <projectexplorer/deployconfiguration.h>
-#include <projectexplorer/gnumakeparser.h>
#include <projectexplorer/kitinformation.h>
-#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/projectexplorerconstants.h>
+#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/target.h>
#include <projectexplorer/toolchain.h>
@@ -108,6 +108,9 @@ void MakeStep::ctor()
this, SLOT(activeBuildConfigurationChanged()));
activeBuildConfigurationChanged();
}
+
+ connect(static_cast<CMakeProject *>(project()), SIGNAL(buildTargetsChanged()),
+ this, SLOT(buildTargetsChanged()));
}
MakeStep::~MakeStep()
@@ -137,6 +140,16 @@ void MakeStep::activeBuildConfigurationChanged()
}
}
+void MakeStep::buildTargetsChanged()
+{
+ QStringList filteredTargets;
+ foreach (const QString t, static_cast<CMakeProject *>(project())->buildTargetTitles()) {
+ if (m_buildTargets.contains(t))
+ filteredTargets.append(t);
+ }
+ setBuildTargets(filteredTargets);
+}
+
void MakeStep::setClean(bool clean)
{
m_clean = clean;
@@ -174,7 +187,7 @@ bool MakeStep::init()
if (!tc) {
m_tasks.append(Task(Task::Error, tr("Qt Creator needs a compiler set up to build. Configure a compiler in the kit options."),
Utils::FileName(), -1,
- Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM)));
+ ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM));
return true; // otherwise the tasks will not get reported
}
@@ -192,12 +205,12 @@ bool MakeStep::init()
if (m_useNinja && !env.value(QLatin1String("NINJA_STATUS")).startsWith(m_ninjaProgressString))
env.set(QLatin1String("NINJA_STATUS"), m_ninjaProgressString + QLatin1String("%o/sec] "));
pp->setEnvironment(env);
- pp->setWorkingDirectory(bc->buildDirectory());
+ pp->setWorkingDirectory(bc->buildDirectory().toString());
pp->setCommand(makeCommand(tc, bc->environment()));
pp->setArguments(arguments);
pp->resolveAll();
- setOutputParser(new ProjectExplorer::GnuMakeParser());
+ setOutputParser(new CMakeParser());
IOutputParser *parser = target()->kit()->createOutputParser();
if (parser)
appendOutputParser(parser);
@@ -237,7 +250,7 @@ void MakeStep::stdOutput(const QString &line)
{
if (m_percentProgress.indexIn(line) != -1) {
bool ok = false;
- int percent = m_percentProgress.cap(1).toInt(&ok);;
+ int percent = m_percentProgress.cap(1).toInt(&ok);
if (ok)
futureInterface()->setProgressValue(percent);
} else if (m_ninjaProgress.indexIn(line) != -1) {
@@ -274,12 +287,15 @@ void MakeStep::setBuildTarget(const QString &buildTarget, bool on)
old << buildTarget;
else if (!on && old.contains(buildTarget))
old.removeOne(buildTarget);
- m_buildTargets = old;
+ setBuildTargets(old);
}
void MakeStep::setBuildTargets(const QStringList &targets)
{
- m_buildTargets = targets;
+ if (targets != m_buildTargets) {
+ m_buildTargets = targets;
+ emit targetsToBuildChanged();
+ }
}
void MakeStep::clearBuildTargets()
@@ -336,7 +352,7 @@ MakeStepConfigWidget::MakeStepConfigWidget(MakeStep *makeStep)
fl->addRow(tr("Targets:"), m_buildTargetsList);
// TODO update this list also on rescans of the CMakeLists.txt
- CMakeProject *pro = static_cast<CMakeProject *>(m_makeStep->target()->project());
+ CMakeProject *pro = static_cast<CMakeProject *>(m_makeStep->project());
QStringList targetList = pro->buildTargetTitles();
targetList.sort();
foreach (const QString &buildTarget, targetList) {
@@ -352,8 +368,8 @@ MakeStepConfigWidget::MakeStepConfigWidget(MakeStep *makeStep)
connect(ProjectExplorer::ProjectExplorerPlugin::instance(), SIGNAL(settingsChanged()),
this, SLOT(updateDetails()));
- connect(pro, SIGNAL(buildTargetsChanged()),
- this, SLOT(buildTargetsChanged()));
+ connect(pro, SIGNAL(buildTargetsChanged()), this, SLOT(buildTargetsChanged()));
+ connect(m_makeStep, SIGNAL(targetsToBuildChanged()), this, SLOT(selectedBuildTargetsChanged()));
connect(pro, SIGNAL(environmentChanged()), this, SLOT(updateDetails()));
connect(m_makeStep, SIGNAL(makeCommandChanged()), this, SLOT(updateDetails()));
}
@@ -389,6 +405,17 @@ void MakeStepConfigWidget::buildTargetsChanged()
updateSummary();
}
+void MakeStepConfigWidget::selectedBuildTargetsChanged()
+{
+ disconnect(m_buildTargetsList, SIGNAL(itemChanged(QListWidgetItem*)), this, SLOT(itemChanged(QListWidgetItem*)));
+ for (int y = 0; y < m_buildTargetsList->count(); ++y) {
+ QListWidgetItem *item = m_buildTargetsList->itemAt(0, y);
+ item->setCheckState(m_makeStep->buildsBuildTarget(item->text()) ? Qt::Checked : Qt::Unchecked);
+ }
+ connect(m_buildTargetsList, SIGNAL(itemChanged(QListWidgetItem*)), this, SLOT(itemChanged(QListWidgetItem*)));
+ updateSummary();
+}
+
void MakeStepConfigWidget::updateDetails()
{
BuildConfiguration *bc = m_makeStep->buildConfiguration();
@@ -408,7 +435,7 @@ void MakeStepConfigWidget::updateDetails()
ProcessParameters param;
param.setMacroExpander(bc->macroExpander());
param.setEnvironment(bc->environment());
- param.setWorkingDirectory(bc->buildDirectory());
+ param.setWorkingDirectory(bc->buildDirectory().toString());
param.setCommand(m_makeStep->makeCommand(tc, bc->environment()));
param.setArguments(arguments);
m_summaryText = param.summary(displayName());
diff --git a/src/plugins/cmakeprojectmanager/makestep.h b/src/plugins/cmakeprojectmanager/makestep.h
index 9d3f972d39..1b03753c98 100644
--- a/src/plugins/cmakeprojectmanager/makestep.h
+++ b/src/plugins/cmakeprojectmanager/makestep.h
@@ -85,8 +85,12 @@ public slots:
void setUseNinja(bool);
void activeBuildConfigurationChanged();
+private slots:
+ void buildTargetsChanged();
+
signals:
void makeCommandChanged();
+ void targetsToBuildChanged();
protected:
void processStarted();
@@ -127,6 +131,8 @@ private slots:
void additionalArgumentsEdited();
void updateDetails();
void buildTargetsChanged();
+ void selectedBuildTargetsChanged();
+
private:
MakeStep *m_makeStep;
QListWidget *m_buildTargetsList;
diff --git a/src/plugins/coreplugin/Core.pluginspec.in b/src/plugins/coreplugin/Core.pluginspec.in
index aaa2c02ffb..3650a8add2 100644
--- a/src/plugins/coreplugin/Core.pluginspec.in
+++ b/src/plugins/coreplugin/Core.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"Core\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"Core\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/coreplugin/actionmanager/actioncontainer.cpp b/src/plugins/coreplugin/actionmanager/actioncontainer.cpp
index c5e23db1bc..e3567b2fbb 100644
--- a/src/plugins/coreplugin/actionmanager/actioncontainer.cpp
+++ b/src/plugins/coreplugin/actionmanager/actioncontainer.cpp
@@ -30,8 +30,8 @@
#include "actioncontainer_p.h"
#include "actionmanager.h"
-#include "coreconstants.h"
-#include "id.h"
+#include <coreplugin/coreconstants.h>
+#include <coreplugin/id.h>
#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
@@ -117,13 +117,13 @@ using namespace Core::Internal;
*/
/*!
- \fn QAction *ActionContainer::insertLocation(const Core::Id &group) const
+ \fn QAction *ActionContainer::insertLocation(const Id &group) const
Returns an action representing the \a group,
that could be used with \c{QWidget::insertAction}.
*/
/*!
- \fn void ActionContainer::appendGroup(const QString &identifier)
+ \fn void ActionContainer::appendGroup(const Id &group)
Adds a group with the given \a identifier to the action container. Using groups
you can segment your action container into logical parts and add actions and
menus directly to these parts.
@@ -132,7 +132,7 @@ using namespace Core::Internal;
*/
/*!
- \fn void ActionContainer::addAction(Core::Command *action, const Core::Id &group)
+ \fn void ActionContainer::addAction(Command *action, const Id &group = Id())
Add the \a action as a menu item to this action container. The action is added as the
last item of the specified \a group.
\sa appendGroup()
@@ -140,18 +140,13 @@ using namespace Core::Internal;
*/
/*!
- \fn void ActionContainer::addMenu(Core::ActionContainer *menu, const Core::Id &group)
+ \fn void ActionContainer::addMenu(ActionContainer *menu, const Id &group = Id())
Add the \a menu as a submenu to this action container. The menu is added as the
last item of the specified \a group.
\sa appendGroup()
\sa addAction()
*/
-/*!
- \fn ActionContainer::~ActionContainer()
- \internal
-*/
-
// ---------- ActionContainerPrivate ------------
/*!
diff --git a/src/plugins/coreplugin/actionmanager/actionmanager.cpp b/src/plugins/coreplugin/actionmanager/actionmanager.cpp
index 94a6236fb0..3bf3d902ca 100644
--- a/src/plugins/coreplugin/actionmanager/actionmanager.cpp
+++ b/src/plugins/coreplugin/actionmanager/actionmanager.cpp
@@ -29,10 +29,10 @@
#include "actionmanager.h"
#include "actionmanager_p.h"
-#include "mainwindow.h"
#include "actioncontainer_p.h"
#include "command_p.h"
-#include "id.h"
+#include <coreplugin/id.h>
+#include <coreplugin/mainwindow.h>
#include <utils/qtcassert.h>
@@ -141,15 +141,16 @@ using namespace Core::Internal;
*/
static ActionManager *m_instance = 0;
+static ActionManagerPrivate *d;
/*!
\internal
*/
ActionManager::ActionManager(QObject *parent)
- : QObject(parent),
- d(new ActionManagerPrivate())
+ : QObject(parent)
{
m_instance = this;
+ d = new ActionManagerPrivate;
}
/*!
@@ -179,8 +180,8 @@ ActionManager *ActionManager::instance()
*/
ActionContainer *ActionManager::createMenu(Id id)
{
- const ActionManagerPrivate::IdContainerMap::const_iterator it = m_instance->d->m_idContainerMap.constFind(id);
- if (it != m_instance->d->m_idContainerMap.constEnd())
+ const ActionManagerPrivate::IdContainerMap::const_iterator it = d->m_idContainerMap.constFind(id);
+ if (it != d->m_idContainerMap.constEnd())
return it.value();
QMenu *m = new QMenu(ICore::mainWindow());
@@ -189,8 +190,8 @@ ActionContainer *ActionManager::createMenu(Id id)
MenuActionContainer *mc = new MenuActionContainer(id);
mc->setMenu(m);
- m_instance->d->m_idContainerMap.insert(id, mc);
- connect(mc, SIGNAL(destroyed()), m_instance->d, SLOT(containerDestroyed()));
+ d->m_idContainerMap.insert(id, mc);
+ connect(mc, SIGNAL(destroyed()), d, SLOT(containerDestroyed()));
return mc;
}
@@ -204,8 +205,8 @@ ActionContainer *ActionManager::createMenu(Id id)
*/
ActionContainer *ActionManager::createMenuBar(Id id)
{
- const ActionManagerPrivate::IdContainerMap::const_iterator it = m_instance->d->m_idContainerMap.constFind(id);
- if (it != m_instance->d->m_idContainerMap.constEnd())
+ const ActionManagerPrivate::IdContainerMap::const_iterator it = d->m_idContainerMap.constFind(id);
+ if (it != d->m_idContainerMap.constEnd())
return it.value();
QMenuBar *mb = new QMenuBar; // No parent (System menu bar on Mac OS X)
@@ -214,8 +215,8 @@ ActionContainer *ActionManager::createMenuBar(Id id)
MenuBarActionContainer *mbc = new MenuBarActionContainer(id);
mbc->setMenuBar(mb);
- m_instance->d->m_idContainerMap.insert(id, mbc);
- connect(mbc, SIGNAL(destroyed()), m_instance->d, SLOT(containerDestroyed()));
+ d->m_idContainerMap.insert(id, mbc);
+ connect(mbc, SIGNAL(destroyed()), d, SLOT(containerDestroyed()));
return mbc;
}
@@ -233,7 +234,7 @@ ActionContainer *ActionManager::createMenuBar(Id id)
*/
Command *ActionManager::registerAction(QAction *action, Id id, const Context &context, bool scriptable)
{
- Action *a = m_instance->d->overridableAction(id);
+ Action *a = d->overridableAction(id);
if (a) {
a->addOverrideAction(action, context, scriptable);
emit m_instance->commandListChanged();
@@ -257,7 +258,7 @@ Command *ActionManager::registerShortcut(QShortcut *shortcut, Id id, const Conte
{
QTC_CHECK(!context.isEmpty());
Shortcut *sc = 0;
- if (CommandPrivate *c = m_instance->d->m_idCmdMap.value(id, 0)) {
+ if (CommandPrivate *c = d->m_idCmdMap.value(id, 0)) {
sc = qobject_cast<Shortcut *>(c);
if (!sc) {
qWarning() << "registerShortcut: id" << id.name()
@@ -266,7 +267,7 @@ Command *ActionManager::registerShortcut(QShortcut *shortcut, Id id, const Conte
}
} else {
sc = new Shortcut(id);
- m_instance->d->m_idCmdMap.insert(id, sc);
+ d->m_idCmdMap.insert(id, sc);
}
if (sc->shortcut()) {
@@ -274,7 +275,7 @@ Command *ActionManager::registerShortcut(QShortcut *shortcut, Id id, const Conte
return sc;
}
- if (!m_instance->d->hasContext(context))
+ if (!d->hasContext(context))
shortcut->setEnabled(false);
shortcut->setObjectName(id.toString());
shortcut->setParent(ICore::mainWindow());
@@ -287,7 +288,7 @@ Command *ActionManager::registerShortcut(QShortcut *shortcut, Id id, const Conte
emit m_instance->commandAdded(id.toString());
if (isPresentationModeEnabled())
- connect(sc->shortcut(), SIGNAL(activated()), m_instance->d, SLOT(shortcutTriggered()));
+ connect(sc->shortcut(), SIGNAL(activated()), d, SLOT(shortcutTriggered()));
return sc;
}
@@ -299,8 +300,8 @@ Command *ActionManager::registerShortcut(QShortcut *shortcut, Id id, const Conte
*/
Command *ActionManager::command(Id id)
{
- const ActionManagerPrivate::IdCmdMap::const_iterator it = m_instance->d->m_idCmdMap.constFind(id);
- if (it == m_instance->d->m_idCmdMap.constEnd()) {
+ const ActionManagerPrivate::IdCmdMap::const_iterator it = d->m_idCmdMap.constFind(id);
+ if (it == d->m_idCmdMap.constEnd()) {
if (warnAboutFindFailures)
qWarning() << "ActionManagerPrivate::command(): failed to find :"
<< id.name();
@@ -318,8 +319,8 @@ Command *ActionManager::command(Id id)
*/
ActionContainer *ActionManager::actionContainer(Id id)
{
- const ActionManagerPrivate::IdContainerMap::const_iterator it = m_instance->d->m_idContainerMap.constFind(id);
- if (it == m_instance->d->m_idContainerMap.constEnd()) {
+ const ActionManagerPrivate::IdContainerMap::const_iterator it = d->m_idContainerMap.constFind(id);
+ if (it == d->m_idContainerMap.constEnd()) {
if (warnAboutFindFailures)
qWarning() << "ActionManagerPrivate::actionContainer(): failed to find :"
<< id.name();
@@ -335,7 +336,7 @@ QList<Command *> ActionManager::commands()
{
// transform list of CommandPrivate into list of Command
QList<Command *> result;
- foreach (Command *cmd, m_instance->d->m_idCmdMap.values())
+ foreach (Command *cmd, d->m_idCmdMap.values())
result << cmd;
return result;
}
@@ -351,7 +352,7 @@ QList<Command *> ActionManager::commands()
void ActionManager::unregisterAction(QAction *action, Id id)
{
Action *a = 0;
- CommandPrivate *c = m_instance->d->m_idCmdMap.value(id, 0);
+ CommandPrivate *c = d->m_idCmdMap.value(id, 0);
QTC_ASSERT(c, return);
a = qobject_cast<Action *>(c);
if (!a) {
@@ -365,7 +366,7 @@ void ActionManager::unregisterAction(QAction *action, Id id)
// ActionContainers listen to the commands' destroyed signals
ICore::mainWindow()->removeAction(a->action());
delete a->action();
- m_instance->d->m_idCmdMap.remove(id);
+ d->m_idCmdMap.remove(id);
delete a;
}
emit m_instance->commandListChanged();
@@ -382,7 +383,7 @@ void ActionManager::unregisterAction(QAction *action, Id id)
void ActionManager::unregisterShortcut(Id id)
{
Shortcut *sc = 0;
- CommandPrivate *c = m_instance->d->m_idCmdMap.value(id, 0);
+ CommandPrivate *c = d->m_idCmdMap.value(id, 0);
QTC_ASSERT(c, return);
sc = qobject_cast<Shortcut *>(c);
if (!sc) {
@@ -391,7 +392,7 @@ void ActionManager::unregisterShortcut(Id id)
return;
}
delete sc->shortcut();
- m_instance->d->m_idCmdMap.remove(id);
+ d->m_idCmdMap.remove(id);
delete sc;
emit m_instance->commandListChanged();
}
@@ -406,38 +407,53 @@ void ActionManager::setPresentationModeEnabled(bool enabled)
foreach (Command *c, commands()) {
if (c->action()) {
if (enabled)
- connect(c->action(), SIGNAL(triggered()), m_instance->d, SLOT(actionTriggered()));
+ connect(c->action(), SIGNAL(triggered()), d, SLOT(actionTriggered()));
else
- disconnect(c->action(), SIGNAL(triggered()), m_instance->d, SLOT(actionTriggered()));
+ disconnect(c->action(), SIGNAL(triggered()), d, SLOT(actionTriggered()));
}
if (c->shortcut()) {
if (enabled)
- connect(c->shortcut(), SIGNAL(activated()), m_instance->d, SLOT(shortcutTriggered()));
+ connect(c->shortcut(), SIGNAL(activated()), d, SLOT(shortcutTriggered()));
else
- disconnect(c->shortcut(), SIGNAL(activated()), m_instance->d, SLOT(shortcutTriggered()));
+ disconnect(c->shortcut(), SIGNAL(activated()), d, SLOT(shortcutTriggered()));
}
}
// The label for the shortcuts:
- if (!m_instance->d->m_presentationLabel) {
- m_instance->d->m_presentationLabel = new QLabel(0, Qt::ToolTip | Qt::WindowStaysOnTopHint);
- QFont font = m_instance->d->m_presentationLabel->font();
+ if (!d->m_presentationLabel) {
+ d->m_presentationLabel = new QLabel(0, Qt::ToolTip | Qt::WindowStaysOnTopHint);
+ QFont font = d->m_presentationLabel->font();
font.setPixelSize(45);
- m_instance->d->m_presentationLabel->setFont(font);
- m_instance->d->m_presentationLabel->setAlignment(Qt::AlignCenter);
- m_instance->d->m_presentationLabel->setMargin(5);
+ d->m_presentationLabel->setFont(font);
+ d->m_presentationLabel->setAlignment(Qt::AlignCenter);
+ d->m_presentationLabel->setMargin(5);
- connect(&m_instance->d->m_presentationLabelTimer, SIGNAL(timeout()), m_instance->d->m_presentationLabel, SLOT(hide()));
+ connect(&d->m_presentationLabelTimer, SIGNAL(timeout()), d->m_presentationLabel, SLOT(hide()));
} else {
- m_instance->d->m_presentationLabelTimer.stop();
- delete m_instance->d->m_presentationLabel;
- m_instance->d->m_presentationLabel = 0;
+ d->m_presentationLabelTimer.stop();
+ delete d->m_presentationLabel;
+ d->m_presentationLabel = 0;
}
}
bool ActionManager::isPresentationModeEnabled()
{
- return m_instance->d->m_presentationLabel;
+ return d->m_presentationLabel;
+}
+
+void ActionManager::initialize()
+{
+ d->initialize();
+}
+
+void ActionManager::saveSettings(QSettings *settings)
+{
+ d->saveSettings(settings);
+}
+
+void ActionManager::setContext(const Context &context)
+{
+ d->setContext(context);
}
/*!
diff --git a/src/plugins/coreplugin/actionmanager/actionmanager.h b/src/plugins/coreplugin/actionmanager/actionmanager.h
index e459d0061b..f2d2019452 100644
--- a/src/plugins/coreplugin/actionmanager/actionmanager.h
+++ b/src/plugins/coreplugin/actionmanager/actionmanager.h
@@ -39,6 +39,7 @@
QT_BEGIN_NAMESPACE
class QAction;
+class QSettings;
class QShortcut;
class QString;
QT_END_NAMESPACE
@@ -47,10 +48,7 @@ namespace Core {
class ActionContainer;
-namespace Internal {
-class ActionManagerPrivate;
-class MainWindow;
-}
+namespace Internal { class MainWindow; }
class CORE_EXPORT ActionManager : public QObject
{
@@ -82,7 +80,9 @@ signals:
private:
ActionManager(QObject *parent = 0);
~ActionManager();
- Internal::ActionManagerPrivate *d;
+ void initialize();
+ void saveSettings(QSettings *settings);
+ void setContext(const Context &context);
friend class Core::Internal::MainWindow;
};
diff --git a/src/plugins/coreplugin/actionmanager/command.cpp b/src/plugins/coreplugin/actionmanager/command.cpp
index 66b07f030e..b7b2eb0300 100644
--- a/src/plugins/coreplugin/actionmanager/command.cpp
+++ b/src/plugins/coreplugin/actionmanager/command.cpp
@@ -29,8 +29,8 @@
#include "command_p.h"
-#include "icontext.h"
-#include "id.h"
+#include <coreplugin/icontext.h>
+#include <coreplugin/id.h>
#include <utils/hostosinfo.h>
@@ -200,11 +200,6 @@
interact with it.
*/
-/*!
- \fn Command::~Command()
- \internal
-*/
-
using namespace Core;
using namespace Core::Internal;
diff --git a/src/plugins/coreplugin/actionmanager/commandmappings.cpp b/src/plugins/coreplugin/actionmanager/commandmappings.cpp
index b3cb20f23f..ee17ff370f 100644
--- a/src/plugins/coreplugin/actionmanager/commandmappings.cpp
+++ b/src/plugins/coreplugin/actionmanager/commandmappings.cpp
@@ -28,9 +28,9 @@
****************************************************************************/
#include "commandmappings.h"
-#include "shortcutsettings.h"
#include "ui_commandmappings.h"
#include "commandsfile.h"
+#include <coreplugin/dialogs/shortcutsettings.h>
#include <utils/hostosinfo.h>
#include <utils/headerviewstretcher.h>
diff --git a/src/plugins/coreplugin/actionmanager/commandsfile.cpp b/src/plugins/coreplugin/actionmanager/commandsfile.cpp
index a75ce5c80e..5d91694862 100644
--- a/src/plugins/coreplugin/actionmanager/commandsfile.cpp
+++ b/src/plugins/coreplugin/actionmanager/commandsfile.cpp
@@ -28,8 +28,8 @@
****************************************************************************/
#include "commandsfile.h"
-#include "shortcutsettings.h"
#include "command_p.h"
+#include <coreplugin/dialogs/shortcutsettings.h>
#include <app/app_version.h>
diff --git a/src/plugins/coreplugin/basefilewizard.cpp b/src/plugins/coreplugin/basefilewizard.cpp
index 1a6f6a9756..eb11eba5c1 100644
--- a/src/plugins/coreplugin/basefilewizard.cpp
+++ b/src/plugins/coreplugin/basefilewizard.cpp
@@ -63,189 +63,6 @@ static int indexOfFile(const GeneratedFiles &f, const QString &path)
return -1;
}
-// ------------ BaseFileWizardParameterData
-class BaseFileWizardParameterData : public QSharedData
-{
-public:
- explicit BaseFileWizardParameterData(IWizard::WizardKind kind = IWizard::FileWizard);
- void clear();
-
- IWizard::WizardKind kind;
- QIcon icon;
- QString description;
- QString displayName;
- QString id;
- QString category;
- QString displayCategory;
- Core::FeatureSet requiredFeatures;
- Core::IWizard::WizardFlags flags;
- QString descriptionImage;
-};
-
-BaseFileWizardParameterData::BaseFileWizardParameterData(IWizard::WizardKind k) :
- kind(k)
-{
-}
-
-void BaseFileWizardParameterData::clear()
-{
- kind = IWizard::FileWizard;
- icon = QIcon();
- description.clear();
- displayName.clear();
- id.clear();
- category.clear();
- displayCategory.clear();
-}
-
-/*!
- \class Core::BaseFileWizardParameters
- \brief The BaseFileWizardParameters class is a parameter class for
- passing parameters to instances of the class Wizard containing name, icon,
- and so on.
-
- \sa Core::GeneratedFile, Core::BaseFileWizard, Core::StandardFileWizard
- \sa Core::Internal::WizardEventLoop
-*/
-
-BaseFileWizardParameters::BaseFileWizardParameters(IWizard::WizardKind kind) :
- m_d(new BaseFileWizardParameterData(kind))
-{
-}
-
-BaseFileWizardParameters::BaseFileWizardParameters(const BaseFileWizardParameters &rhs) :
- m_d(rhs.m_d)
-{
-}
-
-BaseFileWizardParameters &BaseFileWizardParameters::operator=(const BaseFileWizardParameters &rhs)
-{
- if (this != &rhs)
- m_d.operator=(rhs.m_d);
- return *this;
-}
-
-BaseFileWizardParameters::~BaseFileWizardParameters()
-{
-}
-
-void BaseFileWizardParameters::clear()
-{
- m_d->clear();
-}
-
-CORE_EXPORT QDebug operator<<(QDebug d, const BaseFileWizardParameters &p)
-{
- d.nospace() << "Kind: " << p.kind() << " Id: " << p.id()
- << " Category: " << p.category()
- << " DisplayName: " << p.displayName()
- << " Description: " << p.description()
- << " DisplayCategory: " << p.displayCategory()
- << " Required Features: " << p.requiredFeatures().toStringList();
- return d;
-}
-
-IWizard::WizardKind BaseFileWizardParameters::kind() const
-{
- return m_d->kind;
-}
-
-void BaseFileWizardParameters::setKind(IWizard::WizardKind k)
-{
- m_d->kind = k;
-}
-
-QIcon BaseFileWizardParameters::icon() const
-{
- return m_d->icon;
-}
-
-void BaseFileWizardParameters::setIcon(const QIcon &icon)
-{
- m_d->icon = icon;
-}
-
-QString BaseFileWizardParameters::description() const
-{
- return m_d->description;
-}
-
-void BaseFileWizardParameters::setDescription(const QString &v)
-{
- m_d->description = v;
-}
-
-QString BaseFileWizardParameters::displayName() const
-{
- return m_d->displayName;
-}
-
-void BaseFileWizardParameters::setDisplayName(const QString &v)
-{
- m_d->displayName = v;
-}
-
-QString BaseFileWizardParameters::id() const
-{
- return m_d->id;
-}
-
-void BaseFileWizardParameters::setId(const QString &v)
-{
- m_d->id = v;
-}
-
-QString BaseFileWizardParameters::category() const
-{
- return m_d->category;
-}
-
-void BaseFileWizardParameters::setCategory(const QString &v)
-{
- m_d->category = v;
-}
-
-QString BaseFileWizardParameters::displayCategory() const
-{
- return m_d->displayCategory;
-}
-
-Core::FeatureSet BaseFileWizardParameters::requiredFeatures() const
-{
- return m_d->requiredFeatures;
-}
-
-void BaseFileWizardParameters::setRequiredFeatures(Core::FeatureSet features)
-{
-
- m_d->requiredFeatures = features;
-}
-
-void BaseFileWizardParameters::setDisplayCategory(const QString &v)
-{
- m_d->displayCategory = v;
-}
-
-Core::IWizard::WizardFlags BaseFileWizardParameters::flags() const
-{
- return m_d->flags;
-}
-
-void BaseFileWizardParameters::setFlags(Core::IWizard::WizardFlags flags)
-{
- m_d->flags = flags;
-}
-
-QString BaseFileWizardParameters::descriptionImage() const
-{
- return m_d->descriptionImage;
-}
-
-void BaseFileWizardParameters::setDescriptionImage(const QString &path)
-{
- m_d->descriptionImage = path;
-}
-
/*!
\class Core::Internal::WizardEventLoop
\brief The WizardEventLoop class implements a special event
@@ -359,72 +176,15 @@ void WizardEventLoop::rejected()
\sa Core::Internal::WizardEventLoop
*/
-struct BaseFileWizardPrivate
-{
- explicit BaseFileWizardPrivate(const Core::BaseFileWizardParameters &parameters)
- : m_parameters(parameters), m_wizardDialog(0)
- {}
-
- const Core::BaseFileWizardParameters m_parameters;
- QWizard *m_wizardDialog;
-};
-// ---------------- Wizard
-BaseFileWizard::BaseFileWizard(const BaseFileWizardParameters &parameters,
- QObject *parent) :
- IWizard(parent),
- d(new BaseFileWizardPrivate(parameters))
+BaseFileWizard::BaseFileWizard(QObject *parent) :
+ IWizard(parent)
{
}
-BaseFileWizardParameters BaseFileWizard::baseFileWizardParameters() const
-{
- return d->m_parameters;
-}
BaseFileWizard::~BaseFileWizard()
{
- delete d;
-}
-
-IWizard::WizardKind BaseFileWizard::kind() const
-{
- return d->m_parameters.kind();
-}
-
-QIcon BaseFileWizard::icon() const
-{
- return d->m_parameters.icon();
-}
-
-QString BaseFileWizard::description() const
-{
- return d->m_parameters.description();
-}
-
-QString BaseFileWizard::displayName() const
-{
- return d->m_parameters.displayName();
-}
-
-QString BaseFileWizard::id() const
-{
- return d->m_parameters.id();
-}
-
-QString BaseFileWizard::category() const
-{
- return d->m_parameters.category();
-}
-
-QString BaseFileWizard::displayCategory() const
-{
- return d->m_parameters.displayCategory();
-}
-
-QString BaseFileWizard::descriptionImage() const
-{
- return d->m_parameters.descriptionImage();
}
void BaseFileWizard::runWizard(const QString &path, QWidget *parent, const QString &platform, const QVariantMap &extraValues)
@@ -537,8 +297,8 @@ void BaseFileWizard::runWizard(const QString &path, QWidget *parent, const QStri
if (removeOpenProjectAttribute) {
for (int i = 0; i < files.count(); i++) {
- if (files[i].attributes() & Core::GeneratedFile::OpenProjectAttribute)
- files[i].setAttributes(Core::GeneratedFile::OpenEditorAttribute);
+ if (files[i].attributes() & GeneratedFile::OpenProjectAttribute)
+ files[i].setAttributes(GeneratedFile::OpenEditorAttribute);
}
}
@@ -548,17 +308,6 @@ void BaseFileWizard::runWizard(const QString &path, QWidget *parent, const QStri
QMessageBox::critical(0, tr("File Generation Failure"), errorMessage);
}
-
-Core::FeatureSet BaseFileWizard::requiredFeatures() const
-{
- return d->m_parameters.requiredFeatures();
-}
-
-Core::IWizard::WizardFlags BaseFileWizard::flags() const
-{
- return d->m_parameters.flags();
-}
-
/*!
\fn virtual QWizard *Core::BaseFileWizard::createWizardDialog(QWidget *parent,
const WizardDialogParameters &wizardDialogParameters) const
@@ -652,9 +401,9 @@ bool BaseFileWizard::postGenerateFiles(const QWizard *, const GeneratedFiles &l,
bool BaseFileWizard::postGenerateOpenEditors(const GeneratedFiles &l, QString *errorMessage)
{
- foreach (const Core::GeneratedFile &file, l) {
- if (file.attributes() & Core::GeneratedFile::OpenEditorAttribute) {
- if (!Core::EditorManager::openEditor(file.path(), file.editorId())) {
+ foreach (const GeneratedFile &file, l) {
+ if (file.attributes() & GeneratedFile::OpenEditorAttribute) {
+ if (!EditorManager::openEditor(file.path(), file.editorId())) {
if (errorMessage)
*errorMessage = tr("Failed to open an editor for '%1'.").arg(QDir::toNativeSeparators(file.path()));
return false;
@@ -777,7 +526,7 @@ QString BaseFileWizard::buildFileName(const QString &path,
QString BaseFileWizard::preferredSuffix(const QString &mimeType)
{
- const QString rc = Core::ICore::mimeDatabase()->preferredSuffixByType(mimeType);
+ const QString rc = MimeDatabase::preferredSuffixByType(mimeType);
if (rc.isEmpty())
qWarning("%s: WARNING: Unable to find a preferred suffix for %s.",
Q_FUNC_INFO, mimeType.toUtf8().constData());
@@ -803,9 +552,8 @@ QString BaseFileWizard::preferredSuffix(const QString &mimeType)
Creates the files with the \a name under the \a path.
*/
-StandardFileWizard::StandardFileWizard(const BaseFileWizardParameters &parameters,
- QObject *parent) :
- BaseFileWizard(parameters, parent)
+StandardFileWizard::StandardFileWizard(QObject *parent) :
+ BaseFileWizard(parent)
{
}
diff --git a/src/plugins/coreplugin/basefilewizard.h b/src/plugins/coreplugin/basefilewizard.h
index 90a231e274..d8005242c4 100644
--- a/src/plugins/coreplugin/basefilewizard.h
+++ b/src/plugins/coreplugin/basefilewizard.h
@@ -48,64 +48,10 @@ class QWizardPage;
class QDebug;
QT_END_NAMESPACE
-namespace Utils {
- class Wizard;
-}
+namespace Utils { class Wizard; }
namespace Core {
-class IEditor;
-class IFileWizardExtension;
-
-class BaseFileWizardParameterData;
-struct BaseFileWizardPrivate;
-
-class CORE_EXPORT BaseFileWizardParameters
-{
-public:
- explicit BaseFileWizardParameters(IWizard::WizardKind kind = IWizard::FileWizard);
- BaseFileWizardParameters(const BaseFileWizardParameters &);
- BaseFileWizardParameters &operator=(const BaseFileWizardParameters&);
- ~BaseFileWizardParameters();
-
- void clear();
-
- IWizard::WizardKind kind() const;
- void setKind(IWizard::WizardKind k);
-
- QIcon icon() const;
- void setIcon(const QIcon &icon);
-
- QString description() const;
- void setDescription(const QString &description);
-
- QString displayName() const;
- void setDisplayName(const QString &name);
-
- QString id() const;
- void setId(const QString &id);
-
- QString category() const;
- void setCategory(const QString &category);
-
- QString displayCategory() const;
- void setDisplayCategory(const QString &trCategory);
-
- Core::FeatureSet requiredFeatures() const;
- void setRequiredFeatures(Core::FeatureSet features);
-
- Core::IWizard::WizardFlags flags() const;
- void setFlags(Core::IWizard::WizardFlags flags);
-
- QString descriptionImage() const;
- void setDescriptionImage(const QString &path);
-
-private:
- QSharedDataPointer<BaseFileWizardParameterData> m_d;
-};
-
-CORE_EXPORT QDebug operator<<(QDebug d, const BaseFileWizardParameters &);
-
class CORE_EXPORT WizardDialogParameters
{
public:
@@ -163,20 +109,7 @@ public:
virtual ~BaseFileWizard();
// IWizard
- virtual WizardKind kind() const;
- virtual QIcon icon() const;
- virtual QString description() const;
- virtual QString displayName() const;
- virtual QString id() const;
-
- virtual QString category() const;
- virtual QString displayCategory() const;
-
- virtual QString descriptionImage() const;
-
virtual void runWizard(const QString &path, QWidget *parent, const QString &platform, const QVariantMap &extraValues);
- virtual Core::FeatureSet requiredFeatures() const;
- virtual WizardFlags flags() const;
static QString buildFileName(const QString &path, const QString &baseName, const QString &extension);
static void setupWizard(QWizard *);
@@ -185,9 +118,7 @@ public:
protected:
typedef QList<QWizardPage *> WizardPageList;
- explicit BaseFileWizard(const BaseFileWizardParameters &parameters, QObject *parent = 0);
-
- BaseFileWizardParameters baseFileWizardParameters() const;
+ explicit BaseFileWizard(QObject *parent = 0);
virtual QWizard *createWizardDialog(QWidget *parent,
const WizardDialogParameters &wizardDialogParameters) const = 0;
@@ -205,9 +136,6 @@ protected:
OverwriteResult promptOverwrite(GeneratedFiles *files,
QString *errorMessage) const;
static bool postGenerateOpenEditors(const GeneratedFiles &l, QString *errorMessage = 0);
-
-private:
- BaseFileWizardPrivate *d;
};
class CORE_EXPORT StandardFileWizard : public BaseFileWizard
@@ -215,25 +143,13 @@ class CORE_EXPORT StandardFileWizard : public BaseFileWizard
Q_OBJECT
protected:
- explicit StandardFileWizard(const BaseFileWizardParameters &parameters, QObject *parent = 0);
+ explicit StandardFileWizard(QObject *parent = 0);
virtual QWizard *createWizardDialog(QWidget *parent, const WizardDialogParameters &wizardDialogParameters) const;
virtual GeneratedFiles generateFiles(const QWizard *w, QString *errorMessage) const;
virtual GeneratedFiles generateFilesFromPath(const QString &path, const QString &name,
QString *errorMessage) const = 0;
};
-template <class WizardClass>
-QList<WizardClass*> createMultipleBaseFileWizardInstances(const QList<BaseFileWizardParameters> &parametersList, ExtensionSystem::IPlugin *plugin)
-{
- QList<WizardClass*> list;
- foreach (const BaseFileWizardParameters &parameters, parametersList) {
- WizardClass *wc = new WizardClass(parameters, 0);
- plugin->addAutoReleasedObject(wc);
- list << wc;
- }
- return list;
-}
-
} // namespace Core
Q_DECLARE_OPERATORS_FOR_FLAGS(Core::GeneratedFile::Attributes)
diff --git a/src/plugins/coreplugin/core.qrc b/src/plugins/coreplugin/core.qrc
index abe566a13a..d54182e37b 100644
--- a/src/plugins/coreplugin/core.qrc
+++ b/src/plugins/coreplugin/core.qrc
@@ -73,5 +73,7 @@
<file>images/splitbutton_closetop.png</file>
<file>images/splitbutton_vertical.png</file>
<file>images/panel_manage_button.png</file>
+ <file>images/sidebysidediff.png</file>
+ <file>images/textdiff.png</file>
</qresource>
</RCC>
diff --git a/src/plugins/coreplugin/coreconstants.h b/src/plugins/coreplugin/coreconstants.h
index 85f219b987..18430d2362 100644
--- a/src/plugins/coreplugin/coreconstants.h
+++ b/src/plugins/coreplugin/coreconstants.h
@@ -114,6 +114,7 @@ const char CLOSE[] = "QtCreator.Close";
const char CLOSE_ALTERNATIVE[] = "QtCreator.Close_Alternative"; // temporary, see QTCREATORBUG-72
const char CLOSEALL[] = "QtCreator.CloseAll";
const char CLOSEOTHERS[] = "QtCreator.CloseOthers";
+const char CLOSEALLEXCEPTVISIBLE[] = "QtCreator.CloseAllExceptVisible";
const char GOTONEXT[] = "QtCreator.GotoNext";
const char GOTOPREV[] = "QtCreator.GotoPrevious";
const char GOTONEXTINHISTORY[] = "QtCreator.GotoNextInHistory";
@@ -204,6 +205,8 @@ const char ICON_CLOSE_SPLIT_TOP[] = ":/core/images/splitbutton_closetop.png";
const char ICON_CLOSE_SPLIT_BOTTOM[] = ":/core/images/splitbutton_closebottom.png";
const char ICON_CLOSE_SPLIT_LEFT[] = ":/core/images/splitbutton_closeleft.png";
const char ICON_CLOSE_SPLIT_RIGHT[] = ":/core/images/splitbutton_closeright.png";
+const char ICON_SIDE_BY_SIDE_DIFF[] = ":/core/images/sidebysidediff.png";
+const char ICON_TEXT_DIFF[] = ":/core/images/textdiff.png";
const char ICON_FILTER[] = ":/core/images/filtericon.png";
const char ICON_LINK[] = ":/core/images/linkicon.png";
const char ICON_QTLOGO_32[] = ":/core/images/logo/32/QtProject-qtcreator.png";
diff --git a/src/plugins/coreplugin/coreplugin.cpp b/src/plugins/coreplugin/coreplugin.cpp
index fd0b1cc97a..ffd5242f03 100644
--- a/src/plugins/coreplugin/coreplugin.cpp
+++ b/src/plugins/coreplugin/coreplugin.cpp
@@ -28,16 +28,15 @@
****************************************************************************/
#include "coreplugin.h"
-#include "actionmanager.h"
#include "designmode.h"
#include "editmode.h"
-#include "editormanager.h"
-#include "fileiconprovider.h"
#include "helpmanager.h"
#include "mainwindow.h"
#include "mimedatabase.h"
#include "modemanager.h"
#include "infobar.h"
+#include <coreplugin/actionmanager/actionmanager.h>
+#include <coreplugin/editormanager/editormanager.h>
#include <utils/savefile.h>
@@ -48,9 +47,10 @@
using namespace Core;
using namespace Core::Internal;
-CorePlugin::CorePlugin() :
- m_mainWindow(new MainWindow), m_editMode(0), m_designMode(0)
+CorePlugin::CorePlugin() : m_editMode(0), m_designMode(0)
{
+ qRegisterMetaType<Core::Id>();
+ m_mainWindow = new MainWindow;
}
CorePlugin::~CorePlugin()
@@ -66,9 +66,6 @@ CorePlugin::~CorePlugin()
delete m_designMode;
}
- // delete FileIconProvider singleton
- delete FileIconProvider::instance();
-
delete m_mainWindow;
}
@@ -106,7 +103,7 @@ bool CorePlugin::initialize(const QStringList &arguments, QString *errorMessage)
void CorePlugin::extensionsInitialized()
{
- m_mainWindow->mimeDatabase()->syncUserModifiedMimeTypes();
+ MimeDatabase::syncUserModifiedMimeTypes();
if (m_designMode->designModeIsRequired())
addObject(m_designMode);
m_mainWindow->extensionsInitialized();
@@ -114,7 +111,7 @@ void CorePlugin::extensionsInitialized()
bool CorePlugin::delayedInitialize()
{
- HelpManager::instance()->setupHelpManager();
+ HelpManager::setupHelpManager();
return true;
}
diff --git a/src/plugins/coreplugin/coreplugin.pro b/src/plugins/coreplugin/coreplugin.pro
index accc477d71..fbcb6d7990 100644
--- a/src/plugins/coreplugin/coreplugin.pro
+++ b/src/plugins/coreplugin/coreplugin.pro
@@ -12,11 +12,6 @@ greaterThan(QT_MAJOR_VERSION, 4) {
include(../../qtcreatorplugin.pri)
include(../../shared/scriptwrapper/scriptwrapper.pri)
win32-msvc*:QMAKE_CXXFLAGS += -wd4251 -wd4290 -wd4250
-INCLUDEPATH += dialogs \
- actionmanager \
- editormanager \
- progressmanager \
- scriptmanager
SOURCES += mainwindow.cpp \
editmode.cpp \
tabpositionindicator.cpp \
@@ -34,7 +29,7 @@ SOURCES += mainwindow.cpp \
versiondialog.cpp \
editormanager/editormanager.cpp \
editormanager/editorview.cpp \
- editormanager/openeditorsmodel.cpp \
+ editormanager/documentmodel.cpp \
editormanager/openeditorsview.cpp \
editormanager/openeditorswindow.cpp \
editormanager/ieditorfactory.cpp \
@@ -55,7 +50,6 @@ SOURCES += mainwindow.cpp \
progressmanager/progressview.cpp \
progressmanager/progressbar.cpp \
progressmanager/futureprogress.cpp \
- scriptmanager/scriptmanager.cpp \
statusbarwidget.cpp \
coreplugin.cpp \
variablemanager.cpp \
@@ -101,6 +95,7 @@ SOURCES += mainwindow.cpp \
documentmanager.cpp \
removefiledialog.cpp \
iversioncontrol.cpp \
+ dialogs/addtovcsdialog.cpp \
icorelistener.cpp
HEADERS += mainwindow.h \
@@ -118,7 +113,7 @@ HEADERS += mainwindow.h \
statusbarmanager.h \
editormanager/editormanager.h \
editormanager/editorview.h \
- editormanager/openeditorsmodel.h \
+ editormanager/documentmodel.h \
editormanager/openeditorsview.h \
editormanager/openeditorswindow.h \
editormanager/ieditor.h \
@@ -156,9 +151,6 @@ HEADERS += mainwindow.h \
ifilewizardextension.h \
icorelistener.h \
versiondialog.h \
- scriptmanager/metatypedeclarations.h \
- scriptmanager/scriptmanager.h \
- scriptmanager/scriptmanager_p.h \
core_global.h \
statusbarwidget.h \
coreplugin.h \
@@ -200,7 +192,8 @@ HEADERS += mainwindow.h \
idocumentfactory.h \
textdocument.h \
documentmanager.h \
- removefiledialog.h
+ removefiledialog.h \
+ dialogs/addtovcsdialog.h
FORMS += dialogs/newdialog.ui \
actionmanager/commandmappings.ui \
@@ -212,7 +205,8 @@ FORMS += dialogs/newdialog.ui \
variablechooser.ui \
mimetypesettingspage.ui \
mimetypemagicdialog.ui \
- removefiledialog.ui
+ removefiledialog.ui \
+ dialogs/addtovcsdialog.ui
RESOURCES += core.qrc \
fancyactionbar.qrc
@@ -243,6 +237,8 @@ else:unix {
OTHER_FILES += editormanager/BinFiles.mimetypes.xml
equals(TEST, 1) {
- SOURCES += plugintestutils.cpp
- HEADERS += plugintestutils.h
+ SOURCES += testdatadir.cpp \
+ plugintestutils.cpp
+ HEADERS += testdatadir.h \
+ plugintestutils.h
}
diff --git a/src/plugins/coreplugin/coreplugin.qbs b/src/plugins/coreplugin/coreplugin.qbs
index 374da3f4d4..8220b10104 100644
--- a/src/plugins/coreplugin/coreplugin.qbs
+++ b/src/plugins/coreplugin/coreplugin.qbs
@@ -8,23 +8,13 @@ QtcPlugin {
Depends {
name: "Qt"
submodules: [
- "core", "widgets", "xml", "network", "script", "sql", "help", "printsupport"
+ "widgets", "xml", "network", "script", "sql", "help", "printsupport"
]
}
Depends { name: "Utils" }
Depends { name: "Aggregation" }
Depends { name: "app_version_header" }
- cpp.includePaths: base.concat([
- "../..",
- "../../shared/scriptwrapper",
- "dialogs",
- "editormanager",
- "progressmanager",
- "scriptmanager",
- "actionmanager"
- ])
-
cpp.dynamicLibraries: {
if (qbs.targetOS.contains("windows")) return [
"ole32",
@@ -34,204 +24,133 @@ QtcPlugin {
cpp.frameworks: qbs.targetOS.contains("osx") ? ["AppKit"] : undefined
- files: [
- "basefilewizard.cpp",
- "basefilewizard.h",
- "core.qrc",
- "core_global.h",
- "coreconstants.h",
- "coreplugin.cpp",
- "coreplugin.h",
- "designmode.cpp",
- "designmode.h",
- "documentmanager.cpp",
- "documentmanager.h",
- "editmode.cpp",
- "editmode.h",
- "editortoolbar.cpp",
- "editortoolbar.h",
- "externaltool.cpp",
- "externaltool.h",
- "externaltoolmanager.h",
- "fancyactionbar.cpp",
- "fancyactionbar.h",
- "fancyactionbar.qrc",
- "fancytabwidget.cpp",
- "fancytabwidget.h",
- "featureprovider.cpp",
- "featureprovider.h",
- "fileiconprovider.cpp",
- "fileiconprovider.h",
- "fileutils.cpp",
- "fileutils.h",
- "findplaceholder.cpp",
- "findplaceholder.h",
- "generalsettings.cpp",
- "generalsettings.h",
- "generalsettings.ui",
- "generatedfile.cpp",
- "generatedfile.h",
- "helpmanager.cpp",
- "helpmanager.h",
- "icontext.cpp",
- "icontext.h",
- "icore.cpp",
- "icore.h",
- "icorelistener.cpp",
- "icorelistener.h",
- "id.cpp",
- "id.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",
- "manhattanstyle.h",
- "messagemanager.cpp",
- "messagemanager.h",
- "messageoutputwindow.cpp",
- "messageoutputwindow.h",
- "mimedatabase.cpp",
- "mimedatabase.h",
- "mimetypemagicdialog.cpp",
- "mimetypemagicdialog.h",
- "mimetypemagicdialog.ui",
- "mimetypesettings.cpp",
- "mimetypesettings.h",
- "mimetypesettingspage.ui",
- "minisplitter.cpp",
- "minisplitter.h",
- "modemanager.cpp",
- "modemanager.h",
- "navigationsubwidget.cpp",
- "navigationsubwidget.h",
- "navigationwidget.cpp",
- "navigationwidget.h",
- "outputpane.cpp",
- "outputpane.h",
- "outputpanemanager.cpp",
- "outputpanemanager.h",
- "outputwindow.cpp",
- "outputwindow.h",
- "plugindialog.cpp",
- "plugindialog.h",
- "removefiledialog.cpp",
- "removefiledialog.h",
- "removefiledialog.ui",
- "rightpane.cpp",
- "rightpane.h",
- "settingsdatabase.cpp",
- "settingsdatabase.h",
- "sidebar.cpp",
- "sidebar.h",
- "sidebarwidget.cpp",
- "sidebarwidget.h",
- "statusbarmanager.cpp",
- "statusbarmanager.h",
- "statusbarwidget.cpp",
- "statusbarwidget.h",
- "styleanimator.cpp",
- "styleanimator.h",
- "tabpositionindicator.cpp",
- "tabpositionindicator.h",
- "textdocument.cpp",
- "textdocument.h",
- "toolsettings.cpp",
- "toolsettings.h",
- "variablechooser.cpp",
- "variablechooser.h",
- "variablechooser.ui",
- "variablemanager.cpp",
- "variablemanager.h",
- "vcsmanager.cpp",
- "vcsmanager.h",
- "versiondialog.cpp",
- "versiondialog.h",
- "actionmanager/actioncontainer.cpp",
- "actionmanager/actioncontainer.h",
- "actionmanager/actioncontainer_p.h",
- "actionmanager/actionmanager.cpp",
- "actionmanager/actionmanager.h",
- "actionmanager/actionmanager_p.h",
- "actionmanager/command.cpp",
- "actionmanager/command.h",
- "actionmanager/command_p.h",
- "actionmanager/commandbutton.cpp",
- "actionmanager/commandbutton.h",
- "actionmanager/commandmappings.cpp",
- "actionmanager/commandmappings.h",
- "actionmanager/commandmappings.ui",
- "actionmanager/commandsfile.cpp",
- "actionmanager/commandsfile.h",
- "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",
- "dialogs/promptoverwritedialog.cpp",
- "dialogs/promptoverwritedialog.h",
- "dialogs/readonlyfilesdialog.cpp",
- "dialogs/readonlyfilesdialog.h",
- "dialogs/readonlyfilesdialog.ui",
- "dialogs/saveitemsdialog.cpp",
- "dialogs/saveitemsdialog.h",
- "dialogs/saveitemsdialog.ui",
- "dialogs/settingsdialog.cpp",
- "dialogs/settingsdialog.h",
- "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.cpp",
- "editormanager/ieditorfactory.h",
- "editormanager/iexternaleditor.cpp",
- "editormanager/iexternaleditor.h",
- "editormanager/openeditorsmodel.cpp",
- "editormanager/openeditorsmodel.h",
- "editormanager/openeditorsview.cpp",
- "editormanager/openeditorsview.h",
- "editormanager/openeditorswindow.cpp",
- "editormanager/openeditorswindow.h",
- "editormanager/systemeditor.cpp",
- "editormanager/systemeditor.h",
- "progressmanager/futureprogress.cpp",
- "progressmanager/futureprogress.h",
- "progressmanager/progressbar.cpp",
- "progressmanager/progressbar.h",
- "progressmanager/progressmanager.cpp",
- "progressmanager/progressmanager.h",
- "progressmanager/progressmanager_p.h",
- "progressmanager/progressview.cpp",
- "progressmanager/progressview.h",
- "scriptmanager/metatypedeclarations.h",
- "scriptmanager/scriptmanager.cpp",
- "scriptmanager/scriptmanager.h",
- "scriptmanager/scriptmanager_p.h",
- ]
+ Group {
+ name: "General"
+ files: [
+ "basefilewizard.cpp", "basefilewizard.h",
+ "core.qrc",
+ "core_global.h",
+ "coreconstants.h",
+ "coreplugin.cpp", "coreplugin.h",
+ "designmode.cpp", "designmode.h",
+ "documentmanager.cpp", "documentmanager.h",
+ "editmode.cpp", "editmode.h",
+ "editortoolbar.cpp", "editortoolbar.h",
+ "externaltool.cpp", "externaltool.h",
+ "externaltoolmanager.h",
+ "fancyactionbar.cpp", "fancyactionbar.h", "fancyactionbar.qrc",
+ "fancytabwidget.cpp", "fancytabwidget.h",
+ "featureprovider.cpp", "featureprovider.h",
+ "fileiconprovider.cpp", "fileiconprovider.h",
+ "fileutils.cpp", "fileutils.h",
+ "findplaceholder.cpp", "findplaceholder.h",
+ "generalsettings.cpp", "generalsettings.h", "generalsettings.ui",
+ "generatedfile.cpp", "generatedfile.h",
+ "helpmanager.cpp", "helpmanager.h",
+ "icontext.cpp", "icontext.h",
+ "icore.cpp", "icore.h",
+ "icorelistener.cpp", "icorelistener.h",
+ "id.cpp", "id.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", "manhattanstyle.h",
+ "messagemanager.cpp", "messagemanager.h",
+ "messageoutputwindow.cpp", "messageoutputwindow.h",
+ "mimedatabase.cpp", "mimedatabase.h",
+ "mimetypemagicdialog.cpp", "mimetypemagicdialog.h", "mimetypemagicdialog.ui",
+ "mimetypesettings.cpp", "mimetypesettings.h",
+ "mimetypesettingspage.ui",
+ "minisplitter.cpp", "minisplitter.h",
+ "modemanager.cpp", "modemanager.h",
+ "navigationsubwidget.cpp", "navigationsubwidget.h",
+ "navigationwidget.cpp", "navigationwidget.h",
+ "outputpane.cpp", "outputpane.h",
+ "outputpanemanager.cpp", "outputpanemanager.h",
+ "outputwindow.cpp", "outputwindow.h",
+ "plugindialog.cpp", "plugindialog.h",
+ "removefiledialog.cpp", "removefiledialog.h", "removefiledialog.ui",
+ "rightpane.cpp", "rightpane.h",
+ "settingsdatabase.cpp", "settingsdatabase.h",
+ "sidebar.cpp", "sidebar.h",
+ "sidebarwidget.cpp", "sidebarwidget.h",
+ "statusbarmanager.cpp", "statusbarmanager.h",
+ "statusbarwidget.cpp", "statusbarwidget.h",
+ "styleanimator.cpp", "styleanimator.h",
+ "tabpositionindicator.cpp", "tabpositionindicator.h",
+ "textdocument.cpp", "textdocument.h",
+ "toolsettings.cpp", "toolsettings.h",
+ "variablechooser.cpp", "variablechooser.h", "variablechooser.ui",
+ "variablemanager.cpp", "variablemanager.h",
+ "vcsmanager.cpp", "vcsmanager.h",
+ "versiondialog.cpp", "versiondialog.h",
+ ]
+ }
+
+ Group {
+ name: "Action Manager"
+ prefix: "actionmanager/"
+ files: [
+ "actioncontainer.cpp", "actioncontainer.h", "actioncontainer_p.h",
+ "actionmanager.cpp", "actionmanager.h", "actionmanager_p.h",
+ "command.cpp", "command.h", "command_p.h",
+ "commandbutton.cpp", "commandbutton.h",
+ "commandmappings.cpp", "commandmappings.h", "commandmappings.ui",
+ "commandsfile.cpp", "commandsfile.h",
+ ]
+ }
+
+ Group {
+ name: "Dialogs"
+ prefix: "dialogs/"
+ files: [
+ "addtovcsdialog.cpp", "addtovcsdialog.h", "addtovcsdialog.ui",
+ "externaltoolconfig.cpp", "externaltoolconfig.h", "externaltoolconfig.ui",
+ "ioptionspage.cpp", "ioptionspage.h",
+ "iwizard.cpp", "iwizard.h",
+ "newdialog.cpp", "newdialog.h", "newdialog.ui",
+ "openwithdialog.cpp", "openwithdialog.h", "openwithdialog.ui",
+ "promptoverwritedialog.cpp", "promptoverwritedialog.h",
+ "readonlyfilesdialog.cpp", "readonlyfilesdialog.h", "readonlyfilesdialog.ui",
+ "saveitemsdialog.cpp", "saveitemsdialog.h", "saveitemsdialog.ui",
+ "settingsdialog.cpp", "settingsdialog.h",
+ "shortcutsettings.cpp", "shortcutsettings.h",
+ ]
+ }
+
+ Group {
+ name: "Editor Manager"
+ prefix: "editormanager/"
+ files: [
+ "BinFiles.mimetypes.xml",
+ "documentmodel.cpp", "documentmodel.h",
+ "editormanager.cpp", "editormanager.h",
+ "editorview.cpp", "editorview.h",
+ "ieditor.cpp", "ieditor.h",
+ "ieditorfactory.cpp", "ieditorfactory.h",
+ "iexternaleditor.cpp", "iexternaleditor.h",
+ "openeditorsview.cpp", "openeditorsview.h",
+ "openeditorswindow.cpp", "openeditorswindow.h",
+ "systemeditor.cpp", "systemeditor.h",
+ ]
+ }
+
+ Group {
+ name: "Progress Manager"
+ prefix: "progressmanager/"
+ files: [
+ "futureprogress.cpp", "futureprogress.h",
+ "progressbar.cpp", "progressbar.h",
+ "progressmanager.cpp", "progressmanager.h", "progressmanager_p.h",
+ "progressview.cpp", "progressview.h",
+ ]
+ }
Group {
name: "ProgressManager_win"
@@ -261,10 +180,12 @@ QtcPlugin {
Group {
name: "Tests"
- condition: Defaults.testsEnabled(qbs)
+ condition: project.testsEnabled
files: [
"plugintestutils.cpp",
- "plugintestutils.h"
+ "plugintestutils.h",
+ "testdatadir.cpp",
+ "testdatadir.h"
]
}
diff --git a/src/plugins/coreplugin/designmode.cpp b/src/plugins/coreplugin/designmode.cpp
index a591d995fc..4173f73b00 100644
--- a/src/plugins/coreplugin/designmode.cpp
+++ b/src/plugins/coreplugin/designmode.cpp
@@ -201,7 +201,7 @@ void DesignMode::currentEditorChanged(Core::IEditor *editor)
bool mimeEditorAvailable = false;
- if (editor && editor->document()) {
+ if (editor) {
const QString mimeType = editor->document()->mimeType();
if (!mimeType.isEmpty()) {
foreach (DesignEditorInfo *editorInfo, d->m_editors) {
@@ -220,7 +220,7 @@ void DesignMode::currentEditorChanged(Core::IEditor *editor)
}
}
if (d->m_currentEditor)
- disconnect(d->m_currentEditor.data(), SIGNAL(changed()), this, SLOT(updateActions()));
+ disconnect(d->m_currentEditor.data()->document(), SIGNAL(changed()), this, SLOT(updateActions()));
if (!mimeEditorAvailable) {
setActiveContext(Context());
@@ -233,7 +233,7 @@ void DesignMode::currentEditorChanged(Core::IEditor *editor)
d->m_currentEditor = editor;
if (d->m_currentEditor)
- connect(d->m_currentEditor.data(), SIGNAL(changed()), this, SLOT(updateActions()));
+ connect(d->m_currentEditor.data()->document(), SIGNAL(changed()), this, SLOT(updateActions()));
emit actionsUpdated(d->m_currentEditor.data());
}
diff --git a/src/plugins/coreplugin/dialogs/addtovcsdialog.cpp b/src/plugins/coreplugin/dialogs/addtovcsdialog.cpp
new file mode 100644
index 0000000000..c1e3758dba
--- /dev/null
+++ b/src/plugins/coreplugin/dialogs/addtovcsdialog.cpp
@@ -0,0 +1,62 @@
+/****************************************************************************
+**
+** 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 "addtovcsdialog.h"
+#include "ui_addtovcsdialog.h"
+
+#include <QListWidgetItem>
+
+namespace Core {
+namespace Internal {
+
+AddToVcsDialog::AddToVcsDialog(QWidget *parent, const QString &title,
+ const QStringList &files, const QString &vcsDisplayName) :
+ QDialog(parent),
+ ui(new Ui::AddToVcsDialog)
+{
+ ui->setupUi(this);
+ QString addTo = files.size() == 1
+ ? tr("Add the file to version control (%1)").arg(vcsDisplayName)
+ : tr("Add the files to version control (%1)").arg(vcsDisplayName);
+
+ ui->addFilesLabel->setText(addTo);
+ setWindowTitle(title);
+
+ foreach (const QString &file, files) {
+ QListWidgetItem *item = new QListWidgetItem(file);
+ ui->filesListWidget->addItem(item);
+ }
+}
+
+AddToVcsDialog::~AddToVcsDialog()
+{
+ delete ui;
+}
+
+} // namespace Internal
+} // namespace Core
diff --git a/src/plugins/coreplugin/dialogs/addtovcsdialog.h b/src/plugins/coreplugin/dialogs/addtovcsdialog.h
new file mode 100644
index 0000000000..67928099f0
--- /dev/null
+++ b/src/plugins/coreplugin/dialogs/addtovcsdialog.h
@@ -0,0 +1,58 @@
+/****************************************************************************
+**
+** 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 ADDTOVCSDIALOG_H
+#define ADDTOVCSDIALOG_H
+
+#include <QDialog>
+
+namespace Core {
+namespace Internal {
+
+namespace Ui {
+class AddToVcsDialog;
+}
+
+class AddToVcsDialog : public QDialog
+{
+ Q_OBJECT
+
+public:
+ explicit AddToVcsDialog(QWidget *parent, const QString &title,
+ const QStringList &files, const QString &vcsDisplayName);
+ ~AddToVcsDialog();
+
+private:
+ Ui::AddToVcsDialog *ui;
+};
+
+
+} // namespace Internal
+} // namespace Core
+#endif // ADDTOVCSDIALOG_H
diff --git a/src/plugins/coreplugin/dialogs/addtovcsdialog.ui b/src/plugins/coreplugin/dialogs/addtovcsdialog.ui
new file mode 100644
index 0000000000..17493a3f69
--- /dev/null
+++ b/src/plugins/coreplugin/dialogs/addtovcsdialog.ui
@@ -0,0 +1,93 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>Core::Internal::AddToVcsDialog</class>
+ <widget class="QDialog" name="Core::Internal::AddToVcsDialog">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>363</width>
+ <height>433</height>
+ </rect>
+ </property>
+ <property name="minimumSize">
+ <size>
+ <width>200</width>
+ <height>200</height>
+ </size>
+ </property>
+ <property name="baseSize">
+ <size>
+ <width>300</width>
+ <height>500</height>
+ </size>
+ </property>
+ <property name="windowTitle">
+ <string>Dialog</string>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout">
+ <item>
+ <widget class="QLabel" name="addFilesLabel">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QListWidget" name="filesListWidget">
+ <property name="selectionMode">
+ <enum>QAbstractItemView::NoSelection</enum>
+ </property>
+ <property name="selectionBehavior">
+ <enum>QAbstractItemView::SelectRows</enum>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QDialogButtonBox" name="buttonBox">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="standardButtons">
+ <set>QDialogButtonBox::No|QDialogButtonBox::Yes</set>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections>
+ <connection>
+ <sender>buttonBox</sender>
+ <signal>accepted()</signal>
+ <receiver>Core::Internal::AddToVcsDialog</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>Core::Internal::AddToVcsDialog</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/coreplugin/dialogs/iwizard.cpp b/src/plugins/coreplugin/dialogs/iwizard.cpp
index a7c905d665..d6134c8dba 100644
--- a/src/plugins/coreplugin/dialogs/iwizard.cpp
+++ b/src/plugins/coreplugin/dialogs/iwizard.cpp
@@ -28,8 +28,8 @@
****************************************************************************/
#include "iwizard.h"
-#include "icore.h"
-#include "featureprovider.h"
+#include <coreplugin/icore.h>
+#include <coreplugin/featureprovider.h>
#include <extensionsystem/pluginmanager.h>
@@ -128,7 +128,11 @@
*/
/*!
- \fn void IWizard::runWizard(const QString &path, QWidget *parent)
+ \fn void IWizard::runWizard(const QString &path,
+ QWidget *parent,
+ const QString &platform,
+ const QVariantMap &variables)
+
This method is executed when the wizard has been selected by the user
for execution. Any dialogs the wizard opens should use the given \a parent.
The \a path argument is a suggestion for the location where files should be
diff --git a/src/plugins/coreplugin/dialogs/iwizard.h b/src/plugins/coreplugin/dialogs/iwizard.h
index 4618b7b03d..f0e9148e76 100644
--- a/src/plugins/coreplugin/dialogs/iwizard.h
+++ b/src/plugins/coreplugin/dialogs/iwizard.h
@@ -31,18 +31,15 @@
#define IWIZARD_H
#include <coreplugin/core_global.h>
+#include <coreplugin/id.h>
+#include <coreplugin/featureprovider.h>
+#include <QIcon>
#include <QObject>
#include <QVariantMap>
-QT_BEGIN_NAMESPACE
-class QIcon;
-QT_END_NAMESPACE
-
namespace Core {
-class FeatureSet;
-
class CORE_EXPORT IWizard
: public QObject
{
@@ -60,22 +57,49 @@ public:
};
Q_DECLARE_FLAGS(WizardFlags, WizardFlag)
- IWizard(QObject *parent = 0) : QObject(parent) {}
- virtual ~IWizard() {}
-
- virtual WizardKind kind() const = 0;
- virtual QIcon icon() const = 0;
- virtual QString description() const = 0;
- virtual QString displayName() const = 0;
- virtual QString id() const = 0;
-
- virtual QString category() const = 0;
- virtual QString displayCategory() const = 0;
-
- virtual QString descriptionImage() const = 0;
+ class CORE_EXPORT Data
+ {
+ public:
+ Data() : kind(IWizard::FileWizard) {}
+
+ IWizard::WizardKind kind;
+ QIcon icon;
+ QString description;
+ QString displayName;
+ QString id;
+ QString category;
+ QString displayCategory;
+ FeatureSet requiredFeatures;
+ IWizard::WizardFlags flags;
+ QString descriptionImage;
+ };
- virtual FeatureSet requiredFeatures() const = 0;
- virtual WizardFlags flags() const = 0;
+ IWizard(QObject *parent = 0) : QObject(parent) {}
+ ~IWizard() {}
+
+ QString id() const { return m_data.id; }
+ WizardKind kind() const { return m_data.kind; }
+ QIcon icon() const { return m_data.icon; }
+ QString description() const { return m_data.description; }
+ QString displayName() const { return m_data.displayName; }
+ QString category() const { return m_data.category; }
+ QString displayCategory() const { return m_data.displayCategory; }
+ QString descriptionImage() const { return m_data.descriptionImage; }
+ FeatureSet requiredFeatures() const { return m_data.requiredFeatures; }
+ WizardFlags flags() const { return m_data.flags; }
+
+ void setData(const Data &data) { m_data = data; }
+ void setId(const QString &id) { m_data.id = id; }
+ void setWizardKind(WizardKind kind) { m_data.kind = kind; }
+ void setIcon(const QIcon &icon) { m_data.icon = icon; }
+ void setDescription(const QString &description) { m_data.description = description; }
+ void setDisplayName(const QString &displayName) { m_data.displayName = displayName; }
+ void setCategory(const QString &category) { m_data.category = category; }
+ void setDisplayCategory(const QString &displayCategory) { m_data.displayCategory = displayCategory; }
+ void setDescriptionImage(const QString &descriptionImage) { m_data.descriptionImage = descriptionImage; }
+ void setRequiredFeatures(const FeatureSet &featureSet) { m_data.requiredFeatures = featureSet; }
+ void addRequiredFeature(const Feature &feature) { m_data.requiredFeatures |= feature; }
+ void setFlags(WizardFlags flags) { m_data.flags = flags; }
virtual void runWizard(const QString &path, QWidget *parent, const QString &platform, const QVariantMap &variables) = 0;
@@ -88,6 +112,9 @@ public:
static QList<IWizard*> wizardsOfKind(WizardKind kind);
static QStringList allAvailablePlatforms();
static QString displayNameForPlatform(const QString &string);
+
+private:
+ Data m_data;
};
} // namespace Core
diff --git a/src/plugins/coreplugin/dialogs/newdialog.cpp b/src/plugins/coreplugin/dialogs/newdialog.cpp
index ab949655ee..1353b95ae9 100644
--- a/src/plugins/coreplugin/dialogs/newdialog.cpp
+++ b/src/plugins/coreplugin/dialogs/newdialog.cpp
@@ -83,7 +83,7 @@ public:
QModelIndex sourceIndex = sourceModel()->index(sourceRow, 0, sourceParent);
Core::IWizard *wizard = wizardOfItem(qobject_cast<QStandardItemModel*>(sourceModel())->itemFromIndex(sourceIndex));
if (wizard)
- return wizard->isAvailable(m_platform);
+ return m_platform.isEmpty() || wizard->isAvailable(m_platform);
return true;
}
@@ -259,39 +259,31 @@ void NewDialog::setWizards(QList<IWizard*> wizards)
m_dummyIcon = QIcon(QLatin1String(Core::Constants::ICON_NEWFILE));
QStringList availablePlatforms = IWizard::allAvailablePlatforms();
+ m_ui->comboBox->addItem(tr("All Templates"), QString());
- if (availablePlatforms.count() > 1) {
- m_ui->comboBox->addItem(tr("All Templates"), QString());
- foreach (const QString &platform, availablePlatforms) {
- const QString displayNameForPlatform = IWizard::displayNameForPlatform(platform);
- m_ui->comboBox->addItem(tr("%1 Templates").arg(displayNameForPlatform), platform);
- }
- } else {
- if (availablePlatforms.isEmpty()) {
- m_ui->comboBox->addItem(tr("All Templates"), QString());
- } else {
- const QString platform = availablePlatforms.first();
- const QString displayNameForPlatform = IWizard::displayNameForPlatform(platform);
- m_ui->comboBox->addItem(tr("%1 Templates").arg(displayNameForPlatform), platform);
- }
- m_ui->comboBox->setDisabled(true);
+ foreach (const QString &platform, availablePlatforms) {
+ const QString displayNameForPlatform = IWizard::displayNameForPlatform(platform);
+ m_ui->comboBox->addItem(tr("%1 Templates").arg(displayNameForPlatform), platform);
}
+ if (!availablePlatforms.isEmpty())
+ m_ui->comboBox->setCurrentIndex(1); //First Platform
+ else
+ m_ui->comboBox->setDisabled(true);
+
foreach (IWizard *wizard, wizards) {
- if (wizard->isAvailable(selectedPlatform())) {
- QStandardItem *kindItem;
- switch (wizard->kind()) {
- case IWizard::ProjectWizard:
- kindItem = projectKindItem;
- break;
- case IWizard::ClassWizard:
- case IWizard::FileWizard:
- default:
- kindItem = filesClassesKindItem;
- break;
- }
- addItem(kindItem, wizard);
+ QStandardItem *kindItem;
+ switch (wizard->kind()) {
+ case IWizard::ProjectWizard:
+ kindItem = projectKindItem;
+ break;
+ case IWizard::ClassWizard:
+ case IWizard::FileWizard:
+ default:
+ kindItem = filesClassesKindItem;
+ break;
}
+ addItem(kindItem, wizard);
}
if (projectKindItem->columnCount() == 0)
parentItem->removeRow(0);
diff --git a/src/plugins/coreplugin/dialogs/readonlyfilesdialog.cpp b/src/plugins/coreplugin/dialogs/readonlyfilesdialog.cpp
index f264a1dd4a..3a017e8c52 100644
--- a/src/plugins/coreplugin/dialogs/readonlyfilesdialog.cpp
+++ b/src/plugins/coreplugin/dialogs/readonlyfilesdialog.cpp
@@ -27,11 +27,11 @@
**
****************************************************************************/
-#include "fileiconprovider.h"
#include "readonlyfilesdialog.h"
#include "ui_readonlyfilesdialog.h"
#include <coreplugin/editormanager/editormanager.h>
+#include <coreplugin/fileiconprovider.h>
#include <coreplugin/icore.h>
#include <coreplugin/idocument.h>
#include <coreplugin/iversioncontrol.h>
@@ -137,7 +137,7 @@ ReadOnlyFilesDialog::ReadOnlyFilesDialog(IDocument *document, QWidget *parent,
, d(new ReadOnlyFilesDialogPrivate(document, displaySaveAs))
, ui(new Ui::ReadOnlyFilesDialog)
{
- initDialog(QStringList() << document->fileName());
+ initDialog(QStringList() << document->filePath());
}
ReadOnlyFilesDialog::ReadOnlyFilesDialog(const QList<IDocument *> documents, QWidget *parent)
@@ -147,7 +147,7 @@ ReadOnlyFilesDialog::ReadOnlyFilesDialog(const QList<IDocument *> documents, QWi
{
QStringList files;
foreach (IDocument *document, documents)
- files << document->fileName();
+ files << document->filePath();
initDialog(files);
}
@@ -268,7 +268,7 @@ int ReadOnlyFilesDialog::exec()
}
break;
case RO_SaveAs:
- if (!EditorManager::instance()->saveDocumentAs(d->document)) {
+ if (!EditorManager::saveDocumentAs(d->document)) {
failedToMakeWritable << buttengroup.fileName;
continue;
}
@@ -375,14 +375,14 @@ void ReadOnlyFilesDialog::initDialog(const QStringList &fileNames)
// Setup a default entry with filename folder and make writable radio button.
QTreeWidgetItem *item = new QTreeWidgetItem(ui->treeWidget);
item->setText(FileName, visibleName);
- item->setIcon(FileName, FileIconProvider::instance()->icon(QFileInfo(fileName)));
+ item->setIcon(FileName, FileIconProvider::icon(fileName));
item->setText(Folder, Utils::FileUtils::shortNativePath(Utils::FileName(QFileInfo(directory))));
QButtonGroup *radioButtonGroup = new QButtonGroup;
// Add a button for opening the file with a version control system
// if the file is managed by an version control system which allows opening files.
IVersionControl *versionControlForFile =
- ICore::vcsManager()->findVersionControlForDirectory(directory);
+ VcsManager::findVersionControlForDirectory(directory);
const bool fileManagedByVCS = versionControlForFile
&& versionControlForFile->openSupportMode() != IVersionControl::NoOpen;
if (fileManagedByVCS) {
diff --git a/src/plugins/coreplugin/dialogs/saveitemsdialog.cpp b/src/plugins/coreplugin/dialogs/saveitemsdialog.cpp
index 7595ca1946..b77cc255fd 100644
--- a/src/plugins/coreplugin/dialogs/saveitemsdialog.cpp
+++ b/src/plugins/coreplugin/dialogs/saveitemsdialog.cpp
@@ -62,7 +62,7 @@ SaveItemsDialog::SaveItemsDialog(QWidget *parent,
foreach (IDocument *document, items) {
QString visibleName;
QString directory;
- QString fileName = document->fileName();
+ QString fileName = document->filePath();
if (fileName.isEmpty()) {
visibleName = document->suggestedFileName();
} else {
@@ -73,7 +73,7 @@ SaveItemsDialog::SaveItemsDialog(QWidget *parent,
QTreeWidgetItem *item = new QTreeWidgetItem(m_ui.treeWidget, QStringList()
<< visibleName << QDir::toNativeSeparators(directory));
if (!fileName.isEmpty())
- item->setIcon(0, FileIconProvider::instance()->icon(QFileInfo(fileName)));
+ item->setIcon(0, FileIconProvider::icon(fileName));
item->setData(0, Qt::UserRole, qVariantFromValue(document));
}
diff --git a/src/plugins/coreplugin/dialogs/settingsdialog.cpp b/src/plugins/coreplugin/dialogs/settingsdialog.cpp
index eca479ee40..bb6783bcda 100644
--- a/src/plugins/coreplugin/dialogs/settingsdialog.cpp
+++ b/src/plugins/coreplugin/dialogs/settingsdialog.cpp
@@ -29,7 +29,7 @@
#include "settingsdialog.h"
-#include "icore.h"
+#include <coreplugin/icore.h>
#include <extensionsystem/pluginmanager.h>
#include <utils/hostosinfo.h>
@@ -248,6 +248,7 @@ public:
{
setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Expanding);
setItemDelegate(new CategoryListViewDelegate(this));
+ setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
}
virtual QSize sizeHint() const
@@ -257,6 +258,16 @@ public:
width += verticalScrollBar()->width();
return QSize(width, 100);
}
+
+ // QListView installs a event filter on its scrollbars
+ virtual bool eventFilter(QObject *obj, QEvent *event)
+ {
+ if (obj == verticalScrollBar()
+ && (event->type() == QEvent::Show
+ || event->type() == QEvent::Hide))
+ updateGeometry();
+ return QListView::eventFilter(obj, event);
+ }
};
// ----------- SettingsDialog
diff --git a/src/plugins/coreplugin/dialogs/shortcutsettings.cpp b/src/plugins/coreplugin/dialogs/shortcutsettings.cpp
index 60fb4a89a6..26aebb407d 100644
--- a/src/plugins/coreplugin/dialogs/shortcutsettings.cpp
+++ b/src/plugins/coreplugin/dialogs/shortcutsettings.cpp
@@ -28,14 +28,14 @@
****************************************************************************/
#include "shortcutsettings.h"
-#include "actionmanager/actionmanager.h"
-#include "actionmanager/command.h"
-#include "command_p.h"
-#include "commandsfile.h"
-#include "coreconstants.h"
-#include "documentmanager.h"
-#include "icore.h"
-#include "id.h"
+#include <coreplugin/coreconstants.h>
+#include <coreplugin/documentmanager.h>
+#include <coreplugin/icore.h>
+#include <coreplugin/id.h>
+#include <coreplugin/actionmanager/actionmanager.h>
+#include <coreplugin/actionmanager/command.h>
+#include <coreplugin/actionmanager/command_p.h>
+#include <coreplugin/actionmanager/commandsfile.h>
#include <QKeyEvent>
#include <QFileDialog>
diff --git a/src/plugins/coreplugin/documentmanager.cpp b/src/plugins/coreplugin/documentmanager.cpp
index 8b42b01c70..e7c2573e5a 100644
--- a/src/plugins/coreplugin/documentmanager.cpp
+++ b/src/plugins/coreplugin/documentmanager.cpp
@@ -29,17 +29,17 @@
#include "documentmanager.h"
-#include "editormanager.h"
#include "icore.h"
-#include "ieditor.h"
-#include "ieditorfactory.h"
-#include "iexternaleditor.h"
#include "idocument.h"
#include "mimedatabase.h"
-#include "saveitemsdialog.h"
#include "coreconstants.h"
-#include "dialogs/readonlyfilesdialog.h"
+#include <coreplugin/dialogs/readonlyfilesdialog.h>
+#include <coreplugin/dialogs/saveitemsdialog.h>
+#include <coreplugin/editormanager/editormanager.h>
+#include <coreplugin/editormanager/ieditor.h>
+#include <coreplugin/editormanager/ieditorfactory.h>
+#include <coreplugin/editormanager/iexternaleditor.h>
#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
@@ -230,7 +230,7 @@ DocumentManager::~DocumentManager()
delete d;
}
-DocumentManager *DocumentManager::instance()
+QObject *DocumentManager::instance()
{
return m_instance;
}
@@ -266,8 +266,8 @@ static void addFileInfo(const QString &fileName, IDocument *document, bool isLin
(The added file names are guaranteed to be absolute and cleaned.) */
static void addFileInfo(IDocument *document)
{
- const QString fixedName = DocumentManager::fixFileName(document->fileName(), DocumentManager::KeepLinks);
- const QString fixedResolvedName = DocumentManager::fixFileName(document->fileName(), DocumentManager::ResolveLinks);
+ const QString fixedName = DocumentManager::fixFileName(document->filePath(), DocumentManager::KeepLinks);
+ const QString fixedResolvedName = DocumentManager::fixFileName(document->filePath(), DocumentManager::ResolveLinks);
addFileInfo(fixedResolvedName, document, false);
if (fixedName != fixedResolvedName)
addFileInfo(fixedName, document, true);
@@ -286,7 +286,7 @@ void DocumentManager::addDocuments(const QList<IDocument *> &documents, bool add
foreach (IDocument *document, documents) {
if (document && !d->m_documentsWithoutWatch.contains(document)) {
connect(document, SIGNAL(destroyed(QObject*)), m_instance, SLOT(documentDestroyed(QObject*)));
- connect(document, SIGNAL(fileNameChanged(QString,QString)), m_instance, SLOT(fileNameChanged(QString,QString)));
+ connect(document, SIGNAL(filePathChanged(QString,QString)), m_instance, SLOT(filePathChanged(QString,QString)));
d->m_documentsWithoutWatch.append(document);
}
}
@@ -297,7 +297,7 @@ void DocumentManager::addDocuments(const QList<IDocument *> &documents, bool add
if (document && !d->m_documentsWithWatch.contains(document)) {
connect(document, SIGNAL(changed()), m_instance, SLOT(checkForNewFileName()));
connect(document, SIGNAL(destroyed(QObject*)), m_instance, SLOT(documentDestroyed(QObject*)));
- connect(document, SIGNAL(fileNameChanged(QString,QString)), m_instance, SLOT(fileNameChanged(QString,QString)));
+ connect(document, SIGNAL(filePathChanged(QString,QString)), m_instance, SLOT(filePathChanged(QString,QString)));
addFileInfo(document);
}
}
@@ -388,14 +388,14 @@ void DocumentManager::renamedFile(const QString &from, const QString &to)
foreach (IDocument *document, documentsToRename) {
d->m_blockedIDocument = document;
removeFileInfo(document);
- document->rename(to);
+ document->setFilePath(to);
addFileInfo(document);
d->m_blockedIDocument = 0;
}
emit m_instance->allDocumentsRenamed(from, to);
}
-void DocumentManager::fileNameChanged(const QString &oldName, const QString &newName)
+void DocumentManager::filePathChanged(const QString &oldName, const QString &newName)
{
IDocument *doc = qobject_cast<IDocument *>(sender());
QTC_ASSERT(doc, return);
@@ -602,7 +602,7 @@ static QList<IDocument *> saveModifiedFilesHelper(const QList<IDocument *> &docu
foreach (IDocument *document, documents) {
if (document->isModified()) {
- QString name = document->fileName();
+ QString name = document->filePath();
if (name.isEmpty())
name = document->suggestedFileName();
@@ -655,7 +655,7 @@ static QList<IDocument *> saveModifiedFilesHelper(const QList<IDocument *> &docu
}
}
foreach (IDocument *document, documentsToSave) {
- if (!EditorManager::instance()->saveDocument(document)) {
+ if (!EditorManager::saveDocument(document)) {
if (cancelled)
*cancelled = true;
notSaved.append(document);
@@ -668,7 +668,7 @@ static QList<IDocument *> saveModifiedFilesHelper(const QList<IDocument *> &docu
bool DocumentManager::saveDocument(IDocument *document, const QString &fileName, bool *isReadOnly)
{
bool ret = true;
- QString effName = fileName.isEmpty() ? document->fileName() : fileName;
+ QString effName = fileName.isEmpty() ? document->filePath() : fileName;
expectFileChange(effName); // This only matters to other IDocuments which refer to this file
bool addWatcher = removeDocument(document); // So that our own IDocument gets no notification at all
@@ -755,7 +755,7 @@ QString DocumentManager::getSaveAsFileName(const IDocument *document, const QStr
{
if (!document)
return QLatin1String("");
- QString absoluteFilePath = document->fileName();
+ QString absoluteFilePath = document->filePath();
const QFileInfo fi(absoluteFilePath);
QString fileName = fi.fileName();
QString path = fi.absolutePath();
@@ -768,7 +768,7 @@ QString DocumentManager::getSaveAsFileName(const IDocument *document, const QStr
QString filterString;
if (filter.isEmpty()) {
- if (const MimeType &mt = Core::ICore::mimeDatabase()->findByFile(fi))
+ if (const MimeType &mt = MimeDatabase::findByFile(fi))
filterString = mt.filterString();
selectedFilter = &filterString;
} else {
@@ -832,10 +832,11 @@ void DocumentManager::checkForReload()
d->m_blockActivated = true;
- IDocument::ReloadSetting defaultBehavior = EditorManager::instance()->reloadSetting();
- Utils::ReloadPromptAnswer previousAnswer = Utils::ReloadCurrent;
+ IDocument::ReloadSetting defaultBehavior = EditorManager::reloadSetting();
+ Utils::ReloadPromptAnswer previousReloadAnswer = Utils::ReloadCurrent;
+ Utils::FileDeletedPromptAnswer previousDeletedAnswer = Utils::FileDeletedSave;
- QList<IEditor*> editorsToClose;
+ QList<IDocument *> documentsToClose;
QMap<IDocument*, QString> documentsToSave;
// collect file information
@@ -940,7 +941,7 @@ void DocumentManager::checkForReload()
&& type == IDocument::TypeRemoved && !document->isModified()) {
// file removed, but unmodified files should be reloaded
// so we close the file
- editorsToClose << EditorManager::instance()->editorsForDocument(document);
+ documentsToClose << document;
} else if (defaultBehavior == IDocument::IgnoreAll) {
// content change or removed, but settings say ignore
success = document->reload(&errorString, IDocument::FlagIgnore, type);
@@ -952,22 +953,22 @@ void DocumentManager::checkForReload()
if (document->reloadBehavior(trigger, type) == IDocument::BehaviorSilent) {
// content change or removed, IDocument wants silent handling
if (type == IDocument::TypeRemoved)
- editorsToClose << EditorManager::instance()->editorsForDocument(document);
+ documentsToClose << document;
else
success = document->reload(&errorString, IDocument::FlagReload, type);
// IDocument wants us to ask
} else if (type == IDocument::TypeContents) {
// content change, IDocument wants to ask user
- if (previousAnswer == Utils::ReloadNone) {
+ if (previousReloadAnswer == Utils::ReloadNone) {
// answer already given, ignore
success = document->reload(&errorString, IDocument::FlagIgnore, IDocument::TypeContents);
- } else if (previousAnswer == Utils::ReloadAll) {
+ } else if (previousReloadAnswer == Utils::ReloadAll) {
// answer already given, reload
success = document->reload(&errorString, IDocument::FlagReload, IDocument::TypeContents);
} else {
// Ask about content change
- previousAnswer = Utils::reloadPrompt(document->fileName(), document->isModified(), QApplication::activeWindow());
- switch (previousAnswer) {
+ previousReloadAnswer = Utils::reloadPrompt(document->filePath(), document->isModified(), QApplication::activeWindow());
+ switch (previousReloadAnswer) {
case Utils::ReloadAll:
case Utils::ReloadCurrent:
success = document->reload(&errorString, IDocument::FlagReload, IDocument::TypeContents);
@@ -977,7 +978,7 @@ void DocumentManager::checkForReload()
success = document->reload(&errorString, IDocument::FlagIgnore, IDocument::TypeContents);
break;
case Utils::CloseCurrent:
- editorsToClose << EditorManager::instance()->editorsForDocument(document);
+ documentsToClose << document;
break;
}
}
@@ -986,9 +987,15 @@ void DocumentManager::checkForReload()
// Ask about removed file
bool unhandled = true;
while (unhandled) {
- switch (Utils::fileDeletedPrompt(document->fileName(), trigger == IDocument::TriggerExternal, QApplication::activeWindow())) {
+ if (previousDeletedAnswer != Utils::FileDeletedCloseAll) {
+ previousDeletedAnswer =
+ Utils::fileDeletedPrompt(document->filePath(),
+ trigger == IDocument::TriggerExternal,
+ QApplication::activeWindow());
+ }
+ switch (previousDeletedAnswer) {
case Utils::FileDeletedSave:
- documentsToSave.insert(document, document->fileName());
+ documentsToSave.insert(document, document->filePath());
unhandled = false;
break;
case Utils::FileDeletedSaveAs:
@@ -1001,7 +1008,8 @@ void DocumentManager::checkForReload()
break;
}
case Utils::FileDeletedClose:
- editorsToClose << EditorManager::instance()->editorsForDocument(document);
+ case Utils::FileDeletedCloseAll:
+ documentsToClose << document;
unhandled = false;
break;
}
@@ -1010,7 +1018,7 @@ void DocumentManager::checkForReload()
}
if (!success) {
if (errorString.isEmpty())
- errorStrings << tr("Cannot reload %1").arg(QDir::toNativeSeparators(document->fileName()));
+ errorStrings << tr("Cannot reload %1").arg(QDir::toNativeSeparators(document->filePath()));
else
errorStrings << errorString;
}
@@ -1025,7 +1033,7 @@ void DocumentManager::checkForReload()
errorStrings.join(QLatin1String("\n")));
// handle deleted files
- EditorManager::instance()->closeEditors(editorsToClose, false);
+ EditorManager::closeDocuments(documentsToClose, false);
QMapIterator<IDocument *, QString> it(documentsToSave);
while (it.hasNext()) {
it.next();
@@ -1044,11 +1052,11 @@ void DocumentManager::syncWithEditor(const QList<Core::IContext *> &context)
return;
Core::IEditor *editor = Core::EditorManager::currentEditor();
- if (!editor || editor->isTemporary())
+ if (!editor || editor->document()->isTemporary())
return;
foreach (IContext *c, context) {
if (editor->widget() == c->widget()) {
- setCurrentFile(editor->document()->fileName());
+ setCurrentFile(editor->document()->filePath());
break;
}
}
@@ -1307,7 +1315,7 @@ void DocumentManager::populateOpenWithMenu(QMenu *menu, const QString &fileName)
bool anyMatches = false;
- if (const MimeType mt = ICore::mimeDatabase()->findByFile(QFileInfo(fileName))) {
+ if (const MimeType mt = MimeDatabase::findByFile(QFileInfo(fileName))) {
const EditorFactoryList factories = EditorManager::editorFactories(mt, false);
const ExternalEditorList externalEditors = EditorManager::externalEditors(mt, false);
anyMatches = !factories.empty() || !externalEditors.empty();
@@ -1342,14 +1350,14 @@ void DocumentManager::executeOpenWithMenuAction(QAction *action)
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();
- QList<IEditor *> editorsOpenForFile = em->editorsForFileName(entry.fileName);
+ QList<IEditor *> editorsOpenForFile
+ = EditorManager::documentModel()->editorsForFilePath(entry.fileName);
if (!editorsOpenForFile.isEmpty()) {
foreach (IEditor *openEditor, editorsOpenForFile) {
if (entry.editorFactory->id() == openEditor->id())
editorsOpenForFile.removeAll(openEditor);
}
- if (!em->closeEditors(editorsOpenForFile)) // don't open if cancel was pressed
+ if (!EditorManager::closeEditors(editorsOpenForFile)) // don't open if cancel was pressed
return;
}
diff --git a/src/plugins/coreplugin/documentmanager.h b/src/plugins/coreplugin/documentmanager.h
index 549d8d9bc3..6839b01ff4 100644
--- a/src/plugins/coreplugin/documentmanager.h
+++ b/src/plugins/coreplugin/documentmanager.h
@@ -47,6 +47,8 @@ namespace Core {
class IContext;
class IDocument;
+namespace Internal { class MainWindow; }
+
class CORE_EXPORT DocumentManager : public QObject
{
Q_OBJECT
@@ -58,10 +60,7 @@ public:
typedef QPair<QString, Id> RecentFile;
- explicit DocumentManager(QMainWindow *ew);
- virtual ~DocumentManager();
-
- static DocumentManager *instance();
+ static QObject *instance();
// file pool to monitor
static void addDocuments(const QList<IDocument *> &documents, bool addWatcher = true);
@@ -147,11 +146,17 @@ protected:
private slots:
void documentDestroyed(QObject *obj);
- void fileNameChanged(const QString &oldName, const QString &newName);
+ void filePathChanged(const QString &oldName, const QString &newName);
void checkForNewFileName();
void checkForReload();
void changedFile(const QString &file);
void syncWithEditor(const QList<Core::IContext *> &context);
+
+private:
+ explicit DocumentManager(QMainWindow *ew);
+ ~DocumentManager();
+
+ friend class Core::Internal::MainWindow;
};
/*! The FileChangeBlocker blocks all change notifications to all IDocument * that
diff --git a/src/plugins/coreplugin/editmode.cpp b/src/plugins/coreplugin/editmode.cpp
index 1a6072e978..7eae044731 100644
--- a/src/plugins/coreplugin/editmode.cpp
+++ b/src/plugins/coreplugin/editmode.cpp
@@ -28,14 +28,14 @@
****************************************************************************/
#include "editmode.h"
-#include "editormanager.h"
#include "coreconstants.h"
#include "modemanager.h"
#include "minisplitter.h"
#include "outputpane.h"
#include "navigationwidget.h"
#include "rightpane.h"
-#include "ieditor.h"
+#include <coreplugin/editormanager/editormanager.h>
+#include <coreplugin/editormanager/ieditor.h>
#include <QLatin1String>
#include <QHBoxLayout>
@@ -49,7 +49,6 @@ EditMode::EditMode() :
m_splitter(new MiniSplitter),
m_rightSplitWidgetLayout(new QVBoxLayout)
{
- m_editorManager = EditorManager::instance();
setObjectName(QLatin1String("EditMode"));
setDisplayName(tr("Edit"));
setIcon(QIcon(QLatin1String(":/fancyactionbar/images/mode_Edit.png")));
@@ -84,7 +83,7 @@ EditMode::EditMode() :
connect(ModeManager::instance(), SIGNAL(currentModeChanged(Core::IMode*)),
this, SLOT(grabEditorManager(Core::IMode*)));
- m_splitter->setFocusProxy(m_editorManager);
+ m_splitter->setFocusProxy(EditorManager::instance());
setWidget(m_splitter);
setContext(Context(Constants::C_EDIT_MODE,
@@ -95,7 +94,7 @@ EditMode::EditMode() :
EditMode::~EditMode()
{
// Make sure the editor manager does not get deleted
- m_editorManager->setParent(0);
+ EditorManager::instance()->setParent(0);
delete m_splitter;
}
diff --git a/src/plugins/coreplugin/editmode.h b/src/plugins/coreplugin/editmode.h
index 83592731a3..2e65e5e5a7 100644
--- a/src/plugins/coreplugin/editmode.h
+++ b/src/plugins/coreplugin/editmode.h
@@ -55,7 +55,6 @@ private slots:
void grabEditorManager(Core::IMode *mode);
private:
- EditorManager *m_editorManager;
QSplitter *m_splitter;
QVBoxLayout *m_rightSplitWidgetLayout;
};
diff --git a/src/plugins/coreplugin/editormanager/documentmodel.cpp b/src/plugins/coreplugin/editormanager/documentmodel.cpp
new file mode 100644
index 0000000000..737b2fc5fa
--- /dev/null
+++ b/src/plugins/coreplugin/editormanager/documentmodel.cpp
@@ -0,0 +1,398 @@
+/****************************************************************************
+**
+** 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 "documentmodel.h"
+#include "ieditor.h"
+#include <coreplugin/idocument.h>
+
+#include <utils/qtcassert.h>
+
+#include <QDir>
+#include <QIcon>
+
+namespace Core {
+
+struct DocumentModelPrivate
+{
+ DocumentModelPrivate();
+ ~DocumentModelPrivate();
+
+ const QIcon m_lockedIcon;
+ const QIcon m_unlockedIcon;
+
+ QList<DocumentModel::Entry *> m_documents;
+ QMap<IDocument *, QList<IEditor *> > m_editors;
+};
+
+DocumentModelPrivate::DocumentModelPrivate() :
+ m_lockedIcon(QLatin1String(":/core/images/locked.png")),
+ m_unlockedIcon(QLatin1String(":/core/images/unlocked.png"))
+{
+}
+
+DocumentModelPrivate::~DocumentModelPrivate()
+{
+ qDeleteAll(m_documents);
+}
+
+DocumentModel::Entry::Entry() :
+ document(0)
+{
+}
+
+DocumentModel::DocumentModel(QObject *parent) :
+ QAbstractItemModel(parent), d(new DocumentModelPrivate)
+{
+}
+
+DocumentModel::~DocumentModel()
+{
+ delete d;
+}
+
+QIcon DocumentModel::lockedIcon() const
+{
+ return d->m_lockedIcon;
+}
+
+QIcon DocumentModel::unlockedIcon() const
+{
+ return d->m_unlockedIcon;
+}
+
+QString DocumentModel::Entry::fileName() const {
+ return document ? document->filePath() : m_fileName;
+}
+
+QString DocumentModel::Entry::displayName() const {
+ return document ? document->displayName() : m_displayName;
+}
+
+Id DocumentModel::Entry::id() const
+{
+ return m_id;
+}
+
+int DocumentModel::columnCount(const QModelIndex &parent) const
+{
+ if (!parent.isValid())
+ return 2;
+ return 0;
+}
+
+int DocumentModel::rowCount(const QModelIndex &parent) const
+{
+ if (!parent.isValid())
+ return d->m_documents.count() + 1/*<no document>*/;
+ return 0;
+}
+
+// TODO remove
+QList<IEditor *> DocumentModel::oneEditorForEachOpenedDocument() const
+{
+ QList<IEditor *> result;
+ QMapIterator<IDocument *, QList<IEditor *> > it(d->m_editors);
+ while (it.hasNext())
+ result << it.next().value().first();
+ return result;
+}
+
+void DocumentModel::addEditor(IEditor *editor, bool *isNewDocument)
+{
+ if (!editor)
+ return;
+
+ QList<IEditor *> &editorList = d->m_editors[editor->document()];
+ bool isNew = editorList.isEmpty();
+ if (isNewDocument)
+ *isNewDocument = isNew;
+ editorList << editor;
+ if (isNew) {
+ Entry *entry = new Entry;
+ entry->document = editor->document();
+ entry->m_id = editor->id();
+ addEntry(entry);
+ }
+}
+
+void DocumentModel::addRestoredDocument(const QString &fileName, const QString &displayName, const Id &id)
+{
+ Entry *entry = new Entry;
+ entry->m_fileName = fileName;
+ entry->m_displayName = displayName;
+ entry->m_id = id;
+ addEntry(entry);
+}
+
+DocumentModel::Entry *DocumentModel::firstRestoredDocument() const
+{
+ for (int i = 0; i < d->m_documents.count(); ++i)
+ if (!d->m_documents.at(i)->document)
+ return d->m_documents.at(i);
+ return 0;
+}
+
+void DocumentModel::addEntry(Entry *entry)
+{
+ QString fileName = entry->fileName();
+
+ // replace a non-loaded entry (aka 'restored') if possible
+ int previousIndex = indexOfFilePath(fileName);
+ if (previousIndex >= 0) {
+ if (entry->document && d->m_documents.at(previousIndex)->document == 0) {
+ Entry *previousEntry = d->m_documents.at(previousIndex);
+ d->m_documents[previousIndex] = entry;
+ delete previousEntry;
+ connect(entry->document, SIGNAL(changed()), this, SLOT(itemChanged()));
+ } else {
+ delete entry;
+ }
+ return;
+ }
+
+ int index;
+ QString displayName = entry->displayName();
+ for (index = 0; index < d->m_documents.count(); ++index) {
+ if (displayName < d->m_documents.at(index)->displayName())
+ break;
+ }
+ int row = index + 1/*<no document>*/;
+ beginInsertRows(QModelIndex(), row, row);
+ d->m_documents.insert(index, entry);
+ if (entry->document)
+ connect(entry->document, SIGNAL(changed()), this, SLOT(itemChanged()));
+ endInsertRows();
+}
+
+int DocumentModel::indexOfFilePath(const QString &filePath) const
+{
+ if (filePath.isEmpty())
+ return -1;
+ for (int i = 0; i < d->m_documents.count(); ++i) {
+ if (d->m_documents.at(i)->fileName() == filePath)
+ return i;
+ }
+ return -1;
+}
+
+void DocumentModel::removeEntry(DocumentModel::Entry *entry)
+{
+ QTC_ASSERT(!entry->document, return); // we wouldn't know what to do with the associated editors
+ int index = d->m_documents.indexOf(entry);
+ removeDocument(index);
+}
+
+void DocumentModel::removeEditor(IEditor *editor, bool *lastOneForDocument)
+{
+ if (lastOneForDocument)
+ *lastOneForDocument = false;
+ QTC_ASSERT(editor, return);
+ IDocument *document = editor->document();
+ QTC_ASSERT(d->m_editors.contains(document), return);
+ d->m_editors[document].removeAll(editor);
+ if (d->m_editors.value(document).isEmpty()) {
+ if (lastOneForDocument)
+ *lastOneForDocument = true;
+ d->m_editors.remove(document);
+ removeDocument(indexOfDocument(document));
+ }
+}
+
+void DocumentModel::removeDocument(const QString &fileName)
+{
+ int index = indexOfFilePath(fileName);
+ QTC_ASSERT(!d->m_documents.at(index)->document, return); // we wouldn't know what to do with the associated editors
+ removeDocument(index);
+}
+
+void DocumentModel::removeDocument(int idx)
+{
+ if (idx < 0)
+ return;
+ QTC_ASSERT(idx < d->m_documents.size(), return);
+ IDocument *document = d->m_documents.at(idx)->document;
+ int row = idx + 1/*<no document>*/;
+ beginRemoveRows(QModelIndex(), row, row);
+ delete d->m_documents.takeAt(idx);
+ endRemoveRows();
+ if (document)
+ disconnect(document, SIGNAL(changed()), this, SLOT(itemChanged()));
+}
+
+void DocumentModel::removeAllRestoredDocuments()
+{
+ for (int i = d->m_documents.count()-1; i >= 0; --i) {
+ if (!d->m_documents.at(i)->document) {
+ int row = i + 1/*<no document>*/;
+ beginRemoveRows(QModelIndex(), row, row);
+ delete d->m_documents.takeAt(i);
+ endRemoveRows();
+ }
+ }
+}
+
+QList<IEditor *> DocumentModel::editorsForDocument(IDocument *document) const
+{
+ return d->m_editors.value(document);
+}
+
+QList<IEditor *> DocumentModel::editorsForDocuments(const QList<IDocument *> &documents) const
+{
+ QList<IEditor *> result;
+ foreach (IDocument *document, documents)
+ result += d->m_editors.value(document);
+ return result;
+}
+
+int DocumentModel::indexOfDocument(IDocument *document) const
+{
+ for (int i = 0; i < d->m_documents.count(); ++i)
+ if (d->m_documents.at(i)->document == document)
+ return i;
+ return -1;
+}
+
+DocumentModel::Entry *DocumentModel::entryForDocument(IDocument *document) const
+{
+ int index = indexOfDocument(document);
+ if (index < 0)
+ return 0;
+ return d->m_documents.at(index);
+}
+
+QList<IDocument *> DocumentModel::openedDocuments() const
+{
+ return d->m_editors.keys();
+}
+
+IDocument *DocumentModel::documentForFilePath(const QString &filePath) const
+{
+ int index = indexOfFilePath(filePath);
+ if (index < 0)
+ return 0;
+ return d->m_documents.at(index)->document;
+}
+
+QList<IEditor *> DocumentModel::editorsForFilePath(const QString &filePath) const
+{
+ IDocument *document = documentForFilePath(filePath);
+ if (document)
+ return editorsForDocument(document);
+ return QList<IEditor *>();
+}
+
+QModelIndex DocumentModel::index(int row, int column, const QModelIndex &parent) const
+{
+ Q_UNUSED(parent)
+ if (column < 0 || column > 1 || row < 0 || row >= d->m_documents.count() + 1/*<no document>*/)
+ return QModelIndex();
+ return createIndex(row, column);
+}
+
+DocumentModel::Entry *DocumentModel::documentAtRow(int row) const
+{
+ int entryIndex = row - 1/*<no document>*/;
+ if (entryIndex < 0)
+ return 0;
+ return d->m_documents[entryIndex];
+}
+
+int DocumentModel::documentCount() const
+{
+ return d->m_documents.count();
+}
+
+QVariant DocumentModel::data(const QModelIndex &index, int role) const
+{
+ if (!index.isValid() || (index.column() != 0 && role < Qt::UserRole))
+ return QVariant();
+ int entryIndex = index.row() - 1/*<no document>*/;
+ if (entryIndex < 0) {
+ // <no document> entry
+ switch (role) {
+ case Qt::DisplayRole:
+ return tr("<no document>");
+ case Qt::ToolTipRole:
+ return tr("No document is selected.");
+ default:
+ return QVariant();
+ }
+ }
+ const Entry *e = d->m_documents.at(entryIndex);
+ switch (role) {
+ case Qt::DisplayRole:
+ return (e->document && e->document->isModified())
+ ? e->displayName() + QLatin1Char('*')
+ : e->displayName();
+ case Qt::DecorationRole:
+ {
+ bool showLock = false;
+ if (e->document) {
+ showLock = e->document->filePath().isEmpty()
+ ? false
+ : e->document->isFileReadOnly();
+ } else {
+ showLock = !QFileInfo(e->m_fileName).isWritable();
+ }
+ return showLock ? d->m_lockedIcon : QIcon();
+ }
+ case Qt::ToolTipRole:
+ return e->fileName().isEmpty()
+ ? e->displayName()
+ : QDir::toNativeSeparators(e->fileName());
+ default:
+ return QVariant();
+ }
+ return QVariant();
+}
+
+int DocumentModel::rowOfDocument(IDocument *document) const
+{
+ if (!document)
+ return 0 /*<no document>*/;
+ return indexOfDocument(document) + 1/*<no document>*/;
+}
+
+void DocumentModel::itemChanged()
+{
+ IDocument *document = qobject_cast<IDocument *>(sender());
+
+ int idx = indexOfDocument(document);
+ if (idx < 0)
+ return;
+ QModelIndex mindex = index(idx + 1/*<no document>*/, 0);
+ emit dataChanged(mindex, mindex);
+}
+
+QList<DocumentModel::Entry *> DocumentModel::documents() const
+{
+ return d->m_documents;
+}
+
+} // namespace Core
diff --git a/src/plugins/coreplugin/editormanager/openeditorsmodel.h b/src/plugins/coreplugin/editormanager/documentmodel.h
index 61c29c5909..2ec74ff401 100644
--- a/src/plugins/coreplugin/editormanager/openeditorsmodel.h
+++ b/src/plugins/coreplugin/editormanager/documentmodel.h
@@ -27,8 +27,8 @@
**
****************************************************************************/
-#ifndef OPENEDITORSMODEL_H
-#define OPENEDITORSMODEL_H
+#ifndef DOCUMENTMODEL_H
+#define DOCUMENTMODEL_H
#include "../core_global.h"
#include "../id.h"
@@ -39,17 +39,17 @@ QT_FORWARD_DECLARE_CLASS(QIcon)
namespace Core {
-struct OpenEditorsModelPrivate;
+struct DocumentModelPrivate;
class IEditor;
class IDocument;
-class CORE_EXPORT OpenEditorsModel : public QAbstractItemModel
+class CORE_EXPORT DocumentModel : public QAbstractItemModel
{
Q_OBJECT
public:
- explicit OpenEditorsModel(QObject *parent);
- virtual ~OpenEditorsModel();
+ explicit DocumentModel(QObject *parent);
+ virtual ~DocumentModel();
QIcon lockedIcon() const;
QIcon unlockedIcon() const;
@@ -60,13 +60,9 @@ public:
int rowCount(const QModelIndex &parent = QModelIndex()) const;
QModelIndex index(int row, int column = 0, const QModelIndex &parent = QModelIndex()) const;
- void addEditor(IEditor *editor, bool isDuplicate = false);
- void addRestoredEditor(const QString &fileName, const QString &displayName, const Id &id);
- QModelIndex firstRestoredEditor() const;
-
struct CORE_EXPORT Entry {
Entry();
- IEditor *editor;
+ IDocument *document;
QString fileName() const;
QString displayName() const;
Id id() const;
@@ -74,39 +70,42 @@ public:
QString m_displayName;
Id m_id;
};
- QList<Entry> entries() const;
-
- IEditor *editorAt(int row) const;
-
- void removeEditor(IEditor *editor);
- void removeEditor(const QModelIndex &index);
- void removeEditor(const QString &fileName);
-
- void removeAllRestoredEditors();
- void emitDataChanged(IEditor *editor);
-
- QList<IEditor *> editors() const;
- QList<Entry> restoredEditors() const;
- bool isDuplicate(IEditor *editor) const;
- QList<IEditor *> duplicatesFor(IEditor *editor) const;
- IEditor *originalForDuplicate(IEditor *duplicate) const;
- void makeOriginal(IEditor *duplicate);
- QModelIndex indexOf(IEditor *editor) const;
- QString displayNameForDocument(IDocument *document) const;
+ Entry *documentAtRow(int row) const;
+ int rowOfDocument(IDocument *document) const;
+
+ int documentCount() const;
+ QList<Entry *> documents() const;
+ int indexOfDocument(IDocument *document) const;
+ int indexOfFilePath(const QString &filePath) const;
+ Entry *entryForDocument(IDocument *document) const;
+ QList<IDocument *> openedDocuments() const;
+
+ IDocument *documentForFilePath(const QString &filePath) const;
+ QList<IEditor *> editorsForFilePath(const QString &filePath) const;
+ QList<IEditor *> editorsForDocument(IDocument *document) const;
+ QList<IEditor *> editorsForDocuments(const QList<IDocument *> &documents) const;
+ QList<IEditor *> oneEditorForEachOpenedDocument() const;
+
+ // editor manager related methods, nobody else should call it
+ void addEditor(IEditor *editor, bool *isNewDocument);
+ void addRestoredDocument(const QString &fileName, const QString &displayName, const Id &id);
+ Entry *firstRestoredDocument() const;
+ void removeEditor(IEditor *editor, bool *lastOneForDocument);
+ void removeDocument(const QString &fileName);
+ void removeEntry(Entry *entry);
+ void removeAllRestoredDocuments();
private slots:
void itemChanged();
private:
- void addEntry(const Entry &entry);
- int findEditor(IEditor *editor) const;
- int findFileName(const QString &filename) const;
- void removeEditor(int idx);
+ void addEntry(Entry *entry);
+ void removeDocument(int idx);
- OpenEditorsModelPrivate *d;
+ DocumentModelPrivate *d;
};
} // namespace Core
-#endif // OPENEDITORSMODEL_H
+#endif // DOCUMENTMODEL_H
diff --git a/src/plugins/coreplugin/editormanager/editormanager.cpp b/src/plugins/coreplugin/editormanager/editormanager.cpp
index 2f1cc62df8..4a9890f05e 100644
--- a/src/plugins/coreplugin/editormanager/editormanager.cpp
+++ b/src/plugins/coreplugin/editormanager/editormanager.cpp
@@ -29,34 +29,34 @@
#include "editormanager.h"
#include "editorview.h"
-#include "findplaceholder.h"
#include "openeditorswindow.h"
#include "openeditorsview.h"
-#include "openeditorsmodel.h"
-#include "openwithdialog.h"
-#include "outputpane.h"
-#include "outputpanemanager.h"
-#include "rightpane.h"
-#include "documentmanager.h"
-#include "icore.h"
+#include "documentmodel.h"
#include "ieditor.h"
-#include "iversioncontrol.h"
-#include "mimedatabase.h"
-#include "vcsmanager.h"
#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/coreconstants.h>
+#include <coreplugin/dialogs/openwithdialog.h>
+#include <coreplugin/dialogs/readonlyfilesdialog.h>
+#include <coreplugin/documentmanager.h>
#include <coreplugin/editormanager/ieditorfactory.h>
#include <coreplugin/editormanager/iexternaleditor.h>
#include <coreplugin/editortoolbar.h>
#include <coreplugin/fileutils.h>
+#include <coreplugin/findplaceholder.h>
+#include <coreplugin/icore.h>
#include <coreplugin/icorelistener.h>
#include <coreplugin/infobar.h>
+#include <coreplugin/iversioncontrol.h>
+#include <coreplugin/mimedatabase.h>
#include <coreplugin/modemanager.h>
+#include <coreplugin/outputpane.h>
+#include <coreplugin/outputpanemanager.h>
+#include <coreplugin/rightpane.h>
#include <coreplugin/settingsdatabase.h>
#include <coreplugin/variablemanager.h>
-#include <coreplugin/dialogs/readonlyfilesdialog.h>
+#include <coreplugin/vcsmanager.h>
#include <extensionsystem/pluginmanager.h>
@@ -96,31 +96,15 @@ namespace Internal {
class EditorClosingCoreListener : public ICoreListener
{
public:
- EditorClosingCoreListener(EditorManager *em);
- bool editorAboutToClose(IEditor *editor);
- bool coreAboutToClose();
-
-private:
- EditorManager *m_em;
+ bool editorAboutToClose(IEditor *) { return true; }
+ bool coreAboutToClose()
+ {
+ // Do not ask for files to save.
+ // MainWindow::closeEvent has already done that.
+ return EditorManager::closeAllEditors(false);
+ }
};
-EditorClosingCoreListener::EditorClosingCoreListener(EditorManager *em)
- : m_em(em)
-{
-}
-
-bool EditorClosingCoreListener::editorAboutToClose(IEditor *)
-{
- return true;
-}
-
-bool EditorClosingCoreListener::coreAboutToClose()
-{
- // Do not ask for files to save.
- // MainWindow::closeEvent has already done that.
- return m_em->closeAllEditors(false);
-}
-
} // namespace Internal
} // namespace Core
@@ -172,8 +156,9 @@ EditorManagerPlaceHolder* EditorManagerPlaceHolder::current()
namespace Core {
-struct EditorManagerPrivate
+class EditorManagerPrivate
{
+public:
explicit EditorManagerPrivate(QWidget *parent);
~EditorManagerPrivate();
QList<EditLocation> m_globalHistory;
@@ -191,6 +176,7 @@ struct EditorManagerPrivate
QAction *m_closeCurrentEditorAction;
QAction *m_closeAllEditorsAction;
QAction *m_closeOtherEditorsAction;
+ QAction *m_closeAllEditorsExceptVisibleAction;
QAction *m_gotoNextDocHistoryAction;
QAction *m_gotoPreviousDocHistoryAction;
QAction *m_goBackAction;
@@ -209,9 +195,11 @@ struct EditorManagerPrivate
QAction *m_closeCurrentEditorContextAction;
QAction *m_closeAllEditorsContextAction;
QAction *m_closeOtherEditorsContextAction;
+ QAction *m_closeAllEditorsExceptVisibleContextAction;
QAction *m_openGraphicalShellAction;
QAction *m_openTerminalAction;
- QModelIndex m_contextMenuEditorIndex;
+ QAction *m_findInDirectoryAction;
+ DocumentModel::Entry *m_contextMenuEntry;
Internal::OpenEditorsWindow *m_windowPopup;
Internal::EditorClosingCoreListener *m_coreListener;
@@ -219,11 +207,12 @@ struct EditorManagerPrivate
QMap<QString, QVariant> m_editorStates;
Internal::OpenEditorsViewFactory *m_openEditorsFactory;
- OpenEditorsModel *m_editorModel;
+ DocumentModel *m_documentModel;
IDocument::ReloadSetting m_reloadSetting;
QString m_titleAddition;
+ QString m_titleVcsTopic;
bool m_autoSaveEnabled;
int m_autoSaveInterval;
@@ -238,6 +227,7 @@ EditorManagerPrivate::EditorManagerPrivate(QWidget *parent) :
m_closeCurrentEditorAction(new QAction(EditorManager::tr("Close"), parent)),
m_closeAllEditorsAction(new QAction(EditorManager::tr("Close All"), parent)),
m_closeOtherEditorsAction(new QAction(EditorManager::tr("Close Others"), parent)),
+ m_closeAllEditorsExceptVisibleAction(new QAction(EditorManager::tr("Close All Except Visible"), parent)),
m_gotoNextDocHistoryAction(new QAction(EditorManager::tr("Next Open Document in History"), 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)),
@@ -248,15 +238,17 @@ EditorManagerPrivate::EditorManagerPrivate(QWidget *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)),
+ m_closeAllEditorsExceptVisibleContextAction(new QAction(EditorManager::tr("Close All Except Visible"), parent)),
m_openGraphicalShellAction(new QAction(FileUtils::msgGraphicalShellAction(), parent)),
m_openTerminalAction(new QAction(FileUtils::msgTerminalAction(), parent)),
+ m_findInDirectoryAction(new QAction(FileUtils::msgFindInDirectory(), parent)),
m_windowPopup(0),
m_coreListener(0),
m_reloadSetting(IDocument::AlwaysAsk),
m_autoSaveEnabled(true),
m_autoSaveInterval(5)
{
- m_editorModel = new OpenEditorsModel(parent);
+ m_documentModel = new DocumentModel(parent);
}
EditorManagerPrivate::~EditorManagerPrivate()
@@ -265,13 +257,14 @@ EditorManagerPrivate::~EditorManagerPrivate()
}
static EditorManager *m_instance = 0;
+static EditorManagerPrivate *d;
-EditorManager *EditorManager::instance() { return m_instance; }
+QWidget *EditorManager::instance() { return m_instance; }
EditorManager::EditorManager(QWidget *parent) :
- QWidget(parent),
- d(new EditorManagerPrivate(parent))
+ QWidget(parent)
{
+ d = new EditorManagerPrivate(parent);
m_instance = this;
connect(ICore::instance(), SIGNAL(contextAboutToChange(QList<Core::IContext*>)),
@@ -336,6 +329,11 @@ EditorManager::EditorManager(QWidget *parent) :
cmd->setAttribute(Core::Command::CA_UpdateText);
connect(d->m_closeOtherEditorsAction, SIGNAL(triggered()), this, SLOT(closeOtherEditors()));
+ // Close All Others Except Visible Action
+ cmd = ActionManager::registerAction(d->m_closeAllEditorsExceptVisibleAction, Constants::CLOSEALLEXCEPTVISIBLE, editManagerContext, true);
+ mfile->addAction(cmd, Constants::G_FILE_CLOSE);
+ connect(d->m_closeAllEditorsExceptVisibleAction, SIGNAL(triggered()), this, SLOT(closeAllEditorsExceptVisible()));
+
//Save XXX Context Actions
connect(d->m_saveCurrentEditorContextAction, SIGNAL(triggered()), this, SLOT(saveDocumentFromContextMenu()));
connect(d->m_saveAsCurrentEditorContextAction, SIGNAL(triggered()), this, SLOT(saveDocumentAsFromContextMenu()));
@@ -345,9 +343,11 @@ EditorManager::EditorManager(QWidget *parent) :
connect(d->m_closeAllEditorsContextAction, SIGNAL(triggered()), this, SLOT(closeAllEditors()));
connect(d->m_closeCurrentEditorContextAction, SIGNAL(triggered()), this, SLOT(closeEditorFromContextMenu()));
connect(d->m_closeOtherEditorsContextAction, SIGNAL(triggered()), this, SLOT(closeOtherEditorsFromContextMenu()));
+ connect(d->m_closeAllEditorsExceptVisibleContextAction, SIGNAL(triggered()), this, SLOT(closeAllEditorsExceptVisible()));
connect(d->m_openGraphicalShellAction, SIGNAL(triggered()), this, SLOT(showInGraphicalShell()));
connect(d->m_openTerminalAction, SIGNAL(triggered()), this, SLOT(openTerminal()));
+ connect(d->m_findInDirectoryAction, SIGNAL(triggered()), this, SLOT(findInDirectory()));
// Goto Previous In History Action
cmd = ActionManager::registerAction(d->m_gotoPreviousDocHistoryAction, Constants::GOTOPREVINHISTORY, editDesignContext);
@@ -474,7 +474,7 @@ EditorManager::~EditorManager()
void EditorManager::init()
{
- d->m_coreListener = new EditorClosingCoreListener(this);
+ d->m_coreListener = new EditorClosingCoreListener();
ExtensionSystem::PluginManager::addObject(d->m_coreListener);
d->m_openEditorsFactory = new OpenEditorsViewFactory();
@@ -486,7 +486,7 @@ void EditorManager::init()
VariableManager::registerVariable(kCurrentDocumentYPos,
tr("Y-coordinate of the current editor's upper left corner, relative to screen."));
connect(VariableManager::instance(), SIGNAL(variableUpdateRequested(QByteArray)),
- this, SLOT(updateVariable(QByteArray)));
+ m_instance, SLOT(updateVariable(QByteArray)));
}
void EditorManager::updateAutoSave()
@@ -504,9 +504,9 @@ EditorToolBar *EditorManager::createToolBar(QWidget *parent)
void EditorManager::removeEditor(IEditor *editor)
{
- bool isDuplicate = d->m_editorModel->isDuplicate(editor);
- d->m_editorModel->removeEditor(editor);
- if (!isDuplicate)
+ bool lastOneForDocument = false;
+ d->m_documentModel->removeEditor(editor, &lastOneForDocument);
+ if (lastOneForDocument)
DocumentManager::removeDocument(editor->document());
ICore::removeContextObject(editor);
}
@@ -527,7 +527,7 @@ void EditorManager::handleContextChange(const QList<Core::IContext *> &context)
// the locator line edit) first activates the window and sets focus to its focus widget.
// Only afterwards the focus is shifted to the widget that received the click.
d->m_scheduledCurrentEditor = editor;
- QTimer::singleShot(0, this, SLOT(setCurrentEditorFromContextChange()));
+ QTimer::singleShot(0, m_instance, SLOT(setCurrentEditorFromContextChange()));
} else {
updateActions();
}
@@ -552,7 +552,7 @@ void EditorManager::setCurrentEditor(IEditor *editor, bool ignoreNavigationHisto
}
updateActions();
updateWindowTitle();
- emit currentEditorChanged(editor);
+ emit m_instance->currentEditorChanged(editor);
}
@@ -575,7 +575,7 @@ void EditorManager::setCurrentView(Internal::EditorView *view)
}
}
-Internal::EditorView *EditorManager::currentEditorView() const
+Internal::EditorView *EditorManager::currentEditorView()
{
EditorView *view = d->m_currentView;
if (!view) {
@@ -612,7 +612,7 @@ SplitterOrView *EditorManager::findRoot(const EditorView *view, int *rootIndex)
{
SplitterOrView *current = view->parentSplitterOrView();
while (current) {
- int index = m_instance->d->m_root.indexOf(current);
+ int index = d->m_root.indexOf(current);
if (index >= 0) {
if (rootIndex)
*rootIndex = index;
@@ -624,30 +624,14 @@ SplitterOrView *EditorManager::findRoot(const EditorView *view, int *rootIndex)
return 0;
}
-QList<IEditor *> EditorManager::editorsForFileName(const QString &filename) const
+IDocument *EditorManager::currentDocument()
{
- QList<IEditor *> found;
- QString fixedname = DocumentManager::fixFileName(filename, DocumentManager::KeepLinks);
- foreach (IEditor *editor, openedEditors()) {
- if (fixedname == DocumentManager::fixFileName(editor->document()->fileName(), DocumentManager::KeepLinks))
- found << editor;
- }
- return found;
-}
-
-QList<IEditor *> EditorManager::editorsForDocument(IDocument *document) const
-{
- QList<IEditor *> found;
- foreach (IEditor *editor, openedEditors()) {
- if (editor->document() == document)
- found << editor;
- }
- return found;
+ return d->m_currentEditor ? d->m_currentEditor->document() : 0;
}
IEditor *EditorManager::currentEditor()
{
- return m_instance->d->m_currentEditor;
+ return d->m_currentEditor;
}
void EditorManager::emptyView(Core::Internal::EditorView *view)
@@ -657,28 +641,24 @@ void EditorManager::emptyView(Core::Internal::EditorView *view)
QList<IEditor *> editors = view->editors();
foreach (IEditor *editor, editors) {
- if (!d->m_editorModel->isDuplicate(editor)) {
- QList<IEditor *> duplicates = d->m_editorModel->duplicatesFor(editor);
- if (!duplicates.isEmpty()) {
- d->m_editorModel->makeOriginal(duplicates.first());
- } else {
- // it's the only editor for that file and it's not a duplicate,
- // so we need to keep it around (--> in the editor model)
- if (currentEditor() == editor) {
- // we don't want a current editor that is not open in a view
- setCurrentEditor(0);
- }
- editors.removeAll(editor);
- view->removeEditor(editor);
- continue; // don't close the editor
+ if (d->m_documentModel->editorsForDocument(editor->document()).size() == 1) {
+ // it's the only editor for that file
+ // so we need to keep it around (--> in the editor model)
+ if (currentEditor() == editor) {
+ // we don't want a current editor that is not open in a view
+ setCurrentView(view);
+ setCurrentEditor(0);
}
+ editors.removeAll(editor);
+ view->removeEditor(editor);
+ continue; // don't close the editor
}
- emit editorAboutToClose(editor);
+ emit m_instance->editorAboutToClose(editor);
removeEditor(editor);
view->removeEditor(editor);
}
if (!editors.isEmpty()) {
- emit editorsClosed(editors);
+ emit m_instance->editorsClosed(editors);
foreach (IEditor *editor, editors) {
delete editor;
}
@@ -702,8 +682,8 @@ void EditorManager::splitNewWindow(Internal::EditorView *view)
context->setContext(Context(Constants::C_EDITORMANAGER));
context->setWidget(splitter);
ICore::addContextObject(context);
- m_instance->d->m_root.append(splitter);
- m_instance->d->m_rootContext.append(context);
+ d->m_root.append(splitter);
+ d->m_rootContext.append(context);
connect(splitter, SIGNAL(destroyed(QObject*)), m_instance, SLOT(rootDestroyed(QObject*)));
splitter->show();
ICore::raiseWindow(splitter);
@@ -740,54 +720,35 @@ void EditorManager::closeView(Core::Internal::EditorView *view)
}
}
-QList<IEditor*>
- EditorManager::editorsForDocuments(QList<IDocument*> documents) const
-{
- const QList<IEditor *> editors = openedEditors();
- QSet<IEditor *> found;
- foreach (IDocument *document, documents) {
- foreach (IEditor *editor, editors) {
- if (editor->document() == document && !found.contains(editor))
- found << editor;
- }
- }
- return found.toList();
-}
-
-QList<IDocument *> EditorManager::documentsForEditors(QList<IEditor *> editors) const
-{
- QSet<IEditor *> handledEditors;
- QList<IDocument *> documents;
- foreach (IEditor *editor, editors) {
- if (!handledEditors.contains(editor)) {
- documents << editor->document();
- handledEditors.insert(editor);
- }
- }
- return documents;
-}
-
bool EditorManager::closeAllEditors(bool askAboutModifiedEditors)
{
- d->m_editorModel->removeAllRestoredEditors();
- if (closeEditors(openedEditors(), askAboutModifiedEditors)) {
-// d->clearNavigationHistory();
+ d->m_documentModel->removeAllRestoredDocuments();
+ if (closeDocuments(d->m_documentModel->openedDocuments(), askAboutModifiedEditors)) {
return true;
}
return false;
}
-void EditorManager::closeOtherEditors(IEditor *editor)
+void EditorManager::closeAllEditorsExceptVisible()
{
- d->m_editorModel->removeAllRestoredEditors();
- QList<IEditor*> editors = openedEditors();
- editors.removeAll(editor);
- closeEditors(editors, true);
+ d->m_documentModel->removeAllRestoredDocuments();
+ QList<IDocument *> documentsToClose = d->m_documentModel->openedDocuments();
+ foreach (IEditor *editor, visibleEditors())
+ documentsToClose.removeAll(editor->document());
+ closeDocuments(documentsToClose, true);
+}
+
+void EditorManager::closeOtherEditors(IDocument *document)
+{
+ d->m_documentModel->removeAllRestoredDocuments();
+ QList<IDocument *> documentsToClose = d->m_documentModel->openedDocuments();
+ documentsToClose.removeAll(document);
+ closeDocuments(documentsToClose, true);
}
void EditorManager::closeOtherEditors()
{
- IEditor *current = currentEditor();
+ IDocument *current = currentDocument();
QTC_ASSERT(current, return);
closeOtherEditors(current);
}
@@ -810,18 +771,18 @@ static void assignAction(QAction *self, QAction *other)
self->setIconVisibleInMenu(other->isIconVisibleInMenu());
}
-void EditorManager::addSaveAndCloseEditorActions(QMenu *contextMenu, const QModelIndex &editorIndex)
+void EditorManager::addSaveAndCloseEditorActions(QMenu *contextMenu, DocumentModel::Entry *entry)
{
QTC_ASSERT(contextMenu, return);
- d->m_contextMenuEditorIndex = editorIndex;
+ d->m_contextMenuEntry = entry;
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*>();
+ IDocument *document = entry ? entry->document : 0;
- setupSaveActions(editor,
+ setupSaveActions(document,
d->m_saveCurrentEditorContextAction,
d->m_saveAsCurrentEditorContextAction,
d->m_revertToSavedCurrentEditorContextAction);
@@ -833,27 +794,32 @@ void EditorManager::addSaveAndCloseEditorActions(QMenu *contextMenu, const QMode
contextMenu->addSeparator();
- d->m_closeCurrentEditorContextAction->setText(editorIndex.isValid()
- ? tr("Close \"%1\"").arg(editorIndex.data().toString())
+ d->m_closeCurrentEditorContextAction->setText(entry
+ ? tr("Close \"%1\"").arg(entry->displayName())
: tr("Close Editor"));
- d->m_closeOtherEditorsContextAction->setText(editorIndex.isValid()
- ? tr("Close All Except \"%1\"").arg(editorIndex.data().toString())
+ d->m_closeOtherEditorsContextAction->setText(entry
+ ? tr("Close All Except \"%1\"").arg(entry->displayName())
: tr("Close Other Editors"));
- d->m_closeCurrentEditorContextAction->setEnabled(editorIndex.isValid());
- d->m_closeOtherEditorsContextAction->setEnabled(editorIndex.isValid());
- d->m_closeAllEditorsContextAction->setEnabled(!openedEditors().isEmpty());
+ d->m_closeCurrentEditorContextAction->setEnabled(entry != 0);
+ d->m_closeOtherEditorsContextAction->setEnabled(entry != 0);
+ d->m_closeAllEditorsContextAction->setEnabled(!d->m_documentModel->documents().isEmpty());
+ d->m_closeAllEditorsExceptVisibleContextAction->setEnabled(visibleDocumentsCount() < d->m_documentModel->documents().count());
contextMenu->addAction(d->m_closeCurrentEditorContextAction);
contextMenu->addAction(d->m_closeAllEditorsContextAction);
contextMenu->addAction(d->m_closeOtherEditorsContextAction);
+ contextMenu->addAction(d->m_closeAllEditorsExceptVisibleContextAction);
}
-void EditorManager::addNativeDirActions(QMenu *contextMenu, const QModelIndex &editorIndex)
+void EditorManager::addNativeDirActions(QMenu *contextMenu, DocumentModel::Entry *entry)
{
QTC_ASSERT(contextMenu, return);
- d->m_openGraphicalShellAction->setEnabled(editorIndex.isValid());
- d->m_openTerminalAction->setEnabled(editorIndex.isValid());
+ bool enabled = entry && !entry->fileName().isEmpty();
+ d->m_openGraphicalShellAction->setEnabled(enabled);
+ d->m_openTerminalAction->setEnabled(enabled);
+ d->m_findInDirectoryAction->setEnabled(enabled);
contextMenu->addAction(d->m_openGraphicalShellAction);
contextMenu->addAction(d->m_openTerminalAction);
+ contextMenu->addAction(d->m_findInDirectoryAction);
}
static void setFocusToEditorViewAndUnmaximizePanes(EditorView *view)
@@ -951,45 +917,57 @@ void EditorManager::doEscapeKeyFocusMoveMagic()
void EditorManager::saveDocumentFromContextMenu()
{
- IEditor *editor = d->m_contextMenuEditorIndex.data(Qt::UserRole).value<Core::IEditor*>();
- if (editor)
- saveDocument(editor->document());
+ IDocument *document = d->m_contextMenuEntry ? d->m_contextMenuEntry->document : 0;
+ if (document)
+ saveDocument(document);
}
void EditorManager::saveDocumentAsFromContextMenu()
{
- IEditor *editor = d->m_contextMenuEditorIndex.data(Qt::UserRole).value<Core::IEditor*>();
- if (editor)
- saveDocumentAs(editor->document());
+ IDocument *document = d->m_contextMenuEntry ? d->m_contextMenuEntry->document : 0;
+ if (document)
+ saveDocumentAs(document);
}
void EditorManager::revertToSavedFromContextMenu()
{
- IEditor *editor = d->m_contextMenuEditorIndex.data(Qt::UserRole).value<Core::IEditor*>();
- if (editor)
- revertToSaved(editor);
+ IDocument *document = d->m_contextMenuEntry ? d->m_contextMenuEntry->document : 0;
+ if (document)
+ revertToSaved(document);
}
void EditorManager::closeEditorFromContextMenu()
{
- closeEditor(d->m_contextMenuEditorIndex);
+ IDocument *document = d->m_contextMenuEntry ? d->m_contextMenuEntry->document : 0;
+ if (document)
+ closeEditors(d->m_documentModel->editorsForDocument(document));
}
void EditorManager::closeOtherEditorsFromContextMenu()
{
- closeOtherEditors(d->m_contextMenuEditorIndex.data(Qt::UserRole).value<IEditor *>());
+ IDocument *document = d->m_contextMenuEntry ? d->m_contextMenuEntry->document : 0;
+ closeOtherEditors(document);
}
void EditorManager::showInGraphicalShell()
{
- const QString path = d->m_contextMenuEditorIndex.data(Qt::UserRole + 1).toString();
- Core::FileUtils::showInGraphicalShell(ICore::mainWindow(), path);
+ if (!d->m_contextMenuEntry || d->m_contextMenuEntry->fileName().isEmpty())
+ return;
+ Core::FileUtils::showInGraphicalShell(ICore::mainWindow(), d->m_contextMenuEntry->fileName());
}
void EditorManager::openTerminal()
{
- const QString path = QFileInfo(d->m_contextMenuEditorIndex.data(Qt::UserRole + 1).toString()).path();
- Core::FileUtils::openTerminal(path);
+ if (!d->m_contextMenuEntry || d->m_contextMenuEntry->fileName().isEmpty())
+ return;
+ Core::FileUtils::openTerminal(QFileInfo(d->m_contextMenuEntry->fileName()).path());
+}
+
+void EditorManager::findInDirectory()
+{
+ if (!d->m_contextMenuEntry || d->m_contextMenuEntry->fileName().isEmpty())
+ return;
+ emit m_instance->findOnFileSystemRequest(QFileInfo(d->m_contextMenuEntry->fileName()).path());
}
void EditorManager::rootDestroyed(QObject *root)
@@ -1048,20 +1026,21 @@ void EditorManager::setCurrentEditorFromContextChange()
setCurrentEditor(newCurrent);
}
-void EditorManager::closeEditor(Core::IEditor *editor)
+void EditorManager::closeEditor(Core::IEditor *editor, bool askAboutModifiedEditors)
{
if (!editor)
return;
- closeEditors(QList<IEditor *>() << editor);
+ closeEditors(QList<IEditor *>() << editor, askAboutModifiedEditors);
}
-void EditorManager::closeEditor(const QModelIndex &index)
+void EditorManager::closeEditor(DocumentModel::Entry *entry)
{
- IEditor *editor = index.data(Qt::UserRole).value<Core::IEditor*>();
- if (editor)
- closeEditor(editor);
+ if (!entry)
+ return;
+ if (entry->document)
+ closeEditors(d->m_documentModel->editorsForDocument(entry->document));
else
- d->m_editorModel->removeEditor(index);
+ d->m_documentModel->removeEntry(entry);
}
bool EditorManager::closeEditors(const QList<IEditor*> &editorsToClose, bool askAboutModifiedEditors)
@@ -1072,14 +1051,13 @@ bool EditorManager::closeEditors(const QList<IEditor*> &editorsToClose, bool ask
EditorView *currentView = currentEditorView();
bool closingFailed = false;
- QList<IEditor*> acceptedEditors;
+ QSet<IEditor*> acceptedEditors;
+ QSet<IDocument *> acceptedDocuments;
//ask all core listeners to check whether the editor can be closed
const QList<ICoreListener *> listeners =
ExtensionSystem::PluginManager::getObjects<ICoreListener>();
foreach (IEditor *editor, editorsToClose) {
bool editorAccepted = true;
- if (d->m_editorModel->isDuplicate(editor))
- editor = d->m_editorModel->originalForDuplicate(editor);
foreach (ICoreListener *listener, listeners) {
if (!listener->editorAboutToClose(editor)) {
editorAccepted = false;
@@ -1087,21 +1065,24 @@ bool EditorManager::closeEditors(const QList<IEditor*> &editorsToClose, bool ask
break;
}
}
- if (editorAccepted)
- acceptedEditors.append(editor);
+ if (editorAccepted) {
+ acceptedEditors += d->m_documentModel->editorsForDocument(editor->document()).toSet();
+ acceptedDocuments.insert(editor->document());
+ }
}
if (acceptedEditors.isEmpty())
return false;
//ask whether to save modified files
if (askAboutModifiedEditors) {
bool cancelled = false;
- QList<IDocument*> list = DocumentManager::saveModifiedDocuments(documentsForEditors(acceptedEditors), &cancelled);
+ QList<IDocument*> list = DocumentManager::saveModifiedDocuments(acceptedDocuments.toList(), &cancelled);
if (cancelled)
return false;
if (!list.isEmpty()) {
closingFailed = true;
- QSet<IEditor*> skipSet = editorsForDocuments(list).toSet();
- acceptedEditors = acceptedEditors.toSet().subtract(skipSet).toList();
+ acceptedDocuments.subtract(list.toSet());
+ QSet<IEditor*> skipSet = d->m_documentModel->editorsForDocuments(list).toSet();
+ acceptedEditors = acceptedEditors.subtract(skipSet);
}
}
if (acceptedEditors.isEmpty())
@@ -1110,22 +1091,16 @@ bool EditorManager::closeEditors(const QList<IEditor*> &editorsToClose, bool ask
// close Editor History list
windowPopup()->setVisible(false);
- // add duplicates
- QList<IEditor *> duplicates;
- foreach (IEditor *editor, acceptedEditors)
- duplicates += d->m_editorModel->duplicatesFor(editor);
- acceptedEditors += duplicates;
-
QList<EditorView*> closedViews;
// remove the editors
foreach (IEditor *editor, acceptedEditors) {
- emit editorAboutToClose(editor);
- if (!editor->document()->fileName().isEmpty()
- && !editor->isTemporary()) {
+ emit m_instance->editorAboutToClose(editor);
+ if (!editor->document()->filePath().isEmpty()
+ && !editor->document()->isTemporary()) {
QByteArray state = editor->saveState();
if (!state.isEmpty())
- d->m_editorStates.insert(editor->document()->fileName(), QVariant(state));
+ d->m_editorStates.insert(editor->document()->filePath(), QVariant(state));
}
removeEditor(editor);
@@ -1141,30 +1116,40 @@ bool EditorManager::closeEditors(const QList<IEditor*> &editorsToClose, bool ask
}
}
+ bool currentViewHandled = false;
foreach (EditorView *view, closedViews) {
+ OpenEditorFlags flags;
+ if (view == currentView)
+ currentViewHandled = true;
+ else
+ flags = OpenEditorFlags(DoNotChangeCurrentEditor);
IEditor *newCurrent = view->currentEditor();
if (!newCurrent)
newCurrent = pickUnusedEditor();
if (newCurrent) {
- activateEditor(view, newCurrent, DoNotChangeCurrentEditor);
+ activateEditor(view, newCurrent, flags);
} else {
- QModelIndex idx = d->m_editorModel->firstRestoredEditor();
- if (idx.isValid()) {
- activateEditorForIndex(view, idx, DoNotChangeCurrentEditor);
+ DocumentModel::Entry *entry = d->m_documentModel->firstRestoredDocument();
+ if (entry) {
+ activateEditorForEntry(view, entry, flags);
} else {
- const QList<IEditor *> editors = d->m_editorModel->editors();
- if (!editors.isEmpty())
- activateEditor(view, editors.last(), DoNotChangeCurrentEditor);
+ // no "restored" ones, so any entry left should have a document
+ const QList<DocumentModel::Entry *> documents = d->m_documentModel->documents();
+ if (!documents.isEmpty()) {
+ IDocument *document = documents.last()->document;
+ if (document)
+ activateEditorForDocument(view, document, flags);
+ }
}
}
}
- emit editorsClosed(acceptedEditors);
+ emit m_instance->editorsClosed(acceptedEditors.toList());
foreach (IEditor *editor, acceptedEditors)
editor->deleteLater();
- if (currentView) {
+ if (currentView && !currentViewHandled) {
if (IEditor *editor = currentView->currentEditor())
activateEditor(currentView, editor);
else
@@ -1172,7 +1157,7 @@ bool EditorManager::closeEditors(const QList<IEditor*> &editorsToClose, bool ask
}
if (!currentEditor()) {
- emit currentEditorChanged(0);
+ emit m_instance->currentEditorChanged(0);
updateActions();
updateWindowTitle();
}
@@ -1180,53 +1165,10 @@ bool EditorManager::closeEditors(const QList<IEditor*> &editorsToClose, bool ask
return !closingFailed;
}
-void EditorManager::closeDuplicate(Core::IEditor *editor)
+Core::IEditor *EditorManager::pickUnusedEditor(EditorView **foundView)
{
-
- IEditor *original = editor;
- if (d->m_editorModel->isDuplicate(editor))
- original= d->m_editorModel->originalForDuplicate(editor);
- QList<IEditor *> duplicates = d->m_editorModel->duplicatesFor(original);
-
- if (duplicates.isEmpty()) {
- closeEditor(editor);
- return;
- }
-
- if (original== editor)
- d->m_editorModel->makeOriginal(duplicates.first());
-
- EditorView *currentView = currentEditorView();
-
- emit editorAboutToClose(editor);
-
- if (EditorView *view = viewForEditor(editor)) {
- removeEditor(editor);
- view->removeEditor(editor);
-
- IEditor *newCurrent = view->currentEditor();
- if (!newCurrent)
- newCurrent = pickUnusedEditor();
- if (newCurrent) {
- activateEditor(view, newCurrent, DoNotChangeCurrentEditor);
- } else {
- QModelIndex idx = d->m_editorModel->firstRestoredEditor();
- if (idx.isValid())
- activateEditorForIndex(view, idx, DoNotChangeCurrentEditor);
- }
- }
-
- emit editorsClosed(QList<IEditor*>() << editor);
- delete editor;
- if (currentView) {
- if (IEditor *currentEditor = currentView->currentEditor())
- activateEditor(currentView, currentEditor);
- }
-}
-
-Core::IEditor *EditorManager::pickUnusedEditor(EditorView **foundView) const
-{
- foreach (IEditor *editor, openedEditors()) {
+ foreach (IEditor *editor,
+ d->m_documentModel->editorsForDocuments(d->m_documentModel->openedDocuments())) {
EditorView *view = viewForEditor(editor);
if (!view || view->currentEditor() != editor) {
if (foundView)
@@ -1237,24 +1179,28 @@ Core::IEditor *EditorManager::pickUnusedEditor(EditorView **foundView) const
return 0;
}
-void EditorManager::activateEditorForIndex(const QModelIndex &index, OpenEditorFlags flags)
+void EditorManager::activateEditorForEntry(DocumentModel::Entry *entry, OpenEditorFlags flags)
{
- activateEditorForIndex(currentEditorView(), index, flags);
+ activateEditorForEntry(currentEditorView(), entry, flags);
}
-void EditorManager::activateEditorForIndex(Internal::EditorView *view, const QModelIndex &index, OpenEditorFlags flags)
+void EditorManager::activateEditorForEntry(Internal::EditorView *view, DocumentModel::Entry *entry, OpenEditorFlags flags)
{
- Q_ASSERT(view);
- IEditor *editor = index.data(Qt::UserRole).value<IEditor*>();
- if (editor) {
- activateEditor(view, editor, flags);
+ QTC_ASSERT(view, return);
+ if (!entry) { // no document
+ view->setCurrentEditor(0);
+ setCurrentView(view);
+ setCurrentEditor(0);
+ return;
+ }
+ IDocument *document = entry->document;
+ if (document) {
+ activateEditorForDocument(view, document, flags);
return;
}
- QString fileName = index.data(Qt::UserRole + 1).toString();
- Core::Id id = index.data(Qt::UserRole + 2).value<Core::Id>();
- if (!openEditor(view, fileName, id, flags))
- d->m_editorModel->removeEditor(index);
+ if (!openEditor(view, entry->fileName(), entry->id(), flags))
+ d->m_documentModel->removeEntry(entry);
}
void EditorManager::activateView(EditorView *view)
@@ -1280,6 +1226,7 @@ Core::IEditor *EditorManager::placeEditor(Core::Internal::EditorView *view, Core
bool duplicateSupported = editor->duplicateSupported();
if (EditorView *sourceView = viewForEditor(editor)) {
if (editor != sourceView->currentEditor() || !duplicateSupported) {
+ // pull the IEditor over to the new view
sourceView->removeEditor(editor);
view->addEditor(editor);
view->setCurrentEditor(editor);
@@ -1295,7 +1242,6 @@ Core::IEditor *EditorManager::placeEditor(Core::Internal::EditorView *view, Core
} else if (duplicateSupported) {
editor = duplicateEditor(editor);
Q_ASSERT(editor);
- d->m_editorModel->makeOriginal(editor);
}
}
view->addEditor(editor);
@@ -1347,10 +1293,15 @@ Core::IEditor *EditorManager::activateEditor(Core::Internal::EditorView *view, C
return editor;
}
+IEditor *EditorManager::activateEditorForDocument(IDocument *document, OpenEditorFlags flags)
+{
+ return activateEditorForDocument(currentEditorView(), document, flags);
+}
+
Core::IEditor *EditorManager::activateEditorForDocument(Core::Internal::EditorView *view, Core::IDocument *document, OpenEditorFlags flags)
{
Q_ASSERT(view);
- const QList<IEditor*> editors = editorsForDocument(document);
+ const QList<IEditor*> editors = d->m_documentModel->editorsForDocument(document);
if (editors.isEmpty())
return 0;
@@ -1361,8 +1312,7 @@ Core::IEditor *EditorManager::activateEditorForDocument(Core::Internal::EditorVi
* or IExternalEditor), find the one best matching the mimetype passed in.
* Recurse over the parent classes of the mimetype to find them. */
template <class EditorFactoryLike>
-static void mimeTypeFactoryRecursion(const MimeDatabase *db,
- const MimeType &mimeType,
+static void mimeTypeFactoryRecursion(const MimeType &mimeType,
const QList<EditorFactoryLike*> &allFactories,
bool firstMatchOnly,
QList<EditorFactoryLike*> *list)
@@ -1386,8 +1336,8 @@ static void mimeTypeFactoryRecursion(const MimeDatabase *db,
return;
const QStringList::const_iterator pcend = parentTypes .constEnd();
for (QStringList::const_iterator pit = parentTypes .constBegin(); pit != pcend; ++pit) {
- if (const MimeType parent = db->findByType(*pit))
- mimeTypeFactoryRecursion(db, parent, allFactories, firstMatchOnly, list);
+ if (const MimeType parent = MimeDatabase::findByType(*pit))
+ mimeTypeFactoryRecursion(parent, allFactories, firstMatchOnly, list);
}
}
@@ -1396,7 +1346,7 @@ EditorManager::EditorFactoryList
{
EditorFactoryList rc;
const EditorFactoryList allFactories = ExtensionSystem::PluginManager::getObjects<IEditorFactory>();
- mimeTypeFactoryRecursion(ICore::mimeDatabase(), mimeType, allFactories, bestMatchOnly, &rc);
+ mimeTypeFactoryRecursion(mimeType, allFactories, bestMatchOnly, &rc);
if (debugEditorManager)
qDebug() << Q_FUNC_INFO << mimeType.type() << " returns " << rc;
return rc;
@@ -1407,7 +1357,7 @@ EditorManager::ExternalEditorList
{
ExternalEditorList rc;
const ExternalEditorList allEditors = ExtensionSystem::PluginManager::getObjects<IExternalEditor>();
- mimeTypeFactoryRecursion(ICore::mimeDatabase(), mimeType, allEditors, bestMatchOnly, &rc);
+ mimeTypeFactoryRecursion(mimeType, allEditors, bestMatchOnly, &rc);
if (debugEditorManager)
qDebug() << Q_FUNC_INFO << mimeType.type() << " returns " << rc;
return rc;
@@ -1434,15 +1384,15 @@ IEditor *EditorManager::createEditor(const Id &editorId, const QString &fileName
if (!editorId.isValid()) {
const QFileInfo fileInfo(fileName);
// Find by mime type
- MimeType mimeType = ICore::mimeDatabase()->findByFile(fileInfo);
+ MimeType mimeType = MimeDatabase::findByFile(fileInfo);
if (!mimeType) {
qWarning("%s unable to determine mime type of %s/%s. Falling back to text/plain",
Q_FUNC_INFO, fileName.toUtf8().constData(), editorId.name().constData());
- mimeType = ICore::mimeDatabase()->findByType(QLatin1String("text/plain"));
+ mimeType = MimeDatabase::findByType(QLatin1String("text/plain"));
}
// open text files > 48 MB in binary editor
if (fileInfo.size() > maxTextFileSize() && mimeType.type().startsWith(QLatin1String("text")))
- mimeType = ICore::mimeDatabase()->findByType(QLatin1String("application/octet-stream"));
+ mimeType = MimeDatabase::findByType(QLatin1String("application/octet-stream"));
factories = editorFactories(mimeType, true);
} else {
// Find by editor id
@@ -1457,39 +1407,40 @@ IEditor *EditorManager::createEditor(const Id &editorId, const QString &fileName
IEditor *editor = factories.front()->createEditor(m_instance);
if (editor)
- connect(editor, SIGNAL(changed()), m_instance, SLOT(handleEditorStateChange()));
+ connect(editor->document(), SIGNAL(changed()), m_instance, SLOT(handleDocumentStateChange()));
if (editor)
emit m_instance->editorCreated(editor, fileName);
return editor;
}
-void EditorManager::addEditor(IEditor *editor, bool isDuplicate)
+void EditorManager::addEditor(IEditor *editor)
{
if (!editor)
return;
ICore::addContextObject(editor);
- d->m_editorModel->addEditor(editor, isDuplicate);
- if (!isDuplicate) {
- const bool isTemporary = editor->isTemporary();
+ bool isNewDocument = false;
+ d->m_documentModel->addEditor(editor, &isNewDocument);
+ if (isNewDocument) {
+ const bool isTemporary = editor->document()->isTemporary();
const bool addWatcher = !isTemporary;
DocumentManager::addDocument(editor->document(), addWatcher);
if (!isTemporary)
- DocumentManager::addToRecentFiles(editor->document()->fileName(), editor->id());
+ DocumentManager::addToRecentFiles(editor->document()->filePath(), editor->id());
}
- emit editorOpened(editor);
+ emit m_instance->editorOpened(editor);
}
// Run the OpenWithDialog and return the editor id
// selected by the user.
Core::Id EditorManager::getOpenWithEditorId(const QString &fileName,
- bool *isExternalEditor) const
+ bool *isExternalEditor)
{
// Collect editors that can open the file
- MimeType mt = ICore::mimeDatabase()->findByFile(fileName);
+ MimeType mt = MimeDatabase::findByFile(fileName);
//Unable to determine mime type of fileName. Falling back to text/plain",
if (!mt)
- mt = ICore::mimeDatabase()->findByType(QLatin1String("text/plain"));
+ mt = MimeDatabase::findByType(QLatin1String("text/plain"));
QList<Id> allEditorIds;
QStringList allEditorDisplayNames;
QList<Id> externalEditorIds;
@@ -1595,6 +1546,11 @@ static QString autoSaveName(const QString &fileName)
return fileName + QLatin1String(".autosave");
}
+bool EditorManager::isAutoSaveFile(const QString &fileName)
+{
+ return fileName.endsWith(QLatin1String(".autosave"));
+}
+
IEditor *EditorManager::openEditor(Core::Internal::EditorView *view, const QString &fileName,
const Id &editorId, OpenEditorFlags flags, bool *newEditor)
{
@@ -1616,12 +1572,13 @@ IEditor *EditorManager::openEditor(Core::Internal::EditorView *view, const QStri
if (newEditor)
*newEditor = false;
- const QList<IEditor *> editors = editorsForFileName(fn);
+ const QList<IEditor *> editors = d->m_documentModel->editorsForFilePath(fn);
if (!editors.isEmpty()) {
IEditor *editor = editors.first();
- if (flags & EditorManager::CanContainLineNumber)
+ editor = activateEditor(view, editor, flags);
+ if (editor && flags & EditorManager::CanContainLineNumber)
editor->gotoLine(lineNumber, -1);
- return activateEditor(view, editor, flags);
+ return editor;
}
QString realFn = autoSaveName(fn);
@@ -1677,17 +1634,17 @@ bool EditorManager::openExternalEditor(const QString &fileName, const Core::Id &
return ok;
}
-QStringList EditorManager::getOpenFileNames() const
+QStringList EditorManager::getOpenFileNames()
{
QString selectedFilter;
- const QString &fileFilters = ICore::mimeDatabase()->allFiltersString(&selectedFilter);
+ const QString &fileFilters = MimeDatabase::allFiltersString(&selectedFilter);
return DocumentManager::getOpenFileNames(fileFilters, QString(), &selectedFilter);
}
IEditor *EditorManager::openEditorWithContents(const Id &editorId,
QString *titlePattern,
- const QString &contents)
+ const QByteArray &contents)
{
if (debugEditorManager)
qDebug() << Q_FUNC_INFO << editorId.name() << titlePattern << contents;
@@ -1704,10 +1661,10 @@ IEditor *EditorManager::openEditorWithContents(const Id &editorId,
if (base.contains(dollar)) {
int i = 1;
QSet<QString> docnames;
- foreach (IEditor *editor, m_instance->openedEditors()) {
- QString name = editor->document()->fileName();
+ foreach (DocumentModel::Entry *entry, d->m_documentModel->documents()) {
+ QString name = entry->fileName();
if (name.isEmpty())
- name = editor->displayName();
+ name = entry->displayName();
else
name = QFileInfo(name).completeBaseName();
docnames << name;
@@ -1729,31 +1686,26 @@ IEditor *EditorManager::openEditorWithContents(const Id &editorId,
return 0;
}
- if (!edt->createNew(contents)) {
+ if (!edt->document()->setContents(contents)) {
QApplication::restoreOverrideCursor();
delete edt;
edt = 0;
return 0;
}
- if (title.isEmpty())
- title = edt->displayName();
+ if (!title.isEmpty())
+ edt->document()->setDisplayName(title);
+
- edt->setDisplayName(title);
m_instance->addEditor(edt);
QApplication::restoreOverrideCursor();
return edt;
}
-bool EditorManager::hasEditor(const QString &fileName) const
-{
- return !editorsForFileName(fileName).isEmpty();
-}
-
void EditorManager::restoreEditorState(IEditor *editor)
{
QTC_ASSERT(editor, return);
- QString fileName = editor->document()->fileName();
+ QString fileName = editor->document()->filePath();
editor->restoreState(d->m_editorStates.value(fileName).toByteArray());
}
@@ -1765,14 +1717,14 @@ bool EditorManager::saveEditor(IEditor *editor)
bool EditorManager::saveDocument(IDocument *documentParam)
{
IDocument *document = documentParam;
- if (!document && currentEditor())
- document = currentEditor()->document();
+ if (!document && currentDocument())
+ document = currentDocument();
if (!document)
return false;
document->checkPermissions();
- const QString &fileName = document->fileName();
+ const QString &fileName = document->filePath();
if (fileName.isEmpty())
return saveDocumentAs(document);
@@ -1806,14 +1758,13 @@ void EditorManager::autoSave()
{
QStringList errors;
// FIXME: the saving should be staggered
- foreach (IEditor *editor, openedEditors()) {
- IDocument *document = editor->document();
+ foreach (IDocument *document, d->m_documentModel->openedDocuments()) {
if (!document->isModified() || !document->shouldAutoSave())
continue;
- if (document->fileName().isEmpty()) // FIXME: save them to a dedicated directory
+ if (document->filePath().isEmpty()) // FIXME: save them to a dedicated directory
continue;
QString errorString;
- if (!document->autoSave(&errorString, autoSaveName(document->fileName())))
+ if (!document->autoSave(&errorString, autoSaveName(document->filePath())))
errors << errorString;
}
if (!errors.isEmpty())
@@ -1844,25 +1795,25 @@ MakeWritableResult EditorManager::makeFileWritable(IDocument *document)
bool EditorManager::saveDocumentAs(IDocument *documentParam)
{
IDocument *document = documentParam;
- if (!document && currentEditor())
- document = currentEditor()->document();
+ if (!document && currentDocument())
+ document = currentDocument();
if (!document)
return false;
- const QString &filter = ICore::mimeDatabase()->allFiltersString();
+ const QString filter = MimeDatabase::allFiltersString();
QString selectedFilter =
- ICore::mimeDatabase()->findByFile(QFileInfo(document->fileName())).filterString();
+ MimeDatabase::findByFile(QFileInfo(document->filePath())).filterString();
const QString &absoluteFilePath =
DocumentManager::getSaveAsFileName(document, filter, &selectedFilter);
if (absoluteFilePath.isEmpty())
return false;
- if (absoluteFilePath != document->fileName()) {
+ if (absoluteFilePath != document->filePath()) {
// close existing editors for the new file name
- const QList<IEditor *> existList = editorsForFileName(absoluteFilePath);
- if (!existList.isEmpty())
- closeEditors(existList, false);
+ IDocument *otherDocument = d->m_documentModel->documentForFilePath(absoluteFilePath);
+ if (otherDocument)
+ closeDocuments(QList<IDocument *>() << otherDocument, false);
}
const bool success = DocumentManager::saveDocument(document, absoluteFilePath);
@@ -1884,18 +1835,12 @@ bool EditorManager::saveDocumentAs(IDocument *documentParam)
/* Adds the file name to the recent files if there is at least one non-temporary editor for it */
void EditorManager::addDocumentToRecentFiles(IDocument *document)
{
- bool isTemporary = true;
- Id editorId;
- QList<IEditor *> editors = editorsForDocument(document);
- foreach (IEditor *editor, editors) {
- if (!editor->isTemporary()) {
- editorId = editor->id();
- isTemporary = false;
- break;
- }
- }
- if (!isTemporary)
- DocumentManager::addToRecentFiles(document->fileName(), editorId);
+ if (document->isTemporary())
+ return;
+ DocumentModel::Entry *entry = d->m_documentModel->entryForDocument(document);
+ if (!entry)
+ return;
+ DocumentManager::addToRecentFiles(document->filePath(), entry->id());
}
void EditorManager::gotoNextDocHistory()
@@ -1905,7 +1850,7 @@ void EditorManager::gotoNextDocHistory()
dialog->selectNextEditor();
} else {
EditorView *view = currentEditorView();
- dialog->setEditors(d->m_globalHistory, view, d->m_editorModel);
+ dialog->setEditors(d->m_globalHistory, view, d->m_documentModel);
dialog->selectNextEditor();
showPopupOrSelectDocument();
}
@@ -1918,7 +1863,7 @@ void EditorManager::gotoPreviousDocHistory()
dialog->selectPreviousEditor();
} else {
EditorView *view = currentEditorView();
- dialog->setEditors(d->m_globalHistory, view, d->m_editorModel);
+ dialog->setEditors(d->m_globalHistory, view, d->m_documentModel);
dialog->selectPreviousEditor();
showPopupOrSelectDocument();
}
@@ -1926,22 +1871,22 @@ void EditorManager::gotoPreviousDocHistory()
void EditorManager::makeCurrentEditorWritable()
{
- if (IEditor* curEditor = currentEditor())
- makeFileWritable(curEditor->document());
+ if (IDocument* doc = currentDocument())
+ makeFileWritable(doc);
}
void EditorManager::vcsOpenCurrentEditor()
{
- IEditor *curEditor = currentEditor();
- if (!curEditor)
+ IDocument *document = currentDocument();
+ if (!document)
return;
- const QString directory = QFileInfo(curEditor->document()->fileName()).absolutePath();
- IVersionControl *versionControl = ICore::vcsManager()->findVersionControlForDirectory(directory);
+ const QString directory = QFileInfo(document->filePath()).absolutePath();
+ IVersionControl *versionControl = VcsManager::findVersionControlForDirectory(directory);
if (!versionControl || versionControl->openSupportMode() == IVersionControl::NoOpen)
return;
- if (!versionControl->vcsOpen(curEditor->document()->fileName())) {
+ if (!versionControl->vcsOpen(document->filePath())) {
QMessageBox::warning(ICore::mainWindow(), tr("Cannot Open File"),
tr("Cannot open the file for editing with VCS."));
}
@@ -1951,14 +1896,22 @@ void EditorManager::updateWindowTitle()
{
QString windowTitle = tr("Qt Creator");
const QString dashSep = QLatin1String(" - ");
- if (!d->m_titleAddition.isEmpty())
- windowTitle.prepend(d->m_titleAddition + dashSep);
- IEditor *curEditor = currentEditor();
- if (curEditor) {
- QString editorName = curEditor->displayName();
- if (!editorName.isEmpty())
- windowTitle.prepend(editorName + dashSep);
- QString filePath = QFileInfo(curEditor->document()->fileName()).absoluteFilePath();
+ QString vcsTopic;
+ IDocument *document = currentDocument();
+
+ if (!d->m_titleVcsTopic.isEmpty())
+ vcsTopic = QLatin1String(" [") + d->m_titleVcsTopic + QLatin1Char(']');
+ if (!d->m_titleAddition.isEmpty()) {
+ windowTitle.prepend(dashSep);
+ if (!document)
+ windowTitle.prepend(vcsTopic);
+ windowTitle.prepend(d->m_titleAddition);
+ }
+ if (document) {
+ const QString documentName = document->displayName();
+ if (!documentName.isEmpty())
+ windowTitle.prepend(documentName + vcsTopic + dashSep);
+ QString filePath = QFileInfo(document->filePath()).absoluteFilePath();
if (!filePath.isEmpty())
ICore::mainWindow()->setWindowFilePath(filePath);
} else {
@@ -1967,31 +1920,31 @@ void EditorManager::updateWindowTitle()
ICore::mainWindow()->setWindowTitle(windowTitle);
}
-void EditorManager::handleEditorStateChange()
+void EditorManager::handleDocumentStateChange()
{
updateActions();
- IEditor *theEditor = qobject_cast<IEditor *>(sender());
- if (!theEditor->document()->isModified())
- theEditor->document()->removeAutoSaveFile();
- IEditor *currEditor = currentEditor();
- if (theEditor == currEditor) {
+ IDocument *document = qobject_cast<IDocument *>(sender());
+ if (!document->isModified())
+ document->removeAutoSaveFile();
+ if (currentDocument() == document) {
updateWindowTitle();
- emit currentEditorStateChanged(currEditor);
+ emit currentDocumentStateChanged();
}
}
void EditorManager::updateMakeWritableWarning()
{
- IEditor *curEditor = currentEditor();
- bool ww = curEditor->document()->isModified() && curEditor->document()->isFileReadOnly();
- if (ww != curEditor->document()->hasWriteWarning()) {
- curEditor->document()->setWriteWarning(ww);
+ IDocument *document = currentDocument();
+ QTC_ASSERT(document, return);
+ bool ww = document->isModified() && document->isFileReadOnly();
+ if (ww != document->hasWriteWarning()) {
+ 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);
+ const QString directory = QFileInfo(document->filePath()).absolutePath();
+ IVersionControl *versionControl = VcsManager::findVersionControlForDirectory(directory);
if (versionControl && versionControl->openSupportMode() != IVersionControl::NoOpen) {
if (versionControl->settingsFlags() & IVersionControl::AutoOpen) {
vcsOpenCurrentEditor();
@@ -2007,48 +1960,32 @@ void EditorManager::updateMakeWritableWarning()
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);
+ info.setCustomButtonInfo(tr("Open"), m_instance, SLOT(vcsOpenCurrentEditor()));
+ 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);
+ info.setCustomButtonInfo(tr("Make Writable"), m_instance, SLOT(makeCurrentEditorWritable()));
+ document->infoBar()->addInfo(info);
}
} else {
- curEditor->document()->infoBar()->removeInfo(Id(kMakeWritableWarning));
- }
- }
-}
-
-QString EditorManager::fileNameForEditor(IEditor *editor)
-{
- QString fileName;
-
- if (editor) {
- if (!editor->document()->fileName().isEmpty()) {
- QFileInfo fileInfo(editor->document()->fileName());
- fileName = fileInfo.fileName();
- } else {
- fileName = editor->displayName();
+ document->infoBar()->removeInfo(Id(kMakeWritableWarning));
}
}
- return fileName;
}
-void EditorManager::setupSaveActions(IEditor *editor, QAction *saveAction, QAction *saveAsAction, QAction *revertToSavedAction)
+void EditorManager::setupSaveActions(IDocument *document, 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());
+ saveAction->setEnabled(document != 0 && document->isModified());
+ saveAsAction->setEnabled(document != 0 && document->isSaveAsAllowed());
+ revertToSavedAction->setEnabled(document != 0
+ && !document->filePath().isEmpty() && document->isModified());
- const QString fileName = fileNameForEditor(editor);
+ const QString documentName = document ? document->displayName() : QString();
QString quotedName;
- if (!fileName.isEmpty())
- quotedName = QLatin1Char('"') + fileName + QLatin1Char('"');
- if (!quotedName.isEmpty()) {
+ if (!documentName.isEmpty()) {
+ quotedName = QLatin1Char('"') + documentName + QLatin1Char('"');
saveAction->setText(tr("&Save %1").arg(quotedName));
saveAsAction->setText(tr("Save %1 &As...").arg(quotedName));
revertToSavedAction->setText(tr("Revert %1 to Saved").arg(quotedName));
@@ -2057,34 +1994,35 @@ void EditorManager::setupSaveActions(IEditor *editor, QAction *saveAction, QActi
void EditorManager::updateActions()
{
- IEditor *curEditor = currentEditor();
- const QString fileName = fileNameForEditor(curEditor);
- int openedCount = openedEditors().count() + d->m_editorModel->restoredEditors().count();
+ IDocument *curDocument = currentDocument();
+ int openedCount = d->m_documentModel->documentCount();
- if (curEditor) {
+ if (curDocument) {
if (HostOsInfo::isMacHost())
- window()->setWindowModified(curEditor->document()->isModified());
+ m_instance->window()->setWindowModified(curDocument->isModified());
updateMakeWritableWarning();
} else /* curEditor */ if (HostOsInfo::isMacHost()) {
- window()->setWindowModified(false);
+ m_instance->window()->setWindowModified(false);
}
foreach (SplitterOrView *root, d->m_root)
setCloseSplitEnabled(root, root->isSplitter());
QString quotedName;
- if (!fileName.isEmpty())
- quotedName = QLatin1Char('"') + fileName + QLatin1Char('"');
- setupSaveActions(curEditor, d->m_saveAction, d->m_saveAsAction, d->m_revertToSavedAction);
+ if (curDocument)
+ quotedName = QLatin1Char('"') + curDocument->displayName() + QLatin1Char('"');
+ setupSaveActions(curDocument, d->m_saveAction, d->m_saveAsAction, d->m_revertToSavedAction);
- d->m_closeCurrentEditorAction->setEnabled(curEditor != 0);
+ d->m_closeCurrentEditorAction->setEnabled(curDocument);
d->m_closeCurrentEditorAction->setText(tr("Close %1").arg(quotedName));
d->m_closeAllEditorsAction->setEnabled(openedCount > 0);
d->m_closeOtherEditorsAction->setEnabled(openedCount > 1);
d->m_closeOtherEditorsAction->setText((openedCount > 1 ? tr("Close All Except %1").arg(quotedName) : tr("Close Others")));
- d->m_gotoNextDocHistoryAction->setEnabled(d->m_editorModel->rowCount() != 0);
- d->m_gotoPreviousDocHistoryAction->setEnabled(d->m_editorModel->rowCount() != 0);
+ d->m_closeAllEditorsExceptVisibleAction->setEnabled(visibleDocumentsCount() < d->m_documentModel->documents().count());
+
+ d->m_gotoNextDocHistoryAction->setEnabled(d->m_documentModel->rowCount() != 0);
+ d->m_gotoPreviousDocHistoryAction->setEnabled(d->m_documentModel->rowCount() != 0);
EditorView *view = currentEditorView();
d->m_goBackAction->setEnabled(view ? view->canGoBack() : false);
d->m_goForwardAction->setEnabled(view ? view->canGoForward() : false);
@@ -2110,7 +2048,7 @@ void EditorManager::setCloseSplitEnabled(SplitterOrView *splitterOrView, bool en
}
}
-bool EditorManager::hasSplitter() const
+bool EditorManager::hasSplitter()
{
EditorView *view = currentEditorView();
QTC_ASSERT(view, return false);
@@ -2119,7 +2057,7 @@ bool EditorManager::hasSplitter() const
return root->isSplitter();
}
-QList<IEditor*> EditorManager::visibleEditors() const
+QList<IEditor*> EditorManager::visibleEditors()
{
QList<IEditor *> editors;
foreach (SplitterOrView *root, d->m_root) {
@@ -2142,14 +2080,29 @@ QList<IEditor*> EditorManager::visibleEditors() const
return editors;
}
-QList<IEditor*> EditorManager::openedEditors() const
+int EditorManager::visibleDocumentsCount()
+{
+ const QList<IEditor *> editors = visibleEditors();
+ const int editorsCount = editors.count();
+ if (editorsCount < 2)
+ return editorsCount;
+
+ QSet<const IDocument *> visibleDocuments;
+ foreach (IEditor *editor, editors) {
+ if (const IDocument *document = editor->document())
+ visibleDocuments << document;
+ }
+ return visibleDocuments.count();
+}
+
+DocumentModel *EditorManager::documentModel()
{
- return d->m_editorModel->editors();
+ return d->m_documentModel;
}
-OpenEditorsModel *EditorManager::openedEditorsModel() const
+bool EditorManager::closeDocuments(const QList<IDocument *> &document, bool askAboutModifiedEditors)
{
- return d->m_editorModel;
+ return m_instance->closeEditors(d->m_documentModel->editorsForDocuments(document), askAboutModifiedEditors);
}
void EditorManager::addCurrentPositionToNavigationHistory(IEditor *editor, const QByteArray &saveState)
@@ -2177,12 +2130,12 @@ void EditorManager::goForwardInNavigationHistory()
updateActions();
}
-OpenEditorsWindow *EditorManager::windowPopup() const
+OpenEditorsWindow *EditorManager::windowPopup()
{
return d->m_windowPopup;
}
-void EditorManager::showPopupOrSelectDocument() const
+void EditorManager::showPopupOrSelectDocument()
{
if (QApplication::keyboardModifiers() == Qt::NoModifier) {
windowPopup()->selectAndHide();
@@ -2213,38 +2166,39 @@ void EditorManager::showPopupOrSelectDocument() const
}
// Save state of all non-teporary editors.
-QByteArray EditorManager::saveState() const
+QByteArray EditorManager::saveState()
{
QByteArray bytes;
QDataStream stream(&bytes, QIODevice::WriteOnly);
stream << QByteArray("EditorManagerV4");
- QList<IEditor *> editors = openedEditors();
- foreach (IEditor *editor, editors) {
- if (!editor->document()->fileName().isEmpty()
- && !editor->isTemporary()) {
+ // TODO: In case of split views it's not possible to restore these for all correctly with this
+ QList<IDocument *> documents = d->m_documentModel->openedDocuments();
+ foreach (IDocument *document, documents) {
+ if (!document->filePath().isEmpty() && !document->isTemporary()) {
+ IEditor *editor = d->m_documentModel->editorsForDocument(document).first();
QByteArray state = editor->saveState();
if (!state.isEmpty())
- d->m_editorStates.insert(editor->document()->fileName(), QVariant(state));
+ d->m_editorStates.insert(document->filePath(), QVariant(state));
}
}
stream << d->m_editorStates;
- QList<OpenEditorsModel::Entry> entries = d->m_editorModel->entries();
+ QList<DocumentModel::Entry *> entries = d->m_documentModel->documents();
int entriesCount = 0;
- foreach (const OpenEditorsModel::Entry &entry, entries) {
+ foreach (DocumentModel::Entry *entry, entries) {
// The editor may be 0 if it was not loaded yet: In that case it is not temporary
- if (!entry.editor || !entry.editor->isTemporary())
+ if (!entry->document || !entry->document->isTemporary())
++entriesCount;
}
stream << entriesCount;
- foreach (const OpenEditorsModel::Entry &entry, entries) {
- if (!entry.editor || !entry.editor->isTemporary())
- stream << entry.fileName() << entry.displayName() << entry.id();
+ foreach (DocumentModel::Entry *entry, entries) {
+ if (!entry->document || !entry->document->isTemporary())
+ stream << entry->fileName() << entry->displayName() << entry->id();
}
stream << d->m_root.first()->saveState(); // TODO
@@ -2290,7 +2244,7 @@ bool EditorManager::restoreState(const QByteArray &state)
if (rfi.exists() && fi.lastModified() < rfi.lastModified())
openEditor(fileName, id, DoNotMakeVisible);
else
- d->m_editorModel->addRestoredEditor(fileName, displayName, id);
+ d->m_documentModel->addRestoredDocument(fileName, displayName, id);
}
}
@@ -2355,17 +2309,17 @@ void EditorManager::readSettings()
void EditorManager::revertToSaved()
{
- revertToSaved(currentEditor());
+ revertToSaved(currentDocument());
}
-void EditorManager::revertToSaved(Core::IEditor *editor)
+void EditorManager::revertToSaved(Core::IDocument *document)
{
- if (!editor)
+ if (!document)
return;
- const QString fileName = editor->document()->fileName();
+ const QString fileName = document->filePath();
if (fileName.isEmpty())
return;
- if (editor->document()->isModified()) {
+ if (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());
@@ -2378,7 +2332,7 @@ void EditorManager::revertToSaved(Core::IEditor *editor)
}
QString errorString;
- if (!editor->document()->reload(&errorString, IDocument::FlagReload, IDocument::TypeContents))
+ if (!document->reload(&errorString, IDocument::FlagReload, IDocument::TypeContents))
QMessageBox::critical(ICore::mainWindow(), tr("File Error"), errorString);
}
@@ -2401,7 +2355,7 @@ void EditorManager::setReloadSetting(IDocument::ReloadSetting behavior)
d->m_reloadSetting = behavior;
}
-IDocument::ReloadSetting EditorManager::reloadSetting() const
+IDocument::ReloadSetting EditorManager::reloadSetting()
{
return d->m_reloadSetting;
}
@@ -2412,7 +2366,7 @@ void EditorManager::setAutoSaveEnabled(bool enabled)
updateAutoSave();
}
-bool EditorManager::autoSaveEnabled() const
+bool EditorManager::autoSaveEnabled()
{
return d->m_autoSaveEnabled;
}
@@ -2423,12 +2377,12 @@ void EditorManager::setAutoSaveInterval(int interval)
updateAutoSave();
}
-int EditorManager::autoSaveInterval() const
+int EditorManager::autoSaveInterval()
{
return d->m_autoSaveInterval;
}
-QTextCodec *EditorManager::defaultTextCodec() const
+QTextCodec *EditorManager::defaultTextCodec()
{
QSettings *settings = Core::ICore::settings();
if (QTextCodec *candidate = QTextCodec::codecForName(
@@ -2446,9 +2400,8 @@ Core::IEditor *EditorManager::duplicateEditor(Core::IEditor *editor)
IEditor *duplicate = editor->duplicate(0);
duplicate->restoreState(editor->saveState());
- connect(duplicate, SIGNAL(changed()), this, SLOT(handleEditorStateChange()));
- emit editorCreated(duplicate, duplicate->document()->fileName());
- addEditor(duplicate, true);
+ emit m_instance->editorCreated(duplicate, duplicate->document()->filePath());
+ addEditor(duplicate);
return duplicate;
}
@@ -2581,18 +2534,29 @@ void EditorManager::setWindowTitleAddition(const QString &addition)
updateWindowTitle();
}
-QString EditorManager::windowTitleAddition() const
+QString EditorManager::windowTitleAddition()
{
return d->m_titleAddition;
}
+void EditorManager::setWindowTitleVcsTopic(const QString &topic)
+{
+ d->m_titleVcsTopic = topic;
+ m_instance->updateWindowTitle();
+}
+
+QString EditorManager::windowTitleVcsTopic()
+{
+ return d->m_titleVcsTopic;
+}
+
void EditorManager::updateVariable(const QByteArray &variable)
{
- if (VariableManager::instance()->isFileVariable(variable, kCurrentDocumentPrefix)) {
+ if (VariableManager::isFileVariable(variable, kCurrentDocumentPrefix)) {
QString value;
- IEditor *curEditor = currentEditor();
- if (curEditor) {
- QString fileName = curEditor->document()->fileName();
+ IDocument *document = currentDocument();
+ if (document) {
+ QString fileName = document->filePath();
if (!fileName.isEmpty())
value = VariableManager::fileVariableValue(variable, kCurrentDocumentPrefix,
fileName);
diff --git a/src/plugins/coreplugin/editormanager/editormanager.h b/src/plugins/coreplugin/editormanager/editormanager.h
index f76fc15193..5987b9e8b5 100644
--- a/src/plugins/coreplugin/editormanager/editormanager.h
+++ b/src/plugins/coreplugin/editormanager/editormanager.h
@@ -32,6 +32,8 @@
#include "../core_global.h"
+#include "documentmodel.h"
+
#include <coreplugin/id.h>
#include <coreplugin/idocument.h> // enumerations
@@ -40,7 +42,6 @@
#include <QMenu>
QT_BEGIN_NAMESPACE
-class QModelIndex;
QT_END_NAMESPACE
namespace Core {
@@ -63,18 +64,13 @@ enum MakeWritableResult {
Failed
};
-struct EditorManagerPrivate;
-class OpenEditorsModel;
-
namespace Internal {
-class OpenEditorsWindow;
-class EditorView;
-class SplitterOrView;
-
class EditorClosingCoreListener;
+class EditorView;
+class MainWindow;
class OpenEditorsViewFactory;
-
-
+class OpenEditorsWindow;
+class SplitterOrView;
} // namespace Internal
class CORE_EXPORT EditorManagerPlaceHolder : public QWidget
@@ -99,10 +95,7 @@ public:
typedef QList<IEditorFactory *> EditorFactoryList;
typedef QList<IExternalEditor *> ExternalEditorList;
- explicit EditorManager(QWidget *parent);
- virtual ~EditorManager();
- void init();
- static EditorManager *instance();
+ static QWidget *instance();
static EditorToolBar *createToolBar(QWidget *parent = 0);
@@ -122,171 +115,176 @@ public:
const Id &editorId = Id(), OpenEditorFlags flags = 0,
bool *newEditor = 0);
static IEditor *openEditorWithContents(const Id &editorId,
- QString *titlePattern = 0, const QString &contents = QString());
+ QString *titlePattern = 0, const QByteArray &contents = QByteArray());
static bool openExternalEditor(const QString &fileName, const Id &editorId);
- QStringList getOpenFileNames() const;
- Id getOpenWithEditorId(const QString &fileName, bool *isExternalEditor = 0) const;
-
- bool hasEditor(const QString &fileName) const;
- QList<IEditor *> editorsForFileName(const QString &filename) const;
- QList<IEditor *> editorsForDocument(IDocument *document) const;
+ static QStringList getOpenFileNames();
+ static Id getOpenWithEditorId(const QString &fileName, bool *isExternalEditor = 0);
+ static IDocument *currentDocument();
static IEditor *currentEditor();
- QList<IEditor *> visibleEditors() const;
- QList<IEditor*> openedEditors() const;
+ static QList<IEditor *> visibleEditors();
static void activateEditor(IEditor *editor, OpenEditorFlags flags = 0);
- void activateEditorForIndex(const QModelIndex &index, OpenEditorFlags = 0);
- IEditor *activateEditorForDocument(Internal::EditorView *view, IDocument *document, OpenEditorFlags flags = 0);
+ static void activateEditorForEntry(DocumentModel::Entry *entry, OpenEditorFlags flags = 0);
+ static IEditor *activateEditorForDocument(IDocument *document, OpenEditorFlags flags = 0);
+ static IEditor *activateEditorForDocument(Internal::EditorView *view, IDocument *document, OpenEditorFlags flags = 0);
- OpenEditorsModel *openedEditorsModel() const;
- void closeEditor(const QModelIndex &index);
- void closeOtherEditors(IEditor *editor);
+ static DocumentModel *documentModel();
+ static bool closeDocuments(const QList<IDocument *> &documents, bool askAboutModifiedEditors = true);
+ static void closeEditor(DocumentModel::Entry *entry);
+ static void closeOtherEditors(IDocument *document);
- QList<IEditor*> editorsForDocuments(QList<IDocument *> documents) const;
- void addCurrentPositionToNavigationHistory(IEditor *editor = 0, const QByteArray &saveState = QByteArray());
- void cutForwardNavigationHistory();
+ static void addCurrentPositionToNavigationHistory(IEditor *editor = 0, const QByteArray &saveState = QByteArray());
+ static void cutForwardNavigationHistory();
- bool saveEditor(IEditor *editor);
+ static bool saveEditor(IEditor *editor);
- bool closeEditors(const QList<IEditor *> &editorsToClose, bool askAboutModifiedEditors = true);
+ static bool closeEditors(const QList<IEditor *> &editorsToClose, bool askAboutModifiedEditors = true);
+ static void closeEditor(IEditor *editor, bool askAboutModifiedEditors = true);
- MakeWritableResult makeFileWritable(IDocument *document);
+ static MakeWritableResult makeFileWritable(IDocument *document);
- QByteArray saveState() const;
- bool restoreState(const QByteArray &state);
- bool hasSplitter() const;
+ static QByteArray saveState();
+ static bool restoreState(const QByteArray &state);
+ static bool hasSplitter();
- void saveSettings();
- void readSettings();
+ static void saveSettings();
+ static void readSettings();
- Internal::OpenEditorsWindow *windowPopup() const;
- void showPopupOrSelectDocument() const;
+ static Internal::OpenEditorsWindow *windowPopup();
+ static void showPopupOrSelectDocument();
- void showEditorStatusBar(const QString &id,
+ static void showEditorStatusBar(const QString &id,
const QString &infoText,
const QString &buttonText = QString(),
QObject *object = 0, const char *member = 0);
- void hideEditorStatusBar(const QString &id);
+ static void hideEditorStatusBar(const QString &id);
static EditorFactoryList editorFactories(const MimeType &mimeType, bool bestMatchOnly = true);
static ExternalEditorList externalEditors(const MimeType &mimeType, bool bestMatchOnly = true);
- void setReloadSetting(IDocument::ReloadSetting behavior);
- IDocument::ReloadSetting reloadSetting() const;
+ static void setReloadSetting(IDocument::ReloadSetting behavior);
+ static IDocument::ReloadSetting reloadSetting();
- void setAutoSaveEnabled(bool enabled);
- bool autoSaveEnabled() const;
- void setAutoSaveInterval(int interval);
- int autoSaveInterval() const;
+ static void setAutoSaveEnabled(bool enabled);
+ static bool autoSaveEnabled();
+ static void setAutoSaveInterval(int interval);
+ static int autoSaveInterval();
+ static bool isAutoSaveFile(const QString &fileName);
- QTextCodec *defaultTextCodec() const;
+ static QTextCodec *defaultTextCodec();
static qint64 maxTextFileSize();
- void setWindowTitleAddition(const QString &addition);
- QString windowTitleAddition() const;
+ static void setWindowTitleAddition(const QString &addition);
+ static QString windowTitleAddition();
+
+ static void setWindowTitleVcsTopic(const QString &topic);
+ static QString windowTitleVcsTopic();
- void addSaveAndCloseEditorActions(QMenu *contextMenu, const QModelIndex &editorIndex);
- void addNativeDirActions(QMenu *contextMenu, const QModelIndex &editorIndex);
+ static void addSaveAndCloseEditorActions(QMenu *contextMenu, DocumentModel::Entry *entry);
+ static void addNativeDirActions(QMenu *contextMenu, DocumentModel::Entry *entry);
signals:
void currentEditorChanged(Core::IEditor *editor);
- void currentEditorStateChanged(Core::IEditor *editor);
+ void currentDocumentStateChanged();
void editorCreated(Core::IEditor *editor, const QString &fileName);
void editorOpened(Core::IEditor *editor);
void editorAboutToClose(Core::IEditor *editor);
void editorsClosed(QList<Core::IEditor *> editors);
+ void findOnFileSystemRequest(const QString &path);
public slots:
- bool closeAllEditors(bool askAboutModifiedEditors = true);
+ static bool closeAllEditors(bool askAboutModifiedEditors = true);
+ static void closeAllEditorsExceptVisible();
- bool saveDocument(Core::IDocument *documentParam = 0);
- bool saveDocumentAs(Core::IDocument *documentParam = 0);
- void revertToSaved();
- void revertToSaved(Core::IEditor *editor);
- void closeEditor();
- void closeOtherEditors();
- void doEscapeKeyFocusMoveMagic();
+ static bool saveDocument(Core::IDocument *documentParam = 0);
+ static bool saveDocumentAs(Core::IDocument *documentParam = 0);
+ static void revertToSaved();
+ static void revertToSaved(IDocument *document);
+ static void closeEditor();
+ static void closeOtherEditors();
+ static void doEscapeKeyFocusMoveMagic();
private slots:
- void gotoNextDocHistory();
- void gotoPreviousDocHistory();
- void handleContextChange(const QList<Core::IContext *> &context);
- void updateActions();
- void makeCurrentEditorWritable();
- void vcsOpenCurrentEditor();
- void updateWindowTitle();
- void handleEditorStateChange();
- void updateVariable(const QByteArray &variable);
- void autoSave();
+ static void gotoNextDocHistory();
+ static void gotoPreviousDocHistory();
+ static void handleContextChange(const QList<Core::IContext *> &context);
+ static void updateActions();
+ static void makeCurrentEditorWritable();
+ static void vcsOpenCurrentEditor();
+ static void updateWindowTitle();
+ void handleDocumentStateChange();
+ static void updateVariable(const QByteArray &variable);
+ static void autoSave();
- void saveDocumentFromContextMenu();
- void saveDocumentAsFromContextMenu();
- void revertToSavedFromContextMenu();
+ static void saveDocumentFromContextMenu();
+ static void saveDocumentAsFromContextMenu();
+ static void revertToSavedFromContextMenu();
- void closeEditorFromContextMenu();
- void closeOtherEditorsFromContextMenu();
+ static void closeEditorFromContextMenu();
+ static void closeOtherEditorsFromContextMenu();
- void showInGraphicalShell();
- void openTerminal();
+ static void showInGraphicalShell();
+ static void openTerminal();
+ static void findInDirectory();
- void rootDestroyed(QObject *root);
- void setCurrentEditorFromContextChange();
+ static void rootDestroyed(QObject *root);
+ static void setCurrentEditorFromContextChange();
- void gotoNextSplit();
+ static void gotoNextSplit();
public slots:
- void goBackInNavigationHistory();
- void goForwardInNavigationHistory();
- void split(Qt::Orientation orientation);
- void split();
- void splitSideBySide();
- void splitNewWindow();
- void removeCurrentSplit();
- void removeAllSplits();
- void gotoOtherSplit();
+ static void goBackInNavigationHistory();
+ static void goForwardInNavigationHistory();
+ static void split(Qt::Orientation orientation);
+ static void split();
+ static void splitSideBySide();
+ static void splitNewWindow();
+ static void removeCurrentSplit();
+ static void removeAllSplits();
+ static void gotoOtherSplit();
private:
- QList<IDocument *> documentsForEditors(QList<IEditor *> editors) const;
+ explicit EditorManager(QWidget *parent);
+ ~EditorManager();
+ static void init();
+
static IEditor *createEditor(const Id &id = Id(), const QString &fileName = QString());
- void addEditor(IEditor *editor, bool isDuplicate = false);
- void removeEditor(IEditor *editor);
+ static void addEditor(IEditor *editor);
+ static void removeEditor(IEditor *editor);
- void restoreEditorState(IEditor *editor);
+ static void restoreEditorState(IEditor *editor);
- IEditor *placeEditor(Internal::EditorView *view, IEditor *editor);
- IEditor *duplicateEditor(IEditor *editor);
- IEditor *activateEditor(Internal::EditorView *view, IEditor *editor, OpenEditorFlags flags = 0);
- void activateEditorForIndex(Internal::EditorView *view, const QModelIndex &index, OpenEditorFlags = 0);
- void activateView(Internal::EditorView *view);
- IEditor *openEditor(Internal::EditorView *view, const QString &fileName,
+ static IEditor *placeEditor(Internal::EditorView *view, IEditor *editor);
+ static IEditor *duplicateEditor(IEditor *editor);
+ static IEditor *activateEditor(Internal::EditorView *view, IEditor *editor, OpenEditorFlags flags = 0);
+ static void activateEditorForEntry(Internal::EditorView *view, DocumentModel::Entry *entry, OpenEditorFlags flags = 0);
+ static void activateView(Internal::EditorView *view);
+ static IEditor *openEditor(Internal::EditorView *view, const QString &fileName,
const Id &id = Id(), OpenEditorFlags flags = 0, bool *newEditor = 0);
+ static int visibleDocumentsCount();
- void setCurrentEditor(IEditor *editor, bool ignoreNavigationHistory = false);
- void setCurrentView(Internal::EditorView *view);
- Internal::EditorView *currentEditorView() const;
+ static void setCurrentEditor(IEditor *editor, bool ignoreNavigationHistory = false);
+ static void setCurrentView(Internal::EditorView *view);
+ static Internal::EditorView *currentEditorView();
static Internal::EditorView *viewForEditor(IEditor *editor);
static Internal::SplitterOrView *findRoot(const Internal::EditorView *view, int *rootIndex = 0);
- void closeEditor(IEditor *editor);
- void closeDuplicate(IEditor *editor);
- void closeView(Internal::EditorView *view);
- void emptyView(Internal::EditorView *view);
+ static void closeView(Internal::EditorView *view);
+ static void emptyView(Internal::EditorView *view);
static void splitNewWindow(Internal::EditorView *view);
- IEditor *pickUnusedEditor(Internal::EditorView **foundView = 0) const;
- void addDocumentToRecentFiles(IDocument *document);
- 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;
-
+ static IEditor *pickUnusedEditor(Internal::EditorView **foundView = 0);
+ static void addDocumentToRecentFiles(IDocument *document);
+ static void updateAutoSave();
+ static void setCloseSplitEnabled(Internal::SplitterOrView *splitterOrView, bool enable);
+ static void updateMakeWritableWarning();
+ static void setupSaveActions(IDocument *document, QAction *saveAction, QAction *saveAsAction, QAction *revertToSavedAction);
+
+ friend class Core::Internal::MainWindow;
friend class Core::Internal::SplitterOrView;
friend class Core::Internal::EditorView;
friend class Core::EditorToolBar;
diff --git a/src/plugins/coreplugin/editormanager/editorview.cpp b/src/plugins/coreplugin/editormanager/editorview.cpp
index 4da158eb37..ce25cf04a8 100644
--- a/src/plugins/coreplugin/editormanager/editorview.cpp
+++ b/src/plugins/coreplugin/editormanager/editorview.cpp
@@ -29,13 +29,13 @@
#include "editorview.h"
#include "editormanager.h"
-#include "icore.h"
-#include "minisplitter.h"
-#include "openeditorsmodel.h"
+#include "documentmodel.h"
#include <coreplugin/editortoolbar.h>
#include <coreplugin/coreconstants.h>
+#include <coreplugin/icore.h>
#include <coreplugin/infobar.h>
+#include <coreplugin/minisplitter.h>
#include <coreplugin/editormanager/ieditor.h>
#include <coreplugin/findplaceholder.h>
@@ -113,6 +113,11 @@ EditorView::EditorView(SplitterOrView *parentSplitterOrView, QWidget *parent) :
tl->addWidget(m_statusWidget);
}
+ // for the case of no document selected
+ QWidget *empty = new QWidget;
+ m_container->addWidget(empty);
+ m_widgetEditorMap.insert(empty, 0);
+
updateNavigatorActions();
}
@@ -150,10 +155,9 @@ EditorView *EditorView::findNextView()
void EditorView::closeView()
{
- EditorManager *em = ICore::editorManager();
IEditor *editor = currentEditor();
if (editor)
- em->closeEditor(editor);
+ EditorManager::closeEditor(editor);
}
void EditorView::showEditorStatusBar(const QString &id,
@@ -204,7 +208,7 @@ void EditorView::updateEditorHistory(IEditor *editor, QList<EditLocation> &histo
EditLocation location;
location.document = document;
- location.fileName = document->fileName();
+ location.fileName = document->filePath();
location.id = editor->id();
location.state = QVariant(state);
@@ -221,11 +225,11 @@ void EditorView::updateEditorHistory(IEditor *editor, QList<EditLocation> &histo
void EditorView::paintEvent(QPaintEvent *)
{
- EditorView *editorView = ICore::editorManager()->currentEditorView();
+ EditorView *editorView = EditorManager::currentEditorView();
if (editorView != this)
return;
- if (editorCount() > 0)
+ if (m_container->currentIndex() != 0) // so a document is selected
return;
// Discreet indication where an editor would be if there is none
@@ -246,7 +250,7 @@ void EditorView::mousePressEvent(QMouseEvent *e)
void EditorView::focusInEvent(QFocusEvent *)
{
- ICore::editorManager()->setCurrentView(this);
+ EditorManager::setCurrentView(this);
}
void EditorView::addEditor(IEditor *editor)
@@ -291,43 +295,40 @@ void EditorView::removeEditor(IEditor *editor)
IEditor *EditorView::currentEditor() const
{
- if (m_container->count() > 0)
+ if (m_editors.count() > 0)
return m_widgetEditorMap.value(m_container->currentWidget());
return 0;
}
void EditorView::listSelectionActivated(int index)
{
- QAbstractItemModel *model = EditorManager::instance()->openedEditorsModel();
- EditorManager::instance()->activateEditorForIndex(this, model->index(index, 0));
+ EditorManager::activateEditorForEntry(
+ this, EditorManager::documentModel()->documentAtRow(index));
}
void EditorView::splitHorizontally()
{
- EditorManager *editorManager = EditorManager::instance();
if (m_parentSplitterOrView)
m_parentSplitterOrView->split(Qt::Vertical);
- editorManager->updateActions();
+ EditorManager::updateActions();
}
void EditorView::splitVertically()
{
- EditorManager *editorManager = EditorManager::instance();
if (m_parentSplitterOrView)
m_parentSplitterOrView->split(Qt::Horizontal);
- editorManager->updateActions();
+ EditorManager::updateActions();
}
void EditorView::splitNewWindow()
{
- EditorManager::instance()->splitNewWindow(this);
+ EditorManager::splitNewWindow(this);
}
void EditorView::closeSplit()
{
- EditorManager *editorManager = EditorManager::instance();
- editorManager->closeView(this);
- editorManager->updateActions();
+ EditorManager::closeView(this);
+ EditorManager::updateActions();
}
void EditorView::setParentSplitterOrView(SplitterOrView *splitterOrView)
@@ -337,11 +338,11 @@ void EditorView::setParentSplitterOrView(SplitterOrView *splitterOrView)
void EditorView::setCurrentEditor(IEditor *editor)
{
- if (!editor || m_container->count() <= 0
- || m_container->indexOf(editor->widget()) == -1) {
- m_toolBar->updateEditorStatus(0);
+ if (!editor || m_container->indexOf(editor->widget()) == -1) {
+ QTC_CHECK(!editor);
+ m_toolBar->setCurrentEditor(0);
m_infoBarDisplay->setInfoBar(0);
- QTC_CHECK(m_container->count() == 0);
+ m_container->setCurrentIndex(0);
return;
}
@@ -360,12 +361,12 @@ void EditorView::setCurrentEditor(IEditor *editor)
int EditorView::editorCount() const
{
- return m_container->count();
+ return m_editors.size();
}
QList<IEditor *> EditorView::editors() const
{
- return m_widgetEditorMap.values();
+ return m_editors;
}
void EditorView::updateEditorHistory(IEditor *editor)
@@ -395,7 +396,7 @@ void EditorView::addCurrentPositionToNavigationHistory(IEditor *editor, const QB
EditLocation location;
location.document = document;
- location.fileName = document->fileName();
+ location.fileName = document->filePath();
location.id = editor->id();
location.state = QVariant(state);
m_currentNavigationHistoryPosition = qMin(m_currentNavigationHistoryPosition, m_navigationHistory.size()); // paranoia
@@ -450,25 +451,24 @@ void EditorView::updateCurrentPositionInNavigationHistory()
location = &m_navigationHistory[m_navigationHistory.size()-1];
}
location->document = document;
- location->fileName = document->fileName();
+ location->fileName = document->filePath();
location->id = editor->id();
location->state = QVariant(editor->saveState());
}
void EditorView::goBackInNavigationHistory()
{
- EditorManager *em = ICore::editorManager();
updateCurrentPositionInNavigationHistory();
while (m_currentNavigationHistoryPosition > 0) {
--m_currentNavigationHistoryPosition;
EditLocation location = m_navigationHistory.at(m_currentNavigationHistoryPosition);
IEditor *editor = 0;
if (location.document) {
- editor = em->activateEditorForDocument(this, location.document,
+ editor = EditorManager::activateEditorForDocument(this, location.document,
EditorManager::IgnoreNavigationHistory);
}
if (!editor) {
- editor = em->openEditor(this, location.fileName, location.id,
+ editor = EditorManager::openEditor(this, location.fileName, location.id,
EditorManager::IgnoreNavigationHistory);
if (!editor) {
m_navigationHistory.removeAt(m_currentNavigationHistoryPosition);
@@ -483,7 +483,6 @@ void EditorView::goBackInNavigationHistory()
void EditorView::goForwardInNavigationHistory()
{
- EditorManager *em = ICore::editorManager();
updateCurrentPositionInNavigationHistory();
if (m_currentNavigationHistoryPosition >= m_navigationHistory.size()-1)
return;
@@ -491,11 +490,11 @@ void EditorView::goForwardInNavigationHistory()
EditLocation location = m_navigationHistory.at(m_currentNavigationHistoryPosition);
IEditor *editor = 0;
if (location.document) {
- editor = em->activateEditorForDocument(this, location.document,
+ editor = EditorManager::activateEditorForDocument(this, location.document,
EditorManager::IgnoreNavigationHistory);
}
if (!editor) {
- editor = em->openEditor(this, location.fileName, location.id, EditorManager::IgnoreNavigationHistory);
+ editor = EditorManager::openEditor(this, location.fileName, location.id, EditorManager::IgnoreNavigationHistory);
if (!editor) {
//TODO
qDebug() << Q_FUNC_INFO << "can't open file" << location.fileName;
@@ -518,12 +517,23 @@ SplitterOrView::SplitterOrView(Core::IEditor *editor)
m_layout->addWidget(m_view);
}
+SplitterOrView::SplitterOrView(EditorView *view)
+{
+ QTC_CHECK(view);
+ m_layout = new QStackedLayout(this);
+ m_layout->setSizeConstraint(QLayout::SetNoConstraint);
+ m_view = view;
+ m_view->setParentSplitterOrView(this);
+ m_splitter = 0;
+ m_layout->addWidget(m_view);
+}
+
SplitterOrView::~SplitterOrView()
{
delete m_layout;
m_layout = 0;
if (m_view)
- EditorManager::instance()->emptyView(m_view);
+ EditorManager::emptyView(m_view);
delete m_view;
m_view = 0;
delete m_splitter;
@@ -591,34 +601,21 @@ void SplitterOrView::split(Qt::Orientation orientation)
m_splitter = new MiniSplitter(this);
m_splitter->setOrientation(orientation);
m_layout->addWidget(m_splitter);
- EditorManager *em = ICore::editorManager();
- Core::IEditor *e = m_view->currentEditor();
+ m_layout->removeWidget(m_view);
+ EditorView *editorView = m_view;
+ m_view = 0;
+ IEditor *e = editorView->currentEditor();
SplitterOrView *view = 0;
SplitterOrView *otherView = 0;
- if (e) {
-
- foreach (IEditor *editor, m_view->editors())
- m_view->removeEditor(editor);
-
- m_splitter->addWidget((view = new SplitterOrView(e)));
- if (e->duplicateSupported()) {
- Core::IEditor *duplicate = em->duplicateEditor(e);
- m_splitter->addWidget((otherView = new SplitterOrView(duplicate)));
- } else {
- m_splitter->addWidget((otherView = new SplitterOrView()));
- }
- } else {
- m_splitter->addWidget((view = new SplitterOrView()));
- m_splitter->addWidget((otherView = new SplitterOrView()));
- }
+ IEditor *duplicate = e && e->duplicateSupported() ? EditorManager::duplicateEditor(e) : 0;
+ m_splitter->addWidget((view = new SplitterOrView(duplicate)));
+ m_splitter->addWidget((otherView = new SplitterOrView(editorView)));
m_layout->setCurrentWidget(m_splitter);
- view->view()->copyNavigationHistoryFrom(m_view);
- view->view()->setCurrentEditor(view->view()->currentEditor());
- otherView->view()->copyNavigationHistoryFrom(m_view);
- otherView->view()->setCurrentEditor(otherView->view()->currentEditor());
+ view->view()->copyNavigationHistoryFrom(editorView);
+ view->view()->setCurrentEditor(duplicate);
if (orientation == Qt::Horizontal) {
view->view()->setCloseSplitIcon(QIcon(QLatin1String(Constants::ICON_CLOSE_SPLIT_LEFT)));
@@ -628,22 +625,16 @@ void SplitterOrView::split(Qt::Orientation orientation)
otherView->view()->setCloseSplitIcon(QIcon(QLatin1String(Constants::ICON_CLOSE_SPLIT_BOTTOM)));
}
- if (m_view) {
- em->emptyView(m_view);
- delete m_view;
- m_view = 0;
- }
-
if (e)
- em->activateEditor(view->view(), e);
+ EditorManager::activateEditor(otherView->view(), e);
else
- em->setCurrentView(view->view());
+ EditorManager::setCurrentView(otherView->view());
}
void SplitterOrView::unsplitAll()
{
QTC_ASSERT(m_splitter, return);
- EditorView *currentView = EditorManager::instance()->currentEditorView();
+ EditorView *currentView = EditorManager::currentEditorView();
if (currentView) {
currentView->parentSplitterOrView()->takeView();
currentView->setParentSplitterOrView(this);
@@ -662,7 +653,7 @@ void SplitterOrView::unsplitAll()
void SplitterOrView::unsplitAll_helper()
{
if (m_view)
- ICore::editorManager()->emptyView(m_view);
+ 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)))
@@ -677,7 +668,6 @@ void SplitterOrView::unsplit()
return;
Q_ASSERT(m_splitter->count() == 1);
- EditorManager *em = ICore::editorManager();
SplitterOrView *childSplitterOrView = qobject_cast<SplitterOrView*>(m_splitter->widget(0));
QSplitter *oldSplitter = m_splitter;
m_splitter = 0;
@@ -697,7 +687,7 @@ void SplitterOrView::unsplit()
m_view->addEditor(e);
m_view->setCurrentEditor(e);
}
- em->emptyView(childView);
+ EditorManager::emptyView(childView);
} else {
m_view = childSplitterOrView->takeView();
m_view->setParentSplitterOrView(this);
@@ -720,7 +710,7 @@ void SplitterOrView::unsplit()
m_layout->setCurrentWidget(m_view);
}
delete oldSplitter;
- em->setCurrentView(findFirstView());
+ EditorManager::setCurrentView(findFirstView());
}
@@ -739,11 +729,11 @@ QByteArray SplitterOrView::saveState() const
IEditor* e = editor();
// don't save state of temporary or ad-hoc editors
- if (e && (e->isTemporary() || e->document()->fileName().isEmpty())) {
+ if (e && (e->document()->isTemporary() || e->document()->filePath().isEmpty())) {
// look for another editor that is more suited
e = 0;
foreach (IEditor *otherEditor, editors()) {
- if (!otherEditor->isTemporary() && !otherEditor->document()->fileName().isEmpty()) {
+ if (!otherEditor->document()->isTemporary() && !otherEditor->document()->filePath().isEmpty()) {
e = otherEditor;
break;
}
@@ -754,10 +744,10 @@ QByteArray SplitterOrView::saveState() const
stream << QByteArray("empty");
} else if (e == EditorManager::currentEditor()) {
stream << QByteArray("currenteditor")
- << e->document()->fileName() << e->id().toString() << e->saveState();
+ << e->document()->filePath() << e->id().toString() << e->saveState();
} else {
stream << QByteArray("editor")
- << e->document()->fileName() << e->id().toString() << e->saveState();
+ << e->document()->filePath() << e->id().toString() << e->saveState();
}
}
return bytes;
@@ -777,27 +767,26 @@ void SplitterOrView::restoreState(const QByteArray &state)
static_cast<SplitterOrView*>(m_splitter->widget(0))->restoreState(first);
static_cast<SplitterOrView*>(m_splitter->widget(1))->restoreState(second);
} else if (mode == "editor" || mode == "currenteditor") {
- EditorManager *em = ICore::editorManager();
QString fileName;
QString id;
QByteArray editorState;
stream >> fileName >> id >> editorState;
if (!QFile::exists(fileName))
return;
- IEditor *e = em->openEditor(view(), fileName, Id::fromString(id), Core::EditorManager::IgnoreNavigationHistory
+ IEditor *e = EditorManager::openEditor(view(), fileName, Id::fromString(id), Core::EditorManager::IgnoreNavigationHistory
| Core::EditorManager::DoNotChangeCurrentEditor);
if (!e) {
- QModelIndex idx = em->openedEditorsModel()->firstRestoredEditor();
- if (idx.isValid())
- em->activateEditorForIndex(view(), idx, Core::EditorManager::IgnoreNavigationHistory
+ DocumentModel::Entry *entry = EditorManager::documentModel()->firstRestoredDocument();
+ if (entry)
+ EditorManager::activateEditorForEntry(view(), entry, Core::EditorManager::IgnoreNavigationHistory
| Core::EditorManager::DoNotChangeCurrentEditor);
}
if (e) {
e->restoreState(editorState);
if (mode == "currenteditor")
- em->setCurrentEditor(e);
+ EditorManager::setCurrentEditor(e);
}
}
}
diff --git a/src/plugins/coreplugin/editormanager/editorview.h b/src/plugins/coreplugin/editormanager/editorview.h
index a2d38ae82b..69f2cc25da 100644
--- a/src/plugins/coreplugin/editormanager/editorview.h
+++ b/src/plugins/coreplugin/editormanager/editorview.h
@@ -57,7 +57,7 @@ class IContext;
class IDocument;
class IEditor;
class InfoBarDisplay;
-class OpenEditorsModel;
+class DocumentModel;
class EditorToolBar;
namespace Internal {
@@ -164,6 +164,7 @@ class SplitterOrView : public QWidget
Q_OBJECT
public:
explicit SplitterOrView(Core::IEditor *editor = 0);
+ explicit SplitterOrView(EditorView *view);
~SplitterOrView();
void split(Qt::Orientation orientation);
diff --git a/src/plugins/coreplugin/editormanager/ieditor.cpp b/src/plugins/coreplugin/editormanager/ieditor.cpp
index d490e1ba1a..f81e23cbd7 100644
--- a/src/plugins/coreplugin/editormanager/ieditor.cpp
+++ b/src/plugins/coreplugin/editormanager/ieditor.cpp
@@ -47,9 +47,6 @@
(usually filename w/o path).
\li \c kind() must be the same value as the \c kind() of the corresponding
EditorFactory.
- \li The \c changed() signal should be emitted when the modified state of the
- document changes (so \e not every time the document changes, but
- \e {only once}).
\li If duplication is supported, you need to ensure that all duplicates
return the same \c file().
\li QString \c preferredMode() const is the mode the editor manager should
diff --git a/src/plugins/coreplugin/editormanager/ieditor.h b/src/plugins/coreplugin/editormanager/ieditor.h
index f2c64f7a9b..af92523217 100644
--- a/src/plugins/coreplugin/editormanager/ieditor.h
+++ b/src/plugins/coreplugin/editormanager/ieditor.h
@@ -47,12 +47,9 @@ public:
IEditor(QObject *parent = 0) : IContext(parent) {}
virtual ~IEditor() {}
- virtual bool createNew(const QString &contents = QString()) = 0;
virtual bool open(QString *errorString, const QString &fileName, const QString &realFileName) = 0;
virtual IDocument *document() = 0;
virtual Core::Id id() const = 0;
- virtual QString displayName() const = 0;
- virtual void setDisplayName(const QString &title) = 0;
virtual bool duplicateSupported() const { return false; }
virtual IEditor *duplicate(QWidget * /*parent*/) { return 0; }
@@ -64,14 +61,9 @@ public:
virtual int currentColumn() const { return 0; }
virtual void gotoLine(int line, int column = 0) { Q_UNUSED(line) Q_UNUSED(column) }
- virtual bool isTemporary() const = 0;
-
virtual QWidget *toolBar() = 0;
virtual bool isDesignModePreferred() const { return false; }
-
-signals:
- void changed();
};
} // namespace Core
diff --git a/src/plugins/coreplugin/editormanager/iexternaleditor.cpp b/src/plugins/coreplugin/editormanager/iexternaleditor.cpp
index 73566d8ca0..fa5ae52531 100644
--- a/src/plugins/coreplugin/editormanager/iexternaleditor.cpp
+++ b/src/plugins/coreplugin/editormanager/iexternaleditor.cpp
@@ -43,11 +43,6 @@
*/
/*!
- \fn IExternalEditor::~IExternalEditor()
- \internal
-*/
-
-/*!
\fn QStringList IExternalEditor::mimeTypes() const
Returns the mime type the editor supports
*/
diff --git a/src/plugins/coreplugin/editormanager/openeditorsmodel.cpp b/src/plugins/coreplugin/editormanager/openeditorsmodel.cpp
deleted file mode 100644
index a9a3183831..0000000000
--- a/src/plugins/coreplugin/editormanager/openeditorsmodel.cpp
+++ /dev/null
@@ -1,365 +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 "openeditorsmodel.h"
-#include "ieditor.h"
-#include "idocument.h"
-
-#include <QDir>
-#include <QIcon>
-
-namespace Core {
-
-struct OpenEditorsModelPrivate
-{
- OpenEditorsModelPrivate();
-
- const QIcon m_lockedIcon;
- const QIcon m_unlockedIcon;
-
- QList<OpenEditorsModel::Entry> m_editors;
- QList<IEditor *> m_duplicateEditors;
-};
-
-OpenEditorsModelPrivate::OpenEditorsModelPrivate() :
- m_lockedIcon(QLatin1String(":/core/images/locked.png")),
- m_unlockedIcon(QLatin1String(":/core/images/unlocked.png"))
-{
-}
-
-OpenEditorsModel::Entry::Entry() :
- editor(0)
-{
-}
-
-OpenEditorsModel::OpenEditorsModel(QObject *parent) :
- QAbstractItemModel(parent), d(new OpenEditorsModelPrivate)
-{
-}
-
-OpenEditorsModel::~OpenEditorsModel()
-{
- delete d;
-}
-
-QIcon OpenEditorsModel::lockedIcon() const
-{
- return d->m_lockedIcon;
-}
-
-QIcon OpenEditorsModel::unlockedIcon() const
-{
- return d->m_unlockedIcon;
-}
-
-QString OpenEditorsModel::Entry::fileName() const {
- return editor ? editor->document()->fileName() : m_fileName;
-}
-
-QString OpenEditorsModel::Entry::displayName() const {
- return editor ? editor->displayName() : m_displayName;
-}
-
-Id OpenEditorsModel::Entry::id() const
-{
- return editor ? editor->id() : m_id;
-}
-
-int OpenEditorsModel::columnCount(const QModelIndex &parent) const
-{
- Q_UNUSED(parent)
- return 2;
-}
-
-int OpenEditorsModel::rowCount(const QModelIndex &parent) const
-{
- if (!parent.isValid())
- return d->m_editors.count();
- return 0;
-}
-
-QList<IEditor *> OpenEditorsModel::editors() const
-{
- QList<IEditor *> result;
- foreach (const Entry &entry, d->m_editors)
- if (entry.editor)
- result += entry.editor;
- return result;
-}
-
-void OpenEditorsModel::addEditor(IEditor *editor, bool isDuplicate)
-{
- if (!editor)
- return;
-
- if (isDuplicate) {
- d->m_duplicateEditors.append(editor);
- return;
- }
-
- Entry entry;
- entry.editor = editor;
- addEntry(entry);
-}
-
-void OpenEditorsModel::addRestoredEditor(const QString &fileName, const QString &displayName, const Id &id)
-{
- Entry entry;
- entry.m_fileName = fileName;
- entry.m_displayName = displayName;
- entry.m_id = id;
- addEntry(entry);
-}
-
-QModelIndex OpenEditorsModel::firstRestoredEditor() const
-{
- for (int i = 0; i < d->m_editors.count(); ++i)
- if (!d->m_editors.at(i).editor)
- return createIndex(i, 0);
- return QModelIndex();
-}
-
-void OpenEditorsModel::addEntry(const Entry &entry)
-{
- QString fileName = entry.fileName();
-
- int previousIndex = findFileName(fileName);
- if (previousIndex >= 0) {
- if (entry.editor && d->m_editors.at(previousIndex).editor == 0) {
- d->m_editors[previousIndex] = entry;
- connect(entry.editor, SIGNAL(changed()), this, SLOT(itemChanged()));
- }
- return;
- }
-
- int index;
- QString displayName = entry.displayName();
- for (index = 0; index < d->m_editors.count(); ++index) {
- if (displayName < d->m_editors.at(index).displayName())
- break;
- }
-
- beginInsertRows(QModelIndex(), index, index);
- d->m_editors.insert(index, entry);
- if (entry.editor)
- connect(entry.editor, SIGNAL(changed()), this, SLOT(itemChanged()));
- endInsertRows();
-}
-
-
-int OpenEditorsModel::findEditor(IEditor *editor) const
-{
- for (int i = 0; i < d->m_editors.count(); ++i)
- if (d->m_editors.at(i).editor == editor)
- return i;
- return -1;
-}
-
-int OpenEditorsModel::findFileName(const QString &filename) const
-{
- if (filename.isEmpty())
- return -1;
- for (int i = 0; i < d->m_editors.count(); ++i) {
- if (d->m_editors.at(i).fileName() == filename)
- return i;
- }
- return -1;
-}
-
-void OpenEditorsModel::removeEditor(IEditor *editor)
-{
- d->m_duplicateEditors.removeAll(editor);
- removeEditor(findEditor(editor));
-}
-
-void OpenEditorsModel::removeEditor(const QModelIndex &index)
-{
- removeEditor(index.row());
-}
-
-void OpenEditorsModel::removeEditor(const QString &fileName)
-{
- removeEditor(findFileName(fileName));
-}
-
-void OpenEditorsModel::removeEditor(int idx)
-{
- if (idx < 0)
- return;
- IEditor *editor= d->m_editors.at(idx).editor;
- beginRemoveRows(QModelIndex(), idx, idx);
- d->m_editors.removeAt(idx);
- endRemoveRows();
- if (editor)
- disconnect(editor, SIGNAL(changed()), this, SLOT(itemChanged()));
-}
-
-void OpenEditorsModel::removeAllRestoredEditors()
-{
- for (int i = d->m_editors.count()-1; i >= 0; --i) {
- if (!d->m_editors.at(i).editor) {
- beginRemoveRows(QModelIndex(), i, i);
- d->m_editors.removeAt(i);
- endRemoveRows();
- }
- }
-}
-
-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)
- result.append(d->m_editors.at(i));
- }
- return result;
-}
-
-bool OpenEditorsModel::isDuplicate(IEditor *editor) const
-{
- return editor && d->m_duplicateEditors.contains(editor);
-}
-
-IEditor *OpenEditorsModel::originalForDuplicate(IEditor *duplicate) const
-{
- IDocument *document = duplicate->document();
- foreach (const Entry &e, d->m_editors)
- if (e.editor && e.editor->document() == document)
- return e.editor;
- return 0;
-}
-
-QList<IEditor *> OpenEditorsModel::duplicatesFor(IEditor *editor) const
-{
- QList<IEditor *> result;
- IDocument *document = editor->document();
- foreach (IEditor *e, d->m_duplicateEditors)
- if (e->document() == document)
- result += e;
- return result;
-}
-
-void OpenEditorsModel::makeOriginal(IEditor *duplicate)
-{
- Q_ASSERT(duplicate && isDuplicate(duplicate));
- IEditor *original = originalForDuplicate(duplicate);
- Q_ASSERT(original);
- int i = findEditor(original);
- d->m_editors[i].editor = duplicate;
- d->m_duplicateEditors.removeOne(duplicate);
- d->m_duplicateEditors.append(original);
- disconnect(original, SIGNAL(changed()), this, SLOT(itemChanged()));
- connect(duplicate, SIGNAL(changed()), this, SLOT(itemChanged()));
-}
-
-void OpenEditorsModel::emitDataChanged(IEditor *editor)
-{
- int idx = findEditor(editor);
- if (idx < 0)
- return;
- QModelIndex mindex = index(idx, 0);
- emit dataChanged(mindex, mindex);
-}
-
-QModelIndex OpenEditorsModel::index(int row, int column, const QModelIndex &parent) const
-{
- Q_UNUSED(parent)
- if (column < 0 || column > 1 || row < 0 || row >= d->m_editors.count())
- return QModelIndex();
- return createIndex(row, column);
-}
-
-QVariant OpenEditorsModel::data(const QModelIndex &index, int role) const
-{
- if (!index.isValid() || (index.column() != 0 && role < Qt::UserRole))
- return QVariant();
- Entry e = d->m_editors.at(index.row());
- switch (role) {
- case Qt::DisplayRole:
- return (e.editor && e.editor->document()->isModified())
- ? e.displayName() + QLatin1Char('*')
- : e.displayName();
- case Qt::DecorationRole:
- {
- bool showLock = false;
- if (e.editor) {
- showLock = e.editor->document()->fileName().isEmpty()
- ? false
- : e.editor->document()->isFileReadOnly();
- } else {
- showLock = !QFileInfo(e.m_fileName).isWritable();
- }
- return showLock ? d->m_lockedIcon : QIcon();
- }
- case Qt::ToolTipRole:
- return e.fileName().isEmpty()
- ? e.displayName()
- : QDir::toNativeSeparators(e.fileName());
- case Qt::UserRole:
- return qVariantFromValue(e.editor);
- case Qt::UserRole + 1:
- return e.fileName();
- case Qt::UserRole + 2:
- return QVariant::fromValue(e.editor ? Core::Id(e.editor->id()) : e.id());
- default:
- return QVariant();
- }
- return QVariant();
-}
-
-QModelIndex OpenEditorsModel::indexOf(IEditor *editor) const
-{
- int idx = findEditor(originalForDuplicate(editor));
- return createIndex(idx, 0);
-}
-
-QString OpenEditorsModel::displayNameForDocument(IDocument *document) const
-{
- for (int i = 0; i < d->m_editors.count(); ++i)
- if (d->m_editors.at(i).editor && d->m_editors.at(i).editor->document() == document)
- return d->m_editors.at(i).editor->displayName();
- return QString();
-}
-
-void OpenEditorsModel::itemChanged()
-{
- emitDataChanged(qobject_cast<IEditor*>(sender()));
-}
-
-QList<OpenEditorsModel::Entry> OpenEditorsModel::entries() const
-{
- return d->m_editors;
-}
-
-IEditor *OpenEditorsModel::editorAt(int row) const
-{
- return d->m_editors.at(row).editor;
-}
-
-} // namespace Core
diff --git a/src/plugins/coreplugin/editormanager/openeditorsview.cpp b/src/plugins/coreplugin/editormanager/openeditorsview.cpp
index 0b6dacba5b..9d73aea3f4 100644
--- a/src/plugins/coreplugin/editormanager/openeditorsview.cpp
+++ b/src/plugins/coreplugin/editormanager/openeditorsview.cpp
@@ -29,7 +29,8 @@
#include "openeditorsview.h"
#include "editormanager.h"
-#include "openeditorsmodel.h"
+#include "ieditor.h"
+#include "documentmodel.h"
#include <coreplugin/coreconstants.h>
#include <coreplugin/actionmanager/actionmanager.h>
@@ -95,8 +96,9 @@ OpenEditorsWidget::OpenEditorsWidget()
setTextElideMode(Qt::ElideMiddle);
setFrameStyle(QFrame::NoFrame);
setAttribute(Qt::WA_MacShowFocusRect, false);
- EditorManager *em = EditorManager::instance();
- setModel(em->openedEditorsModel());
+ m_model = new ProxyModel(this);
+ m_model->setSourceModel(EditorManager::documentModel());
+ setModel(m_model);
setSelectionMode(QAbstractItemView::SingleSelection);
setSelectionBehavior(QAbstractItemView::SelectRows);
header()->setStretchLastSection(false);
@@ -107,7 +109,7 @@ OpenEditorsWidget::OpenEditorsWidget()
installEventFilter(this);
viewport()->installEventFilter(this);
- connect(em, SIGNAL(currentEditorChanged(Core::IEditor*)),
+ connect(EditorManager::instance(), SIGNAL(currentEditorChanged(Core::IEditor*)),
this, SLOT(updateCurrentItem(Core::IEditor*)));
connect(this, SIGNAL(clicked(QModelIndex)),
this, SLOT(handleClicked(QModelIndex)));
@@ -124,12 +126,13 @@ OpenEditorsWidget::~OpenEditorsWidget()
void OpenEditorsWidget::updateCurrentItem(Core::IEditor *editor)
{
- if (!editor) {
+ IDocument *document = editor ? editor->document() : 0;
+ QModelIndex index = m_model->index(EditorManager::documentModel()->indexOfDocument(document), 0);
+ if (!index.isValid()) {
clearSelection();
return;
}
- EditorManager *em = EditorManager::instance();
- setCurrentIndex(em->openedEditorsModel()->indexOf(editor));
+ setCurrentIndex(index);
selectionModel()->select(currentIndex(),
QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
scrollTo(currentIndex());
@@ -189,12 +192,14 @@ void OpenEditorsWidget::handleClicked(const QModelIndex &index)
void OpenEditorsWidget::activateEditor(const QModelIndex &index)
{
selectionModel()->select(index, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
- EditorManager::instance()->activateEditorForIndex(index);
+ EditorManager::activateEditorForEntry(
+ EditorManager::documentModel()->documentAtRow(m_model->mapToSource(index).row()));
}
void OpenEditorsWidget::closeEditor(const QModelIndex &index)
{
- EditorManager::instance()->closeEditor(index);
+ EditorManager::closeEditor(
+ EditorManager::documentModel()->documentAtRow(m_model->mapToSource(index).row()));
// work around selection changes
updateCurrentItem(EditorManager::currentEditor());
}
@@ -203,9 +208,11 @@ void OpenEditorsWidget::contextMenuRequested(QPoint pos)
{
QMenu contextMenu;
QModelIndex editorIndex = indexAt(pos);
- EditorManager::instance()->addSaveAndCloseEditorActions(&contextMenu, editorIndex);
+ DocumentModel::Entry *entry = EditorManager::documentModel()->documentAtRow(
+ m_model->mapToSource(editorIndex).row());
+ EditorManager::addSaveAndCloseEditorActions(&contextMenu, entry);
contextMenu.addSeparator();
- EditorManager::instance()->addNativeDirActions(&contextMenu, editorIndex);
+ EditorManager::addNativeDirActions(&contextMenu, entry);
contextMenu.exec(mapToGlobal(pos));
}
@@ -230,9 +237,9 @@ int OpenEditorsViewFactory::priority() const
return 200;
}
-Core::Id OpenEditorsViewFactory::id() const
+Id OpenEditorsViewFactory::id() const
{
- return Core::Id("Open Documents");
+ return "Open Documents";
}
QKeySequence OpenEditorsViewFactory::activationSequence() const
@@ -247,3 +254,132 @@ OpenEditorsViewFactory::OpenEditorsViewFactory()
OpenEditorsViewFactory::~OpenEditorsViewFactory()
{
}
+
+
+ProxyModel::ProxyModel(QObject *parent) : QAbstractProxyModel(parent)
+{
+}
+
+QModelIndex ProxyModel::mapFromSource(const QModelIndex &sourceIndex) const
+{
+ // root
+ if (!sourceIndex.isValid())
+ return QModelIndex();
+ // hide the <no document>
+ int row = sourceIndex.row() - 1;
+ if (row < 0)
+ return QModelIndex();
+ return createIndex(row, sourceIndex.column());
+}
+
+QModelIndex ProxyModel::mapToSource(const QModelIndex &proxyIndex) const
+{
+ if (!proxyIndex.isValid())
+ return QModelIndex();
+ // handle missing <no document>
+ return sourceModel()->index(proxyIndex.row() + 1, proxyIndex.column());
+}
+
+QModelIndex ProxyModel::index(int row, int column, const QModelIndex &parent) const
+{
+ if (parent.isValid() || row < 0 || row >= sourceModel()->rowCount(mapToSource(parent)) - 1
+ || column < 0 || column > 1)
+ return QModelIndex();
+ return createIndex(row, column);
+}
+
+QModelIndex ProxyModel::parent(const QModelIndex &child) const
+{
+ Q_UNUSED(child)
+ return QModelIndex();
+}
+
+int ProxyModel::rowCount(const QModelIndex &parent) const
+{
+ if (!parent.isValid())
+ return sourceModel()->rowCount(mapToSource(parent)) - 1;
+ return 0;
+}
+
+int ProxyModel::columnCount(const QModelIndex &parent) const
+{
+ return sourceModel()->columnCount(mapToSource(parent));
+}
+
+void ProxyModel::setSourceModel(QAbstractItemModel *sm)
+{
+ QAbstractItemModel *previousModel = sourceModel();
+ if (previousModel) {
+ disconnect(previousModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
+ this, SLOT(sourceDataChanged(QModelIndex,QModelIndex)));
+ disconnect(previousModel, SIGNAL(rowsInserted(QModelIndex,int,int)),
+ this, SLOT(sourceRowsInserted(QModelIndex,int,int)));
+ disconnect(previousModel, SIGNAL(rowsRemoved(QModelIndex,int,int)),
+ this, SLOT(sourceRowsRemoved(QModelIndex,int,int)));
+ disconnect(previousModel, SIGNAL(rowsAboutToBeInserted(QModelIndex,int,int)),
+ this, SLOT(sourceRowsAboutToBeInserted(QModelIndex,int,int)));
+ disconnect(previousModel, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)),
+ this, SLOT(sourceRowsAboutToBeRemoved(QModelIndex,int,int)));
+ }
+ QAbstractProxyModel::setSourceModel(sm);
+ if (sm) {
+ connect(sm, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
+ this, SLOT(sourceDataChanged(QModelIndex,QModelIndex)));
+ connect(sm, SIGNAL(rowsInserted(QModelIndex,int,int)),
+ this, SLOT(sourceRowsInserted(QModelIndex,int,int)));
+ connect(sm, SIGNAL(rowsRemoved(QModelIndex,int,int)),
+ this, SLOT(sourceRowsRemoved(QModelIndex,int,int)));
+ connect(sm, SIGNAL(rowsAboutToBeInserted(QModelIndex,int,int)),
+ this, SLOT(sourceRowsAboutToBeInserted(QModelIndex,int,int)));
+ connect(sm, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)),
+ this, SLOT(sourceRowsAboutToBeRemoved(QModelIndex,int,int)));
+ }
+}
+
+#if QT_VERSION >= 0x050000
+QModelIndex ProxyModel::sibling(int row, int column, const QModelIndex &idx) const
+{
+ return QAbstractItemModel::sibling(row, column, idx);
+}
+#endif
+
+void ProxyModel::sourceDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
+{
+ QModelIndex topLeftIndex = mapFromSource(topLeft);
+ if (!topLeftIndex.isValid())
+ topLeftIndex = index(0, topLeft.column());
+ QModelIndex bottomRightIndex = mapFromSource(bottomRight);
+ if (!bottomRightIndex.isValid())
+ bottomRightIndex = index(0, bottomRight.column());
+ emit dataChanged(topLeftIndex, bottomRightIndex);
+}
+
+void ProxyModel::sourceRowsRemoved(const QModelIndex &parent, int start, int end)
+{
+ Q_UNUSED(parent)
+ Q_UNUSED(start)
+ Q_UNUSED(end)
+ endRemoveRows();
+}
+
+void ProxyModel::sourceRowsInserted(const QModelIndex &parent, int start, int end)
+{
+ Q_UNUSED(parent)
+ Q_UNUSED(start)
+ Q_UNUSED(end)
+ endInsertRows();
+}
+
+void ProxyModel::sourceRowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
+{
+ int realStart = parent.isValid() || start == 0 ? start : start - 1;
+ int realEnd = parent.isValid() || end == 0 ? end : end - 1;
+ beginRemoveRows(parent, realStart, realEnd);
+}
+
+void ProxyModel::sourceRowsAboutToBeInserted(const QModelIndex &parent, int start, int end)
+{
+ int realStart = parent.isValid() || start == 0 ? start : start - 1;
+ int realEnd = parent.isValid() || end == 0 ? end : end - 1;
+ beginInsertRows(parent, realStart, realEnd);
+}
diff --git a/src/plugins/coreplugin/editormanager/openeditorsview.h b/src/plugins/coreplugin/editormanager/openeditorsview.h
index ab32829a7e..311080f463 100644
--- a/src/plugins/coreplugin/editormanager/openeditorsview.h
+++ b/src/plugins/coreplugin/editormanager/openeditorsview.h
@@ -32,6 +32,7 @@
#include <coreplugin/inavigationwidgetfactory.h>
+#include <QAbstractProxyModel>
#include <QStyledItemDelegate>
#include <QTreeView>
@@ -40,6 +41,34 @@ class IEditor;
namespace Internal {
+class ProxyModel : public QAbstractProxyModel
+{
+ Q_OBJECT
+public:
+ explicit ProxyModel(QObject *parent = 0);
+ QModelIndex mapFromSource(const QModelIndex & sourceIndex) const;
+ QModelIndex mapToSource(const QModelIndex & proxyIndex) const;
+
+ QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const;
+ QModelIndex parent(const QModelIndex &child) const;
+ int rowCount(const QModelIndex &parent = QModelIndex()) const;
+ int columnCount(const QModelIndex &parent = QModelIndex()) const;
+
+ void setSourceModel(QAbstractItemModel *sourceModel);
+
+#if QT_VERSION >= 0x050000
+ // QAbstractProxyModel::sibling is broken in Qt 5
+ QModelIndex sibling(int row, int column, const QModelIndex &idx) const;
+#endif
+
+private slots:
+ void sourceDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight);
+ void sourceRowsRemoved(const QModelIndex &parent, int start, int end);
+ void sourceRowsInserted(const QModelIndex &parent, int start, int end);
+ void sourceRowsAboutToBeRemoved(const QModelIndex &parent, int start, int end);
+ void sourceRowsAboutToBeInserted(const QModelIndex &parent, int start, int end);
+};
+
class OpenEditorsDelegate : public QStyledItemDelegate
{
public:
@@ -73,6 +102,7 @@ private:
using QAbstractItemView::closeEditor;
OpenEditorsDelegate *m_delegate;
+ ProxyModel *m_model;
};
class OpenEditorsViewFactory : public Core::INavigationWidgetFactory
@@ -83,7 +113,7 @@ public:
~OpenEditorsViewFactory();
QString displayName() const;
int priority() const;
- Core::Id id() const;
+ Id id() const;
QKeySequence activationSequence() const;
Core::NavigationView createWidget();
};
diff --git a/src/plugins/coreplugin/editormanager/openeditorswindow.cpp b/src/plugins/coreplugin/editormanager/openeditorswindow.cpp
index 1367c799a5..19693e9820 100644
--- a/src/plugins/coreplugin/editormanager/openeditorswindow.cpp
+++ b/src/plugins/coreplugin/editormanager/openeditorswindow.cpp
@@ -28,10 +28,10 @@
****************************************************************************/
#include "openeditorswindow.h"
-#include "openeditorsmodel.h"
+#include "documentmodel.h"
#include "editormanager.h"
#include "editorview.h"
-#include "idocument.h"
+#include <coreplugin/idocument.h>
#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
@@ -193,7 +193,7 @@ void OpenEditorsWindow::centerOnItem(int selectedIndex)
}
}
-void OpenEditorsWindow::setEditors(const QList<EditLocation> &globalHistory, EditorView *view, OpenEditorsModel *model)
+void OpenEditorsWindow::setEditors(const QList<EditLocation> &globalHistory, EditorView *view, DocumentModel *model)
{
m_editorList->clear();
@@ -203,15 +203,15 @@ void OpenEditorsWindow::setEditors(const QList<EditLocation> &globalHistory, Edi
addHistoryItems(globalHistory, view, model, documentsDone);
// add purely restored editors which are not initialised yet
- foreach (const OpenEditorsModel::Entry &entry, model->entries()) {
- if (entry.editor)
+ foreach (DocumentModel::Entry *entry, model->documents()) {
+ if (entry->document)
continue;
QTreeWidgetItem *item = new QTreeWidgetItem();
- QString title = entry.displayName();
+ QString title = entry->displayName();
item->setIcon(0, m_emptyIcon);
item->setText(0, title);
- item->setToolTip(0, entry.fileName());
- item->setData(0, Qt::UserRole+2, QVariant::fromValue(entry.id()));
+ item->setToolTip(0, entry->fileName());
+ item->setData(0, Qt::UserRole+2, QVariant::fromValue(entry->id()));
item->setTextAlignment(0, Qt::AlignLeft);
m_editorList->addTopLevelItem(item);
@@ -225,11 +225,11 @@ void OpenEditorsWindow::selectEditor(QTreeWidgetItem *item)
return;
if (IDocument *document = item->data(0, Qt::UserRole).value<IDocument*>()) {
EditorView *view = item->data(0, Qt::UserRole+1).value<EditorView*>();
- EditorManager::instance()->activateEditorForDocument(view, document);
+ EditorManager::activateEditorForDocument(view, document);
} else {
if (!EditorManager::openEditor(
item->toolTip(0), item->data(0, Qt::UserRole+2).value<Core::Id>())) {
- EditorManager::instance()->openedEditorsModel()->removeEditor(item->toolTip(0));
+ EditorManager::documentModel()->removeDocument(item->toolTip(0));
delete item;
}
}
@@ -249,21 +249,21 @@ void OpenEditorsWindow::ensureCurrentVisible()
void OpenEditorsWindow::addHistoryItems(const QList<EditLocation> &history, EditorView *view,
- OpenEditorsModel *model, QSet<IDocument *> &documentsDone)
+ DocumentModel *model, QSet<IDocument *> &documentsDone)
{
foreach (const EditLocation &hi, history) {
if (hi.document.isNull() || documentsDone.contains(hi.document))
continue;
documentsDone.insert(hi.document.data());
- QString title = model->displayNameForDocument(hi.document);
+ QString title = hi.document->displayName();
QTC_ASSERT(!title.isEmpty(), continue);
QTreeWidgetItem *item = new QTreeWidgetItem();
if (hi.document->isModified())
title += tr("*");
- item->setIcon(0, !hi.document->fileName().isEmpty() && hi.document->isFileReadOnly()
+ item->setIcon(0, !hi.document->filePath().isEmpty() && hi.document->isFileReadOnly()
? model->lockedIcon() : m_emptyIcon);
item->setText(0, title);
- item->setToolTip(0, hi.document->fileName());
+ item->setToolTip(0, hi.document->filePath());
item->setData(0, Qt::UserRole, QVariant::fromValue(hi.document.data()));
item->setData(0, Qt::UserRole+1, QVariant::fromValue(view));
item->setTextAlignment(0, Qt::AlignLeft);
diff --git a/src/plugins/coreplugin/editormanager/openeditorswindow.h b/src/plugins/coreplugin/editormanager/openeditorswindow.h
index 93b5b38b9d..33ea5640a0 100644
--- a/src/plugins/coreplugin/editormanager/openeditorswindow.h
+++ b/src/plugins/coreplugin/editormanager/openeditorswindow.h
@@ -45,7 +45,7 @@ namespace Core {
class IDocument;
class IEditor;
-class OpenEditorsModel;
+class DocumentModel;
namespace Internal {
@@ -60,7 +60,7 @@ public:
explicit OpenEditorsWindow(QWidget *parent = 0);
- void setEditors(const QList<EditLocation> &globalHistory, EditorView *view, OpenEditorsModel *model);
+ void setEditors(const QList<EditLocation> &globalHistory, EditorView *view, DocumentModel *model);
bool eventFilter(QObject *src, QEvent *e);
void focusInEvent(QFocusEvent *);
@@ -78,7 +78,7 @@ private slots:
private:
static void updateItem(QTreeWidgetItem *item, IEditor *editor);
void addHistoryItems(const QList<EditLocation> &history, EditorView *view,
- OpenEditorsModel *model, QSet<IDocument*> &documentsDone);
+ DocumentModel *model, QSet<IDocument*> &documentsDone);
void ensureCurrentVisible();
bool isCentering();
void centerOnItem(int selectedIndex);
diff --git a/src/plugins/coreplugin/editormanager/systemeditor.cpp b/src/plugins/coreplugin/editormanager/systemeditor.cpp
index 5e77f4aa3d..ef9cb8fec9 100644
--- a/src/plugins/coreplugin/editormanager/systemeditor.cpp
+++ b/src/plugins/coreplugin/editormanager/systemeditor.cpp
@@ -28,7 +28,7 @@
****************************************************************************/
#include "systemeditor.h"
-#include "id.h"
+#include <coreplugin/id.h>
#include <QStringList>
#include <QUrl>
@@ -49,7 +49,7 @@ QStringList SystemEditor::mimeTypes() const
Id SystemEditor::id() const
{
- return Id("CorePlugin.OpenWithSystemEditor");
+ return "CorePlugin.OpenWithSystemEditor";
}
QString SystemEditor::displayName() const
diff --git a/src/plugins/coreplugin/editortoolbar.cpp b/src/plugins/coreplugin/editortoolbar.cpp
index 9fd7e2ca82..536bd883f5 100644
--- a/src/plugins/coreplugin/editortoolbar.cpp
+++ b/src/plugins/coreplugin/editortoolbar.cpp
@@ -34,7 +34,7 @@
#include <coreplugin/icore.h>
#include <coreplugin/editormanager/editormanager.h>
-#include <coreplugin/editormanager/openeditorsmodel.h>
+#include <coreplugin/editormanager/documentmodel.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <utils/hostosinfo.h>
@@ -57,7 +57,7 @@ namespace Core {
struct EditorToolBarPrivate {
explicit EditorToolBarPrivate(QWidget *parent, EditorToolBar *q);
- Core::OpenEditorsModel *m_editorsListModel;
+ Core::DocumentModel *m_editorsListModel;
QComboBox *m_editorList;
QToolButton *m_closeEditorButton;
QToolButton *m_lockButton;
@@ -115,7 +115,7 @@ EditorToolBar::EditorToolBar(QWidget *parent) :
d->m_lockButton->setAutoRaise(true);
d->m_lockButton->setEnabled(false);
- d->m_editorsListModel = EditorManager::instance()->openedEditorsModel();
+ d->m_editorsListModel = EditorManager::documentModel();
connect(d->m_goBackAction, SIGNAL(triggered()), this, SIGNAL(goBackClicked()));
connect(d->m_goForwardAction, SIGNAL(triggered()), this, SIGNAL(goForwardClicked()));
@@ -207,7 +207,7 @@ EditorToolBar::~EditorToolBar()
void EditorToolBar::removeToolbarForEditor(IEditor *editor)
{
QTC_ASSERT(editor, return);
- disconnect(editor, SIGNAL(changed()), this, SLOT(checkEditorStatus()));
+ disconnect(editor->document(), SIGNAL(changed()), this, SLOT(checkDocumentStatus()));
QWidget *toolBar = editor->toolBar();
if (toolBar != 0) {
@@ -238,20 +238,20 @@ void EditorToolBar::closeEditor()
return;
if (d->m_isStandalone)
- EditorManager::instance()->closeEditor(current);
+ EditorManager::closeEditor(current);
emit closeClicked();
}
void EditorToolBar::addEditor(IEditor *editor)
{
QTC_ASSERT(editor, return);
- connect(editor, SIGNAL(changed()), this, SLOT(checkEditorStatus()));
+ connect(editor->document(), SIGNAL(changed()), this, SLOT(checkDocumentStatus()));
QWidget *toolBar = editor->toolBar();
if (toolBar && !d->m_isStandalone)
addCenterToolBar(toolBar);
- updateEditorStatus(editor);
+ updateDocumentStatus(editor->document());
}
void EditorToolBar::addCenterToolBar(QWidget *toolBar)
@@ -278,7 +278,7 @@ void EditorToolBar::setToolbarCreationFlags(ToolbarCreationFlags flags)
{
d->m_isStandalone = flags & FlagsStandalone;
if (d->m_isStandalone) {
- EditorManager *em = EditorManager::instance();
+ QWidget *em = EditorManager::instance();
connect(em, SIGNAL(currentEditorChanged(Core::IEditor*)), SLOT(updateEditorListSelection(Core::IEditor*)));
disconnect(d->m_editorList, SIGNAL(activated(int)), this, SIGNAL(listSelectionActivated(int)));
@@ -290,42 +290,41 @@ void EditorToolBar::setToolbarCreationFlags(ToolbarCreationFlags flags)
void EditorToolBar::setCurrentEditor(IEditor *editor)
{
- QTC_ASSERT(editor, return);
- d->m_editorList->setCurrentIndex(d->m_editorsListModel->indexOf(editor).row());
+ IDocument *document = editor ? editor->document() : 0;
+ d->m_editorList->setCurrentIndex(d->m_editorsListModel->rowOfDocument(document));
// If we never added the toolbar from the editor, we will never change
// the editor, so there's no need to update the toolbar either.
if (!d->m_isStandalone)
- updateToolBar(editor->toolBar());
+ updateToolBar(editor ? editor->toolBar() : 0);
- updateEditorStatus(editor);
+ updateDocumentStatus(document);
}
void EditorToolBar::updateEditorListSelection(IEditor *newSelection)
{
if (newSelection)
- d->m_editorList->setCurrentIndex(d->m_editorsListModel->indexOf(newSelection).row());
+ d->m_editorList->setCurrentIndex(d->m_editorsListModel->rowOfDocument(newSelection->document()));
}
void EditorToolBar::changeActiveEditor(int row)
{
- EditorManager *em = ICore::editorManager();
- QAbstractItemModel *model = d->m_editorList->model();
- em->activateEditorForIndex(model->index(row, 0));
+ EditorManager::activateEditorForEntry(d->m_editorsListModel->documentAtRow(row));
}
void EditorToolBar::listContextMenu(QPoint pos)
{
- QModelIndex index = d->m_editorsListModel->index(d->m_editorList->currentIndex(), 0);
- QString fileName = d->m_editorsListModel->data(index, Qt::UserRole + 1).toString();
+ DocumentModel::Entry *entry = EditorManager::documentModel()->documentAtRow(
+ d->m_editorList->currentIndex());
+ QString fileName = entry ? entry->fileName() : QString();
if (fileName.isEmpty())
return;
QMenu menu;
QAction *copyPath = menu.addAction(tr("Copy Full Path to Clipboard"));
menu.addSeparator();
- EditorManager::instance()->addSaveAndCloseEditorActions(&menu, index);
+ EditorManager::addSaveAndCloseEditorActions(&menu, entry);
menu.addSeparator();
- EditorManager::instance()->addNativeDirActions(&menu, index);
+ EditorManager::addNativeDirActions(&menu, entry);
QAction *result = menu.exec(d->m_editorList->mapToGlobal(pos));
if (result == copyPath)
QApplication::clipboard()->setText(QDir::toNativeSeparators(fileName));
@@ -333,8 +332,8 @@ void EditorToolBar::listContextMenu(QPoint pos)
void EditorToolBar::makeEditorWritable()
{
- if (IEditor *current = EditorManager::currentEditor())
- EditorManager::instance()->makeFileWritable(current->document());
+ if (IDocument *current = EditorManager::currentDocument())
+ EditorManager::makeFileWritable(current);
}
void EditorToolBar::setCanGoBack(bool canGoBack)
@@ -355,20 +354,22 @@ void EditorToolBar::updateActionShortcuts()
d->m_closeSplitButton->setToolTip(ActionManager::command(Constants::REMOVE_CURRENT_SPLIT)->stringWithAppendedShortcut(tr("Remove Split")));
}
-void EditorToolBar::checkEditorStatus()
+void EditorToolBar::checkDocumentStatus()
{
- IEditor *editor = qobject_cast<IEditor *>(sender());
- IEditor *current = EditorManager::currentEditor();
+ IDocument *document = qobject_cast<IDocument *>(sender());
+ QTC_ASSERT(document, return);
+ DocumentModel::Entry *entry = EditorManager::documentModel()->documentAtRow(
+ d->m_editorList->currentIndex());
- if (current == editor)
- updateEditorStatus(editor);
+ if (entry && entry->document && entry->document == document)
+ updateDocumentStatus(document);
}
-void EditorToolBar::updateEditorStatus(IEditor *editor)
+void EditorToolBar::updateDocumentStatus(IDocument *document)
{
- d->m_closeEditorButton->setEnabled(editor != 0);
+ d->m_closeEditorButton->setEnabled(document != 0);
- if (!editor || !editor->document()) {
+ if (!document) {
d->m_lockButton->setIcon(QIcon());
d->m_lockButton->setEnabled(false);
d->m_lockButton->setToolTip(QString());
@@ -376,13 +377,13 @@ void EditorToolBar::updateEditorStatus(IEditor *editor)
return;
}
- d->m_editorList->setCurrentIndex(d->m_editorsListModel->indexOf(editor).row());
+ d->m_editorList->setCurrentIndex(d->m_editorsListModel->rowOfDocument(document));
- if (editor->document()->fileName().isEmpty()) {
+ if (document->filePath().isEmpty()) {
d->m_lockButton->setIcon(QIcon());
d->m_lockButton->setEnabled(false);
d->m_lockButton->setToolTip(QString());
- } else if (editor->document()->isFileReadOnly()) {
+ } else if (document->isFileReadOnly()) {
d->m_lockButton->setIcon(QIcon(d->m_editorsListModel->lockedIcon()));
d->m_lockButton->setEnabled(true);
d->m_lockButton->setToolTip(tr("Make Writable"));
@@ -391,13 +392,10 @@ void EditorToolBar::updateEditorStatus(IEditor *editor)
d->m_lockButton->setEnabled(false);
d->m_lockButton->setToolTip(tr("File is writable"));
}
- IEditor *current = EditorManager::currentEditor();
- if (editor == current)
- d->m_editorList->setToolTip(
- current->document()->fileName().isEmpty()
- ? current->displayName()
- : QDir::toNativeSeparators(editor->document()->fileName())
- );
+ d->m_editorList->setToolTip(
+ document->filePath().isEmpty()
+ ? document->displayName()
+ : QDir::toNativeSeparators(document->filePath()));
}
void EditorToolBar::setNavigationVisible(bool isVisible)
diff --git a/src/plugins/coreplugin/editortoolbar.h b/src/plugins/coreplugin/editortoolbar.h
index 310efc02d1..b9fb824c94 100644
--- a/src/plugins/coreplugin/editortoolbar.h
+++ b/src/plugins/coreplugin/editortoolbar.h
@@ -38,6 +38,7 @@
namespace Core {
class IEditor;
+class IDocument;
struct EditorToolBarPrivate;
@@ -81,7 +82,7 @@ public:
void setCloseSplitIcon(const QIcon &icon);
public slots:
- void updateEditorStatus(IEditor *editor);
+ void updateDocumentStatus(Core::IDocument *document);
signals:
void closeClicked();
@@ -99,7 +100,7 @@ private slots:
void listContextMenu(QPoint);
void makeEditorWritable();
- void checkEditorStatus();
+ void checkDocumentStatus();
void closeEditor();
void updateActionShortcuts();
diff --git a/src/plugins/coreplugin/externaltool.cpp b/src/plugins/coreplugin/externaltool.cpp
index 471977eee6..971704272e 100644
--- a/src/plugins/coreplugin/externaltool.cpp
+++ b/src/plugins/coreplugin/externaltool.cpp
@@ -327,7 +327,7 @@ static void localizedText(const QStringList &locales, QXmlStreamReader *reader,
static bool parseOutputAttribute(const QString &attribute, QXmlStreamReader *reader, ExternalTool::OutputHandling *value)
{
- const QString output = reader->attributes().value(attribute).toString();
+ const QStringRef output = reader->attributes().value(attribute);
if (output == QLatin1String(kOutputShowInPane)) {
*value = ExternalTool::ShowInPane;
} else if (output == QLatin1String(kOutputReplaceSelection)) {
@@ -381,7 +381,7 @@ ExternalTool * ExternalTool::createFromXml(const QByteArray &xml, QString *error
break;
}
if (reader.attributes().hasAttribute(QLatin1String(kModifiesDocument))) {
- const QString &value = reader.attributes().value(QLatin1String(kModifiesDocument)).toString();
+ const QStringRef value = reader.attributes().value(QLatin1String(kModifiesDocument));
if (value == QLatin1String(kYes) || value == QLatin1String(kTrue)) {
tool->m_modifiesCurrentDocument = true;
} else if (value == QLatin1String(kNo) || value == QLatin1String(kFalse)) {
@@ -447,11 +447,11 @@ ExternalTool * ExternalTool::createFromFile(const QString &fileName, QString *er
static QLatin1String stringForOutputHandling(ExternalTool::OutputHandling handling)
{
switch (handling) {
- case Core::Internal::ExternalTool::Ignore:
+ case ExternalTool::Ignore:
return QLatin1String(kOutputIgnore);
- case Core::Internal::ExternalTool::ShowInPane:
+ case ExternalTool::ShowInPane:
return QLatin1String(kOutputShowInPane);
- case Core::Internal::ExternalTool::ReplaceSelection:
+ case ExternalTool::ReplaceSelection:
return QLatin1String(kOutputReplaceSelection);
}
return QLatin1String("");
@@ -590,10 +590,10 @@ void ExternalToolRunner::run()
return;
}
if (m_tool->modifiesCurrentDocument()) {
- if (IEditor *editor = EditorManager::currentEditor()) {
- m_expectedFileName = editor->document()->fileName();
+ if (IDocument *document = EditorManager::currentDocument()) {
+ m_expectedFileName = document->filePath();
bool cancelled = false;
- DocumentManager::saveModifiedDocuments(QList<IDocument *>() << editor->document(), &cancelled);
+ DocumentManager::saveModifiedDocuments(QList<IDocument *>() << document, &cancelled);
if (cancelled) {
deleteLater();
return;
@@ -610,7 +610,7 @@ void ExternalToolRunner::run()
if (!m_resolvedWorkingDirectory.isEmpty())
m_process->setWorkingDirectory(m_resolvedWorkingDirectory);
m_process->setCommand(m_resolvedExecutable, m_resolvedArguments);
- ICore::messageManager()->printToOutputPane(
+ MessageManager::write(
tr("Starting external tool '%1' %2").arg(m_resolvedExecutable, m_resolvedArguments), MessageManager::Silent);
m_process->start();
}
@@ -627,11 +627,11 @@ void ExternalToolRunner::finished(int exitCode, QProcess::ExitStatus status)
if (status == QProcess::NormalExit && exitCode == 0
&& (m_tool->outputHandling() == ExternalTool::ReplaceSelection
|| m_tool->errorHandling() == ExternalTool::ReplaceSelection)) {
- emit ExternalToolManager::instance()->replaceSelectionRequested(m_processOutput);
+ ExternalToolManager::emitReplaceSelectionRequested(m_processOutput);
}
if (m_tool->modifiesCurrentDocument())
DocumentManager::unexpectFileChange(m_expectedFileName);
- ICore::messageManager()->printToOutputPane(
+ MessageManager::write(
tr("'%1' finished").arg(m_resolvedExecutable), MessageManager::Silent);
deleteLater();
}
@@ -652,7 +652,7 @@ void ExternalToolRunner::readStandardOutput()
QByteArray data = m_process->readAllStandardOutput();
QString output = m_outputCodec->toUnicode(data.constData(), data.length(), &m_outputCodecState);
if (m_tool->outputHandling() == ExternalTool::ShowInPane)
- ICore::messageManager()->printToOutputPane(output, MessageManager::NoModeSwitch);
+ MessageManager::write(output);
else if (m_tool->outputHandling() == ExternalTool::ReplaceSelection)
m_processOutput.append(output);
}
@@ -664,39 +664,49 @@ void ExternalToolRunner::readStandardError()
QByteArray data = m_process->readAllStandardError();
QString output = m_outputCodec->toUnicode(data.constData(), data.length(), &m_errorCodecState);
if (m_tool->errorHandling() == ExternalTool::ShowInPane)
- ICore::messageManager()->printToOutputPane(output, MessageManager::NoModeSwitch);
+ MessageManager::write(output);
else if (m_tool->errorHandling() == ExternalTool::ReplaceSelection)
m_processOutput.append(output);
}
-// #pragma mark -- ExternalToolManager
+// ExternalToolManager
-ExternalToolManager *ExternalToolManager::m_instance = 0;
+struct ExternalToolManagerPrivate
+{
+ QMap<QString, ExternalTool *> m_tools;
+ QMap<QString, QList<ExternalTool *> > m_categoryMap;
+ QMap<QString, QAction *> m_actions;
+ QMap<QString, ActionContainer *> m_containers;
+ QAction *m_configureSeparator;
+ QAction *m_configureAction;
+};
+
+static ExternalToolManager *m_instance = 0;
+static ExternalToolManagerPrivate *d = 0;
+
+static void writeSettings();
+static void readSettings(const QMap<QString, ExternalTool *> &tools,
+ QMap<QString, QList<ExternalTool*> > *categoryPriorityMap);
+
+static void parseDirectory(const QString &directory,
+ QMap<QString, QMultiMap<int, ExternalTool*> > *categoryMenus,
+ QMap<QString, ExternalTool *> *tools,
+ bool isPreset = false);
ExternalToolManager::ExternalToolManager()
: QObject(ICore::instance())
{
m_instance = this;
- initialize();
-}
-
-ExternalToolManager::~ExternalToolManager()
-{
- writeSettings();
- // TODO kill running tools
- qDeleteAll(m_tools);
-}
+ d = new ExternalToolManagerPrivate;
-void ExternalToolManager::initialize()
-{
- m_configureSeparator = new QAction(this);
- m_configureSeparator->setSeparator(true);
- m_configureAction = new QAction(tr("Configure..."), this);
- connect(m_configureAction, SIGNAL(triggered()), this, SLOT(openPreferences()));
+ d->m_configureSeparator = new QAction(this);
+ d->m_configureSeparator->setSeparator(true);
+ d->m_configureAction = new QAction(tr("Configure..."), this);
+ connect(d->m_configureAction, SIGNAL(triggered()), this, SLOT(openPreferences()));
// add the external tools menu
ActionContainer *mexternaltools = ActionManager::createMenu(Id(Constants::M_TOOLS_EXTERNAL));
- mexternaltools->menu()->setTitle(tr("&External"));
+ mexternaltools->menu()->setTitle(ExternalToolManager::tr("&External"));
ActionContainer *mtools = ActionManager::actionContainer(Constants::M_TOOLS);
mtools->addMenu(mexternaltools, Constants::G_DEFAULT_THREE);
@@ -710,7 +720,7 @@ void ExternalToolManager::initialize()
&tools,
true);
- QMap<QString, QList<Internal::ExternalTool *> > categoryMap;
+ QMap<QString, QList<ExternalTool *> > categoryMap;
QMapIterator<QString, QMultiMap<int, ExternalTool*> > it(categoryPriorityMap);
while (it.hasNext()) {
it.next();
@@ -722,10 +732,23 @@ void ExternalToolManager::initialize()
setToolsByCategory(categoryMap);
}
-void ExternalToolManager::parseDirectory(const QString &directory,
- QMap<QString, QMultiMap<int, Internal::ExternalTool*> > *categoryMenus,
- QMap<QString, ExternalTool *> *tools,
- bool isPreset)
+ExternalToolManager::~ExternalToolManager()
+{
+ writeSettings();
+ // TODO kill running tools
+ qDeleteAll(d->m_tools);
+ delete d;
+}
+
+QObject *ExternalToolManager::instance()
+{
+ return m_instance;
+}
+
+static void parseDirectory(const QString &directory,
+ QMap<QString, QMultiMap<int, ExternalTool*> > *categoryMenus,
+ QMap<QString, ExternalTool *> *tools,
+ bool isPreset)
{
QTC_ASSERT(categoryMenus, return);
QTC_ASSERT(tools, return);
@@ -735,7 +758,7 @@ void ExternalToolManager::parseDirectory(const QString &directory,
QString error;
ExternalTool *tool = ExternalTool::createFromFile(fileName, &error, ICore::userInterfaceLanguage());
if (!tool) {
- qWarning() << tr("Error while parsing external tool %1: %2").arg(fileName, error);
+ qWarning() << ExternalTool::tr("Error while parsing external tool %1: %2").arg(fileName, error);
continue;
}
if (tools->contains(tool->id())) {
@@ -744,7 +767,7 @@ void ExternalToolManager::parseDirectory(const QString &directory,
ExternalTool *other = tools->value(tool->id());
other->setPreset(QSharedPointer<ExternalTool>(tool));
} else {
- qWarning() << tr("Error: External tool in %1 has duplicate id").arg(fileName);
+ qWarning() << ExternalToolManager::tr("Error: External tool in %1 has duplicate id").arg(fileName);
delete tool;
}
continue;
@@ -762,24 +785,24 @@ void ExternalToolManager::menuActivated()
{
QAction *action = qobject_cast<QAction *>(sender());
QTC_ASSERT(action, return);
- ExternalTool *tool = m_tools.value(action->data().toString());
+ ExternalTool *tool = d->m_tools.value(action->data().toString());
QTC_ASSERT(tool, return);
ExternalToolRunner *runner = new ExternalToolRunner(tool);
if (runner->hasError())
- ICore::messageManager()->printToOutputPane(runner->errorString(), MessageManager::NoModeSwitch);
+ MessageManager::write(runner->errorString());
}
-QMap<QString, QList<Internal::ExternalTool *> > ExternalToolManager::toolsByCategory() const
+QMap<QString, QList<ExternalTool *> > ExternalToolManager::toolsByCategory()
{
- return m_categoryMap;
+ return d->m_categoryMap;
}
-QMap<QString, ExternalTool *> ExternalToolManager::toolsById() const
+QMap<QString, ExternalTool *> ExternalToolManager::toolsById()
{
- return m_tools;
+ return d->m_tools;
}
-void ExternalToolManager::setToolsByCategory(const QMap<QString, QList<Internal::ExternalTool *> > &tools)
+void ExternalToolManager::setToolsByCategory(const QMap<QString, QList<ExternalTool *> > &tools)
{
// clear menu
ActionContainer *mexternaltools = ActionManager::actionContainer(Id(Constants::M_TOOLS_EXTERNAL));
@@ -792,30 +815,30 @@ void ExternalToolManager::setToolsByCategory(const QMap<QString, QList<Internal:
while (it.hasNext()) {
it.next();
foreach (ExternalTool *tool, it.value()) {
- const QString &id = tool->id();
- if (m_tools.value(id) == tool) {
- newActions.insert(id, m_actions.value(id));
+ const QString id = tool->id();
+ if (d->m_tools.value(id) == tool) {
+ newActions.insert(id, d->m_actions.value(id));
// remove from list to prevent deletion
- m_tools.remove(id);
- m_actions.remove(id);
+ d->m_tools.remove(id);
+ d->m_actions.remove(id);
}
newTools.insert(id, tool);
}
}
- qDeleteAll(m_tools);
- QMapIterator<QString, QAction *> remainingActions(m_actions);
- const Id externalToolsPrefix = Id("Tools.External.");
+ qDeleteAll(d->m_tools);
+ QMapIterator<QString, QAction *> remainingActions(d->m_actions);
+ const Id externalToolsPrefix = "Tools.External.";
while (remainingActions.hasNext()) {
remainingActions.next();
ActionManager::unregisterAction(remainingActions.value(),
externalToolsPrefix.withSuffix(remainingActions.key()));
delete remainingActions.value();
}
- m_actions.clear();
+ d->m_actions.clear();
// assign the new stuff
- m_tools = newTools;
- m_actions = newActions;
- m_categoryMap = tools;
+ d->m_tools = newTools;
+ d->m_actions = newActions;
+ d->m_categoryMap = tools;
// create menu structure and remove no-longer used containers
// add all the category menus, QMap is nicely sorted
QMap<QString, ActionContainer *> newContainers;
@@ -827,8 +850,8 @@ 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))
- container = m_containers.take(containerName); // remove to avoid deletion below
+ if (d->m_containers.contains(containerName))
+ container = d->m_containers.take(containerName); // remove to avoid deletion below
else
container = ActionManager::createMenu(Id("Tools.External.Category.").withSuffix(containerName));
newContainers.insert(containerName, container);
@@ -840,14 +863,14 @@ void ExternalToolManager::setToolsByCategory(const QMap<QString, QList<Internal:
// tool action and command
QAction *action = 0;
Command *command = 0;
- if (m_actions.contains(toolId)) {
- action = m_actions.value(toolId);
+ if (d->m_actions.contains(toolId)) {
+ action = d->m_actions.value(toolId);
command = ActionManager::command(externalToolsPrefix.withSuffix(toolId));
} else {
- action = new QAction(tool->displayName(), this);
+ action = new QAction(tool->displayName(), m_instance);
action->setData(toolId);
- m_actions.insert(toolId, action);
- connect(action, SIGNAL(triggered()), this, SLOT(menuActivated()));
+ d->m_actions.insert(toolId, action);
+ connect(action, SIGNAL(triggered()), m_instance, SLOT(menuActivated()));
command = ActionManager::registerAction(action, externalToolsPrefix.withSuffix(toolId), Context(Constants::C_GLOBAL));
command->setAttribute(Command::CA_UpdateText);
}
@@ -859,16 +882,16 @@ void ExternalToolManager::setToolsByCategory(const QMap<QString, QList<Internal:
}
// delete the unused containers
- qDeleteAll(m_containers);
+ qDeleteAll(d->m_containers);
// remember the new containers
- m_containers = newContainers;
+ d->m_containers = newContainers;
// (re)add the configure menu item
- mexternaltools->menu()->addAction(m_configureSeparator);
- mexternaltools->menu()->addAction(m_configureAction);
+ mexternaltools->menu()->addAction(d->m_configureSeparator);
+ mexternaltools->menu()->addAction(d->m_configureAction);
}
-void ExternalToolManager::readSettings(const QMap<QString, ExternalTool *> &tools,
+static void readSettings(const QMap<QString, ExternalTool *> &tools,
QMap<QString, QList<ExternalTool *> > *categoryMap)
{
QSettings *settings = ICore::settings();
@@ -902,14 +925,14 @@ void ExternalToolManager::readSettings(const QMap<QString, ExternalTool *> &tool
settings->endGroup();
}
-void ExternalToolManager::writeSettings()
+static void writeSettings()
{
QSettings *settings = ICore::settings();
settings->beginGroup(QLatin1String("ExternalTools"));
settings->remove(QLatin1String(""));
settings->beginGroup(QLatin1String("OverrideCategories"));
- QMapIterator<QString, QList<ExternalTool *> > it(m_categoryMap);
+ QMapIterator<QString, QList<ExternalTool *> > it(d->m_categoryMap);
while (it.hasNext()) {
it.next();
QString category = it.key();
@@ -933,3 +956,8 @@ void ExternalToolManager::openPreferences()
{
ICore::showOptionsDialog(Constants::SETTINGS_CATEGORY_CORE, Constants::SETTINGS_ID_TOOLS);
}
+
+void ExternalToolManager::emitReplaceSelectionRequested(const QString &output)
+{
+ emit m_instance->replaceSelectionRequested(output);
+}
diff --git a/src/plugins/coreplugin/externaltoolmanager.h b/src/plugins/coreplugin/externaltoolmanager.h
index cc05ec0e74..12bd07e486 100644
--- a/src/plugins/coreplugin/externaltoolmanager.h
+++ b/src/plugins/coreplugin/externaltoolmanager.h
@@ -37,30 +37,23 @@
#include <QList>
#include <QString>
-QT_FORWARD_DECLARE_CLASS(QAction)
-
namespace Core {
-class ActionContainer;
-namespace Internal {
-class ExternalToolRunner;
-class ExternalTool;
-}
+namespace Internal { class ExternalTool; }
class CORE_EXPORT ExternalToolManager : public QObject
{
Q_OBJECT
public:
- static ExternalToolManager *instance() { return m_instance; }
-
ExternalToolManager();
~ExternalToolManager();
- QMap<QString, QList<Internal::ExternalTool *> > toolsByCategory() const;
- QMap<QString, Internal::ExternalTool *> toolsById() const;
-
- void setToolsByCategory(const QMap<QString, QList<Internal::ExternalTool *> > &tools);
+ static QObject *instance();
+ static QMap<QString, QList<Internal::ExternalTool *> > toolsByCategory();
+ static QMap<QString, Internal::ExternalTool *> toolsById();
+ static void setToolsByCategory(const QMap<QString, QList<Internal::ExternalTool *> > &tools);
+ static void emitReplaceSelectionRequested(const QString &output);
signals:
void replaceSelectionRequested(const QString &text);
@@ -68,30 +61,9 @@ signals:
private slots:
void menuActivated();
void openPreferences();
-
-private:
- void initialize();
- void parseDirectory(const QString &directory,
- QMap<QString, QMultiMap<int, Internal::ExternalTool*> > *categoryMenus,
- QMap<QString, Internal::ExternalTool *> *tools,
- bool isPreset = false);
- void readSettings(const QMap<QString, Internal::ExternalTool *> &tools,
- QMap<QString, QList<Internal::ExternalTool*> > *categoryPriorityMap);
- void writeSettings();
-
- static ExternalToolManager *m_instance;
- QMap<QString, Internal::ExternalTool *> m_tools;
- QMap<QString, QList<Internal::ExternalTool *> > m_categoryMap;
- QMap<QString, QAction *> m_actions;
- QMap<QString, ActionContainer *> m_containers;
- QAction *m_configureSeparator;
- QAction *m_configureAction;
-
- // for sending the replaceSelectionRequested signal
- friend class Core::Internal::ExternalToolRunner;
};
-} // Core
+} // namespace Core
#endif // EXTERNALTOOLMANAGER_H
diff --git a/src/plugins/coreplugin/fancyactionbar.cpp b/src/plugins/coreplugin/fancyactionbar.cpp
index a5afc6d78a..d99b5b5eae 100644
--- a/src/plugins/coreplugin/fancyactionbar.cpp
+++ b/src/plugins/coreplugin/fancyactionbar.cpp
@@ -46,23 +46,18 @@
#include <QPropertyAnimation>
#include <QDebug>
-using namespace Core;
-using namespace Internal;
+using namespace Utils;
+
+namespace Core {
+namespace Internal {
FancyToolButton::FancyToolButton(QWidget *parent)
: QToolButton(parent), m_fader(0)
{
- m_hasForceVisible = false;
setAttribute(Qt::WA_Hover, true);
setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
}
-void FancyToolButton::forceVisible(bool visible)
-{
- m_hasForceVisible = true;
- setVisible(visible);
-}
-
bool FancyToolButton::event(QEvent *e)
{
switch (e->type()) {
@@ -85,7 +80,7 @@ bool FancyToolButton::event(QEvent *e)
case QEvent::ToolTip:
{
QHelpEvent *he = static_cast<QHelpEvent *>(e);
- Utils::ToolTip::instance()->show(mapToGlobal(he->pos()), Utils::TextContent(toolTip()), this);
+ ToolTip::show(mapToGlobal(he->pos()), TextContent(toolTip()), this);
return true;
}
default:
@@ -175,8 +170,6 @@ void FancyToolButton::paintEvent(QPaintEvent *event)
painter.drawLine(rect().topLeft() - QPoint(0,1), rect().topRight() - QPoint(0,1));
painter.restore();
}
- QPixmap borderPixmap;
- QMargins margins;
QRect iconRect(0, 0, Core::Constants::TARGET_ICON_SIZE, Core::Constants::TARGET_ICON_SIZE);
// draw popup texts
@@ -304,10 +297,8 @@ void FancyToolButton::actionChanged()
{
// the default action changed in some way, e.g. it might got hidden
// since we inherit a tool button we won't get invisible, so do this here
- if (!m_hasForceVisible) {
- if (QAction* action = defaultAction())
- setVisible(action->isVisible());
- }
+ if (QAction* action = defaultAction())
+ setVisible(action->isVisible());
}
FancyActionBar::FancyActionBar(QWidget *parent)
@@ -351,3 +342,5 @@ QSize FancyActionBar::minimumSizeHint() const
return sizeHint();
}
+} // namespace Internal
+} // namespace Core
diff --git a/src/plugins/coreplugin/fancyactionbar.h b/src/plugins/coreplugin/fancyactionbar.h
index dd4722d4ed..a545d4b42b 100644
--- a/src/plugins/coreplugin/fancyactionbar.h
+++ b/src/plugins/coreplugin/fancyactionbar.h
@@ -57,13 +57,8 @@ public:
float fader() { return m_fader; }
void setFader(float value) { m_fader = value; update(); }
- void forceVisible(bool visible);
-
private slots:
void actionChanged();
-
-private:
- bool m_hasForceVisible;
};
class FancyActionBar : public QWidget
diff --git a/src/plugins/coreplugin/featureprovider.cpp b/src/plugins/coreplugin/featureprovider.cpp
index 0aa2cff9a9..a992e63a67 100644
--- a/src/plugins/coreplugin/featureprovider.cpp
+++ b/src/plugins/coreplugin/featureprovider.cpp
@@ -63,7 +63,7 @@
*/
/*!
- \fn FeatureProvider::Features availableFeatures() const;
+ \fn FetureSet IFeatureProvider::availableFeatures(const QString &platform) const
Returns available features provided by this manager.
\sa FeatureProvider::Features
*/
@@ -95,13 +95,13 @@
/*!
- \fn bool Features::~contains(const Feature &feature)()
+ \fn bool FeatureSet::contains(const Feature &feature) const
Returns true if \a feature is available.
*/
/*!
- \fn bool Features::~contains(const Features &features)()
+ \fn bool FeatureSet::contains(const FeatureSet &features) const
Returns true if all \a features are available.
*/
diff --git a/src/plugins/coreplugin/fileiconprovider.cpp b/src/plugins/coreplugin/fileiconprovider.cpp
index 95d4071a29..867d00eb6c 100644
--- a/src/plugins/coreplugin/fileiconprovider.cpp
+++ b/src/plugins/coreplugin/fileiconprovider.cpp
@@ -49,94 +49,91 @@ using namespace Utils;
\class Core::FileIconProvider
Provides icons based on file suffixes with the ability to overwrite system
- icons for specific subtypes. Implements the QFileIconProvider interface
- and can therefore be used for QFileSystemModel.
+ icons for specific subtypes. The underlying QFileIconProvider
+ can be used for QFileSystemModel.
Note: Registering overlay icons currently completely replaces the system
icon and is therefore not recommended on platforms that have their
own overlay icon handling (Mac/Windows).
- The class is a singleton: It's instance can be accessed via the static instance() method.
Plugins can register custom overlay icons via registerIconOverlayForSuffix(), and
retrieve icons via the icon() method.
- The instance is explicitly deleted by the core plugin for destruction order reasons.
*/
// Cache icons in a list of pairs suffix/icon which should be faster than
// hashes for small lists.
+namespace Core {
+namespace FileIconProvider {
+
enum { debug = 0 };
typedef QPair<QString, QIcon> StringIconPair;
typedef QList<StringIconPair> StringIconPairList;
-// Helper to find an icon by suffix in a list of pairs for const/non-const-iterators.
-
-template <class StringIconPairListIterator>
-inline StringIconPairListIterator
-findBySuffix(const QString &suffix,
- StringIconPairListIterator iter,
- const StringIconPairListIterator &end)
+class FileIconProviderImplementation : public QFileIconProvider
{
- for (; iter != end; ++iter)
- if ((*iter).first == suffix)
- return iter;
- return end;
-}
+public:
+ FileIconProviderImplementation()
+ : m_unknownFileIcon(qApp->style()->standardIcon(QStyle::SP_FileIcon))
+ {}
-namespace Core {
+ QIcon icon(const QFileInfo &info) const;
+ using QFileIconProvider::icon;
-struct FileIconProviderPrivate {
- FileIconProviderPrivate();
+ void registerIconOverlayForSuffix(const QIcon &icon, const QString &suffix)
+ {
+ if (debug)
+ qDebug() << "FileIconProvider::registerIconOverlayForSuffix" << suffix;
- // Mapping of file suffix to icon.
- StringIconPairList m_cache;
+ QTC_ASSERT(!icon.isNull() && !suffix.isEmpty(), return);
- QIcon m_unknownFileIcon;
+ const QPixmap fileIconPixmap = FileIconProvider::overlayIcon(QStyle::SP_FileIcon, icon, QSize(16, 16));
- // singleton pattern
- static FileIconProvider *m_instance;
-};
+ // replace old icon, if it exists
+ for (int i = 0, n = m_cache.size(); i != n; ++i) {
+ if (m_cache.at(i).first == suffix) {
+ m_cache[i].second = fileIconPixmap;
+ return;
+ }
+ }
+ m_cache.append(StringIconPair(suffix, fileIconPixmap));
+ }
-FileIconProviderPrivate::FileIconProviderPrivate() :
- m_unknownFileIcon(qApp->style()->standardIcon(QStyle::SP_FileIcon))
-{
-}
+ void registerIconOverlayForMimeType(const QIcon &icon, const MimeType &mimeType)
+ {
+ foreach (const QString &suffix, mimeType.suffixes())
+ registerIconOverlayForSuffix(icon, suffix);
+ }
-FileIconProvider *FileIconProviderPrivate::m_instance = 0;
+ // Mapping of file suffix to icon.
+ StringIconPairList m_cache;
-// FileIconProvider
+ QIcon m_unknownFileIcon;
+};
-FileIconProvider::FileIconProvider() :
- d(new FileIconProviderPrivate)
+FileIconProviderImplementation *instance()
{
- FileIconProviderPrivate::m_instance = this;
+ static FileIconProviderImplementation theInstance;
+ return &theInstance;
}
-FileIconProvider::~FileIconProvider()
+QFileIconProvider *iconProvider()
{
- FileIconProviderPrivate::m_instance = 0;
- delete d;
+ return instance();
}
-/*!
- Returns the icon associated with the file suffix in fileInfo. If there is none,
- the default icon of the operating system is returned.
- */
-
-QIcon FileIconProvider::icon(const QFileInfo &fileInfo) const
+QIcon FileIconProviderImplementation::icon(const QFileInfo &fileInfo) const
{
- typedef StringIconPairList::const_iterator CacheConstIterator;
-
if (debug)
qDebug() << "FileIconProvider::icon" << fileInfo.absoluteFilePath();
// Check for cached overlay icons by file suffix.
- if (!d->m_cache.isEmpty() && !fileInfo.isDir()) {
+ if (!m_cache.isEmpty() && !fileInfo.isDir()) {
const QString suffix = fileInfo.suffix();
if (!suffix.isEmpty()) {
- const CacheConstIterator it = findBySuffix(suffix, d->m_cache.constBegin(), d->m_cache.constEnd());
- if (it != d->m_cache.constEnd())
- return (*it).second;
+ for (int i = 0, n = m_cache.size(); i != n; ++i)
+ if (m_cache.at(i).first == suffix)
+ return m_cache[i].second;
}
}
// Get icon from OS.
@@ -144,16 +141,32 @@ QIcon FileIconProvider::icon(const QFileInfo &fileInfo) const
return QFileIconProvider::icon(fileInfo);
// File icons are unknown on linux systems.
- return (fileInfo.isDir()) ?
- QFileIconProvider::icon(fileInfo) :
- d->m_unknownFileIcon;
+ return fileInfo.isDir() ? QFileIconProvider::icon(fileInfo) : m_unknownFileIcon;
+}
+
+/*!
+ Returns the icon associated with the file suffix in fileInfo. If there is none,
+ the default icon of the operating system is returned.
+ */
+
+QIcon icon(const QFileInfo &info)
+{
+ return instance()->icon(info);
+}
+
+/*!
+ * \overload
+ */
+QIcon icon(QFileIconProvider::IconType type)
+{
+ return instance()->icon(type);
}
/*!
Creates a pixmap with baseicon at size and overlays overlayIcon over it.
See platform note in class documentation about recommended usage.
*/
-QPixmap FileIconProvider::overlayIcon(QStyle::StandardPixmap baseIcon, const QIcon &overlayIcon, const QSize &size)
+QPixmap overlayIcon(QStyle::StandardPixmap baseIcon, const QIcon &overlayIcon, const QSize &size)
{
QPixmap iconPixmap = qApp->style()->standardIcon(baseIcon).pixmap(size);
QPainter painter(&iconPixmap);
@@ -166,43 +179,26 @@ QPixmap FileIconProvider::overlayIcon(QStyle::StandardPixmap baseIcon, const QIc
Registers an icon for a given suffix, overlaying the system file icon.
See platform note in class documentation about recommended usage.
*/
-void FileIconProvider::registerIconOverlayForSuffix(const QIcon &icon,
- const QString &suffix)
+void registerIconOverlayForSuffix(const char *path, const char *suffix)
{
- typedef StringIconPairList::iterator CacheIterator;
-
- if (debug)
- qDebug() << "FileIconProvider::registerIconOverlayForSuffix" << suffix;
-
- QTC_ASSERT(!icon.isNull() && !suffix.isEmpty(), return);
-
- 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())
- d->m_cache.append(StringIconPair(suffix, fileIconPixmap));
- else
- (*it).second = fileIconPixmap;
+ instance()->registerIconOverlayForSuffix(QIcon(QLatin1String(path)), QLatin1String(suffix));
}
/*!
Registers an icon for all the suffixes of a given mime type, overlaying the system file icon.
*/
-void FileIconProvider::registerIconOverlayForMimeType(const QIcon &icon, const MimeType &mimeType)
+void registerIconOverlayForMimeType(const QIcon &icon, const char *mimeType)
{
- foreach (const QString &suffix, mimeType.suffixes())
- registerIconOverlayForSuffix(icon, suffix);
+ instance()->registerIconOverlayForMimeType(icon, MimeDatabase::findByType(QString::fromLatin1(mimeType)));
}
/*!
- Returns the sole instance of FileIconProvider.
- */
-
-FileIconProvider *FileIconProvider::instance()
+ * \overload
+ */
+void registerIconOverlayForMimeType(const char *path, const char *mimeType)
{
- if (!FileIconProviderPrivate::m_instance)
- FileIconProviderPrivate::m_instance = new FileIconProvider;
- return FileIconProviderPrivate::m_instance;
+ instance()->registerIconOverlayForMimeType(QIcon(QLatin1String(path)), MimeDatabase::findByType(QString::fromLatin1(mimeType)));
}
-} // namespace core
+} // namespace FileIconProvider
+} // namespace Core
diff --git a/src/plugins/coreplugin/fileiconprovider.h b/src/plugins/coreplugin/fileiconprovider.h
index adb95be60e..b77b2031d1 100644
--- a/src/plugins/coreplugin/fileiconprovider.h
+++ b/src/plugins/coreplugin/fileiconprovider.h
@@ -35,40 +35,26 @@
#include <QStyle>
#include <QFileIconProvider>
-QT_BEGIN_NAMESPACE
-class QFileInfo;
-class QIcon;
-class QPixmap;
-class QString;
-QT_END_NAMESPACE
-
namespace Core {
class MimeType;
-struct FileIconProviderPrivate;
-
-class CORE_EXPORT FileIconProvider : public QFileIconProvider
-{
- FileIconProvider();
-
-public:
- virtual ~FileIconProvider();
- // Implement QFileIconProvider
- virtual QIcon icon(const QFileInfo &info) const;
- using QFileIconProvider::icon;
+namespace FileIconProvider {
- // Register additional overlay icons
- static QPixmap overlayIcon(QStyle::StandardPixmap baseIcon, const QIcon &overlayIcon, const QSize &size);
- void registerIconOverlayForSuffix(const QIcon &icon, const QString &suffix);
- void registerIconOverlayForMimeType(const QIcon &icon, const MimeType &mimeType);
+// Access to the single instance
+CORE_EXPORT QFileIconProvider *iconProvider();
- static FileIconProvider *instance();
+// Access to individual items
+CORE_EXPORT QIcon icon(const QFileInfo &info);
+CORE_EXPORT QIcon icon(QFileIconProvider::IconType type);
-private:
- FileIconProviderPrivate *d;
-};
+// Register additional overlay icons
+CORE_EXPORT QPixmap overlayIcon(QStyle::StandardPixmap baseIcon, const QIcon &overlayIcon, const QSize &size);
+CORE_EXPORT void registerIconOverlayForSuffix(const char *path, const char *suffix);
+CORE_EXPORT void registerIconOverlayForMimeType(const char *path, const char *mimeType);
+CORE_EXPORT void registerIconOverlayForMimeType(const QIcon &icon, const char *mimeType);
+} // namespace FileIconProvider
} // namespace Core
#endif // FILEICONPROVIDER_H
diff --git a/src/plugins/coreplugin/fileutils.cpp b/src/plugins/coreplugin/fileutils.cpp
index 143dfbbeaf..716baa3030 100644
--- a/src/plugins/coreplugin/fileutils.cpp
+++ b/src/plugins/coreplugin/fileutils.cpp
@@ -140,6 +140,11 @@ void FileUtils::openTerminal(const QString &path)
QProcess::startDetached(terminalEmulator, args, pwd);
}
+QString FileUtils::msgFindInDirectory()
+{
+ return QApplication::translate("Core::Internal", "Find in This Directory...");
+}
+
QString FileUtils::msgGraphicalShellAction()
{
if (HostOsInfo::isWindowsHost())
@@ -159,7 +164,7 @@ QString FileUtils::msgTerminalAction()
void FileUtils::removeFile(const QString &filePath, bool deleteFromFS)
{
// remove from version control
- ICore::vcsManager()->promptToDelete(filePath);
+ VcsManager::promptToDelete(filePath);
// remove from file system
if (deleteFromFS) {
@@ -194,7 +199,7 @@ bool FileUtils::renameFile(const QString &orgFilePath, const QString &newFilePat
return false;
QString dir = QFileInfo(orgFilePath).absolutePath();
- IVersionControl *vc = ICore::vcsManager()->findVersionControlForDirectory(dir);
+ IVersionControl *vc = VcsManager::findVersionControlForDirectory(dir);
bool result = false;
if (vc && vc->supportsOperation(IVersionControl::MoveOperation))
diff --git a/src/plugins/coreplugin/fileutils.h b/src/plugins/coreplugin/fileutils.h
index aa025f2a54..92ffa12a89 100644
--- a/src/plugins/coreplugin/fileutils.h
+++ b/src/plugins/coreplugin/fileutils.h
@@ -43,6 +43,7 @@ struct CORE_EXPORT FileUtils
// Helpers for common directory browser options.
static void showInGraphicalShell(QWidget *parent, const QString &path);
static void openTerminal(const QString &path);
+ static QString msgFindInDirectory();
// Platform-dependent action descriptions
static QString msgGraphicalShellAction();
static QString msgTerminalAction();
diff --git a/src/plugins/coreplugin/generalsettings.cpp b/src/plugins/coreplugin/generalsettings.cpp
index ead28c556a..e052a77ca4 100644
--- a/src/plugins/coreplugin/generalsettings.cpp
+++ b/src/plugins/coreplugin/generalsettings.cpp
@@ -110,7 +110,7 @@ QWidget *GeneralSettings::createPage(QWidget *parent)
fillLanguageBox();
m_page->colorButton->setColor(StyleHelper::requestedBaseColor());
- m_page->reloadBehavior->setCurrentIndex(EditorManager::instance()->reloadSetting());
+ m_page->reloadBehavior->setCurrentIndex(EditorManager::reloadSetting());
if (HostOsInfo::isAnyUnixHost()) {
QSettings *settings = Core::ICore::settings();
const QStringList availableTerminals = ConsoleProcess::availableTerminalEmulators();
@@ -135,8 +135,8 @@ QWidget *GeneralSettings::createPage(QWidget *parent)
m_page->helpExternalFileBrowserButton->hide();
}
- m_page->autoSaveCheckBox->setChecked(EditorManager::instance()->autoSaveEnabled());
- m_page->autoSaveInterval->setValue(EditorManager::instance()->autoSaveInterval());
+ m_page->autoSaveCheckBox->setChecked(EditorManager::autoSaveEnabled());
+ m_page->autoSaveInterval->setValue(EditorManager::autoSaveInterval());
m_page->resetWarningsButton->setEnabled(Core::InfoBar::anyGloballySuppressed());
connect(m_page->resetColorButton, SIGNAL(clicked()),
@@ -179,7 +179,7 @@ void GeneralSettings::apply()
setLanguage(m_page->languageBox->itemData(currentIndex, Qt::UserRole).toString());
// Apply the new base color if accepted
StyleHelper::setBaseColor(m_page->colorButton->color());
- EditorManager::instance()->setReloadSetting(IDocument::ReloadSetting(m_page->reloadBehavior->currentIndex()));
+ EditorManager::setReloadSetting(IDocument::ReloadSetting(m_page->reloadBehavior->currentIndex()));
if (HostOsInfo::isAnyUnixHost()) {
ConsoleProcess::setTerminalEmulator(Core::ICore::settings(),
m_page->terminalComboBox->lineEdit()->text());
@@ -188,8 +188,8 @@ void GeneralSettings::apply()
m_page->externalFileBrowserEdit->text());
}
}
- EditorManager::instance()->setAutoSaveEnabled(m_page->autoSaveCheckBox->isChecked());
- EditorManager::instance()->setAutoSaveInterval(m_page->autoSaveInterval->value());
+ EditorManager::setAutoSaveEnabled(m_page->autoSaveCheckBox->isChecked());
+ EditorManager::setAutoSaveInterval(m_page->autoSaveInterval->value());
}
void GeneralSettings::finish()
diff --git a/src/plugins/coreplugin/helpmanager.cpp b/src/plugins/coreplugin/helpmanager.cpp
index fba9df5826..e2bb16d471 100644
--- a/src/plugins/coreplugin/helpmanager.cpp
+++ b/src/plugins/coreplugin/helpmanager.cpp
@@ -65,6 +65,7 @@ struct HelpManagerPrivate
};
static HelpManager *m_instance = 0;
+static HelpManagerPrivate *d;
static const char linksForKeyQuery[] = "SELECT d.Title, f.Name, e.Name, "
"d.Name, a.Anchor FROM IndexTable a, FileNameTable d, FolderTable e, "
@@ -83,10 +84,11 @@ struct DbCleaner
// -- HelpManager
HelpManager::HelpManager(QObject *parent) :
- QObject(parent), d(new HelpManagerPrivate)
+ QObject(parent)
{
Q_ASSERT(!m_instance);
m_instance = this;
+ d = new HelpManagerPrivate;
}
HelpManager::~HelpManager()
@@ -97,7 +99,7 @@ HelpManager::~HelpManager()
delete d;
}
-HelpManager *HelpManager::instance()
+QObject *HelpManager::instance()
{
Q_ASSERT(m_instance);
return m_instance;
@@ -143,7 +145,7 @@ void HelpManager::registerDocumentation(const QStringList &files)
}
}
if (docsChanged)
- emit documentationChanged();
+ emit m_instance->documentationChanged();
}
void HelpManager::unregisterDocumentation(const QStringList &nameSpaces)
@@ -164,7 +166,7 @@ void HelpManager::unregisterDocumentation(const QStringList &nameSpaces)
}
}
if (docsChanged)
- emit documentationChanged();
+ emit m_instance->documentationChanged();
}
static QUrl buildQUrl(const QString &ns, const QString &folder,
@@ -179,7 +181,7 @@ static QUrl buildQUrl(const QString &ns, const QString &folder,
}
// This should go into Qt 4.8 once we start using it for Qt Creator
-QMap<QString, QUrl> HelpManager::linksForKeyword(const QString &key) const
+QMap<QString, QUrl> HelpManager::linksForKeyword(const QString &key)
{
QMap<QString, QUrl> links;
if (d->m_needsSetup)
@@ -212,7 +214,7 @@ QMap<QString, QUrl> HelpManager::linksForKeyword(const QString &key) const
return links;
}
-QMap<QString, QUrl> HelpManager::linksForIdentifier(const QString &id) const
+QMap<QString, QUrl> HelpManager::linksForIdentifier(const QString &id)
{
if (d->m_needsSetup)
return QMap<QString, QUrl>();
@@ -220,7 +222,8 @@ QMap<QString, QUrl> HelpManager::linksForIdentifier(const QString &id) const
}
// This should go into Qt 4.8 once we start using it for Qt Creator
-QStringList HelpManager::findKeywords(const QString &key, int maxHits) const
+QStringList HelpManager::findKeywords(const QString &key, Qt::CaseSensitivity caseSensitivity,
+ int maxHits)
{
if (d->m_needsSetup)
return QStringList();
@@ -249,7 +252,7 @@ QStringList HelpManager::findKeywords(const QString &key, int maxHits) const
while (query.next()) {
const QString &keyValue = query.value(0).toString();
if (!keyValue.isEmpty()) {
- if (keyValue.startsWith(key, Qt::CaseInsensitive))
+ if (keyValue.startsWith(key, caseSensitivity))
keywordsToSort.insert(keyValue);
else
keywords.insert(keyValue);
@@ -264,14 +267,14 @@ QStringList HelpManager::findKeywords(const QString &key, int maxHits) const
return keywordsSorted + keywords.toList();
}
-QUrl HelpManager::findFile(const QUrl &url) const
+QUrl HelpManager::findFile(const QUrl &url)
{
if (d->m_needsSetup)
return QUrl();
return d->m_helpEngine->findFile(url);
}
-QByteArray HelpManager::fileData(const QUrl &url) const
+QByteArray HelpManager::fileData(const QUrl &url)
{
if (d->m_needsSetup)
return QByteArray();
@@ -280,24 +283,24 @@ QByteArray HelpManager::fileData(const QUrl &url) const
void HelpManager::handleHelpRequest(const QString &url)
{
- emit helpRequested(QUrl(url));
+ emit m_instance->helpRequested(QUrl(url));
}
-QStringList HelpManager::registeredNamespaces() const
+QStringList HelpManager::registeredNamespaces()
{
if (d->m_needsSetup)
return QStringList();
return d->m_helpEngine->registeredDocumentations();
}
-QString HelpManager::namespaceFromFile(const QString &file) const
+QString HelpManager::namespaceFromFile(const QString &file)
{
if (d->m_needsSetup)
return QString();
return d->m_helpEngine->namespaceName(file);
}
-QString HelpManager::fileFromNamespace(const QString &nameSpace) const
+QString HelpManager::fileFromNamespace(const QString &nameSpace)
{
if (d->m_needsSetup)
return QString();
@@ -311,17 +314,17 @@ void HelpManager::setCustomValue(const QString &key, const QVariant &value)
return;
}
if (d->m_helpEngine->setCustomValue(key, value))
- emit collectionFileChanged();
+ emit m_instance->collectionFileChanged();
}
-QVariant HelpManager::customValue(const QString &key, const QVariant &value) const
+QVariant HelpManager::customValue(const QString &key, const QVariant &value)
{
if (d->m_needsSetup)
return QVariant();
return d->m_helpEngine->customValue(key, value);
}
-HelpManager::Filters HelpManager::filters() const
+HelpManager::Filters HelpManager::filters()
{
if (d->m_needsSetup)
return Filters();
@@ -333,7 +336,7 @@ HelpManager::Filters HelpManager::filters() const
return filters;
}
-HelpManager::Filters HelpManager::fixedFilters() const
+HelpManager::Filters HelpManager::fixedFilters()
{
Filters fixedFilters;
if (d->m_needsSetup)
@@ -362,7 +365,7 @@ HelpManager::Filters HelpManager::fixedFilters() const
return fixedFilters;
}
-HelpManager::Filters HelpManager::userDefinedFilters() const
+HelpManager::Filters HelpManager::userDefinedFilters()
{
if (d->m_needsSetup)
return Filters();
@@ -380,7 +383,7 @@ void HelpManager::removeUserDefinedFilter(const QString &filter)
return;
if (d->m_helpEngine->removeCustomFilter(filter))
- emit collectionFileChanged();
+ emit m_instance->collectionFileChanged();
}
void HelpManager::addUserDefinedFilter(const QString &filter, const QStringList &attr)
@@ -389,7 +392,7 @@ void HelpManager::addUserDefinedFilter(const QString &filter, const QStringList
return;
if (d->m_helpEngine->addCustomFilter(filter, attr))
- emit collectionFileChanged();
+ emit m_instance->collectionFileChanged();
}
// -- private slots
@@ -400,7 +403,7 @@ void HelpManager::setupHelpManager()
return;
d->m_needsSetup = false;
- d->m_helpEngine = new QHelpEngineCore(collectionFilePath(), this);
+ d->m_helpEngine = new QHelpEngineCore(collectionFilePath(), m_instance);
d->m_helpEngine->setAutoSaveFilter(false);
d->m_helpEngine->setCurrentFilter(tr("Unfiltered"));
d->m_helpEngine->setupData();
@@ -422,7 +425,7 @@ void HelpManager::setupHelpManager()
for (it = d->m_customValues.constBegin(); it != d->m_customValues.constEnd(); ++it)
setCustomValue(it.key(), it.value());
- emit setupFinished();
+ emit m_instance->setupFinished();
}
// -- private
diff --git a/src/plugins/coreplugin/helpmanager.h b/src/plugins/coreplugin/helpmanager.h
index 7e1d8f160a..da11acd994 100644
--- a/src/plugins/coreplugin/helpmanager.h
+++ b/src/plugins/coreplugin/helpmanager.h
@@ -45,6 +45,7 @@ struct HelpManagerPrivate;
namespace Internal {
class CorePlugin;
+class MainWindow;
}
class CORE_EXPORT HelpManager : public QObject
@@ -53,38 +54,38 @@ class CORE_EXPORT HelpManager : public QObject
public:
typedef QHash<QString, QStringList> Filters;
- explicit HelpManager(QObject *parent = 0);
- virtual ~HelpManager();
- static HelpManager* instance();
+ static QObject *instance();
static QString collectionFilePath();
- void registerDocumentation(const QStringList &fileNames);
- void unregisterDocumentation(const QStringList &nameSpaces);
+ static void registerDocumentation(const QStringList &fileNames);
+ static void unregisterDocumentation(const QStringList &nameSpaces);
- QMap<QString, QUrl> linksForKeyword(const QString &key) const;
- QMap<QString, QUrl> linksForIdentifier(const QString &id) const;
- QStringList findKeywords(const QString &key, int maxHits = INT_MAX) const;
+ static QMap<QString, QUrl> linksForKeyword(const QString &key);
+ static QMap<QString, QUrl> linksForIdentifier(const QString &id);
+ static QStringList findKeywords(const QString &key,
+ Qt::CaseSensitivity caseSensitivity = Qt::CaseInsensitive,
+ int maxHits = INT_MAX);
- QUrl findFile(const QUrl &url) const;
- QByteArray fileData(const QUrl &url) const;
+ static QUrl findFile(const QUrl &url);
+ static QByteArray fileData(const QUrl &url);
- QStringList registeredNamespaces() const;
- QString namespaceFromFile(const QString &file) const;
- QString fileFromNamespace(const QString &nameSpace) const;
+ static QStringList registeredNamespaces();
+ static QString namespaceFromFile(const QString &file);
+ static QString fileFromNamespace(const QString &nameSpace);
- void setCustomValue(const QString &key, const QVariant &value);
- QVariant customValue(const QString &key, const QVariant &value = QVariant()) const;
+ static void setCustomValue(const QString &key, const QVariant &value);
+ static QVariant customValue(const QString &key, const QVariant &value = QVariant());
- Filters filters() const;
- Filters fixedFilters() const;
+ static Filters filters();
+ static Filters fixedFilters();
- Filters userDefinedFilters() const;
- void removeUserDefinedFilter(const QString &filter);
- void addUserDefinedFilter(const QString &filter, const QStringList &attr);
+ static Filters userDefinedFilters();
+ static void removeUserDefinedFilter(const QString &filter);
+ static void addUserDefinedFilter(const QString &filter, const QStringList &attr);
public slots:
- void handleHelpRequest(const QString &url);
+ static void handleHelpRequest(const QString &url);
signals:
void setupFinished();
@@ -93,10 +94,13 @@ signals:
void helpRequested(const QUrl &url);
private:
- void setupHelpManager();
- void verifyDocumenation();
- HelpManagerPrivate *d;
- friend class Internal::CorePlugin; // setupHelpManager
+ explicit HelpManager(QObject *parent = 0);
+ ~HelpManager();
+
+ static void setupHelpManager();
+ static void verifyDocumenation();
+ friend class Core::Internal::CorePlugin; // setupHelpManager
+ friend class Core::Internal::MainWindow; // constructor/destructor
};
} // Core
diff --git a/src/plugins/coreplugin/icore.cpp b/src/plugins/coreplugin/icore.cpp
index cc1b676d17..3e7bb7398f 100644
--- a/src/plugins/coreplugin/icore.cpp
+++ b/src/plugins/coreplugin/icore.cpp
@@ -86,9 +86,9 @@
/*!
\fn bool ICore::showWarningWithOptions(const QString &title, const QString &text,
const QString &details = QString(),
- const QString &settingsCategory = QString(),
- const QString &settingsId = QString(),
- QWidget *parent = 0);
+ Id settingsCategory = Id(),
+ Id settingsId = Id(),
+ QWidget *parent = 0)
Shows a warning message with a button that opens a settings page.
@@ -98,85 +98,6 @@
/*!
- \fn ActionManager *ICore::actionManager() const
- Returns the application's action manager.
-
- The action manager is responsible for registration of menus and
- menu items and keyboard shortcuts.
-*/
-
-/*!
- \fn DocumentManager *ICore::fileManager() const
- \brief Returns the application's file manager.
-
- The file manager keeps track of files for changes outside the application.
-*/
-
-/*!
- \fn MessageManager *ICore::messageManager()
-
- Returns the application's message manager.
-
- The message manager is the interface to the "General" output pane for
- general application debug messages.
-*/
-
-/*!
- \fn EditorManager *ICore::editorManager()
-
- Returns the application's editor manager.
-
- The editor manager handles all editor related tasks like opening
- documents, the stack of currently open documents and the currently
- active document.
-*/
-
-/*!
- \fn ProgressManager *ICore::progressManager()
-
- Returns the application's progress manager.
-
- Use the progress manager to register a concurrent task to
- show a progress bar the way \QC does it.
-*/
-
-/*!
- \fn ScriptManager *ICore::scriptManager() const
- \internal
-*/
-
-/*!
- \fn VariableManager *ICore::variableManager() const
- Returns the application's variable manager.
-
- The variable manager is used to register application wide string variables
- like \c MY_PROJECT_DIR such that strings like \c{somecommand ${MY_PROJECT_DIR}/sub}
- can be resolved/expanded from anywhere in the application.
-*/
-
-/*!
- \fn VcsManager *ICore::vcsManager()
-
- Returns the application's version control system (VCS) manager.
-
- The VCS manager can be used to retrieve information about
- the version control system used for a directory on hard disk.
- The actual functionality for a specific version control system
- must be implemented in an \c IVersionControl object and registered in
- the plugin manager's object pool.
-*/
-
-/*!
- \fn ModeManager *ICore::modeManager() const
- Returns the application's mode manager.
-
- The mode manager handles everything related to the instances of IMode
- that were added to the plugin manager's object pool as well as their
- buttons and the tool bar with the round buttons in the lower left
- corner of Qt Creator.
-*/
-
-/*!
\fn MimeDatabase *ICore::mimeDatabase()
Uses the MIME database to manage MIME types.
@@ -309,7 +230,7 @@
*/
/*!
- \fn ICore::ICore()
+ \fn ICore::ICore(Internal::MainWindow *mw)
\internal
*/
@@ -364,23 +285,18 @@
#include <utils/hostosinfo.h>
-#include <QDir>
#include <QCoreApplication>
#include <QDebug>
-
+#include <QDir>
#include <QStatusBar>
+using namespace Core::Internal;
+
namespace Core {
// The Core Singleton
static ICore *m_instance = 0;
-
-namespace Internal {
static MainWindow *m_mainwindow;
-} // namespace Internal
-
-using namespace Core::Internal;
-
ICore *ICore::instance()
{
@@ -426,61 +342,6 @@ bool ICore::showWarningWithOptions(const QString &title, const QString &text,
settingsId, parent);
}
-ActionManager *ICore::actionManager()
-{
- return m_mainwindow->actionManager();
-}
-
-DocumentManager *ICore::documentManager()
-{
- return DocumentManager::instance();
-}
-
-MessageManager *ICore::messageManager()
-{
- return m_mainwindow->messageManager();
-}
-
-EditorManager *ICore::editorManager()
-{
- return m_mainwindow->editorManager();
-}
-
-ProgressManager *ICore::progressManager()
-{
- return m_mainwindow->progressManager();
-}
-
-ScriptManager *ICore::scriptManager()
-{
- return m_mainwindow->scriptManager();
-}
-
-VariableManager *ICore::variableManager()
-{
- return m_mainwindow->variableManager();
-}
-
-VcsManager *ICore::vcsManager()
-{
- return m_mainwindow->vcsManager();
-}
-
-ModeManager *ICore::modeManager()
-{
- return m_mainwindow->modeManager();
-}
-
-MimeDatabase *ICore::mimeDatabase()
-{
- return m_mainwindow->mimeDatabase();
-}
-
-HelpManager *ICore::helpManager()
-{
- return m_mainwindow->helpManager();
-}
-
QSettings *ICore::settings(QSettings::Scope scope)
{
return m_mainwindow->settings(scope);
@@ -577,11 +438,6 @@ QWidget *ICore::mainWindow()
return m_mainwindow;
}
-Utils::AppMainWindow *ICore::appMainWindow()
-{
- return m_mainwindow;
-}
-
QStatusBar *ICore::statusBar()
{
return m_mainwindow->statusBar();
diff --git a/src/plugins/coreplugin/icore.h b/src/plugins/coreplugin/icore.h
index 461035772f..e036e083ea 100644
--- a/src/plugins/coreplugin/icore.h
+++ b/src/plugins/coreplugin/icore.h
@@ -43,25 +43,12 @@ class QWidget;
template <class T> class QList;
QT_END_NAMESPACE
-namespace Utils {
-class AppMainWindow;
-}
-
namespace Core {
class IWizard;
-class ActionManager;
class Context;
-class EditorManager;
-class DocumentManager;
-class HelpManager;
class IContext;
-class MessageManager;
-class MimeDatabase;
-class ModeManager;
class ProgressManager;
-class ScriptManager;
class SettingsDatabase;
-class VariableManager;
class VcsManager;
namespace Internal { class MainWindow; }
@@ -93,18 +80,6 @@ public:
Id settingsId = Id(),
QWidget *parent = 0);
- static QT_DEPRECATED ActionManager *actionManager(); // Use Actionmanager::... directly.
- static QT_DEPRECATED DocumentManager *documentManager(); // Use DocumentManager::... directly.
- static MessageManager *messageManager();
- static EditorManager *editorManager();
- static ProgressManager *progressManager();
- static ScriptManager *scriptManager();
- static QT_DEPRECATED VariableManager *variableManager(); // Use VariableManager::... directly.
- static VcsManager *vcsManager();
- static QT_DEPRECATED ModeManager *modeManager(); // Use ModeManager::... directly.
- static MimeDatabase *mimeDatabase();
- static HelpManager *helpManager();
-
static QSettings *settings(QSettings::Scope scope = QSettings::UserScope);
static SettingsDatabase *settingsDatabase();
static QPrinter *printer();
@@ -118,7 +93,6 @@ public:
static QString buildCompatibilityString();
static QWidget *mainWindow();
- static Utils::AppMainWindow *appMainWindow();
static QStatusBar *statusBar();
/* Raises and activates the window for the widget. This contains workarounds for X11. */
static void raiseWindow(QWidget *widget);
diff --git a/src/plugins/coreplugin/id.cpp b/src/plugins/coreplugin/id.cpp
index 6fa2a76083..3bc21c5c97 100644
--- a/src/plugins/coreplugin/id.cpp
+++ b/src/plugins/coreplugin/id.cpp
@@ -135,7 +135,7 @@ static int theId(const QByteArray &ba)
}
/*!
- \fn Core::Id(int uid)
+ \fn Core::Id::Id(int uid)
Constructs an id given \a UID.
diff --git a/src/plugins/coreplugin/idocument.cpp b/src/plugins/coreplugin/idocument.cpp
index 01ec58af3e..3d1f9e82dc 100644
--- a/src/plugins/coreplugin/idocument.cpp
+++ b/src/plugins/coreplugin/idocument.cpp
@@ -34,9 +34,20 @@
#include <QFile>
#include <QFileInfo>
+/*!
+ \fn QString Core::IDocument::filePath() const
+ Returns the absolute path of the file that this document refers to. May be empty for
+ non-file documents.
+ \sa setFilePath()
+*/
+
namespace Core {
-IDocument::IDocument(QObject *parent) : QObject(parent), m_infoBar(0), m_hasWriteWarning(false), m_restored(false)
+IDocument::IDocument(QObject *parent) : QObject(parent),
+ m_temporary(false),
+ m_infoBar(0),
+ m_hasWriteWarning(false),
+ m_restored(false)
{
}
@@ -46,6 +57,18 @@ IDocument::~IDocument()
delete m_infoBar;
}
+/*!
+ Used for example by EditorManager::openEditorWithContents() to set the contents
+ of this document.
+ Returns if setting the contents was successful.
+ The base implementation does nothing and returns false.
+*/
+bool IDocument::setContents(const QByteArray &contents)
+{
+ Q_UNUSED(contents)
+ return false;
+}
+
IDocument::ReloadBehavior IDocument::reloadBehavior(ChangeTrigger state, ChangeType type) const
{
if (type == TypePermissions)
@@ -66,9 +89,28 @@ bool IDocument::shouldAutoSave() const
bool IDocument::isFileReadOnly() const
{
- if (fileName().isEmpty())
+ if (filePath().isEmpty())
return false;
- return !QFileInfo(fileName()).isWritable();
+ return !QFileInfo(filePath()).isWritable();
+}
+
+/*!
+ Returns if the document is a temporary that should for example not be considered
+ when saving/restoring the session state, recent files, etc. Defaults to false.
+ \sa setTemporary()
+*/
+bool IDocument::isTemporary() const
+{
+ return m_temporary;
+}
+
+/*!
+ Sets if the document is \a temporary.
+ \sa isTemporary()
+*/
+void IDocument::setTemporary(bool temporary)
+{
+ m_temporary = temporary;
}
bool IDocument::autoSave(QString *errorString, const QString &fileName)
@@ -110,4 +152,47 @@ InfoBar *IDocument::infoBar()
return m_infoBar;
}
+/*!
+ Set absolute file path for this file to \a filePath. Can be empty.
+ The default implementation sets the file name and sends filePathChanged() and changed()
+ signals. Can be reimplemented by subclasses to do more.
+ \sa filePath()
+*/
+void IDocument::setFilePath(const QString &filePath)
+{
+ if (m_filePath == filePath)
+ return;
+ QString oldName = m_filePath;
+ m_filePath = filePath;
+ emit filePathChanged(oldName, m_filePath);
+ emit changed();
+}
+
+/*!
+ Returns the string to display for this document, e.g. in the open document combo box
+ and pane.
+ \sa setDisplayName()
+*/
+QString IDocument::displayName() const
+{
+ if (!m_displayName.isEmpty())
+ return m_displayName;
+ return QFileInfo(m_filePath).fileName();
+}
+
+/*!
+ Sets the string that is displayed for this document, e.g. in the open document combo box
+ and pane, to \a name. Defaults to the file name of the file path for this document.
+ You can reset the display name to the default by passing an empty string.
+ \sa displayName()
+ \sa filePath()
+ */
+void IDocument::setDisplayName(const QString &name)
+{
+ if (name == m_displayName)
+ return;
+ m_displayName = name;
+ emit changed();
+}
+
} // namespace Core
diff --git a/src/plugins/coreplugin/idocument.h b/src/plugins/coreplugin/idocument.h
index c543366316..3178268389 100644
--- a/src/plugins/coreplugin/idocument.h
+++ b/src/plugins/coreplugin/idocument.h
@@ -82,8 +82,16 @@ public:
virtual ~IDocument();
virtual bool save(QString *errorString, const QString &fileName = QString(), bool autoSave = false) = 0;
- virtual QString fileName() const = 0;
+ virtual bool setContents(const QByteArray &contents);
+
+ QString filePath() const { return m_filePath; }
+ virtual void setFilePath(const QString &filePath);
+ QString displayName() const;
+ void setDisplayName(const QString &name);
+
virtual bool isFileReadOnly() const;
+ bool isTemporary() const;
+ void setTemporary(bool temporary);
virtual QString defaultPath() const = 0;
virtual QString suggestedFileName() const = 0;
@@ -95,11 +103,10 @@ public:
virtual ReloadBehavior reloadBehavior(ChangeTrigger state, ChangeType type) const;
virtual bool reload(QString *errorString, ReloadFlag flag, ChangeType type) = 0;
- virtual void rename(const QString &newName) = 0;
virtual void checkPermissions();
- bool autoSave(QString *errorString, const QString &fileName);
+ bool autoSave(QString *errorString, const QString &filePath);
void setRestoredFrom(const QString &name);
void removeAutoSaveFile();
@@ -114,9 +121,12 @@ signals:
void aboutToReload();
void reloadFinished(bool success);
- void fileNameChanged(const QString &oldName, const QString &newName);
+ void filePathChanged(const QString &oldName, const QString &newName);
private:
+ QString m_filePath;
+ QString m_displayName;
+ bool m_temporary;
QString m_autoSaveName;
InfoBar *m_infoBar;
bool m_hasWriteWarning;
diff --git a/src/plugins/coreplugin/idocumentfactory.h b/src/plugins/coreplugin/idocumentfactory.h
index bf9bbb0055..d9cbaa1311 100644
--- a/src/plugins/coreplugin/idocumentfactory.h
+++ b/src/plugins/coreplugin/idocumentfactory.h
@@ -30,18 +30,14 @@
#ifndef IDOCUMENTFACTORY_H
#define IDOCUMENTFACTORY_H
-#include "core_global.h"
+#include "id.h"
#include <QObject>
-
-QT_BEGIN_NAMESPACE
-class QStringList;
-QT_END_NAMESPACE
+#include <QStringList>
namespace Core {
class IDocument;
-class Id;
class CORE_EXPORT IDocumentFactory : public QObject
{
@@ -50,10 +46,23 @@ class CORE_EXPORT IDocumentFactory : public QObject
public:
IDocumentFactory(QObject *parent = 0) : QObject(parent) {}
- virtual QStringList mimeTypes() const = 0;
- virtual Id id() const = 0;
- virtual QString displayName() const = 0;
virtual IDocument *open(const QString &fileName) = 0;
+
+ Id id() const { return m_id; }
+ QStringList mimeTypes() const { return m_mimeTypes; }
+ QString displayName() const { return m_displayName; }
+
+protected:
+ void setId(Id id) { m_id = id; }
+ void setDisplayName(const QString &displayName) { m_displayName = displayName; }
+ void setMimeTypes(const QStringList &mimeTypes) { m_mimeTypes = mimeTypes; }
+ void addMimeType(const char *mimeType) { m_mimeTypes.append(QLatin1String(mimeType)); }
+ void addMimeType(const QString &mimeType) { m_mimeTypes.append(mimeType); }
+
+private:
+ Id m_id;
+ QStringList m_mimeTypes;
+ QString m_displayName;
};
} // namespace Core
diff --git a/src/plugins/coreplugin/images/sidebysidediff.png b/src/plugins/coreplugin/images/sidebysidediff.png
new file mode 100644
index 0000000000..55c6f2802d
--- /dev/null
+++ b/src/plugins/coreplugin/images/sidebysidediff.png
Binary files differ
diff --git a/src/plugins/coreplugin/images/textdiff.png b/src/plugins/coreplugin/images/textdiff.png
new file mode 100644
index 0000000000..254b187744
--- /dev/null
+++ b/src/plugins/coreplugin/images/textdiff.png
Binary files differ
diff --git a/src/plugins/coreplugin/mainwindow.cpp b/src/plugins/coreplugin/mainwindow.cpp
index 80fd6013cd..e28821914f 100644
--- a/src/plugins/coreplugin/mainwindow.cpp
+++ b/src/plugins/coreplugin/mainwindow.cpp
@@ -28,33 +28,21 @@
****************************************************************************/
#include "mainwindow.h"
-#include "actioncontainer.h"
-#include "command.h"
-#include "actionmanager.h"
-#include "actionmanager_p.h"
#include "icore.h"
#include "coreconstants.h"
-#include "editormanager.h"
#include "toolsettings.h"
#include "mimetypesettings.h"
#include "fancytabwidget.h"
#include "documentmanager.h"
#include "generalsettings.h"
#include "helpmanager.h"
-#include "ieditor.h"
#include "idocumentfactory.h"
#include "messagemanager.h"
#include "modemanager.h"
#include "mimedatabase.h"
-#include "newdialog.h"
#include "outputpanemanager.h"
#include "plugindialog.h"
-#include "progressmanager_p.h"
-#include "progressview.h"
-#include "shortcutsettings.h"
#include "vcsmanager.h"
-#include "scriptmanager_p.h"
-#include "settingsdialog.h"
#include "variablemanager.h"
#include "versiondialog.h"
#include "statusbarmanager.h"
@@ -72,8 +60,19 @@
#endif
#include <app/app_version.h>
+#include <coreplugin/actionmanager/actioncontainer.h>
+#include <coreplugin/actionmanager/actionmanager.h>
+#include <coreplugin/actionmanager/actionmanager_p.h>
+#include <coreplugin/actionmanager/command.h>
+#include <coreplugin/dialogs/newdialog.h>
+#include <coreplugin/dialogs/settingsdialog.h>
+#include <coreplugin/dialogs/shortcutsettings.h>
+#include <coreplugin/editormanager/editormanager.h>
+#include <coreplugin/editormanager/ieditor.h>
#include <coreplugin/icorelistener.h>
#include <coreplugin/inavigationwidgetfactory.h>
+#include <coreplugin/progressmanager/progressmanager_p.h>
+#include <coreplugin/progressmanager/progressview.h>
#include <coreplugin/settingsdatabase.h>
#include <utils/historycompleter.h>
#include <utils/hostosinfo.h>
@@ -101,16 +100,6 @@
#include <QPushButton>
#include <QStyleFactory>
-/*
-#include <signal.h>
-extern "C" void handleSigInt(int sig)
-{
- Q_UNUSED(sig)
- Core::ICore::exit();
- qDebug() << "SIGINT caught. Shutting down.";
-}
-*/
-
using namespace Core;
using namespace Core::Internal;
@@ -129,8 +118,7 @@ MainWindow::MainWindow() :
m_actionManager(new ActionManager(this)),
m_editorManager(0),
m_externalToolManager(0),
- m_progressManager(new ProgressManagerPrivate()),
- m_scriptManager(new ScriptManagerPrivate(this)),
+ m_progressManager(new ProgressManagerPrivate),
m_variableManager(new VariableManager),
m_vcsManager(new VcsManager),
m_statusBarManager(0),
@@ -174,9 +162,9 @@ MainWindow::MainWindow() :
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")))
+ if (QStyleFactory::keys().contains(QLatin1String("Fusion"))) {
baseName = QLatin1String("fusion"); // Qt5
- else { // Qt4
+ } else { // Qt4
// e.g. if we are running on a KDE4 desktop
QByteArray desktopEnvironment = qgetenv("DESKTOP_SESSION");
if (desktopEnvironment == "kde")
@@ -316,13 +304,15 @@ MainWindow::~MainWindow()
delete m_helpManager;
m_helpManager = 0;
+ delete m_variableManager;
+ m_variableManager = 0;
}
bool MainWindow::init(QString *errorMessage)
{
Q_UNUSED(errorMessage)
- if (!mimeDatabase()->addMimeTypes(QLatin1String(":/core/editormanager/BinFiles.mimetypes.xml"), errorMessage))
+ if (!MimeDatabase::addMimeTypes(QLatin1String(":/core/editormanager/BinFiles.mimetypes.xml"), errorMessage))
return false;
ExtensionSystem::PluginManager::addObject(m_coreImpl);
@@ -342,7 +332,7 @@ bool MainWindow::init(QString *errorMessage)
m_outputView->setWidget(OutputPaneManager::instance()->buttonsWidget());
m_outputView->setPosition(Core::StatusBarWidget::Second);
ExtensionSystem::PluginManager::addObject(m_outputView);
- m_messageManager->init();
+ MessageManager::init();
return true;
}
@@ -355,7 +345,7 @@ void MainWindow::extensionsInitialized()
m_navigationWidget->setFactories(ExtensionSystem::PluginManager::getObjects<INavigationWidgetFactory>());
// reading the shortcut settings must be done after all shortcuts have been registered
- m_actionManager->d->initialize();
+ m_actionManager->initialize();
readSettings();
updateContext();
@@ -799,7 +789,7 @@ void MainWindow::newFile()
void MainWindow::openFile()
{
- openFiles(editorManager()->getOpenFileNames(), ICore::SwitchMode);
+ openFiles(EditorManager::getOpenFileNames(), ICore::SwitchMode);
}
static QList<IDocumentFactory*> getNonEditorDocumentFactories()
@@ -815,10 +805,9 @@ static QList<IDocumentFactory*> getNonEditorDocumentFactories()
}
static IDocumentFactory *findDocumentFactory(const QList<IDocumentFactory*> &fileFactories,
- const MimeDatabase *db,
const QFileInfo &fi)
{
- if (const MimeType mt = db->findByFile(fi)) {
+ if (const MimeType mt = MimeDatabase::findByFile(fi)) {
const QString type = mt.type();
foreach (IDocumentFactory *factory, fileFactories) {
if (factory->mimeTypes().contains(type))
@@ -846,7 +835,7 @@ IDocument *MainWindow::openFiles(const QStringList &fileNames, ICore::OpenFilesF
foreach (const QString &fileName, fileNames) {
const QFileInfo fi(fileName);
const QString absoluteFilePath = fi.absoluteFilePath();
- if (IDocumentFactory *documentFactory = findDocumentFactory(nonEditorFileFactories, mimeDatabase(), fi)) {
+ if (IDocumentFactory *documentFactory = findDocumentFactory(nonEditorFileFactories, fi)) {
IDocument *document = documentFactory->open(absoluteFilePath);
if (!document) {
if (flags & ICore::StopOnLoadFail)
@@ -951,10 +940,9 @@ void MainWindow::exit()
void MainWindow::openFileWith()
{
- QStringList fileNames = editorManager()->getOpenFileNames();
- foreach (const QString &fileName, fileNames) {
+ foreach (const QString &fileName, EditorManager::getOpenFileNames()) {
bool isExternal;
- const Id editorId = editorManager()->getOpenWithEditorId(fileName, &isExternal);
+ const Id editorId = EditorManager::getOpenWithEditorId(fileName, &isExternal);
if (!editorId.isValid())
continue;
if (isExternal)
@@ -964,21 +952,6 @@ void MainWindow::openFileWith()
}
}
-ActionManager *MainWindow::actionManager() const
-{
- return m_actionManager;
-}
-
-MessageManager *MainWindow::messageManager() const
-{
- return m_messageManager;
-}
-
-VcsManager *MainWindow::vcsManager() const
-{
- return m_vcsManager;
-}
-
QSettings *MainWindow::settings(QSettings::Scope scope) const
{
if (scope == QSettings::UserScope)
@@ -987,41 +960,6 @@ QSettings *MainWindow::settings(QSettings::Scope scope) const
return m_globalSettings;
}
-EditorManager *MainWindow::editorManager() const
-{
- return m_editorManager;
-}
-
-ProgressManager *MainWindow::progressManager() const
-{
- return m_progressManager;
-}
-
-ScriptManager *MainWindow::scriptManager() const
-{
- return m_scriptManager;
-}
-
-VariableManager *MainWindow::variableManager() const
-{
- return m_variableManager.data();
-}
-
-ModeManager *MainWindow::modeManager() const
-{
- return m_modeManager;
-}
-
-MimeDatabase *MainWindow::mimeDatabase() const
-{
- return m_mimeDatabase;
-}
-
-HelpManager *MainWindow::helpManager() const
-{
- return m_helpManager;
-}
-
IContext *MainWindow::contextObject(QWidget *widget)
{
return m_contextWidgets.value(widget);
@@ -1144,7 +1082,7 @@ void MainWindow::readSettings()
restoreState(m_settings->value(QLatin1String(windowStateKey)).toByteArray());
bool modeSelectorVisible = m_settings->value(QLatin1String(modeSelectorVisibleKey), true).toBool();
- ModeManager::instance()->setModeSelectorVisible(modeSelectorVisible);
+ ModeManager::setModeSelectorVisible(modeSelectorVisible);
m_toggleModeSelectorAction->setChecked(modeSelectorVisible);
m_settings->endGroup();
@@ -1168,7 +1106,7 @@ void MainWindow::writeSettings()
m_settings->endGroup();
DocumentManager::saveSettings();
- m_actionManager->d->saveSettings(m_settings);
+ m_actionManager->saveSettings(m_settings);
m_editorManager->saveSettings();
m_navigationWidget->saveSettings(m_settings);
}
@@ -1211,7 +1149,7 @@ void MainWindow::updateContext()
uniquecontexts.add(id);
}
- m_actionManager->d->setContext(uniquecontexts);
+ m_actionManager->setContext(uniquecontexts);
emit m_coreImpl->contextChanged(m_activeContext, m_additionalContexts);
}
diff --git a/src/plugins/coreplugin/mainwindow.h b/src/plugins/coreplugin/mainwindow.h
index 8254f8e1e7..8c7f0b1290 100644
--- a/src/plugins/coreplugin/mainwindow.h
+++ b/src/plugins/coreplugin/mainwindow.h
@@ -61,7 +61,6 @@ class ModeManager;
class ProgressManager;
class NavigationWidget;
class RightPaneWidget;
-class ScriptManager;
class SettingsDatabase;
class VariableManager;
class VcsManager;
@@ -97,17 +96,6 @@ public:
Core::IDocument *openFiles(const QStringList &fileNames, ICore::OpenFilesFlags flags);
- Core::ActionManager *actionManager() const;
- Core::MessageManager *messageManager() const;
- Core::EditorManager *editorManager() const;
- Core::ProgressManager *progressManager() const;
- Core::ScriptManager *scriptManager() const;
- Core::VariableManager *variableManager() const;
- Core::ModeManager *modeManager() const;
- Core::MimeDatabase *mimeDatabase() const;
- Core::HelpManager *helpManager() const;
-
- VcsManager *vcsManager() const;
QSettings *settings(QSettings::Scope scope) const;
inline SettingsDatabase *settingsDatabase() const { return m_settingsDatabase; }
virtual QPrinter *printer() const;
@@ -183,8 +171,7 @@ private:
ExternalToolManager *m_externalToolManager;
MessageManager *m_messageManager;
ProgressManagerPrivate *m_progressManager;
- ScriptManager *m_scriptManager;
- QScopedPointer<VariableManager> m_variableManager;
+ VariableManager *m_variableManager;
VcsManager *m_vcsManager;
StatusBarManager *m_statusBarManager;
ModeManager *m_modeManager;
diff --git a/src/plugins/coreplugin/manhattanstyle.cpp b/src/plugins/coreplugin/manhattanstyle.cpp
index a07dbac946..15fcbfc977 100644
--- a/src/plugins/coreplugin/manhattanstyle.cpp
+++ b/src/plugins/coreplugin/manhattanstyle.cpp
@@ -274,18 +274,16 @@ void ManhattanStyle::polish(QWidget *widget)
if (qobject_cast<QToolButton*>(widget)) {
widget->setAttribute(Qt::WA_Hover);
widget->setMaximumHeight(Utils::StyleHelper::navigationWidgetHeight() - 2);
- }
- else if (qobject_cast<QLineEdit*>(widget)) {
+ } else if (qobject_cast<QLineEdit*>(widget)) {
widget->setAttribute(Qt::WA_Hover);
widget->setMaximumHeight(Utils::StyleHelper::navigationWidgetHeight() - 2);
- }
- else if (qobject_cast<QLabel*>(widget))
+ } else if (qobject_cast<QLabel*>(widget)) {
widget->setPalette(panelPalette(widget->palette()));
- else if (widget->property("panelwidget_singlerow").toBool())
+ } else if (widget->property("panelwidget_singlerow").toBool()) {
widget->setFixedHeight(Utils::StyleHelper::navigationWidgetHeight());
- else if (qobject_cast<QStatusBar*>(widget))
+ } else if (qobject_cast<QStatusBar*>(widget)) {
widget->setFixedHeight(Utils::StyleHelper::navigationWidgetHeight() + 2);
- else if (qobject_cast<QComboBox*>(widget)) {
+ } else if (qobject_cast<QComboBox*>(widget)) {
widget->setMaximumHeight(Utils::StyleHelper::navigationWidgetHeight() - 2);
widget->setAttribute(Qt::WA_Hover);
}
diff --git a/src/plugins/coreplugin/messagemanager.cpp b/src/plugins/coreplugin/messagemanager.cpp
index b4c653eee9..770f51d621 100644
--- a/src/plugins/coreplugin/messagemanager.cpp
+++ b/src/plugins/coreplugin/messagemanager.cpp
@@ -34,12 +34,18 @@
using namespace Core;
-MessageManager *MessageManager::m_instance = 0;
+static MessageManager *m_instance = 0;
+Internal::MessageOutputWindow *m_messageOutputWindow = 0;
+
+QObject *MessageManager::instance()
+{
+ return m_instance;
+}
MessageManager::MessageManager()
- : m_messageOutputWindow(0)
{
m_instance = this;
+ m_messageOutputWindow = 0;
qRegisterMetaType<Core::MessageManager::PrintToOutputPaneFlags>();
}
@@ -49,7 +55,6 @@ MessageManager::~MessageManager()
ExtensionSystem::PluginManager::removeObject(m_messageOutputWindow);
delete m_messageOutputWindow;
}
-
m_instance = 0;
}
@@ -65,7 +70,12 @@ void MessageManager::showOutputPane()
m_messageOutputWindow->popup(IOutputPane::ModeSwitch);
}
-void MessageManager::printToOutputPane(const QString &text, PrintToOutputPaneFlags flags)
+void MessageManager::write(const QString &text)
+{
+ write(text, NoModeSwitch);
+}
+
+void MessageManager::write(const QString &text, PrintToOutputPaneFlags flags)
{
if (!m_messageOutputWindow)
return;
diff --git a/src/plugins/coreplugin/messagemanager.h b/src/plugins/coreplugin/messagemanager.h
index 3d45be07c7..b00e9962e1 100644
--- a/src/plugins/coreplugin/messagemanager.h
+++ b/src/plugins/coreplugin/messagemanager.h
@@ -38,40 +38,38 @@
namespace Core {
-namespace Internal {
-class MessageOutputWindow;
-}
+namespace Internal { class MainWindow; }
class CORE_EXPORT MessageManager : public QObject
{
Q_OBJECT
public:
- MessageManager();
- ~MessageManager();
+ static QObject *instance();
- void init();
+ static void showOutputPane();
- static MessageManager *instance() { return m_instance; }
-
- void showOutputPane();
enum PrintToOutputPaneFlag {
- NoModeSwitch = Core::IOutputPane::NoModeSwitch,
- ModeSwitch = Core::IOutputPane::ModeSwitch,
- WithFocus = Core::IOutputPane::WithFocus,
- EnsureSizeHint = Core::IOutputPane::EnsureSizeHint,
- Silent = 256,
- Flash = 512 };
+ NoModeSwitch = IOutputPane::NoModeSwitch,
+ ModeSwitch = IOutputPane::ModeSwitch,
+ WithFocus = IOutputPane::WithFocus,
+ EnsureSizeHint = IOutputPane::EnsureSizeHint,
+ Silent = 256,
+ Flash = 51
+ };
Q_DECLARE_FLAGS(PrintToOutputPaneFlags, PrintToOutputPaneFlag)
+ static void write(const QString &text); // imply NoModeSwitch
+
public slots:
- void printToOutputPane(const QString &text, Core::MessageManager::PrintToOutputPaneFlags flags);
+ static void write(const QString &text, Core::MessageManager::PrintToOutputPaneFlags flags);
private:
- Internal::MessageOutputWindow *m_messageOutputWindow;
-
- static MessageManager *m_instance;
+ MessageManager();
+ ~MessageManager();
+ static void init();
+ friend class Core::Internal::MainWindow;
};
} // namespace Core
diff --git a/src/plugins/coreplugin/mimedatabase.cpp b/src/plugins/coreplugin/mimedatabase.cpp
index de1643e541..142c270bb8 100644
--- a/src/plugins/coreplugin/mimedatabase.cpp
+++ b/src/plugins/coreplugin/mimedatabase.cpp
@@ -1044,7 +1044,7 @@ static bool addMagicMatchRule(const QXmlStreamAttributes &atts,
const MagicRuleMatcherPtr &ruleMatcher,
QString *errorMessage)
{
- const QString type = atts.value(QLatin1String(matchTypeAttributeC)).toString();
+ const QStringRef type = atts.value(QLatin1String(matchTypeAttributeC));
if (type != QLatin1String(matchStringTypeValueC) &&
type != QLatin1String(matchByteTypeValueC)) {
qWarning("%s: match type %s is not supported.", Q_FUNC_INFO, type.toUtf8().constData());
@@ -1106,25 +1106,25 @@ bool BaseMimeTypeParser::parse(QIODevice *dev, const QString &fileName, QString
break;
case ParseComment: {
// comments have locale attributes. We want the default, English one
- QString locale = atts.value(QLatin1String(localeAttributeC)).toString();
+ const QStringRef locale = atts.value(QLatin1String(localeAttributeC));
const QString comment = QCoreApplication::translate("MimeType", reader.readElementText().toLatin1());
if (locale.isEmpty())
data.comment = comment;
else
- data.localeComments.insert(locale, comment);
+ data.localeComments.insert(locale.toString(), comment);
}
break;
case ParseAlias: {
- const QString alias = atts.value(QLatin1String(mimeTypeAttributeC)).toString();
+ const QStringRef alias = atts.value(QLatin1String(mimeTypeAttributeC));
if (!alias.isEmpty())
- data.aliases.push_back(alias);
+ data.aliases.push_back(alias.toString());
}
break;
case ParseMagic: {
int priority = 0;
- const QString priorityS = atts.value(QLatin1String(priorityAttributeC)).toString();
+ const QStringRef priorityS = atts.value(QLatin1String(priorityAttributeC));
if (!priorityS.isEmpty()) {
- if (!parseNumber(priorityS, &priority, errorMessage))
+ if (!parseNumber(priorityS.toString(), &priority, errorMessage))
return false;
}
@@ -1278,7 +1278,6 @@ public:
void debug(QTextStream &str) const;
-private:
typedef QHash<QString, MimeMapEntry> TypeMimeTypeMap;
typedef QHash<QString, QString> AliasMap;
typedef QMultiHash<QString, QString> ParentChildrenMap;
@@ -1299,6 +1298,7 @@ private:
AliasMap m_aliasMap;
ParentChildrenMap m_parentChildrenMap;
int m_maxLevel;
+ QMutex m_mutex;
};
const QChar MimeDatabasePrivate::kSemiColon(QLatin1Char(';'));
@@ -1696,7 +1696,7 @@ QList<MimeType> MimeDatabasePrivate::readUserModifiedMimeTypes()
mimeType.setGlobPatterns(toGlobPatterns(patterns.split(kSemiColon)));
} else if (reader.name() == QLatin1String(matchTagC)) {
const QString &value = atts.value(matchValueAttribute).toString();
- const QString &type = atts.value(matchTypeAttribute).toString();
+ const QStringRef type = atts.value(matchTypeAttribute);
const QString &offset = atts.value(matchOffsetAttribute).toString();
QPair<int, int> range = MagicRule::fromOffset(offset);
const int priority = atts.value(priorityAttribute).toString().toInt();
@@ -1827,9 +1827,11 @@ void MimeDatabasePrivate::debug(QTextStream &str) const
str << "<MimeDatabase\n";
}
-MimeDatabase::MimeDatabase() :
- d(new MimeDatabasePrivate)
+static MimeDatabasePrivate *d;
+
+MimeDatabase::MimeDatabase()
{
+ d = new MimeDatabasePrivate;
}
MimeDatabase::~MimeDatabase()
@@ -1837,75 +1839,75 @@ MimeDatabase::~MimeDatabase()
delete d;
}
-MimeType MimeDatabase::findByType(const QString &typeOrAlias) const
+MimeType MimeDatabase::findByType(const QString &typeOrAlias)
{
- m_mutex.lock();
+ d->m_mutex.lock();
const MimeType rc = d->findByType(typeOrAlias);
- m_mutex.unlock();
+ d->m_mutex.unlock();
return rc;
}
-MimeType MimeDatabase::findByFileUnlocked(const QFileInfo &f) const
+MimeType MimeDatabase::findByFileUnlocked(const QFileInfo &f)
{
return d->findByFile(f);
}
-MimeType MimeDatabase::findByFile(const QFileInfo &f) const
+MimeType MimeDatabase::findByFile(const QFileInfo &f)
{
- m_mutex.lock();
+ d->m_mutex.lock();
const MimeType rc = findByFileUnlocked(f);
- m_mutex.unlock();
+ d->m_mutex.unlock();
return rc;
}
-MimeType MimeDatabase::findByData(const QByteArray &data) const
+MimeType MimeDatabase::findByData(const QByteArray &data)
{
- m_mutex.lock();
+ d->m_mutex.lock();
const MimeType rc = d->findByData(data);
- m_mutex.unlock();
+ d->m_mutex.unlock();
return rc;
}
bool MimeDatabase::addMimeType(const MimeType &mt)
{
- m_mutex.lock();
+ d->m_mutex.lock();
const bool rc = d->addMimeType(mt);
- m_mutex.unlock();
+ d->m_mutex.unlock();
return rc;
}
bool MimeDatabase::addMimeTypes(const QString &fileName, QString *errorMessage)
{
- m_mutex.lock();
+ d->m_mutex.lock();
const bool rc = d->addMimeTypes(fileName, errorMessage);
- m_mutex.unlock();
+ d->m_mutex.unlock();
return rc;
}
bool MimeDatabase::addMimeTypes(QIODevice *device, QString *errorMessage)
{
- m_mutex.lock();
+ d->m_mutex.lock();
const bool rc = d->addMimeTypes(device, errorMessage);
- m_mutex.unlock();
+ d->m_mutex.unlock();
return rc;
}
-QStringList MimeDatabase::suffixes() const
+QStringList MimeDatabase::suffixes()
{
- m_mutex.lock();
+ d->m_mutex.lock();
const QStringList rc = d->suffixes();
- m_mutex.unlock();
+ d->m_mutex.unlock();
return rc;
}
-QStringList MimeDatabase::filterStrings() const
+QStringList MimeDatabase::filterStrings()
{
- m_mutex.lock();
+ d->m_mutex.lock();
const QStringList rc = d->filterStrings();
- m_mutex.unlock();
+ d->m_mutex.unlock();
return rc;
}
-QString MimeDatabase::allFiltersString(QString *allFilesFilter) const
+QString MimeDatabase::allFiltersString(QString *allFilesFilter)
{
if (allFilesFilter)
allFilesFilter->clear();
@@ -1929,58 +1931,58 @@ QString MimeDatabase::allFiltersString(QString *allFilesFilter) const
return filters.join(QLatin1String(";;"));
}
-QList<MimeGlobPattern> MimeDatabase::globPatterns() const
+QList<MimeGlobPattern> MimeDatabase::globPatterns()
{
- m_mutex.lock();
+ d->m_mutex.lock();
const QList<MimeGlobPattern> rc = d->globPatterns();
- m_mutex.unlock();
+ d->m_mutex.unlock();
return rc;
}
void MimeDatabase::setGlobPatterns(const QString &typeOrAlias,
const QList<MimeGlobPattern> &globPatterns)
{
- m_mutex.lock();
+ d->m_mutex.lock();
d->setGlobPatterns(typeOrAlias, globPatterns);
- m_mutex.unlock();
+ d->m_mutex.unlock();
}
-MimeDatabase::IMagicMatcherList MimeDatabase::magicMatchers() const
+MimeDatabase::IMagicMatcherList MimeDatabase::magicMatchers()
{
- m_mutex.lock();
+ d->m_mutex.lock();
const IMagicMatcherList rc = d->magicMatchers();
- m_mutex.unlock();
+ d->m_mutex.unlock();
return rc;
}
void MimeDatabase::setMagicMatchers(const QString &typeOrAlias,
const IMagicMatcherList &matchers)
{
- m_mutex.lock();
+ d->m_mutex.lock();
d->setMagicMatchers(typeOrAlias, matchers);
- m_mutex.unlock();
+ d->m_mutex.unlock();
}
-QList<MimeType> MimeDatabase::mimeTypes() const
+QList<MimeType> MimeDatabase::mimeTypes()
{
- m_mutex.lock();
+ d->m_mutex.lock();
const QList<MimeType> &mimeTypes = d->mimeTypes();
- m_mutex.unlock();
+ d->m_mutex.unlock();
return mimeTypes;
}
void MimeDatabase::syncUserModifiedMimeTypes()
{
- m_mutex.lock();
+ d->m_mutex.lock();
d->syncUserModifiedMimeTypes();
- m_mutex.unlock();
+ d->m_mutex.unlock();
}
void MimeDatabase::clearUserModifiedMimeTypes()
{
- m_mutex.lock();
+ d->m_mutex.lock();
d->clearUserModifiedMimeTypes();
- m_mutex.unlock();
+ d->m_mutex.unlock();
}
QList<MimeType> MimeDatabase::readUserModifiedMimeTypes()
@@ -1993,14 +1995,14 @@ void MimeDatabase::writeUserModifiedMimeTypes(const QList<MimeType> &mimeTypes)
MimeDatabasePrivate::writeUserModifiedMimeTypes(mimeTypes);
}
-QString MimeDatabase::preferredSuffixByType(const QString &type) const
+QString MimeDatabase::preferredSuffixByType(const QString &type)
{
if (const MimeType mt = findByType(type))
return mt.preferredSuffix(); // already does Mutex locking
return QString();
}
-QString MimeDatabase::preferredSuffixByFile(const QFileInfo &f) const
+QString MimeDatabase::preferredSuffixByFile(const QFileInfo &f)
{
if (const MimeType mt = findByFile(f))
return mt.preferredSuffix(); // already does Mutex locking
@@ -2009,9 +2011,9 @@ QString MimeDatabase::preferredSuffixByFile(const QFileInfo &f) const
bool MimeDatabase::setPreferredSuffix(const QString &typeOrAlias, const QString &suffix)
{
- m_mutex.lock();
+ d->m_mutex.lock();
const bool rc = d->setPreferredSuffix(typeOrAlias, suffix);
- m_mutex.unlock();
+ d->m_mutex.unlock();
return rc;
}
@@ -2025,15 +2027,15 @@ QStringList MimeDatabase::fromGlobPatterns(const QList<MimeGlobPattern> &globPat
return MimeDatabasePrivate::fromGlobPatterns(globPatterns);
}
-QDebug operator<<(QDebug d, const MimeDatabase &mt)
-{
- QString s;
- {
- QTextStream str(&s);
- mt.d->debug(str);
- }
- d << s;
- return d;
-}
+//QDebug operator<<(QDebug d, const MimeDatabase &mt)
+//{
+// QString s;
+// {
+// QTextStream str(&s);
+// d->debug(str);
+// }
+// db << s;
+// return db;
+//}
} // namespace Core
diff --git a/src/plugins/coreplugin/mimedatabase.h b/src/plugins/coreplugin/mimedatabase.h
index b6086406fd..ead2ea8da6 100644
--- a/src/plugins/coreplugin/mimedatabase.h
+++ b/src/plugins/coreplugin/mimedatabase.h
@@ -52,6 +52,7 @@ class MimeDatabasePrivate;
namespace Internal {
class BaseMimeTypeParser;
class FileMatchContext;
+ class MainWindow;
}
class CORE_EXPORT IMagicMatcher
@@ -260,77 +261,56 @@ public:
typedef IMagicMatcher::IMagicMatcherList IMagicMatcherList;
typedef IMagicMatcher::IMagicMatcherSharedPointer IMagicMatcherSharedPointer;
- MimeDatabase();
- ~MimeDatabase();
-
- bool addMimeTypes(const QString &fileName, QString *errorMessage);
- bool addMimeTypes(QIODevice *device, QString *errorMessage);
- bool addMimeType(const MimeType &mt);
+ static bool addMimeTypes(const QString &fileName, QString *errorMessage);
+ static bool addMimeTypes(QIODevice *device, QString *errorMessage);
+ static bool addMimeType(const MimeType &mt);
// Returns a mime type or Null one if none found
- MimeType findByType(const QString &type) const;
+ static MimeType findByType(const QString &type);
// Returns a mime type or Null one if none found
- MimeType findByFile(const QFileInfo &f) const;
+ static MimeType findByFile(const QFileInfo &f);
// Returns a mime type or Null one if none found
- MimeType findByData(const QByteArray &data) const;
-
- // Convenience that mutex-locks the DB and calls a function
- // of the signature 'void f(const MimeType &, const QFileInfo &, const QString &)'
- // for each filename of a sequence. This avoids locking the DB for each
- // single file.
- template <class Iterator, typename Function>
- inline void findByFile(Iterator i1, const Iterator &i2, Function f) const;
+ static MimeType findByData(const QByteArray &data);
// Return all known suffixes
- QStringList suffixes() const;
- bool setPreferredSuffix(const QString &typeOrAlias, const QString &suffix);
- QString preferredSuffixByType(const QString &type) const;
- QString preferredSuffixByFile(const QFileInfo &f) const;
+ static QStringList suffixes();
+ static bool setPreferredSuffix(const QString &typeOrAlias, const QString &suffix);
+ static QString preferredSuffixByType(const QString &type);
+ static QString preferredSuffixByFile(const QFileInfo &f);
- QStringList filterStrings() const;
+ static QStringList filterStrings();
// Return a string with all the possible file filters, for use with file dialogs
- QString allFiltersString(QString *allFilesFilter = 0) const;
+ static QString allFiltersString(QString *allFilesFilter = 0);
- QList<MimeGlobPattern> globPatterns() const;
- void setGlobPatterns(const QString &typeOrAlias, const QList<MimeGlobPattern> &globPatterns);
+ static QList<MimeGlobPattern> globPatterns();
+ static void setGlobPatterns(const QString &typeOrAlias, const QList<MimeGlobPattern> &globPatterns);
- IMagicMatcherList magicMatchers() const;
- void setMagicMatchers(const QString &typeOrAlias, const IMagicMatcherList &matchers);
+ static IMagicMatcherList magicMatchers();
+ static void setMagicMatchers(const QString &typeOrAlias, const IMagicMatcherList &matchers);
- QList<MimeType> mimeTypes() const;
+ static QList<MimeType> mimeTypes();
// The mime types from the functions bellow are considered only in regard to
// their glob patterns and rule-based magic matchers.
- void syncUserModifiedMimeTypes();
+ static void syncUserModifiedMimeTypes();
static QList<MimeType> readUserModifiedMimeTypes();
static void writeUserModifiedMimeTypes(const QList<MimeType> &mimeTypes);
- void clearUserModifiedMimeTypes();
+ static void clearUserModifiedMimeTypes();
static QList<MimeGlobPattern> toGlobPatterns(const QStringList &patterns,
int weight = MimeGlobPattern::MaxWeight);
static QStringList fromGlobPatterns(const QList<MimeGlobPattern> &globPatterns);
- friend QDebug operator<<(QDebug d, const MimeDatabase &mt);
-
private:
- MimeType findByFileUnlocked(const QFileInfo &f) const;
+ MimeDatabase();
+ ~MimeDatabase();
- MimeDatabasePrivate *d;
- mutable QMutex m_mutex;
-};
+ static MimeType findByFileUnlocked(const QFileInfo &f);
-template <class Iterator, typename Function>
- void MimeDatabase::findByFile(Iterator i1, const Iterator &i2, Function f) const
-{
- m_mutex.lock();
- for ( ; i1 != i2; ++i1) {
- const QFileInfo fi(*i1);
- f(findByFileUnlocked(fi), fi, *i1);
- }
- m_mutex.unlock();
-}
+ friend class Core::Internal::MainWindow;
+};
} // namespace Core
diff --git a/src/plugins/coreplugin/mimetypesettings.cpp b/src/plugins/coreplugin/mimetypesettings.cpp
index 742e1a2db0..07315c389b 100644
--- a/src/plugins/coreplugin/mimetypesettings.cpp
+++ b/src/plugins/coreplugin/mimetypesettings.cpp
@@ -28,14 +28,14 @@
****************************************************************************/
#include "coreconstants.h"
-#include "editormanager.h"
#include "icore.h"
-#include "ieditorfactory.h"
-#include "iexternaleditor.h"
#include "mimedatabase.h"
#include "mimetypemagicdialog.h"
#include "mimetypesettings.h"
#include "ui_mimetypesettingspage.h"
+#include <coreplugin/editormanager/editormanager.h>
+#include <coreplugin/editormanager/ieditorfactory.h>
+#include <coreplugin/editormanager/iexternaleditor.h>
#include <QAbstractTableModel>
#include <QCoreApplication>
@@ -126,10 +126,10 @@ QVariant MimeTypeSettingsModel::data(const QModelIndex &modelIndex, int role) co
void MimeTypeSettingsModel::load()
{
- m_mimeTypes = ICore::mimeDatabase()->mimeTypes();
+ m_mimeTypes = MimeDatabase::mimeTypes();
qSort(m_mimeTypes.begin(), m_mimeTypes.end(), MimeTypeComp());
m_knownPatterns = QSet<QString>::fromList(
- MimeDatabase::fromGlobPatterns(ICore::mimeDatabase()->globPatterns()));
+ MimeDatabase::fromGlobPatterns(MimeDatabase::globPatterns()));
foreach (const MimeType &mimeType, m_mimeTypes) {
QString value;
@@ -240,7 +240,6 @@ public:
static const QChar kSemiColon;
QString m_keywords;
- MimeDatabase *m_mimeDatabase;
MimeTypeSettingsModel *m_model;
QSortFilterProxyModel *m_filterModel;
int m_mimeForPatternSync;
@@ -255,8 +254,7 @@ public:
const QChar MimeTypeSettingsPrivate::kSemiColon(QLatin1Char(';'));
MimeTypeSettingsPrivate::MimeTypeSettingsPrivate()
- : m_mimeDatabase(ICore::mimeDatabase())
- , m_model(new MimeTypeSettingsModel(this))
+ : m_model(new MimeTypeSettingsModel(this))
, m_filterModel(new QSortFilterProxyModel(this))
, m_mimeForPatternSync(-1)
, m_mimeForMagicSync(-1)
@@ -529,15 +527,14 @@ void MimeTypeSettingsPrivate::updateMimeDatabase()
m_modifiedMimeTypes.erase(std::unique(m_modifiedMimeTypes.begin(), m_modifiedMimeTypes.end()),
m_modifiedMimeTypes.end());
- MimeDatabase *db = ICore::mimeDatabase();
QList<MimeType> allModified;
foreach (int index, m_modifiedMimeTypes) {
const MimeType &mimeType = m_model->m_mimeTypes.at(index);
- db->setGlobPatterns(mimeType.type(), mimeType.globPatterns());
- db->setMagicMatchers(mimeType.type(), mimeType.magicMatchers());
+ MimeDatabase::setGlobPatterns(mimeType.type(), mimeType.globPatterns());
+ MimeDatabase::setMagicMatchers(mimeType.type(), mimeType.magicMatchers());
allModified.append(mimeType);
}
- db->writeUserModifiedMimeTypes(allModified);
+ MimeDatabase::writeUserModifiedMimeTypes(allModified);
}
void MimeTypeSettingsPrivate::resetState()
@@ -623,7 +620,7 @@ void MimeTypeSettings::finish()
{
if (d->m_persist) {
if (d->m_reset)
- ICore::mimeDatabase()->clearUserModifiedMimeTypes();
+ MimeDatabase::clearUserModifiedMimeTypes();
else
d->updateMimeDatabase();
}
diff --git a/src/plugins/coreplugin/mimetypesettings.h b/src/plugins/coreplugin/mimetypesettings.h
index 485068167b..19908aeeb6 100644
--- a/src/plugins/coreplugin/mimetypesettings.h
+++ b/src/plugins/coreplugin/mimetypesettings.h
@@ -30,7 +30,7 @@
#ifndef MIMETYPESETTINGSPAGE_H
#define MIMETYPESETTINGSPAGE_H
-#include "ioptionspage.h"
+#include <coreplugin/dialogs/ioptionspage.h>
namespace Core {
namespace Internal {
diff --git a/src/plugins/coreplugin/modemanager.cpp b/src/plugins/coreplugin/modemanager.cpp
index b278f08c48..dbd66952d7 100644
--- a/src/plugins/coreplugin/modemanager.cpp
+++ b/src/plugins/coreplugin/modemanager.cpp
@@ -188,7 +188,7 @@ void ModeManager::objectAdded(QObject *obj)
Command *cmd = ActionManager::registerShortcut(shortcut, shortcutId, Context(Constants::C_GLOBAL));
d->m_modeShortcuts.insert(index, cmd);
- connect(cmd, SIGNAL(keySequenceChanged()), this, SLOT(updateModeToolTip()));
+ connect(cmd, SIGNAL(keySequenceChanged()), m_instance, SLOT(updateModeToolTip()));
for (int i = 0; i < d->m_modeShortcuts.size(); ++i) {
Command *currentCmd = d->m_modeShortcuts.at(i);
// we need this hack with currentlyHasDefaultSequence
@@ -205,7 +205,7 @@ void ModeManager::objectAdded(QObject *obj)
d->m_signalMapper->setMapping(shortcut, mode->id().uniqueIdentifier());
connect(shortcut, SIGNAL(activated()), d->m_signalMapper, SLOT(map()));
connect(mode, SIGNAL(enabledStateChanged(bool)),
- this, SLOT(enabledStateChanged()));
+ m_instance, SLOT(enabledStateChanged()));
}
void ModeManager::updateModeToolTip()
@@ -336,7 +336,7 @@ bool ModeManager::isModeSelectorVisible()
return d->m_modeSelectorVisible;
}
-ModeManager *ModeManager::instance()
+QObject *ModeManager::instance()
{
return m_instance;
}
diff --git a/src/plugins/coreplugin/modemanager.h b/src/plugins/coreplugin/modemanager.h
index f053f98d9f..2577505f97 100644
--- a/src/plugins/coreplugin/modemanager.h
+++ b/src/plugins/coreplugin/modemanager.h
@@ -52,11 +52,7 @@ class CORE_EXPORT ModeManager : public QObject
Q_OBJECT
public:
- explicit ModeManager(Internal::MainWindow *mainWindow, Internal::FancyTabWidget *modeStack);
- virtual ~ModeManager();
-
- static void init();
- static ModeManager *instance();
+ static QObject *instance();
static IMode *currentMode();
static IMode *mode(Id id);
@@ -70,7 +66,7 @@ public:
static bool isModeSelectorVisible();
public slots:
- void setModeSelectorVisible(bool visible);
+ static void setModeSelectorVisible(bool visible);
signals:
void currentModeAboutToChange(Core::IMode *mode);
@@ -88,6 +84,14 @@ private slots:
void enabledStateChanged();
void handleStartup();
void handleShutdown();
+
+private:
+ explicit ModeManager(Internal::MainWindow *mainWindow, Internal::FancyTabWidget *modeStack);
+ ~ModeManager();
+
+ static void init();
+
+ friend class Core::Internal::MainWindow;
};
} // namespace Core
diff --git a/src/plugins/coreplugin/navigationwidget.cpp b/src/plugins/coreplugin/navigationwidget.cpp
index d619077181..180e42dc10 100644
--- a/src/plugins/coreplugin/navigationwidget.cpp
+++ b/src/plugins/coreplugin/navigationwidget.cpp
@@ -348,7 +348,7 @@ void NavigationWidget::restoreSettings(QSettings *settings)
if (d->m_subWidgets.isEmpty())
// Make sure we have at least the projects widget
- insertSubItem(0, qMax(0, factoryIndex(Id("Projects"))));
+ insertSubItem(0, qMax(0, factoryIndex("Projects")));
setShown(settings->value(QLatin1String("Navigation/Visible"), true).toBool());
diff --git a/src/plugins/coreplugin/outputpane.cpp b/src/plugins/coreplugin/outputpane.cpp
index e82d1b255a..0002229bf1 100644
--- a/src/plugins/coreplugin/outputpane.cpp
+++ b/src/plugins/coreplugin/outputpane.cpp
@@ -136,8 +136,10 @@ bool OutputPanePlaceHolder::isMaximized() const
return Internal::OutputPaneManager::instance()->isMaximized();
}
-void OutputPanePlaceHolder::ensureSizeHintAsMinimum()
+void OutputPanePlaceHolder::setDefaultHeight(int height)
{
+ if (height == 0)
+ return;
if (!d->m_splitter)
return;
int idx = d->m_splitter->indexOf(this);
@@ -146,19 +148,24 @@ void OutputPanePlaceHolder::ensureSizeHintAsMinimum()
d->m_splitter->refresh();
QList<int> sizes = d->m_splitter->sizes();
- Internal::OutputPaneManager *om = Internal::OutputPaneManager::instance();
- int minimum = (d->m_splitter->orientation() == Qt::Vertical
- ? om->sizeHint().height() : om->sizeHint().width());
- int difference = minimum - sizes.at(idx);
+ int difference = height - sizes.at(idx);
if (difference <= 0) // is already larger
return;
for (int i = 0; i < sizes.count(); ++i) {
sizes[i] += difference / (sizes.count()-1);
}
- sizes[idx] = minimum;
+ sizes[idx] = height;
d->m_splitter->setSizes(sizes);
}
+void OutputPanePlaceHolder::ensureSizeHintAsMinimum()
+{
+ Internal::OutputPaneManager *om = Internal::OutputPaneManager::instance();
+ int minimum = (d->m_splitter->orientation() == Qt::Vertical
+ ? om->sizeHint().height() : om->sizeHint().width());
+ setDefaultHeight(minimum);
+}
+
void OutputPanePlaceHolder::unmaximize()
{
if (Internal::OutputPaneManager::instance()->isMaximized())
diff --git a/src/plugins/coreplugin/outputpane.h b/src/plugins/coreplugin/outputpane.h
index f908e626d2..ddeef9435e 100644
--- a/src/plugins/coreplugin/outputpane.h
+++ b/src/plugins/coreplugin/outputpane.h
@@ -61,6 +61,7 @@ public:
void unmaximize();
bool isMaximized() const;
+ void setDefaultHeight(int height);
void ensureSizeHintAsMinimum();
private slots:
diff --git a/src/plugins/coreplugin/outputpanemanager.cpp b/src/plugins/coreplugin/outputpanemanager.cpp
index cd105414ca..a34149c0c4 100644
--- a/src/plugins/coreplugin/outputpanemanager.cpp
+++ b/src/plugins/coreplugin/outputpanemanager.cpp
@@ -242,7 +242,7 @@ void OutputPaneManager::init()
const int n = m_panes.size();
int shortcutNumber = 1;
- const Id baseId = Id("QtCreator.Pane.");
+ const Id baseId = "QtCreator.Pane.";
for (int i = 0; i != n; ++i) {
IOutputPane *outPane = m_panes.at(i);
const int idx = m_outputWidgetPane->addWidget(outPane->outputWidget(this));
@@ -473,6 +473,8 @@ void OutputPaneManager::showPage(int idx, int flags)
}
if (ph) {
+ QSettings *settings = ICore::settings();
+ int height = settings->value(QLatin1String("OutputPanePlaceHolder/Height"), 0).toInt();
// make the page visible
ph->setVisible(true);
ensurePageVisible(idx);
@@ -483,6 +485,7 @@ void OutputPaneManager::showPage(int idx, int flags)
ICore::raiseWindow(m_outputWidgetPane);
}
+ ph->setDefaultHeight(height);
if (flags & IOutputPane::EnsureSizeHint)
ph->ensureSizeHintAsMinimum();
} else {
@@ -569,6 +572,12 @@ void OutputPaneManager::saveSettings() const
settings->setValue(QLatin1String(outputPaneVisibleKeyC), m_buttons.at(i)->isVisible());
}
settings->endArray();
+ OutputPanePlaceHolder *ph = OutputPanePlaceHolder::getCurrent();
+ if (ph) {
+ int height = ph->height();
+ if (height)
+ settings->setValue(QLatin1String("OutputPanePlaceHolder/Height"), height);
+ }
}
void OutputPaneManager::clearPage()
diff --git a/src/plugins/coreplugin/outputwindow.cpp b/src/plugins/coreplugin/outputwindow.cpp
index 2c5499571e..bdd82784b1 100644
--- a/src/plugins/coreplugin/outputwindow.cpp
+++ b/src/plugins/coreplugin/outputwindow.cpp
@@ -33,6 +33,8 @@
#include "coreconstants.h"
#include "icore.h"
+#include <utils/synchronousprocess.h>
+
#include <QAction>
#include <QScrollBar>
@@ -175,7 +177,7 @@ void OutputWindow::showEvent(QShowEvent *e)
m_scrollToBottom = false;
}
-QString OutputWindow::doNewlineEnfocement(const QString &out)
+QString OutputWindow::doNewlineEnforcement(const QString &out)
{
m_scrollToBottom = true;
QString s = out;
@@ -200,14 +202,13 @@ void OutputWindow::setMaxLineCount(int count)
void OutputWindow::appendMessage(const QString &output, OutputFormat format)
{
- QString out = output;
- out.remove(QLatin1Char('\r'));
+ const QString out = Utils::SynchronousProcess::normalizeNewlines(output);
setMaximumBlockCount(m_maxLineCount);
const bool atBottom = isScrollbarAtBottom();
if (format == ErrorMessageFormat || format == NormalMessageFormat) {
- m_formatter->appendMessage(doNewlineEnfocement(out), format);
+ m_formatter->appendMessage(doNewlineEnforcement(out), format);
} else {
@@ -239,7 +240,7 @@ void OutputWindow::appendMessage(const QString &output, OutputFormat format)
m_formatter->appendMessage(QLatin1Char('\n') + s, format);
}
} else {
- m_formatter->appendMessage(doNewlineEnfocement(out), format);
+ m_formatter->appendMessage(doNewlineEnforcement(out), format);
}
}
@@ -251,20 +252,19 @@ void OutputWindow::appendMessage(const QString &output, OutputFormat format)
// TODO rename
void OutputWindow::appendText(const QString &textIn, const QTextCharFormat &format)
{
- QString text = textIn;
- text.remove(QLatin1Char('\r'));
+ const QString text = Utils::SynchronousProcess::normalizeNewlines(textIn);
if (m_maxLineCount > 0 && document()->blockCount() >= m_maxLineCount)
return;
const bool atBottom = isScrollbarAtBottom();
QTextCursor cursor = QTextCursor(document());
cursor.movePosition(QTextCursor::End);
cursor.beginEditBlock();
- cursor.insertText(doNewlineEnfocement(text), format);
+ cursor.insertText(doNewlineEnforcement(text), format);
if (m_maxLineCount > 0 && document()->blockCount() >= m_maxLineCount) {
QTextCharFormat tmp;
tmp.setFontWeight(QFont::Bold);
- cursor.insertText(doNewlineEnfocement(tr("Additional output omitted\n")), tmp);
+ cursor.insertText(doNewlineEnforcement(tr("Additional output omitted\n")), tmp);
}
cursor.endEditBlock();
diff --git a/src/plugins/coreplugin/outputwindow.h b/src/plugins/coreplugin/outputwindow.h
index 70a033d377..20d500c633 100644
--- a/src/plugins/coreplugin/outputwindow.h
+++ b/src/plugins/coreplugin/outputwindow.h
@@ -80,7 +80,7 @@ protected:
private:
void enableUndoRedo();
- QString doNewlineEnfocement(const QString &out);
+ QString doNewlineEnforcement(const QString &out);
Core::IContext *m_outputWindowContext;
Utils::OutputFormatter *m_formatter;
diff --git a/src/plugins/coreplugin/plugintestutils.cpp b/src/plugins/coreplugin/plugintestutils.cpp
index d94f606da1..03fd20999d 100644
--- a/src/plugins/coreplugin/plugintestutils.cpp
+++ b/src/plugins/coreplugin/plugintestutils.cpp
@@ -37,7 +37,7 @@
void Core::Tests::closeAndDeleteEditors(QList<IEditor *> editorsToClose)
{
- EditorManager::instance()->closeEditors(editorsToClose, /*askAboutModifiedEditors=*/ false);
+ EditorManager::closeEditors(editorsToClose, /*askAboutModifiedEditors=*/ false);
// The editors are going to be deleted by the event loop (deleteLater()),
// but for tests we need them deleted now.
foreach (Core::IEditor *editor, editorsToClose)
diff --git a/src/plugins/coreplugin/progressmanager/futureprogress.cpp b/src/plugins/coreplugin/progressmanager/futureprogress.cpp
index da6a6a1dcd..84bc025e2f 100644
--- a/src/plugins/coreplugin/progressmanager/futureprogress.cpp
+++ b/src/plugins/coreplugin/progressmanager/futureprogress.cpp
@@ -66,7 +66,7 @@ public:
QWidget *m_widget;
QHBoxLayout *m_widgetLayout;
QWidget *m_statusBarWidget;
- QString m_type;
+ Id m_type;
FutureProgress::KeepOnFinishType m_keep;
bool m_waitingForUserInteraction;
FutureProgress *m_q;
@@ -304,12 +304,12 @@ bool FutureProgress::hasError() const
return d->m_progress->hasError();
}
-void FutureProgress::setType(const QString &type)
+void FutureProgress::setType(Id type)
{
d->m_type = type;
}
-QString FutureProgress::type() const
+Id FutureProgress::type() const
{
return d->m_type;
}
diff --git a/src/plugins/coreplugin/progressmanager/futureprogress.h b/src/plugins/coreplugin/progressmanager/futureprogress.h
index 4cf58b203a..b4577d876f 100644
--- a/src/plugins/coreplugin/progressmanager/futureprogress.h
+++ b/src/plugins/coreplugin/progressmanager/futureprogress.h
@@ -31,6 +31,7 @@
#define FUTUREPROGRESS_H
#include <coreplugin/core_global.h>
+#include <coreplugin/id.h>
#include <QString>
#include <QFuture>
@@ -60,8 +61,8 @@ public:
void setTitle(const QString &title);
QString title() const;
- void setType(const QString &type);
- QString type() const;
+ void setType(Id type);
+ Id type() const;
void setKeepOnFinish(KeepOnFinishType keepType);
bool keepOnFinish() const;
diff --git a/src/plugins/coreplugin/progressmanager/progressmanager.cpp b/src/plugins/coreplugin/progressmanager/progressmanager.cpp
index fc15be7944..361f96a875 100644
--- a/src/plugins/coreplugin/progressmanager/progressmanager.cpp
+++ b/src/plugins/coreplugin/progressmanager/progressmanager.cpp
@@ -245,7 +245,7 @@ using namespace Core::Internal;
*/
/*!
- \fn void Core::ProgressManager::cancelTasks(const QString &type)
+ \fn void Core::ProgressManager::cancelTasks(Core::Id type)
Schedules a cancel for all running tasks of the given \a type.
Please note that the cancel functionality depends on the
@@ -254,20 +254,19 @@ using namespace Core::Internal;
*/
/*!
- \fn void Core::ProgressManager::taskStarted(const QString &type)
+ \fn void Core::ProgressManager::taskStarted(Core::Id type)
Sent whenever a task of a given \a type is started.
*/
/*!
- \fn void Core::ProgressManager::allTasksFinished(const QString &type)
+ \fn void Core::ProgressManager::allTasksFinished(Core::Id type)
Sent when all tasks of a \a type have finished.
*/
-ProgressManagerPrivate::ProgressManagerPrivate(QObject *parent)
- : ProgressManager(parent),
- m_applicationTask(0),
+ProgressManagerPrivate::ProgressManagerPrivate()
+ : m_applicationTask(0),
m_currentStatusDetailsWidget(0),
m_opacityEffect(new QGraphicsOpacityEffect(this)),
m_progressViewPinned(false),
@@ -335,7 +334,7 @@ void ProgressManagerPrivate::init()
p.fill(Qt::transparent);
toggleProgressView->setIcon(QIcon(p));
Command *cmd = ActionManager::registerAction(toggleProgressView,
- Id("QtCreator.ToggleProgressDetails"),
+ "QtCreator.ToggleProgressDetails",
Context(Constants::C_GLOBAL));
cmd->setDefaultKeySequence(QKeySequence(Utils::HostOsInfo::isMacHost()
? tr("Ctrl+Shift+0")
@@ -348,10 +347,10 @@ void ProgressManagerPrivate::init()
initInternal();
}
-void ProgressManagerPrivate::cancelTasks(const QString &type)
+void ProgressManagerPrivate::doCancelTasks(Id type)
{
bool found = false;
- QMap<QFutureWatcher<void> *, QString>::iterator task = m_runningTasks.begin();
+ QMap<QFutureWatcher<void> *, Id>::iterator task = m_runningTasks.begin();
while (task != m_runningTasks.end()) {
if (task.value() != type) {
++task;
@@ -399,7 +398,7 @@ bool ProgressManagerPrivate::eventFilter(QObject *obj, QEvent *event)
void ProgressManagerPrivate::cancelAllRunningTasks()
{
- QMap<QFutureWatcher<void> *, QString>::const_iterator task = m_runningTasks.constBegin();
+ QMap<QFutureWatcher<void> *, Id>::const_iterator task = m_runningTasks.constBegin();
while (task != m_runningTasks.constEnd()) {
disconnect(task.key(), SIGNAL(finished()), this, SLOT(taskFinished()));
if (m_applicationTask == task.key())
@@ -412,8 +411,8 @@ void ProgressManagerPrivate::cancelAllRunningTasks()
updateSummaryProgressBar();
}
-FutureProgress *ProgressManagerPrivate::addTask(const QFuture<void> &future, const QString &title,
- const QString &type, ProgressFlags flags)
+FutureProgress *ProgressManagerPrivate::doAddTask(const QFuture<void> &future, const QString &title,
+ Id type, ProgressFlags flags)
{
// watch
QFutureWatcher<void> *watcher = new QFutureWatcher<void>();
@@ -474,7 +473,7 @@ void ProgressManagerPrivate::taskFinished()
QFutureWatcher<void> *task = static_cast<QFutureWatcher<void> *>(taskObject);
if (m_applicationTask == task)
disconnectApplicationTask();
- QString type = m_runningTasks.value(task);
+ Id type = m_runningTasks.value(task);
m_runningTasks.remove(task);
delete task;
updateSummaryProgressBar();
@@ -507,7 +506,7 @@ void ProgressManagerPrivate::updateSummaryProgressBar()
stopFadeOfSummaryProgress();
m_summaryProgressBar->setFinished(false);
- QMapIterator<QFutureWatcher<void> *, QString> it(m_runningTasks);
+ QMapIterator<QFutureWatcher<void> *, Id> it(m_runningTasks);
static const int TASK_RANGE = 100;
int value = 0;
while (it.hasNext()) {
@@ -564,12 +563,12 @@ void ProgressManagerPrivate::slotRemoveTask()
{
FutureProgress *progress = qobject_cast<FutureProgress *>(sender());
QTC_ASSERT(progress, return);
- QString type = progress->type();
+ Id type = progress->type();
removeTask(progress);
removeOldTasks(type, true);
}
-void ProgressManagerPrivate::removeOldTasks(const QString &type, bool keepOne)
+void ProgressManagerPrivate::removeOldTasks(const Id type, bool keepOne)
{
bool firstFound = !keepOne; // start with false if we want to keep one
QList<FutureProgress *>::iterator i = m_taskList.end();
@@ -601,7 +600,7 @@ void ProgressManagerPrivate::removeOneOldTask()
}
// no ended process, look for a task type with multiple running tasks and remove the oldest one
for (QList<FutureProgress *>::iterator i = m_taskList.begin(); i != m_taskList.end(); ++i) {
- QString type = (*i)->type();
+ Id type = (*i)->type();
int taskCount = 0;
foreach (FutureProgress *p, m_taskList)
@@ -717,3 +716,37 @@ void ToggleButton::paintEvent(QPaintEvent *event)
arrowOpt.rect = QRect(rect().center().x() - 3, rect().center().y() - 6, 9, 9);
s->drawPrimitive(QStyle::PE_IndicatorArrowUp, &arrowOpt, &p, this);
}
+
+
+static ProgressManager *m_instance = 0;
+
+ProgressManager::ProgressManager()
+{
+ m_instance = this;
+}
+
+ProgressManager::~ProgressManager()
+{
+ m_instance = 0;
+}
+
+QObject *ProgressManager::instance()
+{
+ return m_instance;
+}
+
+FutureProgress *ProgressManager::addTask(const QFuture<void> &future, const QString &title, Id type, ProgressFlags flags)
+{
+ return m_instance->doAddTask(future, title, type, flags);
+}
+
+void ProgressManager::setApplicationLabel(const QString &text)
+{
+ m_instance->doSetApplicationLabel(text);
+}
+
+void ProgressManager::cancelTasks(const Id type)
+{
+ if (m_instance)
+ m_instance->doCancelTasks(type);
+}
diff --git a/src/plugins/coreplugin/progressmanager/progressmanager.h b/src/plugins/coreplugin/progressmanager/progressmanager.h
index cd90cd5ce2..ed45d53870 100644
--- a/src/plugins/coreplugin/progressmanager/progressmanager.h
+++ b/src/plugins/coreplugin/progressmanager/progressmanager.h
@@ -31,6 +31,7 @@
#define PROGRESSMANAGER_H
#include <coreplugin/core_global.h>
+#include <coreplugin/id.h>
#include <QObject>
#include <QFuture>
@@ -38,6 +39,8 @@
namespace Core {
class FutureProgress;
+namespace Internal { class ProgressManagerPrivate; }
+
class CORE_EXPORT ProgressManager : public QObject
{
Q_OBJECT
@@ -48,19 +51,30 @@ public:
};
Q_DECLARE_FLAGS(ProgressFlags, ProgressFlag)
- ProgressManager(QObject *parent = 0) : QObject(parent) {}
- virtual ~ProgressManager() {}
+ static QObject *instance();
- virtual FutureProgress *addTask(const QFuture<void> &future, const QString &title,
- const QString &type, ProgressFlags flags = 0) = 0;
- virtual void setApplicationLabel(const QString &text) = 0;
+ static FutureProgress *addTask(const QFuture<void> &future, const QString &title,
+ Core::Id type, ProgressFlags flags = 0);
+ static void setApplicationLabel(const QString &text);
public slots:
- virtual void cancelTasks(const QString &type) = 0;
+ static void cancelTasks(const Core::Id type);
signals:
- void taskStarted(const QString &type);
- void allTasksFinished(const QString &type);
+ void taskStarted(Core::Id type);
+ void allTasksFinished(Core::Id type);
+
+protected:
+ virtual void doCancelTasks(Core::Id type) = 0;
+ virtual FutureProgress *doAddTask(const QFuture<void> &future, const QString &title,
+ Core::Id type, ProgressFlags flags = 0) = 0;
+ virtual void doSetApplicationLabel(const QString &text) = 0;
+
+private:
+ ProgressManager();
+ ~ProgressManager();
+
+ friend class Core::Internal::ProgressManagerPrivate;
};
} // namespace Core
diff --git a/src/plugins/coreplugin/progressmanager/progressmanager_mac.mm b/src/plugins/coreplugin/progressmanager/progressmanager_mac.mm
index a511fc8d70..9649cdc370 100644
--- a/src/plugins/coreplugin/progressmanager/progressmanager_mac.mm
+++ b/src/plugins/coreplugin/progressmanager/progressmanager_mac.mm
@@ -125,7 +125,7 @@ static ApplicationProgressView *sharedProgressView = nil;
@end
-void Core::Internal::ProgressManagerPrivate::setApplicationLabel(const QString &text)
+void Core::Internal::ProgressManagerPrivate::doSetApplicationLabel(const QString &text)
{
NSString *cocoaString = [[NSString alloc] initWithUTF8String:text.toUtf8().constData()];
[[NSApp dockTile] setBadgeLabel:cocoaString];
diff --git a/src/plugins/coreplugin/progressmanager/progressmanager_p.h b/src/plugins/coreplugin/progressmanager/progressmanager_p.h
index ac99df1033..2445220be4 100644
--- a/src/plugins/coreplugin/progressmanager/progressmanager_p.h
+++ b/src/plugins/coreplugin/progressmanager/progressmanager_p.h
@@ -53,19 +53,19 @@ class ProgressManagerPrivate : public Core::ProgressManager
{
Q_OBJECT
public:
- ProgressManagerPrivate(QObject *parent = 0);
+ ProgressManagerPrivate();
~ProgressManagerPrivate();
void init();
void cleanup();
- FutureProgress *addTask(const QFuture<void> &future, const QString &title, const QString &type,
+ FutureProgress *doAddTask(const QFuture<void> &future, const QString &title, Id type,
ProgressFlags flags);
- void setApplicationLabel(const QString &text);
+ void doSetApplicationLabel(const QString &text);
ProgressView *progressView();
public slots:
- void cancelTasks(const QString &type);
+ void doCancelTasks(Core::Id type);
protected:
bool eventFilter(QObject *obj, QEvent *event);
@@ -94,14 +94,14 @@ private:
bool hasError() const;
bool isLastFading() const;
- void removeOldTasks(const QString &type, bool keepOne = false);
+ void removeOldTasks(Id type, bool keepOne = false);
void removeOneOldTask();
void removeTask(FutureProgress *task);
void deleteTask(FutureProgress *task);
QPointer<ProgressView> m_progressView;
QList<FutureProgress *> m_taskList;
- QMap<QFutureWatcher<void> *, QString> m_runningTasks;
+ QMap<QFutureWatcher<void> *, Id> m_runningTasks;
QFutureWatcher<void> *m_applicationTask;
Core::StatusBarWidget *m_statusBarWidgetContainer;
QWidget *m_statusBarWidget;
diff --git a/src/plugins/coreplugin/progressmanager/progressmanager_win.cpp b/src/plugins/coreplugin/progressmanager/progressmanager_win.cpp
index 05a36d88fa..39ad2439de 100644
--- a/src/plugins/coreplugin/progressmanager/progressmanager_win.cpp
+++ b/src/plugins/coreplugin/progressmanager/progressmanager_win.cpp
@@ -113,7 +113,7 @@ void Core::Internal::ProgressManagerPrivate::cleanup()
}
-void Core::Internal::ProgressManagerPrivate::setApplicationLabel(const QString &text)
+void Core::Internal::ProgressManagerPrivate::doSetApplicationLabel(const QString &text)
{
if (!pITask)
return;
@@ -174,7 +174,7 @@ void Core::Internal::ProgressManagerPrivate::cleanup()
{
}
-void Core::Internal::ProgressManagerPrivate::setApplicationLabel(const QString &text)
+void Core::Internal::ProgressManagerPrivate::doSetApplicationLabel(const QString &text)
{
Q_UNUSED(text)
}
diff --git a/src/plugins/coreplugin/progressmanager/progressmanager_x11.cpp b/src/plugins/coreplugin/progressmanager/progressmanager_x11.cpp
index 2650f5d1cf..22f8ad6227 100644
--- a/src/plugins/coreplugin/progressmanager/progressmanager_x11.cpp
+++ b/src/plugins/coreplugin/progressmanager/progressmanager_x11.cpp
@@ -37,7 +37,7 @@ void Core::Internal::ProgressManagerPrivate::cleanup()
{
}
-void Core::Internal::ProgressManagerPrivate::setApplicationLabel(const QString &text)
+void Core::Internal::ProgressManagerPrivate::doSetApplicationLabel(const QString &text)
{
Q_UNUSED(text)
}
diff --git a/src/plugins/coreplugin/progressmanager/progressview.cpp b/src/plugins/coreplugin/progressmanager/progressview.cpp
index 212bcc60d4..5c843dda11 100644
--- a/src/plugins/coreplugin/progressmanager/progressview.cpp
+++ b/src/plugins/coreplugin/progressmanager/progressview.cpp
@@ -35,8 +35,6 @@
using namespace Core;
using namespace Core::Internal;
-static const int PROGRESS_WIDTH = 100;
-
ProgressView::ProgressView(QWidget *parent)
: QWidget(parent), m_referenceWidget(0), m_hovered(false)
{
diff --git a/src/plugins/coreplugin/scriptmanager/metatypedeclarations.h b/src/plugins/coreplugin/scriptmanager/metatypedeclarations.h
deleted file mode 100644
index 9be89d7b63..0000000000
--- a/src/plugins/coreplugin/scriptmanager/metatypedeclarations.h
+++ /dev/null
@@ -1,61 +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 METATYPEDECLARATIONS_H
-#define METATYPEDECLARATIONS_H
-
-#include <coreplugin/messagemanager.h>
-#include <coreplugin/documentmanager.h>
-#include <coreplugin/idocument.h>
-#include <coreplugin/editormanager/ieditor.h>
-#include <coreplugin/editormanager/editormanager.h>
-#include <coreplugin/icore.h>
-
-#include <QList>
-#include <QMetaType>
-
-QT_BEGIN_NAMESPACE
-class QMainWindow;
-class QStatusBar;
-class QSettings;
-QT_END_NAMESPACE
-
-Q_DECLARE_METATYPE(Core::MessageManager*)
-Q_DECLARE_METATYPE(Core::DocumentManager*)
-Q_DECLARE_METATYPE(Core::IDocument*)
-Q_DECLARE_METATYPE(QList<Core::IDocument*>)
-Q_DECLARE_METATYPE(QList<Core::IEditor*>)
-Q_DECLARE_METATYPE(Core::EditorManager*)
-Q_DECLARE_METATYPE(Core::ICore*)
-
-Q_DECLARE_METATYPE(QMainWindow*)
-Q_DECLARE_METATYPE(QStatusBar*)
-Q_DECLARE_METATYPE(QSettings*)
-
-#endif // METATYPEDECLARATIONS_H
diff --git a/src/plugins/coreplugin/scriptmanager/scriptmanager.cpp b/src/plugins/coreplugin/scriptmanager/scriptmanager.cpp
deleted file mode 100644
index ad32725e53..0000000000
--- a/src/plugins/coreplugin/scriptmanager/scriptmanager.cpp
+++ /dev/null
@@ -1,280 +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 "scriptmanager_p.h"
-#include "metatypedeclarations.h"
-
-#include <utils/qtcassert.h>
-#include <interface_wrap_helpers.h>
-#include <wrap_helpers.h>
-
-#include <limits.h>
-
-#include <QDebug>
-#include <QSettings>
-#include <QMessageBox>
-#include <QInputDialog>
-#include <QFileDialog>
-#include <QMainWindow>
-#include <QStatusBar>
-
-// Script function template to pop up a message box
-// with a certain icon and buttons.
-template <int MsgBoxIcon, int MsgBoxButtons>
- static QScriptValue messageBox(QScriptContext *context, QScriptEngine *engine)
-{
- if (context->argumentCount() < 3)
- return QScriptValue(engine, -1);
-
- QWidget *parent = qscriptvalue_cast<QWidget *>(context->argument(0));
- const QString title = context->argument(1).toString();
- const QString msg = context->argument(2).toString();
-
- QMessageBox msgBox(static_cast<QMessageBox::Icon>(MsgBoxIcon), title, msg,
- static_cast<QMessageBox::StandardButtons>(MsgBoxButtons), parent);
-
- return QScriptValue(engine, msgBox.exec());
-}
-
-static QScriptValue inputDialogGetText(QScriptContext *context, QScriptEngine *engine)
-{
- const int argumentCount = context->argumentCount();
- if (argumentCount < 3)
- return QScriptValue(engine, QScriptValue::NullValue);
-
- QWidget *parent = qscriptvalue_cast<QWidget *>(context->argument(0));
- const QString title = context->argument(1).toString();
- const QString label = context->argument(2).toString();
- const QString defaultValue = argumentCount > 3 ? context->argument(3).toString() : QString();
-
- bool ok;
- const QString rc = QInputDialog::getText(parent, title, label, QLineEdit::Normal, defaultValue, &ok);
- if (!ok)
- return QScriptValue(engine, QScriptValue::NullValue);
- return QScriptValue(engine, rc);
-}
-
-static QScriptValue inputDialogGetInteger(QScriptContext *context, QScriptEngine *engine)
-{
- const int argumentCount = context->argumentCount();
- if (argumentCount < 3)
- return QScriptValue(engine, QScriptValue::NullValue);
-
- QWidget *parent = qscriptvalue_cast<QWidget *>(context->argument(0));
- const QString title = context->argument(1).toString();
- const QString label = context->argument(2).toString();
- const int defaultValue = argumentCount > 3 ? context->argument(3).toInt32() : 0;
- const int minValue = argumentCount > 4 ? context->argument(4).toInt32() : INT_MIN;
- const int maxValue = argumentCount > 5 ? context->argument(5).toInt32() : INT_MAX;
-
- bool 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);
-}
-
-static QScriptValue inputDialogGetDouble(QScriptContext *context, QScriptEngine *engine)
-{
- const int argumentCount = context->argumentCount();
- if (argumentCount < 3)
- return QScriptValue(engine, QScriptValue::NullValue);
-
- QWidget *parent = qscriptvalue_cast<QWidget *>(context->argument(0));
- const QString title = context->argument(1).toString();
- const QString label = context->argument(2).toString();
- const double defaultValue = argumentCount > 3 ? context->argument(3).toNumber() : 0;
- // Use QInputDialog defaults
- const double minValue = argumentCount > 4 ? context->argument(4).toNumber() : INT_MIN;
- const double maxValue = argumentCount > 5 ? context->argument(5).toNumber() : INT_MAX;
-
- bool ok;
- const double rc = QInputDialog::getDouble(parent, title, label, defaultValue, minValue, maxValue, 1, &ok);
- if (!ok)
- return QScriptValue(engine, QScriptValue::NullValue);
- return QScriptValue(engine, rc);
-}
-
-static QScriptValue inputDialogGetItem(QScriptContext *context, QScriptEngine *engine)
-{
- const int argumentCount = context->argumentCount();
- if (argumentCount < 4)
- return QScriptValue(engine, QScriptValue::NullValue);
-
- QWidget *parent = qscriptvalue_cast<QWidget *>(context->argument(0));
- const QString title = context->argument(1).toString();
- const QString label = context->argument(2).toString();
- const QStringList items = qscriptvalue_cast<QStringList>(context->argument(3));
- const int defaultItem = argumentCount > 4 ? context->argument(4).toInt32() : 0;
- const bool editable = argumentCount > 5 ? context->argument(5).toInt32() : 0;
-
- bool ok;
- const QString rc = QInputDialog::getItem (parent, title, label, items, defaultItem, editable, &ok);
- if (!ok)
- return QScriptValue(engine, QScriptValue::NullValue);
-
- return QScriptValue(engine, rc);
-}
-
-// Script function template to pop up a file box
-// with a certain icon and buttons.
-template <int TAcceptMode, int TFileMode>
-static QScriptValue fileBox(QScriptContext *context, QScriptEngine *engine)
-{
- const int argumentCount = context->argumentCount();
- if (argumentCount < 2)
- return QScriptValue(engine, QScriptValue::NullValue);
-
- QWidget *parent = qscriptvalue_cast<QWidget *>(context->argument(0));
- const QString title = context->argument(1).toString();
- const QString directory = argumentCount > 2 ? context->argument(2).toString() : QString();
- const QString filter = argumentCount > 3 ? context->argument(3).toString() : QString();
- QFileDialog fileDialog(parent, title, directory, filter);
- fileDialog.setAcceptMode(static_cast<QFileDialog::AcceptMode>(TAcceptMode));
- fileDialog.setFileMode (static_cast<QFileDialog::FileMode>(TFileMode));
- if (fileDialog.exec() == QDialog::Rejected)
- return QScriptValue(engine, QScriptValue::NullValue);
- const QStringList rc = fileDialog.selectedFiles();
- QTC_CHECK(!rc.empty());
- return TFileMode == QFileDialog::ExistingFiles ?
- engine->toScriptValue(rc) : engine->toScriptValue(rc.front());
-}
-
-// ------ ScriptManagerPrivate
-
-namespace Core {
-namespace Internal {
-
-ScriptManagerPrivate::ScriptManagerPrivate(QObject *parent)
- : ScriptManager(parent),
- m_engine(0)
-{
-}
-
-// Split a backtrace of the form:
-// "<anonymous>(BuildManagerCommand(ls))@:0
-// demoProjectExplorer()@:237
-// <anonymous>()@:276
-// <global>()@:0"
-static void parseBackTrace(const QStringList &backTrace, ScriptManagerPrivate::Stack &stack)
-{
- const QChar at = QLatin1Char('@');
- const QChar colon = QLatin1Char(':');
- stack.clear();
- foreach (const QString &line, backTrace) {
- const int atPos = line.lastIndexOf(at);
- if (atPos == -1)
- continue;
- const int colonPos = line.indexOf(colon, atPos + 1);
- if (colonPos == -1)
- continue;
-
- ScriptManagerPrivate::StackFrame frame;
- frame.function = line.left(atPos);
- frame.fileName = line.mid(atPos + 1, colonPos - atPos - 1);
- frame.lineNumber = line.right(line.size() - colonPos - 1).toInt();
- stack.push_back(frame);
- }
-}
-
-bool ScriptManagerPrivate::runScript(const QString &script, QString *errorMessage)
-{
- Stack stack;
- return runScript(script, errorMessage, &stack);
-}
-
-bool ScriptManagerPrivate::runScript(const QString &script, QString *errorMessage, Stack *stack)
-{
- ensureEngineInitialized();
- stack->clear();
-
- m_engine->pushContext();
- m_engine->evaluate(script);
-
- const bool failed = m_engine->hasUncaughtException ();
- if (failed) {
- const int errorLineNumber = m_engine->uncaughtExceptionLineNumber();
- const QStringList backTrace = m_engine->uncaughtExceptionBacktrace();
- parseBackTrace(backTrace, *stack);
- const QString backtrace = backTrace.join(QString(QLatin1Char('\n')));
- *errorMessage = ScriptManager::tr("Exception at line %1: %2\n%3").arg(errorLineNumber).arg(engineError(m_engine)).arg(backtrace);
- }
- m_engine->popContext();
- return !failed;
-}
-
-ScriptManager::QScriptEnginePtr ScriptManagerPrivate::ensureEngineInitialized()
-{
- if (!m_engine.isNull())
- return m_engine;
- m_engine = QScriptEnginePtr(new QScriptEngine);
- // register QObjects that occur as properties
- SharedTools::registerQObject<QMainWindow>(m_engine.data());
- SharedTools::registerQObject<QStatusBar>(m_engine.data());
- SharedTools::registerQObject<QSettings>(m_engine.data());
-
- qScriptRegisterSequenceMetaType<QList<Core::IEditor *> >(m_engine.data());
-
- // CLASSIC: registerInterfaceWithDefaultPrototype<Core::MessageManager, MessageManagerPrototype>(m_engine);
-
- // Message box conveniences
- m_engine->globalObject().setProperty(QLatin1String("critical"),
- m_engine->newFunction(messageBox<QMessageBox::Critical, QMessageBox::Ok>, 3));
- m_engine->globalObject().setProperty(QLatin1String("warning"),
- m_engine->newFunction(messageBox<QMessageBox::Warning, QMessageBox::Ok>, 3));
- m_engine->globalObject().setProperty(QLatin1String("information"),
- m_engine->newFunction(messageBox<QMessageBox::Information, QMessageBox::Ok>, 3));
- // StandardButtons has overloaded operator '|' - grrr.
- enum { MsgBoxYesNo = 0x00014000 };
- m_engine->globalObject().setProperty(QLatin1String("yesNoQuestion"),
- m_engine->newFunction(messageBox<QMessageBox::Question, MsgBoxYesNo>, 3));
-
- m_engine->globalObject().setProperty(QLatin1String("getText"), m_engine->newFunction(inputDialogGetText, 3));
- m_engine->globalObject().setProperty(QLatin1String("getInteger"), m_engine->newFunction(inputDialogGetInteger, 3));
- m_engine->globalObject().setProperty(QLatin1String("getDouble"), m_engine->newFunction(inputDialogGetDouble, 3));
- m_engine->globalObject().setProperty(QLatin1String("getItem"), m_engine->newFunction(inputDialogGetItem, 3));
-
- // file box
- m_engine->globalObject().setProperty(QLatin1String("getOpenFileNames"), m_engine->newFunction(fileBox<QFileDialog::AcceptOpen, QFileDialog::ExistingFiles> , 2));
- m_engine->globalObject().setProperty(QLatin1String("getOpenFileName"), m_engine->newFunction(fileBox<QFileDialog::AcceptOpen, QFileDialog::ExistingFile> , 2));
- m_engine->globalObject().setProperty(QLatin1String("getSaveFileName"), m_engine->newFunction(fileBox<QFileDialog::AcceptSave, QFileDialog::AnyFile> , 2));
- m_engine->globalObject().setProperty(QLatin1String("getExistingDirectory"), m_engine->newFunction(fileBox<QFileDialog::AcceptSave, QFileDialog::DirectoryOnly> , 2));
- return m_engine;
-}
-
-QString ScriptManagerPrivate::engineError(const QScriptEnginePtr &scriptEngine)
-{
- QScriptValue error = scriptEngine->evaluate(QLatin1String("Error"));
- if (error.isValid())
- return error.toString();
- return ScriptManager::tr("Unknown error");
-}
-
-} // namespace Internal
-} // namespace Core
diff --git a/src/plugins/coreplugin/styleanimator.cpp b/src/plugins/coreplugin/styleanimator.cpp
index bd1a9ae4c1..eb1a311cbc 100644
--- a/src/plugins/coreplugin/styleanimator.cpp
+++ b/src/plugins/coreplugin/styleanimator.cpp
@@ -105,8 +105,7 @@ void Transition::paint(QPainter *painter, const QStyleOption *option)
m_running = false;
alpha = 1.0;
}
- }
- else {
+ } else {
m_running = false;
}
drawBlendedImage(painter, option->rect, alpha);
diff --git a/src/plugins/coreplugin/testdatadir.cpp b/src/plugins/coreplugin/testdatadir.cpp
new file mode 100644
index 0000000000..c049585f97
--- /dev/null
+++ b/src/plugins/coreplugin/testdatadir.cpp
@@ -0,0 +1,70 @@
+/****************************************************************************
+**
+** 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 "testdatadir.h"
+
+#include <QDir>
+#include <QFileInfo>
+#include <QString>
+#include <QTest>
+
+using namespace Core::Internal::Tests;
+
+static void maybeAppendSlash(QString *string)
+{
+ const QChar slash = QLatin1Char('/');
+ if (!string->endsWith(slash))
+ string->append(slash);
+}
+
+TestDataDir::TestDataDir(const QString &directory)
+ : m_directory(directory)
+{
+ maybeAppendSlash(&m_directory);
+ QFileInfo fi(m_directory);
+ QVERIFY(fi.exists());
+ QVERIFY(fi.isDir());
+}
+
+QString TestDataDir::file(const QString &fileName) const
+{
+ return directory() + fileName;
+}
+
+QString TestDataDir::directory(const QString &subdir, bool clean) const
+{
+ QString path = m_directory;
+ if (!subdir.isEmpty())
+ path += QLatin1String("/") + subdir;
+ if (clean)
+ path = QDir::cleanPath(path);
+ maybeAppendSlash(&path);
+ return path;
+}
diff --git a/src/plugins/coreplugin/testdatadir.h b/src/plugins/coreplugin/testdatadir.h
new file mode 100644
index 0000000000..d8d654ca02
--- /dev/null
+++ b/src/plugins/coreplugin/testdatadir.h
@@ -0,0 +1,59 @@
+/****************************************************************************
+**
+** 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 TESTDATADIR_H
+#define TESTDATADIR_H
+
+#include "core_global.h"
+
+#include <QString>
+
+namespace Core {
+namespace Internal {
+namespace Tests {
+
+class CORE_EXPORT TestDataDir
+{
+public:
+ TestDataDir(const QString &directory);
+ QString file(const QString &fileName) const;
+
+protected:
+ QString directory(const QString &subdir = QString(), bool clean = true) const;
+
+private:
+ QString m_directory;
+};
+
+} // namespace Tests
+} // namespace Internal
+} // namespace Core
+
+#endif // TESTDATADIR_H
diff --git a/src/plugins/coreplugin/textdocument.cpp b/src/plugins/coreplugin/textdocument.cpp
index dac28c3082..17257e08cb 100644
--- a/src/plugins/coreplugin/textdocument.cpp
+++ b/src/plugins/coreplugin/textdocument.cpp
@@ -28,7 +28,7 @@
****************************************************************************/
#include "textdocument.h"
-#include "editormanager.h"
+#include <coreplugin/editormanager/editormanager.h>
#include <QDebug>
#include <QTextCodec>
@@ -64,7 +64,7 @@ public:
TextDocument::TextDocument(QObject *parent) :
IDocument(parent), d(new Internal::TextDocumentPrivate)
{
- setCodec(Core::EditorManager::instance()->defaultTextCodec());
+ setCodec(Core::EditorManager::defaultTextCodec());
}
TextDocument::~TextDocument()
diff --git a/src/plugins/coreplugin/toolsettings.cpp b/src/plugins/coreplugin/toolsettings.cpp
index 672bc6593f..84b13024b3 100644
--- a/src/plugins/coreplugin/toolsettings.cpp
+++ b/src/plugins/coreplugin/toolsettings.cpp
@@ -64,13 +64,12 @@ bool ToolSettings::matches(const QString & searchKeyWord) const
QWidget *ToolSettings::createPage(QWidget *parent)
{
m_widget = new ExternalToolConfig(parent);
- m_widget->setTools(ExternalToolManager::instance()->toolsByCategory());
+ m_widget->setTools(ExternalToolManager::toolsByCategory());
if (m_searchKeywords.isEmpty())
m_searchKeywords = m_widget->searchKeywords();
return m_widget;
}
-
static QString getUserFilePath(const QString &proposalFileName)
{
QDir resourceDir(ICore::userResourcePath());
@@ -132,7 +131,7 @@ void ToolSettings::apply()
if (!m_widget)
return;
m_widget->apply();
- QMap<QString, ExternalTool *> originalTools = ExternalToolManager::instance()->toolsById();
+ QMap<QString, ExternalTool *> originalTools = ExternalToolManager::toolsById();
QMap<QString, QList<ExternalTool *> > newToolsMap = m_widget->tools();
QMap<QString, QList<ExternalTool *> > resultMap;
QMapIterator<QString, QList<ExternalTool *> > it(newToolsMap);
@@ -202,10 +201,9 @@ void ToolSettings::apply()
QFile::remove(tool->fileName());
}
- ExternalToolManager::instance()->setToolsByCategory(resultMap);
+ ExternalToolManager::setToolsByCategory(resultMap);
}
-
void ToolSettings::finish()
{
}
diff --git a/src/plugins/coreplugin/toolsettings.h b/src/plugins/coreplugin/toolsettings.h
index 89bd4d680a..c161436de9 100644
--- a/src/plugins/coreplugin/toolsettings.h
+++ b/src/plugins/coreplugin/toolsettings.h
@@ -30,7 +30,7 @@
#ifndef TOOLSETTINGS_H
#define TOOLSETTINGS_H
-#include "ioptionspage.h"
+#include <coreplugin/dialogs/ioptionspage.h>
#include <QPointer>
diff --git a/src/plugins/coreplugin/variablemanager.cpp b/src/plugins/coreplugin/variablemanager.cpp
index 06146712ae..873a6481b5 100644
--- a/src/plugins/coreplugin/variablemanager.cpp
+++ b/src/plugins/coreplugin/variablemanager.cpp
@@ -78,7 +78,7 @@ public:
Examples of this are \c{CurrentDocument:FilePath} and \c{CurrentDocument:Selection}.
When the variable manager is requested to replace variables in a string, it looks for
- variable names enclosed in ${ and }, like ${CurrentDocument:FilePath}.
+ variable names enclosed in %{ and }, like %{CurrentDocument:FilePath}.
\note The names of the variables are stored as QByteArray. They are typically
7-bit-clean. In cases where this is not possible, UTF-8 encoding is
@@ -91,32 +91,32 @@ public:
the variable its value when requested. A typical setup is to
\list 1
- \o Register the variables in ExtensionSystem::IPlugin::initialize():
- \code
- static const char kMyVariable[] = "MyVariable";
-
- bool MyPlugin::initialize(const QStringList &arguments, QString *errorString)
- {
- [...]
- VariableManager::registerVariable(kMyVariable, tr("The current value of whatever I want."));
- connect(VariableManager::instance(), SIGNAL(variableUpdateRequested(QByteArray)),
- this, SLOT(updateVariable(QByteArray)));
- [...]
- }
- \endcode
-
- \o Set the variable value when requested:
- \code
- void MyPlugin::updateVariable(const QByteArray &variable)
- {
- if (variable == kMyVariable) {
- QString value;
- // do whatever is necessary to retrieve the value
- [...]
- VariableManager::insert(variable, value);
- }
- }
- \endcode
+ \li Register the variables in ExtensionSystem::IPlugin::initialize():
+ \code
+ static const char kMyVariable[] = "MyVariable";
+
+ bool MyPlugin::initialize(const QStringList &arguments, QString *errorString)
+ {
+ [...]
+ VariableManager::registerVariable(kMyVariable, tr("The current value of whatever I want."));
+ connect(VariableManager::instance(), SIGNAL(variableUpdateRequested(QByteArray)),
+ this, SLOT(updateVariable(QByteArray)));
+ [...]
+ }
+ \endcode
+
+ \li Set the variable value when requested:
+ \code
+ void MyPlugin::updateVariable(const QByteArray &variable)
+ {
+ if (variable == kMyVariable) {
+ QString value;
+ // do whatever is necessary to retrieve the value
+ [...]
+ VariableManager::insert(variable, value);
+ }
+ }
+ \endcode
\endlist
If there are conditions where your variable is not valid, you should call
@@ -159,20 +159,20 @@ public:
There are several different ways to expand a string, covering the different use cases,
listed here sorted by relevance:
\list
- \o Using VariableManager::expandedString(). This is the most comfortable way to get a string
- with variable values expanded, but also the least flexible one. If this is sufficient for
- you, use it.
- \o Using the Utils::expandMacros() methods. These take a string and a macro expander (for which
- you would use the one provided by the variable manager). Mostly the same as
- VariableManager::expandedString(), but also has a variant that does the replacement inline
- instead of returning a new string.
- \o Using Utils::QtcProcess::expandMacros(). This expands the string while conforming to the
- quoting rules of the platform it is run on. Use this method with the variable manager's
- macro expander if your string will be passed as a command line parameter string to an
- external command.
- \o Writing your own macro expander that nests the variable manager's macro expander. And then
- doing one of the above. This allows you to expand additional "local" variables/macros,
- that do not come from the variable manager.
+ \li Using VariableManager::expandedString(). This is the most comfortable way to get a string
+ with variable values expanded, but also the least flexible one. If this is sufficient for
+ you, use it.
+ \li Using the Utils::expandMacros() methods. These take a string and a macro expander (for which
+ you would use the one provided by the variable manager). Mostly the same as
+ VariableManager::expandedString(), but also has a variant that does the replacement inline
+ instead of returning a new string.
+ \li Using Utils::QtcProcess::expandMacros(). This expands the string while conforming to the
+ quoting rules of the platform it is run on. Use this method with the variable manager's
+ macro expander if your string will be passed as a command line parameter string to an
+ external command.
+ \li Writing your own macro expander that nests the variable manager's macro expander. And then
+ doing one of the above. This allows you to expand additional "local" variables/macros,
+ that do not come from the variable manager.
\endlist
*/
@@ -276,7 +276,7 @@ Utils::AbstractMacroExpander *VariableManager::macroExpander()
* Returns the variable manager instance, for connecting to signals. All other methods are static
* and should be called as class methods, not through the instance.
*/
-VariableManager *VariableManager::instance()
+QObject *VariableManager::instance()
{
return variableManagerInstance;
}
diff --git a/src/plugins/coreplugin/variablemanager.h b/src/plugins/coreplugin/variablemanager.h
index 9cc75744f5..927747df95 100644
--- a/src/plugins/coreplugin/variablemanager.h
+++ b/src/plugins/coreplugin/variablemanager.h
@@ -43,17 +43,14 @@ class AbstractMacroExpander;
namespace Core {
-class VariableManagerPrivate;
+namespace Internal { class MainWindow; }
class CORE_EXPORT VariableManager : public QObject
{
Q_OBJECT
public:
- VariableManager();
- ~VariableManager();
-
- static VariableManager *instance();
+ static QObject *instance();
static void insert(const QByteArray &variable, const QString &value);
static bool remove(const QByteArray &variable);
@@ -78,6 +75,12 @@ public:
signals:
void variableUpdateRequested(const QByteArray &variable);
+
+private:
+ VariableManager();
+ ~VariableManager();
+
+ friend class Core::Internal::MainWindow;
};
} // namespace Core
diff --git a/src/plugins/coreplugin/vcsmanager.cpp b/src/plugins/coreplugin/vcsmanager.cpp
index 97960dc178..c2419d8beb 100644
--- a/src/plugins/coreplugin/vcsmanager.cpp
+++ b/src/plugins/coreplugin/vcsmanager.cpp
@@ -31,13 +31,14 @@
#include "iversioncontrol.h"
#include "icore.h"
#include "documentmanager.h"
-#include "editormanager.h"
-#include "ieditor.h"
#include "idocument.h"
#include "infobar.h"
-#include <vcsbase/vcsbaseconstants.h>
+#include <coreplugin/dialogs/addtovcsdialog.h>
+#include <coreplugin/editormanager/editormanager.h>
+#include <coreplugin/editormanager/ieditor.h>
+#include <vcsbase/vcsbaseconstants.h>
#include <extensionsystem/pluginmanager.h>
#include <utils/qtcassert.h>
@@ -177,19 +178,29 @@ public:
IVersionControl *m_unconfiguredVcs;
};
+static VcsManagerPrivate *d = 0;
+static VcsManager *m_instance = 0;
+
VcsManager::VcsManager(QObject *parent) :
- QObject(parent),
- d(new VcsManagerPrivate)
+ QObject(parent)
{
+ m_instance = this;
+ d = new VcsManagerPrivate;
}
// ---- VCSManager:
VcsManager::~VcsManager()
{
+ m_instance = 0;
delete d;
}
+QObject *VcsManager::instance()
+{
+ return m_instance;
+}
+
void VcsManager::extensionsInitialized()
{
// Change signal connections
@@ -197,7 +208,7 @@ void VcsManager::extensionsInitialized()
connect(versionControl, SIGNAL(filesChanged(QStringList)),
DocumentManager::instance(), SIGNAL(filesChangedInternally(QStringList)));
connect(versionControl, SIGNAL(repositoryChanged(QString)),
- this, SIGNAL(repositoryChanged(QString)));
+ m_instance, SIGNAL(repositoryChanged(QString)));
}
}
@@ -214,7 +225,7 @@ void VcsManager::resetVersionControlForDirectory(const QString &inputDirectory)
const QString directory = QDir(inputDirectory).absolutePath();
d->resetCache(directory);
- emit repositoryChanged(directory);
+ emit m_instance->repositoryChanged(directory);
}
IVersionControl* VcsManager::findVersionControlForDirectory(const QString &inputDirectory,
@@ -277,9 +288,7 @@ IVersionControl* VcsManager::findVersionControlForDirectory(const QString &input
const bool isVcsConfigured = versionControl->isConfigured();
if (!isVcsConfigured || d->m_unconfiguredVcs) {
Id vcsWarning("VcsNotConfiguredWarning");
- IDocument *curDocument = 0;
- if (IEditor *curEditor = EditorManager::currentEditor())
- curDocument = curEditor->document();
+ IDocument *curDocument = EditorManager::currentDocument();
if (isVcsConfigured) {
if (curDocument && d->m_unconfiguredVcs == versionControl) {
curDocument->infoBar()->removeInfo(vcsWarning);
@@ -294,7 +303,7 @@ IVersionControl* VcsManager::findVersionControlForDirectory(const QString &input
.arg(versionControl->displayName()),
InfoBarEntry::GlobalSuppressionEnabled);
d->m_unconfiguredVcs = versionControl;
- info.setCustomButtonInfo(tr("Configure"), this, SLOT(configureVcs()));
+ info.setCustomButtonInfo(tr("Configure"), m_instance, SLOT(configureVcs()));
infoBar->addInfo(info);
}
return 0;
@@ -303,7 +312,7 @@ IVersionControl* VcsManager::findVersionControlForDirectory(const QString &input
return versionControl;
}
-QStringList VcsManager::repositories(const IVersionControl *vc) const
+QStringList VcsManager::repositories(const IVersionControl *vc)
{
QStringList result;
foreach (const VcsManagerPrivate::VcsInfo *vi, d->m_vcsInfoList)
@@ -403,11 +412,9 @@ void VcsManager::promptToAdd(const QString &directory, const QStringList &fileNa
if (!vc || !vc->supportsOperation(Core::IVersionControl::AddOperation))
return;
- QMessageBox::StandardButton button =
- QMessageBox::question(Core::ICore::mainWindow(), VcsManager::msgAddToVcsTitle(),
- VcsManager::msgPromptToAddToVcs(fileNames, vc),
- QMessageBox::Yes | QMessageBox::No);
- if (button == QMessageBox::Yes) {
+ Internal::AddToVcsDialog dlg(Core::ICore::mainWindow(), VcsManager::msgAddToVcsTitle(),
+ fileNames, vc->displayName());
+ if (dlg.exec() == QDialog::Accepted) {
QStringList notAddedToVc;
foreach (const QString &file, fileNames) {
if (!vc->vcsAdd(file))
@@ -423,7 +430,7 @@ void VcsManager::promptToAdd(const QString &directory, const QStringList &fileNa
void VcsManager::emitRepositoryChanged(const QString &repository)
{
- emit repositoryChanged(repository);
+ emit m_instance->repositoryChanged(repository);
}
void VcsManager::clearVersionControlCache()
@@ -431,7 +438,7 @@ void VcsManager::clearVersionControlCache()
QStringList repoList = d->m_cachedMatches.keys();
d->clearCache();
foreach (const QString &repo, repoList)
- emit repositoryChanged(repo);
+ emit m_instance->repositoryChanged(repo);
}
void VcsManager::configureVcs()
diff --git a/src/plugins/coreplugin/vcsmanager.h b/src/plugins/coreplugin/vcsmanager.h
index 8eb8fa5b55..6e76995b64 100644
--- a/src/plugins/coreplugin/vcsmanager.h
+++ b/src/plugins/coreplugin/vcsmanager.h
@@ -37,9 +37,10 @@
namespace Core {
-class VcsManagerPrivate;
class IVersionControl;
+namespace Internal { class MainWindow; }
+
/* VcsManager:
* 1) Provides functionality for finding the IVersionControl * for a given
* filename (findVersionControlForDirectory). Note that the VcsManager assumes
@@ -57,36 +58,35 @@ class CORE_EXPORT VcsManager : public QObject
Q_OBJECT
public:
- explicit VcsManager(QObject *parent = 0);
- virtual ~VcsManager();
+ static QObject *instance();
- void extensionsInitialized();
+ static void extensionsInitialized();
- void resetVersionControlForDirectory(const QString &inputDirectory);
- IVersionControl *findVersionControlForDirectory(const QString &directory,
+ static void resetVersionControlForDirectory(const QString &inputDirectory);
+ static IVersionControl *findVersionControlForDirectory(const QString &directory,
QString *topLevelDirectory = 0);
- QStringList repositories(const IVersionControl *) const;
+ static QStringList repositories(const IVersionControl *);
- IVersionControl *checkout(const QString &versionControlType,
+ static IVersionControl *checkout(const QString &versionControlType,
const QString &directory,
const QByteArray &url);
// Used only by Trac plugin.
bool findVersionControl(const QString &versionControl);
// Used only by Trac plugin.
- QString repositoryUrl(const QString &directory);
+ static QString repositoryUrl(const QString &directory);
// Shows a confirmation dialog, whether the file should also be deleted
// from revision control. Calls vcsDelete on the file. Returns false
// if a failure occurs
- bool promptToDelete(const QString &fileName);
- bool promptToDelete(IVersionControl *versionControl, const QString &fileName);
+ static bool promptToDelete(const QString &fileName);
+ static bool promptToDelete(IVersionControl *versionControl, const QString &fileName);
// Shows a confirmation dialog, whether the files in the list should be
// added to revision control. Calls vcsAdd for each file.
- void promptToAdd(const QString &directory, const QStringList &fileNames);
+ static void promptToAdd(const QString &directory, const QStringList &fileNames);
- void emitRepositoryChanged(const QString &repository);
+ static void emitRepositoryChanged(const QString &repository);
// Utility messages for adding files
static QString msgAddToVcsTitle();
@@ -98,13 +98,16 @@ signals:
void repositoryChanged(const QString &repository);
public slots:
- void clearVersionControlCache();
+ static void clearVersionControlCache();
private slots:
- void configureVcs();
+ static void configureVcs();
private:
- VcsManagerPrivate *d;
+ explicit VcsManager(QObject *parent = 0);
+ ~VcsManager();
+
+ friend class Core::Internal::MainWindow;
};
} // namespace Core
diff --git a/src/plugins/cpaster/CodePaster.pluginspec.in b/src/plugins/cpaster/CodePaster.pluginspec.in
index 0f0a56c30a..d45efba3ea 100644
--- a/src/plugins/cpaster/CodePaster.pluginspec.in
+++ b/src/plugins/cpaster/CodePaster.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"CodePaster\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"CodePaster\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/cpaster/codepasterprotocol.cpp b/src/plugins/cpaster/codepasterprotocol.cpp
deleted file mode 100644
index 232f977a69..0000000000
--- a/src/plugins/cpaster/codepasterprotocol.cpp
+++ /dev/null
@@ -1,212 +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 "codepasterprotocol.h"
-#include "codepastersettings.h"
-
-#include <coreplugin/icore.h>
-#include <coreplugin/messagemanager.h>
-
-#include <utils/hostosinfo.h>
-#include <utils/qtcassert.h>
-
-#include <QNetworkReply>
-#include <QDebug>
-
-enum { debug = 0 };
-
-namespace CodePaster {
-
-CodePasterProtocol::CodePasterProtocol() :
- m_page(new CodePaster::CodePasterSettingsPage),
- m_pasteReply(0),
- m_fetchReply(0),
- m_listReply(0),
- m_fetchId(-1)
-{
-}
-
-CodePasterProtocol::~CodePasterProtocol()
-{
-}
-
-QString CodePasterProtocol::name() const
-{
- return QLatin1String("CodePaster");
-}
-
-unsigned CodePasterProtocol::capabilities() const
-{
- return ListCapability|PostCommentCapability|PostDescriptionCapability;
-}
-
-bool CodePasterProtocol::checkConfiguration(QString *errorMessage)
-{
- const QString hostName = m_page->hostName();
- if (hostName.isEmpty()) {
- if (errorMessage) {
- *errorMessage = Utils::HostOsInfo::isMacHost()
- ? tr("No Server defined in the CodePaster preferences.")
- : tr("No Server defined in the CodePaster options.");
- }
- return false;
- }
- // Check the host once. Note that it can be modified in the settings page.
- if (m_hostChecked == hostName)
- return true;
- const bool ok = httpStatus(m_page->hostName(), errorMessage);
- if (ok)
- m_hostChecked = hostName;
- return ok;
-}
-
-void CodePasterProtocol::fetch(const QString &id)
-{
- QTC_ASSERT(!m_fetchReply, return);
-
- QString hostName = m_page->hostName();
- const QString httpPrefix = QLatin1String("http://");
- QString link;
- // Did the user enter a complete URL instead of an id?
- if (id.startsWith(httpPrefix)) {
- // Append 'raw' format option
- link = id;
- link += QLatin1String("&format=raw");
- const int idPos = id.lastIndexOf(QLatin1Char('='));
- m_fetchId = idPos != -1 ? id.mid(idPos + 1) : id;
- } else {
- link = httpPrefix;
- link.append(hostName);
- link.append(QLatin1String("/?format=raw&id="));
- link.append(id);
- m_fetchId = id;
- }
- m_fetchReply = httpGet(link);
- connect(m_fetchReply, SIGNAL(finished()), this, SLOT(fetchFinished()));
-}
-
-void CodePasterProtocol::list()
-{
- QTC_ASSERT(!m_listReply, return);
-
- QString hostName = m_page->hostName();
- QString link = QLatin1String("http://");
- link += hostName;
- link += QLatin1String("/?command=browse&format=raw");
- m_listReply = httpGet(link);
- connect(m_listReply, SIGNAL(finished()), this, SLOT(listFinished()));
-}
-
-void CodePasterProtocol::paste(const QString &text,
- ContentType /* ct */, int /* expiryDays */,
- const QString &username,
- const QString &comment,
- const QString &description)
-{
- QTC_ASSERT(!m_pasteReply, return);
- const QString hostName = m_page->hostName();
-
- QByteArray data = "command=processcreate&submit=submit&highlight_type=0&description=";
- data += QUrl::toPercentEncoding(description);
- data += "&comment=";
- data += QUrl::toPercentEncoding(comment);
- data += "&code=";
- data += QUrl::toPercentEncoding(fixNewLines(text));
- data += "&poster=";
- data += QUrl::toPercentEncoding(username);
-
- m_pasteReply = httpPost(QLatin1String("http://") + hostName, data);
- connect(m_pasteReply, SIGNAL(finished()), this, SLOT(pasteFinished()));
-}
-
-void CodePasterProtocol::pasteFinished()
-{
- if (m_pasteReply->error()) {
- qWarning("Error pasting: %s", qPrintable(m_pasteReply->errorString()));
- } else {
- // Cut out the href-attribute
- QString contents = QString::fromLatin1(m_pasteReply->readAll());
- int hrefPos = contents.indexOf(QLatin1String("href=\""));
- if (hrefPos != -1) {
- hrefPos += 6;
- const int endPos = contents.indexOf(QLatin1Char('"'), hrefPos);
- if (endPos != -1)
- emit pasteDone(contents.mid(hrefPos, endPos - hrefPos));
- }
- }
- m_pasteReply->deleteLater();
- m_pasteReply = 0;
-}
-
-bool CodePasterProtocol::hasSettings() const
-{
- return true;
-}
-
-Core::IOptionsPage *CodePasterProtocol::settingsPage() const
-{
- return m_page;
-}
-
-void CodePasterProtocol::fetchFinished()
-{
- QString title;
- QString content;
- bool error = m_fetchReply->error();
- if (error) {
- content = m_fetchReply->errorString();
- } else {
- 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>"))) {
- content = tr("No such paste");
- error = true;
- }
- title = QString::fromLatin1("Codepaster: %1").arg(m_fetchId);
- }
- m_fetchReply->deleteLater();
- m_fetchReply = 0;
- emit fetchDone(title, content, error);
-}
-
-void CodePasterProtocol::listFinished()
-{
- if (m_listReply->error()) {
- Core::ICore::messageManager()->printToOutputPane(m_listReply->errorString(), Core::MessageManager::NoModeSwitch);
- } else {
- const QByteArray data = m_listReply->readAll();
- const QStringList lines = QString::fromLatin1(data).split(QLatin1Char('\n'));
- emit listDone(name(), lines);
- }
- m_listReply->deleteLater();
- m_listReply = 0;
-}
-
-} // namespace CodePaster
diff --git a/src/plugins/cpaster/codepasterprotocol.h b/src/plugins/cpaster/codepasterprotocol.h
deleted file mode 100644
index 699d38c626..0000000000
--- a/src/plugins/cpaster/codepasterprotocol.h
+++ /dev/null
@@ -1,81 +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 CODEPASTERPROTOCOL_H
-#define CODEPASTERPROTOCOL_H
-
-#include "protocol.h"
-
-QT_BEGIN_NAMESPACE
-class QNetworkReply;
-QT_END_NAMESPACE
-
-namespace CodePaster {
-
-class CodePasterSettingsPage;
-
-class CodePasterProtocol : public NetworkProtocol
-{
- Q_OBJECT
-public:
- explicit CodePasterProtocol();
- ~CodePasterProtocol();
-
- QString name() const;
-
- virtual unsigned capabilities() const;
- bool hasSettings() const;
- Core::IOptionsPage *settingsPage() const;
-
- virtual bool checkConfiguration(QString *errorMessage = 0);
- void fetch(const QString &id);
- void list();
- void paste(const QString &text,
- ContentType ct = Text,
- int expiryDays = 1,
- const QString &username = QString(),
- const QString &comment = QString(),
- const QString &description = QString());
-public slots:
- void fetchFinished();
- void listFinished();
- void pasteFinished();
-
-private:
- CodePasterSettingsPage *m_page;
- QNetworkReply *m_pasteReply;
- QNetworkReply *m_fetchReply;
- QNetworkReply *m_listReply;
- QString m_fetchId;
- QString m_hostChecked;
-};
-
-} // namespace CodePaster
-
-#endif // CODEPASTERPROTOCOL_H
diff --git a/src/plugins/cpaster/codepastersettings.cpp b/src/plugins/cpaster/codepastersettings.cpp
deleted file mode 100644
index 4f2e4558e6..0000000000
--- a/src/plugins/cpaster/codepastersettings.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 "codepastersettings.h"
-#include "cpasterconstants.h"
-
-#include <coreplugin/icore.h>
-
-#include <QCoreApplication>
-#include <QLineEdit>
-#include <QFormLayout>
-#include <QVBoxLayout>
-#include <QLabel>
-#include <QDebug>
-
-static const char settingsGroupC[] = "CodePasterSettings";
-static const char serverKeyC[] = "Server";
-
-namespace CodePaster {
-
-CodePasterSettingsPage::CodePasterSettingsPage()
-{
- setId("C.CodePaster");
- setDisplayName(tr("CodePaster"));
- setCategory(Constants::CPASTER_SETTINGS_CATEGORY);
- setDisplayCategory(QCoreApplication::translate("CodePaster",
- Constants::CPASTER_SETTINGS_TR_CATEGORY));
-
- const QString keyRoot = QLatin1String(settingsGroupC) + QLatin1Char('/');
- m_host = Core::ICore::settings()->value(keyRoot + QLatin1String(serverKeyC), QString()).toString();
-}
-
-QWidget *CodePasterSettingsPage::createPage(QWidget *parent)
-{
- QWidget *outerWidget = new QWidget(parent);
- QVBoxLayout *outerLayout = new QVBoxLayout(outerWidget);
-
- QFormLayout *formLayout = new QFormLayout;
- formLayout->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow);
- QLineEdit *lineEdit = new QLineEdit(m_host);
- connect(lineEdit, SIGNAL(textChanged(QString)), this, SLOT(serverChanged(QString)));
- formLayout->addRow(tr("Server:"), lineEdit);
- outerLayout->addLayout(formLayout);
- outerLayout->addSpacerItem(new QSpacerItem(0, 3, QSizePolicy::Ignored, QSizePolicy::Fixed));
-
- QLabel *noteLabel = new QLabel(tr("<i>Note: Specify the host name for the CodePaster service "
- "without any protocol prepended (e.g. codepaster.mycompany.com).</i>"));
- noteLabel->setWordWrap(true);
- outerLayout->addWidget(noteLabel);
-
- outerLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Ignored, QSizePolicy::MinimumExpanding));
- return outerWidget;
-}
-
-void CodePasterSettingsPage::apply()
-{
- QSettings *settings = Core::ICore::settings();
- const QString keyRoot = QLatin1String(settingsGroupC) + QLatin1Char('/');
- settings->beginGroup(QLatin1String(settingsGroupC));
- settings->setValue(QLatin1String(serverKeyC), m_host);
- settings->endGroup();
-}
-
-void CodePasterSettingsPage::serverChanged(const QString &host)
-{
- m_host = host.trimmed();
-}
-
-QString CodePasterSettingsPage::hostName() const
-{
- return m_host;
-}
-} // namespace CodePaster
diff --git a/src/plugins/cpaster/columnindicatortextedit.cpp b/src/plugins/cpaster/columnindicatortextedit.cpp
index 0964f6954b..9ea126ca55 100644
--- a/src/plugins/cpaster/columnindicatortextedit.cpp
+++ b/src/plugins/cpaster/columnindicatortextedit.cpp
@@ -41,6 +41,7 @@ ColumnIndicatorTextEdit::ColumnIndicatorTextEdit(QWidget *parent) :
font.setFamily(QLatin1String("Courier New"));
setFont(font);
setReadOnly(true);
+ setUndoRedoEnabled(false);
QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
sizePolicy.setVerticalStretch(3);
setSizePolicy(sizePolicy);
diff --git a/src/plugins/cpaster/cpaster.pro b/src/plugins/cpaster/cpaster.pro
index d73d615280..f697c94e16 100644
--- a/src/plugins/cpaster/cpaster.pro
+++ b/src/plugins/cpaster/cpaster.pro
@@ -3,10 +3,8 @@ include(../../qtcreatorplugin.pri)
HEADERS += cpasterplugin.h \
settingspage.h \
protocol.h \
- codepasterprotocol.h \
pasteview.h \
cpasterconstants.h \
- codepastersettings.h \
pastebindotcomprotocol.h \
pastebindotcaprotocol.h \
settings.h \
@@ -20,9 +18,7 @@ HEADERS += cpasterplugin.h \
SOURCES += cpasterplugin.cpp \
settingspage.cpp \
protocol.cpp \
- codepasterprotocol.cpp \
pasteview.cpp \
- codepastersettings.cpp \
pastebindotcomprotocol.cpp \
pastebindotcaprotocol.cpp \
settings.cpp \
diff --git a/src/plugins/cpaster/cpaster.qbs b/src/plugins/cpaster/cpaster.qbs
index c1857e6106..01815bb7c5 100644
--- a/src/plugins/cpaster/cpaster.qbs
+++ b/src/plugins/cpaster/cpaster.qbs
@@ -12,10 +12,6 @@ QtcPlugin {
cpp.includePaths: base.concat("../../shared/cpaster")
files: [
- "codepasterprotocol.cpp",
- "codepasterprotocol.h",
- "codepastersettings.cpp",
- "codepastersettings.h",
"columnindicatortextedit.cpp",
"columnindicatortextedit.h",
"cpasterconstants.h",
diff --git a/src/plugins/cpaster/cpasterplugin.cpp b/src/plugins/cpaster/cpasterplugin.cpp
index 5c39007014..58020e6153 100644
--- a/src/plugins/cpaster/cpasterplugin.cpp
+++ b/src/plugins/cpaster/cpasterplugin.cpp
@@ -30,7 +30,6 @@
#include "cpasterplugin.h"
#include "pasteview.h"
-#include "codepasterprotocol.h"
#include "kdepasteprotocol.h"
#include "pastebindotcomprotocol.h"
#include "pastebindotcaprotocol.h"
@@ -133,7 +132,6 @@ bool CodepasterPlugin::initialize(const QStringList &arguments, QString *errorMe
Protocol *protos[] = { new PasteBinDotComProtocol,
new PasteBinDotCaProtocol,
new KdePasteProtocol,
- new CodePasterProtocol,
new FileShareProtocol
};
const int count = sizeof(protos) / sizeof(Protocol *);
@@ -157,7 +155,7 @@ bool CodepasterPlugin::initialize(const QStringList &arguments, QString *errorMe
Core::ActionManager::actionContainer(Core::Constants::M_TOOLS);
Core::ActionContainer *cpContainer =
- Core::ActionManager::createMenu(Core::Id("CodePaster"));
+ Core::ActionManager::createMenu("CodePaster");
cpContainer->menu()->setTitle(tr("&Code Pasting"));
toolsContainer->addMenu(cpContainer);
@@ -308,7 +306,7 @@ void CodepasterPlugin::finishPost(const QString &link)
{
if (m_settings->copyToClipboard)
QApplication::clipboard()->setText(link);
- ICore::messageManager()->printToOutputPane(link, m_settings->displayOutput ? Core::MessageManager::ModeSwitch : Core::MessageManager::Silent);
+ MessageManager::write(link, m_settings->displayOutput ? Core::MessageManager::ModeSwitch : Core::MessageManager::Silent);
}
// Extract the characters that can be used for a file name from a title
@@ -348,14 +346,13 @@ void CodepasterPlugin::finishFetch(const QString &titleDescription,
const QString &content,
bool error)
{
- Core::MessageManager *messageManager = ICore::messageManager();
// Failure?
if (error) {
- messageManager->printToOutputPane(content, Core::MessageManager::NoModeSwitch);
+ MessageManager::write(content);
return;
}
if (content.isEmpty()) {
- messageManager->printToOutputPane(tr("Empty snippet received for \"%1\".").arg(titleDescription), Core::MessageManager::NoModeSwitch);
+ MessageManager::write(tr("Empty snippet received for \"%1\".").arg(titleDescription));
return;
}
// If the mime type has a preferred suffix (cpp/h/patch...), use that for
@@ -365,7 +362,7 @@ void CodepasterPlugin::finishFetch(const QString &titleDescription,
// Default to "txt".
QByteArray byteContent = content.toUtf8();
QString suffix;
- if (const Core::MimeType mimeType = Core::ICore::mimeDatabase()->findByData(byteContent))
+ if (const MimeType mimeType = MimeDatabase::findByData(byteContent))
suffix = mimeType.preferredSuffix();
if (suffix.isEmpty())
suffix = QLatin1String("txt");
@@ -374,7 +371,7 @@ void CodepasterPlugin::finishFetch(const QString &titleDescription,
saver.setAutoRemove(false);
saver.write(byteContent);
if (!saver.finalize()) {
- messageManager->printToOutputPane(saver.errorString(), Core::MessageManager::NoModeSwitch);
+ MessageManager::write(saver.errorString());
return;
}
const QString fileName = saver.fileName();
@@ -382,7 +379,7 @@ void CodepasterPlugin::finishFetch(const QString &titleDescription,
// Open editor with title.
Core::IEditor *editor = EditorManager::openEditor(fileName);
QTC_ASSERT(editor, return);
- editor->setDisplayName(titleDescription);
+ editor->document()->setDisplayName(titleDescription);
}
CodepasterPlugin *CodepasterPlugin::instance()
diff --git a/src/plugins/cpaster/fileshareprotocol.cpp b/src/plugins/cpaster/fileshareprotocol.cpp
index 0663a5463f..379c0de176 100644
--- a/src/plugins/cpaster/fileshareprotocol.cpp
+++ b/src/plugins/cpaster/fileshareprotocol.cpp
@@ -69,7 +69,7 @@ QString FileShareProtocol::name() const
unsigned FileShareProtocol::capabilities() const
{
- return ListCapability|PostDescriptionCapability;
+ return ListCapability | PostDescriptionCapability | PostUserNameCapability;
}
bool FileShareProtocol::hasSettings() const
@@ -205,11 +205,10 @@ void FileShareProtocol::paste(const QString &text,
saver.setResult(&writer);
}
if (!saver.finalize()) {
- Core::ICore::messageManager()->printToOutputPane(saver.errorString(), Core::MessageManager::NoModeSwitch);
+ Core::MessageManager::write(saver.errorString());
return;
}
- const QString msg = tr("Pasted: %1").arg(saver.fileName());
- Core::ICore::messageManager()->printToOutputPane(msg, Core::MessageManager::NoModeSwitch);
+ Core::MessageManager::write(tr("Pasted: %1").arg(saver.fileName()));
}
} // namespace CodePaster
diff --git a/src/plugins/cpaster/frontend/frontend.qbs b/src/plugins/cpaster/frontend/frontend.qbs
index 87262aa3d6..70be0e9f00 100644
--- a/src/plugins/cpaster/frontend/frontend.qbs
+++ b/src/plugins/cpaster/frontend/frontend.qbs
@@ -9,21 +9,32 @@ QtcTool {
submodules: ["gui", "network"]
}
Depends { name: "Core" }
+ Depends { name: "CppTools" }
- 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",
- ]
+ Group {
+ name: "Frontend Sources"
+ files: [
+ "main.cpp",
+ "argumentscollector.h", "argumentscollector.cpp"
+ ]
+ }
+
+ Group {
+ name: "Plugin Sources"
+ prefix: "../"
+ files: [
+ "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/kdepasteprotocol.cpp b/src/plugins/cpaster/kdepasteprotocol.cpp
index 2f62b80ca9..782e574019 100644
--- a/src/plugins/cpaster/kdepasteprotocol.cpp
+++ b/src/plugins/cpaster/kdepasteprotocol.cpp
@@ -61,7 +61,7 @@ QString KdePasteProtocol::protocolName()
unsigned KdePasteProtocol::capabilities() const
{
- return ListCapability;
+ return ListCapability | PostUserNameCapability;
}
bool KdePasteProtocol::checkConfiguration(QString *errorMessage)
diff --git a/src/plugins/cpaster/pastebindotcaprotocol.cpp b/src/plugins/cpaster/pastebindotcaprotocol.cpp
index 1592cd2fd7..4f3d6e443a 100644
--- a/src/plugins/cpaster/pastebindotcaprotocol.cpp
+++ b/src/plugins/cpaster/pastebindotcaprotocol.cpp
@@ -37,6 +37,7 @@
#include <QStringList>
static const char urlC[] = "http://pastebin.ca/";
+static const char protocolNameC[] = "Pastebin.Ca";
namespace CodePaster {
PasteBinDotCaProtocol::PasteBinDotCaProtocol() :
@@ -47,9 +48,14 @@ PasteBinDotCaProtocol::PasteBinDotCaProtocol() :
{
}
+QString PasteBinDotCaProtocol::protocolName()
+{
+ return QLatin1String(protocolNameC);
+}
+
unsigned PasteBinDotCaProtocol::capabilities() const
{
- return ListCapability | PostDescriptionCapability;
+ return ListCapability | PostDescriptionCapability | PostCommentCapability;
}
void PasteBinDotCaProtocol::fetch(const QString &id)
@@ -90,8 +96,8 @@ static QByteArray toTypeId(Protocol::ContentType ct)
void PasteBinDotCaProtocol::paste(const QString &text,
ContentType ct, int expiryDays,
- const QString &username,
- const QString & /* comment */,
+ const QString &/* username */,
+ const QString & comment,
const QString &description)
{
QTC_ASSERT(!m_pasteReply, return);
@@ -101,11 +107,11 @@ void PasteBinDotCaProtocol::paste(const QString &text,
data += "&type=";
data += toTypeId(ct);
data += "&description=";
- data += QUrl::toPercentEncoding(description);
+ data += QUrl::toPercentEncoding(comment);
data += "&expiry=";
data += QByteArray::number(expiryDays);
- data += "%20day&name=";
- data += QUrl::toPercentEncoding(username);
+ data += "%20day&name="; // Title or name.
+ data += QUrl::toPercentEncoding(description);
// fire request
const QString link = QLatin1String(urlC) + QLatin1String("quiet-paste.php");
m_pasteReply = httpPost(link, data);
@@ -115,7 +121,7 @@ void PasteBinDotCaProtocol::paste(const QString &text,
void PasteBinDotCaProtocol::pasteFinished()
{
if (m_pasteReply->error()) {
- qWarning("Pastebin.ca protocol error: %s", qPrintable(m_pasteReply->errorString()));
+ qWarning("%s protocol error: %s", protocolNameC, qPrintable(m_pasteReply->errorString()));
} else {
/// returns ""SUCCESS:[id]""
const QByteArray data = m_pasteReply->readAll();
@@ -134,7 +140,7 @@ void PasteBinDotCaProtocol::fetchFinished()
if (error) {
content = m_fetchReply->errorString();
} else {
- title = QString::fromLatin1("Pastebin.ca: %1").arg(m_fetchId);
+ title = name() + QLatin1String(": ") + m_fetchId;
const QByteArray data = m_fetchReply->readAll();
content = QString::fromUtf8(data);
content.remove(QLatin1Char('\r'));
@@ -220,7 +226,7 @@ void PasteBinDotCaProtocol::listFinished()
{
const bool error = m_listReply->error();
if (error)
- qWarning("pastebin.ca list failed: %s", qPrintable(m_listReply->errorString()));
+ qWarning("%s list failed: %s", protocolNameC, qPrintable(m_listReply->errorString()));
else
emit listDone(name(), parseLists(m_listReply));
m_listReply->deleteLater();
diff --git a/src/plugins/cpaster/pastebindotcaprotocol.h b/src/plugins/cpaster/pastebindotcaprotocol.h
index 181220f5d1..1a091e9a95 100644
--- a/src/plugins/cpaster/pastebindotcaprotocol.h
+++ b/src/plugins/cpaster/pastebindotcaprotocol.h
@@ -39,7 +39,7 @@ class PasteBinDotCaProtocol : public NetworkProtocol
public:
explicit PasteBinDotCaProtocol();
- static QString protocolName() { return QLatin1String("Pastebin.Ca"); }
+ static QString protocolName();
QString name() const { return protocolName(); }
virtual bool hasSettings() const { return false; }
diff --git a/src/plugins/cpaster/pastebindotcomprotocol.cpp b/src/plugins/cpaster/pastebindotcomprotocol.cpp
index a7de02335a..ccfd920a3c 100644
--- a/src/plugins/cpaster/pastebindotcomprotocol.cpp
+++ b/src/plugins/cpaster/pastebindotcomprotocol.cpp
@@ -48,6 +48,8 @@ static const char PASTEBIN_ARCHIVE[]="archive";
static const char API_KEY[]="api_dev_key=516686fc461fb7f9341fd7cf2af6f829&"; // user: qtcreator_apikey
+static const char PROTOCOL_NAME[] = "Pastebin.Com";
+
namespace CodePaster {
PasteBinDotComProtocol::PasteBinDotComProtocol() :
m_fetchReply(0),
@@ -61,12 +63,12 @@ PasteBinDotComProtocol::PasteBinDotComProtocol() :
QString PasteBinDotComProtocol::protocolName()
{
- return QLatin1String("Pastebin.Com");
+ return QLatin1String(PROTOCOL_NAME);
}
unsigned PasteBinDotComProtocol::capabilities() const
{
- return ListCapability;
+ return ListCapability | PostDescriptionCapability;
}
static inline QByteArray format(Protocol::ContentType ct)
@@ -112,7 +114,7 @@ static inline QByteArray expirySpecification(int expiryDays)
void PasteBinDotComProtocol::paste(const QString &text,
ContentType ct, int expiryDays,
- const QString &username,
+ const QString & /* username */, // Not used unless registered user
const QString &comment,
const QString &description)
{
@@ -127,8 +129,8 @@ void PasteBinDotComProtocol::paste(const QString &text,
pasteData += expirySpecification(expiryDays);
pasteData += '&';
pasteData += format(ct);
- pasteData += "api_paste_name=";
- pasteData += QUrl::toPercentEncoding(username);
+ pasteData += "api_paste_name="; // Title or name.
+ pasteData += QUrl::toPercentEncoding(description);
pasteData += "&api_paste_code=";
pasteData += QUrl::toPercentEncoding(fixNewLines(text));
// fire request
@@ -141,7 +143,7 @@ void PasteBinDotComProtocol::paste(const QString &text,
void PasteBinDotComProtocol::pasteFinished()
{
if (m_pasteReply->error())
- qWarning("Pastebin.com protocol error: %s", qPrintable(m_pasteReply->errorString()));
+ qWarning("%s protocol error: %s", PROTOCOL_NAME, qPrintable(m_pasteReply->errorString()));
else
emit pasteDone(QString::fromLatin1(m_pasteReply->readAll()));
@@ -178,7 +180,7 @@ void PasteBinDotComProtocol::fetchFinished()
if (debug)
qDebug() << "fetchFinished: error" << m_fetchId << content;
} else {
- title = QString::fromLatin1("Pastebin.com: %1").arg(m_fetchId);
+ title = QLatin1String(PROTOCOL_NAME) + QLatin1String(": ") + m_fetchId;
content = QString::fromLatin1(m_fetchReply->readAll());
// Cut out from '<pre>' formatting
const int preEnd = content.lastIndexOf(QLatin1String("</pre>"));
@@ -214,13 +216,6 @@ void PasteBinDotComProtocol::list()
qDebug() << "list: sending " << url << m_listReply;
}
-static inline void padString(QString *s, int len)
-{
- const int missing = len - s->length();
- if (missing > 0)
- s->append(QString(missing, QLatin1Char(' ')));
-}
-
/* Quick & dirty: Parse out the 'archive' table as of 16.3.2011:
\code
<table class="maintable" cellspacing="0">
diff --git a/src/plugins/cpaster/pasteview.cpp b/src/plugins/cpaster/pasteview.cpp
index f8de8f9533..7ac1af9f4e 100644
--- a/src/plugins/cpaster/pasteview.cpp
+++ b/src/plugins/cpaster/pasteview.cpp
@@ -114,6 +114,7 @@ void PasteView::protocolChanged(int p)
{
const unsigned caps = m_protocols.at(p)->capabilities();
m_ui.uiDescription->setEnabled(caps & Protocol::PostDescriptionCapability);
+ m_ui.uiUsername->setEnabled(caps & Protocol::PostUserNameCapability);
m_ui.uiComment->setEnabled(caps & Protocol::PostCommentCapability);
}
diff --git a/src/plugins/cpaster/pasteview.h b/src/plugins/cpaster/pasteview.h
index acb2c2fae1..1b027dc83b 100644
--- a/src/plugins/cpaster/pasteview.h
+++ b/src/plugins/cpaster/pasteview.h
@@ -31,7 +31,8 @@
#define PASTEVIEW_H
#include "ui_pasteview.h"
-#include "splitter.h"
+
+#include <splitter.h>
#include <QDialog>
diff --git a/src/plugins/cpaster/pasteview.ui b/src/plugins/cpaster/pasteview.ui
index 714826778a..aa7675fb0a 100644
--- a/src/plugins/cpaster/pasteview.ui
+++ b/src/plugins/cpaster/pasteview.ui
@@ -216,7 +216,7 @@ p, li { white-space: pre-wrap; }
<customwidget>
<class>CodePaster::ColumnIndicatorTextEdit</class>
<extends>QTextEdit</extends>
- <header>columnindicatortextedit.h</header>
+ <header location="global">cpaster/columnindicatortextedit.h</header>
</customwidget>
</customwidgets>
<tabstops>
diff --git a/src/plugins/cpaster/protocol.cpp b/src/plugins/cpaster/protocol.cpp
index 8d9e1fd61a..bc07a8fed9 100644
--- a/src/plugins/cpaster/protocol.cpp
+++ b/src/plugins/cpaster/protocol.cpp
@@ -92,6 +92,7 @@ Protocol::ContentType Protocol::contentType(const QString &mt)
return C;
if (mt == QLatin1String(CppTools::Constants::CPP_SOURCE_MIMETYPE)
|| mt == QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE)
+ || mt == QLatin1String(CppTools::Constants::OBJECTIVE_C_SOURCE_MIMETYPE)
|| mt == QLatin1String(CppTools::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE))
return Cpp;
if (mt == QLatin1String(QmlJSTools::Constants::QML_MIMETYPE)
diff --git a/src/plugins/cpaster/protocol.h b/src/plugins/cpaster/protocol.h
index 343dfeb5db..a2036aabbf 100644
--- a/src/plugins/cpaster/protocol.h
+++ b/src/plugins/cpaster/protocol.h
@@ -58,7 +58,8 @@ public:
enum Capabilities {
ListCapability = 0x1,
PostCommentCapability = 0x2,
- PostDescriptionCapability = 0x4
+ PostDescriptionCapability = 0x4,
+ PostUserNameCapability = 0x8
};
virtual ~Protocol();
diff --git a/src/plugins/cppeditor/CppEditor.mimetypes.xml b/src/plugins/cppeditor/CppEditor.mimetypes.xml
index 11600c9cba..37eeb170a5 100644
--- a/src/plugins/cppeditor/CppEditor.mimetypes.xml
+++ b/src/plugins/cppeditor/CppEditor.mimetypes.xml
@@ -63,10 +63,13 @@
<mime-type type="text/x-objcsrc">
<comment>Objective-C source code</comment>
<sub-class-of type="text/x-csrc"/>
- <magic priority="30">
- <match value="#import" type="string" offset="0"/>
- </magic>
<glob pattern="*.m"/>
+ </mime-type>
+
+ <mime-type type="text/x-objc++src">
+ <comment>Objective-C++ source code</comment>
+ <sub-class-of type="text/x-c++src"/>
+ <sub-class-of type="text/x-objcsrc"/>
<glob pattern="*.mm"/>
</mime-type>
diff --git a/src/plugins/cppeditor/CppEditor.pluginspec.in b/src/plugins/cppeditor/CppEditor.pluginspec.in
index 8f6e5e10da..34fd5afb06 100644
--- a/src/plugins/cppeditor/CppEditor.pluginspec.in
+++ b/src/plugins/cppeditor/CppEditor.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"CppEditor\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"CppEditor\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/cppeditor/cppautocompleter.cpp b/src/plugins/cppeditor/cppautocompleter.cpp
index 169a341570..f7e9233bb2 100644
--- a/src/plugins/cppeditor/cppautocompleter.cpp
+++ b/src/plugins/cppeditor/cppautocompleter.cpp
@@ -50,12 +50,12 @@ bool CppAutoCompleter::contextAllowsAutoParentheses(const QTextCursor &cursor,
{
QChar ch;
- if (! textToInsert.isEmpty())
+ if (!textToInsert.isEmpty())
ch = textToInsert.at(0);
- if (! (MatchingText::shouldInsertMatchingText(cursor)
- || ch == QLatin1Char('\'')
- || ch == QLatin1Char('"')))
+ if (!(MatchingText::shouldInsertMatchingText(cursor)
+ || ch == QLatin1Char('\'')
+ || ch == QLatin1Char('"')))
return false;
else if (isInCommentHelper(cursor))
return false;
diff --git a/src/plugins/cppeditor/cppclasswizard.cpp b/src/plugins/cppeditor/cppclasswizard.cpp
index 70e22afd16..d56ea5cc5d 100644
--- a/src/plugins/cppeditor/cppclasswizard.cpp
+++ b/src/plugins/cppeditor/cppclasswizard.cpp
@@ -96,9 +96,8 @@ static bool lowerCaseFiles()
// Set up new class widget from settings
void ClassNamePage::initParameters()
{
- const Core::MimeDatabase *mdb = Core::ICore::mimeDatabase();
- m_newClassWidget->setHeaderExtension(mdb->preferredSuffixByType(QLatin1String(Constants::CPP_HEADER_MIMETYPE)));
- m_newClassWidget->setSourceExtension(mdb->preferredSuffixByType(QLatin1String(Constants::CPP_SOURCE_MIMETYPE)));
+ m_newClassWidget->setHeaderExtension(Core::MimeDatabase::preferredSuffixByType(QLatin1String(Constants::CPP_HEADER_MIMETYPE)));
+ m_newClassWidget->setSourceExtension(Core::MimeDatabase::preferredSuffixByType(QLatin1String(Constants::CPP_SOURCE_MIMETYPE)));
m_newClassWidget->setLowerCaseFiles(lowerCaseFiles());
}
@@ -141,17 +140,10 @@ CppClassWizardParameters CppClassWizardDialog::parameters() const
// ========= CppClassWizard =========
-CppClassWizard::CppClassWizard(const Core::BaseFileWizardParameters &parameters,
- QObject *parent)
- : Core::BaseFileWizard(parameters, parent)
+CppClassWizard::CppClassWizard()
{
}
-Core::FeatureSet CppClassWizard::requiredFeatures() const
-{
- return Core::FeatureSet();
-}
-
QString CppClassWizard::sourceSuffix() const
{
return preferredSuffix(QLatin1String(Constants::CPP_SOURCE_MIMETYPE));
diff --git a/src/plugins/cppeditor/cppclasswizard.h b/src/plugins/cppeditor/cppclasswizard.h
index 0fe581e278..7fc40ec74e 100644
--- a/src/plugins/cppeditor/cppclasswizard.h
+++ b/src/plugins/cppeditor/cppclasswizard.h
@@ -96,25 +96,20 @@ class CppClassWizard : public Core::BaseFileWizard
Q_OBJECT
public:
- explicit CppClassWizard(const Core::BaseFileWizardParameters &parameters,
- QObject *parent = 0);
+ CppClassWizard();
- virtual Core::FeatureSet requiredFeatures() const;
-
-protected:
- virtual QWizard *createWizardDialog(QWidget *parent,
+private:
+ QWizard *createWizardDialog(QWidget *parent,
const Core::WizardDialogParameters &wizardDialogParameters) const;
- virtual Core::GeneratedFiles generateFiles(const QWizard *w,
+ Core::GeneratedFiles generateFiles(const QWizard *w,
QString *errorMessage) const;
QString sourceSuffix() const;
QString headerSuffix() const;
-private:
static bool generateHeaderAndSource(const CppClassWizardParameters &params,
QString *header, QString *source);
-
};
} // namespace Internal
diff --git a/src/plugins/cppeditor/cppeditor.cpp b/src/plugins/cppeditor/cppeditor.cpp
index a7ba65664d..8475ce10d1 100644
--- a/src/plugins/cppeditor/cppeditor.cpp
+++ b/src/plugins/cppeditor/cppeditor.cpp
@@ -43,7 +43,7 @@
#include <cpptools/cpptoolsconstants.h>
#include <cpptools/cppchecksymbols.h>
#include <cpptools/cppcodeformatter.h>
-#include <cpptools/cppcompletionsupport.h>
+#include <cpptools/cppcompletionassistprovider.h>
#include <cpptools/cpphighlightingsupport.h>
#include <cpptools/cpplocalsymbols.h>
#include <cpptools/cppqtstyleindenter.h>
@@ -243,7 +243,7 @@ struct CanonicalSymbol
const QTextCursor &cursor,
QString *code)
{
- if (! info.doc)
+ if (!info.doc)
return 0;
QTextCursor tc = cursor;
@@ -255,8 +255,8 @@ struct CanonicalSymbol
int pos = tc.position();
- if (! isIdentifierChar(document->characterAt(pos)))
- if (! (pos > 0 && isIdentifierChar(document->characterAt(pos - 1))))
+ if (!isIdentifierChar(document->characterAt(pos)))
+ if (!(pos > 0 && isIdentifierChar(document->characterAt(pos - 1))))
return 0;
while (isIdentifierChar(document->characterAt(pos)))
@@ -293,7 +293,7 @@ struct CanonicalSymbol
const LookupItem &r = results.at(i);
Symbol *decl = r.declaration();
- if (! (decl && decl->enclosingScope()))
+ if (!(decl && decl->enclosingScope()))
break;
if (Class *classScope = r.declaration()->enclosingScope()->asClass()) {
@@ -303,7 +303,7 @@ struct CanonicalSymbol
if (classId && classId->isEqualTo(declId))
continue; // skip it, it's a ctor or a dtor.
- else if (Function *funTy = r.declaration()->type()->asFunctionType()) {
+ if (Function *funTy = r.declaration()->type()->asFunctionType()) {
if (funTy->isVirtual())
return r.declaration();
}
@@ -322,8 +322,6 @@ struct CanonicalSymbol
};
-int numberOfClosedEditors = 0;
-
/// Check if previous line is a CppStyle Doxygen Comment
bool isPreviousLineCppStyleComment(const QTextCursor &cursor)
{
@@ -512,7 +510,6 @@ CPPEditorWidget::CPPEditorWidget(QWidget *parent)
, m_firstRenameChange(false)
, m_objcEnabled(false)
, m_commentsSettings(CppTools::CppToolsSettings::instance()->commentsSettings())
- , m_completionSupport(0)
{
qRegisterMetaType<SemanticInfo>("CppTools::SemanticInfo");
@@ -533,8 +530,6 @@ CPPEditorWidget::CPPEditorWidget(QWidget *parent)
this, SLOT(updateSemanticInfo(CppTools::SemanticInfo)));
connect(editorSupport, SIGNAL(highlighterStarted(QFuture<TextEditor::HighlightingResult>*,uint)),
this, SLOT(highlighterStarted(QFuture<TextEditor::HighlightingResult>*,uint)));
-
- m_completionSupport = m_modelManager->completionSupport(editor());
}
m_highlightRevision = 0;
@@ -563,16 +558,7 @@ CPPEditorWidget::CPPEditorWidget(QWidget *parent)
CPPEditorWidget::~CPPEditorWidget()
{
if (m_modelManager)
- m_modelManager->deleteEditorSupport(editor());
-
- ++numberOfClosedEditors;
- if (numberOfClosedEditors == 5) {
- if (m_modelManager)
- m_modelManager->GC();
- numberOfClosedEditors = 0;
- }
-
- delete m_completionSupport;
+ m_modelManager->deleteCppEditorSupport(editor());
}
TextEditor::BaseTextEditor *CPPEditorWidget::createEditor()
@@ -644,7 +630,6 @@ void CPPEditorWidget::createToolBar(CPPEditor *editor)
// set up slots to document changes
updateContentsChangedSignal();
- connect(editorDocument(), SIGNAL(changed()), this, SLOT(updateFileName()));
// set up function declaration - definition link
connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(updateFunctionDeclDefLink()));
@@ -710,7 +695,8 @@ CppModelManagerInterface *CPPEditorWidget::modelManager() const
void CPPEditorWidget::setMimeType(const QString &mt)
{
BaseTextEditorWidget::setMimeType(mt);
- setObjCEnabled(mt == QLatin1String(CppTools::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE));
+ setObjCEnabled(mt == QLatin1String(CppTools::Constants::OBJECTIVE_C_SOURCE_MIMETYPE)
+ || mt == QLatin1String(CppTools::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE));
}
void CPPEditorWidget::setObjCEnabled(bool onoff)
@@ -779,7 +765,7 @@ void CPPEditorWidget::onDocumentUpdated()
const Macro *CPPEditorWidget::findCanonicalMacro(const QTextCursor &cursor, Document::Ptr doc) const
{
- if (! doc)
+ if (!doc)
return 0;
int line, col;
@@ -891,7 +877,7 @@ void CPPEditorWidget::markSymbols(const QTextCursor &tc, const SemanticInfo &inf
{
abortRename();
- if (! info.doc)
+ if (!info.doc)
return;
if (const Macro *macro = findCanonicalMacro(textCursor(), info.doc)) {
@@ -942,7 +928,7 @@ void CPPEditorWidget::markSymbols(const QTextCursor &tc, const SemanticInfo &inf
} else {
const QList<QTextEdit::ExtraSelection> selections = extraSelections(CodeSemanticsSelection);
- if (! selections.isEmpty())
+ if (!selections.isEmpty())
setExtraSelections(CodeSemanticsSelection, QList<QTextEdit::ExtraSelection>());
}
}
@@ -1000,9 +986,6 @@ void CPPEditorWidget::onContentsChanged(int position, int charsRemoved, int char
updateUses();
}
-void CPPEditorWidget::updateFileName()
-{}
-
void CPPEditorWidget::jumpToOutlineElement(int index)
{
QModelIndex modelIndex = m_outlineCombo->view()->currentIndex();
@@ -1019,7 +1002,7 @@ void CPPEditorWidget::jumpToOutlineElement(int index)
modelIndex = m_proxyModel->index(index, 0); // toplevel index
QModelIndex sourceIndex = m_proxyModel->mapToSource(modelIndex);
Symbol *symbol = m_outlineModel->symbolFromIndex(sourceIndex);
- if (! symbol)
+ if (!symbol)
return;
openCppEditorAt(linkToSymbol(symbol));
@@ -1047,7 +1030,7 @@ bool CPPEditorWidget::sortedOutline() const
void CPPEditorWidget::updateOutlineNow()
{
const Snapshot snapshot = m_modelManager->snapshot();
- Document::Ptr document = snapshot.document(editorDocument()->fileName());
+ Document::Ptr document = snapshot.document(editorDocument()->filePath());
if (!document)
return;
@@ -1256,10 +1239,10 @@ static inline LookupItem skipForwardDeclarations(const QList<LookupItem> &resolv
const FullySpecifiedType ty = result.type().simplified();
if (ty->isForwardClassDeclarationType()) {
- while (! candidates.isEmpty()) {
+ while (!candidates.isEmpty()) {
LookupItem r = candidates.takeFirst();
- if (! r.type()->isForwardClassDeclarationType()) {
+ if (!r.type()->isForwardClassDeclarationType()) {
result = r;
break;
}
@@ -1267,10 +1250,10 @@ static inline LookupItem skipForwardDeclarations(const QList<LookupItem> &resolv
}
if (ty->isObjCForwardClassDeclarationType()) {
- while (! candidates.isEmpty()) {
+ while (!candidates.isEmpty()) {
LookupItem r = candidates.takeFirst();
- if (! r.type()->isObjCForwardClassDeclarationType()) {
+ if (!r.type()->isObjCForwardClassDeclarationType()) {
result = r;
break;
}
@@ -1278,10 +1261,10 @@ static inline LookupItem skipForwardDeclarations(const QList<LookupItem> &resolv
}
if (ty->isObjCForwardProtocolDeclarationType()) {
- while (! candidates.isEmpty()) {
+ while (!candidates.isEmpty()) {
LookupItem r = candidates.takeFirst();
- if (! r.type()->isObjCForwardProtocolDeclarationType()) {
+ if (!r.type()->isObjCForwardProtocolDeclarationType()) {
result = r;
break;
}
@@ -1367,7 +1350,7 @@ CPPEditorWidget::Link CPPEditorWidget::attemptFuncDeclDef(const QTextCursor &cur
CPPEditorWidget::Link CPPEditorWidget::findMacroLink(const QByteArray &name) const
{
- if (! name.isEmpty()) {
+ if (!name.isEmpty()) {
if (Document::Ptr doc = m_lastSemanticInfo.doc) {
const Snapshot snapshot = m_modelManager->snapshot();
QSet<QString> processed;
@@ -1383,7 +1366,7 @@ CPPEditorWidget::Link CPPEditorWidget::findMacroLink(const QByteArray &name,
const Snapshot &snapshot,
QSet<QString> *processed) const
{
- if (doc && ! name.startsWith('<') && ! processed->contains(doc->fileName())) {
+ if (doc && !name.startsWith('<') && !processed->contains(doc->fileName())) {
processed->insert(doc->fileName());
foreach (const Macro &macro, doc->definedMacros()) {
@@ -1395,7 +1378,7 @@ CPPEditorWidget::Link CPPEditorWidget::findMacroLink(const QByteArray &name,
}
}
- const QList<Document::Include> includes = doc->includes();
+ const QList<Document::Include> includes = doc->resolvedIncludes();
for (int index = includes.size() - 1; index != -1; --index) {
const Document::Include &i = includes.at(index);
Link link = findMacroLink(name, snapshot.document(i.resolvedFileName()), snapshot,
@@ -1432,7 +1415,7 @@ CPPEditorWidget::Link CPPEditorWidget::findLinkAt(const QTextCursor &cursor, boo
const Snapshot &snapshot = m_modelManager->snapshot();
- // Try to macth decl/def. For this we need the semantic doc with the AST.
+ // Try to match decl/def. For this we need the semantic doc with the AST.
if (m_lastSemanticInfo.doc
&& m_lastSemanticInfo.doc->translationUnit()
&& m_lastSemanticInfo.doc->translationUnit()->ast()) {
@@ -1481,11 +1464,10 @@ CPPEditorWidget::Link CPPEditorWidget::findLinkAt(const QTextCursor &cursor, boo
int depth = 0;
for (; j < tokens.size(); ++j) {
- if (tokens.at(j).is(T_LPAREN))
+ if (tokens.at(j).is(T_LPAREN)) {
++depth;
-
- else if (tokens.at(j).is(T_RPAREN)) {
- if (! --depth)
+ } else if (tokens.at(j).is(T_RPAREN)) {
+ if (!--depth)
break;
}
}
@@ -1506,7 +1488,7 @@ CPPEditorWidget::Link CPPEditorWidget::findLinkAt(const QTextCursor &cursor, boo
}
// Now we prefer the doc from the snapshot with macros expanded.
- Document::Ptr doc = snapshot.document(editorDocument()->fileName());
+ Document::Ptr doc = snapshot.document(editorDocument()->filePath());
if (!doc) {
doc = m_lastSemanticInfo.doc;
if (!doc)
@@ -1517,7 +1499,7 @@ CPPEditorWidget::Link CPPEditorWidget::findLinkAt(const QTextCursor &cursor, boo
const QTextBlock block = tc.block();
int pos = cursor.positionInBlock();
QChar ch = document()->characterAt(cursor.position());
- if (pos > 0 && ! (ch.isLetterOrNumber() || ch == QLatin1Char('_')))
+ if (pos > 0 && !(ch.isLetterOrNumber() || ch == QLatin1Char('_')))
--pos; // positionInBlock points to a delimiter character.
const Token tk = SimpleLexer::tokenAt(block.text(), pos,
BackwardsScanner::previousBlockState(block), true);
@@ -1528,7 +1510,7 @@ CPPEditorWidget::Link CPPEditorWidget::findLinkAt(const QTextCursor &cursor, boo
// Handle include directives
if (tk.is(T_STRING_LITERAL) || tk.is(T_ANGLE_STRING_LITERAL)) {
const unsigned lineno = cursor.blockNumber() + 1;
- foreach (const Document::Include &incl, doc->includes()) {
+ foreach (const Document::Include &incl, doc->resolvedIncludes()) {
if (incl.line() == lineno) {
link.targetFileName = incl.resolvedFileName();
link.linkTextStart = beginOfToken + 1;
@@ -1576,15 +1558,13 @@ CPPEditorWidget::Link CPPEditorWidget::findLinkAt(const QTextCursor &cursor, boo
const QChar ch = document()->characterAt(pos);
if (ch.isSpace())
continue;
- else {
- if (ch == QLatin1Char('(') && ! expression.isEmpty()) {
- tc.setPosition(pos);
- if (TextEditor::TextBlockUserData::findNextClosingParenthesis(&tc, true))
- expression.append(tc.selectedText());
- }
-
- break;
+ if (ch == QLatin1Char('(') && !expression.isEmpty()) {
+ tc.setPosition(pos);
+ if (TextEditor::TextBlockUserData::findNextClosingParenthesis(&tc, true))
+ expression.append(tc.selectedText());
}
+
+ break;
}
TypeOfExpression typeOfExpression;
@@ -1600,7 +1580,7 @@ CPPEditorWidget::Link CPPEditorWidget::findLinkAt(const QTextCursor &cursor, boo
foreach (const LookupItem &r, resolvedSymbols) {
if (Symbol *d = r.declaration()) {
if (d->isDeclaration() || d->isFunction()) {
- if (editorDocument()->fileName() == QString::fromUtf8(d->fileName(), d->fileNameLength())) {
+ if (editorDocument()->filePath() == QString::fromUtf8(d->fileName(), d->fileNameLength())) {
if (unsigned(lineNumber) == d->line() && unsigned(positionInBlock) >= d->column()) { // ### TODO: check the end
result = r; // take the symbol under cursor.
break;
@@ -1659,7 +1639,7 @@ Symbol *CPPEditorWidget::findDefinition(Symbol *symbol, const Snapshot &snapshot
if (symbol->isFunction())
return 0; // symbol is a function definition.
- else if (! symbol->type()->isFunctionType())
+ else if (!symbol->type()->isFunctionType())
return 0; // not a function declaration
return symbolFinder()->findMatchingDefinition(symbol, snapshot);
@@ -1740,7 +1720,7 @@ void CPPEditorWidget::contextMenuEvent(QContextMenuEvent *e)
QSignalMapper mapper;
connect(&mapper, SIGNAL(mapped(int)), this, SLOT(performQuickFix(int)));
- if (! isOutdated()) {
+ if (!isOutdated()) {
TextEditor::IAssistInterface *interface =
createAssistInterface(TextEditor::QuickFix, TextEditor::ExplicitlyInvoked);
if (interface) {
@@ -1878,15 +1858,14 @@ Core::IEditor *CPPEditor::duplicate(QWidget *parent)
Core::Id CPPEditor::id() const
{
- return Core::Id(CppEditor::Constants::CPPEDITOR_ID);
+ return CppEditor::Constants::CPPEDITOR_ID;
}
bool CPPEditor::open(QString *errorString, const QString &fileName, const QString &realFileName)
{
if (!TextEditor::BaseTextEditor::open(errorString, fileName, realFileName))
return false;
- editorWidget()->setMimeType(
- Core::ICore::mimeDatabase()->findByFile(QFileInfo(fileName)).type());
+ editorWidget()->setMimeType(Core::MimeDatabase::findByFile(QFileInfo(fileName)).type());
return true;
}
@@ -1895,17 +1874,18 @@ const Utils::CommentDefinition *CPPEditor::commentDefinition() const
return &m_commentDefinition;
}
+TextEditor::CompletionAssistProvider *CPPEditor::completionAssistProvider()
+{
+ return CppModelManagerInterface::instance()->cppEditorSupport(this)->completionAssistProvider();
+}
+
void CPPEditorWidget::setFontSettings(const TextEditor::FontSettings &fs)
{
TextEditor::BaseTextEditorWidget::setFontSettings(fs);
- CppHighlighter *highlighter
- = qobject_cast<CppHighlighter*>(baseTextDocument()->syntaxHighlighter());
+ TextEditor::SyntaxHighlighter *highlighter = baseTextDocument()->syntaxHighlighter();
if (!highlighter)
return;
- const QVector<QTextCharFormat> formats = fs.toTextCharFormats(highlighterFormatCategories());
- highlighter->setFormats(formats.constBegin(), formats.constEnd());
-
m_occurrencesFormat = fs.toTextCharFormat(TextEditor::C_OCCURRENCES);
m_occurrencesUnusedFormat = fs.toTextCharFormat(TextEditor::C_OCCURRENCES_UNUSED);
m_occurrencesUnusedFormat.setUnderlineStyle(QTextCharFormat::WaveUnderline);
@@ -2038,7 +2018,7 @@ void CPPEditorWidget::updateSemanticInfo(const SemanticInfo &semanticInfo)
// We can use the semanticInfo's snapshot (and avoid locking), but not its
// document, since it doesn't contain expanded macros.
- LookupContext context(semanticInfo.snapshot.document(editorDocument()->fileName()),
+ LookupContext context(semanticInfo.snapshot.document(editorDocument()->filePath()),
semanticInfo.snapshot);
SemanticInfo::LocalUseIterator it(semanticInfo.localUses);
@@ -2068,11 +2048,10 @@ void CPPEditorWidget::updateSemanticInfo(const SemanticInfo &semanticInfo)
setExtraSelections(UnusedSymbolSelection, unusedSelections);
- if (! m_renameSelections.isEmpty())
+ if (!m_renameSelections.isEmpty())
setExtraSelections(CodeSemanticsSelection, m_renameSelections); // ###
- else {
+ else
markSymbols(textCursor(), semanticInfo);
- }
m_lastSemanticInfo.forced = false; // clear the forced flag
@@ -2126,10 +2105,12 @@ TextEditor::IAssistInterface *CPPEditorWidget::createAssistInterface(
TextEditor::AssistReason reason) const
{
if (kind == TextEditor::Completion) {
- if (m_completionSupport)
- return m_completionSupport->createAssistInterface(
+ CppEditorSupport *ces = CppModelManagerInterface::instance()->cppEditorSupport(editor());
+ CppCompletionAssistProvider *cap = ces->completionAssistProvider();
+ if (cap)
+ return cap->createAssistInterface(
ProjectExplorer::ProjectExplorerPlugin::currentProject(),
- document(), position(), reason);
+ editor()->document()->filePath(), document(), position(), reason);
} else if (kind == TextEditor::QuickFix) {
if (!semanticInfo().doc || isOutdated())
return 0;
@@ -2201,14 +2182,14 @@ void CPPEditorWidget::onFunctionDeclDefLinkFound(QSharedPointer<FunctionDeclDefL
{
abortDeclDefLink();
m_declDefLink = link;
-
- // disable the link if content of the target editor changes
- TextEditor::BaseTextEditorWidget *targetEditor =
- TextEditor::RefactoringChanges::editorForFile(link->targetFile->fileName());
- if (targetEditor && targetEditor != this) {
- connect(targetEditor, SIGNAL(textChanged()),
- this, SLOT(abortDeclDefLink()));
+ Core::IDocument *targetDocument = Core::EditorManager::documentModel()->documentForFilePath(
+ m_declDefLink->targetFile->fileName());
+ if (editorDocument() != targetDocument) {
+ if (TextEditor::BaseTextDocument *baseTextDocument = qobject_cast<TextEditor::BaseTextDocument *>(targetDocument))
+ connect(baseTextDocument->document(), SIGNAL(contentsChanged()),
+ this, SLOT(abortDeclDefLink()));
}
+
}
void CPPEditorWidget::applyDeclDefLinkChanges(bool jumpToMatch)
@@ -2231,12 +2212,12 @@ void CPPEditorWidget::abortDeclDefLink()
if (!m_declDefLink)
return;
- // undo connect from onFunctionDeclDefLinkFound
- TextEditor::BaseTextEditorWidget *targetEditor =
- TextEditor::RefactoringChanges::editorForFile(m_declDefLink->targetFile->fileName());
- if (targetEditor && targetEditor != this) {
- disconnect(targetEditor, SIGNAL(textChanged()),
- this, SLOT(abortDeclDefLink()));
+ Core::IDocument *targetDocument = Core::EditorManager::documentModel()->documentForFilePath(
+ m_declDefLink->targetFile->fileName());
+ if (editorDocument() != targetDocument) {
+ if (TextEditor::BaseTextDocument *baseTextDocument = qobject_cast<TextEditor::BaseTextDocument *>(targetDocument))
+ disconnect(baseTextDocument->document(), SIGNAL(contentsChanged()),
+ this, SLOT(abortDeclDefLink()));
}
m_declDefLink->hideMarker(this);
diff --git a/src/plugins/cppeditor/cppeditor.h b/src/plugins/cppeditor/cppeditor.h
index 341d4fc872..5573df9cc3 100644
--- a/src/plugins/cppeditor/cppeditor.h
+++ b/src/plugins/cppeditor/cppeditor.h
@@ -79,10 +79,11 @@ public:
Core::IEditor *duplicate(QWidget *parent);
Core::Id id() const;
- bool isTemporary() const { return false; }
bool open(QString *errorString, const QString &fileName, const QString &realFileName);
const Utils::CommentDefinition *commentDefinition() const;
+ TextEditor::CompletionAssistProvider *completionAssistProvider();
+
private:
Utils::CommentDefinition m_commentDefinition;
};
@@ -159,7 +160,6 @@ protected Q_SLOTS:
void slotCodeStyleSettingsChanged(const QVariant &);
private Q_SLOTS:
- void updateFileName();
void jumpToOutlineElement(int index);
void updateOutlineNow();
void updateOutlineIndex();
@@ -262,8 +262,6 @@ private:
QSharedPointer<FunctionDeclDefLink> m_declDefLink;
CppTools::CommentsSettings m_commentsSettings;
-
- CppTools::CppCompletionSupport *m_completionSupport;
};
} // namespace Internal
diff --git a/src/plugins/cppeditor/cppeditor.pro b/src/plugins/cppeditor/cppeditor.pro
index d646ca23b1..d715c81e16 100644
--- a/src/plugins/cppeditor/cppeditor.pro
+++ b/src/plugins/cppeditor/cppeditor.pro
@@ -11,6 +11,7 @@ HEADERS += cppeditorplugin.h \
cppfilewizard.h \
cppfunctiondecldeflink.h \
cpphighlighter.h \
+ cpphighlighterfactory.h \
cpphoverhandler.h \
cppoutline.h \
cppquickfixassistant.h \
@@ -27,6 +28,7 @@ SOURCES += cppeditorplugin.cpp \
cppfilewizard.cpp \
cppfunctiondecldeflink.cpp \
cpphighlighter.cpp \
+ cpphighlighterfactory.cpp \
cpphoverhandler.cpp \
cppoutline.cpp \
cppquickfixassistant.cpp \
diff --git a/src/plugins/cppeditor/cppeditor.qbs b/src/plugins/cppeditor/cppeditor.qbs
index 39533511cd..c1b3ae2196 100644
--- a/src/plugins/cppeditor/cppeditor.qbs
+++ b/src/plugins/cppeditor/cppeditor.qbs
@@ -2,7 +2,6 @@ import qbs.base 1.0
import qbs.FileInfo
import "../QtcPlugin.qbs" as QtcPlugin
-import "../../../qbs/defaults.js" as Defaults
QtcPlugin {
name: "CppEditor"
@@ -14,8 +13,6 @@ QtcPlugin {
Depends { name: "TextEditor" }
Depends { name: "ProjectExplorer" }
- cpp.includePaths: base.concat("../../libs/3rdparty")
-
files: [
"cppautocompleter.cpp",
"cppautocompleter.h",
@@ -37,6 +34,8 @@ QtcPlugin {
"cppfunctiondecldeflink.h",
"cpphighlighter.cpp",
"cpphighlighter.h",
+ "cpphighlighterfactory.cpp",
+ "cpphighlighterfactory.h",
"cpphoverhandler.cpp",
"cpphoverhandler.h",
"cppoutline.cpp",
@@ -55,7 +54,7 @@ QtcPlugin {
Group {
name: "Tests"
- condition: Defaults.testsEnabled(qbs)
+ condition: project.testsEnabled
files: [
"cppdoxygen_test.cpp",
"cppquickfix_test.cpp",
diff --git a/src/plugins/cppeditor/cppeditorplugin.cpp b/src/plugins/cppeditor/cppeditorplugin.cpp
index 24c046e17b..3b939b49d0 100644
--- a/src/plugins/cppeditor/cppeditorplugin.cpp
+++ b/src/plugins/cppeditor/cppeditorplugin.cpp
@@ -39,6 +39,7 @@
#include "cppsnippetprovider.h"
#include "cppquickfixassistant.h"
#include "cppquickfixes.h"
+#include "cpphighlighterfactory.h"
#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/actionmanager/actionmanager.h>
@@ -56,6 +57,7 @@
#include <QCoreApplication>
#include <QStringList>
+using namespace Core;
using namespace CppEditor;
using namespace CppEditor::Internal;
@@ -68,34 +70,21 @@ enum { QUICKFIX_INTERVAL = 20 };
CppEditorFactory::CppEditorFactory(CppEditorPlugin *owner) :
m_owner(owner)
{
- m_mimeTypes << QLatin1String(CppEditor::Constants::C_SOURCE_MIMETYPE)
- << QLatin1String(CppEditor::Constants::C_HEADER_MIMETYPE)
- << QLatin1String(CppEditor::Constants::CPP_SOURCE_MIMETYPE)
- << QLatin1String(CppEditor::Constants::CPP_HEADER_MIMETYPE);
+ setId(CppEditor::Constants::CPPEDITOR_ID);
+ setDisplayName(qApp->translate("OpenWith::Editors", CppEditor::Constants::CPPEDITOR_DISPLAY_NAME));
+ addMimeType(CppEditor::Constants::C_SOURCE_MIMETYPE);
+ addMimeType(CppEditor::Constants::C_HEADER_MIMETYPE);
+ addMimeType(CppEditor::Constants::CPP_SOURCE_MIMETYPE);
+ addMimeType(CppEditor::Constants::CPP_HEADER_MIMETYPE);
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)));
+ FileIconProvider::registerIconOverlayForMimeType(":/cppeditor/images/qt_cpp.png", CppEditor::Constants::CPP_SOURCE_MIMETYPE);
+ FileIconProvider::registerIconOverlayForMimeType(":/cppeditor/images/qt_c.png", CppEditor::Constants::C_SOURCE_MIMETYPE);
+ FileIconProvider::registerIconOverlayForMimeType(":/cppeditor/images/qt_h.png", CppEditor::Constants::CPP_HEADER_MIMETYPE);
}
}
-Core::Id CppEditorFactory::id() const
-{
- return Core::Id(CppEditor::Constants::CPPEDITOR_ID);
-}
-
-QString CppEditorFactory::displayName() const
-{
- return qApp->translate("OpenWith::Editors", CppEditor::Constants::CPPEDITOR_DISPLAY_NAME);
-}
-
-Core::IEditor *CppEditorFactory::createEditor(QWidget *parent)
+IEditor *CppEditorFactory::createEditor(QWidget *parent)
{
CPPEditorWidget *editor = new CPPEditorWidget(parent);
editor->setRevisionsVisible(true);
@@ -103,11 +92,6 @@ Core::IEditor *CppEditorFactory::createEditor(QWidget *parent)
return editor->editor();
}
-QStringList CppEditorFactory::mimeTypes() const
-{
- return m_mimeTypes;
-}
-
///////////////////////////////// CppEditorPlugin //////////////////////////////////
CppEditorPlugin *CppEditorPlugin::m_instance = 0;
@@ -140,7 +124,7 @@ void CppEditorPlugin::initializeEditor(CPPEditorWidget *editor)
m_actionHandler->setupActions(editor);
editor->setLanguageSettingsId(CppTools::Constants::CPP_SETTINGS_ID);
- TextEditor::TextEditorSettings::instance()->initializeEditor(editor);
+ TextEditor::TextEditorSettings::initializeEditor(editor);
// method combo box sorting
connect(this, SIGNAL(outlineSortingChanged(bool)),
@@ -165,7 +149,7 @@ CppQuickFixAssistProvider *CppEditorPlugin::quickFixProvider() const
bool CppEditorPlugin::initialize(const QStringList & /*arguments*/, QString *errorMessage)
{
- if (!Core::ICore::mimeDatabase()->addMimeTypes(QLatin1String(":/cppeditor/CppEditor.mimetypes.xml"), errorMessage))
+ if (!Core::MimeDatabase::addMimeTypes(QLatin1String(":/cppeditor/CppEditor.mimetypes.xml"), errorMessage))
return false;
addAutoReleasedObject(new CppEditorFactory(this));
@@ -173,50 +157,58 @@ bool CppEditorPlugin::initialize(const QStringList & /*arguments*/, QString *err
addAutoReleasedObject(new CppOutlineWidgetFactory);
addAutoReleasedObject(new CppTypeHierarchyFactory);
addAutoReleasedObject(new CppSnippetProvider);
+ addAutoReleasedObject(new CppHighlighterFactory);
m_quickFixProvider = new CppQuickFixAssistProvider;
addAutoReleasedObject(m_quickFixProvider);
CppEditor::Internal::registerQuickFixes(this);
- QObject *core = Core::ICore::instance();
- CppFileWizard::BaseFileWizardParameters wizardParameters(Core::IWizard::FileWizard);
-
- wizardParameters.setCategory(QLatin1String(Constants::WIZARD_CATEGORY));
- wizardParameters.setDisplayCategory(QCoreApplication::translate(Constants::WIZARD_CATEGORY,
- Constants::WIZARD_TR_CATEGORY));
- wizardParameters.setDisplayName(tr("C++ Class"));
- wizardParameters.setId(QLatin1String("A.Class"));
- wizardParameters.setKind(Core::IWizard::ClassWizard);
- wizardParameters.setDescription(tr("Creates a C++ header and a source file for a new class that you can add to a C++ project."));
- addAutoReleasedObject(new CppClassWizard(wizardParameters, core));
-
- wizardParameters.setKind(Core::IWizard::FileWizard);
- wizardParameters.setDescription(tr("Creates a C++ source file that you can add to a C++ project."));
- wizardParameters.setDisplayName(tr("C++ Source File"));
- wizardParameters.setId(QLatin1String("B.Source"));
- addAutoReleasedObject(new CppFileWizard(wizardParameters, Source, core));
-
- wizardParameters.setDescription(tr("Creates a C++ header file that you can add to a C++ project."));
- wizardParameters.setDisplayName(tr("C++ Header File"));
- wizardParameters.setId(QLatin1String("C.Header"));
- addAutoReleasedObject(new CppFileWizard(wizardParameters, Header, core));
-
- Core::Context context(CppEditor::Constants::C_CPPEDITOR);
-
- Core::ActionContainer *contextMenu= Core::ActionManager::createMenu(CppEditor::Constants::M_CONTEXT);
-
- Core::Command *cmd;
- Core::ActionContainer *cppToolsMenu = Core::ActionManager::actionContainer(Core::Id(CppTools::Constants::M_TOOLS_CPP));
-
- cmd = Core::ActionManager::command(Core::Id(CppTools::Constants::SWITCH_HEADER_SOURCE));
+ QString trCat = QCoreApplication::translate(Constants::WIZARD_CATEGORY, Constants::WIZARD_TR_CATEGORY);
+
+ IWizard *wizard = new CppClassWizard;
+ wizard->setWizardKind(IWizard::ClassWizard);
+ wizard->setCategory(QLatin1String(Constants::WIZARD_CATEGORY));
+ wizard->setDisplayCategory(trCat);
+ wizard->setDisplayName(tr("C++ Class"));
+ wizard->setId(QLatin1String("A.Class"));
+ wizard->setDescription(tr("Creates a C++ header and a source file for a new class that you can add to a C++ project."));
+ addAutoReleasedObject(wizard);
+
+ wizard = new CppFileWizard(Source);
+ wizard->setWizardKind(IWizard::FileWizard);
+ wizard->setCategory(QLatin1String(Constants::WIZARD_CATEGORY));
+ wizard->setDisplayCategory(trCat);
+ wizard->setDisplayName(tr("C++ Class"));
+ wizard->setDescription(tr("Creates a C++ source file that you can add to a C++ project."));
+ wizard->setDisplayName(tr("C++ Source File"));
+ wizard->setId(QLatin1String("B.Source"));
+ addAutoReleasedObject(wizard);
+
+ wizard = new CppFileWizard(Header);
+ wizard->setWizardKind(IWizard::FileWizard);
+ wizard->setCategory(QLatin1String(Constants::WIZARD_CATEGORY));
+ wizard->setDisplayCategory(trCat);
+ wizard->setDescription(tr("Creates a C++ header file that you can add to a C++ project."));
+ wizard->setDisplayName(tr("C++ Header File"));
+ wizard->setId(QLatin1String("C.Header"));
+ addAutoReleasedObject(wizard);
+
+ Context context(CppEditor::Constants::C_CPPEDITOR);
+
+ ActionContainer *contextMenu = ActionManager::createMenu(CppEditor::Constants::M_CONTEXT);
+
+ Command *cmd;
+ ActionContainer *cppToolsMenu = ActionManager::actionContainer(CppTools::Constants::M_TOOLS_CPP);
+
+ cmd = ActionManager::command(CppTools::Constants::SWITCH_HEADER_SOURCE);
contextMenu->addAction(cmd);
- cmd = Core::ActionManager::command(TextEditor::Constants::FOLLOW_SYMBOL_UNDER_CURSOR);
+ cmd = ActionManager::command(TextEditor::Constants::FOLLOW_SYMBOL_UNDER_CURSOR);
contextMenu->addAction(cmd);
cppToolsMenu->addAction(cmd);
QAction *switchDeclarationDefinition = new QAction(tr("Switch Between Method Declaration/Definition"), this);
- cmd = Core::ActionManager::registerAction(switchDeclarationDefinition,
+ cmd = ActionManager::registerAction(switchDeclarationDefinition,
Constants::SWITCH_DECLARATION_DEFINITION, context, true);
cmd->setDefaultKeySequence(QKeySequence(tr("Shift+F2")));
connect(switchDeclarationDefinition, SIGNAL(triggered()),
@@ -224,12 +216,12 @@ bool CppEditorPlugin::initialize(const QStringList & /*arguments*/, QString *err
contextMenu->addAction(cmd);
cppToolsMenu->addAction(cmd);
- cmd = Core::ActionManager::command(TextEditor::Constants::FOLLOW_SYMBOL_UNDER_CURSOR_IN_NEXT_SPLIT);
+ cmd = ActionManager::command(TextEditor::Constants::FOLLOW_SYMBOL_UNDER_CURSOR_IN_NEXT_SPLIT);
cppToolsMenu->addAction(cmd);
QAction *openDeclarationDefinitionInNextSplit =
new QAction(tr("Open Method Declaration/Definition in Next Split"), this);
- cmd = Core::ActionManager::registerAction(openDeclarationDefinitionInNextSplit,
+ cmd = ActionManager::registerAction(openDeclarationDefinitionInNextSplit,
Constants::OPEN_DECLARATION_DEFINITION_IN_NEXT_SPLIT, context, true);
cmd->setDefaultKeySequence(QKeySequence(Utils::HostOsInfo::isMacHost()
? tr("Meta+E, Shift+F2")
@@ -239,28 +231,28 @@ bool CppEditorPlugin::initialize(const QStringList & /*arguments*/, QString *err
cppToolsMenu->addAction(cmd);
m_findUsagesAction = new QAction(tr("Find Usages"), this);
- cmd = Core::ActionManager::registerAction(m_findUsagesAction, Constants::FIND_USAGES, context);
+ cmd = ActionManager::registerAction(m_findUsagesAction, Constants::FIND_USAGES, context);
cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+Shift+U")));
connect(m_findUsagesAction, SIGNAL(triggered()), this, SLOT(findUsages()));
contextMenu->addAction(cmd);
cppToolsMenu->addAction(cmd);
m_openTypeHierarchyAction = new QAction(tr("Open Type Hierarchy"), this);
- cmd = Core::ActionManager::registerAction(m_openTypeHierarchyAction, Constants::OPEN_TYPE_HIERARCHY, context);
- cmd->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+Shift+T") : tr("Ctrl+Shift+T")));
+ cmd = ActionManager::registerAction(m_openTypeHierarchyAction, Constants::OPEN_TYPE_HIERARCHY, context);
+ cmd->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+Shift+T") : tr("Ctrl+Shift+T")));
connect(m_openTypeHierarchyAction, SIGNAL(triggered()), this, SLOT(openTypeHierarchy()));
contextMenu->addAction(cmd);
cppToolsMenu->addAction(cmd);
// Refactoring sub-menu
- Core::Context globalContext(Core::Constants::C_GLOBAL);
- Core::Command *sep = contextMenu->addSeparator(globalContext);
+ Context globalContext(Core::Constants::C_GLOBAL);
+ Command *sep = contextMenu->addSeparator(globalContext);
sep->action()->setObjectName(QLatin1String(Constants::M_REFACTORING_MENU_INSERTION_POINT));
contextMenu->addSeparator(globalContext);
m_renameSymbolUnderCursorAction = new QAction(tr("Rename Symbol Under Cursor"),
this);
- cmd = Core::ActionManager::registerAction(m_renameSymbolUnderCursorAction,
+ cmd = ActionManager::registerAction(m_renameSymbolUnderCursorAction,
Constants::RENAME_SYMBOL_UNDER_CURSOR,
context);
cmd->setDefaultKeySequence(QKeySequence(tr("CTRL+SHIFT+R")));
@@ -271,7 +263,7 @@ bool CppEditorPlugin::initialize(const QStringList & /*arguments*/, QString *err
// Update context in global context
cppToolsMenu->addSeparator(globalContext);
m_updateCodeModelAction = new QAction(tr("Update Code Model"), this);
- cmd = Core::ActionManager::registerAction(m_updateCodeModelAction, Core::Id(Constants::UPDATE_CODEMODEL), globalContext);
+ cmd = ActionManager::registerAction(m_updateCodeModelAction, Constants::UPDATE_CODEMODEL, globalContext);
CppTools::CppModelManagerInterface *cppModelManager = CppTools::CppModelManagerInterface::instance();
connect(m_updateCodeModelAction, SIGNAL(triggered()), cppModelManager, SLOT(updateModifiedSourceFiles()));
cppToolsMenu->addAction(cmd);
@@ -286,18 +278,19 @@ bool CppEditorPlugin::initialize(const QStringList & /*arguments*/, QString *err
contextMenu->addSeparator(context);
- cmd = Core::ActionManager::command(TextEditor::Constants::AUTO_INDENT_SELECTION);
+ cmd = ActionManager::command(TextEditor::Constants::AUTO_INDENT_SELECTION);
contextMenu->addAction(cmd);
- cmd = Core::ActionManager::command(TextEditor::Constants::UN_COMMENT_SELECTION);
+ cmd = ActionManager::command(TextEditor::Constants::UN_COMMENT_SELECTION);
contextMenu->addAction(cmd);
- connect(Core::ICore::progressManager(), SIGNAL(taskStarted(QString)),
- this, SLOT(onTaskStarted(QString)));
- connect(Core::ICore::progressManager(), SIGNAL(allTasksFinished(QString)),
- this, SLOT(onAllTasksFinished(QString)));
+ connect(ProgressManager::instance(), SIGNAL(taskStarted(Core::Id)),
+ this, SLOT(onTaskStarted(Core::Id)));
+ connect(ProgressManager::instance(), SIGNAL(allTasksFinished(Core::Id)),
+ this, SLOT(onAllTasksFinished(Core::Id)));
- connect(Core::ICore::editorManager(), SIGNAL(currentEditorChanged(Core::IEditor*)), SLOT(currentEditorChanged(Core::IEditor*)));
+ connect(EditorManager::instance(), SIGNAL(currentEditorChanged(Core::IEditor*)),
+ SLOT(currentEditorChanged(Core::IEditor*)));
readSettings();
return true;
@@ -305,12 +298,12 @@ bool CppEditorPlugin::initialize(const QStringList & /*arguments*/, QString *err
void CppEditorPlugin::readSettings()
{
- m_sortedOutline = Core::ICore::settings()->value(QLatin1String("CppTools/SortedMethodOverview"), false).toBool();
+ m_sortedOutline = ICore::settings()->value(QLatin1String("CppTools/SortedMethodOverview"), false).toBool();
}
void CppEditorPlugin::writeSettings()
{
- Core::ICore::settings()->setValue(QLatin1String("CppTools/SortedMethodOverview"), m_sortedOutline);
+ ICore::settings()->setValue(QLatin1String("CppTools/SortedMethodOverview"), m_sortedOutline);
}
void CppEditorPlugin::extensionsInitialized()
@@ -325,35 +318,35 @@ ExtensionSystem::IPlugin::ShutdownFlag CppEditorPlugin::aboutToShutdown()
void CppEditorPlugin::switchDeclarationDefinition()
{
- CPPEditorWidget *editor = qobject_cast<CPPEditorWidget*>(Core::EditorManager::currentEditor()->widget());
+ CPPEditorWidget *editor = qobject_cast<CPPEditorWidget*>(EditorManager::currentEditor()->widget());
if (editor)
editor->switchDeclarationDefinition(/*inNextSplit*/ false);
}
void CppEditorPlugin::openDeclarationDefinitionInNextSplit()
{
- CPPEditorWidget *editor = qobject_cast<CPPEditorWidget*>(Core::EditorManager::currentEditor()->widget());
+ CPPEditorWidget *editor = qobject_cast<CPPEditorWidget*>(EditorManager::currentEditor()->widget());
if (editor)
editor->switchDeclarationDefinition(/*inNextSplit*/ true);
}
void CppEditorPlugin::renameSymbolUnderCursor()
{
- CPPEditorWidget *editor = qobject_cast<CPPEditorWidget*>(Core::EditorManager::currentEditor()->widget());
+ CPPEditorWidget *editor = qobject_cast<CPPEditorWidget*>(EditorManager::currentEditor()->widget());
if (editor)
editor->renameSymbolUnderCursor();
}
void CppEditorPlugin::findUsages()
{
- CPPEditorWidget *editor = qobject_cast<CPPEditorWidget*>(Core::EditorManager::currentEditor()->widget());
+ CPPEditorWidget *editor = qobject_cast<CPPEditorWidget*>(EditorManager::currentEditor()->widget());
if (editor)
editor->findUsages();
}
-void CppEditorPlugin::onTaskStarted(const QString &type)
+void CppEditorPlugin::onTaskStarted(Core::Id type)
{
- if (type == QLatin1String(CppTools::Constants::TASK_INDEX)) {
+ if (type == CppTools::Constants::TASK_INDEX) {
m_renameSymbolUnderCursorAction->setEnabled(false);
m_findUsagesAction->setEnabled(false);
m_updateCodeModelAction->setEnabled(false);
@@ -361,9 +354,9 @@ void CppEditorPlugin::onTaskStarted(const QString &type)
}
}
-void CppEditorPlugin::onAllTasksFinished(const QString &type)
+void CppEditorPlugin::onAllTasksFinished(Core::Id type)
{
- if (type == QLatin1String(CppTools::Constants::TASK_INDEX)) {
+ if (type == CppTools::Constants::TASK_INDEX) {
m_renameSymbolUnderCursorAction->setEnabled(true);
m_findUsagesAction->setEnabled(true);
m_updateCodeModelAction->setEnabled(true);
@@ -371,22 +364,21 @@ void CppEditorPlugin::onAllTasksFinished(const QString &type)
}
}
-void CppEditorPlugin::currentEditorChanged(Core::IEditor *editor)
+void CppEditorPlugin::currentEditorChanged(IEditor *editor)
{
- if (! editor)
+ if (!editor)
return;
- else if (CPPEditorWidget *textEditor = qobject_cast<CPPEditorWidget *>(editor->widget())) {
+ if (CPPEditorWidget *textEditor = qobject_cast<CPPEditorWidget *>(editor->widget()))
textEditor->semanticRehighlight(/*force = */ true);
- }
}
void CppEditorPlugin::openTypeHierarchy()
{
- CPPEditorWidget *editor = qobject_cast<CPPEditorWidget*>(Core::EditorManager::currentEditor()->widget());
+ CPPEditorWidget *editor = qobject_cast<CPPEditorWidget*>(EditorManager::currentEditor()->widget());
if (editor) {
- Core::NavigationWidget *navigation = Core::NavigationWidget::instance();
- navigation->activateSubWidget(Core::Id(Constants::TYPE_HIERARCHY_ID));
+ NavigationWidget *navigation = NavigationWidget::instance();
+ navigation->activateSubWidget(Constants::TYPE_HIERARCHY_ID);
emit typeHierarchyRequested();
}
}
diff --git a/src/plugins/cppeditor/cppeditorplugin.h b/src/plugins/cppeditor/cppeditorplugin.h
index 93bc4368b2..2d53b3656b 100644
--- a/src/plugins/cppeditor/cppeditorplugin.h
+++ b/src/plugins/cppeditor/cppeditorplugin.h
@@ -35,7 +35,6 @@
#include <extensionsystem/iplugin.h>
#include <QtPlugin>
-#include <QStringList>
#include <QAction>
namespace TextEditor {
@@ -86,8 +85,8 @@ public slots:
void setSortedOutline(bool sorted);
private slots:
- void onTaskStarted(const QString &type);
- void onAllTasksFinished(const QString &type);
+ void onTaskStarted(Core::Id type);
+ void onAllTasksFinished(Core::Id type);
void currentEditorChanged(Core::IEditor *editor);
#ifdef WITH_TESTS
@@ -120,6 +119,8 @@ private slots:
void test_FollowSymbolUnderCursor_baseClassFunctionIntroducedByUsingDeclaration();
void test_FollowSymbolUnderCursor_funWithSameNameAsBaseClassFunIntroducedByUsingDeclaration();
void test_FollowSymbolUnderCursor_funLocalVarHidesOuterClass();
+ void test_FollowSymbolUnderCursor_classConstructor();
+ void test_FollowSymbolUnderCursor_classDestructor();
void test_FollowSymbolUnderCursor_using_QTCREATORBUG7903_globalNamespace();
void test_FollowSymbolUnderCursor_using_QTCREATORBUG7903_namespace();
void test_FollowSymbolUnderCursor_using_QTCREATORBUG7903_insideFunction();
@@ -156,6 +157,7 @@ private slots:
void test_quickfix_InsertDefFromDecl_afterClass();
void test_quickfix_InsertDefFromDecl_headerSource_basic1();
void test_quickfix_InsertDefFromDecl_headerSource_basic2();
+ void test_quickfix_InsertDefFromDecl_headerSource_basic3();
void test_quickfix_InsertDefFromDecl_headerSource_namespace1();
void test_quickfix_InsertDefFromDecl_headerSource_namespace2();
void test_quickfix_InsertDefFromDecl_freeFunction();
@@ -166,6 +168,9 @@ private slots:
void test_quickfix_InsertDefFromDecl_ignoreSurroundingGeneratedDeclarations();
void test_quickfix_InsertDefFromDecl_respectWsInOperatorNames1();
void test_quickfix_InsertDefFromDecl_respectWsInOperatorNames2();
+ void test_quickfix_InsertDefFromDecl_macroUsesAtEndOfFile1();
+ void test_quickfix_InsertDefFromDecl_macroUsesAtEndOfFile2();
+ void test_quickfix_InsertDefFromDecl_erroneousStatementAtEndOfFile();
void test_quickfix_InsertDeclFromDef();
@@ -247,6 +252,16 @@ private slots:
void test_quickfix_InsertVirtualMethods_notrigger_allImplemented();
void test_quickfix_InsertVirtualMethods_BaseClassInNamespace();
+ void test_quickfix_OptimizeForLoop_postcrement();
+ void test_quickfix_OptimizeForLoop_condition();
+ void test_quickfix_OptimizeForLoop_flipedCondition();
+ void test_quickfix_OptimizeForLoop_alterVariableName();
+ void test_quickfix_OptimizeForLoop_optimizeBoth();
+ void test_quickfix_OptimizeForLoop_emptyInitializer();
+ void test_quickfix_OptimizeForLoop_wrongInitializer();
+ void test_quickfix_OptimizeForLoop_noTriggerNumeric1();
+ void test_quickfix_OptimizeForLoop_noTriggerNumeric2();
+
// The following tests depend on the projects that are loaded on startup
// and will be skipped in case no projects are loaded.
void test_openEachFile();
@@ -287,15 +302,10 @@ class CppEditorFactory : public Core::IEditorFactory
public:
CppEditorFactory(CppEditorPlugin *owner);
- // IEditorFactory
- QStringList mimeTypes() const;
Core::IEditor *createEditor(QWidget *parent);
- Core::Id id() const;
- QString displayName() const;
private:
CppEditorPlugin *m_owner;
- QStringList m_mimeTypes;
};
} // namespace Internal
diff --git a/src/plugins/cppeditor/cppelementevaluator.cpp b/src/plugins/cppeditor/cppelementevaluator.cpp
index 34c4fd5ccb..c7cc6dfa68 100644
--- a/src/plugins/cppeditor/cppelementevaluator.cpp
+++ b/src/plugins/cppeditor/cppelementevaluator.cpp
@@ -85,7 +85,7 @@ void CppElementEvaluator::execute()
return;
const Snapshot &snapshot = m_modelManager->snapshot();
- Document::Ptr doc = snapshot.document(m_editor->editorDocument()->fileName());
+ Document::Ptr doc = snapshot.document(m_editor->editorDocument()->filePath());
if (!doc)
return;
@@ -113,7 +113,7 @@ void CppElementEvaluator::execute()
return;
const LookupItem &lookupItem = lookupItems.first(); // ### TODO: select best candidate.
- handleLookupItemMatch(snapshot, lookupItem, typeOfExpression.context());
+ handleLookupItemMatch(snapshot, lookupItem, typeOfExpression.context(), scope);
}
}
@@ -130,7 +130,7 @@ void CppElementEvaluator::checkDiagnosticMessage(int pos)
bool CppElementEvaluator::matchIncludeFile(const CPlusPlus::Document::Ptr &document, unsigned line)
{
- foreach (const Document::Include &includeFile, document->includes()) {
+ foreach (const Document::Include &includeFile, document->resolvedIncludes()) {
if (includeFile.line() == line) {
m_element = QSharedPointer<CppElement>(new CppInclude(includeFile));
return true;
@@ -155,11 +155,17 @@ bool CppElementEvaluator::matchMacroInUse(const CPlusPlus::Document::Ptr &docume
void CppElementEvaluator::handleLookupItemMatch(const Snapshot &snapshot,
const LookupItem &lookupItem,
- const LookupContext &context)
+ const LookupContext &context,
+ const Scope *scope)
{
Symbol *declaration = lookupItem.declaration();
if (!declaration) {
const QString &type = Overview().prettyType(lookupItem.type(), QString());
+ // special case for bug QTCREATORBUG-4780
+ if (scope && scope->isFunction()
+ && lookupItem.type().isEqualTo(scope->asFunction()->returnType())) {
+ return;
+ }
m_element = QSharedPointer<CppElement>(new Unknown(type));
} else {
const FullySpecifiedType &type = declaration->type();
diff --git a/src/plugins/cppeditor/cppelementevaluator.h b/src/plugins/cppeditor/cppelementevaluator.h
index 0c3876945f..33baf0eac6 100644
--- a/src/plugins/cppeditor/cppelementevaluator.h
+++ b/src/plugins/cppeditor/cppelementevaluator.h
@@ -76,7 +76,8 @@ private:
bool matchMacroInUse(const CPlusPlus::Document::Ptr &document, unsigned pos);
void handleLookupItemMatch(const CPlusPlus::Snapshot &snapshot,
const CPlusPlus::LookupItem &lookupItem,
- const CPlusPlus::LookupContext &lookupContext);
+ const CPlusPlus::LookupContext &lookupContext,
+ const CPlusPlus::Scope *scope);
CPPEditorWidget *m_editor;
CppTools::CppModelManagerInterface *m_modelManager;
diff --git a/src/plugins/cppeditor/cppfilewizard.cpp b/src/plugins/cppeditor/cppfilewizard.cpp
index 6fa07c58b2..262a2acaec 100644
--- a/src/plugins/cppeditor/cppfilewizard.cpp
+++ b/src/plugins/cppeditor/cppfilewizard.cpp
@@ -43,18 +43,14 @@ using namespace CppEditor::Internal;
enum { debugWizard = 0 };
-CppFileWizard::CppFileWizard(const BaseFileWizardParameters &parameters,
- FileType type,
- QObject *parent) :
- Core::StandardFileWizard(parameters, parent),
- m_type(type)
+CppFileWizard::CppFileWizard(FileType type)
+ : m_type(type)
{
}
Core::GeneratedFiles CppFileWizard::generateFilesFromPath(const QString &path,
const QString &name,
QString * /*errorMessage*/) const
-
{
const QString mimeType = m_type == Source ? QLatin1String(Constants::CPP_SOURCE_MIMETYPE) : QLatin1String(Constants::CPP_HEADER_MIMETYPE);
const QString fileName = Core::BaseFileWizard::buildFileName(path, name, preferredSuffix(mimeType));
diff --git a/src/plugins/cppeditor/cppfilewizard.h b/src/plugins/cppeditor/cppfilewizard.h
index 7b9f05174c..38bea28a47 100644
--- a/src/plugins/cppeditor/cppfilewizard.h
+++ b/src/plugins/cppeditor/cppfilewizard.h
@@ -42,16 +42,11 @@ class CppFileWizard : public Core::StandardFileWizard
Q_OBJECT
public:
- typedef Core::BaseFileWizardParameters BaseFileWizardParameters;
+ CppFileWizard(FileType type);
- CppFileWizard(const BaseFileWizardParameters &parameters,
- FileType type,
- QObject *parent = 0);
-
-protected:
+private:
QString fileContents(FileType type, const QString &baseName) const;
-protected:
Core::GeneratedFiles generateFilesFromPath(const QString &path,
const QString &fileName,
QString *errorMessage) const;
diff --git a/src/plugins/cppeditor/cppfunctiondecldeflink.cpp b/src/plugins/cppeditor/cppfunctiondecldeflink.cpp
index 2135ee25ad..4539875297 100644
--- a/src/plugins/cppeditor/cppfunctiondecldeflink.cpp
+++ b/src/plugins/cppeditor/cppfunctiondecldeflink.cpp
@@ -55,6 +55,7 @@ using namespace CppEditor;
using namespace CppEditor::Internal;
using namespace CppTools;
using namespace TextEditor;
+using namespace Utils;
FunctionDeclDefLinkFinder::FunctionDeclDefLinkFinder(QObject *parent)
: QObject(parent)
@@ -300,7 +301,7 @@ void FunctionDeclDefLink::apply(CPPEditorWidget *editor, bool jumpToMatch)
const int targetStart = newTargetFile->position(targetLine, targetColumn);
const int targetEnd = targetStart + targetInitial.size();
if (targetInitial == newTargetFile->textOf(targetStart, targetEnd)) {
- const Utils::ChangeSet changeset = changes(snapshot, targetStart);
+ const ChangeSet changeset = changes(snapshot, targetStart);
newTargetFile->setChangeSet(changeset);
if (jumpToMatch) {
const int jumpTarget = newTargetFile->position(targetFunction->line(), targetFunction->column());
@@ -308,10 +309,8 @@ void FunctionDeclDefLink::apply(CPPEditorWidget *editor, bool jumpToMatch)
}
newTargetFile->apply();
} else {
- Utils::ToolTip::instance()->show(
- editor->toolTipPosition(linkSelection),
- Utils::TextContent(
- tr("Target file was changed, could not apply changes")));
+ ToolTip::show(editor->toolTipPosition(linkSelection),
+ TextContent(tr("Target file was changed, could not apply changes")));
}
}
@@ -778,9 +777,8 @@ Utils::ChangeSet FunctionDeclDefLink::changes(const Snapshot &snapshot, int targ
FullySpecifiedType type = rewriteType(newParam->type(), &env, control);
newTargetParam = overview.prettyType(type, newParam->name());
hadChanges = true;
- }
// otherwise preserve as much as possible from the existing parameter
- else {
+ } else {
Symbol *targetParam = targetFunction->argumentAt(existingParamIndex);
Symbol *sourceParam = sourceFunction->argumentAt(existingParamIndex);
ParameterDeclarationAST *targetParamAst = targetParameterDecls.at(existingParamIndex);
@@ -833,9 +831,8 @@ Utils::ChangeSet FunctionDeclDefLink::changes(const Snapshot &snapshot, int targ
newTargetParam += overview.prettyType(replacementType, replacementName);
newTargetParam += targetFile->textOf(parameterTypeEnd, parameterEnd);
hadChanges = true;
- }
// change the name only?
- else if (!namesEqual(targetParam->name(), replacementName)) {
+ } else if (!namesEqual(targetParam->name(), replacementName)) {
DeclaratorIdAST *id = getDeclaratorId(targetParamAst->declarator);
const QString &replacementNameStr = overview.prettyName(replacementName);
if (id) {
@@ -878,9 +875,8 @@ Utils::ChangeSet FunctionDeclDefLink::changes(const Snapshot &snapshot, int targ
newTargetParam += rest;
}
hadChanges = true;
- }
// change nothing - though the parameter might still have moved
- else {
+ } else {
if (existingParamIndex != newParamIndex)
hadChanges = true;
newTargetParam = targetFile->textOf(parameterStart, parameterEnd);
@@ -934,9 +930,8 @@ Utils::ChangeSet FunctionDeclDefLink::changes(const Snapshot &snapshot, int targ
if (!targetFunction->isConst() && !targetFunction->isVolatile()) {
cvString.prepend(QLatin1Char(' '));
changes.insert(targetFile->endOf(targetFunctionDeclarator->rparen_token), cvString);
- }
// modify/remove existing specifiers
- else {
+ } else {
SimpleSpecifierAST *constSpecifier = 0;
SimpleSpecifierAST *volatileSpecifier = 0;
for (SpecifierListAST *it = targetFunctionDeclarator->cv_qualifier_list; it; it = it->next) {
@@ -954,9 +949,8 @@ Utils::ChangeSet FunctionDeclDefLink::changes(const Snapshot &snapshot, int targ
changes.remove(targetFile->endOf(constSpecifier->specifier_token - 1), targetFile->endOf(constSpecifier));
if (!newFunction->isVolatile())
changes.remove(targetFile->endOf(volatileSpecifier->specifier_token - 1), targetFile->endOf(volatileSpecifier));
- }
// otherwise adjust, remove or extend the one existing specifier
- else {
+ } else {
SimpleSpecifierAST *specifier = constSpecifier ? constSpecifier : volatileSpecifier;
QTC_ASSERT(specifier, return changes);
diff --git a/src/plugins/cppeditor/cpphighlighter.cpp b/src/plugins/cppeditor/cpphighlighter.cpp
index 5b02d92502..7e16616ed2 100644
--- a/src/plugins/cppeditor/cpphighlighter.cpp
+++ b/src/plugins/cppeditor/cpphighlighter.cpp
@@ -28,6 +28,7 @@
****************************************************************************/
#include "cpphighlighter.h"
+#include "cppeditorenums.h"
#include <cpptools/cppdoxygen.h>
#include <cpptools/cpptoolsreuse.h>
@@ -37,7 +38,6 @@
#include <cplusplus/Lexer.h>
#include <QTextDocument>
-#include <QDebug>
using namespace CppEditor::Internal;
using namespace TextEditor;
@@ -46,6 +46,21 @@ using namespace CPlusPlus;
CppHighlighter::CppHighlighter(QTextDocument *document) :
TextEditor::SyntaxHighlighter(document)
{
+ static QVector<TextEditor::TextStyle> categories;
+ if (categories.isEmpty()) {
+ categories << TextEditor::C_NUMBER
+ << TextEditor::C_STRING
+ << TextEditor::C_TYPE
+ << TextEditor::C_KEYWORD
+ << TextEditor::C_OPERATOR
+ << TextEditor::C_PREPROCESSOR
+ << TextEditor::C_LABEL
+ << TextEditor::C_COMMENT
+ << TextEditor::C_DOXYGEN_COMMENT
+ << TextEditor::C_DOXYGEN_TAG
+ << TextEditor::C_VISUAL_WHITESPACE;
+ }
+ setTextFormatCategories(categories);
}
void CppHighlighter::highlightBlock(const QString &text)
@@ -80,11 +95,11 @@ void CppHighlighter::highlightBlock(const QString &text)
BaseTextDocumentLayout::clearParentheses(currentBlock());
if (text.length()) {// the empty line can still contain whitespace
if (initialState == Lexer::State_MultiLineComment)
- highlightLine(text, 0, text.length(), m_formats[CppCommentFormat]);
+ highlightLine(text, 0, text.length(), formatForCategory(CppCommentFormat));
else if (initialState == Lexer::State_MultiLineDoxyComment)
- highlightLine(text, 0, text.length(), m_formats[CppDoxygenCommentFormat]);
+ highlightLine(text, 0, text.length(), formatForCategory(CppDoxygenCommentFormat));
else
- setFormat(0, text.length(), m_formats[CppVisualWhitespace]);
+ setFormat(0, text.length(), formatForCategory(CppVisualWhitespace));
}
BaseTextDocumentLayout::setFoldingIndent(currentBlock(), foldingIndent);
return;
@@ -109,7 +124,7 @@ void CppHighlighter::highlightBlock(const QString &text)
}
if (previousTokenEnd != tk.begin())
- setFormat(previousTokenEnd, tk.begin() - previousTokenEnd, m_formats[CppVisualWhitespace]);
+ setFormat(previousTokenEnd, tk.begin() - previousTokenEnd, formatForCategory(CppVisualWhitespace));
if (tk.is(T_LPAREN) || tk.is(T_LBRACE) || tk.is(T_LBRACKET)) {
const QChar c = text.at(tk.begin());
@@ -148,11 +163,11 @@ void CppHighlighter::highlightBlock(const QString &text)
continue;
if (i == 0 && tk.is(T_POUND)) {
- highlightLine(text, tk.begin(), tk.length(), m_formats[CppPreprocessorFormat]);
+ highlightLine(text, tk.begin(), tk.length(), formatForCategory(CppPreprocessorFormat));
expectPreprocessorKeyword = true;
} else if (highlightCurrentWordAsPreprocessor &&
(tk.isKeyword() || tk.is(T_IDENTIFIER)) && isPPKeyword(text.midRef(tk.begin(), tk.length()))) {
- setFormat(tk.begin(), tk.length(), m_formats[CppPreprocessorFormat]);
+ setFormat(tk.begin(), tk.length(), formatForCategory(CppPreprocessorFormat));
const QStringRef ppKeyword = text.midRef(tk.begin(), tk.length());
if (ppKeyword == QLatin1String("error")
|| ppKeyword == QLatin1String("warning")
@@ -160,16 +175,14 @@ void CppHighlighter::highlightBlock(const QString &text)
onlyHighlightComments = true;
}
- } else if (tk.is(T_NUMERIC_LITERAL))
- setFormat(tk.begin(), tk.length(), m_formats[CppNumberFormat]);
-
- else if (tk.isStringLiteral() || tk.isCharLiteral())
- highlightLine(text, tk.begin(), tk.length(), m_formats[CppStringFormat]);
-
- else if (tk.isComment()) {
+ } else if (tk.is(T_NUMERIC_LITERAL)) {
+ setFormat(tk.begin(), tk.length(), formatForCategory(CppNumberFormat));
+ } else if (tk.isStringLiteral() || tk.isCharLiteral()) {
+ highlightLine(text, tk.begin(), tk.length(), formatForCategory(CppStringFormat));
+ } else if (tk.isComment()) {
const int startPosition = initialState ? previousTokenEnd : tk.begin();
if (tk.is(T_COMMENT) || tk.is(T_CPP_COMMENT))
- highlightLine(text, startPosition, tk.end() - startPosition, m_formats[CppCommentFormat]);
+ highlightLine(text, startPosition, tk.end() - startPosition, formatForCategory(CppCommentFormat));
else // a doxygen comment
highlightDoxygenComment(text, startPosition, tk.end() - startPosition);
@@ -177,8 +190,8 @@ void CppHighlighter::highlightBlock(const QString &text)
// we need to insert a close comment parenthesis, if
// - the line starts in a C Comment (initalState != 0)
// - the first token of the line is a T_COMMENT (i == 0 && tk.is(T_COMMENT))
- // - is not a continuation line (tokens.size() > 1 || ! state)
- if (initialState && i == 0 && (tokens.size() > 1 || ! state)) {
+ // - is not a continuation line (tokens.size() > 1 || !state)
+ if (initialState && i == 0 && (tokens.size() > 1 || !state)) {
--braceDepth;
// unless we are at the end of the block, we reduce the folding indent
if (i == tokens.size()-1)
@@ -192,26 +205,23 @@ void CppHighlighter::highlightBlock(const QString &text)
initialState = 0;
}
- } else if (tk.isKeyword() || CppTools::isQtKeyword(text.midRef(tk.begin(), tk.length())) || tk.isObjCAtKeyword())
- setFormat(tk.begin(), tk.length(), m_formats[CppKeywordFormat]);
-
- else if (tk.isOperator())
- setFormat(tk.begin(), tk.length(), m_formats[CppOperatorFormat]);
-
- else if (i == 0 && tokens.size() > 1 && tk.is(T_IDENTIFIER) && tokens.at(1).is(T_COLON))
- setFormat(tk.begin(), tk.length(), m_formats[CppLabelFormat]);
-
- else if (tk.is(T_IDENTIFIER))
+ } else if (tk.isKeyword() || CppTools::isQtKeyword(text.midRef(tk.begin(), tk.length())) || tk.isObjCAtKeyword()) {
+ setFormat(tk.begin(), tk.length(), formatForCategory(CppKeywordFormat));
+ } else if (tk.isOperator()) {
+ setFormat(tk.begin(), tk.length(), formatForCategory(CppOperatorFormat));
+ } else if (i == 0 && tokens.size() > 1 && tk.is(T_IDENTIFIER) && tokens.at(1).is(T_COLON)) {
+ setFormat(tk.begin(), tk.length(), formatForCategory(CppLabelFormat));
+ } else if (tk.is(T_IDENTIFIER)) {
highlightWord(text.midRef(tk.begin(), tk.length()), tk.begin(), tk.length());
-
+ }
}
// mark the trailing white spaces
const int lastTokenEnd = tokens.last().end();
if (text.length() > lastTokenEnd)
- highlightLine(text, lastTokenEnd, text.length() - lastTokenEnd, m_formats[CppVisualWhitespace]);
+ highlightLine(text, lastTokenEnd, text.length() - lastTokenEnd, formatForCategory(CppVisualWhitespace));
- if (! initialState && state && ! tokens.isEmpty()) {
+ if (!initialState && state && !tokens.isEmpty()) {
parentheses.append(Parenthesis(Parenthesis::Opened, QLatin1Char('+'),
tokens.last().begin()));
++braceDepth;
@@ -331,7 +341,7 @@ bool CppHighlighter::isPPKeyword(const QStringRef &text) const
void CppHighlighter::highlightLine(const QString &text, int position, int length,
const QTextCharFormat &format)
{
- QTextCharFormat visualSpaceFormat = m_formats[CppVisualWhitespace];
+ QTextCharFormat visualSpaceFormat = formatForCategory(CppVisualWhitespace);
visualSpaceFormat.setBackground(format.background());
const int end = position + length;
@@ -361,11 +371,11 @@ void CppHighlighter::highlightWord(QStringRef word, int position, int length)
|| (word.at(1) == QLatin1Char('T') && word.at(2) == QLatin1Char('_'))) { // QT_
for (int i = 1; i < word.length(); ++i) {
const QChar &ch = word.at(i);
- if (! (ch.isUpper() || ch == QLatin1Char('_')))
+ if (!(ch.isUpper() || ch == QLatin1Char('_')))
return;
}
- setFormat(position, length, m_formats[CppTypeFormat]);
+ setFormat(position, length, formatForCategory(CppTypeFormat));
}
}
}
@@ -377,10 +387,10 @@ void CppHighlighter::highlightDoxygenComment(const QString &text, int position,
const QChar *uc = text.unicode();
const QChar *it = uc + position;
- const QTextCharFormat &format = m_formats[CppDoxygenCommentFormat];
- const QTextCharFormat &kwFormat = m_formats[CppDoxygenTagFormat];
+ const QTextCharFormat &format = formatForCategory(CppDoxygenCommentFormat);
+ const QTextCharFormat &kwFormat = formatForCategory(CppDoxygenTagFormat);
- while (! it->isNull()) {
+ while (!it->isNull()) {
if (it->unicode() == QLatin1Char('\\') ||
it->unicode() == QLatin1Char('@')) {
++it;
diff --git a/src/plugins/cppeditor/cpphighlighter.h b/src/plugins/cppeditor/cpphighlighter.h
index 9e38897c29..e697783559 100644
--- a/src/plugins/cppeditor/cpphighlighter.h
+++ b/src/plugins/cppeditor/cpphighlighter.h
@@ -30,8 +30,6 @@
#ifndef CPPHIGHLIGHTER_H
#define CPPHIGHLIGHTER_H
-#include "cppeditorenums.h"
-
#include <texteditor/syntaxhighlighter.h>
#include <QTextCharFormat>
@@ -51,12 +49,6 @@ public:
virtual 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);
- }
-
private:
void highlightWord(QStringRef word, int position, int length);
void highlightLine(const QString &line, int position, int length,
@@ -66,8 +58,6 @@ private:
int length);
bool isPPKeyword(const QStringRef &text) const;
-
- QTextCharFormat m_formats[NumCppFormats];
};
} // namespace Internal
diff --git a/src/plugins/cppeditor/cpphighlighterfactory.cpp b/src/plugins/cppeditor/cpphighlighterfactory.cpp
new file mode 100644
index 0000000000..32af1d125e
--- /dev/null
+++ b/src/plugins/cppeditor/cpphighlighterfactory.cpp
@@ -0,0 +1,48 @@
+/****************************************************************************
+**
+** 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 "cpphighlighterfactory.h"
+#include "cppeditorconstants.h"
+#include "cpphighlighter.h"
+
+using namespace CppEditor::Internal;
+
+CppHighlighterFactory::CppHighlighterFactory()
+{
+ setId(CppEditor::Constants::CPPEDITOR_ID);
+ addMimeType(CppEditor::Constants::C_SOURCE_MIMETYPE);
+ addMimeType(CppEditor::Constants::C_HEADER_MIMETYPE);
+ addMimeType(CppEditor::Constants::CPP_SOURCE_MIMETYPE);
+ addMimeType(CppEditor::Constants::CPP_HEADER_MIMETYPE);
+}
+
+TextEditor::SyntaxHighlighter *CppHighlighterFactory::createHighlighter() const
+{
+ return new CppHighlighter;
+}
diff --git a/src/plugins/cppeditor/cpphighlighterfactory.h b/src/plugins/cppeditor/cpphighlighterfactory.h
new file mode 100644
index 0000000000..6fc4283b31
--- /dev/null
+++ b/src/plugins/cppeditor/cpphighlighterfactory.h
@@ -0,0 +1,51 @@
+/****************************************************************************
+**
+** 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 CPPHIGHLIGHTERFACTORY_H
+#define CPPHIGHLIGHTERFACTORY_H
+
+#include <texteditor/ihighlighterfactory.h>
+
+namespace CppEditor {
+namespace Internal {
+
+class CppHighlighterFactory : public TextEditor::IHighlighterFactory
+{
+ Q_OBJECT
+
+public:
+ CppHighlighterFactory();
+
+ virtual TextEditor::SyntaxHighlighter *createHighlighter() const;
+};
+
+} // namespace Internal
+} // namespace CppEditor
+
+#endif // CPPHIGHLIGHTERFACTORY_H
diff --git a/src/plugins/cppeditor/cpphoverhandler.cpp b/src/plugins/cppeditor/cpphoverhandler.cpp
index cf7d3bab47..bd69c13eae 100644
--- a/src/plugins/cppeditor/cpphoverhandler.cpp
+++ b/src/plugins/cppeditor/cpphoverhandler.cpp
@@ -79,12 +79,11 @@ void CppHoverHandler::identifyMatch(TextEditor::ITextEditor *editor, int pos)
setToolTip(cppElement->tooltip);
QStringList candidates = cppElement->helpIdCandidates;
candidates.removeDuplicates();
- HelpManager *hm = HelpManager::instance();
foreach (const QString &helpId, candidates) {
if (helpId.isEmpty())
continue;
- const QMap<QString, QUrl> helpLinks = hm->linksForIdentifier(helpId);
+ const QMap<QString, QUrl> helpLinks = Core::HelpManager::linksForIdentifier(helpId);
if (!helpLinks.isEmpty()) {
setLastHelpItemIdentified(TextEditor::HelpItem(helpId,
cppElement->helpMark,
diff --git a/src/plugins/cppeditor/cppoutline.cpp b/src/plugins/cppeditor/cppoutline.cpp
index ff0bbd997c..2a47c1ef25 100644
--- a/src/plugins/cppeditor/cppoutline.cpp
+++ b/src/plugins/cppeditor/cppoutline.cpp
@@ -171,9 +171,8 @@ void CppOutlineWidget::updateTextCursor(const QModelIndex &proxyIndex)
if (debug)
qDebug() << "CppOutline - moving cursor to" << symbol->line() << symbol->column() - 1;
- Core::EditorManager *editorManager = Core::EditorManager::instance();
- editorManager->cutForwardNavigationHistory();
- editorManager->addCurrentPositionToNavigationHistory();
+ Core::EditorManager::cutForwardNavigationHistory();
+ Core::EditorManager::addCurrentPositionToNavigationHistory();
// line has to be 1 based, column 0 based!
m_editor->gotoLine(symbol->line(), symbol->column() - 1);
diff --git a/src/plugins/cppeditor/cppquickfix_test.cpp b/src/plugins/cppeditor/cppquickfix_test.cpp
index 8ac2e80d27..c20e2570c3 100644
--- a/src/plugins/cppeditor/cppquickfix_test.cpp
+++ b/src/plugins/cppeditor/cppquickfix_test.cpp
@@ -38,6 +38,7 @@
#include <cpptools/cppcodestylepreferences.h>
#include <cpptools/cppmodelmanager.h>
#include <cpptools/cpppreprocessor.h>
+#include <cpptools/cpppreprocessertesthelper.h>
#include <cpptools/cpptoolssettings.h>
#include <cpptools/includeutils.h>
@@ -148,7 +149,7 @@ private:
QList<TestDocumentPtr> testFiles;
CppCodeStylePreferences *cppCodeStylePreferences;
- QString cppCodeStylePreferencesOriginalDelegateId;
+ QByteArray cppCodeStylePreferencesOriginalDelegateId;
QStringList includePathsToRestore;
bool restoreIncludePaths;
@@ -249,7 +250,7 @@ void TestCase::init(const QStringList &includePaths)
cppCodeStylePreferences = CppToolsSettings::instance()->cppCodeStyle();
QVERIFY(cppCodeStylePreferences);
cppCodeStylePreferencesOriginalDelegateId = cppCodeStylePreferences->currentDelegateId();
- cppCodeStylePreferences->setCurrentDelegate(QLatin1String("qt"));
+ cppCodeStylePreferences->setCurrentDelegate("qt");
}
TestCase::~TestCase()
@@ -347,27 +348,6 @@ private:
const QString m_include;
};
-QString includeBaseDirectory()
-{
- return QLatin1String(SRCDIR)
- + QLatin1String("/../../../tests/auto/cplusplus/preprocessor/data/include-data");
-}
-
-QString globalQtCoreIncludePath()
-{
- return QDir::cleanPath(includeBaseDirectory() + QLatin1String("/QtCore"));
-}
-
-QString globalIncludePath()
-{
- return QDir::cleanPath(includeBaseDirectory() + QLatin1String("/global"));
-}
-
-QString directoryOfTestFile()
-{
- return QDir::cleanPath(includeBaseDirectory() + QLatin1String("/local"));
-}
-
} // anonymous namespace
/// Checks:
@@ -922,6 +902,7 @@ void CppEditorPlugin::test_quickfix_InsertDefFromDecl_afterClass()
}
/// Check from header file: If there is a source file, insert the definition in the source file.
+/// Case: Source file is empty.
void CppEditorPlugin::test_quickfix_InsertDefFromDecl_headerSource_basic1()
{
QList<TestDocumentPtr> testFiles;
@@ -954,7 +935,8 @@ void CppEditorPlugin::test_quickfix_InsertDefFromDecl_headerSource_basic1()
data.run(&factory);
}
-/// Check from source file: Insert in source file, not header file.
+/// Check from header file: If there is a source file, insert the definition in the source file.
+/// Case: Source file is not empty.
void CppEditorPlugin::test_quickfix_InsertDefFromDecl_headerSource_basic2()
{
QList<TestDocumentPtr> testFiles;
@@ -962,6 +944,44 @@ void CppEditorPlugin::test_quickfix_InsertDefFromDecl_headerSource_basic2()
QByteArray original;
QByteArray expected;
+ // Header File
+ original = "void f()@;\n";
+ expected = original + "\n";
+ testFiles << TestDocument::create(original, expected, QLatin1String("file.h"));
+
+ // Source File
+ original =
+ "#include \"file.h\"\n"
+ "\n"
+ "int x;\n"
+ ;
+ expected =
+ "#include \"file.h\"\n"
+ "\n"
+ "int x;\n"
+ "\n"
+ "\n"
+ "void f()\n"
+ "{\n"
+ "\n"
+ "}\n"
+ "\n"
+ ;
+ testFiles << TestDocument::create(original, expected, QLatin1String("file.cpp"));
+
+ InsertDefFromDecl factory;
+ TestCase data(testFiles);
+ data.run(&factory);
+}
+
+/// Check from source file: Insert in source file, not header file.
+void CppEditorPlugin::test_quickfix_InsertDefFromDecl_headerSource_basic3()
+{
+ QList<TestDocumentPtr> testFiles;
+
+ QByteArray original;
+ QByteArray expected;
+
// Empty Header File
testFiles << TestDocument::create("", "\n", QLatin1String("file.h"));
@@ -1290,6 +1310,131 @@ void CppEditorPlugin::test_quickfix_InsertDefFromDecl_respectWsInOperatorNames2(
data.run(&factory);
}
+/// Check if a function like macro use is not separated by the function to insert
+/// Case: Macro preceded by preproceesor directives and declaration.
+void CppEditorPlugin::test_quickfix_InsertDefFromDecl_macroUsesAtEndOfFile1()
+{
+ QList<TestDocumentPtr> testFiles;
+
+ QByteArray original;
+ QByteArray expected;
+
+ // Header File
+ original = "void f()@;\n";
+ expected = original + "\n";
+ testFiles << TestDocument::create(original, expected, QLatin1String("file.h"));
+
+ // Source File
+ original =
+ "#include \"file.h\"\n"
+ "#define MACRO(X) X x;\n"
+ "int lala;\n"
+ "\n"
+ "MACRO(int)\n"
+ ;
+ expected =
+ "#include \"file.h\"\n"
+ "#define MACRO(X) X x;\n"
+ "int lala;\n"
+ "\n"
+ "\n"
+ "\n"
+ "void f()\n"
+ "{\n"
+ "\n"
+ "}\n"
+ "\n"
+ "MACRO(int)\n"
+ "\n"
+ ;
+ testFiles << TestDocument::create(original, expected, QLatin1String("file.cpp"));
+
+ InsertDefFromDecl factory;
+ TestCase data(testFiles);
+ data.run(&factory);
+}
+
+/// Check if a function like macro use is not separated by the function to insert
+/// Case: Marco preceded only by preprocessor directives.
+void CppEditorPlugin::test_quickfix_InsertDefFromDecl_macroUsesAtEndOfFile2()
+{
+ QList<TestDocumentPtr> testFiles;
+
+ QByteArray original;
+ QByteArray expected;
+
+ // Header File
+ original = "void f()@;\n";
+ expected = original + "\n";
+ testFiles << TestDocument::create(original, expected, QLatin1String("file.h"));
+
+ // Source File
+ original =
+ "#include \"file.h\"\n"
+ "#define MACRO(X) X x;\n"
+ "\n"
+ "MACRO(int)\n"
+ ;
+ expected =
+ "#include \"file.h\"\n"
+ "#define MACRO(X) X x;\n"
+ "\n"
+ "\n"
+ "\n"
+ "void f()\n"
+ "{\n"
+ "\n"
+ "}\n"
+ "\n"
+ "MACRO(int)\n"
+ "\n"
+ ;
+ testFiles << TestDocument::create(original, expected, QLatin1String("file.cpp"));
+
+ InsertDefFromDecl factory;
+ TestCase data(testFiles);
+ data.run(&factory);
+}
+
+/// Check if insertion happens before syntactically erroneous statements at end of file.
+void CppEditorPlugin::test_quickfix_InsertDefFromDecl_erroneousStatementAtEndOfFile()
+{
+ QList<TestDocumentPtr> testFiles;
+
+ QByteArray original;
+ QByteArray expected;
+
+ // Header File
+ original = "void f()@;\n";
+ expected = original + "\n";
+ testFiles << TestDocument::create(original, expected, QLatin1String("file.h"));
+
+ // Source File
+ original =
+ "#include \"file.h\"\n"
+ "\n"
+ "MissingSemicolon(int)\n"
+ ;
+ expected =
+ "#include \"file.h\"\n"
+ "\n"
+ "\n"
+ "\n"
+ "void f()\n"
+ "{\n"
+ "\n"
+ "}\n"
+ "\n"
+ "MissingSemicolon(int)\n"
+ "\n"
+ ;
+ testFiles << TestDocument::create(original, expected, QLatin1String("file.cpp"));
+
+ InsertDefFromDecl factory;
+ TestCase data(testFiles);
+ data.run(&factory);
+}
+
// Function for one of InsertDeclDef section cases
void insertToSectionDeclFromDef(const QByteArray &section, int sectionIndex)
{
@@ -1341,7 +1486,7 @@ void CppEditorPlugin::test_quickfix_InsertDeclFromDef()
QList<Include> includesForSource(const QByteArray &source)
{
- const QString fileName = directoryOfTestFile() + QLatin1String("/file.cpp");
+ const QString fileName = TestIncludePaths::directoryOfTestFile() + QLatin1String("/file.cpp");
Utils::FileSaver srcSaver(fileName);
srcSaver.write(source);
srcSaver.finalize();
@@ -1351,11 +1496,11 @@ QList<Include> includesForSource(const QByteArray &source)
CppModelManager *cmm = CppModelManager::instance();
cmm->GC();
CppPreprocessor pp((QPointer<CppModelManager>(cmm)));
- pp.setIncludePaths(QStringList(globalIncludePath()));
+ pp.setIncludePaths(QStringList(TestIncludePaths::globalIncludePath()));
pp.run(fileName);
Document::Ptr document = cmm->snapshot().document(fileName);
- return document->includes();
+ return document->resolvedIncludes();
}
/// Check: Detection of include groups separated by new lines
@@ -1508,7 +1653,7 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_normal()
// Header File
original = "class Foo {};\n";
expected = original + "\n";
- testFiles << TestDocument::create(original, expected, directoryOfTestFile() + QLatin1Char('/')
+ testFiles << TestDocument::create(original, expected, TestIncludePaths::directoryOfTestFile() + QLatin1Char('/')
+ QLatin1String("afile.h"));
// Source File
@@ -1530,12 +1675,12 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_normal()
"}\n"
"\n"
;
- testFiles << TestDocument::create(original, expected, directoryOfTestFile() + QLatin1Char('/')
+ testFiles << TestDocument::create(original, expected, TestIncludePaths::directoryOfTestFile() + QLatin1Char('/')
+ QLatin1String("afile.cpp"));
// Do not use the test factory, at least once we want to go through the "full stack".
AddIncludeForUndefinedIdentifier factory;
- TestCase data(testFiles, QStringList(globalIncludePath()));
+ TestCase data(testFiles, QStringList(TestIncludePaths::globalIncludePath()));
data.run(&factory);
}
@@ -1558,11 +1703,11 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_ignoremoc()
"#include \"file.moc\";\n"
"\n"
;
- testFiles << TestDocument::create(original, expected, directoryOfTestFile() + QLatin1Char('/')
+ testFiles << TestDocument::create(original, expected, TestIncludePaths::directoryOfTestFile() + QLatin1Char('/')
+ QLatin1String("file.cpp"));
AddIncludeForUndefinedIdentifierTestFactory factory(QLatin1String("\"file.h\""));
- TestCase data(testFiles, QStringList(globalIncludePath()));
+ TestCase data(testFiles, QStringList(TestIncludePaths::globalIncludePath()));
data.run(&factory);
}
@@ -1585,11 +1730,11 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_sortingTop(
"#include \"z.h\"\n"
"\n\n"
;
- testFiles << TestDocument::create(original, expected, directoryOfTestFile() + QLatin1Char('/')
+ testFiles << TestDocument::create(original, expected, TestIncludePaths::directoryOfTestFile() + QLatin1Char('/')
+ QLatin1String("file.cpp"));
AddIncludeForUndefinedIdentifierTestFactory factory(QLatin1String("\"file.h\""));
- TestCase data(testFiles, QStringList(globalIncludePath()));
+ TestCase data(testFiles, QStringList(TestIncludePaths::globalIncludePath()));
data.run(&factory);
}
@@ -1612,11 +1757,11 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_sortingMidd
"#include \"z.h\"\n"
"\n\n"
;
- testFiles << TestDocument::create(original, expected, directoryOfTestFile() + QLatin1Char('/')
+ testFiles << TestDocument::create(original, expected, TestIncludePaths::directoryOfTestFile() + QLatin1Char('/')
+ QLatin1String("file.cpp"));
AddIncludeForUndefinedIdentifierTestFactory factory(QLatin1String("\"file.h\""));
- TestCase data(testFiles, QStringList(globalIncludePath()));
+ TestCase data(testFiles, QStringList(TestIncludePaths::globalIncludePath()));
data.run(&factory);
}
@@ -1639,11 +1784,11 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_sortingBott
"#include \"file.h\"\n"
"\n\n"
;
- testFiles << TestDocument::create(original, expected, directoryOfTestFile() + QLatin1Char('/')
+ testFiles << TestDocument::create(original, expected, TestIncludePaths::directoryOfTestFile() + QLatin1Char('/')
+ QLatin1String("file.cpp"));
AddIncludeForUndefinedIdentifierTestFactory factory(QLatin1String("\"file.h\""));
- TestCase data(testFiles, QStringList(globalIncludePath()));
+ TestCase data(testFiles, QStringList(TestIncludePaths::globalIncludePath()));
data.run(&factory);
}
@@ -1666,11 +1811,11 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_appendToUns
"#include \"file.h\"\n"
"\n\n"
;
- testFiles << TestDocument::create(original, expected, directoryOfTestFile() + QLatin1Char('/')
+ testFiles << TestDocument::create(original, expected, TestIncludePaths::directoryOfTestFile() + QLatin1Char('/')
+ QLatin1String("file.cpp"));
AddIncludeForUndefinedIdentifierTestFactory factory(QLatin1String("\"file.h\""));
- TestCase data(testFiles, QStringList(globalIncludePath()));
+ TestCase data(testFiles, QStringList(TestIncludePaths::globalIncludePath()));
data.run(&factory);
}
@@ -1694,11 +1839,11 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_firstLocalI
"#include <b.h>\n"
"\n\n"
;
- testFiles << TestDocument::create(original, expected, directoryOfTestFile() + QLatin1Char('/')
+ testFiles << TestDocument::create(original, expected, TestIncludePaths::directoryOfTestFile() + QLatin1Char('/')
+ QLatin1String("file.cpp"));
AddIncludeForUndefinedIdentifierTestFactory factory(QLatin1String("\"file.h\""));
- TestCase data(testFiles, QStringList(globalIncludePath()));
+ TestCase data(testFiles, QStringList(TestIncludePaths::globalIncludePath()));
data.run(&factory);
}
@@ -1725,11 +1870,11 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_firstGlobal
"void f();\n"
"\n"
;
- testFiles << TestDocument::create(original, expected, directoryOfTestFile() + QLatin1Char('/')
+ testFiles << TestDocument::create(original, expected, TestIncludePaths::directoryOfTestFile() + QLatin1Char('/')
+ QLatin1String("file.cpp"));
AddIncludeForUndefinedIdentifierTestFactory factory(QLatin1String("<file.h>"));
- TestCase data(testFiles, QStringList(globalIncludePath()));
+ TestCase data(testFiles, QStringList(TestIncludePaths::globalIncludePath()));
data.run(&factory);
}
@@ -1756,11 +1901,11 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_preferGroup
"#include \"foo.h\"\n"
"\n\n"
;
- testFiles << TestDocument::create(original, expected, directoryOfTestFile() + QLatin1Char('/')
+ testFiles << TestDocument::create(original, expected, TestIncludePaths::directoryOfTestFile() + QLatin1Char('/')
+ QLatin1String("file.cpp"));
AddIncludeForUndefinedIdentifierTestFactory factory(QLatin1String("\"prefixc.h\""));
- TestCase data(testFiles, QStringList(globalIncludePath()));
+ TestCase data(testFiles, QStringList(TestIncludePaths::globalIncludePath()));
data.run(&factory);
}
@@ -1784,11 +1929,11 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_newGroupIfO
"#include \"file.h\"\n"
"\n\n"
;
- testFiles << TestDocument::create(original, expected, directoryOfTestFile() + QLatin1Char('/')
+ testFiles << TestDocument::create(original, expected, TestIncludePaths::directoryOfTestFile() + QLatin1Char('/')
+ QLatin1String("file.cpp"));
AddIncludeForUndefinedIdentifierTestFactory factory(QLatin1String("\"file.h\""));
- TestCase data(testFiles, QStringList(globalIncludePath()));
+ TestCase data(testFiles, QStringList(TestIncludePaths::globalIncludePath()));
data.run(&factory);
}
@@ -1813,11 +1958,11 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_mixedDirsSo
"#include <utils/file.h>\n"
"\n\n"
;
- testFiles << TestDocument::create(original, expected, directoryOfTestFile() + QLatin1Char('/')
+ testFiles << TestDocument::create(original, expected, TestIncludePaths::directoryOfTestFile() + QLatin1Char('/')
+ QLatin1String("file.cpp"));
AddIncludeForUndefinedIdentifierTestFactory factory(QLatin1String("<firstlib/file.h>"));
- TestCase data(testFiles, QStringList(globalIncludePath()));
+ TestCase data(testFiles, QStringList(TestIncludePaths::globalIncludePath()));
data.run(&factory);
}
@@ -1842,11 +1987,11 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_mixedDirsUn
"#include <lastlib/file.h>\n"
"\n\n"
;
- testFiles << TestDocument::create(original, expected, directoryOfTestFile() + QLatin1Char('/')
+ testFiles << TestDocument::create(original, expected, TestIncludePaths::directoryOfTestFile() + QLatin1Char('/')
+ QLatin1String("file.cpp"));
AddIncludeForUndefinedIdentifierTestFactory factory(QLatin1String("<lastlib/file.h>"));
- TestCase data(testFiles, QStringList(globalIncludePath()));
+ TestCase data(testFiles, QStringList(TestIncludePaths::globalIncludePath()));
data.run(&factory);
}
@@ -1869,11 +2014,11 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_mixedInclud
"#include <global.h>\n"
"\n\n"
;
- testFiles << TestDocument::create(original, expected, directoryOfTestFile() + QLatin1Char('/')
+ testFiles << TestDocument::create(original, expected, TestIncludePaths::directoryOfTestFile() + QLatin1Char('/')
+ QLatin1String("file.cpp"));
AddIncludeForUndefinedIdentifierTestFactory factory(QLatin1String("\"z.h\""));
- TestCase data(testFiles, QStringList(globalIncludePath()));
+ TestCase data(testFiles, QStringList(TestIncludePaths::globalIncludePath()));
data.run(&factory);
}
@@ -1896,11 +2041,11 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_mixedInclud
"#include <global.h>\n"
"\n\n"
;
- testFiles << TestDocument::create(original, expected, directoryOfTestFile() + QLatin1Char('/')
+ testFiles << TestDocument::create(original, expected, TestIncludePaths::directoryOfTestFile() + QLatin1Char('/')
+ QLatin1String("file.cpp"));
AddIncludeForUndefinedIdentifierTestFactory factory(QLatin1String("\"a.h\""));
- TestCase data(testFiles, QStringList(globalIncludePath()));
+ TestCase data(testFiles, QStringList(TestIncludePaths::globalIncludePath()));
data.run(&factory);
}
@@ -1923,11 +2068,11 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_mixedInclud
"#include <global.h>\n"
"\n\n"
;
- testFiles << TestDocument::create(original, expected, directoryOfTestFile() + QLatin1Char('/')
+ testFiles << TestDocument::create(original, expected, TestIncludePaths::directoryOfTestFile() + QLatin1Char('/')
+ QLatin1String("file.cpp"));
AddIncludeForUndefinedIdentifierTestFactory factory(QLatin1String("\"lib/file.h\""));
- TestCase data(testFiles, QStringList(globalIncludePath()));
+ TestCase data(testFiles, QStringList(TestIncludePaths::globalIncludePath()));
data.run(&factory);
}
@@ -1950,11 +2095,11 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_mixedInclud
"#include <lib/file.h>\n"
"\n\n"
;
- testFiles << TestDocument::create(original, expected, directoryOfTestFile() + QLatin1Char('/')
+ testFiles << TestDocument::create(original, expected, TestIncludePaths::directoryOfTestFile() + QLatin1Char('/')
+ QLatin1String("file.cpp"));
AddIncludeForUndefinedIdentifierTestFactory factory(QLatin1String("<lib/file.h>"));
- TestCase data(testFiles, QStringList(globalIncludePath()));
+ TestCase data(testFiles, QStringList(TestIncludePaths::globalIncludePath()));
data.run(&factory);
}
@@ -1975,11 +2120,11 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_noinclude()
"void f();\n"
"\n"
;
- testFiles << TestDocument::create(original, expected, directoryOfTestFile() + QLatin1Char('/')
+ testFiles << TestDocument::create(original, expected, TestIncludePaths::directoryOfTestFile() + QLatin1Char('/')
+ QLatin1String("file.cpp"));
AddIncludeForUndefinedIdentifierTestFactory factory(QLatin1String("\"file.h\""));
- TestCase data(testFiles, QStringList(globalIncludePath()));
+ TestCase data(testFiles, QStringList(TestIncludePaths::globalIncludePath()));
data.run(&factory);
}
@@ -2006,11 +2151,11 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_veryFirstIn
"void @f();\n"
"\n"
;
- testFiles << TestDocument::create(original, expected, directoryOfTestFile() + QLatin1Char('/')
+ testFiles << TestDocument::create(original, expected, TestIncludePaths::directoryOfTestFile() + QLatin1Char('/')
+ QLatin1String("file.cpp"));
AddIncludeForUndefinedIdentifierTestFactory factory(QLatin1String("\"file.h\""));
- TestCase data(testFiles, QStringList(globalIncludePath()));
+ TestCase data(testFiles, QStringList(TestIncludePaths::globalIncludePath()));
data.run(&factory);
}
@@ -2041,11 +2186,11 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_veryFirstIn
"void @f();\n"
"\n"
;
- testFiles << TestDocument::create(original, expected, directoryOfTestFile() + QLatin1Char('/')
+ testFiles << TestDocument::create(original, expected, TestIncludePaths::directoryOfTestFile() + QLatin1Char('/')
+ QLatin1String("file.cpp"));
AddIncludeForUndefinedIdentifierTestFactory factory(QLatin1String("\"file.h\""));
- TestCase data(testFiles, QStringList(globalIncludePath()));
+ TestCase data(testFiles, QStringList(TestIncludePaths::globalIncludePath()));
data.run(&factory);
}
@@ -2067,11 +2212,11 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_checkQSomet
"QDir dir;\n"
"\n"
;
- testFiles << TestDocument::create(original, expected, directoryOfTestFile() + QLatin1Char('/')
+ testFiles << TestDocument::create(original, expected, TestIncludePaths::directoryOfTestFile() + QLatin1Char('/')
+ QLatin1String("file.cpp"));
AddIncludeForUndefinedIdentifier factory;
- TestCase data(testFiles, QStringList(globalQtCoreIncludePath()));
+ TestCase data(testFiles, QStringList(TestIncludePaths::globalQtCoreIncludePath()));
data.run(&factory);
}
@@ -3623,3 +3768,93 @@ void CppEditorPlugin::test_quickfix_InsertVirtualMethods_BaseClassInNamespace()
TestCase data(testFiles);
data.run(&factory);
}
+
+/// Check: optimize postcrement
+void CppEditorPlugin::test_quickfix_OptimizeForLoop_postcrement()
+{
+ const QByteArray original = "void foo() {f@or (int i = 0; i < 3; i++) {}}\n";
+ const QByteArray expected = "void foo() {for (int i = 0; i < 3; ++i) {}}\n\n";
+ OptimizeForLoop factory;
+ TestCase data(original, expected);
+ data.run(&factory);
+}
+
+/// Check: optimize condition
+void CppEditorPlugin::test_quickfix_OptimizeForLoop_condition()
+{
+ const QByteArray original = "void foo() {f@or (int i = 0; i < 3 + 5; ++i) {}}\n";
+ const QByteArray expected = "void foo() {for (int i = 0, total = 3 + 5; i < total; ++i) {}}\n\n";
+ OptimizeForLoop factory;
+ TestCase data(original, expected);
+ data.run(&factory);
+}
+
+/// Check: optimize fliped condition
+void CppEditorPlugin::test_quickfix_OptimizeForLoop_flipedCondition()
+{
+ const QByteArray original = "void foo() {f@or (int i = 0; 3 + 5 > i; ++i) {}}\n";
+ const QByteArray expected = "void foo() {for (int i = 0, total = 3 + 5; total > i; ++i) {}}\n\n";
+ OptimizeForLoop factory;
+ TestCase data(original, expected);
+ data.run(&factory);
+}
+
+/// Check: if "total" used, create other name.
+void CppEditorPlugin::test_quickfix_OptimizeForLoop_alterVariableName()
+{
+ const QByteArray original = "void foo() {f@or (int i = 0, total = 0; i < 3 + 5; ++i) {}}\n";
+ const QByteArray expected = "void foo() {for (int i = 0, total = 0, totalX = 3 + 5; i < totalX; ++i) {}}\n\n";
+ OptimizeForLoop factory;
+ TestCase data(original, expected);
+ data.run(&factory);
+}
+
+/// Check: optimize postcrement and condition
+void CppEditorPlugin::test_quickfix_OptimizeForLoop_optimizeBoth()
+{
+ const QByteArray original = "void foo() {f@or (int i = 0; i < 3 + 5; i++) {}}\n";
+ const QByteArray expected = "void foo() {for (int i = 0, total = 3 + 5; i < total; ++i) {}}\n\n";
+ OptimizeForLoop factory;
+ TestCase data(original, expected);
+ data.run(&factory);
+}
+
+/// Check: empty initializier
+void CppEditorPlugin::test_quickfix_OptimizeForLoop_emptyInitializer()
+{
+ const QByteArray original = "int i; void foo() {f@or (; i < 3 + 5; ++i) {}}\n";
+ const QByteArray expected = "int i; void foo() {for (int total = 3 + 5; i < total; ++i) {}}\n\n";
+ OptimizeForLoop factory;
+ TestCase data(original, expected);
+ data.run(&factory);
+}
+
+/// Check: wrong initializier type -> no trigger
+void CppEditorPlugin::test_quickfix_OptimizeForLoop_wrongInitializer()
+{
+ const QByteArray original = "int i; void foo() {f@or (double a = 0; i < 3 + 5; ++i) {}}\n";
+ const QByteArray expected = "int i; void foo() {f@or (double a = 0; i < 3 + 5; ++i) {}}\n\n";
+ OptimizeForLoop factory;
+ TestCase data(original, expected);
+ data.run(&factory);
+}
+
+/// Check: No trigger when numeric
+void CppEditorPlugin::test_quickfix_OptimizeForLoop_noTriggerNumeric1()
+{
+ const QByteArray original = "void foo() {fo@r (int i = 0; i < 3; ++i) {}}\n";
+ const QByteArray expected = original + "\n";
+ OptimizeForLoop factory;
+ TestCase data(original, expected);
+ data.run(&factory);
+}
+
+/// Check: No trigger when numeric
+void CppEditorPlugin::test_quickfix_OptimizeForLoop_noTriggerNumeric2()
+{
+ const QByteArray original = "void foo() {fo@r (int i = 0; i < -3; ++i) {}}\n";
+ const QByteArray expected = original + "\n";
+ OptimizeForLoop factory;
+ TestCase data(original, expected);
+ data.run(&factory);
+}
diff --git a/src/plugins/cppeditor/cppquickfixassistant.cpp b/src/plugins/cppeditor/cppquickfixassistant.cpp
index 1157f45d65..2c6d7e3217 100644
--- a/src/plugins/cppeditor/cppquickfixassistant.cpp
+++ b/src/plugins/cppeditor/cppquickfixassistant.cpp
@@ -82,7 +82,7 @@ const IAssistProvider *CppQuickFixAssistProcessor::provider() const
CppQuickFixAssistInterface::CppQuickFixAssistInterface(CPPEditorWidget *editor,
TextEditor::AssistReason reason)
: DefaultAssistInterface(editor->document(), editor->position(),
- editor->editorDocument()->fileName(), reason)
+ editor->editorDocument()->filePath(), reason)
, m_editor(editor)
, m_semanticInfo(editor->semanticInfo())
, m_snapshot(CppTools::CppModelManagerInterface::instance()->snapshot())
diff --git a/src/plugins/cppeditor/cppquickfixes.cpp b/src/plugins/cppeditor/cppquickfixes.cpp
index 14d8db4ed9..fd01a487f4 100644
--- a/src/plugins/cppeditor/cppquickfixes.cpp
+++ b/src/plugins/cppeditor/cppquickfixes.cpp
@@ -131,6 +131,8 @@ void CppEditor::Internal::registerQuickFixes(ExtensionSystem::IPlugin *plugIn)
plugIn->addAutoReleasedObject(new AssignToLocalVariable);
plugIn->addAutoReleasedObject(new InsertVirtualMethods);
+
+ plugIn->addAutoReleasedObject(new OptimizeForLoop);
}
// In the following anonymous namespace all functions are collected, which could be of interest for
@@ -202,15 +204,15 @@ Class *isMemberFunction(const LookupContext &context, Function *function)
QTC_ASSERT(function, return 0);
Scope *enclosingScope = function->enclosingScope();
- while (! (enclosingScope->isNamespace() || enclosingScope->isClass()))
+ while (!(enclosingScope->isNamespace() || enclosingScope->isClass()))
enclosingScope = enclosingScope->enclosingScope();
QTC_ASSERT(enclosingScope != 0, return 0);
const Name *functionName = function->name();
- if (! functionName)
+ if (!functionName)
return 0; // anonymous function names are not valid c++
- if (! functionName->isQualifiedNameId())
+ if (!functionName->isQualifiedNameId())
return 0; // trying to add a declaration for a global function
const QualifiedNameId *q = functionName->asQualifiedNameId();
@@ -227,12 +229,50 @@ Class *isMemberFunction(const LookupContext &context, Function *function)
return 0;
}
+Namespace *isNamespaceFunction(const LookupContext &context, Function *function)
+{
+ QTC_ASSERT(function, return 0);
+ if (isMemberFunction(context, function))
+ return 0;
+
+ Scope *enclosingScope = function->enclosingScope();
+ while (!(enclosingScope->isNamespace() || enclosingScope->isClass()))
+ enclosingScope = enclosingScope->enclosingScope();
+ QTC_ASSERT(enclosingScope != 0, return 0);
+
+ const Name *functionName = function->name();
+ if (!functionName)
+ return 0; // anonymous function names are not valid c++
+
+ // global namespace
+ if (!functionName->isQualifiedNameId()) {
+ foreach (Symbol *s, context.globalNamespace()->symbols()) {
+ if (Namespace *matchingNamespace = s->asNamespace())
+ return matchingNamespace;
+ }
+ return 0;
+ }
+
+ const QualifiedNameId *q = functionName->asQualifiedNameId();
+ if (!q->base())
+ return 0;
+
+ if (ClassOrNamespace *binding = context.lookupType(q->base(), enclosingScope)) {
+ foreach (Symbol *s, binding->symbols()) {
+ if (Namespace *matchingNamespace = s->asNamespace())
+ return matchingNamespace;
+ }
+ }
+
+ return 0;
+}
+
// Given include is e.g. "afile.h" or <afile.h> (quotes/angle brackets included!).
void insertNewIncludeDirective(const QString &include, CppRefactoringFilePtr file)
{
// Find optimal position
using namespace IncludeUtils;
- LineForNewIncludeDirective finder(file->document(), file->cppDocument()->includes(),
+ LineForNewIncludeDirective finder(file->document(), file->cppDocument()->resolvedIncludes(),
LineForNewIncludeDirective::IgnoreMocIncludes,
LineForNewIncludeDirective::AutoDetect);
unsigned newLinesToPrepend = 0;
@@ -287,8 +327,10 @@ public:
// check for ! before parentheses
if (nested && priority - 2 >= 0) {
negation = interface->path()[priority - 2]->asUnaryExpression();
- if (negation && ! interface->currentFile()->tokenAt(negation->unary_op_token).is(T_EXCLAIM))
+ if (negation
+ && !interface->currentFile()->tokenAt(negation->unary_op_token).is(T_EXCLAIM)) {
negation = 0;
+ }
}
}
@@ -335,9 +377,9 @@ void InverseLogicalComparison::match(const CppQuickFixInterface &interface,
const QList<AST *> &path = interface->path();
int index = path.size() - 1;
BinaryExpressionAST *binary = path.at(index)->asBinaryExpression();
- if (! binary)
+ if (!binary)
return;
- if (! interface->isCursorOn(binary->binary_op_token))
+ if (!interface->isCursorOn(binary->binary_op_token))
return;
Kind invertToken;
@@ -398,7 +440,7 @@ public:
ChangeSet changes;
changes.flip(currentFile->range(binary->left_expression),
currentFile->range(binary->right_expression));
- if (! replacement.isEmpty())
+ if (!replacement.isEmpty())
changes.replace(currentFile->range(binary->binary_op_token), replacement);
currentFile->setChangeSet(changes);
@@ -419,9 +461,9 @@ void FlipLogicalOperands::match(const CppQuickFixInterface &interface, QuickFixO
int index = path.size() - 1;
BinaryExpressionAST *binary = path.at(index)->asBinaryExpression();
- if (! binary)
+ if (!binary)
return;
- if (! interface->isCursorOn(binary->binary_op_token))
+ if (!interface->isCursorOn(binary->binary_op_token))
return;
Kind flipToken;
@@ -513,10 +555,10 @@ void RewriteLogicalAnd::match(const CppQuickFixInterface &interface, QuickFixOpe
break;
}
- if (! expression)
+ if (!expression)
return;
- if (! interface->isCursorOn(expression->binary_op_token))
+ if (!interface->isCursorOn(expression->binary_op_token))
return;
QSharedPointer<RewriteLogicalAndOp> op(new RewriteLogicalAndOp(interface));
@@ -534,10 +576,10 @@ void RewriteLogicalAnd::match(const CppQuickFixInterface &interface, QuickFixOpe
bool SplitSimpleDeclaration::checkDeclaration(SimpleDeclarationAST *declaration)
{
- if (! declaration->semicolon_token)
+ if (!declaration->semicolon_token)
return false;
- if (! declaration->decl_specifier_list)
+ if (!declaration->decl_specifier_list)
return false;
for (SpecifierListAST *it = declaration->decl_specifier_list; it; it = it->next) {
@@ -550,10 +592,10 @@ bool SplitSimpleDeclaration::checkDeclaration(SimpleDeclarationAST *declaration)
return false;
}
- if (! declaration->declarator_list)
+ if (!declaration->declarator_list)
return false;
- else if (! declaration->declarator_list->next)
+ else if (!declaration->declarator_list->next)
return false;
return true;
@@ -624,10 +666,9 @@ void SplitSimpleDeclaration::match(const CppQuickFixInterface &interface,
for (int index = path.size() - 1; index != -1; --index) {
AST *node = path.at(index);
- if (CoreDeclaratorAST *coreDecl = node->asCoreDeclarator())
+ if (CoreDeclaratorAST *coreDecl = node->asCoreDeclarator()) {
core_declarator = coreDecl;
-
- else if (SimpleDeclarationAST *simpleDecl = node->asSimpleDeclaration()) {
+ } else if (SimpleDeclarationAST *simpleDecl = node->asSimpleDeclaration()) {
if (checkDeclaration(simpleDecl)) {
SimpleDeclarationAST *declaration = simpleDecl;
@@ -698,7 +739,7 @@ void AddBracesToIf::match(const CppQuickFixInterface &interface, QuickFixOperati
int index = path.size() - 1;
IfStatementAST *ifStatement = path.at(index)->asIfStatement();
if (ifStatement && interface->isCursorOn(ifStatement->if_token) && ifStatement->statement
- && ! ifStatement->statement->asCompoundStatement()) {
+ && !ifStatement->statement->asCompoundStatement()) {
result.append(QuickFixOperation::Ptr(
new AddBracesToIfOp(interface, index, ifStatement->statement)));
return;
@@ -710,7 +751,7 @@ void AddBracesToIf::match(const CppQuickFixInterface &interface, QuickFixOperati
IfStatementAST *ifStatement = path.at(index)->asIfStatement();
if (ifStatement && ifStatement->statement
&& interface->isCursorOn(ifStatement->statement)
- && ! ifStatement->statement->asCompoundStatement()) {
+ && !ifStatement->statement->asCompoundStatement()) {
result.append(QuickFixOperation::Ptr(
new AddBracesToIfOp(interface, index, ifStatement->statement)));
return;
@@ -776,7 +817,7 @@ void MoveDeclarationOutOfIf::match(const CppQuickFixInterface &interface,
if (statement->match(op->pattern, &op->matcher) && op->condition->declarator) {
DeclaratorAST *declarator = op->condition->declarator;
op->core = declarator->core_declarator;
- if (! op->core)
+ if (!op->core)
return;
if (interface->isCursorOn(op->core)) {
@@ -847,13 +888,13 @@ void MoveDeclarationOutOfWhile::match(const CppQuickFixInterface &interface,
DeclaratorAST *declarator = op->condition->declarator;
op->core = declarator->core_declarator;
- if (! op->core)
+ if (!op->core)
return;
- if (! declarator->equal_token)
+ if (!declarator->equal_token)
return;
- if (! declarator->initializer)
+ if (!declarator->initializer)
return;
if (interface->isCursorOn(op->core)) {
@@ -962,20 +1003,20 @@ void SplitIfStatement::match(const CppQuickFixInterface &interface, QuickFixOper
}
}
- if (! pattern || ! pattern->statement)
+ if (!pattern || !pattern->statement)
return;
unsigned splitKind = 0;
for (++index; index < path.size(); ++index) {
AST *node = path.at(index);
BinaryExpressionAST *condition = node->asBinaryExpression();
- if (! condition)
+ if (!condition)
return;
Token binaryToken = interface->currentFile()->tokenAt(condition->binary_op_token);
// only accept a chain of ||s or &&s - no mixing
- if (! splitKind) {
+ if (!splitKind) {
splitKind = binaryToken.kind();
if (splitKind != T_AMPER_AMPER && splitKind != T_PIPE_PIPE)
return;
@@ -1412,7 +1453,7 @@ void ConvertNumericLiteral::match(const CppQuickFixInterface &interface, QuickFi
NumericLiteralAST *literal = path.last()->asNumericLiteral();
- if (! literal)
+ if (!literal)
return;
Token token = file->tokenAt(literal->asNumericLiteral()->literal_token);
@@ -1529,7 +1570,7 @@ public:
fwdHeaders.insert(snapshot().document(headerFile));
foreach (Document::Ptr doc, snapshot()) {
QFileInfo headerFileInfo(doc->fileName());
- if (doc->globalSymbolCount() == 0 && doc->includes().size() == 1)
+ if (doc->globalSymbolCount() == 0 && doc->resolvedIncludes().size() == 1)
fwdHeaders.insert(doc);
else if (headerFileInfo.suffix().isEmpty())
fwdHeaders.insert(doc);
@@ -1550,7 +1591,7 @@ public:
} else if (headerFileInfo.fileName().at(0).isUpper()) {
best = c;
// and continue
- } else if (! best.isEmpty()) {
+ } else if (!best.isEmpty()) {
if (c.count(QLatin1Char('/')) < best.count(QLatin1Char('/')))
best = c;
}
@@ -1575,7 +1616,7 @@ public:
foreach (const LookupItem &r,
interface->context().lookup(name, interface->semanticInfo().doc->scopeAt(line, column))) {
- if (! r.declaration())
+ if (!r.declaration())
continue;
else if (ForwardClassDeclaration *fwd = r.declaration()->asForwardClassDeclaration())
fwdClass = fwd;
@@ -1651,7 +1692,7 @@ public:
scope,
TypeOfExpression::Preprocess);
- if (! result.isEmpty()) {
+ if (!result.isEmpty()) {
SubstitutionEnvironment env;
env.setContext(assistInterface()->context());
env.switchScope(result.first().scope());
@@ -1666,7 +1707,7 @@ public:
Overview oo = CppCodeStyleSettings::currentProjectCodeStyleOverview();
QString ty = oo.prettyType(tn, simpleNameAST->name);
- if (! ty.isEmpty()) {
+ if (!ty.isEmpty()) {
ChangeSet changes;
changes.replace(currentFile->startOf(binaryAST),
currentFile->endOf(simpleNameAST),
@@ -1700,17 +1741,17 @@ void AddLocalDeclaration::match(const CppQuickFixInterface &interface, QuickFixO
const QList<LookupItem> results = interface->context().lookup(nameAST->name, file->scopeAt(nameAST->firstToken()));
Declaration *decl = 0;
foreach (const LookupItem &r, results) {
- if (! r.declaration())
+ if (!r.declaration())
continue;
- else if (Declaration *d = r.declaration()->asDeclaration()) {
- if (! d->type()->isFunctionType()) {
+ if (Declaration *d = r.declaration()->asDeclaration()) {
+ if (!d->type()->isFunctionType()) {
decl = d;
break;
}
}
}
- if (! decl) {
+ if (!decl) {
result.append(QuickFixOperation::Ptr(
new AddLocalDeclarationOp(interface, index, binary, nameAST)));
return;
@@ -2083,25 +2124,25 @@ public:
for (int i = astPathList.size() - 1; i >= 0; --i) {
AST *ast = astPathList.at(i);
- if (! m_hasSimpleDeclaration && ast->asSimpleDeclaration()) {
+ if (!m_hasSimpleDeclaration && ast->asSimpleDeclaration()) {
m_hasSimpleDeclaration = true;
filtered.append(ast);
- } else if (! m_hasFunctionDefinition && ast->asFunctionDefinition()) {
+ } else if (!m_hasFunctionDefinition && ast->asFunctionDefinition()) {
m_hasFunctionDefinition = true;
filtered.append(ast);
- } else if (! m_hasParameterDeclaration && ast->asParameterDeclaration()) {
+ } else if (!m_hasParameterDeclaration && ast->asParameterDeclaration()) {
m_hasParameterDeclaration = true;
filtered.append(ast);
- } else if (! m_hasIfStatement && ast->asIfStatement()) {
+ } else if (!m_hasIfStatement && ast->asIfStatement()) {
m_hasIfStatement = true;
filtered.append(ast);
- } else if (! m_hasWhileStatement && ast->asWhileStatement()) {
+ } else if (!m_hasWhileStatement && ast->asWhileStatement()) {
m_hasWhileStatement = true;
filtered.append(ast);
- } else if (! m_hasForStatement && ast->asForStatement()) {
+ } else if (!m_hasForStatement && ast->asForStatement()) {
m_hasForStatement = true;
filtered.append(ast);
- } else if (! m_hasForeachStatement && ast->asForeachStatement()) {
+ } else if (!m_hasForeachStatement && ast->asForeachStatement()) {
m_hasForeachStatement = true;
filtered.append(ast);
}
@@ -2143,7 +2184,7 @@ void ReformatPointerDeclaration::match(const CppQuickFixInterface &interface,
// 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()) {
+ if (!change.isEmpty()) {
result.append(QuickFixOperation::Ptr(
new ReformatPointerDeclarationOp(interface, change)));
}
@@ -2152,7 +2193,7 @@ void ReformatPointerDeclaration::match(const CppQuickFixInterface &interface,
= ReformatPointerDeclarationASTPathResultsFilter().filter(path);
foreach (AST *ast, suitableASTs) {
change = formatter.format(ast);
- if (! change.isEmpty()) {
+ if (!change.isEmpty()) {
result.append(QuickFixOperation::Ptr(
new ReformatPointerDeclarationOp(interface, change)));
return;
@@ -2593,8 +2634,8 @@ public:
m_loc.prefix().count(QLatin1String("\n")) + 2);
c.movePosition(QTextCursor::EndOfLine);
if (m_defpos == DefPosImplementationFile) {
- if (BaseTextEditorWidget *editor = refactoring.editorForFile(m_loc.fileName()))
- editor->setTextCursor(c);
+ if (targetFile->editor())
+ targetFile->editor()->setTextCursor(c);
} else {
assistInterface()->editor()->setTextCursor(c);
}
@@ -2621,7 +2662,7 @@ void InsertDefFromDecl::match(const CppQuickFixInterface &interface, QuickFixOpe
if (SimpleDeclarationAST *simpleDecl = node->asSimpleDeclaration()) {
if (idx > 0 && path.at(idx - 1)->asStatement())
return;
- if (simpleDecl->symbols && ! simpleDecl->symbols->next) {
+ if (simpleDecl->symbols && !simpleDecl->symbols->next) {
if (Symbol *symbol = simpleDecl->symbols->value) {
if (Declaration *decl = symbol->asDeclaration()) {
if (Function *func = decl->type()->asFunctionType()) {
@@ -3974,44 +4015,6 @@ private:
const ChangeSet::Range m_toRange;
};
-Namespace *isNamespaceFunction(const LookupContext &context, Function *function)
-{
- QTC_ASSERT(function, return 0);
- if (isMemberFunction(context, function))
- return 0;
-
- Scope *enclosingScope = function->enclosingScope();
- while (!(enclosingScope->isNamespace() || enclosingScope->isClass()))
- enclosingScope = enclosingScope->enclosingScope();
- QTC_ASSERT(enclosingScope != 0, return 0);
-
- const Name *functionName = function->name();
- if (!functionName)
- return 0; // anonymous function names are not valid c++
-
- // global namespace
- if (!functionName->isQualifiedNameId()) {
- foreach (Symbol *s, context.globalNamespace()->symbols()) {
- if (Namespace *matchingNamespace = s->asNamespace())
- return matchingNamespace;
- }
- return 0;
- }
-
- const QualifiedNameId *q = functionName->asQualifiedNameId();
- if (!q->base())
- return 0;
-
- if (ClassOrNamespace *binding = context.lookupType(q->base(), enclosingScope)) {
- foreach (Symbol *s, binding->symbols()) {
- if (Namespace *matchingNamespace = s->asNamespace())
- return matchingNamespace;
- }
- }
-
- return 0;
-}
-
} // anonymous namespace
void MoveFuncDefToDecl::match(const CppQuickFixInterface &interface, QuickFixOperations &result)
@@ -4078,8 +4081,7 @@ void MoveFuncDefToDecl::match(const CppQuickFixInterface &interface, QuickFixOpe
if (!declText.isEmpty())
break;
}
- }
- else if (Namespace *matchingNamespace = isNamespaceFunction(interface->context(), func)) {
+ } else if (Namespace *matchingNamespace = isNamespaceFunction(interface->context(), func)) {
// Dealing with free functions
bool isHeaderFile = false;
declFileName = correspondingHeaderOrSource(interface->fileName(), &isHeaderFile);
@@ -4410,8 +4412,7 @@ public:
m_factory->classFunctionModel->clear();
Overview printer = CppCodeStyleSettings::currentProjectCodeStyleOverview();
printer.showFunctionSignatures = true;
- const TextEditor::FontSettings &fs =
- TextEditor::TextEditorSettings::instance()->fontSettings();
+ const TextEditor::FontSettings &fs = TextEditor::TextEditorSettings::fontSettings();
const Format formatReimpFunc = fs.formatFor(C_DISABLED_CODE);
foreach (const Class *clazz, baseClasses) {
QStandardItem *itemBase = new QStandardItem(printer.prettyName(clazz->name()));
@@ -4615,7 +4616,7 @@ public:
const LookupContext targetContext(headerFile->cppDocument(), assistInterface()->snapshot());
const Class *targetClass = m_classAST->symbol;
- ClassOrNamespace *targetCoN = targetContext.lookupType(targetClass->scope());
+ ClassOrNamespace *targetCoN = targetContext.lookupType(targetClass->enclosingScope());
if (!targetCoN)
targetCoN = targetContext.globalNamespace();
UseMinimalNames useMinimalNames(targetCoN);
@@ -5052,4 +5053,187 @@ void InsertVirtualMethods::match(const CppQuickFixInterface &interface, QuickFix
delete op;
}
+namespace {
+
+class OptimizeForLoopOperation: public CppQuickFixOperation
+{
+public:
+ OptimizeForLoopOperation(const CppQuickFixInterface &interface, const ForStatementAST *forAst,
+ const bool optimizePostcrement, const ExpressionAST *expression,
+ const FullySpecifiedType type)
+ : CppQuickFixOperation(interface)
+ , m_forAst(forAst)
+ , m_optimizePostcrement(optimizePostcrement)
+ , m_expression(expression)
+ , m_type(type)
+ {
+ setDescription(QApplication::translate("CppTools::QuickFix", "Optimize for-Loop"));
+ }
+
+ void perform()
+ {
+ QTC_ASSERT(m_forAst, return);
+
+ const QString filename = assistInterface()->currentFile()->fileName();
+ const CppRefactoringChanges refactoring(assistInterface()->snapshot());
+ const CppRefactoringFilePtr file = refactoring.file(filename);
+ ChangeSet change;
+
+ // Optimize post (in|de)crement operator to pre (in|de)crement operator
+ if (m_optimizePostcrement && m_forAst->expression) {
+ PostIncrDecrAST *incrdecr = m_forAst->expression->asPostIncrDecr();
+ if (incrdecr && incrdecr->base_expression && incrdecr->incr_decr_token) {
+ change.flip(file->range(incrdecr->base_expression),
+ file->range(incrdecr->incr_decr_token));
+ }
+ }
+
+ // Optimize Condition
+ int renamePos = -1;
+ if (m_expression) {
+ QString varName = QLatin1String("total");
+
+ if (file->textOf(m_forAst->initializer).length() == 1) {
+ Overview oo = CppCodeStyleSettings::currentProjectCodeStyleOverview();
+ const QString typeAndName = oo.prettyType(m_type, varName);
+ renamePos = file->endOf(m_forAst->initializer) - 1 + typeAndName.length();
+ change.insert(file->endOf(m_forAst->initializer) - 1, // "-1" because of ";"
+ typeAndName + QLatin1String(" = ") + file->textOf(m_expression));
+ } else {
+ // Check if varName is already used
+ if (DeclarationStatementAST *ds = m_forAst->initializer->asDeclarationStatement()) {
+ if (DeclarationAST *decl = ds->declaration) {
+ if (SimpleDeclarationAST *sdecl = decl->asSimpleDeclaration()) {
+ for (;;) {
+ bool match = false;
+ for (DeclaratorListAST *it = sdecl->declarator_list; it;
+ it = it->next) {
+ if (file->textOf(it->value->core_declarator) == varName) {
+ varName += QLatin1Char('X');
+ match = true;
+ break;
+ }
+ }
+ if (!match)
+ break;
+ }
+ }
+ }
+ }
+
+ renamePos = file->endOf(m_forAst->initializer) + 1 + varName.length();
+ change.insert(file->endOf(m_forAst->initializer) - 1, // "-1" because of ";"
+ QLatin1String(", ") + varName + QLatin1String(" = ")
+ + file->textOf(m_expression));
+ }
+
+ ChangeSet::Range exprRange(file->startOf(m_expression), file->endOf(m_expression));
+ change.replace(exprRange, varName);
+ }
+
+ file->setChangeSet(change);
+ file->apply();
+
+ // Select variable name and trigger symbol rename
+ if (renamePos != -1) {
+ QTextCursor c = file->cursor();
+ c.setPosition(renamePos);
+ assistInterface()->editor()->setTextCursor(c);
+ assistInterface()->editor()->renameSymbolUnderCursor();
+ c.select(QTextCursor::WordUnderCursor);
+ assistInterface()->editor()->setTextCursor(c);
+ }
+ }
+
+private:
+ const ForStatementAST *m_forAst;
+ const bool m_optimizePostcrement;
+ const ExpressionAST *m_expression;
+ const FullySpecifiedType m_type;
+};
+
+} // anonymous namespace
+
+void OptimizeForLoop::match(const CppQuickFixInterface &interface, QuickFixOperations &result)
+{
+ const QList<AST *> path = interface->path();
+ ForStatementAST *forAst = 0;
+ if (!path.isEmpty())
+ forAst = path.last()->asForStatement();
+ if (!forAst || !interface->isCursorOn(forAst))
+ return;
+
+ // Check for optimizing a postcrement
+ const CppRefactoringFilePtr file = interface->currentFile();
+ bool optimizePostcrement = false;
+ if (forAst->expression) {
+ if (PostIncrDecrAST *incrdecr = forAst->expression->asPostIncrDecr()) {
+ const Token t = file->tokenAt(incrdecr->incr_decr_token);
+ if (t.is(T_PLUS_PLUS) || t.is(T_MINUS_MINUS))
+ optimizePostcrement = true;
+ }
+ }
+
+ // Check for optimizing condition
+ bool optimizeCondition = false;
+ FullySpecifiedType conditionType;
+ ExpressionAST *conditionExpression = 0;
+ if (forAst->initializer && forAst->condition) {
+ if (BinaryExpressionAST *binary = forAst->condition->asBinaryExpression()) {
+ // Get the expression against which we should evaluate
+ IdExpressionAST *conditionId = binary->left_expression->asIdExpression();
+ if (conditionId) {
+ conditionExpression = binary->right_expression;
+ } else {
+ conditionId = binary->right_expression->asIdExpression();
+ conditionExpression = binary->left_expression;
+ }
+
+ if (conditionId && conditionExpression
+ && !(conditionExpression->asNumericLiteral()
+ || conditionExpression->asStringLiteral()
+ || conditionExpression->asIdExpression()
+ || conditionExpression->asUnaryExpression())) {
+ // Determine type of for initializer
+ FullySpecifiedType initializerType;
+ if (DeclarationStatementAST *stmt = forAst->initializer->asDeclarationStatement()) {
+ if (stmt->declaration) {
+ if (SimpleDeclarationAST *decl = stmt->declaration->asSimpleDeclaration()) {
+ if (decl->symbols) {
+ if (Symbol *symbol = decl->symbols->value)
+ initializerType = symbol->type();
+ }
+ }
+ }
+ }
+
+ // Determine type of for condition
+ TypeOfExpression typeOfExpression;
+ typeOfExpression.init(interface->semanticInfo().doc, interface->snapshot(),
+ interface->context().bindings());
+ typeOfExpression.setExpandTemplates(true);
+ Scope *scope = file->scopeAt(conditionId->firstToken());
+ const QList<LookupItem> conditionItems = typeOfExpression(
+ conditionId, interface->semanticInfo().doc, scope);
+ if (!conditionItems.isEmpty())
+ conditionType = conditionItems.first().type();
+
+ if (conditionType.isValid()
+ && (file->textOf(forAst->initializer) == QLatin1String(";")
+ || initializerType == conditionType)) {
+ optimizeCondition = true;
+ }
+ }
+ }
+ }
+
+ if (optimizePostcrement || optimizeCondition) {
+ OptimizeForLoopOperation *op
+ = new OptimizeForLoopOperation(interface, forAst, optimizePostcrement,
+ (optimizeCondition) ? conditionExpression : 0,
+ conditionType);
+ result.append(QuickFixOperation::Ptr(op));
+ }
+}
+
#include "cppquickfixes.moc"
diff --git a/src/plugins/cppeditor/cppquickfixes.h b/src/plugins/cppeditor/cppquickfixes.h
index 9cc84c6b5d..e218bd02fa 100644
--- a/src/plugins/cppeditor/cppquickfixes.h
+++ b/src/plugins/cppeditor/cppquickfixes.h
@@ -584,6 +584,16 @@ private:
InsertVirtualMethodsDialog *m_dialog;
};
+/*!
+ Optimizes a for loop to avoid permanent condition check and forces to use preincrement
+ or predecrement operators in the expression of the for loop.
+ */
+class OptimizeForLoop : public CppQuickFixFactory
+{
+public:
+ void match(const CppQuickFixInterface &interface, TextEditor::QuickFixOperations &result);
+};
+
} // namespace Internal
} // namespace CppEditor
diff --git a/src/plugins/cppeditor/cppsnippetprovider.cpp b/src/plugins/cppeditor/cppsnippetprovider.cpp
index 6586ae67ae..85cb83ab00 100644
--- a/src/plugins/cppeditor/cppsnippetprovider.cpp
+++ b/src/plugins/cppeditor/cppsnippetprovider.cpp
@@ -36,8 +36,6 @@
#include <cpptools/cppqtstyleindenter.h>
-#include <texteditor/texteditorsettings.h>
-#include <texteditor/fontsettings.h>
#include <texteditor/snippets/snippeteditor.h>
#include <QLatin1String>
@@ -65,12 +63,7 @@ QString CppSnippetProvider::displayName() const
void CppSnippetProvider::decorateEditor(TextEditor::SnippetEditorWidget *editor) const
{
- CppHighlighter *highlighter = new CppHighlighter;
- const TextEditor::FontSettings &fs = TextEditor::TextEditorSettings::instance()->fontSettings();
- const QVector<QTextCharFormat> &formats =
- fs.toTextCharFormats(CPPEditorWidget::highlighterFormatCategories());
- highlighter->setFormats(formats.constBegin(), formats.constEnd());
- editor->setSyntaxHighlighter(highlighter);
+ editor->setSyntaxHighlighter(new CppHighlighter);
editor->setIndenter(new CppTools::CppQtStyleIndenter);
editor->setAutoCompleter(new CppAutoCompleter);
}
diff --git a/src/plugins/cppeditor/cpptypehierarchy.cpp b/src/plugins/cppeditor/cpptypehierarchy.cpp
index 2883a6f8f2..992623565a 100644
--- a/src/plugins/cppeditor/cpptypehierarchy.cpp
+++ b/src/plugins/cppeditor/cpptypehierarchy.cpp
@@ -99,6 +99,12 @@ public:
m_link = cppClass->link;
}
+ void clear()
+ {
+ QLabel::clear();
+ m_link = CPPEditorWidget::Link();
+ }
+
private:
void mousePressEvent(QMouseEvent *)
{
@@ -114,45 +120,42 @@ private:
CPPEditorWidget::Link m_link;
};
-} // namespace Internal
-} // namespace CppEditor
-
// CppTypeHierarchyWidget
-CppTypeHierarchyWidget::CppTypeHierarchyWidget(Core::IEditor *editor) :
+CppTypeHierarchyWidget::CppTypeHierarchyWidget() :
QWidget(0),
m_treeView(0),
m_model(0),
- m_delegate(0)
+ m_delegate(0),
+ m_noTypeHierarchyAvailableLabel(0)
{
+ m_inspectedClass = new CppClassLabel(this);
+ m_inspectedClass->setMargin(5);
+ m_model = new QStandardItemModel(this);
+ m_treeView = new NavigationTreeView(this);
+ m_delegate = new AnnotatedItemDelegate(this);
+ m_delegate->setDelimiter(QLatin1String(" "));
+ m_delegate->setAnnotationRole(AnnotationRole);
+ m_treeView->setModel(m_model);
+ m_treeView->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ m_treeView->setItemDelegate(m_delegate);
+ m_treeView->setRootIsDecorated(false);
+ connect(m_treeView, SIGNAL(clicked(QModelIndex)), this, SLOT(onItemClicked(QModelIndex)));
+
+ m_noTypeHierarchyAvailableLabel = new QLabel(tr("No type hierarchy available"), this);
+ m_noTypeHierarchyAvailableLabel->setAlignment(Qt::AlignCenter);
+ m_noTypeHierarchyAvailableLabel->setAutoFillBackground(true);
+ m_noTypeHierarchyAvailableLabel->setBackgroundRole(QPalette::Base);
+
QVBoxLayout *layout = new QVBoxLayout;
layout->setMargin(0);
layout->setSpacing(0);
+ layout->addWidget(m_inspectedClass);
+ layout->addWidget(m_treeView);
+ layout->addWidget(m_noTypeHierarchyAvailableLabel);
- if (qobject_cast<CPPEditor *>(editor)) {
- m_inspectedClass = new CppClassLabel(this);
- m_inspectedClass->setMargin(5);
- layout->addWidget(m_inspectedClass);
- m_model = new QStandardItemModel(this);
- m_treeView = new NavigationTreeView(this);
- m_delegate = new AnnotatedItemDelegate(this);
- m_delegate->setDelimiter(QLatin1String(" "));
- m_delegate->setAnnotationRole(AnnotationRole);
- m_treeView->setModel(m_model);
- m_treeView->setEditTriggers(QAbstractItemView::NoEditTriggers);
- m_treeView->setItemDelegate(m_delegate);
- m_treeView->setRootIsDecorated(false);
- layout->addWidget(m_treeView);
-
- connect(m_treeView, SIGNAL(clicked(QModelIndex)), this, SLOT(onItemClicked(QModelIndex)));
- connect(CppEditorPlugin::instance(), SIGNAL(typeHierarchyRequested()), this, SLOT(perform()));
- } else {
- QLabel *label = new QLabel(tr("No type hierarchy available"), this);
- label->setAlignment(Qt::AlignCenter);
- label->setAutoFillBackground(true);
- label->setBackgroundRole(QPalette::Base);
- layout->addWidget(label);
- }
setLayout(layout);
+
+ connect(CppEditorPlugin::instance(), SIGNAL(typeHierarchyRequested()), SLOT(perform()));
}
CppTypeHierarchyWidget::~CppTypeHierarchyWidget()
@@ -160,14 +163,17 @@ CppTypeHierarchyWidget::~CppTypeHierarchyWidget()
void CppTypeHierarchyWidget::perform()
{
- CPPEditor *editor = qobject_cast<CPPEditor *>(Core::EditorManager::instance()->currentEditor());
+ showNoTypeHierarchyLabel();
+
+ CPPEditor *editor = qobject_cast<CPPEditor *>(Core::EditorManager::currentEditor());
if (!editor)
return;
+
CPPEditorWidget *widget = qobject_cast<CPPEditorWidget *>(editor->widget());
if (!widget)
return;
- m_model->clear();
+ clearTypeHierarchy();
CppElementEvaluator evaluator(widget);
evaluator.setLookupBaseClasses(true);
@@ -185,11 +191,14 @@ void CppTypeHierarchyWidget::perform()
m_model->invisibleRootItem()->appendRow(derived);
buildHierarchy(*cppClass, derived, true, &CppClass::derived);
m_treeView->expandAll();
+
+ showTypeHierarchy();
}
}
}
-void CppTypeHierarchyWidget::buildHierarchy(const CppClass &cppClass, QStandardItem *parent, bool isRoot, const HierarchyMember member)
+void CppTypeHierarchyWidget::buildHierarchy(const CppClass &cppClass, QStandardItem *parent,
+ bool isRoot, const HierarchyMember member)
{
if (!isRoot) {
QStandardItem *item = itemForClass(cppClass);
@@ -200,6 +209,26 @@ void CppTypeHierarchyWidget::buildHierarchy(const CppClass &cppClass, QStandardI
buildHierarchy(klass, parent, false, member);
}
+void CppTypeHierarchyWidget::showNoTypeHierarchyLabel()
+{
+ m_inspectedClass->hide();
+ m_treeView->hide();
+ m_noTypeHierarchyAvailableLabel->show();
+}
+
+void CppTypeHierarchyWidget::showTypeHierarchy()
+{
+ m_inspectedClass->show();
+ m_treeView->show();
+ m_noTypeHierarchyAvailableLabel->hide();
+}
+
+void CppTypeHierarchyWidget::clearTypeHierarchy()
+{
+ m_inspectedClass->clear();
+ m_model->clear();
+}
+
void CppTypeHierarchyWidget::onItemClicked(const QModelIndex &index)
{
const TextEditor::BaseTextEditorWidget::Link link
@@ -214,7 +243,7 @@ void CppTypeHierarchyWidget::onItemClicked(const QModelIndex &index)
// CppTypeHierarchyStackedWidget
CppTypeHierarchyStackedWidget::CppTypeHierarchyStackedWidget(QWidget *parent) :
QStackedWidget(parent),
- m_typeHiearchyWidgetInstance(new CppTypeHierarchyWidget(Core::EditorManager::currentEditor()))
+ m_typeHiearchyWidgetInstance(new CppTypeHierarchyWidget)
{
addWidget(m_typeHiearchyWidgetInstance);
}
@@ -259,3 +288,7 @@ Core::NavigationView CppTypeHierarchyFactory::createWidget()
navigationView.widget = w;
return navigationView;
}
+
+} // namespace Internal
+} // namespace CppEditor
+
diff --git a/src/plugins/cppeditor/cpptypehierarchy.h b/src/plugins/cppeditor/cpptypehierarchy.h
index eb8f426925..5b06035845 100644
--- a/src/plugins/cppeditor/cpptypehierarchy.h
+++ b/src/plugins/cppeditor/cpptypehierarchy.h
@@ -65,7 +65,7 @@ class CppTypeHierarchyWidget : public QWidget
{
Q_OBJECT
public:
- CppTypeHierarchyWidget(Core::IEditor *editor);
+ CppTypeHierarchyWidget();
virtual ~CppTypeHierarchyWidget();
public slots:
@@ -76,13 +76,18 @@ private slots:
private:
typedef QList<CppClass> CppClass::*HierarchyMember;
- void buildHierarchy(const CppClass &cppClass, QStandardItem *parent, bool isRoot, HierarchyMember member);
+ void buildHierarchy(const CppClass &cppClass, QStandardItem *parent,
+ bool isRoot, HierarchyMember member);
+ void showNoTypeHierarchyLabel();
+ void showTypeHierarchy();
+ void clearTypeHierarchy();
CPPEditorWidget *m_cppEditor;
Utils::NavigationTreeView *m_treeView;
QStandardItemModel *m_model;
Utils::AnnotatedItemDelegate *m_delegate;
CppClassLabel *m_inspectedClass;
+ QLabel *m_noTypeHierarchyAvailableLabel;
};
// @todo: Pretty much the same design as the OutlineWidgetStack. Maybe we can generalize the
diff --git a/src/plugins/cppeditor/fileandtokenactions_test.cpp b/src/plugins/cppeditor/fileandtokenactions_test.cpp
index 0670b0fa5b..1dd403903f 100644
--- a/src/plugins/cppeditor/fileandtokenactions_test.cpp
+++ b/src/plugins/cppeditor/fileandtokenactions_test.cpp
@@ -105,7 +105,7 @@ public:
static void escape();
/// Undoing changes
- static void undoChangesInEditorWidget(BaseTextEditorWidget *editorWidget);
+ static void undoChangesInDocument(BaseTextDocument *editorDocument);
static void undoChangesInAllEditorWidgets();
/// Execute actions for the current cursor position of editorWidget.
@@ -135,7 +135,6 @@ typedef TestActionsTestCase::ActionPointer ActionPointer;
void TestActionsTestCase::run(const Actions &tokenActions, const Actions &fileActions)
{
CppModelManagerInterface *mm = CppModelManagerInterface::instance();
- EditorManager *em = EditorManager::instance();
// Collect files to process
QStringList filesToOpen;
@@ -175,10 +174,10 @@ void TestActionsTestCase::run(const Actions &tokenActions, const Actions &fileAc
undoAllChangesAndCloseAllEditors();
// Open editor
- QCOMPARE(em->openedEditors().size(), 0);
- CPPEditor *editor = dynamic_cast<CPPEditor *>(em->openEditor(filePath));
+ QCOMPARE(EditorManager::documentModel()->openedDocuments().size(), 0);
+ CPPEditor *editor = dynamic_cast<CPPEditor *>(EditorManager::openEditor(filePath));
QVERIFY(editor);
- QCOMPARE(em->openedEditors().size(), 1);
+ QCOMPARE(EditorManager::documentModel()->openedDocuments().size(), 1);
QVERIFY(mm->isCppEditor(editor));
QVERIFY(mm->workingCopy().contains(filePath));
@@ -197,7 +196,7 @@ void TestActionsTestCase::run(const Actions &tokenActions, const Actions &fileAc
Snapshot snapshot = mm->snapshot();
Document::Ptr document = snapshot.preprocessedDocument(
- editorWidget->document()->toPlainText(), filePath);
+ editorWidget->document()->toPlainText().toUtf8(), filePath);
QVERIFY(document);
document->parse();
TranslationUnit *translationUnit = document->translationUnit();
@@ -252,21 +251,19 @@ void TestActionsTestCase::escape()
QTest::keyClick(w, Qt::Key_Escape);
}
-void TestActionsTestCase::undoChangesInEditorWidget(BaseTextEditorWidget *editorWidget)
+void TestActionsTestCase::undoChangesInDocument(BaseTextDocument *editorDocument)
{
- QTextDocument * const document = editorWidget->document();
+ QTextDocument * const document = editorDocument->document();
QVERIFY(document);
while (document->isUndoAvailable())
- editorWidget->undo();
+ document->undo();
}
void TestActionsTestCase::undoChangesInAllEditorWidgets()
{
- EditorManager *em = EditorManager::instance();
- foreach (IEditor *editor, em->openedEditors()) {
- BaseTextEditor *baseTextEditor = qobject_cast<BaseTextEditor*>(editor);
- BaseTextEditorWidget *baseTextEditorWidget = baseTextEditor->editorWidget();
- undoChangesInEditorWidget(baseTextEditorWidget);
+ foreach (IDocument *document, EditorManager::documentModel()->openedDocuments()) {
+ BaseTextDocument *baseTextDocument = qobject_cast<BaseTextDocument *>(document);
+ undoChangesInDocument(baseTextDocument);
}
}
@@ -302,11 +299,10 @@ void TestActionsTestCase::moveWordCamelCaseToToken(TranslationUnit *translationU
void TestActionsTestCase::undoAllChangesAndCloseAllEditors()
{
- EditorManager *em = EditorManager::instance();
undoChangesInAllEditorWidgets();
- em->closeAllEditors(/*askAboutModifiedEditors =*/ false);
+ EditorManager::closeAllEditors(/*askAboutModifiedEditors =*/ false);
QApplication::processEvents();
- QCOMPARE(em->openedEditors().size(), 0);
+ QCOMPARE(EditorManager::documentModel()->openedDocuments().size(), 0);
}
void TestActionsTestCase::configureAllProjects(const QList<QPointer<ProjectExplorer::Project> >
@@ -335,10 +331,8 @@ public:
void FollowSymbolUnderCursorTokenAction::run(CPPEditorWidget *editorWidget)
{
- EditorManager *em = EditorManager::instance();
-
// Follow link
- IEditor *editorBefore = em->currentEditor();
+ IEditor *editorBefore = EditorManager::currentEditor();
const int originalLine = editorBefore->currentLine();
const int originalColumn = editorBefore->currentColumn();
editorWidget->openLinkUnderCursor();
@@ -346,9 +340,9 @@ void FollowSymbolUnderCursorTokenAction::run(CPPEditorWidget *editorWidget)
QApplication::processEvents();
// Go back
- IEditor *editorAfter = em->currentEditor();
+ IEditor *editorAfter = EditorManager::currentEditor();
if (editorAfter != editorBefore)
- em->goBackInNavigationHistory();
+ EditorManager::goBackInNavigationHistory();
else
editorBefore->gotoLine(originalLine, originalColumn);
QApplication::processEvents();
@@ -363,19 +357,17 @@ public:
void SwitchDeclarationDefinitionTokenAction::run(CPPEditorWidget *)
{
- EditorManager *em = EditorManager::instance();
-
// Switch Declaration/Definition
- IEditor *editorBefore = em->currentEditor();
+ IEditor *editorBefore = EditorManager::currentEditor();
const int originalLine = editorBefore->currentLine();
const int originalColumn = editorBefore->currentColumn();
CppEditor::Internal::CppEditorPlugin::instance()->switchDeclarationDefinition();
QApplication::processEvents();
// Go back
- IEditor *editorAfter = em->currentEditor();
+ IEditor *editorAfter = EditorManager::currentEditor();
if (editorAfter != editorBefore)
- em->goBackInNavigationHistory();
+ EditorManager::goBackInNavigationHistory();
else
editorBefore->gotoLine(originalLine, originalColumn);
QApplication::processEvents();
@@ -444,7 +436,8 @@ void InvokeCompletionTokenAction::run(CPPEditorWidget *editorWidget)
// editorWidget->setFocus();
QApplication::processEvents();
- TestActionsTestCase::undoChangesInEditorWidget(editorWidget);
+ BaseTextDocument *doc = qobject_cast<BaseTextDocument *>(editorWidget->editorDocument());
+ TestActionsTestCase::undoChangesInDocument(doc);
}
class RunAllQuickFixesTokenAction : public TestActionsTestCase::AbstractAction
@@ -502,17 +495,15 @@ public:
void SwitchHeaderSourceFileAction::run(CPPEditorWidget *)
{
- EditorManager *em = EditorManager::instance();
-
// Switch Header/Source
- IEditor *editorBefore = em->currentEditor();
+ IEditor *editorBefore = EditorManager::currentEditor();
CppTools::Internal::CppToolsPlugin::instance()->switchHeaderSource();
QApplication::processEvents();
// Go back
- IEditor *editorAfter = em->currentEditor();
+ IEditor *editorAfter = EditorManager::currentEditor();
if (editorAfter != editorBefore)
- em->goBackInNavigationHistory();
+ EditorManager::goBackInNavigationHistory();
QApplication::processEvents();
}
diff --git a/src/plugins/cppeditor/followsymbol_switchmethoddecldef_test.cpp b/src/plugins/cppeditor/followsymbol_switchmethoddecldef_test.cpp
index a236396de9..5e115202ff 100644
--- a/src/plugins/cppeditor/followsymbol_switchmethoddecldef_test.cpp
+++ b/src/plugins/cppeditor/followsymbol_switchmethoddecldef_test.cpp
@@ -144,7 +144,7 @@ public:
TestCase(CppEditorAction action, const QList<TestDocumentPtr> theTestFiles);
~TestCase();
- void run();
+ void run(bool expectedFail = false);
private:
TestCase(const TestCase &);
@@ -278,7 +278,7 @@ TestDocumentPtr TestCase::testFileWithTargetCursorMarker()
return TestDocumentPtr();
}
-void TestCase::run()
+void TestCase::run(bool expectedFail)
{
TestDocumentPtr initialTestFile = testFileWithInitialCursorMarker();
QVERIFY(initialTestFile);
@@ -308,16 +308,18 @@ void TestCase::run()
QCoreApplication::processEvents();
// Compare
- IEditor *currentEditor = EditorManager::instance()->currentEditor();
+ IEditor *currentEditor = EditorManager::currentEditor();
BaseTextEditor *currentTextEditor = dynamic_cast<BaseTextEditor*>(currentEditor);
QVERIFY(currentTextEditor);
- QCOMPARE(currentTextEditor->document()->fileName(), targetTestFile->filePath());
+ QCOMPARE(currentTextEditor->document()->filePath(), targetTestFile->filePath());
int expectedLine, expectedColumn;
currentTextEditor->convertPosition(targetTestFile->targetCursorPosition,
&expectedLine, &expectedColumn);
// qDebug() << "Expected line:" << expectedLine;
// qDebug() << "Expected column:" << expectedColumn;
+ if (expectedFail)
+ QEXPECT_FAIL("", "Contributor works on a fix.", Abort);
QCOMPARE(currentTextEditor->currentLine(), expectedLine);
QCOMPARE(currentTextEditor->currentColumn() - 1, expectedColumn);
}
@@ -583,7 +585,7 @@ void CppEditorPlugin::test_FollowSymbolUnderCursor_globalVarFromEnum()
;
TestCase test(TestCase::FollowSymbolUnderCursor, source);
- test.run();
+ test.run(/*expectedFail =*/ true);
}
void CppEditorPlugin::test_FollowSymbolUnderCursor_selfInitialization()
@@ -860,6 +862,42 @@ void CppEditorPlugin::test_FollowSymbolUnderCursor_funLocalVarHidesOuterClass()
test.run();
}
+void CppEditorPlugin::test_FollowSymbolUnderCursor_classConstructor()
+{
+ const QByteArray source =
+ "class Foo {\n"
+ " F@oo();"
+ " ~Foo();"
+ "};\n\n"
+ "Foo::$Foo()\n"
+ "{\n"
+ "}\n\n"
+ "Foo::~Foo()\n"
+ "{\n"
+ "}\n";
+
+ TestCase test(TestCase::FollowSymbolUnderCursor, source);
+ test.run();
+}
+
+void CppEditorPlugin::test_FollowSymbolUnderCursor_classDestructor()
+{
+ const QByteArray source =
+ "class Foo {\n"
+ " Foo();"
+ " ~@Foo();"
+ "};\n\n"
+ "Foo::Foo()\n"
+ "{\n"
+ "}\n\n"
+ "Foo::~$Foo()\n"
+ "{\n"
+ "}\n";
+
+ TestCase test(TestCase::FollowSymbolUnderCursor, source);
+ test.run();
+}
+
void CppEditorPlugin::test_FollowSymbolUnderCursor_using_QTCREATORBUG7903_globalNamespace()
{
const QByteArray source =
diff --git a/src/plugins/cpptools/CppTools.pluginspec.in b/src/plugins/cpptools/CppTools.pluginspec.in
index d677db481e..88a3b91356 100644
--- a/src/plugins/cpptools/CppTools.pluginspec.in
+++ b/src/plugins/cpptools/CppTools.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"CppTools\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"CppTools\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/cpptools/abstracteditorsupport.h b/src/plugins/cpptools/abstracteditorsupport.h
index 0c55994e74..e45a50e791 100644
--- a/src/plugins/cpptools/abstracteditorsupport.h
+++ b/src/plugins/cpptools/abstracteditorsupport.h
@@ -45,6 +45,7 @@ public:
explicit AbstractEditorSupport(CppModelManagerInterface *modelmanager);
virtual ~AbstractEditorSupport();
+ /// \returns the contents, encoded as UTF-8
virtual QByteArray contents() const = 0;
virtual QString fileName() const = 0;
diff --git a/src/plugins/cpptools/builtinindexingsupport.cpp b/src/plugins/cpptools/builtinindexingsupport.cpp
index cefa6894f8..faec76d150 100644
--- a/src/plugins/cpptools/builtinindexingsupport.cpp
+++ b/src/plugins/cpptools/builtinindexingsupport.cpp
@@ -57,10 +57,9 @@ static void parse(QFutureInterface<void> &future,
const QString fileName = files.at(i);
const bool isSourceFile = i < sourceCount;
- if (isSourceFile)
+ if (isSourceFile) {
(void) preproc->run(conf);
-
- else if (! processingHeaders) {
+ } else if (!processingHeaders) {
(void) preproc->run(conf);
processingHeaders = true;
@@ -101,7 +100,6 @@ public:
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
@@ -121,11 +119,20 @@ public:
foreach (const ModelItemInfo &info, modelInfos) {
int index = matcher.indexIn(info.symbolName);
if (index != -1) {
- QStringList path = info.fullyQualifiedName.mid(0,
- info.fullyQualifiedName.size() - 1);
+ QString text = info.symbolName;
+ QString scope = info.symbolScope;
+ if (info.type == ModelItemInfo::Method) {
+ QString name;
+ info.unqualifiedNameAndScope(info.symbolName, &name, &scope);
+ text = name + info.symbolType;
+ } else if (info.type == ModelItemInfo::Declaration){
+ text = ModelItemInfo::representDeclaration(info.symbolName,
+ info.symbolType);
+ }
+
Find::SearchResultItem item;
- item.path = path;
- item.text = info.symbolName;
+ item.path = scope.split(QLatin1String("::"), QString::SkipEmptyParts);
+ item.text = text;
item.textMarkPos = -1;
item.textMarkLength = 0;
item.icon = info.icon;
@@ -183,7 +190,7 @@ QFuture<void> BuiltinIndexingSupport::refreshSourceFiles(const QStringList &sour
m_synchronizer.clearFutures();
foreach (const QFuture<void> &future, futures) {
- if (! (future.isFinished() || future.isCanceled()))
+ if (!(future.isFinished() || future.isCanceled()))
m_synchronizer.addFuture(future);
}
}
@@ -191,9 +198,8 @@ QFuture<void> BuiltinIndexingSupport::refreshSourceFiles(const QStringList &sour
m_synchronizer.addFuture(result);
if (mode == CppModelManagerInterface::ForcedProgressNotification || sourceFiles.count() > 1) {
- Core::ICore::progressManager()->addTask(result,
- QCoreApplication::translate("CppTools::Internal::BuiltinIndexingSupport", "Parsing"),
- QLatin1String(CppTools::Constants::TASK_INDEX));
+ Core::ProgressManager::addTask(result, QCoreApplication::translate("CppTools::Internal::BuiltinIndexingSupport", "Parsing"),
+ CppTools::Constants::TASK_INDEX);
}
return result;
diff --git a/src/plugins/cpptools/completionsettingspage.cpp b/src/plugins/cpptools/completionsettingspage.cpp
index 92b249fc45..37ca2ed172 100644
--- a/src/plugins/cpptools/completionsettingspage.cpp
+++ b/src/plugins/cpptools/completionsettingspage.cpp
@@ -63,7 +63,7 @@ QWidget *CompletionSettingsPage::createPage(QWidget *parent)
m_page->setupUi(w);
const TextEditor::CompletionSettings &settings =
- TextEditor::TextEditorSettings::instance()->completionSettings();
+ TextEditor::TextEditorSettings::completionSettings();
int caseSensitivityIndex = 0;
switch (settings.m_caseSensitivity) {
@@ -131,7 +131,7 @@ void CompletionSettingsPage::apply()
settings.m_partiallyComplete = m_page->partiallyComplete->isChecked();
settings.m_spaceAfterFunctionName = m_page->spaceAfterFunctionName->isChecked();
- TextEditor::TextEditorSettings::instance()->setCompletionSettings(settings);
+ TextEditor::TextEditorSettings::setCompletionSettings(settings);
if (!requireCommentsSettingsUpdate())
return;
diff --git a/src/plugins/cpptools/cppchecksymbols.cpp b/src/plugins/cpptools/cppchecksymbols.cpp
index 2f076eead9..066e71f619 100644
--- a/src/plugins/cpptools/cppchecksymbols.cpp
+++ b/src/plugins/cpptools/cppchecksymbols.cpp
@@ -94,12 +94,12 @@ public:
protected:
void process(Document::Ptr doc, QSet<Namespace *> *processed)
{
- if (! doc)
+ if (!doc)
return;
- else if (! processed->contains(doc->globalNamespace())) {
+ if (!processed->contains(doc->globalNamespace())) {
processed->insert(doc->globalNamespace());
- foreach (const Document::Include &i, doc->includes())
+ foreach (const Document::Include &i, doc->resolvedIncludes())
process(_snapshot.document(i.resolvedFileName()), processed);
_mainDocument = (doc == _doc); // ### improve
@@ -115,7 +115,7 @@ protected:
void addType(const Name *name)
{
- if (! name) {
+ if (!name) {
return;
} else if (const QualifiedNameId *q = name->asQualifiedNameId()) {
@@ -130,7 +130,7 @@ protected:
void addField(const Name *name)
{
- if (! name) {
+ if (!name) {
return;
} else if (name->isNameId()) {
@@ -142,7 +142,7 @@ protected:
void addFunction(const Name *name)
{
- if (! name) {
+ if (!name) {
return;
} else if (name->isNameId()) {
@@ -153,7 +153,7 @@ protected:
void addStatic(const Name *name)
{
- if (! name) {
+ if (!name) {
return;
} else if (name->isNameId() || name->isTemplateNameId()) {
@@ -196,7 +196,7 @@ protected:
if (symbol->isTypedef())
addType(symbol->name());
- else if (! symbol->type()->isFunctionType() && symbol->enclosingScope()->isClass())
+ else if (!symbol->type()->isFunctionType() && symbol->enclosingScope()->isClass())
addField(symbol->name());
return true;
@@ -333,7 +333,7 @@ void CheckSymbols::run()
qSort(_macroUses.begin(), _macroUses.end(), sortByLinePredicate);
_doc->clearDiagnosticMessages();
- if (! isCanceled()) {
+ if (!isCanceled()) {
if (_doc->translationUnit()) {
accept(_doc->translationUnit()->ast());
_usages << QVector<Result>::fromList(_macroUses);
@@ -473,7 +473,7 @@ bool CheckSymbols::visit(NamespaceAST *ast)
{
if (ast->identifier_token) {
const Token &tok = tokenAt(ast->identifier_token);
- if (! tok.generated()) {
+ if (!tok.generated()) {
unsigned line, column;
getTokenStartPosition(ast->identifier_token, &line, &column);
Result use(line, column, tok.length(), CppHighlightingSupport::TypeUse);
@@ -499,7 +499,7 @@ bool CheckSymbols::visit(SimpleDeclarationAST *ast)
{
NameAST *declrIdNameAST = 0;
if (ast->declarator_list && !ast->declarator_list->next) {
- if (ast->symbols && ! ast->symbols->next && !ast->symbols->value->isGenerated()) {
+ if (ast->symbols && !ast->symbols->next && !ast->symbols->value->isGenerated()) {
Symbol *decl = ast->symbols->value;
if (NameAST *nameAST = declaratorId(ast->declarator_list->value)) {
if (Function *funTy = decl->type()->asFunctionType()) {
@@ -559,7 +559,7 @@ bool CheckSymbols::visit(ElaboratedTypeSpecifierAST *ast)
bool CheckSymbols::visit(MemberAccessAST *ast)
{
accept(ast->base_expression);
- if (! ast->member_name)
+ if (!ast->member_name)
return false;
if (const Name *name = ast->member_name->name) {
@@ -711,7 +711,7 @@ QByteArray CheckSymbols::textOf(AST *ast) const
void CheckSymbols::checkNamespace(NameAST *name)
{
- if (! name)
+ if (!name)
return;
unsigned line, column;
@@ -730,15 +730,15 @@ void CheckSymbols::checkNamespace(NameAST *name)
bool CheckSymbols::hasVirtualDestructor(Class *klass) const
{
- if (! klass)
+ if (!klass)
return false;
const Identifier *id = klass->identifier();
- if (! id)
+ if (!id)
return false;
for (Symbol *s = klass->find(id); s; s = s->next()) {
- if (! s->name())
+ if (!s->name())
continue;
- else if (s->name()->isDestructorNameId()) {
+ if (s->name()->isDestructorNameId()) {
if (Function *funTy = s->type()->asFunctionType()) {
if (funTy->isVirtual() && id->isEqualTo(s->identifier()))
return true;
@@ -754,9 +754,9 @@ bool CheckSymbols::hasVirtualDestructor(ClassOrNamespace *binding) const
QList<ClassOrNamespace *> todo;
todo.append(binding);
- while (! todo.isEmpty()) {
+ while (!todo.isEmpty()) {
ClassOrNamespace *b = todo.takeFirst();
- if (b && ! processed.contains(b)) {
+ if (b && !processed.contains(b)) {
processed.insert(b);
foreach (Symbol *s, b->symbols()) {
if (Class *k = s->asClass()) {
@@ -775,7 +775,7 @@ bool CheckSymbols::hasVirtualDestructor(ClassOrNamespace *binding) const
void CheckSymbols::checkName(NameAST *ast, Scope *scope)
{
if (ast && ast->name) {
- if (! scope)
+ if (!scope)
scope = enclosingScope();
if (ast->asDestructorName() != 0) {
@@ -796,7 +796,7 @@ void CheckSymbols::checkName(NameAST *ast, Scope *scope)
}
}
} else if (maybeType(ast->name) || maybeStatic(ast->name)) {
- if (! 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);
@@ -852,7 +852,10 @@ bool CheckSymbols::visit(QualifiedNameAST *ast)
addUse(ast->unqualified_name, CppHighlightingSupport::FunctionUse);
}
} else {
- maybeAddTypeOrStatic(binding->find(ast->unqualified_name->name), ast->unqualified_name);
+ QList<LookupItem> items = binding->find(ast->unqualified_name->name);
+ if (items.empty())
+ items = _context.lookup(ast->name, enclosingScope());
+ maybeAddTypeOrStatic(items, ast->unqualified_name);
}
if (TemplateIdAST *template_id = ast->unqualified_name->asTemplateId())
@@ -895,7 +898,7 @@ ClassOrNamespace *CheckSymbols::checkNestedName(QualifiedNameAST *ast)
}
accept(template_id->template_argument_list);
- if (! binding)
+ if (!binding)
continue;
}
@@ -1026,7 +1029,7 @@ bool CheckSymbols::visit(FunctionDefinitionAST *ast)
_astStack.append(thisFunction);
bool processEntireDeclr = true;
- if (ast->declarator && ast->symbol && ! ast->symbol->isGenerated()) {
+ if (ast->declarator && ast->symbol && !ast->symbol->isGenerated()) {
Function *fun = ast->symbol;
if (NameAST *declId = declaratorId(ast->declarator)) {
processEntireDeclr = false;
@@ -1077,7 +1080,7 @@ bool CheckSymbols::visit(FunctionDefinitionAST *ast)
void CheckSymbols::addUse(NameAST *ast, Kind kind)
{
- if (! ast)
+ if (!ast)
return;
if (QualifiedNameAST *q = ast->asQualifiedName())
@@ -1085,7 +1088,7 @@ void CheckSymbols::addUse(NameAST *ast, Kind kind)
if (DestructorNameAST *dtor = ast->asDestructorName())
ast = dtor->unqualified_name;
- if (! ast)
+ if (!ast)
return; // nothing to do
else if (ast->asOperatorFunctionId() != 0 || ast->asConversionFunctionId() != 0)
return; // nothing to do
@@ -1100,7 +1103,7 @@ void CheckSymbols::addUse(NameAST *ast, Kind kind)
void CheckSymbols::addUse(unsigned tokenIndex, Kind kind)
{
- if (! tokenIndex)
+ if (!tokenIndex)
return;
const Token &tok = tokenAt(tokenIndex);
@@ -1120,7 +1123,7 @@ void CheckSymbols::addUse(const Result &use)
if (use.isInvalid())
return;
- if (! enclosingFunctionDefinition()) {
+ if (!enclosingFunctionDefinition()) {
if (_usages.size() >= _chunkSize) {
if (use.line > _lineOfLastUsage)
flush();
@@ -1137,7 +1140,7 @@ void CheckSymbols::addUse(const Result &use)
void CheckSymbols::addType(ClassOrNamespace *b, NameAST *ast)
{
unsigned startToken;
- if (! b || !acceptName(ast, &startToken))
+ if (!b || !acceptName(ast, &startToken))
return;
const Token &tok = tokenAt(startToken);
@@ -1218,11 +1221,11 @@ bool CheckSymbols::maybeAddField(const QList<LookupItem> &candidates, NameAST *a
foreach (const LookupItem &r, candidates) {
Symbol *c = r.declaration();
- if (! c)
+ if (!c)
continue;
- else if (! c->isDeclaration())
+ else if (!c->isDeclaration())
return false;
- else if (! (c->enclosingScope() && c->enclosingScope()->isClass()))
+ else if (!(c->enclosingScope() && c->enclosingScope()->isClass()))
return false; // shadowed
else if (c->isTypedef() || (c->type() && c->type()->isFunctionType()))
return false; // shadowed
@@ -1261,7 +1264,7 @@ bool CheckSymbols::maybeAddFunction(const QList<LookupItem> &candidates, NameAST
Symbol *c = r.declaration();
// Skip current if there's no declaration or name.
- if (! c || !c->name())
+ if (!c || !c->name())
continue;
// In addition check for destructors, since the leading ~ is not taken into consideration.
@@ -1272,13 +1275,13 @@ bool CheckSymbols::maybeAddFunction(const QList<LookupItem> &candidates, NameAST
isConstructor = isConstructorDeclaration(c);
Function *funTy = c->type()->asFunctionType();
- if (! funTy) {
+ if (!funTy) {
//Try to find a template function
if (Template * t = r.type()->asTemplateType())
if ((c = t->declaration()))
funTy = c->type()->asFunctionType();
}
- if (! funTy)
+ if (!funTy)
continue; // TODO: add diagnostic messages and color call-operators calls too?
if (argumentCount < funTy->minimumArgumentCount()) {
@@ -1286,7 +1289,7 @@ bool CheckSymbols::maybeAddFunction(const QList<LookupItem> &candidates, NameAST
kind = funTy->isVirtual() ? CppHighlightingSupport::VirtualMethodUse : CppHighlightingSupport::FunctionUse;
matchType = Match_TooFewArgs;
}
- } else if (argumentCount > funTy->argumentCount() && ! funTy->isVariadic()) {
+ } else if (argumentCount > funTy->argumentCount() && !funTy->isVariadic()) {
if (matchType != Match_Ok) {
matchType = Match_TooManyArgs;
kind = funTy->isVirtual() ? CppHighlightingSupport::VirtualMethodUse : CppHighlightingSupport::FunctionUse;
@@ -1335,9 +1338,8 @@ NameAST *CheckSymbols::declaratorId(DeclaratorAST *ast) const
if (ast && ast->core_declarator) {
if (NestedDeclaratorAST *nested = ast->core_declarator->asNestedDeclarator())
return declaratorId(nested->declarator);
- else if (DeclaratorIdAST *declId = ast->core_declarator->asDeclaratorId()) {
+ if (DeclaratorIdAST *declId = ast->core_declarator->asDeclaratorId())
return declId->name;
- }
}
return 0;
diff --git a/src/plugins/cpptools/cppclassesfilter.cpp b/src/plugins/cpptools/cppclassesfilter.cpp
index 3c656d3fc6..316edb2898 100644
--- a/src/plugins/cpptools/cppclassesfilter.cpp
+++ b/src/plugins/cpptools/cppclassesfilter.cpp
@@ -32,18 +32,31 @@
using namespace CppTools;
using namespace CppTools::Internal;
-CppClassesFilter::CppClassesFilter(CppModelManager *manager)
- : CppLocatorFilter(manager)
+CppClassesFilter::CppClassesFilter(CppLocatorData *locatorData)
+ : CppLocatorFilter(locatorData)
{
setId("Classes");
setShortcutString(QLatin1String("c"));
setIncludedByDefault(false);
setDisplayName(tr("C++ Classes"));
-
- search.setSymbolsToSearchFor(SymbolSearcher::Classes);
- search.setSeparateScope(true);
}
CppClassesFilter::~CppClassesFilter()
{
}
+
+QList<QList<CppTools::ModelItemInfo> > CppClassesFilter::itemsToMatchUserInputAgainst() const
+{
+ return QList<QList<CppTools::ModelItemInfo> >() << m_data->classes();
+}
+
+Locator::FilterEntry CppClassesFilter::filterEntryFromModelItemInfo(const ModelItemInfo &info)
+{
+ const QVariant id = qVariantFromValue(info);
+ Locator::FilterEntry filterEntry(this, info.symbolName, id, info.icon);
+ filterEntry.extraInfo = info.symbolScope.isEmpty()
+ ? info.shortNativeFilePath()
+ : info.symbolScope;
+
+ return filterEntry;
+}
diff --git a/src/plugins/cpptools/cppclassesfilter.h b/src/plugins/cpptools/cppclassesfilter.h
index 52038d3638..cb0475dd48 100644
--- a/src/plugins/cpptools/cppclassesfilter.h
+++ b/src/plugins/cpptools/cppclassesfilter.h
@@ -31,6 +31,7 @@
#define CPPCLASSESFILTER_H
#include "cpptools_global.h"
+#include "cpplocatordata.h"
#include "cpplocatorfilter.h"
namespace CppTools {
@@ -40,8 +41,12 @@ class CPPTOOLS_EXPORT CppClassesFilter : public Internal::CppLocatorFilter
Q_OBJECT
public:
- CppClassesFilter(Internal::CppModelManager *manager);
+ CppClassesFilter(Internal::CppLocatorData *locatorData);
~CppClassesFilter();
+
+private:
+ QList<QList<CppTools::ModelItemInfo> > itemsToMatchUserInputAgainst() const;
+ Locator::FilterEntry filterEntryFromModelItemInfo(const ModelItemInfo &info);
};
} // namespace CppTools
diff --git a/src/plugins/cpptools/cppcodeformatter.cpp b/src/plugins/cpptools/cppcodeformatter.cpp
index 967bc9321c..72e0edb76f 100644
--- a/src/plugins/cpptools/cppcodeformatter.cpp
+++ b/src/plugins/cpptools/cppcodeformatter.cpp
@@ -519,9 +519,9 @@ void CodeFormatter::recalculateStateAfter(const QTextBlock &block)
int previousPreviousMarker = -1;
for (int i = size - 1; i >= 0; --i) {
if (m_currentState.at(i).type == cpp_macro_conditional) {
- if (previousMarker == -1)
+ if (previousMarker == -1) {
previousMarker = i;
- else {
+ } else {
previousPreviousMarker = i;
break;
}
@@ -840,7 +840,7 @@ bool CodeFormatter::tryDeclaration()
return true;
case T_IDENTIFIER:
if (m_tokenIndex == 0) {
- QString tokenText = currentTokenText().toString();
+ const QStringRef tokenText = currentTokenText();
if (tokenText.startsWith(QLatin1String("Q_"))
|| tokenText.startsWith(QLatin1String("QT_"))
|| tokenText.startsWith(QLatin1String("QML_"))
diff --git a/src/plugins/cpptools/cppcodemodelsettings.cpp b/src/plugins/cpptools/cppcodemodelsettings.cpp
new file mode 100644
index 0000000000..a115d16bd0
--- /dev/null
+++ b/src/plugins/cpptools/cppcodemodelsettings.cpp
@@ -0,0 +1,69 @@
+/****************************************************************************
+**
+** 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 "cppcodemodelsettings.h"
+#include "cppmodelmanagersupport.h"
+#include "cpptoolsconstants.h"
+
+using namespace CppTools;
+using namespace CppTools::Internal;
+
+void CppCodeModelSettings::fromSettings(QSettings *s)
+{
+ s->beginGroup(QLatin1String(Constants::CPPTOOLS_SETTINGSGROUP));
+ QVariant supporters = s->value(QLatin1String(Constants::CPPTOOLS_MODEL_MANAGER_SUPPORTERS_KEY));
+ setIdForMimeType(supporters, QLatin1String(Constants::C_SOURCE_MIMETYPE));
+ setIdForMimeType(supporters, QLatin1String(Constants::CPP_SOURCE_MIMETYPE));
+ setIdForMimeType(supporters, QLatin1String(Constants::OBJECTIVE_C_SOURCE_MIMETYPE));
+ setIdForMimeType(supporters, QLatin1String(Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE));
+ s->endGroup();
+}
+
+void CppCodeModelSettings::toSettings(QSettings *s)
+{
+ s->beginGroup(QLatin1String(Constants::CPPTOOLS_SETTINGSGROUP));
+ QHash<QString, QVariant> var;
+ foreach (const QString &mimeType, m_modelManagerSupportByMimeType.keys())
+ var[mimeType] = m_modelManagerSupportByMimeType[mimeType];
+ s->setValue(QLatin1String(Constants::CPPTOOLS_MODEL_MANAGER_SUPPORTERS_KEY), QVariant(var));
+ s->endGroup();
+}
+
+void CppCodeModelSettings::setModelManagerSupports(const QList<ModelManagerSupport *> &supporters)
+{
+ m_availableModelManagerSupportersByName.clear();
+ foreach (ModelManagerSupport *supporter, supporters)
+ m_availableModelManagerSupportersByName[supporter->displayName()] = supporter->id();
+}
+
+void CppCodeModelSettings::setIdForMimeType(const QVariant &var, const QString &mimeType)
+{
+ QHash<QString, QVariant> mimeToId = var.toHash();
+ m_modelManagerSupportByMimeType[mimeType] = mimeToId.value(mimeType, defaultId()).toString();
+}
diff --git a/src/plugins/cpptools/cppcompletionsupport.h b/src/plugins/cpptools/cppcodemodelsettings.h
index 216317e232..be4042a318 100644
--- a/src/plugins/cpptools/cppcompletionsupport.h
+++ b/src/plugins/cpptools/cppcodemodelsettings.h
@@ -27,47 +27,49 @@
**
****************************************************************************/
-#ifndef CPPTOOLS_CPPCOMPLETIONSUPPORT_H
-#define CPPTOOLS_CPPCOMPLETIONSUPPORT_H
+#ifndef CPPTOOLS_INTERNAL_CPPCODEMODELSETTINGS_H
+#define CPPTOOLS_INTERNAL_CPPCODEMODELSETTINGS_H
-#include "cpptools_global.h"
+#include <QHash>
+#include <QList>
+#include <QSettings>
+#include <QString>
-#include <texteditor/codeassist/assistenums.h>
-
-QT_BEGIN_NAMESPACE
-class QTextDocument;
-QT_END_NAMESPACE
-
-namespace ProjectExplorer {
-class Project;
-}
+namespace CppTools {
-namespace TextEditor {
-class IAssistInterface;
-class ITextEditor;
-}
+class ModelManagerSupport;
-namespace CppTools {
+namespace Internal {
-class CPPTOOLS_EXPORT CppCompletionSupport
+class CppCodeModelSettings
{
+ QHash<QString, QString> m_modelManagerSupportByMimeType;
+ QHash<QString, QString> m_availableModelManagerSupportersByName;
+ QString m_defaultId;
+
public:
- CppCompletionSupport(TextEditor::ITextEditor *editor);
- virtual ~CppCompletionSupport() = 0;
+ void fromSettings(QSettings *s);
+ void toSettings(QSettings *s);
+
+ void setModelManagerSupports(const QList<ModelManagerSupport *> &supporters);
+
+ QString &modelManagerSupportId(const QString &mimeType)
+ { return m_modelManagerSupportByMimeType[mimeType]; }
+
+ const QHash<QString, QString> &availableModelManagerSupportersByName() const
+ { return m_availableModelManagerSupportersByName; }
- virtual TextEditor::IAssistInterface *createAssistInterface(ProjectExplorer::Project *project,
- QTextDocument *document,
- int position,
- TextEditor::AssistReason reason) const = 0;
+ QString defaultId() const
+ { return m_defaultId; }
-protected:
- TextEditor::ITextEditor *editor() const
- { return m_editor; }
+ void setDefaultId(const QString &defaultId)
+ { m_defaultId = defaultId; }
private:
- TextEditor::ITextEditor *m_editor;
+ void setIdForMimeType(const QVariant &var, const QString &mimeType);
};
+} // namespace Internal
} // namespace CppTools
-#endif // CPPTOOLS_CPPCOMPLETIONSUPPORT_H
+#endif // CPPTOOLS_INTERNAL_CPPCODEMODELSETTINGS_H
diff --git a/src/plugins/cpptools/cppcodemodelsettingspage.cpp b/src/plugins/cpptools/cppcodemodelsettingspage.cpp
new file mode 100644
index 0000000000..af18b70445
--- /dev/null
+++ b/src/plugins/cpptools/cppcodemodelsettingspage.cpp
@@ -0,0 +1,148 @@
+/****************************************************************************
+**
+** 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 "cppcodemodelsettingspage.h"
+#include "cpptoolsconstants.h"
+#include "ui_cppcodemodelsettingspage.h"
+
+#include <coreplugin/icore.h>
+
+#include <QTextStream>
+
+using namespace CppTools;
+using namespace CppTools::Internal;
+
+CppCodeModelSettingsWidget::CppCodeModelSettingsWidget(QWidget *parent)
+ : QWidget(parent)
+ , m_ui(new Ui::CppCodeModelSettingsPage)
+{
+ m_ui->setupUi(this);
+}
+
+CppCodeModelSettingsWidget::~CppCodeModelSettingsWidget()
+{
+ delete m_ui;
+}
+
+void CppCodeModelSettingsWidget::setSettings(const QSharedPointer<CppCodeModelSettings> &s)
+{
+ m_settings = s;
+
+ applyToWidget(m_ui->cChooser, QLatin1String(Constants::C_SOURCE_MIMETYPE));
+ applyToWidget(m_ui->cppChooser, QLatin1String(Constants::CPP_SOURCE_MIMETYPE));
+ applyToWidget(m_ui->objcChooser, QLatin1String(Constants::OBJECTIVE_C_SOURCE_MIMETYPE));
+ applyToWidget(m_ui->objcppChooser, QLatin1String(Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE));
+}
+
+void CppCodeModelSettingsWidget::applyToWidget(QComboBox *chooser, const QString &mimeType) const
+{
+ chooser->clear();
+
+ QStringList names = m_settings->availableModelManagerSupportersByName().keys();
+ qSort(names);
+ foreach (const QString &name, names) {
+ const QString &id = m_settings->availableModelManagerSupportersByName()[name];
+ chooser->addItem(name, id);
+ if (id == m_settings->modelManagerSupportId(mimeType))
+ chooser->setCurrentIndex(chooser->count() - 1);
+ }
+ chooser->setEnabled(names.size() > 1);
+}
+
+void CppCodeModelSettingsWidget::applyToSettings() const
+{
+ bool changed = false;
+ changed |= applyToSettings(m_ui->cChooser, QLatin1String(Constants::C_SOURCE_MIMETYPE));
+ changed |= applyToSettings(m_ui->cppChooser, QLatin1String(Constants::CPP_SOURCE_MIMETYPE));
+ changed |= applyToSettings(m_ui->objcChooser,
+ QLatin1String(Constants::OBJECTIVE_C_SOURCE_MIMETYPE));
+ changed |= applyToSettings(m_ui->objcppChooser,
+ QLatin1String(Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE));
+
+ if (changed)
+ m_settings->toSettings(Core::ICore::settings());
+}
+
+QString CppCodeModelSettingsWidget::searchKeywords() const
+{
+ QString rc;
+ QTextStream ts(&rc);
+ ts << m_ui->theGroupBox->title()
+ << ' ' << m_ui->cLabel->text()
+ << ' ' << m_ui->cppLabel->text()
+ << ' ' << m_ui->objcLabel->text()
+ << ' ' << m_ui->objcppLabel->text();
+ foreach (const QString &mmsNames, m_settings->availableModelManagerSupportersByName().keys())
+ ts << ' ' << mmsNames;
+ rc.remove(QLatin1Char('&'));
+ return rc;
+}
+
+bool CppCodeModelSettingsWidget::applyToSettings(QComboBox *chooser, const QString &mimeType) const
+{
+ QString newId = chooser->itemData(chooser->currentIndex()).toString();
+ QString &currentId = m_settings->modelManagerSupportId(mimeType);
+ if (newId == currentId)
+ return false;
+
+ currentId = newId;
+ return true;
+}
+
+CppCodeModelSettingsPage::CppCodeModelSettingsPage(QSharedPointer<CppCodeModelSettings> &settings,
+ QObject *parent)
+ : Core::IOptionsPage(parent)
+ , m_settings(settings)
+{
+ setId(Constants::CPP_CODE_MODEL_SETTINGS_ID);
+ setDisplayName(QCoreApplication::translate("CppTools",Constants::CPP_CODE_MODEL_SETTINGS_NAME));
+ setCategory(Constants::CPP_SETTINGS_CATEGORY);
+ setDisplayCategory(QCoreApplication::translate("CppTools",Constants::CPP_SETTINGS_TR_CATEGORY));
+ setCategoryIcon(QLatin1String(Constants::SETTINGS_CATEGORY_CPP_ICON));
+}
+
+QWidget *CppCodeModelSettingsPage::createPage(QWidget *parent)
+{
+ m_widget = new CppCodeModelSettingsWidget(parent);
+ m_widget->setSettings(m_settings);
+ if (m_searchKeywords.isEmpty())
+ m_searchKeywords = m_widget->searchKeywords();
+ return m_widget;
+}
+
+void CppCodeModelSettingsPage::apply()
+{
+ if (m_widget)
+ m_widget->applyToSettings();
+}
+
+bool CppCodeModelSettingsPage::matches(const QString &s) const
+{
+ return m_searchKeywords.contains(s, Qt::CaseInsensitive);
+}
diff --git a/src/plugins/cpptools/cppcodemodelsettingspage.h b/src/plugins/cpptools/cppcodemodelsettingspage.h
new file mode 100644
index 0000000000..310671e6be
--- /dev/null
+++ b/src/plugins/cpptools/cppcodemodelsettingspage.h
@@ -0,0 +1,90 @@
+/****************************************************************************
+**
+** 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 CPPTOOLS_INTERNAL_CPPCODEMODELSETTINGSPAGE_H
+#define CPPTOOLS_INTERNAL_CPPCODEMODELSETTINGSPAGE_H
+
+#include "cppcodemodelsettings.h"
+
+#include <coreplugin/dialogs/ioptionspage.h>
+
+#include <QPointer>
+#include <QWidget>
+
+QT_FORWARD_DECLARE_CLASS(QComboBox)
+QT_FORWARD_DECLARE_CLASS(QSettings)
+
+namespace CppTools {
+namespace Internal {
+
+namespace Ui { class CppCodeModelSettingsPage; }
+
+class CppCodeModelSettingsWidget: public QWidget
+{
+ Q_OBJECT
+
+public:
+ explicit CppCodeModelSettingsWidget(QWidget *parent = 0);
+ ~CppCodeModelSettingsWidget();
+
+ void setSettings(const QSharedPointer<CppCodeModelSettings> &s);
+ void applyToSettings() const;
+
+ QString searchKeywords() const;
+
+private:
+ bool applyToSettings(QComboBox *chooser, const QString &mimeType) const;
+ void applyToWidget(QComboBox *chooser, const QString &mimeType) const;
+
+private:
+ Ui::CppCodeModelSettingsPage *m_ui;
+ QSharedPointer<CppCodeModelSettings> m_settings;
+};
+
+class CppCodeModelSettingsPage: public Core::IOptionsPage
+{
+public:
+ explicit CppCodeModelSettingsPage(QSharedPointer<CppCodeModelSettings> &settings,
+ QObject *parent = 0);
+
+ QWidget *createPage(QWidget *parent);
+ void apply();
+ void finish() { }
+ bool matches(const QString &s) const;
+
+private:
+ const QSharedPointer<CppCodeModelSettings> m_settings;
+ QPointer<CppCodeModelSettingsWidget> m_widget;
+ QString m_searchKeywords;
+};
+
+} // Internal namespace
+} // CppTools namespace
+
+#endif // CPPTOOLS_INTERNAL_CPPCODEMODELSETTINGSPAGE_H
diff --git a/src/plugins/cpptools/cppcodemodelsettingspage.ui b/src/plugins/cpptools/cppcodemodelsettingspage.ui
new file mode 100644
index 0000000000..70155c527b
--- /dev/null
+++ b/src/plugins/cpptools/cppcodemodelsettingspage.ui
@@ -0,0 +1,97 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>CppTools::Internal::CppCodeModelSettingsPage</class>
+ <widget class="QWidget" name="CppTools::Internal::CppCodeModelSettingsPage">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>629</width>
+ <height>374</height>
+ </rect>
+ </property>
+ <property name="windowTitle">
+ <string>Form</string>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout">
+ <item>
+ <widget class="QGroupBox" name="theGroupBox">
+ <property name="title">
+ <string>Code Completion and Semantic Highlighting</string>
+ </property>
+ <layout class="QFormLayout" name="formLayout">
+ <item row="0" column="0">
+ <widget class="QLabel" name="cLabel">
+ <property name="text">
+ <string>C</string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="1">
+ <widget class="QComboBox" name="cChooser">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Expanding" vsizetype="Fixed">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="0">
+ <widget class="QLabel" name="cppLabel">
+ <property name="text">
+ <string>C++</string>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="1">
+ <widget class="QComboBox" name="cppChooser">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="MinimumExpanding" vsizetype="Fixed">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="0">
+ <widget class="QLabel" name="objcLabel">
+ <property name="text">
+ <string>Objective C</string>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="1">
+ <widget class="QComboBox" name="objcChooser"/>
+ </item>
+ <item row="3" column="0">
+ <widget class="QLabel" name="objcppLabel">
+ <property name="text">
+ <string>Objective C++</string>
+ </property>
+ </widget>
+ </item>
+ <item row="3" column="1">
+ <widget class="QComboBox" name="objcppChooser"/>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item>
+ <spacer name="verticalSpacer">
+ <property name="orientation">
+ <enum>Qt::Vertical</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>20</width>
+ <height>151</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/src/plugins/cpptools/cppcodestylesettings.cpp b/src/plugins/cpptools/cppcodestylesettings.cpp
index 742b562d57..057a8cbd7f 100644
--- a/src/plugins/cpptools/cppcodestylesettings.cpp
+++ b/src/plugins/cpptools/cppcodestylesettings.cpp
@@ -210,7 +210,7 @@ static void configureOverviewWithCodeStyleSettings(CPlusPlus::Overview &overview
CPlusPlus::Overview CppCodeStyleSettings::currentProjectCodeStyleOverview()
{
ProjectExplorer::Project *project = ProjectExplorer::ProjectExplorerPlugin::currentProject();
- if (! project)
+ if (!project)
return currentGlobalCodeStyleOverview();
ProjectExplorer::EditorConfiguration *editorConfiguration = project->editorConfiguration();
diff --git a/src/plugins/cpptools/cppcodestylesettingspage.cpp b/src/plugins/cpptools/cppcodestylesettingspage.cpp
index 01a0589eb5..ca94a0ec57 100644
--- a/src/plugins/cpptools/cppcodestylesettingspage.cpp
+++ b/src/plugins/cpptools/cppcodestylesettingspage.cpp
@@ -275,9 +275,8 @@ CppCodeStylePreferencesWidget::CppCodeStylePreferencesWidget(QWidget *parent)
for (int i = 0; i < m_previews.size(); ++i)
m_previews[i]->setPlainText(QLatin1String(defaultCodeStyleSnippets[i]));
- TextEditor::TextEditorSettings *textEditorSettings = TextEditorSettings::instance();
- decorateEditors(textEditorSettings->fontSettings());
- connect(textEditorSettings, SIGNAL(fontSettingsChanged(TextEditor::FontSettings)),
+ decorateEditors(TextEditorSettings::fontSettings());
+ connect(TextEditorSettings::instance(), SIGNAL(fontSettingsChanged(TextEditor::FontSettings)),
this, SLOT(decorateEditors(TextEditor::FontSettings)));
setVisualizeWhitespace(true);
@@ -575,8 +574,7 @@ QWidget *CppCodeStyleSettingsPage::createPage(QWidget *parent)
m_pageCppCodeStylePreferences->setCurrentDelegate(originalCodeStylePreferences->currentDelegate());
// we set id so that it won't be possible to set delegate to the original prefs
m_pageCppCodeStylePreferences->setId(originalCodeStylePreferences->id());
- TextEditorSettings *settings = TextEditorSettings::instance();
- m_widget = new CodeStyleEditor(settings->codeStyleFactory(CppTools::Constants::CPP_SETTINGS_ID),
+ m_widget = new CodeStyleEditor(TextEditorSettings::codeStyleFactory(CppTools::Constants::CPP_SETTINGS_ID),
m_pageCppCodeStylePreferences, parent);
return m_widget;
diff --git a/src/plugins/cpptools/cppcompletion_test.cpp b/src/plugins/cpptools/cppcompletion_test.cpp
index d08f62a172..3616561d09 100644
--- a/src/plugins/cpptools/cppcompletion_test.cpp
+++ b/src/plugins/cpptools/cppcompletion_test.cpp
@@ -34,6 +34,7 @@
#include <coreplugin/plugintestutils.h>
#include <texteditor/plaintexteditor.h>
#include <texteditor/codeassist/iassistproposal.h>
+#include <texteditor/convenience.h>
#include <utils/changeset.h>
#include <utils/fileutils.h>
@@ -101,7 +102,7 @@ public:
QStringList completions;
CppCompletionAssistInterface *ai
= new CppCompletionAssistInterface(editorWidget->document(), position,
- editorWidget->editorDocument()->fileName(),
+ editorWidget->editorDocument()->filePath(),
ExplicitlyInvoked, snapshot,
QStringList(), QStringList());
CppCompletionAssistProcessor processor;
@@ -115,6 +116,14 @@ public:
if (!listmodel)
return completions;
+ const int pos = proposal->basePosition();
+ const int length = position - pos;
+ const QString prefix = Convenience::textAt(QTextCursor(editorWidget->document()), pos, length);
+ if (!prefix.isEmpty())
+ listmodel->filter(prefix);
+ if (listmodel->isSortable(prefix))
+ listmodel->sort(prefix);
+
for (int i = 0; i < listmodel->size(); ++i)
completions << listmodel->text(i);
@@ -2062,6 +2071,676 @@ void CppToolsPlugin::test_completion_recursive_using_typedef_declarations()
QCOMPARE(completions.size(), 0);
}
+void CppToolsPlugin::test_completion_prefix_first_QTCREATORBUG_8737()
+{
+ const QByteArray source =
+ "void f()\n"
+ "{\n"
+ " int a_b_c, a_c, a_c_a;\n"
+ " @;\n"
+ " // padding so we get the scope right\n"
+ "}\n"
+ ;
+ CompletionTestCase test(source, "a_c");
+
+ QStringList completions = test.getCompletions();
+
+ QVERIFY(completions.size() >= 2);
+ QCOMPARE(completions.at(0), QLatin1String("a_c"));
+ QCOMPARE(completions.at(1), QLatin1String("a_c_a"));
+ QVERIFY(completions.contains(QLatin1String("a_b_c")));
+}
+
+void CppToolsPlugin::test_completion_prefix_first_QTCREATORBUG_9236()
+{
+ const QByteArray source =
+ "class r_etclass\n"
+ "{\n"
+ "public:\n"
+ " int raEmTmber;\n"
+ " void r_e_t(int re_t)\n"
+ " {\n"
+ " int r_et;\n"
+ " int rETUCASE;\n"
+ " @\n"
+ " // padding so we get the scope right\n"
+ " }\n"
+ "};\n"
+ ;
+ CompletionTestCase test(source, "ret");
+
+ QStringList completions = test.getCompletions();
+
+ QVERIFY(completions.size() >= 2);
+ QCOMPARE(completions.at(0), QLatin1String("return"));
+ QCOMPARE(completions.at(1), QLatin1String("rETUCASE"));
+ QVERIFY(completions.contains(QLatin1String("r_etclass")));
+ QVERIFY(completions.contains(QLatin1String("raEmTmber")));
+ QVERIFY(completions.contains(QLatin1String("r_e_t")));
+ QVERIFY(completions.contains(QLatin1String("re_t")));
+ QVERIFY(completions.contains(QLatin1String("r_et")));
+}
+
+void CppToolsPlugin::test_completion_class_declaration_inside_function_or_block_QTCREATORBUG3620()
+{
+ test_completion();
+}
+
+void CppToolsPlugin::test_completion_class_declaration_inside_function_or_block_QTCREATORBUG3620_data()
+{
+ QTest::addColumn<QByteArray>("code");
+ QTest::addColumn<QStringList>("expectedCompletions");
+
+ QByteArray code;
+ QStringList completions;
+
+ code = "\n"
+ "void foo()\n"
+ "{\n"
+ " struct C { int m; };\n"
+ " C c;\n"
+ " @\n"
+ " // padding so we get the scope right\n"
+ "}\n";
+ completions.append(QLatin1String("C"));
+ completions.append(QLatin1String("m"));
+ QTest::newRow("case: class definition inside function")
+ << code << completions;
+
+ completions.clear();
+
+ code = "\n"
+ "void foo()\n"
+ "{\n"
+ " {\n"
+ " struct C { int m; };\n"
+ " C c;\n"
+ " @\n"
+ " // padding so we get the scope right\n"
+ " }\n"
+ "}\n"
+ ;
+ completions.append(QLatin1String("C"));
+ completions.append(QLatin1String("m"));
+ QTest::newRow("case: class definition inside block inside function")
+ << code << completions;
+
+ completions.clear();
+
+ code = "\n"
+ "void foo()\n"
+ "{\n"
+ " {\n"
+ " struct C { int m1; };\n"
+ " }\n"
+ " {\n"
+ " struct C { int m2; };\n"
+ " C c;\n"
+ " @\n"
+ " // padding so we get the scope right\n"
+ " }\n"
+ "}\n"
+ ;
+ completions.append(QLatin1String("C"));
+ completions.append(QLatin1String("m2"));
+ QTest::newRow("case: class definition with the same name inside different block inside function")
+ << code << completions;
+
+ completions.clear();
+}
+
+void CppToolsPlugin::test_completion_namespace_alias_inside_function_or_block_QTCREATORBUG166()
+{
+ test_completion();
+}
+
+void CppToolsPlugin::test_completion_namespace_alias_inside_function_or_block_QTCREATORBUG166_data()
+{
+ QTest::addColumn<QByteArray>("code");
+ QTest::addColumn<QStringList>("expectedCompletions");
+
+ QByteArray code;
+ QStringList completions;
+
+ code = "\n"
+ "namespace NS1\n"
+ "{\n"
+ "namespace NS2\n"
+ "{\n"
+ " struct C\n"
+ " {\n"
+ " int m;\n"
+ " };\n"
+ "}\n"
+ "void foo()\n"
+ "{\n"
+ " namespace NS = NS1::NS2;\n"
+ " NS::C c;\n"
+ " @\n"
+ " // padding so we get the scope right\n"
+ "}\n"
+ ;
+ completions.append(QLatin1String("C"));
+ completions.append(QLatin1String("m"));
+ QTest::newRow("case: namespace alias inside function")
+ << code << completions;
+
+ completions.clear();
+
+ code = "\n"
+ "namespace NS1\n"
+ "{\n"
+ "namespace NS2\n"
+ "{\n"
+ " struct C\n"
+ " {\n"
+ " int m;\n"
+ " };\n"
+ "}\n"
+ "void foo()\n"
+ "{\n"
+ " {\n"
+ " namespace NS = NS1::NS2;\n"
+ " NS::C c;\n"
+ " @\n"
+ " // padding so we get the scope right\n"
+ " }\n"
+ "}\n"
+ ;
+ completions.append(QLatin1String("C"));
+ completions.append(QLatin1String("m"));
+ QTest::newRow("case: namespace alias inside block inside function")
+ << code << completions;
+
+ completions.clear();
+}
+
+void CppToolsPlugin::test_completion_class_declaration_inside_function_or_block_QTCREATORBUG3620_static_member()
+{
+ const QByteArray source =
+ "void foo()\n"
+ "{\n"
+ " {\n"
+ " struct C { static void staticFun1(); int m1; };\n"
+ " }\n"
+ " {\n"
+ " struct C { static void staticFun2(); int m2; };\n"
+ " @\n"
+ " // padding so we get the scope right\n"
+ " }\n"
+ "}\n"
+ ;
+ CompletionTestCase test(source, "C::");
+
+ const QStringList completions = test.getCompletions();
+
+ QCOMPARE(completions.size(), 3);
+ QVERIFY(completions.contains(QLatin1String("C")));
+ QVERIFY(completions.contains(QLatin1String("staticFun2")));
+ QVERIFY(completions.contains(QLatin1String("m2")));
+}
+
+void CppToolsPlugin::test_completion_enum_inside_block_inside_function_QTCREATORBUG5456()
+{
+ const QByteArray source =
+ "void foo()\n"
+ "{\n"
+ " {\n"
+ " enum E { e1, e2, e3 };\n"
+ " @\n"
+ " // padding so we get the scope right\n"
+ " }\n"
+ "}\n"
+ ;
+ CompletionTestCase test(source, "E::");
+
+ const QStringList completions = test.getCompletions();
+
+ QCOMPARE(completions.size(), 4);
+ QVERIFY(completions.contains(QLatin1String("E")));
+ QVERIFY(completions.contains(QLatin1String("e1")));
+ QVERIFY(completions.contains(QLatin1String("e2")));
+ QVERIFY(completions.contains(QLatin1String("e3")));
+}
+
+void CppToolsPlugin::test_completion_enum_inside_function_QTCREATORBUG5456()
+{
+ const QByteArray source =
+ "void foo()\n"
+ "{\n"
+ " enum E { e1, e2, e3 };\n"
+ " @\n"
+ " // padding so we get the scope right\n"
+ "}\n"
+ ;
+ CompletionTestCase test(source, "E::");
+
+ const QStringList completions = test.getCompletions();
+
+ QCOMPARE(completions.size(), 4);
+ QVERIFY(completions.contains(QLatin1String("E")));
+ QVERIFY(completions.contains(QLatin1String("e1")));
+ QVERIFY(completions.contains(QLatin1String("e2")));
+ QVERIFY(completions.contains(QLatin1String("e3")));
+}
+
+void CppToolsPlugin::test_completion_lambdaCalls_1()
+{
+ const QByteArray source =
+ "struct S { int bar; };\n"
+ "void foo()\n"
+ "{\n"
+ " @\n"
+ " // padding so we get the scope right\n"
+ "}\n"
+ ;
+ CompletionTestCase test(source, "[](){ return new S; } ()->");
+
+ const QStringList completions = test.getCompletions();
+
+ QCOMPARE(completions.size(), 2);
+ QVERIFY(completions.contains(QLatin1String("S")));
+ QVERIFY(completions.contains(QLatin1String("bar")));
+}
+
+void CppToolsPlugin::test_completion_lambdaCalls_2()
+{
+ const QByteArray source =
+ "struct S { int bar; };\n"
+ "void foo()\n"
+ "{\n"
+ " @\n"
+ " // padding so we get the scope right\n"
+ "}\n"
+ ;
+ CompletionTestCase test(source, "[] { return new S; } ()->");
+
+ const QStringList completions = test.getCompletions();
+
+ QCOMPARE(completions.size(), 2);
+ QVERIFY(completions.contains(QLatin1String("S")));
+ QVERIFY(completions.contains(QLatin1String("bar")));
+}
+
+void CppToolsPlugin::test_completion_lambdaCalls_3()
+{
+ const QByteArray source =
+ "struct S { int bar; };\n"
+ "void foo()\n"
+ "{\n"
+ " @\n"
+ " // padding so we get the scope right\n"
+ "}\n"
+ ;
+ CompletionTestCase test(source, "[]() ->S* { return new S; } ()->");
+
+ const QStringList completions = test.getCompletions();
+
+ QCOMPARE(completions.size(), 2);
+ QVERIFY(completions.contains(QLatin1String("S")));
+ QVERIFY(completions.contains(QLatin1String("bar")));
+}
+
+void CppToolsPlugin::test_completion_lambdaCalls_4()
+{
+ const QByteArray source =
+ "struct S { int bar; };\n"
+ "void foo()\n"
+ "{\n"
+ " @\n"
+ " // padding so we get the scope right\n"
+ "}\n"
+ ;
+ CompletionTestCase test(source, "[]() throw() { return new S; } ()->");
+
+ const QStringList completions = test.getCompletions();
+
+ QCOMPARE(completions.size(), 2);
+ QVERIFY(completions.contains(QLatin1String("S")));
+ QVERIFY(completions.contains(QLatin1String("bar")));
+}
+
+void CppToolsPlugin::test_completion_lambdaCalls_5()
+{
+ const QByteArray source =
+ "struct S { int bar; };\n"
+ "void foo()\n"
+ "{\n"
+ " @\n"
+ " // padding so we get the scope right\n"
+ "}\n"
+ ;
+ CompletionTestCase test(source, "[]() throw()->S* { return new S; } ()->");
+
+ const QStringList completions = test.getCompletions();
+
+ QCOMPARE(completions.size(), 2);
+ QVERIFY(completions.contains(QLatin1String("S")));
+ QVERIFY(completions.contains(QLatin1String("bar")));
+}
+
+void CppToolsPlugin::test_completion_local_type_and_member_1()
+{
+ const QByteArray source =
+ "struct OtherType { int otherTypeMember; };\n"
+ "void foo()\n"
+ "{\n"
+ " struct LocalType\n"
+ " {\n"
+ " int localTypeMember;\n"
+ " OtherType ot;\n"
+ " };\n"
+ " LocalType lt;\n"
+ " @\n"
+ " // padding so we get the scope right\n"
+ "}\n"
+ ;
+ CompletionTestCase test(source, "lt.ot.");
+
+ const QStringList completions = test.getCompletions();
+
+ QCOMPARE(completions.size(), 2);
+ QVERIFY(completions.contains(QLatin1String("OtherType")));
+ QVERIFY(completions.contains(QLatin1String("otherTypeMember")));
+}
+
+void CppToolsPlugin::test_completion_local_type_and_member_2()
+{
+ const QByteArray source =
+ "void foo()\n"
+ "{\n"
+ " struct OtherType { int otherTypeMember; };\n"
+ " struct LocalType\n"
+ " {\n"
+ " int localTypeMember;\n"
+ " OtherType ot;\n"
+ " };\n"
+ " LocalType lt;\n"
+ " @\n"
+ " // padding so we get the scope right\n"
+ "}\n"
+ ;
+ CompletionTestCase test(source, "lt.ot.");
+
+ const QStringList completions = test.getCompletions();
+
+ QCOMPARE(completions.size(), 2);
+ QVERIFY(completions.contains(QLatin1String("OtherType")));
+ QVERIFY(completions.contains(QLatin1String("otherTypeMember")));
+}
+
+void CppToolsPlugin::test_completion_local_type_and_member_3()
+{
+ const QByteArray source =
+ "void foo()\n"
+ "{\n"
+ " struct OtherType { int otherTypeMember; };\n"
+ " {\n"
+ " struct LocalType\n"
+ " {\n"
+ " int localTypeMember;\n"
+ " OtherType ot;\n"
+ " };\n"
+ " LocalType lt;\n"
+ " @\n"
+ " // padding so we get the scope right\n"
+ " }\n"
+ "}\n"
+ ;
+ CompletionTestCase test(source, "lt.ot.");
+
+ const QStringList completions = test.getCompletions();
+
+ QCOMPARE(completions.size(), 2);
+ QVERIFY(completions.contains(QLatin1String("OtherType")));
+ QVERIFY(completions.contains(QLatin1String("otherTypeMember")));
+}
+
+void CppToolsPlugin::test_completion_local_type_and_member_4()
+{
+ const QByteArray source =
+ "namespace NS {struct OtherType { int otherTypeMember; };}\n"
+ "void foo()\n"
+ "{\n"
+ " struct LocalType\n"
+ " {\n"
+ " int localTypeMember;\n"
+ " NS::OtherType ot;\n"
+ " };\n"
+ " LocalType lt;\n"
+ " @\n"
+ " // padding so we get the scope right\n"
+ "}\n"
+ ;
+ CompletionTestCase test(source, "lt.ot.");
+
+ const QStringList completions = test.getCompletions();
+
+ QCOMPARE(completions.size(), 2);
+ QVERIFY(completions.contains(QLatin1String("OtherType")));
+ QVERIFY(completions.contains(QLatin1String("otherTypeMember")));
+}
+
+void CppToolsPlugin::test_completion_local_type_and_member_5()
+{
+ const QByteArray source =
+ "namespace NS {struct OtherType { int otherTypeMember; };}\n"
+ "void foo()\n"
+ "{\n"
+ " using namespace NS;\n"
+ " struct LocalType\n"
+ " {\n"
+ " int localTypeMember;\n"
+ " OtherType ot;\n"
+ " };\n"
+ " LocalType lt;\n"
+ " @\n"
+ " // padding so we get the scope right\n"
+ "}\n"
+ ;
+ CompletionTestCase test(source, "lt.ot.");
+
+ const QStringList completions = test.getCompletions();
+
+ QCOMPARE(completions.size(), 2);
+ QVERIFY(completions.contains(QLatin1String("OtherType")));
+ QVERIFY(completions.contains(QLatin1String("otherTypeMember")));
+}
+
+void CppToolsPlugin::test_completion_local_type_and_member_6()
+{
+ const QByteArray source =
+ "namespace NS {struct OtherType { int otherTypeMember; };}\n"
+ "void foo()\n"
+ "{\n"
+ " using NS::OtherType;\n"
+ " struct LocalType\n"
+ " {\n"
+ " int localTypeMember;\n"
+ " OtherType ot;\n"
+ " };\n"
+ " LocalType lt;\n"
+ " @\n"
+ " // padding so we get the scope right\n"
+ "}\n"
+ ;
+ CompletionTestCase test(source, "lt.ot.");
+
+ const QStringList completions = test.getCompletions();
+
+ QCOMPARE(completions.size(), 2);
+ QVERIFY(completions.contains(QLatin1String("OtherType")));
+ QVERIFY(completions.contains(QLatin1String("otherTypeMember")));
+}
+
+void CppToolsPlugin::test_completion_template_parameter_defined_inside_scope_of_declaration_QTCREATORBUG9169_1()
+{
+ const QByteArray source =
+ "struct A\n"
+ "{\n"
+ " void foo();\n"
+ " struct B\n"
+ " {\n"
+ " int b;\n"
+ " };\n"
+ "};\n"
+ "template<typename T>\n"
+ "struct Template\n"
+ "{\n"
+ " T* get();\n"
+ "};\n"
+ "namespace foo\n"
+ "{\n"
+ " struct B\n"
+ " {\n"
+ " int foo_b;\n"
+ " };\n"
+ "}\n"
+ "using namespace foo;\n"
+ "void A::foo()\n"
+ "{\n"
+ " Template<B> templ;\n"
+ " @\n"
+ " // padding so we get the scope right\n"
+ "}\n"
+ ;
+ CompletionTestCase test(source, "templ.get()->");
+
+ const QStringList completions = test.getCompletions();
+
+ QCOMPARE(completions.size(), 2);
+ QVERIFY(completions.contains(QLatin1String("B")));
+ QVERIFY(completions.contains(QLatin1String("b")));
+}
+
+void CppToolsPlugin::test_completion_template_parameter_defined_inside_scope_of_declaration_QTCREATORBUG9169_2()
+{
+ const QByteArray source =
+ "struct A\n"
+ "{\n"
+ " void foo();\n"
+ " struct B\n"
+ " {\n"
+ " int b;\n"
+ " };\n"
+ "};\n"
+ "template<typename T>\n"
+ "struct Template\n"
+ "{\n"
+ " T t;\n"
+ "};\n"
+ "namespace foo\n"
+ "{\n"
+ " struct B\n"
+ " {\n"
+ " int foo_b;\n"
+ " };\n"
+ "}\n"
+ "using namespace foo;\n"
+ "void A::foo()\n"
+ "{\n"
+ " Template<B> templ;\n"
+ " @\n"
+ " // padding so we get the scope right\n"
+ "}\n"
+ ;
+ CompletionTestCase test(source, "templ.t.");
+
+ const QStringList completions = test.getCompletions();
+
+ QCOMPARE(completions.size(), 2);
+ QVERIFY(completions.contains(QLatin1String("B")));
+ QVERIFY(completions.contains(QLatin1String("b")));
+}
+
+void CppToolsPlugin::test_completion_template_parameter_defined_inside_scope_of_declaration_QTCREATORBUG8852_1()
+{
+ const QByteArray source =
+ "template <typename T>\n"
+ "struct QList\n"
+ "{\n"
+ " T at(int i) const;\n"
+ "};\n"
+ "namespace ns\n"
+ "{\n"
+ " struct Foo { int bar; };\n"
+ " void foo()\n"
+ " {\n"
+ " QList<Foo> list;\n"
+ " @\n"
+ " // padding so we get the scope right\n"
+ " }\n"
+ "}\n"
+ ;
+ CompletionTestCase test(source, "list.at(0).");
+
+ const QStringList completions = test.getCompletions();
+
+ QCOMPARE(completions.size(), 2);
+ QVERIFY(completions.contains(QLatin1String("Foo")));
+ QVERIFY(completions.contains(QLatin1String("bar")));
+}
+
+void CppToolsPlugin::test_completion_template_parameter_defined_inside_scope_of_declaration_QTCREATORBUG8852_2()
+{
+ const QByteArray source =
+ "template <typename T>\n"
+ "struct QList\n"
+ "{\n"
+ " T at(int i) const;\n"
+ "};\n"
+ "namespace ns\n"
+ "{\n"
+ " struct Foo { int bar; };\n"
+ " namespace nested\n"
+ " {\n"
+ " void foo()\n"
+ " {\n"
+ " QList<Foo> list;\n"
+ " @\n"
+ " // padding so we get the scope right\n"
+ " }\n"
+ " }\n"
+ "}\n"
+ ;
+ CompletionTestCase test(source, "list.at(0).");
+
+ const QStringList completions = test.getCompletions();
+
+ QCOMPARE(completions.size(), 2);
+ QVERIFY(completions.contains(QLatin1String("Foo")));
+ QVERIFY(completions.contains(QLatin1String("bar")));
+}
+
+void CppToolsPlugin::test_completion_template_parameter_defined_inside_scope_of_declaration_QTCREATORBUG8852_3()
+{
+ const QByteArray source =
+ "template <typename T>\n"
+ "struct QList\n"
+ "{\n"
+ " T at(int i) const;\n"
+ "};\n"
+ "namespace ns\n"
+ "{\n"
+ " struct Foo { int bar; };\n"
+ "}\n"
+ "void foo()\n"
+ "{\n"
+ " using namespace ns;\n"
+ " QList<Foo> list;\n"
+ " @\n"
+ " // padding so we get the scope right\n"
+ "}\n"
+ ;
+ CompletionTestCase test(source, "list.at(0).");
+
+ const QStringList completions = test.getCompletions();
+
+ QCOMPARE(completions.size(), 2);
+ QVERIFY(completions.contains(QLatin1String("Foo")));
+ QVERIFY(completions.contains(QLatin1String("bar")));
+}
+
void CppToolsPlugin::test_completion_signals_hide_QPrivateSignal()
{
const QByteArray source =
diff --git a/src/plugins/cpptools/cppcompletionassist.cpp b/src/plugins/cpptools/cppcompletionassist.cpp
index d782c0fdc4..4a9ea06122 100644
--- a/src/plugins/cpptools/cppcompletionassist.cpp
+++ b/src/plugins/cpptools/cppcompletionassist.cpp
@@ -210,15 +210,16 @@ void CppAssistProposalItem::applyContextualContent(TextEditor::BaseTextEditor *e
} else {
toInsert = text();
- const CompletionSettings &completionSettings =
- TextEditorSettings::instance()->completionSettings();
+ const CompletionSettings &completionSettings = TextEditorSettings::completionSettings();
const bool autoInsertBrackets = completionSettings.m_autoInsertBrackets;
if (autoInsertBrackets && symbol && symbol->type()) {
if (Function *function = symbol->type()->asFunctionType()) {
// If the member is a function, automatically place the opening parenthesis,
// except when it might take template parameters.
- if (! function->hasReturnType() && (function->unqualifiedName() && !function->unqualifiedName()->isDestructorNameId())) {
+ if (!function->hasReturnType()
+ && (function->unqualifiedName()
+ && !function->unqualifiedName()->isDestructorNameId())) {
// Don't insert any magic, since the user might have just wanted to select the class
/// ### port me
@@ -228,7 +229,7 @@ void CppAssistProposalItem::applyContextualContent(TextEditor::BaseTextEditor *e
if (function->argumentCount() == 0)
extraChars += QLatin1Char('<');
#endif
- } else if (!isDereferenced(editor, basePosition) && ! function->isAmbiguous()) {
+ } else if (!isDereferenced(editor, basePosition) && !function->isAmbiguous()) {
// When the user typed the opening parenthesis, he'll likely also type the closing one,
// in which case it would be annoying if we put the cursor after the already automatically
// inserted closing parenthesis.
@@ -253,7 +254,7 @@ void CppAssistProposalItem::applyContextualContent(TextEditor::BaseTextEditor *e
}
// If the function takes no arguments, automatically place the closing parenthesis
- if (!isOverloaded() && ! function->hasArguments() && skipClosingParenthesis) {
+ if (!isOverloaded() && !function->hasArguments() && skipClosingParenthesis) {
extraChars += QLatin1Char(')');
if (endWithSemicolon) {
extraChars += semicolon;
@@ -392,7 +393,7 @@ int CppFunctionHintModel::activeArgument(const QString &prefix) const
++parcount;
else if (tk.is(T_RPAREN))
--parcount;
- else if (! parcount && tk.is(T_COMMA))
+ else if (!parcount && tk.is(T_COMMA))
++argnr;
}
@@ -414,44 +415,25 @@ IAssistProcessor *InternalCompletionAssistProvider::createProcessor() const
return new CppCompletionAssistProcessor;
}
-namespace {
-class CppCompletionSupportInternal: public CppCompletionSupport
+TextEditor::IAssistInterface *InternalCompletionAssistProvider::createAssistInterface(
+ ProjectExplorer::Project *project, const QString &filePath, QTextDocument *document,
+ int position, TextEditor::AssistReason reason) const
{
-public:
- CppCompletionSupportInternal(TextEditor::ITextEditor *editor)
- : CppCompletionSupport(editor)
- {}
-
- virtual ~CppCompletionSupportInternal()
- {}
-
- virtual TextEditor::IAssistInterface *createAssistInterface(ProjectExplorer::Project *project,
- QTextDocument *document,
- int position,
- TextEditor::AssistReason reason) const
- {
- CppModelManagerInterface *modelManager = CppModelManagerInterface::instance();
- QStringList includePaths;
- QStringList frameworkPaths;
- if (project) {
- includePaths = modelManager->projectInfo(project).includePaths();
- frameworkPaths = modelManager->projectInfo(project).frameworkPaths();
- }
- return new CppTools::Internal::CppCompletionAssistInterface(
- document,
- position,
- editor()->document()->fileName(),
- reason,
- modelManager->snapshot(),
- includePaths,
- frameworkPaths);
+ CppModelManagerInterface *modelManager = CppModelManagerInterface::instance();
+ QStringList includePaths;
+ QStringList frameworkPaths;
+ if (project) {
+ includePaths = modelManager->projectInfo(project).includePaths();
+ frameworkPaths = modelManager->projectInfo(project).frameworkPaths();
}
-};
-}
-
-CppCompletionSupport *InternalCompletionAssistProvider::completionSupport(ITextEditor *editor)
-{
- return new CppCompletionSupportInternal(editor);
+ return new CppTools::Internal::CppCompletionAssistInterface(
+ document,
+ position,
+ filePath,
+ reason,
+ modelManager->snapshot(),
+ includePaths,
+ frameworkPaths);
}
// -----------------
@@ -506,8 +488,8 @@ public:
BasicProposalItem *operator()(Symbol *symbol)
{
//using declaration can be qualified
- if (! symbol || ! symbol->name() || (symbol->name()->isQualifiedNameId()
- && ! symbol->asUsingDeclaration()))
+ if (!symbol || !symbol->name() || (symbol->name()->isQualifiedNameId()
+ && !symbol->asUsingDeclaration()))
return 0;
BasicProposalItem *previousItem = switchCompletionItem(0);
@@ -574,7 +556,7 @@ Class *asClassOrTemplateClassType(FullySpecifiedType ty)
{
if (Class *classTy = ty->asClassType())
return classTy;
- else if (Template *templ = ty->asTemplateType()) {
+ if (Template *templ = ty->asTemplateType()) {
if (Symbol *decl = templ->declaration())
return decl->asClass();
}
@@ -597,7 +579,7 @@ Function *asFunctionOrTemplateFunctionType(FullySpecifiedType ty)
{
if (Function *funTy = ty->asFunctionType())
return funTy;
- else if (Template *templ = ty->asTemplateType()) {
+ if (Template *templ = ty->asTemplateType()) {
if (Symbol *decl = templ->declaration())
return decl->asFunction();
}
@@ -819,13 +801,11 @@ int CppCompletionAssistProcessor::startOfOperator(int pos,
&& *kind != T_DOT))) {
*kind = T_EOF_SYMBOL;
start = pos;
- }
// Include completion: can be triggered by slash, but only in a string
- else if (*kind == T_SLASH && (tk.isNot(T_STRING_LITERAL) && tk.isNot(T_ANGLE_STRING_LITERAL))) {
+ } else if (*kind == T_SLASH && (tk.isNot(T_STRING_LITERAL) && tk.isNot(T_ANGLE_STRING_LITERAL))) {
*kind = T_EOF_SYMBOL;
start = pos;
- }
- else if (*kind == T_LPAREN) {
+ } else if (*kind == T_LPAREN) {
if (tokenIdx > 0) {
const Token &previousToken = tokens.at(tokenIdx - 1); // look at the token at the left of T_LPAREN
switch (previousToken.kind()) {
@@ -963,13 +943,11 @@ int CppCompletionAssistProcessor::startCompletionHelper()
startOfExpression = endOfExpression - expression.length();
if (m_model->m_completionOperator == T_LPAREN) {
- if (expression.endsWith(QLatin1String("SIGNAL")))
+ if (expression.endsWith(QLatin1String("SIGNAL"))) {
m_model->m_completionOperator = T_SIGNAL;
-
- else if (expression.endsWith(QLatin1String("SLOT")))
+ } else if (expression.endsWith(QLatin1String("SLOT"))) {
m_model->m_completionOperator = T_SLOT;
-
- else if (m_interface->position() != endOfOperator) {
+ } else if (m_interface->position() != endOfOperator) {
// We don't want a function completion when the cursor isn't at the opening brace
expression.clear();
m_model->m_completionOperator = T_EOF_SYMBOL;
@@ -1010,7 +988,7 @@ bool CppCompletionAssistProcessor::tryObjCCompletion()
const QString expr = m_interface->textAt(startPos, m_interface->position() - startPos);
Document::Ptr thisDocument = m_interface->snapshot().document(m_interface->fileName());
- if (! thisDocument)
+ if (!thisDocument)
return false;
m_model->m_typeOfExpression->init(thisDocument, m_interface->snapshot());
@@ -1157,7 +1135,7 @@ bool CppCompletionAssistProcessor::completeInclude(const QTextCursor &cursor)
includePaths.append(currentFilePath);
const Core::MimeType mimeType =
- Core::ICore::mimeDatabase()->findByType(QLatin1String("text/x-c++hdr"));
+ Core::MimeDatabase::findByType(QLatin1String("text/x-c++hdr"));
const QStringList suffixes = mimeType.suffixes();
foreach (const QString &includePath, includePaths) {
@@ -1215,9 +1193,9 @@ bool CppCompletionAssistProcessor::objcKeywordsWanted() const
const QString fileName = m_interface->fileName();
- const Core::MimeDatabase *mdb = Core::ICore::mimeDatabase();
- const QString mt = mdb->findByFile(fileName).type();
- return mt == QLatin1String(CppTools::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE);
+ const QString mt = Core::MimeDatabase::findByFile(fileName).type();
+ return mt == QLatin1String(CppTools::Constants::OBJECTIVE_C_SOURCE_MIMETYPE)
+ || mt == QLatin1String(CppTools::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE);
}
int CppCompletionAssistProcessor::startCompletionInternal(const QString fileName,
@@ -1228,7 +1206,7 @@ int CppCompletionAssistProcessor::startCompletionInternal(const QString fileName
QString expression = expr.trimmed();
Document::Ptr thisDocument = m_interface->snapshot().document(fileName);
- if (! thisDocument)
+ if (!thisDocument)
return -1;
m_model->m_typeOfExpression->init(thisDocument, m_interface->snapshot());
@@ -1245,7 +1223,7 @@ int CppCompletionAssistProcessor::startCompletionInternal(const QString fileName
return m_startPosition;
}
- else if (m_model->m_completionOperator == T_SIGNAL || m_model->m_completionOperator == T_SLOT) {
+ if (m_model->m_completionOperator == T_SIGNAL || m_model->m_completionOperator == T_SLOT) {
// Apply signal/slot completion on 'this'
expression = QLatin1String("this");
}
@@ -1257,7 +1235,7 @@ int CppCompletionAssistProcessor::startCompletionInternal(const QString fileName
if (results.isEmpty()) {
if (m_model->m_completionOperator == T_SIGNAL || m_model->m_completionOperator == T_SLOT) {
- if (! (expression.isEmpty() || expression == QLatin1String("this"))) {
+ if (!(expression.isEmpty() || expression == QLatin1String("this"))) {
expression = QLatin1String("this");
results = (*m_model->m_typeOfExpression)(utf8Exp, scope);
}
@@ -1353,9 +1331,9 @@ void CppCompletionAssistProcessor::globalCompletion(CPlusPlus::Scope *currentSco
if (ClassOrNamespace *binding = context.lookupType(scope)) {
for (unsigned i = 0; i < scope->memberCount(); ++i) {
Symbol *member = scope->memberAt(i);
- if (! member->name())
+ if (!member->name())
continue;
- else if (UsingNamespaceDirective *u = member->asUsingNamespaceDirective()) {
+ if (UsingNamespaceDirective *u = member->asUsingNamespaceDirective()) {
if (ClassOrNamespace *b = binding->lookupType(u->name()))
usingBindings.append(b);
}
@@ -1389,7 +1367,7 @@ void CppCompletionAssistProcessor::globalCompletion(CPlusPlus::Scope *currentSco
for (; currentBinding; currentBinding = currentBinding->parent()) {
const QList<Symbol *> symbols = currentBinding->symbols();
- if (! symbols.isEmpty()) {
+ if (!symbols.isEmpty()) {
if (symbols.first()->isClass())
completeClass(currentBinding);
else
@@ -1422,7 +1400,7 @@ bool CppCompletionAssistProcessor::completeMember(const QList<CPlusPlus::LookupI
if (binding)
completeClass(binding, /*static lookup = */ true);
- return ! m_completions.isEmpty();
+ return !m_completions.isEmpty();
}
return false;
@@ -1450,6 +1428,14 @@ bool CppCompletionAssistProcessor::completeScope(const QList<CPlusPlus::LookupIt
break;
}
+ // it can be class defined inside a block
+ if (classTy->enclosingScope()->isBlock()) {
+ if (ClassOrNamespace *b = context.lookupType(classTy->name(), classTy->enclosingScope())) {
+ completeClass(b);
+ break;
+ }
+ }
+
} else if (Namespace *nsTy = ty->asNamespaceType()) {
if (ClassOrNamespace *b = context.lookupType(nsTy)) {
completeNamespace(b);
@@ -1465,14 +1451,26 @@ bool CppCompletionAssistProcessor::completeScope(const QList<CPlusPlus::LookupIt
}
} else if (Enum *e = ty->asEnumType()) {
+ // it can be class defined inside a block
+ if (e->enclosingScope()->isBlock()) {
+ if (ClassOrNamespace *b = context.lookupType(e)) {
+ Block *block = e->enclosingScope()->asBlock();
+ if (ClassOrNamespace *bb = b->findBlock(block)) {
+ completeNamespace(bb);
+ break;
+ }
+ }
+ }
+
if (ClassOrNamespace *b = context.lookupType(e)) {
completeNamespace(b);
break;
}
+
}
}
- return ! m_completions.isEmpty();
+ return !m_completions.isEmpty();
}
void CppCompletionAssistProcessor::completeNamespace(CPlusPlus::ClassOrNamespace *b)
@@ -1481,9 +1479,9 @@ void CppCompletionAssistProcessor::completeNamespace(CPlusPlus::ClassOrNamespace
QList<ClassOrNamespace *> bindingsToVisit;
bindingsToVisit.append(b);
- while (! bindingsToVisit.isEmpty()) {
+ while (!bindingsToVisit.isEmpty()) {
ClassOrNamespace *binding = bindingsToVisit.takeFirst();
- if (! binding || bindingsVisited.contains(binding))
+ if (!binding || bindingsVisited.contains(binding))
continue;
bindingsVisited.insert(binding);
@@ -1501,9 +1499,9 @@ void CppCompletionAssistProcessor::completeNamespace(CPlusPlus::ClassOrNamespace
scopesToVisit.append(e);
}
- while (! scopesToVisit.isEmpty()) {
+ while (!scopesToVisit.isEmpty()) {
Scope *scope = scopesToVisit.takeFirst();
- if (! scope || scopesVisited.contains(scope))
+ if (!scope || scopesVisited.contains(scope))
continue;
scopesVisited.insert(scope);
@@ -1522,9 +1520,9 @@ void CppCompletionAssistProcessor::completeClass(CPlusPlus::ClassOrNamespace *b,
QList<ClassOrNamespace *> bindingsToVisit;
bindingsToVisit.append(b);
- while (! bindingsToVisit.isEmpty()) {
+ while (!bindingsToVisit.isEmpty()) {
ClassOrNamespace *binding = bindingsToVisit.takeFirst();
- if (! binding || bindingsVisited.contains(binding))
+ if (!binding || bindingsVisited.contains(binding))
continue;
bindingsVisited.insert(binding);
@@ -1541,9 +1539,9 @@ void CppCompletionAssistProcessor::completeClass(CPlusPlus::ClassOrNamespace *b,
foreach (Enum *e, binding->unscopedEnums())
scopesToVisit.append(e);
- while (! scopesToVisit.isEmpty()) {
+ while (!scopesToVisit.isEmpty()) {
Scope *scope = scopesToVisit.takeFirst();
- if (! scope || scopesVisited.contains(scope))
+ if (!scope || scopesVisited.contains(scope))
continue;
scopesVisited.insert(scope);
@@ -1557,7 +1555,7 @@ void CppCompletionAssistProcessor::completeClass(CPlusPlus::ClassOrNamespace *b,
|| member->isQtPropertyDeclaration()
|| member->isQtEnum()) {
continue;
- } else if (! staticLookup && (member->isTypedef() ||
+ } else if (!staticLookup && (member->isTypedef() ||
member->isEnum() ||
member->isClass())) {
continue;
@@ -1595,11 +1593,11 @@ bool CppCompletionAssistProcessor::completeQtMethod(const QList<CPlusPlus::Looku
continue; // not a pointer or a reference to a pointer.
NamedType *namedTy = ty->asNamedType();
- if (! namedTy) // not a class name.
+ if (!namedTy) // not a class name.
continue;
ClassOrNamespace *b = context.lookupType(namedTy->name(), p.scope());
- if (! b)
+ if (!b)
continue;
QList<ClassOrNamespace *>todo;
@@ -1620,17 +1618,17 @@ bool CppCompletionAssistProcessor::completeQtMethod(const QList<CPlusPlus::Looku
}
foreach (Scope *scope, scopes) {
- if (! scope->isClass())
+ if (!scope->isClass())
continue;
for (unsigned i = 0; i < scope->memberCount(); ++i) {
Symbol *member = scope->memberAt(i);
Function *fun = member->type()->asFunctionType();
- if (! fun)
+ if (!fun)
continue;
- if (wantSignals && ! fun->isSignal())
+ if (wantSignals && !fun->isSignal())
continue;
- else if (! wantSignals && ! fun->isSlot())
+ else if (!wantSignals && !fun->isSlot())
continue;
unsigned count = fun->argumentCount();
@@ -1653,7 +1651,7 @@ bool CppCompletionAssistProcessor::completeQtMethod(const QList<CPlusPlus::Looku
signature = QString::fromLatin1(normalized, normalized.size());
- if (! signatures.contains(signature)) {
+ if (!signatures.contains(signature)) {
BasicProposalItem *ci = toCompletionItem(fun);
if (!ci)
break;
@@ -1671,7 +1669,7 @@ bool CppCompletionAssistProcessor::completeQtMethod(const QList<CPlusPlus::Looku
}
}
- return ! m_completions.isEmpty();
+ return !m_completions.isEmpty();
}
void CppCompletionAssistProcessor::addSnippets()
@@ -1708,18 +1706,18 @@ void CppCompletionAssistProcessor::addMacros_helper(const CPlusPlus::Snapshot &s
{
Document::Ptr doc = snapshot.document(fileName);
- if (! doc || processed->contains(doc->fileName()))
+ if (!doc || processed->contains(doc->fileName()))
return;
processed->insert(doc->fileName());
- foreach (const Document::Include &i, doc->includes()) {
+ foreach (const Document::Include &i, doc->resolvedIncludes()) {
addMacros_helper(snapshot, i.resolvedFileName(), processed, definedMacros);
}
foreach (const Macro &macro, doc->definedMacros()) {
const QString macroName = QString::fromUtf8(macro.name().constData(), macro.name().length());
- if (! macro.isHidden())
+ if (!macro.isHidden())
definedMacros->insert(macroName);
else
definedMacros->remove(macroName);
@@ -1738,14 +1736,14 @@ bool CppCompletionAssistProcessor::completeConstructorOrFunction(const QList<CPl
if (Class *klass = asClassOrTemplateClassType(exprTy)) {
const Name *className = klass->name();
- if (! className)
+ if (!className)
continue; // nothing to do for anonymous classes.
for (unsigned i = 0; i < klass->memberCount(); ++i) {
Symbol *member = klass->memberAt(i);
const Name *memberName = member->name();
- if (! memberName)
+ if (!memberName)
continue; // skip anonymous member.
else if (memberName->isQualifiedNameId())
@@ -1769,10 +1767,13 @@ bool CppCompletionAssistProcessor::completeConstructorOrFunction(const QList<CPl
if (Function *fun = asFunctionOrTemplateFunctionType(ty)) {
- if (! fun->name())
+ if (!fun->name()) {
continue;
- else if (! functions.isEmpty() && enclosingNonTemplateScope(functions.first()) != enclosingNonTemplateScope(fun))
+ } else if (!functions.isEmpty()
+ && enclosingNonTemplateScope(functions.first())
+ != enclosingNonTemplateScope(fun)) {
continue; // skip fun, it's an hidden declaration.
+ }
bool newOverload = true;
@@ -1819,7 +1820,7 @@ bool CppCompletionAssistProcessor::completeConstructorOrFunction(const QList<CPl
// check if function signature autocompletion is appropriate
// Also check if the function name is a destructor name.
bool isDestructor = false;
- if (! functions.isEmpty() && ! toolTipOnly) {
+ if (!functions.isEmpty() && !toolTipOnly) {
// function definitions will only happen in class or namespace scope,
// so get the current location's enclosing scope.
@@ -1906,7 +1907,7 @@ bool CppCompletionAssistProcessor::completeConstructorOrFunction(const QList<CPl
}
}
- if (! functions.empty() && !isDestructor) {
+ if (!functions.empty() && !isDestructor) {
m_hintProposal = createHintProposal(functions);
return true;
}
diff --git a/src/plugins/cpptools/cppcompletionassist.h b/src/plugins/cpptools/cppcompletionassist.h
index 0515ce0804..a78777a863 100644
--- a/src/plugins/cpptools/cppcompletionassist.h
+++ b/src/plugins/cpptools/cppcompletionassist.h
@@ -89,7 +89,11 @@ class InternalCompletionAssistProvider : public CppCompletionAssistProvider
public:
virtual TextEditor::IAssistProcessor *createProcessor() const;
- virtual CppCompletionSupport *completionSupport(TextEditor::ITextEditor *editor);
+
+ virtual TextEditor::IAssistInterface *createAssistInterface(
+ ProjectExplorer::Project *project, const QString &filePath, QTextDocument *document,
+ int position, TextEditor::AssistReason reason) const;
+
};
class CppCompletionAssistProcessor : public TextEditor::IAssistProcessor
diff --git a/src/plugins/cpptools/cppcompletionassistprovider.h b/src/plugins/cpptools/cppcompletionassistprovider.h
index b9739e3648..e45b20946f 100644
--- a/src/plugins/cpptools/cppcompletionassistprovider.h
+++ b/src/plugins/cpptools/cppcompletionassistprovider.h
@@ -30,11 +30,23 @@
#ifndef CPPTOOLS_CPPCOMPLETIONASSISTPROVIDER_H
#define CPPTOOLS_CPPCOMPLETIONASSISTPROVIDER_H
-#include "cppcompletionsupport.h"
#include "cpptools_global.h"
+#include <texteditor/codeassist/assistenums.h>
#include <texteditor/codeassist/completionassistprovider.h>
+QT_BEGIN_NAMESPACE
+class QTextDocument;
+QT_END_NAMESPACE
+
+namespace ProjectExplorer {
+class Project;
+}
+
+namespace TextEditor {
+class IAssistInterface;
+}
+
namespace CppTools {
class CPPTOOLS_EXPORT CppCompletionAssistProvider : public TextEditor::CompletionAssistProvider
@@ -46,7 +58,9 @@ public:
virtual int activationCharSequenceLength() const;
virtual bool isActivationCharSequence(const QString &sequence) const;
- virtual CppCompletionSupport *completionSupport(TextEditor::ITextEditor *editor) = 0;
+ virtual TextEditor::IAssistInterface *createAssistInterface(
+ ProjectExplorer::Project *project, const QString &filePath, QTextDocument *document,
+ int position, TextEditor::AssistReason reason) const = 0;
static int activationSequenceChar(const QChar &ch, const QChar &ch2,
const QChar &ch3, unsigned *kind,
diff --git a/src/plugins/cpptools/cppcurrentdocumentfilter.cpp b/src/plugins/cpptools/cppcurrentdocumentfilter.cpp
index e7aa07ac90..93b7e5907a 100644
--- a/src/plugins/cpptools/cppcurrentdocumentfilter.cpp
+++ b/src/plugins/cpptools/cppcurrentdocumentfilter.cpp
@@ -36,7 +36,7 @@
using namespace CppTools::Internal;
using namespace CPlusPlus;
-CppCurrentDocumentFilter::CppCurrentDocumentFilter(CppModelManager *manager, Core::EditorManager *editorManager)
+CppCurrentDocumentFilter::CppCurrentDocumentFilter(CppModelManager *manager)
: m_modelManager(manager)
{
setId("Methods in current Document");
@@ -49,13 +49,11 @@ CppCurrentDocumentFilter::CppCurrentDocumentFilter(CppModelManager *manager, Cor
SymbolSearcher::Functions |
SymbolSearcher::Classes);
- search.setSeparateScope(true);
-
connect(manager, SIGNAL(documentUpdated(CPlusPlus::Document::Ptr)),
this, SLOT(onDocumentUpdated(CPlusPlus::Document::Ptr)));
- connect(editorManager, SIGNAL(currentEditorChanged(Core::IEditor*)),
+ connect(Core::EditorManager::instance(), SIGNAL(currentEditorChanged(Core::IEditor*)),
this, SLOT(onCurrentEditorChanged(Core::IEditor*)));
- connect(editorManager, SIGNAL(editorAboutToClose(Core::IEditor*)),
+ connect(Core::EditorManager::instance(), SIGNAL(editorAboutToClose(Core::IEditor*)),
this, SLOT(onEditorAboutToClose(Core::IEditor*)));
}
@@ -81,20 +79,31 @@ QList<Locator::FilterEntry> CppCurrentDocumentFilter::matchesFor(QFutureInterfac
m_itemsOfCurrentDoc = search(thisDocument);
}
+ const Qt::CaseSensitivity caseSensitivityForPrefix = caseSensitivity(entry);
+
foreach (const ModelItemInfo & info, m_itemsOfCurrentDoc)
{
if (future.isCanceled())
break;
- if ((hasWildcard && regexp.exactMatch(info.symbolName))
- || (!hasWildcard && matcher.indexIn(info.symbolName) != -1))
+ QString matchString = info.symbolName;
+ if (info.type == ModelItemInfo::Declaration)
+ matchString = ModelItemInfo::representDeclaration(info.symbolName, info.symbolType);
+ else if (info.type == ModelItemInfo::Method)
+ matchString += info.symbolType;
+
+ if ((hasWildcard && regexp.exactMatch(matchString))
+ || (!hasWildcard && matcher.indexIn(matchString) != -1))
{
- QString symbolName = info.symbolName;// + (info.type == ModelItemInfo::Declaration ? ";" : " {...}");
QVariant id = qVariantFromValue(info);
- Locator::FilterEntry filterEntry(this, symbolName, id, info.icon);
- filterEntry.extraInfo = info.symbolType;
-
- if (info.symbolName.startsWith(entry))
+ QString name = matchString;
+ QString extraInfo = info.symbolScope;
+ if (info.type == ModelItemInfo::Method)
+ info.unqualifiedNameAndScope(matchString, &name, &extraInfo);
+ Locator::FilterEntry filterEntry(this, name, id, info.icon);
+ filterEntry.extraInfo = extraInfo;
+
+ if (matchString.startsWith(entry, caseSensitivityForPrefix))
betterEntries.append(filterEntry);
else
goodEntries.append(filterEntry);
@@ -127,7 +136,7 @@ void CppCurrentDocumentFilter::onDocumentUpdated(Document::Ptr doc)
void CppCurrentDocumentFilter::onCurrentEditorChanged(Core::IEditor * currentEditor)
{
if (currentEditor)
- m_currentFileName = currentEditor->document()->fileName();
+ m_currentFileName = currentEditor->document()->filePath();
else
m_currentFileName.clear();
m_itemsOfCurrentDoc.clear();
@@ -136,7 +145,7 @@ void CppCurrentDocumentFilter::onCurrentEditorChanged(Core::IEditor * currentEdi
void CppCurrentDocumentFilter::onEditorAboutToClose(Core::IEditor * editorAboutToClose)
{
if (!editorAboutToClose) return;
- if (m_currentFileName == editorAboutToClose->document()->fileName()) {
+ if (m_currentFileName == editorAboutToClose->document()->filePath()) {
m_currentFileName.clear();
m_itemsOfCurrentDoc.clear();
}
diff --git a/src/plugins/cpptools/cppcurrentdocumentfilter.h b/src/plugins/cpptools/cppcurrentdocumentfilter.h
index 3466f0e0c1..d23c8e9c7d 100644
--- a/src/plugins/cpptools/cppcurrentdocumentfilter.h
+++ b/src/plugins/cpptools/cppcurrentdocumentfilter.h
@@ -33,10 +33,7 @@
#include <locator/ilocatorfilter.h>
-namespace Core {
-class EditorManager;
-class IEditor;
-}
+namespace Core { class IEditor; }
namespace CppTools {
namespace Internal {
@@ -48,7 +45,7 @@ class CppCurrentDocumentFilter : public Locator::ILocatorFilter
Q_OBJECT
public:
- CppCurrentDocumentFilter(CppModelManager *manager, Core::EditorManager *editorManager);
+ explicit CppCurrentDocumentFilter(CppModelManager *manager);
~CppCurrentDocumentFilter() {}
QList<Locator::FilterEntry> matchesFor(QFutureInterface<Locator::FilterEntry> &future, const QString &entry);
diff --git a/src/plugins/cpptools/cppfilesettingspage.cpp b/src/plugins/cpptools/cppfilesettingspage.cpp
index 1c0c49904d..9de31210d8 100644
--- a/src/plugins/cpptools/cppfilesettingspage.cpp
+++ b/src/plugins/cpptools/cppfilesettingspage.cpp
@@ -30,6 +30,7 @@
#include "cppfilesettingspage.h"
#include "cpptoolsconstants.h"
+#include "cpptoolsplugin.h"
#include <ui_cppfilesettingspage.h>
#include <coreplugin/icore.h>
@@ -52,6 +53,8 @@
static const char headerSuffixKeyC[] = "HeaderSuffix";
static const char sourceSuffixKeyC[] = "SourceSuffix";
+static const char headerSearchPathsKeyC[] = "HeaderSearchPaths";
+static const char sourceSearchPathsKeyC[] = "SourceSearchPaths";
static const char licenseTemplatePathKeyC[] = "LicenseTemplate";
const char *licenseTemplateTemplate = QT_TRANSLATE_NOOP("CppTools::Internal::CppFileSettingsWidget",
@@ -75,6 +78,8 @@ void CppFileSettings::toSettings(QSettings *s) const
s->beginGroup(QLatin1String(Constants::CPPTOOLS_SETTINGSGROUP));
s->setValue(QLatin1String(headerSuffixKeyC), headerSuffix);
s->setValue(QLatin1String(sourceSuffixKeyC), sourceSuffix);
+ s->setValue(QLatin1String(headerSearchPathsKeyC), headerSearchPaths);
+ s->setValue(QLatin1String(sourceSearchPathsKeyC), sourceSearchPaths);
s->setValue(QLatin1String(Constants::LOWERCASE_CPPFILES_KEY), lowerCaseFiles);
s->setValue(QLatin1String(licenseTemplatePathKeyC), licenseTemplatePath);
s->endGroup();
@@ -82,9 +87,22 @@ void CppFileSettings::toSettings(QSettings *s) const
void CppFileSettings::fromSettings(QSettings *s)
{
+ const QStringList defaultHeaderSearchPaths = QStringList()
+ << QLatin1String("include")
+ << QLatin1String("Include")
+ << QDir::toNativeSeparators(QLatin1String("../include"))
+ << QDir::toNativeSeparators(QLatin1String("../Include"));
+ const QStringList defaultSourceSearchPaths = QStringList()
+ << QDir::toNativeSeparators(QLatin1String("../src"))
+ << QDir::toNativeSeparators(QLatin1String("../Src"))
+ << QLatin1String("..");
s->beginGroup(QLatin1String(Constants::CPPTOOLS_SETTINGSGROUP));
headerSuffix= s->value(QLatin1String(headerSuffixKeyC), QLatin1String("h")).toString();
sourceSuffix = s->value(QLatin1String(sourceSuffixKeyC), QLatin1String("cpp")).toString();
+ headerSearchPaths = s->value(QLatin1String(headerSearchPathsKeyC), defaultHeaderSearchPaths)
+ .toStringList();
+ sourceSearchPaths = s->value(QLatin1String(sourceSearchPathsKeyC), defaultSourceSearchPaths)
+ .toStringList();
const bool lowerCaseDefault = Constants::lowerCaseFilesDefault;
lowerCaseFiles = s->value(QLatin1String(Constants::LOWERCASE_CPPFILES_KEY), QVariant(lowerCaseDefault)).toBool();
licenseTemplatePath = s->value(QLatin1String(licenseTemplatePathKeyC), QString()).toString();
@@ -93,9 +111,8 @@ void CppFileSettings::fromSettings(QSettings *s)
bool CppFileSettings::applySuffixesToMimeDB()
{
- Core::MimeDatabase *mdb = Core::ICore::mimeDatabase();
- return mdb->setPreferredSuffix(QLatin1String(CppTools::Constants::CPP_SOURCE_MIMETYPE), sourceSuffix)
- && mdb->setPreferredSuffix(QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE), headerSuffix);
+ return Core::MimeDatabase::setPreferredSuffix(QLatin1String(CppTools::Constants::CPP_SOURCE_MIMETYPE), sourceSuffix)
+ && Core::MimeDatabase::setPreferredSuffix(QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE), headerSuffix);
}
bool CppFileSettings::equals(const CppFileSettings &rhs) const
@@ -103,6 +120,8 @@ bool CppFileSettings::equals(const CppFileSettings &rhs) const
return lowerCaseFiles == rhs.lowerCaseFiles
&& headerSuffix == rhs.headerSuffix
&& sourceSuffix == rhs.sourceSuffix
+ && headerSearchPaths == rhs.headerSearchPaths
+ && sourceSearchPaths == rhs.sourceSearchPaths
&& licenseTemplatePath == rhs.licenseTemplatePath;
}
@@ -205,9 +224,8 @@ QString CppFileSettings::licenseTemplate(const QString &fileName, const QString
return QString();
}
- QTextCodec *codec = Core::EditorManager::instance()->defaultTextCodec();
QTextStream licenseStream(&file);
- licenseStream.setCodec(codec);
+ licenseStream.setCodec(Core::EditorManager::defaultTextCodec());
licenseStream.setAutoDetectUnicode(true);
QString license = licenseStream.readAll();
@@ -227,13 +245,12 @@ CppFileSettingsWidget::CppFileSettingsWidget(QWidget *parent) :
m_ui(new Internal::Ui::CppFileSettingsPage)
{
m_ui->setupUi(this);
- const Core::MimeDatabase *mdb = Core::ICore::mimeDatabase();
// populate suffix combos
- if (const Core::MimeType sourceMt = mdb->findByType(QLatin1String(CppTools::Constants::CPP_SOURCE_MIMETYPE)))
+ if (const Core::MimeType sourceMt = Core::MimeDatabase::findByType(QLatin1String(CppTools::Constants::CPP_SOURCE_MIMETYPE)))
foreach (const QString &suffix, sourceMt.suffixes())
m_ui->sourceSuffixComboBox->addItem(suffix);
- if (const Core::MimeType headerMt = mdb->findByType(QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE)))
+ if (const Core::MimeType headerMt = Core::MimeDatabase::findByType(QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE)))
foreach (const QString &suffix, headerMt.suffixes())
m_ui->headerSuffixComboBox->addItem(suffix);
m_ui->licenseTemplatePathChooser->setExpectedKind(Utils::PathChooser::File);
@@ -255,12 +272,22 @@ void CppFileSettingsWidget::setLicenseTemplatePath(const QString &lp)
m_ui->licenseTemplatePathChooser->setPath(lp);
}
+static QStringList trimmedPaths(const QString &paths)
+{
+ QStringList res;
+ foreach (const QString &path, paths.split(QLatin1Char(','), QString::SkipEmptyParts))
+ res << path.trimmed();
+ return res;
+}
+
CppFileSettings CppFileSettingsWidget::settings() const
{
CppFileSettings rc;
rc.lowerCaseFiles = m_ui->lowerCaseFileNamesCheckBox->isChecked();
rc.headerSuffix = m_ui->headerSuffixComboBox->currentText();
rc.sourceSuffix = m_ui->sourceSuffixComboBox->currentText();
+ rc.headerSearchPaths = trimmedPaths(m_ui->headerSearchPathsEdit->text());
+ rc.sourceSearchPaths = trimmedPaths(m_ui->sourceSearchPathsEdit->text());
rc.licenseTemplatePath = licenseTemplatePath();
return rc;
}
@@ -268,8 +295,12 @@ CppFileSettings CppFileSettingsWidget::settings() const
QString CppFileSettingsWidget::searchKeywords() const
{
QString rc;
- QTextStream(&rc) << m_ui->headerSuffixLabel->text()
+ QTextStream(&rc) << m_ui->headersGroupBox->title()
+ << ' ' << m_ui->headerSuffixLabel->text()
+ << ' ' << m_ui->headerSearchPathsLabel->text()
+ << ' ' << m_ui->sourcesGroupBox->title()
<< ' ' << m_ui->sourceSuffixLabel->text()
+ << ' ' << m_ui->sourceSearchPathsLabel->text()
<< ' ' << m_ui->lowerCaseFileNamesCheckBox->text()
<< ' ' << m_ui->licenseTemplateLabel->text();
rc.remove(QLatin1Char('&'));
@@ -287,6 +318,8 @@ void CppFileSettingsWidget::setSettings(const CppFileSettings &s)
m_ui->lowerCaseFileNamesCheckBox->setChecked(s.lowerCaseFiles);
setComboText(m_ui->headerSuffixComboBox, s.headerSuffix);
setComboText(m_ui->sourceSuffixComboBox, s.sourceSuffix);
+ m_ui->headerSearchPathsEdit->setText(s.headerSearchPaths.join(QLatin1String(",")));
+ m_ui->sourceSearchPathsEdit->setText(s.sourceSearchPaths.join(QLatin1String(",")));
setLicenseTemplatePath(s.licenseTemplatePath);
}
@@ -339,6 +372,7 @@ void CppFileSettingsPage::apply()
*m_settings = newSettings;
m_settings->toSettings(Core::ICore::settings());
m_settings->applySuffixesToMimeDB();
+ CppToolsPlugin::clearHeaderSourceCache();
}
}
}
diff --git a/src/plugins/cpptools/cppfilesettingspage.h b/src/plugins/cpptools/cppfilesettingspage.h
index 06db6d63b3..6fcf0dbc17 100644
--- a/src/plugins/cpptools/cppfilesettingspage.h
+++ b/src/plugins/cpptools/cppfilesettingspage.h
@@ -50,7 +50,9 @@ struct CppFileSettings
CppFileSettings();
QString headerSuffix;
+ QStringList headerSearchPaths;
QString sourceSuffix;
+ QStringList sourceSearchPaths;
bool lowerCaseFiles;
QString licenseTemplatePath;
diff --git a/src/plugins/cpptools/cppfilesettingspage.ui b/src/plugins/cpptools/cppfilesettingspage.ui
index 2b8626f05e..5ac5606319 100644
--- a/src/plugins/cpptools/cppfilesettingspage.ui
+++ b/src/plugins/cpptools/cppfilesettingspage.ui
@@ -6,52 +6,148 @@
<rect>
<x>0</x>
<y>0</y>
- <width>291</width>
- <height>142</height>
+ <width>547</width>
+ <height>305</height>
</rect>
</property>
- <layout class="QFormLayout" name="formLayout">
- <property name="fieldGrowthPolicy">
- <enum>QFormLayout::ExpandingFieldsGrow</enum>
- </property>
- <item row="0" column="0">
- <widget class="QLabel" name="headerSuffixLabel">
- <property name="text">
- <string>Header suffix:</string>
+ <layout class="QVBoxLayout" name="verticalLayout">
+ <item>
+ <widget class="QGroupBox" name="headersGroupBox">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Preferred" vsizetype="Fixed">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
</property>
- </widget>
- </item>
- <item row="0" column="1">
- <widget class="QComboBox" name="headerSuffixComboBox"/>
- </item>
- <item row="1" column="0">
- <widget class="QLabel" name="sourceSuffixLabel">
- <property name="text">
- <string>Source suffix:</string>
+ <property name="title">
+ <string>Headers</string>
</property>
+ <layout class="QFormLayout" name="formLayout_2">
+ <item row="0" column="0">
+ <widget class="QLabel" name="headerSuffixLabel">
+ <property name="text">
+ <string>&amp;Suffix:</string>
+ </property>
+ <property name="buddy">
+ <cstring>headerSuffixComboBox</cstring>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="1">
+ <widget class="QComboBox" name="headerSuffixComboBox">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="0">
+ <widget class="QLabel" name="headerSearchPathsLabel">
+ <property name="text">
+ <string>S&amp;earch paths:</string>
+ </property>
+ <property name="buddy">
+ <cstring>headerSearchPathsEdit</cstring>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="1">
+ <widget class="QLineEdit" name="headerSearchPathsEdit">
+ <property name="toolTip">
+ <string>Comma-separated list of header paths.
+
+Paths can be absolute or relative to the directory of the current open document.
+
+These paths are used in addition to current directory on Switch Header/Source.</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
</widget>
</item>
- <item row="1" column="1">
- <widget class="QComboBox" name="sourceSuffixComboBox"/>
- </item>
- <item row="2" column="1">
- <widget class="QCheckBox" name="lowerCaseFileNamesCheckBox">
- <property name="text">
- <string>Lower case file names</string>
+ <item>
+ <widget class="QGroupBox" name="sourcesGroupBox">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Preferred" vsizetype="Fixed">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
</property>
+ <property name="title">
+ <string>Sources</string>
+ </property>
+ <layout class="QFormLayout" name="formLayout_3">
+ <item row="1" column="0">
+ <widget class="QLabel" name="sourceSuffixLabel">
+ <property name="text">
+ <string>S&amp;uffix:</string>
+ </property>
+ <property name="buddy">
+ <cstring>sourceSuffixComboBox</cstring>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="1">
+ <widget class="QComboBox" name="sourceSuffixComboBox">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="0">
+ <widget class="QLabel" name="sourceSearchPathsLabel">
+ <property name="text">
+ <string>Se&amp;arch paths:</string>
+ </property>
+ <property name="buddy">
+ <cstring>sourceSearchPathsEdit</cstring>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="1">
+ <widget class="QLineEdit" name="sourceSearchPathsEdit">
+ <property name="toolTip">
+ <string>Comma-separated list of source paths.
+
+Paths can be absolute or relative to the directory of the current open document.
+
+These paths are used in addition to current directory on Switch Header/Source.</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
</widget>
</item>
- <item row="3" column="0">
- <widget class="QLabel" name="licenseTemplateLabel">
+ <item>
+ <widget class="QCheckBox" name="lowerCaseFileNamesCheckBox">
<property name="text">
- <string>License template:</string>
+ <string>&amp;Lower case file names</string>
</property>
</widget>
</item>
- <item row="3" column="1">
- <widget class="Utils::PathChooser" name="licenseTemplatePathChooser" native="true"/>
+ <item>
+ <layout class="QHBoxLayout" name="horizontalLayout">
+ <item>
+ <widget class="QLabel" name="licenseTemplateLabel">
+ <property name="text">
+ <string>License &amp;template:</string>
+ </property>
+ <property name="buddy">
+ <cstring>licenseTemplatePathChooser</cstring>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="Utils::PathChooser" name="licenseTemplatePathChooser" native="true"/>
+ </item>
+ </layout>
</item>
- <item row="4" column="0" colspan="2">
+ <item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
@@ -65,13 +161,6 @@
</spacer>
</item>
</layout>
- <zorder>licenseTemplatePathChooser</zorder>
- <zorder>sourceSuffixLabel</zorder>
- <zorder>headerSuffixLabel</zorder>
- <zorder>lowerCaseFileNamesCheckBox</zorder>
- <zorder>headerSuffixComboBox</zorder>
- <zorder>sourceSuffixComboBox</zorder>
- <zorder>licenseTemplateLabel</zorder>
</widget>
<customwidgets>
<customwidget>
diff --git a/src/plugins/cpptools/cppfindreferences.cpp b/src/plugins/cpptools/cppfindreferences.cpp
index bcf590c0d9..4e5957ca45 100644
--- a/src/plugins/cpptools/cppfindreferences.cpp
+++ b/src/plugins/cpptools/cppfindreferences.cpp
@@ -48,12 +48,13 @@
#include <functional>
+using namespace Core;
using namespace CppTools::Internal;
using namespace CppTools;
using namespace CPlusPlus;
-static QString getSource(const QString &fileName,
- const CppModelManagerInterface::WorkingCopy &workingCopy)
+static QByteArray getSource(const QString &fileName,
+ const CppModelManagerInterface::WorkingCopy &workingCopy)
{
if (workingCopy.contains(fileName)) {
return workingCopy.source(fileName);
@@ -61,13 +62,13 @@ static QString getSource(const QString &fileName,
QString fileContents;
Utils::TextFileFormat format;
QString error;
- QTextCodec *defaultCodec = Core::EditorManager::instance()->defaultTextCodec();
+ QTextCodec *defaultCodec = EditorManager::defaultTextCodec();
Utils::TextFileFormat::ReadResult result = Utils::TextFileFormat::readFile(
fileName, defaultCodec, &fileContents, &format, &error);
if (result != Utils::TextFileFormat::ReadSuccess)
qWarning() << "Could not read " << fileName << ". Error: " << error;
- return fileContents;
+ return fileContents.toUtf8();
}
}
@@ -105,11 +106,11 @@ public:
if (Document::Ptr previousDoc = snapshot.document(fileName)) {
Control *control = previousDoc->control();
- if (! control->findIdentifier(symbolId->chars(), symbolId->size()))
+ if (!control->findIdentifier(symbolId->chars(), symbolId->size()))
return usages; // skip this document, it's not using symbolId.
}
Document::Ptr doc;
- const QString unpreprocessedSource = getSource(fileName, workingCopy);
+ const QByteArray unpreprocessedSource = getSource(fileName, workingCopy);
if (symbolDocument && fileName == symbolDocument->fileName()) {
doc = symbolDocument;
@@ -123,7 +124,7 @@ public:
if (doc != symbolDocument)
doc->check();
- FindUsages process(unpreprocessedSource.toUtf8(), doc, snapshot);
+ FindUsages process(unpreprocessedSource, doc, snapshot);
process(symbol);
usages = process.usages();
@@ -188,8 +189,11 @@ static void find_helper(QFutureInterface<Usage> &future,
const QString sourceFile = QString::fromUtf8(symbol->fileName(), symbol->fileNameLength());
QStringList files(sourceFile);
- if (symbol->isClass() || symbol->isForwardClassDeclaration() || (symbol->enclosingScope() && ! symbol->isStatic() &&
- symbol->enclosingScope()->isNamespace())) {
+ if (symbol->isClass()
+ || symbol->isForwardClassDeclaration()
+ || (symbol->enclosingScope()
+ && !symbol->isStatic()
+ && symbol->enclosingScope()->isNamespace())) {
foreach (const Document::Ptr &doc, context.snapshot()) {
if (doc->fileName() == sourceFile)
continue;
@@ -269,16 +273,15 @@ void CppFindReferences::findAll_helper(Find::SearchResult *search)
connect(search, SIGNAL(activated(Find::SearchResultItem)),
this, SLOT(openEditor(Find::SearchResultItem)));
- Find::SearchResultWindow::instance()->popup(Core::IOutputPane::ModeSwitch | Core::IOutputPane::WithFocus);
+ Find::SearchResultWindow::instance()->popup(IOutputPane::ModeSwitch | IOutputPane::WithFocus);
const CppModelManagerInterface::WorkingCopy workingCopy = _modelManager->workingCopy();
QFuture<Usage> result;
result = QtConcurrent::run(&find_helper, workingCopy,
parameters.context, this, parameters.symbol);
createWatcher(result, search);
- Core::ProgressManager *progressManager = Core::ICore::progressManager();
- Core::FutureProgress *progress = progressManager->addTask(result, tr("Searching"),
- QLatin1String(CppTools::Constants::TASK_SEARCH));
+ FutureProgress *progress = ProgressManager::addTask(result, tr("Searching"),
+ CppTools::Constants::TASK_SEARCH);
connect(progress, SIGNAL(clicked()), search, SLOT(popup()));
}
@@ -436,7 +439,7 @@ bool CppFindReferences::findSymbol(CppFindReferencesParameters *parameters,
Document::Ptr newSymbolDocument = snapshot.document(symbolFile);
// document is not parsed and has no bindings yet, do it
- QString source = getSource(newSymbolDocument->fileName(), _modelManager->workingCopy());
+ QByteArray source = getSource(newSymbolDocument->fileName(), _modelManager->workingCopy());
Document::Ptr doc =
snapshot.preprocessedDocument(source, newSymbolDocument->fileName());
doc->check();
@@ -509,10 +512,10 @@ void CppFindReferences::setPaused(bool paused)
void CppFindReferences::openEditor(const Find::SearchResultItem &item)
{
if (item.path.size() > 0) {
- Core::EditorManager::openEditorAt(QDir::fromNativeSeparators(item.path.first()),
+ EditorManager::openEditorAt(QDir::fromNativeSeparators(item.path.first()),
item.lineNumber, item.textMarkPos);
} else {
- Core::EditorManager::openEditor(QDir::fromNativeSeparators(item.text));
+ EditorManager::openEditor(QDir::fromNativeSeparators(item.text));
}
}
@@ -538,7 +541,7 @@ public:
{
QList<Usage> usages;
Document::Ptr doc = snapshot.document(fileName);
- QString source;
+ QByteArray source;
restart_search:
if (future->isPaused())
@@ -563,8 +566,8 @@ restart_search:
if (macro.name() == useMacro.name()) {
unsigned lineStart;
- const QString &lineSource = matchingLine(use.begin(), source, &lineStart);
- usages.append(Usage(fileName, lineSource, use.beginLine(),
+ const QByteArray &lineSource = matchingLine(use.begin(), source, &lineStart);
+ usages.append(Usage(fileName, QString::fromUtf8(lineSource), use.beginLine(),
use.begin() - lineStart, useMacro.name().length()));
}
}
@@ -575,18 +578,18 @@ restart_search:
return usages;
}
- static QString matchingLine(unsigned position, const QString &source,
- unsigned *lineStart = 0)
+ static QByteArray matchingLine(unsigned position, const QByteArray &source,
+ unsigned *lineStart = 0)
{
- int lineBegin = source.lastIndexOf(QLatin1Char('\n'), position) + 1;
- int lineEnd = source.indexOf(QLatin1Char('\n'), position);
+ int lineBegin = source.lastIndexOf('\n', position) + 1;
+ int lineEnd = source.indexOf('\n', position);
if (lineEnd == -1)
lineEnd = source.length();
if (lineStart)
*lineStart = lineBegin;
- const QString matchingLine = source.mid(lineBegin, lineEnd - lineBegin);
+ const QByteArray matchingLine = source.mid(lineBegin, lineEnd - lineBegin);
return matchingLine;
}
};
@@ -637,7 +640,7 @@ void CppFindReferences::findMacroUses(const Macro &macro, const QString &replace
connect(search, SIGNAL(replaceButtonClicked(QString,QList<Find::SearchResultItem>,bool)),
SLOT(onReplaceButtonClicked(QString,QList<Find::SearchResultItem>,bool)));
- Find::SearchResultWindow::instance()->popup(Core::IOutputPane::ModeSwitch | Core::IOutputPane::WithFocus);
+ Find::SearchResultWindow::instance()->popup(IOutputPane::ModeSwitch | IOutputPane::WithFocus);
connect(search, SIGNAL(activated(Find::SearchResultItem)),
this, SLOT(openEditor(Find::SearchResultItem)));
@@ -649,10 +652,11 @@ void CppFindReferences::findMacroUses(const Macro &macro, const QString &replace
// add the macro definition itself
{
- const QString &source = getSource(macro.fileName(), workingCopy);
+ const QByteArray &source = getSource(macro.fileName(), workingCopy);
unsigned lineStart;
- const QString line = FindMacroUsesInFile::matchingLine(macro.offset(), source, &lineStart);
- search->addResult(macro.fileName(), macro.line(), line,
+ const QByteArray line = FindMacroUsesInFile::matchingLine(macro.offset(), source,
+ &lineStart);
+ search->addResult(macro.fileName(), macro.line(), QString::fromUtf8(line),
macro.offset() - lineStart, macro.name().length());
}
@@ -660,9 +664,8 @@ void CppFindReferences::findMacroUses(const Macro &macro, const QString &replace
result = QtConcurrent::run(&findMacroUses_helper, workingCopy, snapshot, this, macro);
createWatcher(result, search);
- Core::ProgressManager *progressManager = Core::ICore::progressManager();
- Core::FutureProgress *progress = progressManager->addTask(result, tr("Searching"),
- QLatin1String(CppTools::Constants::TASK_SEARCH));
+ FutureProgress *progress = ProgressManager::addTask(result, tr("Searching"),
+ CppTools::Constants::TASK_SEARCH);
connect(progress, SIGNAL(clicked()), search, SLOT(popup()));
}
diff --git a/src/plugins/cpptools/cppfindreferences.h b/src/plugins/cpptools/cppfindreferences.h
index 9f7a96046c..13f2da5fc6 100644
--- a/src/plugins/cpptools/cppfindreferences.h
+++ b/src/plugins/cpptools/cppfindreferences.h
@@ -42,8 +42,8 @@
QT_FORWARD_DECLARE_CLASS(QTimer)
namespace Find {
- struct SearchResultItem;
- class SearchResult;
+class SearchResultItem;
+class SearchResult;
} // namespace Find
namespace CppTools {
diff --git a/src/plugins/cpptools/cppfunctionsfilter.cpp b/src/plugins/cpptools/cppfunctionsfilter.cpp
index 670276d463..53c94b0f1c 100644
--- a/src/plugins/cpptools/cppfunctionsfilter.cpp
+++ b/src/plugins/cpptools/cppfunctionsfilter.cpp
@@ -31,18 +31,36 @@
using namespace CppTools::Internal;
-CppFunctionsFilter::CppFunctionsFilter(CppModelManager *manager)
- : CppLocatorFilter(manager)
+CppFunctionsFilter::CppFunctionsFilter(CppLocatorData *locatorData)
+ : CppLocatorFilter(locatorData)
{
setId("Methods");
setDisplayName(tr("C++ Methods and Functions"));
setShortcutString(QString(QLatin1Char('m')));
setIncludedByDefault(false);
-
- search.setSymbolsToSearchFor(SymbolSearcher::Functions);
- search.setSeparateScope(true);
}
CppFunctionsFilter::~CppFunctionsFilter()
{
}
+
+QList<QList<CppTools::ModelItemInfo> > CppFunctionsFilter::itemsToMatchUserInputAgainst() const
+{
+ return QList<QList<CppTools::ModelItemInfo> >() << m_data->functions();
+}
+
+Locator::FilterEntry CppFunctionsFilter::filterEntryFromModelItemInfo(const CppTools::ModelItemInfo &info)
+{
+ const QVariant id = qVariantFromValue(info);
+
+ QString name = info.symbolName;
+ QString extraInfo = info.symbolScope;
+ info.unqualifiedNameAndScope(name, &name, &extraInfo);
+ if (extraInfo.isEmpty())
+ extraInfo = info.shortNativeFilePath();
+
+ Locator::FilterEntry filterEntry(this, name + info.symbolType, id, info.icon);
+ filterEntry.extraInfo = extraInfo;
+
+ return filterEntry;
+}
diff --git a/src/plugins/cpptools/cppfunctionsfilter.h b/src/plugins/cpptools/cppfunctionsfilter.h
index 9d67ef2543..1357e6d76d 100644
--- a/src/plugins/cpptools/cppfunctionsfilter.h
+++ b/src/plugins/cpptools/cppfunctionsfilter.h
@@ -30,6 +30,7 @@
#ifndef CPPFUNCTIONSFILTER_H
#define CPPFUNCTIONSFILTER_H
+#include "cpplocatordata.h"
#include "cpplocatorfilter.h"
namespace CppTools {
@@ -40,8 +41,12 @@ class CppFunctionsFilter : public CppLocatorFilter
Q_OBJECT
public:
- CppFunctionsFilter(CppModelManager *manager);
+ CppFunctionsFilter(CppLocatorData *locatorData);
~CppFunctionsFilter();
+
+private:
+ QList<QList<ModelItemInfo> > itemsToMatchUserInputAgainst() const;
+ Locator::FilterEntry filterEntryFromModelItemInfo(const ModelItemInfo &info);
};
} // namespace Internal
diff --git a/src/plugins/cpptools/cppheadersource_test.cpp b/src/plugins/cpptools/cppheadersource_test.cpp
new file mode 100644
index 0000000000..26d833d1c4
--- /dev/null
+++ b/src/plugins/cpptools/cppheadersource_test.cpp
@@ -0,0 +1,72 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Orgad Shaneh <orgads@gmail.com>.
+** 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 "cpptoolsreuse.h"
+
+#include <coreplugin/testdatadir.h>
+
+#include <QDir>
+#include <QtTest>
+
+static inline QString _(const QByteArray &ba) { return QString::fromLatin1(ba, ba.size()); }
+
+namespace CppTools {
+namespace Internal {
+
+void CppToolsPlugin::test_headersource()
+{
+ QFETCH(QString, sourceFileName);
+ QFETCH(QString, headerFileName);
+
+ bool wasHeader;
+ Core::Internal::Tests::TestDataDir dataDir(
+ _(SRCDIR "/../../../tests/cppheadersource/") + _(QTest::currentDataTag()));
+
+ const QString sourcePath = dataDir.file(sourceFileName);
+ const QString headerPath = dataDir.file(headerFileName);
+
+ clearHeaderSourceCache();
+ QCOMPARE(correspondingHeaderOrSource(sourcePath, &wasHeader), headerPath);
+ QVERIFY(!wasHeader);
+ clearHeaderSourceCache();
+ QCOMPARE(correspondingHeaderOrSource(headerPath, &wasHeader), sourcePath);
+ QVERIFY(wasHeader);
+}
+
+void CppToolsPlugin::test_headersource_data()
+{
+ QTest::addColumn<QString>("sourceFileName");
+ QTest::addColumn<QString>("headerFileName");
+ QTest::newRow("samedir") << _("foo.cpp") << _("foo.h");
+ QTest::newRow("includesub") << _("foo.cpp") << _("include/foo.h");
+}
+
+} // namespace Internal
+} // namespace CppTools
diff --git a/src/plugins/cpptools/cpphighlightingsupport.cpp b/src/plugins/cpptools/cpphighlightingsupport.cpp
index 66469fcc87..2534618467 100644
--- a/src/plugins/cpptools/cpphighlightingsupport.cpp
+++ b/src/plugins/cpptools/cpphighlightingsupport.cpp
@@ -40,7 +40,3 @@ CppHighlightingSupport::CppHighlightingSupport(TextEditor::ITextEditor *editor)
CppHighlightingSupport::~CppHighlightingSupport()
{
}
-
-CppHighlightingSupportFactory::~CppHighlightingSupportFactory()
-{
-}
diff --git a/src/plugins/cpptools/cpphighlightingsupport.h b/src/plugins/cpptools/cpphighlightingsupport.h
index 7fd77898c2..ee085732b2 100644
--- a/src/plugins/cpptools/cpphighlightingsupport.h
+++ b/src/plugins/cpptools/cpphighlightingsupport.h
@@ -67,6 +67,7 @@ public:
virtual bool requiresSemanticInfo() const = 0;
virtual bool hightlighterHandlesDiagnostics() const = 0;
+ virtual bool hightlighterHandlesIfdefedOutBlocks() const = 0;
virtual QFuture<TextEditor::HighlightingResult> highlightingFuture(
const CPlusPlus::Document::Ptr &doc,
@@ -80,14 +81,6 @@ private:
TextEditor::ITextEditor *m_editor;
};
-class CPPTOOLS_EXPORT CppHighlightingSupportFactory
-{
-public:
- virtual ~CppHighlightingSupportFactory() = 0;
-
- virtual CppHighlightingSupport *highlightingSupport(TextEditor::ITextEditor *editor) = 0;
-};
-
} // namespace CppTools
#endif // CPPTOOLS_CPPHIGHLIGHTINGSUPPORT_H
diff --git a/src/plugins/cpptools/cpphighlightingsupportinternal.cpp b/src/plugins/cpptools/cpphighlightingsupportinternal.cpp
index ae39a0a076..4ad285258b 100644
--- a/src/plugins/cpptools/cpphighlightingsupportinternal.cpp
+++ b/src/plugins/cpptools/cpphighlightingsupportinternal.cpp
@@ -92,12 +92,3 @@ QFuture<TextEditor::HighlightingResult> CppHighlightingSupportInternal::highligh
LookupContext context(doc, snapshot);
return CheckSymbols::go(doc, context, macroUses);
}
-
-CppHighlightingSupportInternalFactory::~CppHighlightingSupportInternalFactory()
-{
-}
-
-CppHighlightingSupport *CppHighlightingSupportInternalFactory::highlightingSupport(TextEditor::ITextEditor *editor)
-{
- return new CppHighlightingSupportInternal(editor);
-}
diff --git a/src/plugins/cpptools/cpphighlightingsupportinternal.h b/src/plugins/cpptools/cpphighlightingsupportinternal.h
index a2b5d4db73..7d27486491 100644
--- a/src/plugins/cpptools/cpphighlightingsupportinternal.h
+++ b/src/plugins/cpptools/cpphighlightingsupportinternal.h
@@ -49,19 +49,14 @@ public:
virtual bool hightlighterHandlesDiagnostics() const
{ return false; }
+ virtual bool hightlighterHandlesIfdefedOutBlocks() const
+ { return false; }
+
virtual QFuture<TextEditor::HighlightingResult> highlightingFuture(
const CPlusPlus::Document::Ptr &doc,
const CPlusPlus::Snapshot &snapshot) const;
};
-class CppHighlightingSupportInternalFactory: public CppHighlightingSupportFactory
-{
-public:
- virtual ~CppHighlightingSupportInternalFactory();
-
- virtual CppHighlightingSupport *highlightingSupport(TextEditor::ITextEditor *editor);
-};
-
} // namespace Internal
} // namespace CppTools
diff --git a/src/plugins/cpptools/cpplocalsymbols.cpp b/src/plugins/cpptools/cpplocalsymbols.cpp
index 361fd5d9d6..58d9bffbae 100644
--- a/src/plugins/cpptools/cpplocalsymbols.cpp
+++ b/src/plugins/cpptools/cpplocalsymbols.cpp
@@ -84,7 +84,7 @@ protected:
if (Symbol *member = scope->memberAt(i)) {
if (member->isTypedef())
continue;
- else if (! member->isGenerated() && (member->isDeclaration() || member->isArgument())) {
+ if (!member->isGenerated() && (member->isDeclaration() || member->isArgument())) {
if (member->name() && member->name()->isNameId()) {
const Identifier *id = member->identifier();
unsigned line, column;
@@ -106,10 +106,10 @@ protected:
const Identifier *id = identifier(simpleName->identifier_token);
for (int i = _scopeStack.size() - 1; i != -1; --i) {
if (Symbol *member = _scopeStack.at(i)->find(id)) {
- if (member->isTypedef() ||
- !(member->isDeclaration() || member->isArgument()))
+ if (member->isTypedef() || !(member->isDeclaration() || member->isArgument()))
continue;
- else if (!member->isGenerated() && (member->sourceLocation() < firstToken || member->enclosingScope()->isFunction())) {
+ if (!member->isGenerated() && (member->sourceLocation() < firstToken
+ || member->enclosingScope()->isFunction())) {
unsigned line, column;
getTokenStartPosition(simpleName->identifier_token, &line, &column);
localUses[member].append(
diff --git a/src/plugins/cpptools/cpplocatordata.cpp b/src/plugins/cpptools/cpplocatordata.cpp
new file mode 100644
index 0000000000..14fcd9df2c
--- /dev/null
+++ b/src/plugins/cpptools/cpplocatordata.cpp
@@ -0,0 +1,162 @@
+/****************************************************************************
+**
+** 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 "cpplocatordata.h"
+
+using namespace CppTools;
+using namespace CppTools::Internal;
+
+static const int MaxPendingDocuments = 10;
+
+CppLocatorData::CppLocatorData(CppModelManager *modelManager)
+ : m_modelManager(modelManager)
+ , m_pendingDocumentsMutex(QMutex::Recursive)
+{
+ m_search.setSymbolsToSearchFor(SymbolSearcher::Enums
+ | SymbolSearcher::Classes
+ | SymbolSearcher::Functions);
+ m_pendingDocuments.reserve(MaxPendingDocuments);
+
+ connect(m_modelManager, SIGNAL(documentUpdated(CPlusPlus::Document::Ptr)),
+ this, SLOT(onDocumentUpdated(CPlusPlus::Document::Ptr)));
+
+ connect(m_modelManager, SIGNAL(aboutToRemoveFiles(QStringList)),
+ this, SLOT(onAboutToRemoveFiles(QStringList)));
+}
+
+QList<ModelItemInfo> CppLocatorData::enums()
+{
+ flushPendingDocument(true);
+ return allModelItemInfos(m_allEnums);
+}
+
+QList<ModelItemInfo> CppLocatorData::classes()
+{
+ flushPendingDocument(true);
+ return allModelItemInfos(m_allClasses);
+}
+
+QList<ModelItemInfo> CppLocatorData::functions()
+{
+ flushPendingDocument(true);
+ return allModelItemInfos(m_allFunctions);
+}
+
+void CppLocatorData::onDocumentUpdated(const CPlusPlus::Document::Ptr &document)
+{
+ QMutexLocker locker(&m_pendingDocumentsMutex);
+
+ int i = 0, ei = m_pendingDocuments.size();
+ for (; i < ei; ++i) {
+ const CPlusPlus::Document::Ptr &doc = m_pendingDocuments.at(i);
+ if (doc->fileName() == document->fileName()
+ && doc->revision() < document->revision()) {
+ m_pendingDocuments[i] = document;
+ break;
+ }
+ }
+
+ if (i == ei)
+ m_pendingDocuments.append(document);
+
+ flushPendingDocument(false);
+}
+
+void CppLocatorData::onAboutToRemoveFiles(const QStringList &files)
+{
+ QMutexLocker locker(&m_pendingDocumentsMutex);
+
+ for (int i = 0; i < m_pendingDocuments.size(); ) {
+ if (files.contains(m_pendingDocuments.at(i)->fileName()))
+ m_pendingDocuments.remove(i);
+ else
+ ++i;
+ }
+
+ foreach (const QString &file, files) {
+ m_allEnums.remove(file);
+ m_allClasses.remove(file);
+ m_allFunctions.remove(file);
+ removeFilePath(file);
+ }
+}
+
+void CppLocatorData::flushPendingDocument(bool force)
+{
+ QMutexLocker locker(&m_pendingDocumentsMutex);
+ if (!force && m_pendingDocuments.size() < MaxPendingDocuments)
+ return;
+
+ foreach (CPlusPlus::Document::Ptr doc, m_pendingDocuments) {
+ const QString fileName = findOrInsertFilePath(doc->fileName());
+
+ QList<ModelItemInfo> resultsEnums;
+ QList<ModelItemInfo> resultsClasses;
+ QList<ModelItemInfo> resultsFunctions;
+
+ const int sizeHint = m_allEnums[fileName].size() + m_allClasses[fileName].size()
+ + m_allFunctions[fileName].size() + 10;
+ const QList<ModelItemInfo> results = m_search(doc, sizeHint);
+ foreach (const ModelItemInfo &info, results) {
+ switch (info.type) {
+ case ModelItemInfo::Enum:
+ resultsEnums.append(info);
+ break;
+ case ModelItemInfo::Class:
+ resultsClasses.append(info);
+ break;
+ case ModelItemInfo::Method:
+ resultsFunctions.append(info);
+ break;
+ default:
+ break;
+ }
+ }
+
+ m_allEnums[fileName] = resultsEnums;
+ m_allClasses[fileName] = resultsClasses;
+ m_allFunctions[fileName] = resultsFunctions;
+ }
+
+ m_pendingDocuments.clear();
+ m_pendingDocuments.reserve(MaxPendingDocuments);
+}
+
+QList<ModelItemInfo> CppLocatorData::allModelItemInfos(const QHash<QString,
+ QList<ModelItemInfo> > &items) const
+{
+ QList<ModelItemInfo> result;
+ QHashIterator<QString, QList<ModelItemInfo> > it(items);
+ while (it.hasNext()) {
+ it.next();
+ result.append(it.value());
+ }
+ return result;
+}
diff --git a/src/plugins/debugger/gdb/remoteplaingdbadapter.h b/src/plugins/cpptools/cpplocatordata.h
index 92df4945f0..d7a47c4161 100644
--- a/src/plugins/debugger/gdb/remoteplaingdbadapter.h
+++ b/src/plugins/cpptools/cpplocatordata.h
@@ -27,46 +27,61 @@
**
****************************************************************************/
-#ifndef REMOTEPLAINGDBADAPTER_H
-#define REMOTEPLAINGDBADAPTER_H
-#include "abstractplaingdbadapter.h"
-#include "remotegdbprocess.h"
+#ifndef CPPLOCATORDATA_H
+#define CPPLOCATORDATA_H
-namespace Debugger {
+#include <QHash>
+#include <QVector>
+
+#include <cplusplus/CppDocument.h>
+
+#include "cppmodelmanager.h"
+#include "searchsymbols.h"
+
+namespace CppTools {
namespace Internal {
-class GdbRemotePlainEngine : public GdbAbstractPlainEngine
+class CppLocatorData : public QObject
{
Q_OBJECT
-
public:
- friend class RemoteGdbProcess;
- explicit GdbRemotePlainEngine(const DebuggerStartParameters &startParameters);
+ explicit CppLocatorData(CppModelManager *modelManager);
+
+ QList<ModelItemInfo> enums();
+ QList<ModelItemInfo> classes();
+ QList<ModelItemInfo> functions();
private slots:
- void handleGdbStarted();
- void handleGdbStartFailed1();
+ void onDocumentUpdated(const CPlusPlus::Document::Ptr &document);
+ void onAboutToRemoveFiles(const QStringList &files);
+
+private:
+ void flushPendingDocument(bool force);
+ QList<ModelItemInfo> allModelItemInfos(const QHash<QString,
+ QList<ModelItemInfo> > &items) const;
+
+ QString findOrInsertFilePath(const QString &path)
+ { return *m_filePaths.insert(path); }
+
+ void removeFilePath(const QString &path)
+ { m_filePaths.remove(path); }
private:
- void setupEngine();
- void setupInferior();
- void interruptInferior2();
- void shutdownEngine();
- void notifyEngineRemoteSetupDone(int gdbServerPort, int qmlPort);
- void notifyEngineRemoteSetupFailed(const QString &reason);
- AbstractGdbProcess *gdbProc() { return &m_gdbProc; }
- DumperHandling dumperHandling() const { return DumperLoadedByGdbPreload; }
-
- QByteArray execFilePath() const;
- QByteArray toLocalEncoding(const QString &s) const;
- QString fromLocalEncoding(const QByteArray &b) const;
- void handleApplicationOutput(const QByteArray &output);
-
- RemoteGdbProcess m_gdbProc;
+ CppModelManager *m_modelManager;
+
+ QSet<QString> m_filePaths; // Used to avoid QString duplication
+
+ SearchSymbols m_search;
+ QHash<QString, QList<ModelItemInfo> > m_allEnums;
+ QHash<QString, QList<ModelItemInfo> > m_allClasses;
+ QHash<QString, QList<ModelItemInfo> > m_allFunctions;
+
+ mutable QMutex m_pendingDocumentsMutex;
+ QVector<CPlusPlus::Document::Ptr> m_pendingDocuments;
};
} // namespace Internal
-} // namespace Debugger
+} // namespace CppTools
-#endif // REMOTEPLAINGDBADAPTER_H
+#endif // CPPLOCATORDATA_H
diff --git a/src/plugins/cpptools/cpplocatorfilter.cpp b/src/plugins/cpptools/cpplocatorfilter.cpp
index 0117a7d981..d8caaf8260 100644
--- a/src/plugins/cpptools/cpplocatorfilter.cpp
+++ b/src/plugins/cpptools/cpplocatorfilter.cpp
@@ -30,90 +30,45 @@
#include "cpplocatorfilter.h"
#include "cppmodelmanager.h"
-#include <utils/fileutils.h>
-
#include <QStringMatcher>
using namespace CppTools::Internal;
-using namespace Utils;
-
-static const int MaxPendingDocuments = 10;
-CppLocatorFilter::CppLocatorFilter(CppModelManager *manager)
- : m_manager(manager)
- , m_pendingDocumentsMutex(QMutex::Recursive)
+CppLocatorFilter::CppLocatorFilter(CppLocatorData *locatorData)
+ : m_data(locatorData)
{
setId("Classes and Methods");
setDisplayName(tr("C++ Classes and Methods"));
setShortcutString(QString(QLatin1Char(':')));
setIncludedByDefault(false);
-
- m_pendingDocuments.reserve(MaxPendingDocuments);
-
- connect(manager, SIGNAL(documentUpdated(CPlusPlus::Document::Ptr)),
- this, SLOT(onDocumentUpdated(CPlusPlus::Document::Ptr)));
-
- connect(manager, SIGNAL(aboutToRemoveFiles(QStringList)),
- this, SLOT(onAboutToRemoveFiles(QStringList)));
}
CppLocatorFilter::~CppLocatorFilter()
-{ }
-
-
-void CppLocatorFilter::flushPendingDocument(bool force)
{
- QMutexLocker locker(&m_pendingDocumentsMutex);
- if (!force && m_pendingDocuments.size() < MaxPendingDocuments)
- return;
-
- foreach (CPlusPlus::Document::Ptr doc, m_pendingDocuments) {
- QList<ModelItemInfo> &results = m_searchList[doc->fileName()];
- results = search(doc, results.size() + 10);
- }
-
- m_pendingDocuments.clear();
- m_pendingDocuments.reserve(MaxPendingDocuments);
}
-void CppLocatorFilter::onDocumentUpdated(CPlusPlus::Document::Ptr updatedDoc)
+Locator::FilterEntry CppLocatorFilter::filterEntryFromModelItemInfo(const CppTools::ModelItemInfo &info)
{
- QMutexLocker locker(&m_pendingDocumentsMutex);
+ const QVariant id = qVariantFromValue(info);
+ Locator::FilterEntry filterEntry(this, info.scopedSymbolName(), id, info.icon);
+ filterEntry.extraInfo = info.type == ModelItemInfo::Class || info.type == ModelItemInfo::Enum
+ ? info.shortNativeFilePath()
+ : info.symbolType;
- int i = 0, ei = m_pendingDocuments.size();
- for (; i < ei; ++i) {
- const CPlusPlus::Document::Ptr &doc = m_pendingDocuments.at(i);
- if (doc->fileName() == updatedDoc->fileName()
- && doc->revision() < updatedDoc->revision()) {
- m_pendingDocuments[i] = updatedDoc;
- break;
- }
- }
-
- if (i == ei)
- m_pendingDocuments.append(updatedDoc);
-
- flushPendingDocument(false);
+ return filterEntry;
}
-void CppLocatorFilter::onAboutToRemoveFiles(const QStringList &files)
+void CppLocatorFilter::refresh(QFutureInterface<void> &future)
{
- QMutexLocker locker(&m_pendingDocumentsMutex);
-
- for (int i = 0; i < m_pendingDocuments.size(); ) {
- if (files.contains(m_pendingDocuments.at(i)->fileName()))
- m_pendingDocuments.remove(i);
- else
- ++i;
- }
-
- foreach (const QString &file, files)
- m_searchList.remove(file);
+ Q_UNUSED(future)
}
-void CppLocatorFilter::refresh(QFutureInterface<void> &future)
+QList<QList<CppTools::ModelItemInfo> > CppLocatorFilter::itemsToMatchUserInputAgainst() const
{
- Q_UNUSED(future)
+ return QList<QList<CppTools::ModelItemInfo> >()
+ << m_data->classes()
+ << m_data->functions()
+ << m_data->enums();
}
static bool compareLexigraphically(const Locator::FilterEntry &a,
@@ -124,8 +79,6 @@ static bool compareLexigraphically(const Locator::FilterEntry &a,
QList<Locator::FilterEntry> CppLocatorFilter::matchesFor(QFutureInterface<Locator::FilterEntry> &future, const QString &origEntry)
{
- flushPendingDocument(true);
-
QString entry = trimWildcards(origEntry);
QList<Locator::FilterEntry> goodEntries;
QList<Locator::FilterEntry> betterEntries;
@@ -135,29 +88,19 @@ QList<Locator::FilterEntry> CppLocatorFilter::matchesFor(QFutureInterface<Locato
if (!regexp.isValid())
return goodEntries;
bool hasWildcard = (entry.contains(asterisk) || entry.contains(QLatin1Char('?')));
+ bool hasColonColon = entry.contains(QLatin1String("::"));
+ const Qt::CaseSensitivity caseSensitivityForPrefix = caseSensitivity(entry);
- QHashIterator<QString, QList<ModelItemInfo> > it(m_searchList);
- while (it.hasNext()) {
- if (future.isCanceled())
- break;
-
- it.next();
-
- const QList<ModelItemInfo> items = it.value();
+ const QList<QList<CppTools::ModelItemInfo> > itemLists = itemsToMatchUserInputAgainst();
+ foreach (const QList<CppTools::ModelItemInfo> &items, itemLists) {
foreach (const ModelItemInfo &info, items) {
- if ((hasWildcard && regexp.exactMatch(info.symbolName))
- || (!hasWildcard && matcher.indexIn(info.symbolName) != -1)) {
-
- QVariant id = qVariantFromValue(info);
- Locator::FilterEntry filterEntry(this, info.symbolName, id, info.icon);
- if (! info.symbolType.isEmpty()) {
- filterEntry.extraInfo = info.symbolType;
- } else {
- filterEntry.extraInfo = FileUtils::shortNativePath(
- FileName::fromString(info.fileName));
- }
-
- if (info.symbolName.startsWith(entry))
+ if (future.isCanceled())
+ break;
+ const QString matchString = hasColonColon ? info.scopedSymbolName() : info.symbolName;
+ if ((hasWildcard && regexp.exactMatch(matchString))
+ || (!hasWildcard && matcher.indexIn(matchString) != -1)) {
+ const Locator::FilterEntry filterEntry = filterEntryFromModelItemInfo(info);
+ if (matchString.startsWith(entry, caseSensitivityForPrefix))
betterEntries.append(filterEntry);
else
goodEntries.append(filterEntry);
@@ -166,9 +109,9 @@ QList<Locator::FilterEntry> CppLocatorFilter::matchesFor(QFutureInterface<Locato
}
if (goodEntries.size() < 1000)
- qSort(goodEntries.begin(), goodEntries.end(), compareLexigraphically);
+ qStableSort(goodEntries.begin(), goodEntries.end(), compareLexigraphically);
if (betterEntries.size() < 1000)
- qSort(betterEntries.begin(), betterEntries.end(), compareLexigraphically);
+ qStableSort(betterEntries.begin(), betterEntries.end(), compareLexigraphically);
betterEntries += goodEntries;
return betterEntries;
@@ -179,9 +122,3 @@ void CppLocatorFilter::accept(Locator::FilterEntry selection) const
ModelItemInfo info = qvariant_cast<CppTools::ModelItemInfo>(selection.internalData);
Core::EditorManager::openEditorAt(info.fileName, info.line, info.column);
}
-
-void CppLocatorFilter::reset()
-{
- m_searchList.clear();
- m_previousEntry.clear();
-}
diff --git a/src/plugins/cpptools/cpplocatorfilter.h b/src/plugins/cpptools/cpplocatorfilter.h
index e4cfbaca75..583cdbb57f 100644
--- a/src/plugins/cpptools/cpplocatorfilter.h
+++ b/src/plugins/cpptools/cpplocatorfilter.h
@@ -30,6 +30,7 @@
#ifndef CPPLOCATORFILTER_H
#define CPPLOCATORFILTER_H
+#include "cpplocatordata.h"
#include "searchsymbols.h"
#include <locator/ilocatorfilter.h>
@@ -44,32 +45,19 @@ class CppLocatorFilter : public Locator::ILocatorFilter
Q_OBJECT
public:
- CppLocatorFilter(CppModelManager *manager);
+ CppLocatorFilter(CppLocatorData *locatorData);
~CppLocatorFilter();
QList<Locator::FilterEntry> matchesFor(QFutureInterface<Locator::FilterEntry> &future, const QString &entry);
void accept(Locator::FilterEntry selection) const;
void refresh(QFutureInterface<void> &future);
- void reset();
-
-protected:
- SearchSymbols search;
-
- void flushPendingDocument(bool force);
-
-private slots:
- void onDocumentUpdated(CPlusPlus::Document::Ptr updatedDoc);
- void onAboutToRemoveFiles(const QStringList &files);
-
private:
- CppModelManager *m_manager;
-
- QHash<QString, QList<ModelItemInfo> > m_searchList;
- QString m_previousEntry;
+ virtual QList<QList<ModelItemInfo> > itemsToMatchUserInputAgainst() const;
+ virtual Locator::FilterEntry filterEntryFromModelItemInfo(const ModelItemInfo &info);
- mutable QMutex m_pendingDocumentsMutex;
- QVector<CPlusPlus::Document::Ptr> m_pendingDocuments;
+protected:
+ CppLocatorData *m_data;
};
} // namespace Internal
diff --git a/src/plugins/cpptools/cpplocatorfilter_test.cpp b/src/plugins/cpptools/cpplocatorfilter_test.cpp
new file mode 100644
index 0000000000..cd8768192b
--- /dev/null
+++ b/src/plugins/cpptools/cpplocatorfilter_test.cpp
@@ -0,0 +1,294 @@
+/****************************************************************************
+**
+** 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 "cppclassesfilter.h"
+#include "cppcurrentdocumentfilter.h"
+#include "cppfunctionsfilter.h"
+#include "cpplocatorfilter.h"
+#include "cppmodelmanager.h"
+
+#include <coreplugin/editormanager/editormanager.h>
+#include <coreplugin/testdatadir.h>
+#include <extensionsystem/pluginmanager.h>
+#include <locator/locatorfiltertest.h>
+#include <utils/fileutils.h>
+
+#include <QDebug>
+#include <QFileInfo>
+#include <QtTest>
+
+using namespace Core;
+using namespace Core::Internal::Tests;
+using namespace CppTools::Internal;
+using namespace ExtensionSystem;
+using namespace Locator;
+using namespace Locator::Internal;
+using namespace Locator::Internal::Tests;
+using namespace Utils;
+
+Q_DECLARE_METATYPE(ILocatorFilter *)
+
+namespace {
+
+class MyTestDataDir : public Core::Internal::Tests::TestDataDir
+{
+public:
+ MyTestDataDir(const QString &testDataDirectory)
+ : TestDataDir(QLatin1String(SRCDIR "/../../../tests/cpplocators/") + testDataDirectory) {}
+};
+
+class CppLocatorFilterTest : public BasicLocatorFilterTest
+{
+public:
+ CppLocatorFilterTest(ILocatorFilter *filter, const QString &fileName)
+ : BasicLocatorFilterTest(filter)
+ , m_modelManager(CppModelManager::instance())
+ , m_fileName(fileName)
+ {
+ QVERIFY(!m_fileName.isEmpty());
+ m_modelManager->GC();
+ QVERIFY(m_modelManager->snapshot().isEmpty());
+ }
+
+private:
+ virtual void doBeforeLocatorRun()
+ {
+ m_modelManager->updateSourceFiles(QStringList() << m_fileName).waitForFinished();
+ QVERIFY(m_modelManager->snapshot().contains(m_fileName));
+ QCoreApplication::processEvents();
+ }
+
+ virtual void doAfterLocatorRun()
+ {
+ m_modelManager->GC();
+ QVERIFY(m_modelManager->snapshot().isEmpty());
+ }
+
+ CppModelManager *m_modelManager;
+ const QString m_fileName;
+};
+
+class CppCurrentDocumentFilterTest : public BasicLocatorFilterTest
+{
+public:
+ CppCurrentDocumentFilterTest(const QString &fileName)
+ : BasicLocatorFilterTest(PluginManager::getObject<CppCurrentDocumentFilter>())
+ , m_modelManager(CppModelManager::instance())
+ , m_editor(0)
+ , m_fileName(fileName)
+ {
+ QVERIFY(!m_fileName.isEmpty());
+ m_modelManager->GC();
+ QVERIFY(m_modelManager->snapshot().isEmpty());
+ }
+
+private:
+ virtual void doBeforeLocatorRun()
+ {
+ QVERIFY(EditorManager::documentModel()->openedDocuments().isEmpty());
+ m_modelManager->GC();
+ QVERIFY(m_modelManager->snapshot().isEmpty());
+
+ m_editor = EditorManager::openEditor(m_fileName);
+ QVERIFY(m_editor);
+ while (!m_modelManager->snapshot().contains(m_fileName))
+ QCoreApplication::processEvents();
+ }
+
+ virtual void doAfterLocatorRun()
+ {
+ EditorManager::closeEditor(m_editor, /*askAboutModifiedEditors=*/ false);
+ QCoreApplication::processEvents();
+ QVERIFY(EditorManager::documentModel()->openedDocuments().isEmpty());
+ m_modelManager->GC();
+ QVERIFY(m_modelManager->snapshot().isEmpty());
+ }
+
+ CppModelManager *m_modelManager;
+ IEditor *m_editor;
+ const QString m_fileName;
+};
+
+inline QString _(const QByteArray &ba) { return QString::fromLatin1(ba, ba.size()); }
+
+} // anonymous namespace
+
+void CppToolsPlugin::test_cpplocatorfilters_CppLocatorFilter()
+{
+ QFETCH(QString, testFile);
+ QFETCH(ILocatorFilter *, filter);
+ QFETCH(QString, searchText);
+ QFETCH(ResultDataList, expectedResults);
+
+ CppLocatorFilterTest test(filter, testFile);
+ ResultDataList results = ResultData::fromFilterEntryList(test.matchesFor(searchText));
+// ResultData::printFilterEntries(results);
+ QVERIFY(!results.isEmpty());
+ QCOMPARE(results, expectedResults);
+}
+
+void CppToolsPlugin::test_cpplocatorfilters_CppLocatorFilter_data()
+{
+ QTest::addColumn<QString>("testFile");
+ QTest::addColumn<ILocatorFilter *>("filter");
+ QTest::addColumn<QString>("searchText");
+ QTest::addColumn<ResultDataList>("expectedResults");
+
+ ILocatorFilter *cppFunctionsFilter = PluginManager::getObject<CppFunctionsFilter>();
+ ILocatorFilter *cppClassesFilter = PluginManager::getObject<CppClassesFilter>();
+ ILocatorFilter *cppLocatorFilter = PluginManager::getObject<CppLocatorFilter>();
+
+ MyTestDataDir testDirectory(QLatin1String("testdata_basic"));
+ const QString testFile = testDirectory.file(QLatin1String("file1.cpp"));
+ const QString testFileShort = FileUtils::shortNativePath(FileName::fromString(testFile));
+
+ QTest::newRow("CppFunctionsFilter")
+ << testFile
+ << cppFunctionsFilter
+ << QString::fromLatin1("function")
+ << (QList<ResultData>()
+ << ResultData(_("functionDefinedInClass(bool, int)"), _("MyClass"))
+ << ResultData(_("functionDefinedInClass(bool, int)"), _("MyNamespace::MyClass"))
+ << ResultData(_("functionDefinedInClass(bool, int)"), _("<anonymous namespace>::MyClass"))
+ << ResultData(_("functionDefinedOutSideClass(char)"), _("MyClass"))
+ << ResultData(_("functionDefinedOutSideClass(char)"), _("MyNamespace::MyClass"))
+ << ResultData(_("functionDefinedOutSideClass(char)"), _("<anonymous namespace>::MyClass"))
+ << ResultData(_("functionDefinedOutSideClassAndNamespace(float)"), _("MyNamespace::MyClass"))
+ << ResultData(_("myFunction(bool, int)"), testFileShort)
+ << ResultData(_("myFunction(bool, int)"), _("MyNamespace"))
+ << ResultData(_("myFunction(bool, int)"), _("<anonymous namespace>"))
+ );
+
+ QTest::newRow("CppFunctionsFilter-WithNamespacePrefix")
+ << testFile
+ << cppFunctionsFilter
+ << _("mynamespace::")
+ << (QList<ResultData>()
+ << ResultData(_("MyClass()"), _("MyNamespace::MyClass"))
+ << ResultData(_("functionDefinedInClass(bool, int)"), _("MyNamespace::MyClass"))
+ << ResultData(_("functionDefinedOutSideClass(char)"), _("MyNamespace::MyClass"))
+ << ResultData(_("functionDefinedOutSideClassAndNamespace(float)"), _("MyNamespace::MyClass"))
+ << ResultData(_("myFunction(bool, int)"), _("MyNamespace"))
+ );
+
+ QTest::newRow("CppClassesFilter")
+ << testFile
+ << cppClassesFilter
+ << _("myclass")
+ << (QList<ResultData>()
+ << ResultData(_("MyClass"), testFileShort)
+ << ResultData(_("MyClass"), _("MyNamespace"))
+ << ResultData(_("MyClass"), _("<anonymous namespace>"))
+ );
+
+ QTest::newRow("CppClassesFilter-WithNamespacePrefix")
+ << testFile
+ << cppClassesFilter
+ << _("mynamespace::")
+ << (QList<ResultData>()
+ << ResultData(_("MyClass"), _("MyNamespace"))
+ );
+
+ // all symbols in the left column are expected to be fully qualified.
+ QTest::newRow("CppLocatorFilter-filtered")
+ << testFile
+ << cppLocatorFilter
+ << _("my")
+ << (QList<ResultData>()
+ << ResultData(_("<anonymous namespace>::MyClass"), testFileShort)
+ << ResultData(_("<anonymous namespace>::MyClass::MyClass"), _("()"))
+ << ResultData(_("<anonymous namespace>::MyClass::functionDefinedOutSideClass"), _("(char)"))
+ << ResultData(_("<anonymous namespace>::MyEnum"), testFileShort)
+ << ResultData(_("<anonymous namespace>::myFunction"), _("(bool, int)"))
+ << ResultData(_("MyClass"), testFileShort)
+ << ResultData(_("MyClass::MyClass"), _("()"))
+ << ResultData(_("MyClass::functionDefinedOutSideClass"), _("(char)"))
+ << ResultData(_("MyEnum"), testFileShort)
+ << ResultData(_("MyNamespace::MyClass"), testFileShort)
+ << ResultData(_("MyNamespace::MyClass::MyClass"), _("()"))
+ << ResultData(_("MyNamespace::MyClass::functionDefinedOutSideClass"), _("(char)"))
+ << ResultData(_("MyNamespace::MyClass::functionDefinedOutSideClassAndNamespace"), _("(float)"))
+ << ResultData(_("MyNamespace::MyEnum"), testFileShort)
+ << ResultData(_("MyNamespace::myFunction"), _("(bool, int)"))
+ << ResultData(_("myFunction"), _("(bool, int)"))
+ );
+}
+
+void CppToolsPlugin::test_cpplocatorfilters_CppCurrentDocumentFilter()
+{
+ MyTestDataDir testDirectory(QLatin1String("testdata_basic"));
+ const QString testFile = testDirectory.file(QLatin1String("file1.cpp"));
+
+ QList<ResultData> expectedResults = QList<ResultData>()
+ << ResultData(_("int myVariable"), _(""))
+ << ResultData(_("myFunction(bool, int)"), _(""))
+ << ResultData(_("MyEnum"), _(""))
+ << ResultData(_("int V1"), _("MyEnum"))
+ << ResultData(_("int V2"), _("MyEnum"))
+ << ResultData(_("MyClass"), _(""))
+ << ResultData(_("MyClass"), _("MyClass"))
+ << ResultData(_("functionDeclaredOnly"), _("MyClass"))
+ << ResultData(_("functionDefinedInClass"), _("MyClass"))
+ << ResultData(_("functionDefinedOutSideClass"), _("MyClass"))
+ << ResultData(_("functionDefinedOutSideClass"), _("MyClass"))
+ << ResultData(_("int myVariable"), _("MyNamespace"))
+ << ResultData(_("myFunction"), _("MyNamespace"))
+ << ResultData(_("MyEnum"), _("MyNamespace"))
+ << ResultData(_("int V1"), _("MyNamespace::MyEnum"))
+ << ResultData(_("int V2"), _("MyNamespace::MyEnum"))
+ << ResultData(_("MyClass"), _("MyNamespace"))
+ << ResultData(_("MyClass"), _("MyNamespace::MyClass"))
+ << ResultData(_("functionDeclaredOnly"), _("MyNamespace::MyClass"))
+ << ResultData(_("functionDefinedInClass"), _("MyNamespace::MyClass"))
+ << ResultData(_("functionDefinedOutSideClass"), _("MyNamespace::MyClass"))
+ << ResultData(_("functionDefinedOutSideClassAndNamespace"), _("MyNamespace::MyClass"))
+ << ResultData(_("functionDefinedOutSideClass"), _("MyNamespace::MyClass"))
+ << ResultData(_("functionDefinedOutSideClassAndNamespace"), _("MyNamespace::MyClass"))
+ << ResultData(_("int myVariable"), _("<anonymous namespace>"))
+ << ResultData(_("myFunction"), _("<anonymous namespace>"))
+ << ResultData(_("MyEnum"), _("<anonymous namespace>"))
+ << ResultData(_("int V1"), _("<anonymous namespace>::MyEnum"))
+ << ResultData(_("int V2"), _("<anonymous namespace>::MyEnum"))
+ << ResultData(_("MyClass"), _("<anonymous namespace>"))
+ << ResultData(_("MyClass"), _("<anonymous namespace>::MyClass"))
+ << ResultData(_("functionDeclaredOnly"), _("<anonymous namespace>::MyClass"))
+ << ResultData(_("functionDefinedInClass"), _("<anonymous namespace>::MyClass"))
+ << ResultData(_("functionDefinedOutSideClass"), _("<anonymous namespace>::MyClass"))
+ << ResultData(_("functionDefinedOutSideClass"), _("<anonymous namespace>::MyClass"))
+ << ResultData(_("main()"), _(""))
+ ;
+
+ CppCurrentDocumentFilterTest test(testFile);
+ ResultDataList results = ResultData::fromFilterEntryList(test.matchesFor());
+// ResultData::printFilterEntries(results);
+ QVERIFY(!results.isEmpty());
+ QCOMPARE(expectedResults, results);
+}
diff --git a/src/plugins/cpptools/cppmodelmanager.cpp b/src/plugins/cpptools/cppmodelmanager.cpp
index 4314395916..4fb3f381e2 100644
--- a/src/plugins/cpptools/cppmodelmanager.cpp
+++ b/src/plugins/cpptools/cppmodelmanager.cpp
@@ -28,31 +28,31 @@
****************************************************************************/
#include "cppmodelmanager.h"
-#include "cpppreprocessor.h"
-#include "cpptoolsconstants.h"
+#include "abstracteditorsupport.h"
#include "builtinindexingsupport.h"
-#include "cppcompletionassist.h"
+#include "cppcodemodelsettings.h"
+#include "cppfindreferences.h"
#include "cpphighlightingsupport.h"
-#include "cpphighlightingsupportinternal.h"
#include "cppindexingsupport.h"
-#include "abstracteditorsupport.h"
+#include "cppmodelmanagersupportinternal.h"
+#include "cpppreprocessor.h"
+#include "cpptoolsconstants.h"
#include "cpptoolseditorsupport.h"
-#include "cppfindreferences.h"
+#include "cpptoolsplugin.h"
#include <coreplugin/icore.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/session.h>
-
#include <extensionsystem/pluginmanager.h>
#include <utils/qtcassert.h>
#include <QCoreApplication>
#include <QDebug>
#include <QMutexLocker>
-#include <QTimer>
#include <QTextBlock>
+#include <QTimer>
#if defined(QTCREATOR_WITH_DUMP_AST) && defined(Q_CC_GNU)
#define WITH_AST_DUMP
@@ -99,7 +99,7 @@ using namespace CppTools;
using namespace CppTools::Internal;
using namespace CPlusPlus;
-#ifdef WITH_AST_DUMP
+#ifdef QTCREATOR_WITH_DUMP_AST
#include <cxxabi.h>
@@ -173,15 +173,14 @@ static const char pp_configuration[] =
"#define __inline inline\n"
"#define __forceinline inline\n";
-void CppModelManager::updateModifiedSourceFiles()
+QStringList CppModelManager::timeStampModifiedFiles(const QList<Document::Ptr> documentsToCheck)
{
- const Snapshot snapshot = this->snapshot();
QStringList sourceFiles;
- foreach (const Document::Ptr doc, snapshot) {
+ foreach (const Document::Ptr doc, documentsToCheck) {
const QDateTime lastModified = doc->lastModified();
- if (! lastModified.isNull()) {
+ if (!lastModified.isNull()) {
QFileInfo fileInfo(doc->fileName());
if (fileInfo.exists() && fileInfo.lastModified() != lastModified)
@@ -189,56 +188,69 @@ void CppModelManager::updateModifiedSourceFiles()
}
}
- updateSourceFiles(sourceFiles);
+ return sourceFiles;
+}
+
+void CppModelManager::updateModifiedSourceFiles()
+{
+ const Snapshot snapshot = this->snapshot();
+ QList<Document::Ptr> documentsToCheck;
+ foreach (const Document::Ptr document, snapshot)
+ documentsToCheck << document;
+
+ const QStringList filesToUpdate = timeStampModifiedFiles(documentsToCheck);
+ updateSourceFiles(filesToUpdate);
}
/*!
\class CppTools::CppModelManager
- \brief The CppModelManager class keeps track of one CppCodeModel instance
- for each project and all the related CppCodeModelPart instances.
+ \brief The CppModelManager keeps tracks of the source files the code model is aware of.
- It also takes care of updating the code models when C++ files are
- modified within \QC.
+ The CppModelManager manages the source files in a Snapshot object.
+
+ The snapshot is updated in case e.g.
+ * New files are opened/edited (Editor integration)
+ * A project manager pushes updated project information (Project integration)
+ * Files are garbage collected
*/
-QMutex CppModelManager::m_modelManagerMutex;
-CppModelManager *CppModelManager::m_modelManagerInstance = 0;
+QMutex CppModelManager::m_instanceMutex;
+CppModelManager *CppModelManager::m_instance = 0;
CppModelManager *CppModelManager::instance()
{
- if (m_modelManagerInstance)
- return m_modelManagerInstance;
- QMutexLocker locker(&m_modelManagerMutex);
- if (!m_modelManagerInstance)
- m_modelManagerInstance = new CppModelManager;
- return m_modelManagerInstance;
+ if (m_instance)
+ return m_instance;
+
+ QMutexLocker locker(&m_instanceMutex);
+ if (!m_instance)
+ m_instance = new CppModelManager;
+
+ return m_instance;
}
CppModelManager::CppModelManager(QObject *parent)
: CppModelManagerInterface(parent)
- , m_enableGC(true)
- , m_completionAssistProvider(0)
- , m_highlightingFactory(0)
, m_indexingSupporter(0)
+ , m_enableGC(true)
{
m_findReferences = new CppFindReferences(this);
m_indexerEnabled = qgetenv("QTCREATOR_NO_CODE_INDEXER").isNull();
m_dirty = true;
- ProjectExplorer::ProjectExplorerPlugin *pe =
- ProjectExplorer::ProjectExplorerPlugin::instance();
+ m_delayedGcTimer = new QTimer(this);
+ m_delayedGcTimer->setSingleShot(true);
+ connect(m_delayedGcTimer, SIGNAL(timeout()), this, SLOT(GC()));
- QTC_ASSERT(pe, return);
-
- ProjectExplorer::SessionManager *session = pe->session();
- connect(session, SIGNAL(projectAdded(ProjectExplorer::Project*)),
+ QObject *sessionManager = ProjectExplorer::SessionManager::instance();
+ connect(sessionManager, SIGNAL(projectAdded(ProjectExplorer::Project*)),
this, SLOT(onProjectAdded(ProjectExplorer::Project*)));
-
- connect(session, SIGNAL(aboutToRemoveProject(ProjectExplorer::Project*)),
+ connect(sessionManager, SIGNAL(aboutToRemoveProject(ProjectExplorer::Project*)),
this, SLOT(onAboutToRemoveProject(ProjectExplorer::Project*)));
-
- connect(session, SIGNAL(aboutToUnloadSession(QString)),
+ connect(sessionManager, SIGNAL(aboutToLoadSession(QString)),
+ this, SLOT(onAboutToLoadSession()));
+ connect(sessionManager, SIGNAL(aboutToUnloadSession(QString)),
this, SLOT(onAboutToUnloadSession()));
connect(Core::ICore::instance(), SIGNAL(coreAboutToClose()),
@@ -246,19 +258,16 @@ CppModelManager::CppModelManager(QObject *parent)
qRegisterMetaType<CPlusPlus::Document::Ptr>("CPlusPlus::Document::Ptr");
- m_completionFallback = new InternalCompletionAssistProvider;
- m_completionAssistProvider = m_completionFallback;
- ExtensionSystem::PluginManager::addObject(m_completionAssistProvider);
- m_highlightingFallback = new CppHighlightingSupportInternalFactory;
- m_highlightingFactory = m_highlightingFallback;
+ m_modelManagerSupportFallback.reset(new ModelManagerSupportInternal);
+ CppToolsPlugin::instance()->codeModelSettings()->setDefaultId(
+ m_modelManagerSupportFallback->id());
+ addModelManagerSupport(m_modelManagerSupportFallback.data());
+
m_internalIndexingSupport = new BuiltinIndexingSupport;
}
CppModelManager::~CppModelManager()
{
- ExtensionSystem::PluginManager::removeObject(m_completionAssistProvider);
- delete m_completionFallback;
- delete m_highlightingFallback;
delete m_internalIndexingSupport;
}
@@ -293,7 +302,7 @@ bool CppModelManager::replaceDocument(Document::Ptr newDoc)
void CppModelManager::ensureUpdated()
{
QMutexLocker locker(&m_projectMutex);
- if (! m_dirty)
+ if (!m_dirty)
return;
m_projectFiles = internalProjectFiles();
@@ -306,10 +315,10 @@ void CppModelManager::ensureUpdated()
QStringList CppModelManager::internalProjectFiles() const
{
QStringList files;
- QMapIterator<ProjectExplorer::Project *, ProjectInfo> it(m_projects);
+ QMapIterator<ProjectExplorer::Project *, ProjectInfo> it(m_projectToProjectsInfo);
while (it.hasNext()) {
it.next();
- ProjectInfo pinfo = it.value();
+ const ProjectInfo pinfo = it.value();
foreach (const ProjectPart::Ptr &part, pinfo.projectParts()) {
foreach (const ProjectFile &file, part->files)
files += file.path;
@@ -322,10 +331,10 @@ QStringList CppModelManager::internalProjectFiles() const
QStringList CppModelManager::internalIncludePaths() const
{
QStringList includePaths;
- QMapIterator<ProjectExplorer::Project *, ProjectInfo> it(m_projects);
+ QMapIterator<ProjectExplorer::Project *, ProjectInfo> it(m_projectToProjectsInfo);
while (it.hasNext()) {
it.next();
- ProjectInfo pinfo = it.value();
+ const ProjectInfo pinfo = it.value();
foreach (const ProjectPart::Ptr &part, pinfo.projectParts())
foreach (const QString &path, part->includePaths)
includePaths.append(CppPreprocessor::cleanPath(path));
@@ -337,10 +346,10 @@ QStringList CppModelManager::internalIncludePaths() const
QStringList CppModelManager::internalFrameworkPaths() const
{
QStringList frameworkPaths;
- QMapIterator<ProjectExplorer::Project *, ProjectInfo> it(m_projects);
+ QMapIterator<ProjectExplorer::Project *, ProjectInfo> it(m_projectToProjectsInfo);
while (it.hasNext()) {
it.next();
- ProjectInfo pinfo = it.value();
+ const ProjectInfo pinfo = it.value();
foreach (const ProjectPart::Ptr &part, pinfo.projectParts())
foreach (const QString &path, part->frameworkPaths)
frameworkPaths.append(CppPreprocessor::cleanPath(path));
@@ -353,10 +362,10 @@ QByteArray CppModelManager::internalDefinedMacros() const
{
QByteArray macros;
QSet<QByteArray> alreadyIn;
- QMapIterator<ProjectExplorer::Project *, ProjectInfo> it(m_projects);
+ QMapIterator<ProjectExplorer::Project *, ProjectInfo> it(m_projectToProjectsInfo);
while (it.hasNext()) {
it.next();
- ProjectInfo pinfo = it.value();
+ const ProjectInfo pinfo = it.value();
foreach (const ProjectPart::Ptr &part, pinfo.projectParts()) {
const QList<QByteArray> defs = part->defines.split('\n');
foreach (const QByteArray &def, defs) {
@@ -375,9 +384,9 @@ QByteArray CppModelManager::internalDefinedMacros() const
void CppModelManager::dumpModelManagerConfiguration()
{
// Tons of debug output...
- qDebug()<<"========= CppModelManager::dumpModelManagerConfiguration ======";
- foreach (const ProjectInfo &pinfo, m_projects) {
- qDebug()<<" for project:"<< pinfo.project().data()->document()->fileName();
+ qDebug() << "========= CppModelManager::dumpModelManagerConfiguration ======";
+ foreach (const ProjectInfo &pinfo, m_projectToProjectsInfo) {
+ qDebug() << " for project:"<< pinfo.project().data()->projectFilePath();
foreach (const ProjectPart::Ptr &part, pinfo.projectParts()) {
qDebug() << "=== part ===";
const char* cVersion;
@@ -400,7 +409,7 @@ void CppModelManager::dumpModelManagerConfiguration()
cxxExtensions << QLatin1String("MicrosoftExtensions");
if (part->cxxExtensions & ProjectPart::BorlandExtensions)
cxxExtensions << QLatin1String("BorlandExtensions");
- if (part->cxxExtensions & ProjectPart::OpenMP)
+ if (part->cxxExtensions & ProjectPart::OpenMPExtensions)
cxxExtensions << QLatin1String("OpenMP");
qDebug() << "cVersion:" << cVersion;
@@ -425,35 +434,64 @@ void CppModelManager::dumpModelManagerConfiguration()
qDebug() << inc;
qDebug() << "=== Merged defined macros ===";
qDebug() << m_definedMacros;
- qDebug()<<"========= End of dump ======";
+ qDebug() << "========= End of dump ======";
}
-void CppModelManager::addEditorSupport(AbstractEditorSupport *editorSupport)
+void CppModelManager::addExtraEditorSupport(AbstractEditorSupport *editorSupport)
{
- m_addtionalEditorSupport.insert(editorSupport);
+ m_extraEditorSupports.insert(editorSupport);
}
-void CppModelManager::removeEditorSupport(AbstractEditorSupport *editorSupport)
+void CppModelManager::removeExtraEditorSupport(AbstractEditorSupport *editorSupport)
{
- m_addtionalEditorSupport.remove(editorSupport);
+ m_extraEditorSupports.remove(editorSupport);
}
/// \brief Returns the \c CppEditorSupport for the given text editor. It will
/// create one when none exists yet.
-CppEditorSupport *CppModelManager::cppEditorSupport(TextEditor::BaseTextEditor *editor)
+CppEditorSupport *CppModelManager::cppEditorSupport(TextEditor::BaseTextEditor *textEditor)
{
- Q_ASSERT(editor);
+ Q_ASSERT(textEditor);
- QMutexLocker locker(&m_editorSupportMutex);
+ QMutexLocker locker(&m_cppEditorSupportsMutex);
- CppEditorSupport *editorSupport = m_editorSupport.value(editor, 0);
+ CppEditorSupport *editorSupport = m_cppEditorSupports.value(textEditor, 0);
if (!editorSupport) {
- editorSupport = new CppEditorSupport(this, editor);
- m_editorSupport.insert(editor, editorSupport);
+ editorSupport = new CppEditorSupport(this, textEditor);
+ m_cppEditorSupports.insert(textEditor, editorSupport);
}
return editorSupport;
}
+/// \brief Removes the CppEditorSupport for the closed editor.
+void CppModelManager::deleteCppEditorSupport(TextEditor::BaseTextEditor *textEditor)
+{
+ static short numberOfClosedEditors = 0;
+
+ QTC_ASSERT(textEditor, return);
+
+ if (!isCppEditor(textEditor))
+ return;
+
+ CppEditorSupport *editorSupport;
+ int numberOfOpenEditors = 0;
+
+ { // Only lock the operations on m_cppEditorSupport
+ QMutexLocker locker(&m_cppEditorSupportsMutex);
+ editorSupport = m_cppEditorSupports.value(textEditor, 0);
+ m_cppEditorSupports.remove(textEditor);
+ numberOfOpenEditors = m_cppEditorSupports.size();
+ }
+
+ delete editorSupport;
+
+ ++numberOfClosedEditors;
+ if (numberOfOpenEditors == 0 || numberOfClosedEditors == 5) {
+ numberOfClosedEditors = 0;
+ delayedGC();
+ }
+}
+
QList<int> CppModelManager::references(CPlusPlus::Symbol *symbol, const LookupContext &context)
{
return m_findReferences->references(symbol, context);
@@ -465,7 +503,8 @@ void CppModelManager::findUsages(CPlusPlus::Symbol *symbol, const CPlusPlus::Loo
m_findReferences->findUsages(symbol, context);
}
-void CppModelManager::renameUsages(CPlusPlus::Symbol *symbol, const CPlusPlus::LookupContext &context,
+void CppModelManager::renameUsages(CPlusPlus::Symbol *symbol,
+ const CPlusPlus::LookupContext &context,
const QString &replacement)
{
if (symbol->identifier())
@@ -490,29 +529,29 @@ void CppModelManager::replaceSnapshot(const CPlusPlus::Snapshot &newSnapshot)
CppModelManager::WorkingCopy CppModelManager::buildWorkingCopyList()
{
- QList<CppEditorSupport *> supporters;
+ QList<CppEditorSupport *> cppEditorSupports;
{
- QMutexLocker locker(&m_editorSupportMutex);
- supporters = m_editorSupport.values();
+ QMutexLocker locker(&m_cppEditorSupportsMutex);
+ cppEditorSupports = m_cppEditorSupports.values();
}
WorkingCopy workingCopy;
- foreach (const CppEditorSupport *editorSupport, supporters) {
+ foreach (const CppEditorSupport *editorSupport, cppEditorSupports) {
workingCopy.insert(editorSupport->fileName(), editorSupport->contents(),
editorSupport->editorRevision());
}
- QSetIterator<AbstractEditorSupport *> jt(m_addtionalEditorSupport);
- while (jt.hasNext()) {
- AbstractEditorSupport *es = jt.next();
- workingCopy.insert(es->fileName(), QString::fromUtf8(es->contents()));
+ QSetIterator<AbstractEditorSupport *> it(m_extraEditorSupports);
+ while (it.hasNext()) {
+ AbstractEditorSupport *es = it.next();
+ workingCopy.insert(es->fileName(), es->contents());
}
- // add the project configuration file
- QByteArray conf(pp_configuration);
+ // Add the project configuration file
+ QByteArray conf = QByteArray::fromRawData(pp_configuration, qstrlen(pp_configuration));
conf += definedMacros();
- workingCopy.insert(configurationFileName(), QString::fromLocal8Bit(conf));
+ workingCopy.insert(configurationFileName(), conf);
return workingCopy;
}
@@ -536,79 +575,200 @@ QFuture<void> CppModelManager::updateSourceFiles(const QStringList &sourceFiles,
QList<CppModelManager::ProjectInfo> CppModelManager::projectInfos() const
{
QMutexLocker locker(&m_projectMutex);
-
- return m_projects.values();
+ return m_projectToProjectsInfo.values();
}
CppModelManager::ProjectInfo CppModelManager::projectInfo(ProjectExplorer::Project *project) const
{
QMutexLocker locker(&m_projectMutex);
+ return m_projectToProjectsInfo.value(project, ProjectInfo(project));
+}
+
+/// \brief Remove all files and their includes (recursively) of given ProjectInfo from the snapshot.
+void CppModelManager::removeProjectInfoFilesAndIncludesFromSnapshot(const ProjectInfo &projectInfo)
+{
+ if (!projectInfo.isValid())
+ return;
+
+ QMutexLocker snapshotLocker(&m_snapshotMutex);
+ foreach (const ProjectPart::Ptr &projectPart, projectInfo.projectParts()) {
+ foreach (const ProjectFile &cxxFile, projectPart->files) {
+ foreach (const QString &fileName, m_snapshot.allIncludesForDocument(cxxFile.path))
+ m_snapshot.remove(fileName);
+ m_snapshot.remove(cxxFile.path);
+ }
+ }
+}
- return m_projects.value(project, ProjectInfo(project));
+/// \brief Remove all given files from the snapshot.
+void CppModelManager::removeFilesFromSnapshot(const QSet<QString> &filesToRemove)
+{
+ QMutexLocker snapshotLocker(&m_snapshotMutex);
+ QSetIterator<QString> i(filesToRemove);
+ while (i.hasNext())
+ m_snapshot.remove(i.next());
}
-QFuture<void> CppModelManager::updateProjectInfo(const ProjectInfo &pinfo)
+class ProjectInfoComparer
{
- { // only hold the mutex for a limited scope, so the dumping afterwards can aquire it without deadlocking.
- QMutexLocker locker(&m_projectMutex);
+public:
+ ProjectInfoComparer(const CppModelManager::ProjectInfo &oldProjectInfo,
+ const CppModelManager::ProjectInfo &newProjectInfo)
+ : m_old(oldProjectInfo)
+ , m_oldSourceFiles(oldProjectInfo.sourceFiles().toSet())
+ , m_new(newProjectInfo)
+ , m_newSourceFiles(newProjectInfo.sourceFiles().toSet())
+ {}
+
+ bool definesChanged() const
+ {
+ return m_new.defines() != m_old.defines();
+ }
+
+ bool configurationChanged() const
+ {
+ return definesChanged()
+ || m_new.includePaths() != m_old.includePaths()
+ || m_new.frameworkPaths() != m_old.frameworkPaths();
+ }
- if (! pinfo.isValid())
- return QFuture<void>();
+ bool nothingChanged() const
+ {
+ return !configurationChanged() && m_new.sourceFiles() == m_old.sourceFiles();
+ }
- ProjectExplorer::Project *project = pinfo.project().data();
- ProjectInfo oldProjectInfo = m_projects.value(project);
+ QSet<QString> addedFiles() const
+ {
+ QSet<QString> addedFilesSet = m_newSourceFiles;
+ addedFilesSet.subtract(m_oldSourceFiles);
+ return addedFilesSet;
+ }
+
+ QSet<QString> removedFiles() const
+ {
+ QSet<QString> removedFilesSet = m_oldSourceFiles;
+ removedFilesSet.subtract(m_newSourceFiles);
+ return removedFilesSet;
+ }
+
+ /// Returns a list of common files that have a changed timestamp.
+ QSet<QString> timeStampModifiedFiles(const Snapshot &snapshot) const
+ {
+ QSet<QString> commonSourceFiles = m_newSourceFiles;
+ commonSourceFiles.intersect(m_oldSourceFiles);
+
+ QList<Document::Ptr> documentsToCheck;
+ QSetIterator<QString> i(commonSourceFiles);
+ while (i.hasNext()) {
+ const QString file = i.next();
+ if (Document::Ptr document = snapshot.document(file))
+ documentsToCheck << document;
+ }
+
+ return CppModelManager::timeStampModifiedFiles(documentsToCheck).toSet();
+ }
+
+private:
+ const CppModelManager::ProjectInfo &m_old;
+ const QSet<QString> m_oldSourceFiles;
+
+ const CppModelManager::ProjectInfo &m_new;
+ const QSet<QString> m_newSourceFiles;
+};
+
+QFuture<void> CppModelManager::updateProjectInfo(const ProjectInfo &newProjectInfo)
+{
+ if (!newProjectInfo.isValid())
+ return QFuture<void>();
+
+ QStringList filesToReindex;
+ bool filesRemoved = false;
+
+ { // Only hold the mutex for a limited scope, so the dumping afterwards does not deadlock.
+ QMutexLocker projectLocker(&m_projectMutex);
+
+ ProjectExplorer::Project *project = newProjectInfo.project().data();
+ const QStringList newSourceFiles = newProjectInfo.sourceFiles();
+
+ // Check if we can avoid a full reindexing
+ ProjectInfo oldProjectInfo = m_projectToProjectsInfo.value(project);
if (oldProjectInfo.isValid()) {
- if (pinfo.defines() == oldProjectInfo.defines()
- && pinfo.includePaths() == oldProjectInfo.includePaths()
- && pinfo.frameworkPaths() == oldProjectInfo.frameworkPaths()
- && pinfo.sourceFiles() == oldProjectInfo.sourceFiles()) {
+ ProjectInfoComparer comparer(oldProjectInfo, newProjectInfo);
+ if (comparer.nothingChanged())
return QFuture<void>();
- }
- foreach (const ProjectPart::Ptr &projectPart, oldProjectInfo.projectParts()) {
- foreach (const ProjectFile &cxxFile, projectPart->files) {
- foreach (const QString &fileName,
- m_snapshot.allIncludesForDocument(cxxFile.path)) {
- m_snapshot.remove(fileName);
- }
- m_snapshot.remove(cxxFile.path);
+ // If the project configuration changed, do a full reindexing
+ if (comparer.configurationChanged()) {
+ removeProjectInfoFilesAndIncludesFromSnapshot(oldProjectInfo);
+ filesToReindex << newSourceFiles;
+
+ // The "configuration file" includes all defines and therefore should be updated
+ if (comparer.definesChanged()) {
+ QMutexLocker snapshotLocker(&m_snapshotMutex);
+ m_snapshot.remove(configurationFileName());
}
+
+ // Otherwise check for added and modified files
+ } else {
+ const QSet<QString> addedFiles = comparer.addedFiles();
+ filesToReindex << addedFiles.toList();
+
+ const QSet<QString> modifiedFiles = comparer.timeStampModifiedFiles(snapshot());
+ filesToReindex << modifiedFiles.toList();
}
+
+ // Announce and purge the removed files from the snapshot
+ const QSet<QString> removedFiles = comparer.removedFiles();
+ if (!removedFiles.isEmpty()) {
+ filesRemoved = true;
+ emit aboutToRemoveFiles(removedFiles.toList());
+ removeFilesFromSnapshot(removedFiles);
+ }
+
+ // A new project was opened/created, do a full indexing
+ } else {
+ filesToReindex << newSourceFiles;
}
- m_snapshot.remove(configurationFileName());
- m_projects.insert(project, pinfo);
+ // Update Project/ProjectInfo and File/ProjectPart table
m_dirty = true;
-
- m_srcToProjectPart.clear();
- foreach (const ProjectInfo &projectInfo, m_projects) {
+ m_projectToProjectsInfo.insert(project, newProjectInfo);
+ m_fileToProjectParts.clear();
+ foreach (const ProjectInfo &projectInfo, m_projectToProjectsInfo) {
foreach (const ProjectPart::Ptr &projectPart, projectInfo.projectParts()) {
foreach (const ProjectFile &cxxFile, projectPart->files) {
- m_srcToProjectPart[cxxFile.path].append(projectPart);
+ m_fileToProjectParts[cxxFile.path].append(projectPart);
}
}
}
- }
+ } // Mutex scope
+
+ // If requested, dump everything we got
if (!qgetenv("QTCREATOR_DUMP_PROJECT_INFO").isEmpty())
dumpModelManagerConfiguration();
- emit projectPartsUpdated(pinfo.project().data());
+ // Remove files from snapshot that are not reachable any more
+ if (filesRemoved)
+ GC();
+
+ emit projectPartsUpdated(newProjectInfo.project().data());
- return updateSourceFiles(pinfo.sourceFiles(), ForcedProgressNotification);
+ // Trigger reindexing
+ return updateSourceFiles(filesToReindex, ForcedProgressNotification);
}
QList<ProjectPart::Ptr> CppModelManager::projectPart(const QString &fileName) const
{
- QList<ProjectPart::Ptr> parts = m_srcToProjectPart.value(fileName);
+ QList<ProjectPart::Ptr> parts = m_fileToProjectParts.value(fileName);
if (!parts.isEmpty())
return parts;
DependencyTable table;
table.build(snapshot());
- QStringList deps = table.filesDependingOn(fileName);
+ const QStringList deps = table.filesDependingOn(fileName);
foreach (const QString &dep, deps) {
- parts = m_srcToProjectPart.value(dep);
+ parts = m_fileToProjectParts.value(dep);
if (!parts.isEmpty())
return parts;
}
@@ -616,23 +776,19 @@ QList<ProjectPart::Ptr> CppModelManager::projectPart(const QString &fileName) co
return parts;
}
-/// \brief Removes the CppEditorSupport for the closed editor.
-void CppModelManager::deleteEditorSupport(TextEditor::BaseTextEditor *textEditor)
+ProjectPart::Ptr CppModelManager::fallbackProjectPart() const
{
- QTC_ASSERT(textEditor, return);
+ ProjectPart::Ptr part(new ProjectPart);
- if (!isCppEditor(textEditor))
- return;
+ part->defines = m_definedMacros;
+ part->includePaths = m_includePaths;
+ part->frameworkPaths = m_frameworkPaths;
+ part->cVersion = ProjectPart::C11;
+ part->cxxVersion = ProjectPart::CXX11;
+ part->cxxExtensions = ProjectPart::AllExtensions;
+ part->qtVersion = ProjectPart::Qt5;
- CppEditorSupport *editorSupport;
-
- { // only lock the operations on m_editorSupport
- QMutexLocker locker(&m_editorSupportMutex);
- editorSupport = m_editorSupport.value(textEditor, 0);
- m_editorSupport.remove(textEditor);
- }
-
- delete editorSupport;
+ return part;
}
bool CppModelManager::isCppEditor(Core::IEditor *editor) const
@@ -652,28 +808,37 @@ void CppModelManager::onProjectAdded(ProjectExplorer::Project *)
m_dirty = true;
}
+void CppModelManager::delayedGC()
+{
+ m_delayedGcTimer->start(500);
+}
+
void CppModelManager::onAboutToRemoveProject(ProjectExplorer::Project *project)
{
do {
QMutexLocker locker(&m_projectMutex);
m_dirty = true;
- m_projects.remove(project);
+ m_projectToProjectsInfo.remove(project);
} while (0);
+ delayedGC();
+}
+
+void CppModelManager::onAboutToLoadSession()
+{
+ if (m_delayedGcTimer->isActive())
+ m_delayedGcTimer->stop();
GC();
}
void CppModelManager::onAboutToUnloadSession()
{
- if (Core::ProgressManager *pm = Core::ICore::progressManager())
- pm->cancelTasks(QLatin1String(CppTools::Constants::TASK_INDEX));
+ Core::ProgressManager::cancelTasks(CppTools::Constants::TASK_INDEX);
do {
QMutexLocker locker(&m_projectMutex);
- m_projects.clear();
+ m_projectToProjectsInfo.clear();
m_dirty = true;
} while (0);
-
- GC();
}
void CppModelManager::onCoreAboutToClose()
@@ -686,38 +851,58 @@ void CppModelManager::GC()
if (!m_enableGC)
return;
- Snapshot currentSnapshot = snapshot();
- QSet<QString> processed;
- QStringList todo = projectFiles();
+ // Collect files of CppEditorSupport and AbstractEditorSupport.
+ QStringList filesInEditorSupports;
+ QList<CppEditorSupport *> cppEditorSupports;
+ {
+ QMutexLocker locker(&m_cppEditorSupportsMutex);
+ cppEditorSupports = m_cppEditorSupports.values();
+ }
+ foreach (const CppEditorSupport *cppEditorSupport, cppEditorSupports)
+ filesInEditorSupports << cppEditorSupport->fileName();
+
+ QSetIterator<AbstractEditorSupport *> jt(m_extraEditorSupports);
+ while (jt.hasNext()) {
+ AbstractEditorSupport *abstractEditorSupport = jt.next();
+ filesInEditorSupports << abstractEditorSupport->fileName();
+ }
- while (! todo.isEmpty()) {
- QString fn = todo.last();
+ Snapshot currentSnapshot = snapshot();
+ QSet<QString> reachableFiles;
+ // The configuration file is part of the project files, which is just fine.
+ // If single files are open, without any project, then there is no need to
+ // keep the configuration file around.
+ QStringList todo = filesInEditorSupports + projectFiles();
+
+ // Collect all files that are reachable from the project files
+ while (!todo.isEmpty()) {
+ const QString file = todo.last();
todo.removeLast();
- if (processed.contains(fn))
+ if (reachableFiles.contains(file))
continue;
+ reachableFiles.insert(file);
- processed.insert(fn);
-
- if (Document::Ptr doc = currentSnapshot.document(fn))
+ if (Document::Ptr doc = currentSnapshot.document(file))
todo += doc->includedFiles();
}
- QStringList removedFiles;
-
+ // Find out the files in the current snapshot that are not reachable from the project files
+ QStringList notReachableFiles;
Snapshot newSnapshot;
for (Snapshot::const_iterator it = currentSnapshot.begin(); it != currentSnapshot.end(); ++it) {
const QString fileName = it.key();
- if (processed.contains(fileName))
+ if (reachableFiles.contains(fileName))
newSnapshot.insert(it.value());
else
- removedFiles.append(fileName);
+ notReachableFiles.append(fileName);
}
- emit aboutToRemoveFiles(removedFiles);
-
+ // Announce removing files and replace the snapshot
+ emit aboutToRemoveFiles(notReachableFiles);
replaceSnapshot(newSnapshot);
+ emit gcFinished();
}
void CppModelManager::finishedRefreshingSourceFiles(const QStringList &files)
@@ -725,38 +910,37 @@ void CppModelManager::finishedRefreshingSourceFiles(const QStringList &files)
emit sourceFilesRefreshed(files);
}
-CppCompletionSupport *CppModelManager::completionSupport(Core::IEditor *editor) const
+void CppModelManager::addModelManagerSupport(ModelManagerSupport *modelManagerSupport)
{
- if (TextEditor::ITextEditor *textEditor = qobject_cast<TextEditor::ITextEditor *>(editor))
- return m_completionAssistProvider->completionSupport(textEditor);
- else
- return 0;
+ Q_ASSERT(modelManagerSupport);
+ m_idTocodeModelSupporter[modelManagerSupport->id()] = modelManagerSupport;
+ QSharedPointer<CppCodeModelSettings> cms = CppToolsPlugin::instance()->codeModelSettings();
+ cms->setModelManagerSupports(m_idTocodeModelSupporter.values());
}
-void CppModelManager::setCppCompletionAssistProvider(CppCompletionAssistProvider *completionAssistProvider)
+ModelManagerSupport *CppModelManager::modelManagerSupportForMimeType(const QString &mimeType) const
{
- ExtensionSystem::PluginManager::removeObject(m_completionAssistProvider);
- if (completionAssistProvider)
- m_completionAssistProvider = completionAssistProvider;
- else
- m_completionAssistProvider = m_completionFallback;
- ExtensionSystem::PluginManager::addObject(m_completionAssistProvider);
+ QSharedPointer<CppCodeModelSettings> cms = CppToolsPlugin::instance()->codeModelSettings();
+ const QString &id = cms->modelManagerSupportId(mimeType);
+ return m_idTocodeModelSupporter.value(id, m_modelManagerSupportFallback.data());
}
-CppHighlightingSupport *CppModelManager::highlightingSupport(Core::IEditor *editor) const
+CppCompletionAssistProvider *CppModelManager::completionAssistProvider(Core::IEditor *editor) const
{
- if (TextEditor::ITextEditor *textEditor = qobject_cast<TextEditor::ITextEditor *>(editor))
- return m_highlightingFactory->highlightingSupport(textEditor);
- else
- return 0;
+ ModelManagerSupport *cms = modelManagerSupportForMimeType(editor->document()->mimeType());
+
+ return cms->completionAssistProvider();
}
-void CppModelManager::setHighlightingSupportFactory(CppHighlightingSupportFactory *highlightingFactory)
+CppHighlightingSupport *CppModelManager::highlightingSupport(Core::IEditor *editor) const
{
- if (highlightingFactory)
- m_highlightingFactory = highlightingFactory;
- else
- m_highlightingFactory = m_highlightingFallback;
+ TextEditor::ITextEditor *textEditor = qobject_cast<TextEditor::ITextEditor *>(editor);
+ if (!textEditor)
+ return 0;
+
+ ModelManagerSupport *cms = modelManagerSupportForMimeType(editor->document()->mimeType());
+
+ return cms->highlightingSupport(textEditor);
}
void CppModelManager::setIndexingSupport(CppIndexingSupport *indexingSupport)
@@ -770,19 +954,38 @@ CppIndexingSupport *CppModelManager::indexingSupport()
return m_indexingSupporter ? m_indexingSupporter : m_internalIndexingSupport;
}
-void CppModelManager::setExtraDiagnostics(const QString &fileName, const QString &kind,
+void CppModelManager::setExtraDiagnostics(const QString &fileName,
+ const QString &kind,
const QList<Document::DiagnosticMessage> &diagnostics)
{
- QList<CppEditorSupport *> supporters;
+ QList<CppEditorSupport *> cppEditorSupports;
+
+ {
+ QMutexLocker locker(&m_cppEditorSupportsMutex);
+ cppEditorSupports = m_cppEditorSupports.values();
+ }
+
+ foreach (CppEditorSupport *editorSupport, cppEditorSupports) {
+ if (editorSupport->fileName() == fileName) {
+ editorSupport->setExtraDiagnostics(kind, diagnostics);
+ break;
+ }
+ }
+}
+
+void CppModelManager::setIfdefedOutBlocks(const QString &fileName,
+ const QList<TextEditor::BlockRange> &ifdeffedOutBlocks)
+{
+ QList<CppEditorSupport *> cppEditorSupports;
{
- QMutexLocker locker(&m_editorSupportMutex);
- supporters = m_editorSupport.values();
+ QMutexLocker locker(&m_cppEditorSupportsMutex);
+ cppEditorSupports = m_cppEditorSupports.values();
}
- foreach (CppEditorSupport *supporter, supporters) {
- if (supporter->fileName() == fileName) {
- supporter->setExtraDiagnostics(kind, diagnostics);
+ foreach (CppEditorSupport *editorSupport, cppEditorSupports) {
+ if (editorSupport->fileName() == fileName) {
+ editorSupport->setIfdefedOutBlocks(ifdeffedOutBlocks);
break;
}
}
diff --git a/src/plugins/cpptools/cppmodelmanager.h b/src/plugins/cpptools/cppmodelmanager.h
index 5758cdb4b3..2ec1423e3a 100644
--- a/src/plugins/cpptools/cppmodelmanager.h
+++ b/src/plugins/cpptools/cppmodelmanager.h
@@ -31,6 +31,7 @@
#define CPPMODELMANAGER_H
#include "cpptools_global.h"
+
#include "cppmodelmanagerinterface.h"
#include <projectexplorer/project.h>
@@ -38,12 +39,10 @@
#include <QHash>
#include <QMutex>
+#include <QTimer>
namespace Core { class IEditor; }
-
-namespace TextEditor {
-class BaseTextEditorWidget;
-} // namespace TextEditor
+namespace TextEditor { class BaseTextEditorWidget; }
namespace CppTools {
@@ -73,22 +72,22 @@ public:
virtual QList<ProjectInfo> projectInfos() const;
virtual ProjectInfo projectInfo(ProjectExplorer::Project *project) const;
- virtual QFuture<void> updateProjectInfo(const ProjectInfo &pinfo);
+ virtual QFuture<void> updateProjectInfo(const ProjectInfo &newProjectInfo);
virtual QList<CppTools::ProjectPart::Ptr> projectPart(const QString &fileName) const;
+ virtual ProjectPart::Ptr fallbackProjectPart() const;
virtual CPlusPlus::Snapshot snapshot() const;
virtual Document::Ptr document(const QString &fileName) const;
bool replaceDocument(Document::Ptr newDoc);
- virtual void GC();
-
- virtual bool isCppEditor(Core::IEditor *editor) const;
void emitDocumentUpdated(CPlusPlus::Document::Ptr doc);
- virtual void addEditorSupport(AbstractEditorSupport *editorSupport);
- virtual void removeEditorSupport(AbstractEditorSupport *editorSupport);
- virtual CppEditorSupport *cppEditorSupport(TextEditor::BaseTextEditor *editor);
- virtual void deleteEditorSupport(TextEditor::BaseTextEditor *textEditor);
+ virtual bool isCppEditor(Core::IEditor *editor) const;
+
+ virtual void addExtraEditorSupport(AbstractEditorSupport *editorSupport);
+ virtual void removeExtraEditorSupport(AbstractEditorSupport *editorSupport);
+ virtual CppEditorSupport *cppEditorSupport(TextEditor::BaseTextEditor *textEditor);
+ virtual void deleteCppEditorSupport(TextEditor::BaseTextEditor *textEditor);
virtual QList<int> references(CPlusPlus::Symbol *symbol, const CPlusPlus::LookupContext &context);
@@ -101,14 +100,15 @@ public:
virtual void setExtraDiagnostics(const QString &fileName, const QString &key,
const QList<Document::DiagnosticMessage> &diagnostics);
+ virtual void setIfdefedOutBlocks(const QString &fileName,
+ const QList<TextEditor::BlockRange> &ifdeffedOutBlocks);
void finishedRefreshingSourceFiles(const QStringList &files);
- virtual CppCompletionSupport *completionSupport(Core::IEditor *editor) const;
- virtual void setCppCompletionAssistProvider(CppCompletionAssistProvider *completionAssistProvider);
-
+ virtual void addModelManagerSupport(ModelManagerSupport *modelManagerSupport);
+ virtual ModelManagerSupport *modelManagerSupportForMimeType(const QString &mimeType) const;
+ virtual CppCompletionAssistProvider *completionAssistProvider(Core::IEditor *editor) const;
virtual CppHighlightingSupport *highlightingSupport(Core::IEditor *editor) const;
- virtual void setHighlightingSupportFactory(CppHighlightingSupportFactory *highlightingFactory);
virtual void setIndexingSupport(CppIndexingSupport *indexingSupport);
virtual CppIndexingSupport *indexingSupport();
@@ -143,21 +143,29 @@ public:
return m_definedMacros;
}
-Q_SIGNALS:
- void aboutToRemoveFiles(const QStringList &files);
+ static QStringList timeStampModifiedFiles(const QList<Document::Ptr> documentsToCheck);
+
+signals:
+ void gcFinished(); // Needed for tests.
-public Q_SLOTS:
+public slots:
virtual void updateModifiedSourceFiles();
+ virtual void GC();
-private Q_SLOTS:
- // this should be executed in the GUI thread.
- void onAboutToRemoveProject(ProjectExplorer::Project *project);
+private slots:
+ // This should be executed in the GUI thread.
+ void onAboutToLoadSession();
void onAboutToUnloadSession();
- void onCoreAboutToClose();
void onProjectAdded(ProjectExplorer::Project *project);
+ void onAboutToRemoveProject(ProjectExplorer::Project *project);
+ void onCoreAboutToClose();
private:
+ void delayedGC();
void replaceSnapshot(const CPlusPlus::Snapshot &newSnapshot);
+ void removeFilesFromSnapshot(const QSet<QString> &removedFiles);
+ void removeProjectInfoFilesAndIncludesFromSnapshot(const ProjectInfo &projectInfo);
+
WorkingCopy buildWorkingCopyList();
void ensureUpdated();
@@ -169,42 +177,43 @@ private:
void dumpModelManagerConfiguration();
private:
- static QMutex m_modelManagerMutex;
- static CppModelManager *m_modelManagerInstance;
+ static QMutex m_instanceMutex;
+ static CppModelManager *m_instance;
private:
- // snapshot
+ // Snapshot
mutable QMutex m_snapshotMutex;
CPlusPlus::Snapshot m_snapshot;
- bool m_enableGC;
-
- // project integration
+ // Project integration
mutable QMutex m_projectMutex;
- QMap<ProjectExplorer::Project *, ProjectInfo> m_projects;
- QMap<QString, QList<CppTools::ProjectPart::Ptr> > m_srcToProjectPart;
- // cached/calculated from the projects and/or their project-parts
+ QMap<ProjectExplorer::Project *, ProjectInfo> m_projectToProjectsInfo;
+ QMap<QString, QList<CppTools::ProjectPart::Ptr> > m_fileToProjectParts;
+ // The members below are cached/(re)calculated from the projects and/or their project parts
bool m_dirty;
QStringList m_projectFiles;
QStringList m_includePaths;
QStringList m_frameworkPaths;
QByteArray m_definedMacros;
- // editor integration
- mutable QMutex m_editorSupportMutex;
- QMap<TextEditor::BaseTextEditor *, CppEditorSupport *> m_editorSupport;
-
- QSet<AbstractEditorSupport *> m_addtionalEditorSupport;
+ // Editor integration
+ mutable QMutex m_cppEditorSupportsMutex;
+ QMap<TextEditor::BaseTextEditor *, CppEditorSupport *> m_cppEditorSupports;
+ QSet<AbstractEditorSupport *> m_extraEditorSupports;
- CppFindReferences *m_findReferences;
- bool m_indexerEnabled;
+ // Completion & highlighting
+ QHash<QString, ModelManagerSupport *> m_idTocodeModelSupporter;
+ QScopedPointer<ModelManagerSupport> m_modelManagerSupportFallback;
- CppCompletionAssistProvider *m_completionAssistProvider;
- CppCompletionAssistProvider *m_completionFallback;
- CppHighlightingSupportFactory *m_highlightingFactory;
- CppHighlightingSupportFactory *m_highlightingFallback;
+ // Indexing
CppIndexingSupport *m_indexingSupporter;
CppIndexingSupport *m_internalIndexingSupport;
+ bool m_indexerEnabled;
+
+ CppFindReferences *m_findReferences;
+
+ bool m_enableGC;
+ QTimer *m_delayedGcTimer;
};
} // namespace Internal
diff --git a/src/plugins/cpptools/cppmodelmanager_test.cpp b/src/plugins/cpptools/cppmodelmanager_test.cpp
index 4971974a25..8f4f588390 100644
--- a/src/plugins/cpptools/cppmodelmanager_test.cpp
+++ b/src/plugins/cpptools/cppmodelmanager_test.cpp
@@ -32,74 +32,51 @@
#include "cpppreprocessor.h"
#include "modelmanagertesthelper.h"
+#include <coreplugin/editormanager/editormanager.h>
+#include <coreplugin/testdatadir.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/session.h>
+#include <utils/hostosinfo.h>
#include <QDebug>
#include <QFileInfo>
#include <QtTest>
+#if QT_VERSION >= 0x050000
+#define MSKIP_SINGLE(x) QSKIP(x)
+#else
+#define MSKIP_SINGLE(x) QSKIP(x, SkipSingle)
+#endif
+
using namespace CppTools::Internal;
+using namespace ProjectExplorer;
typedef CPlusPlus::Document Document;
typedef CppTools::CppModelManagerInterface::ProjectInfo ProjectInfo;
typedef CppTools::ProjectPart ProjectPart;
typedef CppTools::ProjectFile ProjectFile;
-typedef ProjectExplorer::Project Project;
+
+Q_DECLARE_METATYPE(QList<ProjectFile>)
namespace {
-class TestDataDirectory
+class MyTestDataDir : public Core::Internal::Tests::TestDataDir
{
public:
- TestDataDirectory(const QString &testDataDirectory)
- : m_testDataDirectory(QLatin1String(SRCDIR "/../../../tests/cppmodelmanager/")
- + testDataDirectory)
- {
- QFileInfo testDataDir(m_testDataDirectory);
- QVERIFY(testDataDir.exists());
- QVERIFY(testDataDir.isDir());
- }
-
+ MyTestDataDir(const QString &dir)
+ : TestDataDir(QLatin1String(SRCDIR "/../../../tests/cppmodelmanager/") + dir)
+ {}
QString includeDir(bool cleaned = true) const
- {
- return testDataDir(QLatin1String("include"), cleaned);
- }
+ { return directory(QLatin1String("include"), cleaned); }
QString frameworksDir(bool cleaned = true) const
- {
- return testDataDir(QLatin1String("frameworks"), cleaned);
- }
+ { return directory(QLatin1String("frameworks"), cleaned); }
QString fileFromSourcesDir(const QString &fileName) const
- {
- return testDataDir(QLatin1String("sources")) + fileName;
- }
-
- /// File from the test data directory (top leve)
- QString file(const QString &fileName) const
- {
- return testDataDir(QString()) + fileName;
- }
-
-private:
- QString testDataDir(const QString& subdir, bool cleaned = true) const
- {
- QString path = m_testDataDirectory;
- if (!subdir.isEmpty())
- path += QLatin1String("/") + subdir;
- if (cleaned)
- return CppPreprocessor::cleanPath(path);
- else
- return path;
- }
-
-private:
- const QString m_testDataDirectory;
+ { return directory(QLatin1String("sources")) + fileName; }
};
-
// TODO: When possible, use this helper class in all tests
class ProjectCreator
{
@@ -111,7 +88,7 @@ public:
/// 'files' is expected to be a list of file names that reside in 'dir'.
void create(const QString &name, const QString &dir, const QStringList files)
{
- const TestDataDirectory projectDir(dir);
+ const MyTestDataDir projectDir(dir);
foreach (const QString &file, files)
projectFiles << projectDir.file(file);
@@ -142,7 +119,7 @@ class ExampleProjectConfigurator
{
public:
ExampleProjectConfigurator(const QString &projectFile,
- ProjectExplorer::ProjectExplorerPlugin *projectExplorer)
+ ProjectExplorerPlugin *projectExplorer)
{
const QString projectUserFile = projectFile + QLatin1String(".user");
QVERIFY(!QFileInfo(projectUserFile).exists());
@@ -165,16 +142,62 @@ public:
QVERIFY(QFile::remove(m_fileToRemove));
}
- ProjectExplorer::Project *project() const
+ Project *project() const
{
return m_project;
}
private:
- ProjectExplorer::Project *m_project;
+ Project *m_project;
QString m_fileToRemove;
};
+/// Changes a file on the disk and restores its original contents on destruction
+class FileChangerAndRestorer
+{
+public:
+ FileChangerAndRestorer(const QString &filePath)
+ : m_filePath(filePath)
+ {
+ }
+
+ ~FileChangerAndRestorer()
+ {
+ restoreContents();
+ }
+
+ /// Saves the contents also internally so it can be restored on destruction
+ bool readContents(QByteArray *contents)
+ {
+ Utils::FileReader fileReader;
+ const bool isFetchOk = fileReader.fetch(m_filePath);
+ if (isFetchOk) {
+ m_originalFileContents = fileReader.data();
+ if (contents)
+ *contents = m_originalFileContents;
+ }
+ return isFetchOk;
+ }
+
+ void writeContents(const QByteArray &contents) const
+ {
+ Utils::FileSaver fileSaver(m_filePath);
+ fileSaver.write(contents);
+ fileSaver.finalize();
+ }
+
+private:
+ void restoreContents() const
+ {
+ Utils::FileSaver fileSaver(m_filePath);
+ fileSaver.write(m_originalFileContents);
+ fileSaver.finalize();
+ }
+
+ QByteArray m_originalFileContents;
+ const QString &m_filePath;
+};
+
} // anonymous namespace
/// Check: The preprocessor cleans include and framework paths.
@@ -183,7 +206,7 @@ void CppToolsPlugin::test_modelmanager_paths_are_clean()
ModelManagerTestHelper helper;
CppModelManager *mm = CppModelManager::instance();
- const TestDataDirectory testDataDir(QLatin1String("testdata"));
+ const MyTestDataDir testDataDir(QLatin1String("testdata"));
Project *project = helper.createProject(QLatin1String("test_modelmanager_paths_are_clean"));
ProjectInfo pi = mm->projectInfo(project);
@@ -211,10 +234,13 @@ void CppToolsPlugin::test_modelmanager_paths_are_clean()
/// Check: Frameworks headers are resolved.
void CppToolsPlugin::test_modelmanager_framework_headers()
{
+ if (Utils::HostOsInfo::isWindowsHost())
+ MSKIP_SINGLE("Can't resolve framework soft links on Windows.");
+
ModelManagerTestHelper helper;
CppModelManager *mm = CppModelManager::instance();
- const TestDataDirectory testDataDir(QLatin1String("testdata"));
+ const MyTestDataDir testDataDir(QLatin1String("testdata"));
Project *project = helper.createProject(QLatin1String("test_modelmanager_framework_headers"));
ProjectInfo pi = mm->projectInfo(project);
@@ -231,8 +257,7 @@ void CppToolsPlugin::test_modelmanager_framework_headers()
part->files << ProjectFile(source, ProjectFile::CXXSource);
pi.appendProjectPart(part);
- mm->updateProjectInfo(pi);
- mm->updateSourceFiles(QStringList(source)).waitForFinished();
+ mm->updateProjectInfo(pi).waitForFinished();
QCoreApplication::processEvents();
QVERIFY(mm->snapshot().contains(source));
@@ -260,7 +285,7 @@ void CppToolsPlugin::test_modelmanager_refresh_also_includes_of_project_files()
ModelManagerTestHelper helper;
CppModelManager *mm = CppModelManager::instance();
- const TestDataDirectory testDataDir(QLatin1String("testdata"));
+ const MyTestDataDir testDataDir(QLatin1String("testdata"));
const QString testCpp(testDataDir.fileFromSourcesDir(
QLatin1String("test_modelmanager_refresh.cpp")));
@@ -279,7 +304,6 @@ void CppToolsPlugin::test_modelmanager_refresh_also_includes_of_project_files()
part->includePaths = QStringList() << testDataDir.includeDir(false);
part->files.append(ProjectFile(testCpp, ProjectFile::CXXSource));
pi.appendProjectPart(part);
-
mm->updateProjectInfo(pi);
QStringList refreshedFiles = helper.waitForRefreshedSourceFiles();
@@ -300,6 +324,7 @@ void CppToolsPlugin::test_modelmanager_refresh_also_includes_of_project_files()
pi.clearProjectParts();
pi.appendProjectPart(part);
mm->updateProjectInfo(pi);
+
refreshedFiles = helper.waitForRefreshedSourceFiles();
QCOMPARE(refreshedFiles.size(), 1);
@@ -323,7 +348,7 @@ void CppToolsPlugin::test_modelmanager_refresh_several_times()
ModelManagerTestHelper helper;
CppModelManager *mm = CppModelManager::instance();
- const TestDataDirectory testDataDir(QLatin1String("testdata_refresh"));
+ const MyTestDataDir testDataDir(QLatin1String("testdata_refresh"));
const QString testHeader1(testDataDir.file(QLatin1String("defines.h")));
const QString testHeader2(testDataDir.file(QLatin1String("header.h")));
@@ -341,7 +366,6 @@ void CppToolsPlugin::test_modelmanager_refresh_several_times()
part->files.append(ProjectFile(testHeader2, ProjectFile::CXXHeader));
part->files.append(ProjectFile(testCpp, ProjectFile::CXXSource));
pi.appendProjectPart(part);
-
mm->updateProjectInfo(pi);
CPlusPlus::Snapshot snapshot;
@@ -363,6 +387,7 @@ void CppToolsPlugin::test_modelmanager_refresh_several_times()
pi.appendProjectPart(part);
mm->updateProjectInfo(pi);
+
refreshedFiles = helper.waitForRefreshedSourceFiles();
QCOMPARE(refreshedFiles.size(), 3);
@@ -394,7 +419,7 @@ void CppToolsPlugin::test_modelmanager_refresh_test_for_changes()
ModelManagerTestHelper helper;
CppModelManager *mm = CppModelManager::instance();
- const TestDataDirectory testDataDir(QLatin1String("testdata_refresh"));
+ const MyTestDataDir testDataDir(QLatin1String("testdata_refresh"));
const QString testCpp(testDataDir.file(QLatin1String("source.cpp")));
Project *project = helper.createProject(QLatin1String("test_modelmanager_refresh_2"));
@@ -419,6 +444,165 @@ void CppToolsPlugin::test_modelmanager_refresh_test_for_changes()
QVERIFY(subsequentFuture.isCanceled() && subsequentFuture.isFinished());
}
+/// Check: (1) Added project files are recognized and parsed.
+/// Check: (2) Removed project files are recognized and purged from the snapshot.
+void CppToolsPlugin::test_modelmanager_refresh_added_and_purge_removed()
+{
+ ModelManagerTestHelper helper;
+ CppModelManager *mm = CppModelManager::instance();
+
+ const MyTestDataDir testDataDir(QLatin1String("testdata_refresh"));
+
+ const QString testHeader1(testDataDir.file(QLatin1String("header.h")));
+ const QString testHeader2(testDataDir.file(QLatin1String("defines.h")));
+ const QString testCpp(testDataDir.file(QLatin1String("source.cpp")));
+
+ Project *project = helper.createProject(QLatin1String("test_modelmanager_refresh_3"));
+ ProjectInfo pi = mm->projectInfo(project);
+ QCOMPARE(pi.project().data(), project);
+
+ ProjectPart::Ptr part(new ProjectPart);
+ part->cxxVersion = ProjectPart::CXX98;
+ part->qtVersion = ProjectPart::Qt5;
+ part->files.append(ProjectFile(testCpp, ProjectFile::CXXSource));
+ part->files.append(ProjectFile(testHeader1, ProjectFile::CXXHeader));
+ pi.appendProjectPart(part);
+
+ CPlusPlus::Snapshot snapshot;
+ QStringList refreshedFiles;
+
+ mm->updateProjectInfo(pi);
+ refreshedFiles = helper.waitForRefreshedSourceFiles();
+
+ QCOMPARE(refreshedFiles.size(), 2);
+ QVERIFY(refreshedFiles.contains(testHeader1));
+ QVERIFY(refreshedFiles.contains(testCpp));
+
+ snapshot = mm->snapshot();
+ QVERIFY(snapshot.contains(testHeader1));
+ QVERIFY(snapshot.contains(testCpp));
+
+ // Now add testHeader2 and remove testHeader1
+ pi.clearProjectParts();
+ ProjectPart::Ptr newPart(new ProjectPart);
+ newPart->cxxVersion = ProjectPart::CXX98;
+ newPart->qtVersion = ProjectPart::Qt5;
+ newPart->files.append(ProjectFile(testCpp, ProjectFile::CXXSource));
+ newPart->files.append(ProjectFile(testHeader2, ProjectFile::CXXHeader));
+ pi.appendProjectPart(newPart);
+
+ mm->updateProjectInfo(pi);
+ refreshedFiles = helper.waitForRefreshedSourceFiles();
+
+ // Only the added project file was reparsed
+ QCOMPARE(refreshedFiles.size(), 1);
+ QVERIFY(refreshedFiles.contains(testHeader2));
+
+ snapshot = mm->snapshot();
+ QVERIFY(snapshot.contains(testHeader2));
+ QVERIFY(snapshot.contains(testCpp));
+ // The removed project file is not anymore in the snapshot
+ QVERIFY(!snapshot.contains(testHeader1));
+}
+
+/// Check: Timestamp modified files are reparsed if project files are added or removed
+/// while the project configuration stays the same
+void CppToolsPlugin::test_modelmanager_refresh_timeStampModified_if_sourcefiles_change()
+{
+ QFETCH(QString, fileToChange);
+ QFETCH(QList<ProjectFile>, initialProjectFiles);
+ QFETCH(QList<ProjectFile>, finalProjectFiles);
+
+ ModelManagerTestHelper helper;
+ CppModelManager *mm = CppModelManager::instance();
+
+ Project *project = helper.createProject(
+ QLatin1String("test_modelmanager_refresh_timeStampModified"));
+ ProjectInfo pi = mm->projectInfo(project);
+ QCOMPARE(pi.project().data(), project);
+
+ ProjectPart::Ptr part(new ProjectPart);
+ part->cxxVersion = ProjectPart::CXX98;
+ part->qtVersion = ProjectPart::Qt5;
+ foreach (const ProjectFile &file, initialProjectFiles)
+ part->files.append(file);
+ pi.appendProjectPart(part);
+
+ Document::Ptr document;
+ CPlusPlus::Snapshot snapshot;
+ QStringList refreshedFiles;
+
+ mm->updateProjectInfo(pi);
+ refreshedFiles = helper.waitForRefreshedSourceFiles();
+
+ QCOMPARE(refreshedFiles.size(), initialProjectFiles.size());
+ snapshot = mm->snapshot();
+ foreach (const ProjectFile &file, initialProjectFiles) {
+ QVERIFY(refreshedFiles.contains(file.path));
+ QVERIFY(snapshot.contains(file.path));
+ }
+
+ document = snapshot.document(fileToChange);
+ const QDateTime lastModifiedBefore = document->lastModified();
+ QCOMPARE(document->globalSymbolCount(), 1U);
+ QCOMPARE(document->globalSymbolAt(0)->name()->identifier()->chars(), "someGlobal");
+
+ // Modify the file
+ QTest::qSleep(1000); // Make sure the timestamp is different
+ FileChangerAndRestorer fileChangerAndRestorer(fileToChange);
+ QByteArray originalContents;
+ QVERIFY(fileChangerAndRestorer.readContents(&originalContents));
+ const QByteArray newFileContentes = originalContents + "\nint addedOtherGlobal;";
+ fileChangerAndRestorer.writeContents(newFileContentes);
+
+ // Add or remove source file. The configuration stays the same.
+ part->files.clear();
+ foreach (const ProjectFile &file, finalProjectFiles)
+ part->files.append(file);
+ pi.clearProjectParts();
+ pi.appendProjectPart(part);
+
+ mm->updateProjectInfo(pi);
+ refreshedFiles = helper.waitForRefreshedSourceFiles();
+
+ QCOMPARE(refreshedFiles.size(), finalProjectFiles.size());
+ snapshot = mm->snapshot();
+ foreach (const ProjectFile &file, finalProjectFiles) {
+ QVERIFY(refreshedFiles.contains(file.path));
+ QVERIFY(snapshot.contains(file.path));
+ }
+ document = snapshot.document(fileToChange);
+ const QDateTime lastModifiedAfter = document->lastModified();
+ QVERIFY(lastModifiedAfter > lastModifiedBefore);
+ QCOMPARE(document->globalSymbolCount(), 2U);
+ QCOMPARE(document->globalSymbolAt(0)->name()->identifier()->chars(), "someGlobal");
+ QCOMPARE(document->globalSymbolAt(1)->name()->identifier()->chars(), "addedOtherGlobal");
+}
+
+void CppToolsPlugin::test_modelmanager_refresh_timeStampModified_if_sourcefiles_change_data()
+{
+ QTest::addColumn<QString>("fileToChange");
+ QTest::addColumn<QList<ProjectFile> >("initialProjectFiles");
+ QTest::addColumn<QList<ProjectFile> >("finalProjectFiles");
+
+ const MyTestDataDir testDataDir(QLatin1String("testdata_refresh2"));
+ const QString testCpp(testDataDir.file(QLatin1String("source.cpp")));
+ const QString testCpp2(testDataDir.file(QLatin1String("source2.cpp")));
+
+ const QString fileToChange = testCpp;
+ QList<ProjectFile> projectFiles1 = QList<ProjectFile>()
+ << ProjectFile(testCpp, ProjectFile::CXXSource);
+ QList<ProjectFile> projectFiles2 = QList<ProjectFile>()
+ << ProjectFile(testCpp, ProjectFile::CXXSource)
+ << ProjectFile(testCpp2, ProjectFile::CXXSource);
+
+ // Add a file
+ QTest::newRow("case: add project file") << fileToChange << projectFiles1 << projectFiles2;
+
+ // Remove a file
+ QTest::newRow("case: remove project file") << fileToChange << projectFiles2 << projectFiles1;
+}
+
/// Check: If a second project is opened, the code model is still aware of
/// files of the first project.
void CppToolsPlugin::test_modelmanager_snapshot_after_two_projects()
@@ -471,11 +655,13 @@ void CppToolsPlugin::test_modelmanager_snapshot_after_two_projects()
/// though it might not be actually generated in the build dir.
void CppToolsPlugin::test_modelmanager_extraeditorsupport_uiFiles()
{
- TestDataDirectory testDataDirectory(QLatin1String("testdata_guiproject1"));
+ ModelManagerTestHelper helper;
+
+ MyTestDataDir testDataDirectory(QLatin1String("testdata_guiproject1"));
const QString projectFile = testDataDirectory.file(QLatin1String("testdata_guiproject1.pro"));
// Open project with *.ui file
- ProjectExplorer::ProjectExplorerPlugin *pe = ProjectExplorer::ProjectExplorerPlugin::instance();
+ ProjectExplorerPlugin *pe = ProjectExplorerPlugin::instance();
ExampleProjectConfigurator exampleProjectConfigurator(projectFile, pe);
Project *project = exampleProjectConfigurator.project();
@@ -487,7 +673,7 @@ void CppToolsPlugin::test_modelmanager_extraeditorsupport_uiFiles()
QCOMPARE(workingCopy.size(), 2); // mm->configurationFileName() and "ui_*.h"
QStringList fileNamesInWorkinCopy;
- QHashIterator<QString, QPair<QString, unsigned> > it = workingCopy.iterator();
+ QHashIterator<QString, QPair<QByteArray, unsigned> > it = workingCopy.iterator();
while (it.hasNext()) {
it.next();
fileNamesInWorkinCopy << QFileInfo(it.key()).fileName();
@@ -512,7 +698,71 @@ void CppToolsPlugin::test_modelmanager_extraeditorsupport_uiFiles()
QCOMPARE(QFileInfo(includedFiles.at(1)).fileName(), QLatin1String("ui_mainwindow.h"));
// Close Project
- ProjectExplorer::SessionManager *sm = pe->session();
- sm->removeProject(project);
- ModelManagerTestHelper::verifyClean();
+ SessionManager::removeProject(project);
+ helper.waitForFinishedGc();
+}
+
+/// QTCREATORBUG-9828: Locator shows symbols of closed files
+/// Check: The garbage collector should be run if the last CppEditor is closed.
+void CppToolsPlugin::test_modelmanager_gc_if_last_cppeditor_closed()
+{
+ ModelManagerTestHelper helper;
+
+ MyTestDataDir testDataDirectory(QLatin1String("testdata_guiproject1"));
+ const QString file = testDataDirectory.file(QLatin1String("main.cpp"));
+
+ CppModelManager *mm = CppModelManager::instance();
+
+ // Open a file in the editor
+ QCOMPARE(Core::EditorManager::documentModel()->openedDocuments().size(), 0);
+ Core::IEditor *editor = Core::EditorManager::openEditor(file);
+ QVERIFY(editor);
+ QCOMPARE(Core::EditorManager::documentModel()->openedDocuments().size(), 1);
+ QVERIFY(mm->isCppEditor(editor));
+ QVERIFY(mm->workingCopy().contains(file));
+
+ // Check: File is in the snapshot
+ QVERIFY(mm->snapshot().contains(file));
+
+ // Close file/editor
+ Core::EditorManager::closeEditor(editor, /*askAboutModifiedEditors=*/ false);
+ helper.waitForFinishedGc();
+
+ // Check: File is removed from the snapshpt
+ QVERIFY(!mm->workingCopy().contains(file));
+ QVERIFY(!mm->snapshot().contains(file));
+}
+
+/// Check: Files that are open in the editor are not garbage collected.
+void CppToolsPlugin::test_modelmanager_dont_gc_opened_files()
+{
+ ModelManagerTestHelper helper;
+
+ MyTestDataDir testDataDirectory(QLatin1String("testdata_guiproject1"));
+ const QString file = testDataDirectory.file(QLatin1String("main.cpp"));
+
+ CppModelManager *mm = CppModelManager::instance();
+
+ // Open a file in the editor
+ QCOMPARE(Core::EditorManager::documentModel()->openedDocuments().size(), 0);
+ Core::IEditor *editor = Core::EditorManager::openEditor(file);
+ QVERIFY(editor);
+ QCOMPARE(Core::EditorManager::documentModel()->openedDocuments().size(), 1);
+ QVERIFY(mm->isCppEditor(editor));
+
+ // Check: File is in the working copy and snapshot
+ QVERIFY(mm->workingCopy().contains(file));
+ QVERIFY(mm->snapshot().contains(file));
+
+ // Run the garbage collector
+ mm->GC();
+
+ // Check: File is still there
+ QVERIFY(mm->workingCopy().contains(file));
+ QVERIFY(mm->snapshot().contains(file));
+
+ // Close editor
+ Core::EditorManager::closeEditors(QList<Core::IEditor*>() << editor);
+ helper.waitForFinishedGc();
+ QVERIFY(mm->snapshot().isEmpty());
}
diff --git a/src/plugins/cpptools/cppmodelmanagerinterface.cpp b/src/plugins/cpptools/cppmodelmanagerinterface.cpp
index d3e34ca320..d2e138dc66 100644
--- a/src/plugins/cpptools/cppmodelmanagerinterface.cpp
+++ b/src/plugins/cpptools/cppmodelmanagerinterface.cpp
@@ -29,11 +29,15 @@
#include "cppmodelmanagerinterface.h"
-#include <projectexplorer/toolchain.h>
-#include <projectexplorer/headerpath.h>
#include <cplusplus/pp-engine.h>
-#include <QtCore/QSet>
+#include <projectexplorer/headerpath.h>
+#include <projectexplorer/toolchain.h>
+
+#include <QSet>
+
+using namespace CppTools;
+using namespace ProjectExplorer;
/*!
\enum CppTools::CppModelManagerInterface::ProgressNotificationMode
@@ -44,15 +48,16 @@
\value ForcedProgressNotification
Notify regardless of the number of files requested for update.
-
\value ReservedProgressNotification
Notify only if more than one file is requested for update.
*/
/*!
\enum CppTools::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
@@ -63,8 +68,36 @@
Parser may enable tricks for Qt v5.x
*/
-using namespace CppTools;
-using namespace ProjectExplorer;
+/*!
+ \fn virtual QFuture<void> updateProjectInfo(const ProjectInfo &pinfo) = 0;
+ \param pinfo Updated ProjectInfo.
+ \return A future that reports progress and allows to cancel the reparsing operation.
+
+ This function is expected to be called by the project managers to update the
+ code model with new project information.
+
+ In particular, the function should be called in case:
+ 1. A new project is opened/created
+ 2. The project configuration changed. This includes
+ 2.1 Changes of defines, includes, framework paths
+ 2.2 Addition/Removal of project files
+
+ \sa CppTools::CppModelManagerInterface::updateSourceFiles()
+*/
+
+/*!
+ \fn virtual QFuture<void> updateSourceFiles(const QStringList &sourceFiles, ProgressNotificationMode mode = ReservedProgressNotification) = 0;
+ \param sourceFiles List of source file to update. The items are absolute paths.
+ \param mode The progress modification mode.
+ \return A future that reports progress and allows to cancel the reparsing operation.
+
+ Trigger an asynchronous reparsing of the given source files.
+
+ This function is not meant to be called by the project managers.
+
+ \sa CppTools::CppModelManagerInterface::ProgressNotificationMode
+ \sa CppTools::CppModelManagerInterface::updateProjectInfo()
+*/
ProjectPart::ProjectPart()
: cVersion(C89)
@@ -76,12 +109,13 @@ ProjectPart::ProjectPart()
{
}
-/**
- * @brief Retrieves info from concrete compiler using it's flags.
- * @param tc Either nullptr or toolchain for project's active target.
- * @param cxxflags C++ or Objective-C++ flags.
- * @param cflags C or ObjectiveC flags if possible, \a cxxflags otherwise.
- */
+/*!
+ \brief Retrieves info from concrete compiler using it's flags.
+
+ \param tc Either nullptr or toolchain for project's active target.
+ \param cxxflags C++ or Objective-C++ flags.
+ \param cflags C or ObjectiveC flags if possible, \a cxxflags otherwise.
+*/
void ProjectPart::evaluateToolchain(const ToolChain *tc,
const QStringList &cxxflags,
const QStringList &cflags,
@@ -89,6 +123,7 @@ void ProjectPart::evaluateToolchain(const ToolChain *tc,
{
if (!tc)
return;
+
ToolChain::CompilerFlags cxx = tc->compilerFlags(cxxflags);
ToolChain::CompilerFlags c = (cxxflags == cflags)
? cxx : tc->compilerFlags(cflags);
@@ -112,19 +147,19 @@ void ProjectPart::evaluateToolchain(const ToolChain *tc,
if (cxx & ToolChain::MicrosoftExtensions)
cxxExtensions |= MicrosoftExtensions;
if (cxx & ToolChain::OpenMP)
- cxxExtensions |= OpenMP;
+ cxxExtensions |= OpenMPExtensions;
cWarningFlags = tc->warningFlags(cflags);
cxxWarningFlags = tc->warningFlags(cxxflags);
- QList<HeaderPath> headers = tc->systemHeaderPaths(cxxflags, sysRoot);
+ const QList<HeaderPath> headers = tc->systemHeaderPaths(cxxflags, sysRoot);
foreach (const HeaderPath &header, headers)
if (header.kind() == HeaderPath::FrameworkHeaderPath)
frameworkPaths << header.path();
else
includePaths << header.path();
- QByteArray macros = tc->predefinedMacros(cxxflags);
+ const QByteArray macros = tc->predefinedMacros(cxxflags);
if (!macros.isEmpty()) {
if (!defines.isEmpty())
defines += '\n';
@@ -141,7 +176,7 @@ const QString CppModelManagerInterface::configurationFileName()
CppModelManagerInterface::CppModelManagerInterface(QObject *parent)
: QObject(parent)
{
- Q_ASSERT(! g_instance);
+ Q_ASSERT(!g_instance);
g_instance = this;
}
@@ -156,7 +191,6 @@ CppModelManagerInterface *CppModelManagerInterface::instance()
return g_instance;
}
-
void CppModelManagerInterface::ProjectInfo::clearProjectParts()
{
m_projectParts.clear();
@@ -166,33 +200,32 @@ void CppModelManagerInterface::ProjectInfo::clearProjectParts()
m_defines.clear();
}
-void CppModelManagerInterface::ProjectInfo::appendProjectPart(
- const ProjectPart::Ptr &part)
+void CppModelManagerInterface::ProjectInfo::appendProjectPart(const ProjectPart::Ptr &part)
{
if (!part)
return;
m_projectParts.append(part);
- // update include paths
+ // Update include paths
QSet<QString> incs = QSet<QString>::fromList(m_includePaths);
foreach (const QString &ins, part->includePaths)
incs.insert(ins);
m_includePaths = incs.toList();
- // update framework paths
+ // Update framework paths
QSet<QString> frms = QSet<QString>::fromList(m_frameworkPaths);
foreach (const QString &frm, part->frameworkPaths)
frms.insert(frm);
m_frameworkPaths = frms.toList();
- // update source files
+ // Update source files
QSet<QString> srcs = QSet<QString>::fromList(m_sourceFiles);
foreach (const ProjectFile &file, part->files)
srcs.insert(file.path);
m_sourceFiles = srcs.toList();
- // update defines
+ // Update defines
if (!m_defines.isEmpty())
m_defines.append('\n');
m_defines.append(part->defines);
diff --git a/src/plugins/cpptools/cppmodelmanagerinterface.h b/src/plugins/cpptools/cppmodelmanagerinterface.h
index ac1bcf9a3d..4bcf1c6059 100644
--- a/src/plugins/cpptools/cppmodelmanagerinterface.h
+++ b/src/plugins/cpptools/cppmodelmanagerinterface.h
@@ -31,26 +31,28 @@
#define CPPMODELMANAGERINTERFACE_H
#include "cpptools_global.h"
+
#include "cppprojectfile.h"
#include <cplusplus/CppDocument.h>
#include <projectexplorer/toolchain.h>
-#include <QObject>
+#include <QFuture>
#include <QHash>
+#include <QObject>
#include <QPointer>
#include <QStringList>
-#include <QFuture>
namespace Core { class IEditor; }
namespace CPlusPlus { class LookupContext; }
namespace ProjectExplorer { class Project; }
-namespace TextEditor { class BaseTextEditor; }
+namespace TextEditor { class BaseTextEditor; class BlockRange; }
namespace Utils { class FileName; }
namespace CppTools {
+
class AbstractEditorSupport;
-class CppCompletionSupport;
+class ModelManagerSupport;
class CppCompletionAssistProvider;
class CppEditorSupport;
class CppHighlightingSupport;
@@ -84,7 +86,9 @@ public:
GnuExtensions = 0x1,
MicrosoftExtensions = 0x2,
BorlandExtensions = 0x4,
- OpenMP = 0x8
+ OpenMPExtensions = 0x8,
+
+ AllExtensions = GnuExtensions | MicrosoftExtensions | BorlandExtensions | OpenMPExtensions
};
Q_DECLARE_FLAGS(CXXExtensions, CXXExtension)
@@ -97,7 +101,7 @@ public:
typedef QSharedPointer<ProjectPart> Ptr;
-public: //attributes
+public:
QList<ProjectFile> files;
QByteArray defines;
QStringList includePaths;
@@ -116,8 +120,7 @@ class CPPTOOLS_EXPORT CppModelManagerInterface : public QObject
Q_OBJECT
public:
-
- // Documented in source file.
+ // Documented in source file.
enum ProgressNotificationMode {
ForcedProgressNotification,
ReservedProgressNotification
@@ -127,17 +130,17 @@ public:
{
public:
ProjectInfo()
- { }
+ {}
ProjectInfo(QPointer<ProjectExplorer::Project> project)
: m_project(project)
- { }
+ {}
operator bool() const
- { return ! m_project.isNull(); }
+ { return !m_project.isNull(); }
bool isValid() const
- { return ! m_project.isNull(); }
+ { return !m_project.isNull(); }
bool isNull() const
{ return m_project.isNull(); }
@@ -163,39 +166,48 @@ public:
const QByteArray defines() const
{ return m_defines; }
- private: // attributes
+ private:
QPointer<ProjectExplorer::Project> m_project;
QList<ProjectPart::Ptr> m_projectParts;
- // the attributes below are calculated from the project parts.
+ // The members below are (re)calculated from the project parts once a part is appended.
QStringList m_includePaths;
QStringList m_frameworkPaths;
QStringList m_sourceFiles;
QByteArray m_defines;
};
+ /// The working-copy stores all files that are stored on disk in their current state.
+ ///
+ /// So, currently the working copy holds:
+ /// - unsaved content of editors
+ /// - uic-ed UI files (through \c AbstractEditorSupport)
+ /// - the preprocessor configuration
+ ///
+ /// Contents are keyed on filename, and hold the revision in the editor and the editor's
+ /// contents encoded as UTF-8.
class CPPTOOLS_EXPORT WorkingCopy
{
public:
- void insert(const QString &fileName, const QString &source, unsigned revision = 0)
+ void insert(const QString &fileName, const QByteArray &source, unsigned revision = 0)
{ _elements.insert(fileName, qMakePair(source, revision)); }
bool contains(const QString &fileName) const
{ return _elements.contains(fileName); }
- QString source(const QString &fileName) const
+ QByteArray source(const QString &fileName) const
{ return _elements.value(fileName).first; }
- QPair<QString, unsigned> get(const QString &fileName) const
+ QPair<QByteArray, unsigned> get(const QString &fileName) const
{ return _elements.value(fileName); }
- QHashIterator<QString, QPair<QString, unsigned> > iterator() const
- { return QHashIterator<QString, QPair<QString, unsigned> >(_elements); }
+ QHashIterator<QString, QPair<QByteArray, unsigned> > iterator() const
+ { return QHashIterator<QString, QPair<QByteArray, unsigned> >(_elements); }
int size() const
{ return _elements.size(); }
private:
- typedef QHash<QString, QPair<QString, unsigned> > Table;
+ typedef QHash<QString, QPair<QByteArray, unsigned> > Table;
Table _elements;
};
@@ -217,13 +229,14 @@ public:
virtual ProjectInfo projectInfo(ProjectExplorer::Project *project) const = 0;
virtual QFuture<void> updateProjectInfo(const ProjectInfo &pinfo) = 0;
virtual QList<ProjectPart::Ptr> projectPart(const QString &fileName) const = 0;
+ virtual ProjectPart::Ptr fallbackProjectPart() const = 0;
virtual QStringList includePaths() = 0;
- virtual void addEditorSupport(CppTools::AbstractEditorSupport *editorSupport) = 0;
- virtual void removeEditorSupport(CppTools::AbstractEditorSupport *editorSupport) = 0;
- virtual CppEditorSupport *cppEditorSupport(TextEditor::BaseTextEditor *editor) = 0;
- virtual void deleteEditorSupport(TextEditor::BaseTextEditor *textEditor) = 0;
+ virtual void addExtraEditorSupport(CppTools::AbstractEditorSupport *editorSupport) = 0;
+ virtual void removeExtraEditorSupport(CppTools::AbstractEditorSupport *editorSupport) = 0;
+ virtual CppEditorSupport *cppEditorSupport(TextEditor::BaseTextEditor *textEditor) = 0;
+ virtual void deleteCppEditorSupport(TextEditor::BaseTextEditor *textEditor) = 0;
virtual QList<int> references(CPlusPlus::Symbol *symbol,
const CPlusPlus::LookupContext &context) = 0;
@@ -237,17 +250,21 @@ public:
virtual void setExtraDiagnostics(const QString &fileName, const QString &kind,
const QList<CPlusPlus::Document::DiagnosticMessage> &diagnostics) = 0;
+ virtual void setIfdefedOutBlocks(const QString &fileName,
+ const QList<TextEditor::BlockRange> &ifdeffedOutBlocks) = 0;
- virtual CppTools::CppCompletionSupport *completionSupport(Core::IEditor *editor) const = 0;
- virtual void setCppCompletionAssistProvider(CppTools::CppCompletionAssistProvider *completionAssistProvider) = 0;
-
- virtual CppTools::CppHighlightingSupport *highlightingSupport(Core::IEditor *editor) const = 0;
- virtual void setHighlightingSupportFactory(CppTools::CppHighlightingSupportFactory *highlightingFactory) = 0;
+ virtual void addModelManagerSupport(ModelManagerSupport *modelManagerSupport) = 0;
+ virtual ModelManagerSupport *modelManagerSupportForMimeType(const QString &mimeType) const = 0;
+ virtual CppCompletionAssistProvider *completionAssistProvider(Core::IEditor *editor) const = 0;
+ virtual CppHighlightingSupport *highlightingSupport(Core::IEditor *editor) const = 0;
virtual void setIndexingSupport(CppTools::CppIndexingSupport *indexingSupport) = 0;
- virtual CppTools::CppIndexingSupport *indexingSupport() = 0;
+ virtual CppIndexingSupport *indexingSupport() = 0;
+
+signals:
+ /// Project data might be locked while this is emitted.
+ void aboutToRemoveFiles(const QStringList &files);
-Q_SIGNALS:
void documentUpdated(CPlusPlus::Document::Ptr doc);
void sourceFilesRefreshed(const QStringList &files);
@@ -256,11 +273,12 @@ Q_SIGNALS:
/// 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;
+public slots:
+ // Documented in source file.
virtual QFuture<void> updateSourceFiles(const QStringList &sourceFiles,
ProgressNotificationMode mode = ReservedProgressNotification) = 0;
+
+ virtual void updateModifiedSourceFiles() = 0;
virtual void GC() = 0;
};
diff --git a/src/plugins/help/help_global.h b/src/plugins/cpptools/cppmodelmanagersupport.cpp
index 2f985ff4d2..8892dbada4 100644
--- a/src/plugins/help/help_global.h
+++ b/src/plugins/cpptools/cppmodelmanagersupport.cpp
@@ -27,15 +27,10 @@
**
****************************************************************************/
-#ifndef HELP_GLOBAL_H
-#define HELP_GLOBAL_H
+#include "cppmodelmanagersupport.h"
-#include <qglobal.h>
+using namespace CppTools;
-#if defined(HELP_LIBRARY)
-# define HELP_EXPORT Q_DECL_EXPORT
-#else
-# define HELP_EXPORT Q_DECL_IMPORT
-#endif
-
-#endif // HELP_GLOBAL_H
+ModelManagerSupport::~ModelManagerSupport()
+{
+}
diff --git a/src/plugins/cpptools/cppmodelmanagersupport.h b/src/plugins/cpptools/cppmodelmanagersupport.h
new file mode 100644
index 0000000000..be738c82a4
--- /dev/null
+++ b/src/plugins/cpptools/cppmodelmanagersupport.h
@@ -0,0 +1,58 @@
+/****************************************************************************
+**
+** 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 CPPTOOLS_CPPMODELMANAGERSUPPORT_H
+#define CPPTOOLS_CPPMODELMANAGERSUPPORT_H
+
+#include "cpptools_global.h"
+
+#include <QString>
+
+namespace TextEditor { class ITextEditor; }
+
+namespace CppTools {
+
+class CppCompletionAssistProvider;
+class CppHighlightingSupport;
+
+class CPPTOOLS_EXPORT ModelManagerSupport
+{
+public:
+ virtual ~ModelManagerSupport() = 0;
+
+ virtual QString id() const = 0;
+ virtual QString displayName() const = 0;
+
+ virtual CppCompletionAssistProvider *completionAssistProvider() = 0;
+ virtual CppHighlightingSupport *highlightingSupport(TextEditor::ITextEditor *editor) = 0;
+};
+
+} // CppTools namespace
+
+#endif // CPPTOOLS_CPPMODELMANAGERSUPPORT_H
diff --git a/src/plugins/analyzerbase/analyzeroptionspage.cpp b/src/plugins/cpptools/cppmodelmanagersupportinternal.cpp
index a38da98f38..40527b8027 100644
--- a/src/plugins/analyzerbase/analyzeroptionspage.cpp
+++ b/src/plugins/cpptools/cppmodelmanagersupportinternal.cpp
@@ -2,7 +2,6 @@
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
-** Author: Nicolas Arnaud-Cormos, KDAB (nicolas.arnaud-cormos@kdab.com)
**
** This file is part of Qt Creator.
**
@@ -28,37 +27,41 @@
**
****************************************************************************/
-#include "analyzeroptionspage.h"
-#include "analyzersettings.h"
+#include "cppcompletionassist.h"
+#include "cpphighlightingsupportinternal.h"
+#include "cppmodelmanagersupportinternal.h"
#include <QCoreApplication>
-#include <QDebug>
-#include <QWidget>
-using namespace Analyzer;
-using namespace Analyzer::Internal;
+using namespace CppTools;
+using namespace CppTools::Internal;
-AnalyzerOptionsPage::AnalyzerOptionsPage(AbstractAnalyzerSubConfig *config, QObject *parent) :
- Core::IOptionsPage(parent),
- m_config(config)
+ModelManagerSupportInternal::ModelManagerSupportInternal()
+ : m_completionAssistProvider(new InternalCompletionAssistProvider)
{
- setId(m_config->id());
- setDisplayName(m_config->displayName());
- setCategory("T.Analyzer");
- setDisplayCategory(QCoreApplication::translate("Analyzer", "Analyzer"));
- setCategoryIcon(QLatin1String(":/images/analyzer_category.png"));
}
-QWidget *AnalyzerOptionsPage::createPage(QWidget *parent)
+ModelManagerSupportInternal::~ModelManagerSupportInternal()
{
- return m_config->createConfigWidget(parent);
}
-void AnalyzerOptionsPage::apply()
+QString ModelManagerSupportInternal::id() const
{
- AnalyzerGlobalSettings::instance()->writeSettings();
+ return QLatin1String("CppTools.BuiltinCodeModel");
}
-void AnalyzerOptionsPage::finish()
+QString ModelManagerSupportInternal::displayName() const
{
+ return QCoreApplication::translate("ModelManagerSupportInternal::displayName",
+ "Qt Creator Built-in");
+}
+
+CppCompletionAssistProvider *ModelManagerSupportInternal::completionAssistProvider()
+{
+ return m_completionAssistProvider.data();
+}
+
+CppHighlightingSupport *ModelManagerSupportInternal::highlightingSupport(TextEditor::ITextEditor *editor)
+{
+ return new CppHighlightingSupportInternal(editor);
}
diff --git a/src/plugins/cmakeprojectmanager/cmakeuicodemodelsupport.h b/src/plugins/cpptools/cppmodelmanagersupportinternal.h
index c68dafeed3..650337358d 100644
--- a/src/plugins/cmakeprojectmanager/cmakeuicodemodelsupport.h
+++ b/src/plugins/cpptools/cppmodelmanagersupportinternal.h
@@ -27,37 +27,35 @@
**
****************************************************************************/
-#ifndef CMAKEUICODEMODELSUPPORT_H
-#define CMAKEUICODEMODELSUPPORT_H
+#ifndef CPPTOOLS_INTERNAL_CPPMODELMANAGERSUPPORTINTERNAL_H
+#define CPPTOOLS_INTERNAL_CPPMODELMANAGERSUPPORTINTERNAL_H
-#include <cpptools/uicodecompletionsupport.h>
+#include "cppmodelmanagersupport.h"
-#include <QDateTime>
+#include <QScopedPointer>
-namespace CppTools { class CppModelManagerInterface; }
-
-namespace CMakeProjectManager {
+namespace CppTools {
namespace Internal {
-class CMakeProject;
-
-class CMakeUiCodeModelSupport : public CppTools::UiCodeModelSupport
+class ModelManagerSupportInternal: public ModelManagerSupport
{
- Q_OBJECT
+ Q_DISABLE_COPY(ModelManagerSupportInternal)
+
public:
- CMakeUiCodeModelSupport(CppTools::CppModelManagerInterface *modelmanager,
- CMakeProject *project,
- const QString &sourceFile,
- const QString &uiHeaderFile);
- ~CMakeUiCodeModelSupport();
-protected:
- virtual QString uicCommand() const;
- virtual QStringList environment() const;
+ ModelManagerSupportInternal();
+ virtual ~ModelManagerSupportInternal();
+
+ virtual QString id() const;
+ virtual QString displayName() const;
+
+ virtual CppCompletionAssistProvider *completionAssistProvider();
+ virtual CppHighlightingSupport *highlightingSupport(TextEditor::ITextEditor *editor);
+
private:
- CMakeProject *m_project;
+ QScopedPointer<CppCompletionAssistProvider> m_completionAssistProvider;
};
+} // Internal namespace
+} // CppTools namespace
-} // Internal
-} // Qt4ProjectManager
-#endif // CMAKEUICODEMODELSUPPORT_H
+#endif // CPPTOOLS_INTERNAL_CPPMODELMANAGERSUPPORTINTERNAL_H
diff --git a/src/plugins/cpptools/cpppointerdeclarationformatter.cpp b/src/plugins/cpptools/cpppointerdeclarationformatter.cpp
index 73cab694ce..53480f9b70 100644
--- a/src/plugins/cpptools/cpppointerdeclarationformatter.cpp
+++ b/src/plugins/cpptools/cpppointerdeclarationformatter.cpp
@@ -79,7 +79,7 @@ static unsigned firstTypeSpecifierWithoutFollowingAttribute(
SpecifierListAST *list, TranslationUnit *translationUnit, unsigned endToken, bool *found)
{
*found = false;
- if (! list || ! translationUnit || ! endToken)
+ if (!list || !translationUnit || !endToken)
return 0;
for (SpecifierListAST *it = list; it; it = it->next) {
@@ -159,7 +159,7 @@ bool PointerDeclarationFormatter::visit(SimpleDeclarationAST *ast)
// characters from the beginning since our rewritten declaration
// will contain all type specifiers.
int charactersToRemove = 0;
- if (! isFirstDeclarator) {
+ if (!isFirstDeclarator) {
const int startAST = m_cppRefactoringFile->startOf(ast);
const int startFirstDeclarator = m_cppRefactoringFile->startOf(firstDeclarator);
CHECK_RV(startAST < startFirstDeclarator, "No specifier", true);
@@ -191,8 +191,8 @@ bool PointerDeclarationFormatter::visit(SimpleDeclarationAST *ast)
m_cppRefactoringFile->cppDocument()->translationUnit(),
lastActivationToken,
&foundBegin);
- if (! foundBegin) {
- CHECK_RV(! isFirstDeclarator, "Declaration without attributes not supported", true);
+ if (!foundBegin) {
+ CHECK_RV(!isFirstDeclarator, "Declaration without attributes not supported", true);
firstActivationToken = declarator->firstToken();
}
@@ -380,7 +380,7 @@ void PointerDeclarationFormatter::checkAndRewrite(DeclaratorAST *declarator,
// Check for expanded tokens
for (unsigned token = tokenRange.start; token <= tokenRange.end; ++token)
- CHECK_R(! tokenAt(token).expanded(), "Token is expanded");
+ CHECK_R(!tokenAt(token).expanded(), "Token is expanded");
Range range(m_cppRefactoringFile->startOf(tokenRange.start),
m_cppRefactoringFile->endOf(tokenRange.end));
diff --git a/src/plugins/cpptools/cpppreprocessertesthelper.cpp b/src/plugins/cpptools/cpppreprocessertesthelper.cpp
new file mode 100644
index 0000000000..dc1f48df35
--- /dev/null
+++ b/src/plugins/cpptools/cpppreprocessertesthelper.cpp
@@ -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.
+**
+****************************************************************************/
+
+
+#include "cpppreprocessertesthelper.h"
+
+#include <QDir>
+
+using namespace CppTools;
+
+QString TestIncludePaths::includeBaseDirectory()
+{
+ return QLatin1String(SRCDIR)
+ + QLatin1String("/../../../tests/auto/cplusplus/preprocessor/data/include-data");
+}
+
+QString TestIncludePaths::globalQtCoreIncludePath()
+{
+ return QDir::cleanPath(includeBaseDirectory() + QLatin1String("/QtCore"));
+}
+
+QString TestIncludePaths::globalIncludePath()
+{
+ return QDir::cleanPath(includeBaseDirectory() + QLatin1String("/global"));
+}
+
+QString TestIncludePaths::directoryOfTestFile()
+{
+ return QDir::cleanPath(includeBaseDirectory() + QLatin1String("/local"));
+}
diff --git a/src/plugins/cpptools/cpppreprocessertesthelper.h b/src/plugins/cpptools/cpppreprocessertesthelper.h
new file mode 100644
index 0000000000..c4eea5059e
--- /dev/null
+++ b/src/plugins/cpptools/cpppreprocessertesthelper.h
@@ -0,0 +1,53 @@
+/****************************************************************************
+**
+** 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 CPPPREPROCESSERTESTHELPER_H
+#define CPPPREPROCESSERTESTHELPER_H
+
+#include "cpptools_global.h"
+
+#include <QtGlobal>
+
+QT_FORWARD_DECLARE_CLASS(QString)
+
+namespace CppTools {
+
+class CPPTOOLS_EXPORT TestIncludePaths
+{
+public:
+ static QString includeBaseDirectory();
+ static QString globalQtCoreIncludePath();
+ static QString globalIncludePath();
+ static QString directoryOfTestFile();
+};
+
+} // namespace CppTools
+
+#endif // CPPPREPROCESSERTESTHELPER_H
diff --git a/src/plugins/cpptools/cpppreprocessor.cpp b/src/plugins/cpptools/cpppreprocessor.cpp
index 57a3fb4a72..48cb7fc77c 100644
--- a/src/plugins/cpptools/cpppreprocessor.cpp
+++ b/src/plugins/cpptools/cpppreprocessor.cpp
@@ -1,7 +1,9 @@
-#include "cppmodelmanager.h"
#include "cpppreprocessor.h"
+#include "cppmodelmanager.h"
+
#include <utils/hostosinfo.h>
+#include <utils/textfileformat.h>
#include <QCoreApplication>
@@ -21,7 +23,8 @@ using namespace CPlusPlus;
using namespace CppTools;
using namespace CppTools::Internal;
-CppPreprocessor::CppPreprocessor(QPointer<CppModelManager> modelManager, bool dumpFileNameWhileParsing)
+CppPreprocessor::CppPreprocessor(QPointer<CppModelManager> modelManager,
+ bool dumpFileNameWhileParsing)
: m_snapshot(modelManager->snapshot()),
m_modelManager(modelManager),
m_dumpFileNameWhileParsing(dumpFileNameWhileParsing),
@@ -68,10 +71,8 @@ void CppPreprocessor::setIncludePaths(const QStringList &includePaths)
void CppPreprocessor::setFrameworkPaths(const QStringList &frameworkPaths)
{
m_frameworkPaths.clear();
-
- foreach (const QString &frameworkPath, frameworkPaths) {
+ foreach (const QString &frameworkPath, frameworkPaths)
addFrameworkPath(frameworkPath);
- }
}
// Add the given framework path, and expand private frameworks.
@@ -86,7 +87,7 @@ 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.
- QString cleanFrameworkPath = cleanPath(frameworkPath);
+ const QString cleanFrameworkPath = cleanPath(frameworkPath);
if (!m_frameworkPaths.contains(cleanFrameworkPath))
m_frameworkPaths.append(cleanFrameworkPath);
@@ -95,7 +96,8 @@ void CppPreprocessor::addFrameworkPath(const QString &frameworkPath)
foreach (const QFileInfo &framework, frameworkDir.entryInfoList(filter)) {
if (!framework.isDir())
continue;
- const QFileInfo privateFrameworks(framework.absoluteFilePath(), QLatin1String("Frameworks"));
+ const QFileInfo privateFrameworks(framework.absoluteFilePath(),
+ QLatin1String("Frameworks"));
if (privateFrameworks.exists() && privateFrameworks.isDir())
addFrameworkPath(privateFrameworks.absoluteFilePath());
}
@@ -119,7 +121,6 @@ public:
_doc(doc),
_mode(Document::FastCheck)
{
-
if (workingCopy.contains(_doc->fileName()))
_mode = Document::FullCheck;
}
@@ -154,14 +155,14 @@ void CppPreprocessor::resetEnvironment()
}
void CppPreprocessor::getFileContents(const QString &absoluteFilePath,
- QString *contents,
+ QByteArray *contents,
unsigned *revision) const
{
if (absoluteFilePath.isEmpty())
return;
if (m_workingCopy.contains(absoluteFilePath)) {
- QPair<QString, unsigned> entry = m_workingCopy.get(absoluteFilePath);
+ const QPair<QByteArray, unsigned> entry = m_workingCopy.get(absoluteFilePath);
if (contents)
*contents = entry.first;
if (revision)
@@ -169,17 +170,11 @@ void CppPreprocessor::getFileContents(const QString &absoluteFilePath,
return;
}
- QFile file(absoluteFilePath);
- if (file.open(QFile::ReadOnly | QFile::Text)) {
- QTextCodec *defaultCodec = Core::EditorManager::instance()->defaultTextCodec();
- QTextStream stream(&file);
- stream.setCodec(defaultCodec);
- if (contents)
- *contents = stream.readAll();
- if (revision)
- *revision = 0;
- file.close();
- }
+ QString errStr;
+ if (contents)
+ Utils::TextFileFormat::readFileUTF8(absoluteFilePath, contents, &errStr);
+ if (revision)
+ *revision = 0;
}
bool CppPreprocessor::checkFile(const QString &absoluteFilePath) const
@@ -187,7 +182,7 @@ bool CppPreprocessor::checkFile(const QString &absoluteFilePath) const
if (absoluteFilePath.isEmpty() || m_included.contains(absoluteFilePath))
return true;
- QFileInfo fileInfo(absoluteFilePath);
+ const QFileInfo fileInfo(absoluteFilePath);
return fileInfo.isFile() && fileInfo.isReadable();
}
@@ -218,48 +213,51 @@ QString CppPreprocessor::cleanPath(const QString &path)
QString CppPreprocessor::resolveFile_helper(const QString &fileName, IncludeType type)
{
- QFileInfo fileInfo(fileName);
+ const QFileInfo fileInfo(fileName);
if (fileName == Preprocessor::configurationFileName || fileInfo.isAbsolute())
return fileName;
if (type == IncludeLocal && m_currentDoc) {
- QFileInfo currentFileInfo(m_currentDoc->fileName());
- QString path = cleanPath(currentFileInfo.absolutePath()) + fileName;
+ const QFileInfo currentFileInfo(m_currentDoc->fileName());
+ const QString path = cleanPath(currentFileInfo.absolutePath()) + fileName;
if (checkFile(path))
return path;
+ // Fall through! "16.2 Source file inclusion" from the standard states to continue
+ // searching as if this would be a global include.
}
foreach (const QString &includePath, m_includePaths) {
- QString path = includePath + fileName;
+ const QString path = includePath + fileName;
if (m_workingCopy.contains(path) || checkFile(path))
return path;
}
- int index = fileName.indexOf(QLatin1Char('/'));
+ const int index = fileName.indexOf(QLatin1Char('/'));
if (index != -1) {
- QString frameworkName = fileName.left(index);
- QString name = frameworkName + QLatin1String(".framework/Headers/") + fileName.mid(index + 1);
+ const QString frameworkName = fileName.left(index);
+ const QString name = frameworkName + QLatin1String(".framework/Headers/")
+ + fileName.mid(index + 1);
foreach (const QString &frameworkPath, m_frameworkPaths) {
- QString path = frameworkPath + name;
+ const QString path = frameworkPath + name;
if (checkFile(path))
return path;
}
}
- //qDebug() << "**** file" << fileName << "not found!";
return QString();
}
void CppPreprocessor::macroAdded(const Macro &macro)
{
- if (! m_currentDoc)
+ if (!m_currentDoc)
return;
m_currentDoc->appendMacro(macro);
}
-static inline const Macro revision(const CppModelManagerInterface::WorkingCopy &s, const Macro &macro)
+static inline const Macro revision(const CppModelManagerInterface::WorkingCopy &s,
+ const Macro &macro)
{
Macro newMacro(macro);
newMacro.setFileRevision(s.get(macro.fileName()).second);
@@ -268,7 +266,7 @@ static inline const Macro revision(const CppModelManagerInterface::WorkingCopy &
void CppPreprocessor::passedMacroDefinitionCheck(unsigned offset, unsigned line, const Macro &macro)
{
- if (! m_currentDoc)
+ if (!m_currentDoc)
return;
m_currentDoc->addMacroUse(revision(m_workingCopy, macro), offset, macro.name().length(), line,
@@ -277,7 +275,7 @@ void CppPreprocessor::passedMacroDefinitionCheck(unsigned offset, unsigned line,
void CppPreprocessor::failedMacroDefinitionCheck(unsigned offset, const ByteArrayRef &name)
{
- if (! m_currentDoc)
+ if (!m_currentDoc)
return;
m_currentDoc->addUndefinedMacroUse(QByteArray(name.start(), name.size()), offset);
@@ -285,7 +283,7 @@ void CppPreprocessor::failedMacroDefinitionCheck(unsigned offset, const ByteArra
void CppPreprocessor::notifyMacroReference(unsigned offset, unsigned line, const Macro &macro)
{
- if (! m_currentDoc)
+ if (!m_currentDoc)
return;
m_currentDoc->addMacroUse(revision(m_workingCopy, macro), offset, macro.name().length(), line,
@@ -296,18 +294,17 @@ void CppPreprocessor::startExpandingMacro(unsigned offset, unsigned line,
const Macro &macro,
const QVector<MacroArgumentReference> &actuals)
{
- if (! m_currentDoc)
+ if (!m_currentDoc)
return;
- m_currentDoc->addMacroUse(revision(m_workingCopy, macro), offset, macro.name().length(), line, actuals);
+ m_currentDoc->addMacroUse(revision(m_workingCopy, macro), offset, macro.name().length(), line,
+ actuals);
}
void CppPreprocessor::stopExpandingMacro(unsigned, const Macro &)
{
- if (! m_currentDoc)
+ if (!m_currentDoc)
return;
-
- //qDebug() << "stop expanding:" << macro.name;
}
void CppPreprocessor::markAsIncludeGuard(const QByteArray &macroName)
@@ -320,7 +317,7 @@ void CppPreprocessor::markAsIncludeGuard(const QByteArray &macroName)
void CppPreprocessor::mergeEnvironment(Document::Ptr doc)
{
- if (! doc)
+ if (!doc)
return;
const QString fn = doc->fileName();
@@ -330,8 +327,8 @@ void CppPreprocessor::mergeEnvironment(Document::Ptr doc)
m_processed.insert(fn);
- foreach (const Document::Include &incl, doc->includes()) {
- QString includedFile = incl.resolvedFileName();
+ foreach (const Document::Include &incl, doc->resolvedIncludes()) {
+ const QString includedFile = incl.resolvedFileName();
if (Document::Ptr includedDoc = m_snapshot.document(includedFile))
mergeEnvironment(includedDoc);
@@ -344,18 +341,28 @@ void CppPreprocessor::mergeEnvironment(Document::Ptr doc)
void CppPreprocessor::startSkippingBlocks(unsigned offset)
{
- //qDebug() << "start skipping blocks:" << offset;
if (m_currentDoc)
m_currentDoc->startSkippingBlocks(offset);
}
void CppPreprocessor::stopSkippingBlocks(unsigned offset)
{
- //qDebug() << "stop skipping blocks:" << offset;
if (m_currentDoc)
m_currentDoc->stopSkippingBlocks(offset);
}
+// This is a temporary fix to handle non-ascii characters. This can be removed when the lexer can
+// handle multi-byte characters.
+static QByteArray convertToLatin1(const QByteArray &contents)
+{
+ const char *p = contents.constData();
+ while (char ch = *p++)
+ if (ch & 0x80)
+ return QString::fromUtf8(contents).toLatin1();
+
+ return contents;
+}
+
void CppPreprocessor::sourceNeeded(unsigned line, const QString &fileName, IncludeType type)
{
if (fileName.isEmpty())
@@ -363,7 +370,7 @@ void CppPreprocessor::sourceNeeded(unsigned line, const QString &fileName, Inclu
QString absoluteFileName = resolveFile(fileName, type);
absoluteFileName = QDir::cleanPath(absoluteFileName);
- if (m_currentDoc && !absoluteFileName.isEmpty())
+ if (m_currentDoc)
m_currentDoc->addIncludeFile(Document::Include(fileName, absoluteFileName, line, type));
if (m_included.contains(absoluteFileName))
return; // we've already seen this file.
@@ -371,10 +378,11 @@ void CppPreprocessor::sourceNeeded(unsigned line, const QString &fileName, Inclu
m_included.insert(absoluteFileName);
unsigned editorRevision = 0;
- QString contents;
+ QByteArray contents;
getFileContents(absoluteFileName, &contents, &editorRevision);
+ contents = convertToLatin1(contents);
if (m_currentDoc) {
- if (contents.isEmpty() && ! QFileInfo(absoluteFileName).isAbsolute()) {
+ if (contents.isEmpty() && !QFileInfo(absoluteFileName).isAbsolute()) {
QString msg = QCoreApplication::translate(
"CppPreprocessor", "%1: No such file or directory").arg(fileName);
@@ -384,17 +392,14 @@ void CppPreprocessor::sourceNeeded(unsigned line, const QString &fileName, Inclu
msg);
m_currentDoc->addDiagnosticMessage(d);
-
- //qWarning() << "file not found:" << fileName << m_currentDoc->fileName() << env.current_line;
-
return;
}
}
if (m_dumpFileNameWhileParsing) {
qDebug() << "Parsing file:" << absoluteFileName
-// << "contents:" << contents.size()
- ;
+ << "contents:" << contents.size()
+ ;
}
Document::Ptr doc = m_snapshot.document(absoluteFileName);
@@ -407,15 +412,19 @@ void CppPreprocessor::sourceNeeded(unsigned line, const QString &fileName, Inclu
doc->setRevision(m_revision);
doc->setEditorRevision(editorRevision);
- QFileInfo info(absoluteFileName);
+ const QFileInfo info(absoluteFileName);
if (info.exists())
doc->setLastModified(info.lastModified());
- Document::Ptr previousDoc = switchDocument(doc);
+ const Document::Ptr previousDoc = switchDocument(doc);
const QByteArray preprocessedCode = m_preprocess.run(absoluteFileName, contents);
-
-// { QByteArray b(preprocessedCode); b.replace("\n", "<<<\n"); qDebug("Preprocessed code for \"%s\": [[%s]]", fileName.toUtf8().constData(), b.constData()); }
+// {
+// QByteArray b(preprocessedCode);
+// b.replace("\n", "<<<\n");
+// qDebug("Preprocessed code for \"%s\": [[%s]]", fileName.toUtf8().constData(),
+// b.constData());
+// }
doc->setUtf8Source(preprocessedCode);
doc->keepSourceAndAST();
@@ -432,7 +441,7 @@ void CppPreprocessor::sourceNeeded(unsigned line, const QString &fileName, Inclu
Document::Ptr CppPreprocessor::switchDocument(Document::Ptr doc)
{
- Document::Ptr previousDoc = m_currentDoc;
+ const Document::Ptr previousDoc = m_currentDoc;
m_currentDoc = doc;
return previousDoc;
}
diff --git a/src/plugins/cpptools/cpppreprocessor.h b/src/plugins/cpptools/cpppreprocessor.h
index c54bbefb30..e1e3f228d1 100644
--- a/src/plugins/cpptools/cpppreprocessor.h
+++ b/src/plugins/cpptools/cpppreprocessor.h
@@ -44,7 +44,7 @@ public:
protected:
CPlusPlus::Document::Ptr switchDocument(CPlusPlus::Document::Ptr doc);
- void getFileContents(const QString &absoluteFilePath, QString *contents, unsigned *revision) const;
+ void getFileContents(const QString &absoluteFilePath, QByteArray *contents, unsigned *revision) const;
bool checkFile(const QString &absoluteFilePath) const;
QString resolveFile(const QString &fileName, IncludeType type);
QString resolveFile_helper(const QString &fileName, IncludeType type);
diff --git a/src/plugins/cpptools/cpppreprocessor_test.cpp b/src/plugins/cpptools/cpppreprocessor_test.cpp
new file mode 100644
index 0000000000..38c197e6e6
--- /dev/null
+++ b/src/plugins/cpptools/cpppreprocessor_test.cpp
@@ -0,0 +1,120 @@
+/****************************************************************************
+**
+** 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 "cppmodelmanager.h"
+#include "cpppreprocessertesthelper.h"
+#include "cpppreprocessor.h"
+
+#include <cplusplus/CppDocument.h>
+#include <utils/fileutils.h>
+
+#include <QFile>
+#include <QFileInfo>
+#include <QtTest>
+
+using namespace CPlusPlus;
+using namespace CppTools;
+using namespace CppTools::Internal;
+
+typedef Document::Include Include;
+
+class SourcePreprocessor
+{
+public:
+ SourcePreprocessor()
+ : m_cmm(CppModelManager::instance())
+ {
+ cleanUp();
+ }
+
+ Document::Ptr run(const QByteArray &source)
+ {
+ const QString fileName = TestIncludePaths::directoryOfTestFile()
+ + QLatin1String("/file.cpp");
+ if (QFileInfo(fileName).exists())
+ return Document::Ptr(); // Test file was not removed.
+
+ Utils::FileSaver srcSaver(fileName);
+ srcSaver.write(source);
+ srcSaver.finalize();
+
+ CppPreprocessor pp((QPointer<CppModelManager>(m_cmm)));
+ pp.setIncludePaths(QStringList(TestIncludePaths::directoryOfTestFile()));
+ pp.run(fileName);
+
+ Document::Ptr document = m_cmm->snapshot().document(fileName);
+ QFile(fileName).remove();
+ return document;
+ }
+
+ ~SourcePreprocessor()
+ {
+ cleanUp();
+ }
+
+private:
+ void cleanUp()
+ {
+ m_cmm->GC();
+ QVERIFY(m_cmm->snapshot().isEmpty());
+ }
+
+private:
+ CppModelManager *m_cmm;
+};
+
+void CppToolsPlugin::test_cpppreprocessor_includes()
+{
+ QByteArray source =
+ "#include \"header.h\"\n"
+ "#include \"notresolvable.h\"\n"
+ "\n"
+ ;
+
+ SourcePreprocessor processor;
+ Document::Ptr document = processor.run(source);
+ QVERIFY(document);
+
+ const QList<Document::Include> resolvedIncludes = document->resolvedIncludes();
+ QVERIFY(resolvedIncludes.size() == 1);
+ QVERIFY(resolvedIncludes.at(0).type() == Client::IncludeLocal);
+ QCOMPARE(resolvedIncludes.at(0).unresolvedFileName(), QLatin1String("header.h"));
+ const QString expectedResolvedFileName
+ = TestIncludePaths::directoryOfTestFile() + QLatin1String("/header.h");
+ QCOMPARE(resolvedIncludes.at(0).resolvedFileName(), expectedResolvedFileName);
+
+ const QList<Document::Include> unresolvedIncludes = document->unresolvedIncludes();
+ QVERIFY(unresolvedIncludes.size() == 1);
+ QVERIFY(unresolvedIncludes.at(0).type() == Client::IncludeLocal);
+ QCOMPARE(unresolvedIncludes.at(0).unresolvedFileName(), QLatin1String("notresolvable.h"));
+ QVERIFY(unresolvedIncludes.at(0).resolvedFileName().isEmpty());
+}
+
diff --git a/src/plugins/cpptools/cppprojectfile.cpp b/src/plugins/cpptools/cppprojectfile.cpp
index a7e62a2905..22b995c947 100644
--- a/src/plugins/cpptools/cppprojectfile.cpp
+++ b/src/plugins/cpptools/cppprojectfile.cpp
@@ -50,9 +50,8 @@ ProjectFile::ProjectFile(const QString &file, Kind kind)
ProjectFile::Kind ProjectFile::classify(const QString &file)
{
- const Core::MimeDatabase *mimeDatabase = Core::ICore::mimeDatabase();
const QFileInfo fi(file);
- const Core::MimeType mimeType = mimeDatabase->findByFile(fi);
+ const Core::MimeType mimeType = Core::MimeDatabase::findByFile(fi);
if (!mimeType)
return Unclassified;
const QString mt = mimeType.type();
@@ -64,6 +63,8 @@ ProjectFile::Kind ProjectFile::classify(const QString &file)
return CXXSource;
if (mt == QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE))
return CXXHeader;
+ if (mt == QLatin1String(CppTools::Constants::OBJECTIVE_C_SOURCE_MIMETYPE))
+ return ObjCSource;
if (mt == QLatin1String(CppTools::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE))
return ObjCXXSource;
return Unclassified;
@@ -107,6 +108,7 @@ ProjectFileAdder::ProjectFileAdder(QList<ProjectFile> &files)
addMapping(CppTools::Constants::C_HEADER_MIMETYPE, ProjectFile::CHeader);
addMapping(CppTools::Constants::CPP_SOURCE_MIMETYPE, ProjectFile::CXXSource);
addMapping(CppTools::Constants::CPP_HEADER_MIMETYPE, ProjectFile::CXXHeader);
+ addMapping(CppTools::Constants::OBJECTIVE_C_SOURCE_MIMETYPE, ProjectFile::ObjCSource);
addMapping(CppTools::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE, ProjectFile::ObjCXXSource);
}
@@ -127,8 +129,7 @@ bool ProjectFileAdder::maybeAdd(const QString &path)
void ProjectFileAdder::addMapping(const char *mimeName, ProjectFile::Kind kind)
{
- const Core::MimeDatabase *mimeDatabase = Core::ICore::mimeDatabase();
- Core::MimeType mimeType = mimeDatabase->findByType(QLatin1String(mimeName));
+ Core::MimeType mimeType = Core::MimeDatabase::findByType(QLatin1String(mimeName));
if (!mimeType.isNull())
m_mapping.append(Pair(mimeType, kind));
}
diff --git a/src/plugins/cpptools/cpprefactoringchanges.cpp b/src/plugins/cpptools/cpprefactoringchanges.cpp
index 11111f1c2f..9bc68f57e1 100644
--- a/src/plugins/cpptools/cpprefactoringchanges.cpp
+++ b/src/plugins/cpptools/cpprefactoringchanges.cpp
@@ -109,7 +109,7 @@ CppRefactoringFileConstPtr CppRefactoringChanges::fileNoEditor(const QString &fi
{
QTextDocument *document = 0;
if (data()->m_workingCopy.contains(fileName))
- document = new QTextDocument(data()->m_workingCopy.source(fileName));
+ document = new QTextDocument(QString::fromUtf8(data()->m_workingCopy.source(fileName)));
CppRefactoringFilePtr result(new CppRefactoringFile(document, fileName));
result->m_data = m_data;
@@ -144,7 +144,7 @@ Document::Ptr CppRefactoringFile::cppDocument() const
{
if (!m_cppDocument || !m_cppDocument->translationUnit() ||
!m_cppDocument->translationUnit()->ast()) {
- const QString source = document()->toPlainText();
+ const QByteArray source = document()->toPlainText().toUtf8();
const QString name = fileName();
const Snapshot &snapshot = data()->m_snapshot;
diff --git a/src/plugins/cpptools/cppsemanticinfo.h b/src/plugins/cpptools/cppsemanticinfo.h
index 5f7e8b302d..45fa63b428 100644
--- a/src/plugins/cpptools/cppsemanticinfo.h
+++ b/src/plugins/cpptools/cppsemanticinfo.h
@@ -47,7 +47,7 @@ public:
{
const CPlusPlus::Snapshot snapshot;
const QString fileName;
- const QString code;
+ const QByteArray code;
const int line;
const int column;
const unsigned revision;
@@ -59,7 +59,7 @@ public:
Source(const CPlusPlus::Snapshot &snapshot,
const QString &fileName,
- const QString &code,
+ const QByteArray &code,
int line, int column,
unsigned revision,
bool force)
diff --git a/src/plugins/cpptools/cpptools.pro b/src/plugins/cpptools/cpptools.pro
index 89415fdea7..b27d4f46fe 100644
--- a/src/plugins/cpptools/cpptools.pro
+++ b/src/plugins/cpptools/cpptools.pro
@@ -1,6 +1,7 @@
include(../../qtcreatorplugin.pri)
DEFINES += CPPTOOLS_LIBRARY
+win32-msvc*:DEFINES += _SCL_SECURE_NO_WARNINGS
HEADERS += completionsettingspage.h \
cppclassesfilter.h \
cppcurrentdocumentfilter.h \
@@ -19,7 +20,6 @@ HEADERS += completionsettingspage.h \
cppfindreferences.h \
cppcodeformatter.h \
symbolsfindfilter.h \
- uicodecompletionsupport.h \
insertionpointlocator.h \
cpprefactoringchanges.h \
abstracteditorsupport.h \
@@ -33,7 +33,7 @@ HEADERS += completionsettingspage.h \
doxygengenerator.h \
commentssettings.h \
symbolfinder.h \
- cppcompletionsupport.h \
+ cppmodelmanagersupport.h \
cpphighlightingsupport.h \
cpphighlightingsupportinternal.h \
cppchecksymbols.h \
@@ -46,7 +46,11 @@ HEADERS += completionsettingspage.h \
cpppointerdeclarationformatter.h \
cppprojectfile.h \
cpppreprocessor.h \
- includeutils.h
+ includeutils.h \
+ cpplocatordata.h \
+ cppmodelmanagersupportinternal.h \
+ cppcodemodelsettings.h \
+ cppcodemodelsettingspage.h
SOURCES += completionsettingspage.cpp \
cppclassesfilter.cpp \
@@ -65,7 +69,6 @@ SOURCES += completionsettingspage.cpp \
cppfindreferences.cpp \
cppcodeformatter.cpp \
symbolsfindfilter.cpp \
- uicodecompletionsupport.cpp \
insertionpointlocator.cpp \
cpprefactoringchanges.cpp \
cppcompletionassist.cpp \
@@ -78,7 +81,7 @@ SOURCES += completionsettingspage.cpp \
doxygengenerator.cpp \
commentssettings.cpp \
symbolfinder.cpp \
- cppcompletionsupport.cpp \
+ cppmodelmanagersupport.cpp \
cpphighlightingsupport.cpp \
cpphighlightingsupportinternal.cpp \
cppchecksymbols.cpp \
@@ -91,11 +94,16 @@ SOURCES += completionsettingspage.cpp \
cpppointerdeclarationformatter.cpp \
cppprojectfile.cpp \
cpppreprocessor.cpp \
- includeutils.cpp
+ includeutils.cpp \
+ cpplocatordata.cpp \
+ cppmodelmanagersupportinternal.cpp \
+ cppcodemodelsettings.cpp \
+ cppcodemodelsettingspage.cpp
FORMS += completionsettingspage.ui \
cppfilesettingspage.ui \
- cppcodestylesettingspage.ui
+ cppcodestylesettingspage.ui \
+ cppcodemodelsettingspage.ui
equals(TEST, 1) {
SOURCES += \
@@ -103,9 +111,15 @@ equals(TEST, 1) {
cppcompletion_test.cpp \
cppmodelmanager_test.cpp \
modelmanagertesthelper.cpp \
- cpppointerdeclarationformatter_test.cpp
+ cpppointerdeclarationformatter_test.cpp \
+ cpplocatorfilter_test.cpp \
+ symbolsearcher_test.cpp \
+ cpppreprocessor_test.cpp \
+ cpppreprocessertesthelper.cpp \
+ cppheadersource_test.cpp
HEADERS += \
+ cpppreprocessertesthelper.h \
modelmanagertesthelper.h
DEFINES += SRCDIR=\\\"$$PWD\\\"
diff --git a/src/plugins/cpptools/cpptools.qbs b/src/plugins/cpptools/cpptools.qbs
index cf23e66920..e78d40ee19 100644
--- a/src/plugins/cpptools/cpptools.qbs
+++ b/src/plugins/cpptools/cpptools.qbs
@@ -2,7 +2,6 @@ import qbs.base 1.0
import qbs.FileInfo
import "../QtcPlugin.qbs" as QtcPlugin
-import "../../../qbs/defaults.js" as Defaults
QtcPlugin {
name: "CppTools"
@@ -16,6 +15,12 @@ QtcPlugin {
Depends { name: "CPlusPlus" }
Depends { name: "LanguageUtils" }
+ cpp.defines: base
+ Properties {
+ condition: qbs.toolchain.contains("msvc")
+ cpp.defines: base.concat("_SCL_SECURE_NO_WARNINGS")
+ }
+
files: [
"abstracteditorsupport.cpp",
"abstracteditorsupport.h",
@@ -43,8 +48,6 @@ QtcPlugin {
"cppcompletionassist.h",
"cppcompletionassistprovider.cpp",
"cppcompletionassistprovider.h",
- "cppcompletionsupport.cpp",
- "cppcompletionsupport.h",
"cppcurrentdocumentfilter.cpp",
"cppcurrentdocumentfilter.h",
"cppdoxygen.cpp",
@@ -64,10 +67,16 @@ QtcPlugin {
"cppindexingsupport.h",
"cpplocalsymbols.cpp",
"cpplocalsymbols.h",
+ "cpplocatordata.cpp",
+ "cpplocatordata.h",
"cpplocatorfilter.cpp",
"cpplocatorfilter.h",
"cppmodelmanager.cpp",
"cppmodelmanager.h",
+ "cppmodelmanagersupport.h",
+ "cppmodelmanagersupport.cpp",
+ "cppmodelmanagersupportinternal.h",
+ "cppmodelmanagersupportinternal.cpp",
"cppmodelmanagerinterface.cpp",
"cppmodelmanagerinterface.h",
"cppqtstyleindenter.cpp",
@@ -102,25 +111,33 @@ QtcPlugin {
"symbolsfindfilter.h",
"typehierarchybuilder.cpp",
"typehierarchybuilder.h",
- "uicodecompletionsupport.cpp",
- "uicodecompletionsupport.h",
"builtinindexingsupport.cpp",
"builtinindexingsupport.h",
"cpppreprocessor.cpp",
"cpppreprocessor.h",
"includeutils.cpp",
- "includeutils.h"
+ "includeutils.h",
+ "cppcodemodelsettings.cpp",
+ "cppcodemodelsettings.h",
+ "cppcodemodelsettingspage.cpp",
+ "cppcodemodelsettingspage.h",
+ "cppcodemodelsettingspage.ui"
]
Group {
name: "Tests"
- condition: Defaults.testsEnabled(qbs)
+ condition: project.testsEnabled
files: [
"cppcodegen_test.cpp",
"cppcompletion_test.cpp",
+ "cppheadersource_test.cpp",
"cppmodelmanager_test.cpp",
"modelmanagertesthelper.cpp", "modelmanagertesthelper.h",
- "cpppointerdeclarationformatter_test.cpp"
+ "cpppointerdeclarationformatter_test.cpp",
+ "cpplocatorfilter_test.cpp",
+ "symbolsearcher_test.cpp",
+ "cpppreprocessor_test.cpp",
+ "cpppreprocessertesthelper.cpp", "cpppreprocessertesthelper.h"
]
cpp.defines: outer.concat(['SRCDIR="' + FileInfo.path(filePath) + '"'])
@@ -128,5 +145,6 @@ QtcPlugin {
Export {
Depends { name: "CPlusPlus" }
+ Depends { name: "Qt.concurrent" }
}
}
diff --git a/src/plugins/cpptools/cpptoolsconstants.h b/src/plugins/cpptools/cpptoolsconstants.h
index 746936d600..0fa5d036cd 100644
--- a/src/plugins/cpptools/cpptoolsconstants.h
+++ b/src/plugins/cpptools/cpptoolsconstants.h
@@ -43,18 +43,22 @@ const char TASK_SEARCH[] = "CppTools.Task.Search";
const char C_SOURCE_MIMETYPE[] = "text/x-csrc";
const char C_HEADER_MIMETYPE[] = "text/x-chdr";
const char CPP_SOURCE_MIMETYPE[] = "text/x-c++src";
-const char OBJECTIVE_CPP_SOURCE_MIMETYPE[] = "text/x-objcsrc";
+const char OBJECTIVE_C_SOURCE_MIMETYPE[] = "text/x-objcsrc";
+const char OBJECTIVE_CPP_SOURCE_MIMETYPE[] = "text/x-objc++src";
const char CPP_HEADER_MIMETYPE[] = "text/x-c++hdr";
// QSettings keys for use by the "New Class" wizards.
const char CPPTOOLS_SETTINGSGROUP[] = "CppTools";
const char LOWERCASE_CPPFILES_KEY[] = "LowerCaseFiles";
enum { lowerCaseFilesDefault = 1 };
+const char CPPTOOLS_MODEL_MANAGER_SUPPORTERS_KEY[] = "ModelManagerSupporters";
const char CPP_CODE_STYLE_SETTINGS_ID[] = "A.Code Style";
const char CPP_CODE_STYLE_SETTINGS_NAME[] = QT_TRANSLATE_NOOP("CppTools", "Code Style");
const char CPP_FILE_SETTINGS_ID[] = "B.File Naming";
const char CPP_FILE_SETTINGS_NAME[] = QT_TRANSLATE_NOOP("CppTools", "File Naming");
+const char CPP_CODE_MODEL_SETTINGS_ID[] = "C.Code Model";
+const char CPP_CODE_MODEL_SETTINGS_NAME[] = QT_TRANSLATE_NOOP("CppTools", "Code Model");
const char CPP_SETTINGS_CATEGORY[] = "I.C++";
const char CPP_SETTINGS_TR_CATEGORY[] = QT_TRANSLATE_NOOP("CppTools", "C++");
const char SETTINGS_CATEGORY_CPP_ICON[] = ":/core/images/category_cpp.png";
diff --git a/src/plugins/cpptools/cpptoolseditorsupport.cpp b/src/plugins/cpptools/cpptoolseditorsupport.cpp
index 86efe3bd26..fc4d64b3c9 100644
--- a/src/plugins/cpptools/cpptoolseditorsupport.cpp
+++ b/src/plugins/cpptools/cpptoolseditorsupport.cpp
@@ -27,6 +27,7 @@
**
****************************************************************************/
+#include "cppcompletionassistprovider.h"
#include "cpptoolseditorsupport.h"
#include "cppmodelmanager.h"
#include "cpplocalsymbols.h"
@@ -74,11 +75,10 @@ protected:
if (_functionDefinition)
return false;
- else if (FunctionDefinitionAST *def = ast->asFunctionDefinition()) {
+ if (FunctionDefinitionAST *def = ast->asFunctionDefinition())
return checkDeclaration(def);
- }
- else if (ObjCMethodDeclarationAST *method = ast->asObjCMethodDeclaration()) {
+ if (ObjCMethodDeclarationAST *method = ast->asObjCMethodDeclaration()) {
if (method->function_body)
return checkDeclaration(method);
}
@@ -118,6 +118,7 @@ CppEditorSupport::CppEditorSupport(CppModelManager *modelManager, BaseTextEditor
, m_initialized(false)
, m_lastHighlightRevision(0)
, m_highlightingSupport(modelManager->highlightingSupport(textEditor))
+ , m_completionAssistProvider(0)
{
connect(m_modelManager, SIGNAL(documentUpdated(CPlusPlus::Document::Ptr)),
this, SLOT(onDocumentUpdated(CPlusPlus::Document::Ptr)));
@@ -163,15 +164,15 @@ CppEditorSupport::~CppEditorSupport()
QString CppEditorSupport::fileName() const
{
- return m_textEditor->document()->fileName();
+ return m_textEditor->document()->filePath();
}
-QString CppEditorSupport::contents() const
+QByteArray CppEditorSupport::contents() const
{
const int editorRev = editorRevision();
if (m_cachedContentsEditorRevision != editorRev && !m_fileIsBeingReloaded) {
m_cachedContentsEditorRevision = editorRev;
- m_cachedContents = m_textEditor->textDocument()->contents();
+ m_cachedContents = m_textEditor->textDocument()->contents().toUtf8();
}
return m_cachedContents;
@@ -193,6 +194,13 @@ void CppEditorSupport::setExtraDiagnostics(const QString &key,
emit diagnosticsChanged();
}
+void CppEditorSupport::setIfdefedOutBlocks(const QList<BlockRange> &ifdefedOutBlocks)
+{
+ m_editorUpdates.ifdefedOutBlocks = ifdefedOutBlocks;
+
+ emit diagnosticsChanged();
+}
+
bool CppEditorSupport::initialized()
{
return m_initialized;
@@ -223,6 +231,11 @@ void CppEditorSupport::recalculateSemanticInfoDetached(bool force)
startHighlighting();
}
+CppCompletionAssistProvider *CppEditorSupport::completionAssistProvider() const
+{
+ return m_completionAssistProvider;
+}
+
void CppEditorSupport::updateDocument()
{
m_revision = editorRevision();
@@ -246,7 +259,7 @@ void CppEditorSupport::updateDocumentNow()
if (m_highlightingSupport && !m_highlightingSupport->requiresSemanticInfo())
startHighlighting();
- const QStringList sourceFiles(m_textEditor->document()->fileName());
+ const QStringList sourceFiles(m_textEditor->document()->filePath());
m_documentParser = m_modelManager->updateSourceFiles(sourceFiles);
}
}
@@ -263,11 +276,13 @@ void CppEditorSupport::onDocumentUpdated(Document::Ptr doc)
return; // outdated content, wait for a new document to be parsed
// Update the ifdeffed-out blocks:
- QList<Document::Block> skippedBlocks = doc->skippedBlocks();
- m_editorUpdates.ifdefedOutBlocks.clear();
- m_editorUpdates.ifdefedOutBlocks.reserve(skippedBlocks.size());
- foreach (const Document::Block &block, skippedBlocks) {
- m_editorUpdates.ifdefedOutBlocks.append(BlockRange(block.begin(), block.end()));
+ if (m_highlightingSupport && !m_highlightingSupport->hightlighterHandlesIfdefedOutBlocks()) {
+ QList<Document::Block> skippedBlocks = doc->skippedBlocks();
+ QList<BlockRange> ifdefedOutBlocks;
+ ifdefedOutBlocks.reserve(skippedBlocks.size());
+ foreach (const Document::Block &block, skippedBlocks)
+ ifdefedOutBlocks.append(BlockRange(block.begin(), block.end()));
+ setIfdefedOutBlocks(ifdefedOutBlocks);
}
if (m_highlightingSupport && !m_highlightingSupport->hightlighterHandlesDiagnostics()) {
@@ -277,7 +292,7 @@ void CppEditorSupport::onDocumentUpdated(Document::Ptr doc)
}
// update semantic info in a future
- if (! m_initialized ||
+ if (!m_initialized ||
(m_textEditor->widget()->isVisible()
&& (m_lastSemanticInfo.doc.isNull()
|| m_lastSemanticInfo.doc->translationUnit()->ast() == 0
@@ -297,7 +312,7 @@ void CppEditorSupport::startHighlighting()
// Start highlighting only if the editor is or would be visible
// (in case another mode is active) in the edit mode.
- if (!Core::EditorManager::instance()->visibleEditors().contains(m_textEditor))
+ if (!Core::EditorManager::visibleEditors().contains(m_textEditor))
return;
if (m_highlightingSupport->requiresSemanticInfo()) {
@@ -374,7 +389,7 @@ void CppEditorSupport::onDiagnosticsChanged()
c.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, m.length());
} else {
for (int i = 0; i < text.size(); ++i) {
- if (! text.at(i).isSpace()) {
+ if (!text.at(i).isSpace()) {
c.setPosition(c.position() + i);
break;
}
@@ -416,7 +431,7 @@ SemanticInfo::Source CppEditorSupport::currentSource(bool force)
const Snapshot snapshot = m_modelManager->snapshot();
- QString code;
+ QByteArray code;
if (force || m_lastSemanticInfo.revision != editorRevision())
code = contents(); // get the source code only when needed.
@@ -512,6 +527,8 @@ void CppEditorSupport::onMimeTypeChanged()
connect(this, SIGNAL(semanticInfoUpdated(CppTools::SemanticInfo)),
this, SLOT(startHighlighting()));
+ m_completionAssistProvider = m_modelManager->completionAssistProvider(m_textEditor);
+
updateDocumentNow();
}
diff --git a/src/plugins/cpptools/cpptoolseditorsupport.h b/src/plugins/cpptools/cpptoolseditorsupport.h
index f3bce1b546..46e9ee3d51 100644
--- a/src/plugins/cpptools/cpptoolseditorsupport.h
+++ b/src/plugins/cpptools/cpptoolseditorsupport.h
@@ -50,6 +50,8 @@ class ITextMark;
namespace CppTools {
+class CppCompletionAssistProvider;
+
/**
* \brief The CppEditorSupport class oversees the actions that happen when a C++ text editor updates
* its document.
@@ -86,17 +88,20 @@ class CPPTOOLS_EXPORT CppEditorSupport: public QObject
{
Q_OBJECT
+ typedef TextEditor::BlockRange BlockRange;
+
public:
CppEditorSupport(Internal::CppModelManager *modelManager, TextEditor::BaseTextEditor *textEditor);
virtual ~CppEditorSupport();
QString fileName() const;
- QString contents() const;
+ QByteArray contents() const;
unsigned editorRevision() const;
void setExtraDiagnostics(const QString &key,
const QList<CPlusPlus::Document::DiagnosticMessage> &messages);
+ void setIfdefedOutBlocks(const QList<BlockRange> &ifdefedOutBlocks);
/// True after the document was parsed/updated for the first time
/// and the first semantic info calculation was started.
@@ -112,6 +117,8 @@ public:
/// \param force do not check if the old semantic info is still valid
void recalculateSemanticInfoDetached(bool force = false);
+ CppCompletionAssistProvider *completionAssistProvider() const;
+
signals:
void documentUpdated();
void diagnosticsChanged();
@@ -136,7 +143,6 @@ private slots:
void updateEditorNow();
private:
- typedef TextEditor::BaseTextEditorWidget::BlockRange BlockRange;
struct EditorUpdates {
EditorUpdates()
: revision(-1)
@@ -167,7 +173,7 @@ private:
QFuture<void> m_documentParser;
// content caching
- mutable QString m_cachedContents;
+ mutable QByteArray m_cachedContents;
mutable int m_cachedContentsEditorRevision;
bool m_fileIsBeingReloaded;
@@ -187,6 +193,9 @@ private:
unsigned m_lastHighlightRevision;
QFuture<TextEditor::HighlightingResult> m_highlighter;
QScopedPointer<CppTools::CppHighlightingSupport> m_highlightingSupport;
+
+ // Completion:
+ CppCompletionAssistProvider *m_completionAssistProvider;
};
} // namespace CppTools
diff --git a/src/plugins/cpptools/cpptoolsplugin.cpp b/src/plugins/cpptools/cpptoolsplugin.cpp
index 7f2bdbd24c..3d84020d06 100644
--- a/src/plugins/cpptools/cpptoolsplugin.cpp
+++ b/src/plugins/cpptools/cpptoolsplugin.cpp
@@ -30,6 +30,7 @@
#include "cpptoolsconstants.h"
#include "cpptoolsplugin.h"
#include "cppfilesettingspage.h"
+#include "cppcodemodelsettingspage.h"
#include "cppcodestylesettingspage.h"
#include "cppclassesfilter.h"
#include "cppfunctionsfilter.h"
@@ -40,6 +41,7 @@
#include "cpptoolssettings.h"
#include "cpptoolsreuse.h"
#include "cppprojectfile.h"
+#include "cpplocatordata.h"
#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/actionmanager/actionmanager.h>
@@ -51,6 +53,9 @@
#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
+#ifdef Q_OS_WIN
+#include <utils/winutils.h>
+#endif
#include <QtPlugin>
#include <QFileInfo>
@@ -59,6 +64,7 @@
#include <QMenu>
#include <QAction>
+using namespace Core;
using namespace CPlusPlus;
namespace CppTools {
@@ -69,8 +75,9 @@ enum { debug = 0 };
static CppToolsPlugin *m_instance = 0;
static QHash<QString, QString> m_headerSourceMapping;
-CppToolsPlugin::CppToolsPlugin() :
- m_fileSettings(new CppFileSettings)
+CppToolsPlugin::CppToolsPlugin()
+ : m_fileSettings(new CppFileSettings)
+ , m_codeModelSettings(new CppCodeModelSettings)
{
m_instance = this;
}
@@ -86,6 +93,21 @@ CppToolsPlugin *CppToolsPlugin::instance()
return m_instance;
}
+void CppToolsPlugin::clearHeaderSourceCache()
+{
+ m_headerSourceMapping.clear();
+}
+
+const QStringList &CppToolsPlugin::headerSearchPaths()
+{
+ return m_instance->m_fileSettings->headerSearchPaths;
+}
+
+const QStringList &CppToolsPlugin::sourceSearchPaths()
+{
+ return m_instance->m_fileSettings->sourceSearchPaths;
+}
+
bool CppToolsPlugin::initialize(const QStringList &arguments, QString *error)
{
Q_UNUSED(arguments)
@@ -95,39 +117,41 @@ bool CppToolsPlugin::initialize(const QStringList &arguments, QString *error)
// Objects
CppModelManager *modelManager = CppModelManager::instance();
- Core::VcsManager *vcsManager = Core::ICore::vcsManager();
- connect(vcsManager, SIGNAL(repositoryChanged(QString)),
+ connect(VcsManager::instance(), SIGNAL(repositoryChanged(QString)),
modelManager, SLOT(updateModifiedSourceFiles()));
- connect(Core::DocumentManager::instance(), SIGNAL(filesChangedInternally(QStringList)),
+ connect(DocumentManager::instance(), SIGNAL(filesChangedInternally(QStringList)),
modelManager, SLOT(updateSourceFiles(QStringList)));
- addAutoReleasedObject(new CppLocatorFilter(modelManager));
- addAutoReleasedObject(new CppClassesFilter(modelManager));
- addAutoReleasedObject(new CppFunctionsFilter(modelManager));
- addAutoReleasedObject(new CppCurrentDocumentFilter(modelManager, Core::ICore::editorManager()));
+ CppLocatorData *locatorData = new CppLocatorData(modelManager);
+ addAutoReleasedObject(locatorData);
+ addAutoReleasedObject(new CppLocatorFilter(locatorData));
+ addAutoReleasedObject(new CppClassesFilter(locatorData));
+ addAutoReleasedObject(new CppFunctionsFilter(locatorData));
+ addAutoReleasedObject(new CppCurrentDocumentFilter(modelManager));
addAutoReleasedObject(new CppFileSettingsPage(m_fileSettings));
+// addAutoReleasedObject(new CppCodeModelSettingsPage(m_codeModelSettings));
addAutoReleasedObject(new SymbolsFindFilter(modelManager));
addAutoReleasedObject(new CppCodeStyleSettingsPage);
// Menus
- Core::ActionContainer *mtools = Core::ActionManager::actionContainer(Core::Constants::M_TOOLS);
- Core::ActionContainer *mcpptools = Core::ActionManager::createMenu(CppTools::Constants::M_TOOLS_CPP);
+ ActionContainer *mtools = ActionManager::actionContainer(Core::Constants::M_TOOLS);
+ ActionContainer *mcpptools = ActionManager::createMenu(CppTools::Constants::M_TOOLS_CPP);
QMenu *menu = mcpptools->menu();
menu->setTitle(tr("&C++"));
menu->setEnabled(true);
mtools->addMenu(mcpptools);
// Actions
- Core::Context context(CppEditor::Constants::C_CPPEDITOR);
+ Context context(CppEditor::Constants::C_CPPEDITOR);
QAction *switchAction = new QAction(tr("Switch Header/Source"), this);
- Core::Command *command = Core::ActionManager::registerAction(switchAction, Constants::SWITCH_HEADER_SOURCE, context, true);
+ Command *command = ActionManager::registerAction(switchAction, Constants::SWITCH_HEADER_SOURCE, context, true);
command->setDefaultKeySequence(QKeySequence(Qt::Key_F4));
mcpptools->addAction(command);
connect(switchAction, SIGNAL(triggered()), this, SLOT(switchHeaderSource()));
QAction *openInNextSplitAction = new QAction(tr("Open Corresponding Header/Source in Next Split"), this);
- command = Core::ActionManager::registerAction(openInNextSplitAction, Constants::OPEN_HEADER_SOURCE_IN_NEXT_SPLIT, context, true);
+ command = ActionManager::registerAction(openInNextSplitAction, Constants::OPEN_HEADER_SOURCE_IN_NEXT_SPLIT, context, true);
command->setDefaultKeySequence(QKeySequence(Utils::HostOsInfo::isMacHost()
? tr("Meta+E, F4")
: tr("Ctrl+E, F4")));
@@ -141,9 +165,10 @@ void CppToolsPlugin::extensionsInitialized()
{
// The Cpp editor plugin, which is loaded later on, registers the Cpp mime types,
// so, apply settings here
- m_fileSettings->fromSettings(Core::ICore::settings());
+ m_fileSettings->fromSettings(ICore::settings());
if (!m_fileSettings->applySuffixesToMimeDB())
qWarning("Unable to apply cpp suffixes to mime database (cpp mime types not found).\n");
+ m_codeModelSettings->fromSettings(ICore::settings());
}
ExtensionSystem::IPlugin::ShutdownFlag CppToolsPlugin::aboutToShutdown()
@@ -151,20 +176,25 @@ ExtensionSystem::IPlugin::ShutdownFlag CppToolsPlugin::aboutToShutdown()
return SynchronousShutdown;
}
+QSharedPointer<CppCodeModelSettings> CppToolsPlugin::codeModelSettings() const
+{
+ return m_codeModelSettings;
+}
+
void CppToolsPlugin::switchHeaderSource()
{
QString otherFile = correspondingHeaderOrSource(
- Core::EditorManager::currentEditor()->document()->fileName());
+ EditorManager::currentDocument()->filePath());
if (!otherFile.isEmpty())
- Core::EditorManager::openEditor(otherFile);
+ EditorManager::openEditor(otherFile);
}
void CppToolsPlugin::switchHeaderSourceInNextSplit()
{
QString otherFile = correspondingHeaderOrSource(
- Core::EditorManager::currentEditor()->document()->fileName());
+ EditorManager::currentDocument()->filePath());
if (!otherFile.isEmpty())
- Core::EditorManager::openEditor(otherFile, Core::Id(), Core::EditorManager::OpenInOtherSplit);
+ EditorManager::openEditor(otherFile, Id(), EditorManager::OpenInOtherSplit);
}
static QStringList findFilesInProject(const QString &name,
@@ -192,24 +222,24 @@ static QStringList findFilesInProject(const QString &name,
// source belonging to a header and vice versa
static QStringList matchingCandidateSuffixes(ProjectFile::Kind kind)
{
- Core::MimeDatabase *md = Core::ICore::instance()->mimeDatabase();
switch (kind) {
// Note that C/C++ headers are undistinguishable
case ProjectFile::CHeader:
case ProjectFile::CXXHeader:
case ProjectFile::ObjCHeader:
case ProjectFile::ObjCXXHeader:
- return md->findByType(QLatin1String(Constants::C_SOURCE_MIMETYPE)).suffixes()
- + md->findByType(QLatin1String(Constants::CPP_SOURCE_MIMETYPE)).suffixes()
- + md->findByType(QLatin1String(Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE)).suffixes();
+ return MimeDatabase::findByType(QLatin1String(Constants::C_SOURCE_MIMETYPE)).suffixes()
+ + MimeDatabase::findByType(QLatin1String(Constants::CPP_SOURCE_MIMETYPE)).suffixes()
+ + MimeDatabase::findByType(QLatin1String(Constants::OBJECTIVE_C_SOURCE_MIMETYPE)).suffixes()
+ + MimeDatabase::findByType(QLatin1String(Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE)).suffixes();
case ProjectFile::CSource:
case ProjectFile::ObjCSource:
- return md->findByType(QLatin1String(Constants::C_HEADER_MIMETYPE)).suffixes();
+ return MimeDatabase::findByType(QLatin1String(Constants::C_HEADER_MIMETYPE)).suffixes();
case ProjectFile::CXXSource:
case ProjectFile::ObjCXXSource:
case ProjectFile::CudaSource:
case ProjectFile::OpenCLSource:
- return md->findByType(QLatin1String(Constants::CPP_HEADER_MIMETYPE)).suffixes();
+ return MimeDatabase::findByType(QLatin1String(Constants::CPP_HEADER_MIMETYPE)).suffixes();
default:
return QStringList();
}
@@ -228,6 +258,14 @@ static QStringList baseNameWithAllSuffixes(const QString &baseName, const QStrin
return result;
}
+static QStringList baseDirWithAllDirectories(const QDir &baseDir, const QStringList &directories)
+{
+ QStringList result;
+ foreach (const QString &dir, directories)
+ result << QDir::cleanPath(baseDir.absoluteFilePath(dir));
+ return result;
+}
+
static int commonStringLength(const QString &s1, const QString &s2)
{
int length = qMin(s1.length(), s2.length());
@@ -304,15 +342,28 @@ QString correspondingHeaderOrSource(const QString &fileName, bool *wasHeader)
}
const QDir absoluteDir = fi.absoluteDir();
-
- // Try to find a file in the same directory first
- foreach (const QString &candidateFileName, candidateFileNames) {
- const QFileInfo candidateFi(absoluteDir, candidateFileName);
- if (candidateFi.isFile()) {
- m_headerSourceMapping[fi.absoluteFilePath()] = candidateFi.absoluteFilePath();
- if (!isHeader || !baseName.endsWith(privateHeaderSuffix))
- m_headerSourceMapping[candidateFi.absoluteFilePath()] = fi.absoluteFilePath();
- return candidateFi.absoluteFilePath();
+ QStringList candidateDirs(absoluteDir.absolutePath());
+ // If directory is not root, try matching against its siblings
+ const QStringList searchPaths = isHeader ? m_instance->sourceSearchPaths()
+ : m_instance->headerSearchPaths();
+ candidateDirs += baseDirWithAllDirectories(absoluteDir, searchPaths);
+
+ // Try to find a file in the same or sibling directories first
+ foreach (const QString &candidateDir, candidateDirs) {
+ foreach (const QString &candidateFileName, candidateFileNames) {
+ const QString candidateFilePath = candidateDir + QLatin1Char('/') + candidateFileName;
+#ifdef Q_OS_WIN
+ const QString normalized = Utils::normalizePathName(candidateFilePath);
+#else
+ const QString normalized = candidateFilePath;
+#endif
+ const QFileInfo candidateFi(normalized);
+ if (candidateFi.isFile()) {
+ m_headerSourceMapping[fi.absoluteFilePath()] = candidateFi.absoluteFilePath();
+ if (!isHeader || !baseName.endsWith(privateHeaderSuffix))
+ m_headerSourceMapping[candidateFi.absoluteFilePath()] = fi.absoluteFilePath();
+ return candidateFi.absoluteFilePath();
+ }
}
}
diff --git a/src/plugins/cpptools/cpptoolsplugin.h b/src/plugins/cpptools/cpptoolsplugin.h
index f16591f100..4f7653ddaf 100644
--- a/src/plugins/cpptools/cpptoolsplugin.h
+++ b/src/plugins/cpptools/cpptoolsplugin.h
@@ -49,6 +49,7 @@ namespace Internal {
class CppModelManager;
struct CppFileSettings;
+class CppCodeModelSettings;
class CPPTOOLS_EXPORT CppToolsPlugin : public ExtensionSystem::IPlugin
{
@@ -60,11 +61,16 @@ public:
~CppToolsPlugin();
static CppToolsPlugin *instance();
+ static const QStringList &headerSearchPaths();
+ static const QStringList &sourceSearchPaths();
+ static void clearHeaderSourceCache();
bool initialize(const QStringList &arguments, QString *errorMessage);
void extensionsInitialized();
ShutdownFlag aboutToShutdown();
+ QSharedPointer<CppCodeModelSettings> codeModelSettings() const;
+
public slots:
void switchHeaderSource();
void switchHeaderSourceInNextSplit();
@@ -147,6 +153,36 @@ private slots:
void test_completion_recursive_using_declarations1();
void test_completion_recursive_using_declarations2();
void test_completion_recursive_using_typedef_declarations();
+ void test_completion_prefix_first_QTCREATORBUG_8737();
+ void test_completion_prefix_first_QTCREATORBUG_9236();
+
+ void test_completion_class_declaration_inside_function_or_block_QTCREATORBUG3620();
+ void test_completion_class_declaration_inside_function_or_block_QTCREATORBUG3620_data();
+ void test_completion_namespace_alias_inside_function_or_block_QTCREATORBUG166();
+ void test_completion_namespace_alias_inside_function_or_block_QTCREATORBUG166_data();
+ void test_completion_class_declaration_inside_function_or_block_QTCREATORBUG3620_static_member();
+ void test_completion_enum_inside_block_inside_function_QTCREATORBUG5456();
+ void test_completion_enum_inside_function_QTCREATORBUG5456();
+
+ void test_completion_template_parameter_defined_inside_scope_of_declaration_QTCREATORBUG9169_1();
+ void test_completion_template_parameter_defined_inside_scope_of_declaration_QTCREATORBUG9169_2();
+ void test_completion_template_parameter_defined_inside_scope_of_declaration_QTCREATORBUG8852_1();
+ void test_completion_template_parameter_defined_inside_scope_of_declaration_QTCREATORBUG8852_2();
+ void test_completion_template_parameter_defined_inside_scope_of_declaration_QTCREATORBUG8852_3();
+
+ //lambda
+ void test_completion_lambdaCalls_1();
+ void test_completion_lambdaCalls_2();
+ void test_completion_lambdaCalls_3();
+ void test_completion_lambdaCalls_4();
+ void test_completion_lambdaCalls_5();
+
+ void test_completion_local_type_and_member_1();
+ void test_completion_local_type_and_member_2();
+ void test_completion_local_type_and_member_3();
+ void test_completion_local_type_and_member_4();
+ void test_completion_local_type_and_member_5();
+ void test_completion_local_type_and_member_6();
void test_completion_signals_hide_QPrivateSignal();
@@ -161,13 +197,30 @@ private slots:
void test_format_pointerdeclaration_macros();
void test_format_pointerdeclaration_macros_data();
+ void test_cpppreprocessor_includes();
+
void test_modelmanager_paths_are_clean();
void test_modelmanager_framework_headers();
void test_modelmanager_refresh_also_includes_of_project_files();
void test_modelmanager_refresh_several_times();
void test_modelmanager_refresh_test_for_changes();
+ void test_modelmanager_refresh_added_and_purge_removed();
+ void test_modelmanager_refresh_timeStampModified_if_sourcefiles_change();
+ void test_modelmanager_refresh_timeStampModified_if_sourcefiles_change_data();
void test_modelmanager_snapshot_after_two_projects();
void test_modelmanager_extraeditorsupport_uiFiles();
+ void test_modelmanager_gc_if_last_cppeditor_closed();
+ void test_modelmanager_dont_gc_opened_files();
+
+ void test_cpplocatorfilters_CppLocatorFilter();
+ void test_cpplocatorfilters_CppLocatorFilter_data();
+ void test_cpplocatorfilters_CppCurrentDocumentFilter();
+
+ void test_builtinsymbolsearcher();
+ void test_builtinsymbolsearcher_data();
+
+ void test_headersource_data();
+ void test_headersource();
private:
void test_completion();
@@ -175,6 +228,7 @@ private:
private:
QSharedPointer<CppFileSettings> m_fileSettings;
+ QSharedPointer<CppCodeModelSettings> m_codeModelSettings;
CppToolsSettings *m_settings;
};
diff --git a/src/plugins/cpptools/cpptoolssettings.cpp b/src/plugins/cpptools/cpptoolssettings.cpp
index 2f034bac91..2385e4aa53 100644
--- a/src/plugins/cpptools/cpptoolssettings.cpp
+++ b/src/plugins/cpptools/cpptoolssettings.cpp
@@ -50,7 +50,7 @@ static const char idKey[] = "CppGlobal";
using namespace CppTools;
using namespace CppTools::Internal;
-using TextEditor::TabSettings;
+using namespace TextEditor;
namespace CppTools {
namespace Internal {
@@ -89,23 +89,21 @@ CppToolsSettings::CppToolsSettings(QObject *parent)
this,
SIGNAL(commentsSettingsChanged(CppTools::CommentsSettings)));
- TextEditor::TextEditorSettings *textEditorSettings = TextEditor::TextEditorSettings::instance();
-
// code style factory
- TextEditor::ICodeStylePreferencesFactory *factory = new CppTools::CppCodeStylePreferencesFactory();
- textEditorSettings->registerCodeStyleFactory(factory);
+ ICodeStylePreferencesFactory *factory = new CppTools::CppCodeStylePreferencesFactory();
+ TextEditorSettings::registerCodeStyleFactory(factory);
// code style pool
- TextEditor::CodeStylePool *pool = new TextEditor::CodeStylePool(factory, this);
- textEditorSettings->registerCodeStylePool(Constants::CPP_SETTINGS_ID, pool);
+ CodeStylePool *pool = new CodeStylePool(factory, this);
+ TextEditorSettings::registerCodeStylePool(Constants::CPP_SETTINGS_ID, pool);
// global code style settings
d->m_globalCodeStyle = new CppCodeStylePreferences(this);
d->m_globalCodeStyle->setDelegatingPool(pool);
d->m_globalCodeStyle->setDisplayName(tr("Global", "Settings"));
- d->m_globalCodeStyle->setId(QLatin1String(idKey));
+ d->m_globalCodeStyle->setId(idKey);
pool->addCodeStyle(d->m_globalCodeStyle);
- textEditorSettings->registerCodeStyle(CppTools::Constants::CPP_SETTINGS_ID, d->m_globalCodeStyle);
+ TextEditorSettings::registerCodeStyle(CppTools::Constants::CPP_SETTINGS_ID, d->m_globalCodeStyle);
/*
For every language we have exactly 1 pool. The pool contains:
@@ -135,7 +133,7 @@ CppToolsSettings::CppToolsSettings(QObject *parent)
// built-in settings
// Qt style
CppCodeStylePreferences *qtCodeStyle = new CppCodeStylePreferences();
- qtCodeStyle->setId(QLatin1String("qt"));
+ qtCodeStyle->setId("qt");
qtCodeStyle->setDisplayName(tr("Qt"));
qtCodeStyle->setReadOnly(true);
TabSettings qtTabSettings;
@@ -148,7 +146,7 @@ CppToolsSettings::CppToolsSettings(QObject *parent)
// GNU style
CppCodeStylePreferences *gnuCodeStyle = new CppCodeStylePreferences();
- gnuCodeStyle->setId(QLatin1String("gnu"));
+ gnuCodeStyle->setId("gnu");
gnuCodeStyle->setDisplayName(tr("GNU"));
gnuCodeStyle->setReadOnly(true);
TabSettings gnuTabSettings;
@@ -203,15 +201,14 @@ CppToolsSettings::CppToolsSettings(QObject *parent)
QString(), s, &legacyTabSettings);
} else {
// delegating to global
- legacyTabSettings = textEditorSettings->codeStyle()->currentTabSettings();
+ legacyTabSettings = TextEditorSettings::codeStyle()->currentTabSettings();
}
// create custom code style out of old settings
QVariant v;
v.setValue(legacyCodeStyleSettings);
TextEditor::ICodeStylePreferences *oldCreator = pool->createCodeStyle(
- QLatin1String("legacy"), legacyTabSettings,
- v, tr("Old Creator"));
+ "legacy", legacyTabSettings, v, tr("Old Creator"));
// change the current delegate and save
d->m_globalCodeStyle->setCurrentDelegate(oldCreator);
@@ -224,28 +221,19 @@ CppToolsSettings::CppToolsSettings(QObject *parent)
// mimetypes to be handled
- textEditorSettings->registerMimeTypeForLanguageId(
- QLatin1String(Constants::C_SOURCE_MIMETYPE),
- Constants::CPP_SETTINGS_ID);
- textEditorSettings->registerMimeTypeForLanguageId(
- QLatin1String(Constants::C_HEADER_MIMETYPE),
- Constants::CPP_SETTINGS_ID);
- textEditorSettings->registerMimeTypeForLanguageId(
- QLatin1String(Constants::CPP_SOURCE_MIMETYPE),
- Constants::CPP_SETTINGS_ID);
- textEditorSettings->registerMimeTypeForLanguageId(
- QLatin1String(Constants::CPP_HEADER_MIMETYPE),
- Constants::CPP_SETTINGS_ID);
+ TextEditorSettings::registerMimeTypeForLanguageId(Constants::C_SOURCE_MIMETYPE, Constants::CPP_SETTINGS_ID);
+ TextEditorSettings::registerMimeTypeForLanguageId(Constants::C_HEADER_MIMETYPE, Constants::CPP_SETTINGS_ID);
+ TextEditorSettings::registerMimeTypeForLanguageId(Constants::CPP_SOURCE_MIMETYPE, Constants::CPP_SETTINGS_ID);
+ TextEditorSettings::registerMimeTypeForLanguageId(Constants::CPP_HEADER_MIMETYPE, Constants::CPP_SETTINGS_ID);
}
CppToolsSettings::~CppToolsSettings()
{
ExtensionSystem::PluginManager::removeObject(d->m_completionSettingsPage);
- TextEditor::TextEditorSettings *textEditorSettings = TextEditor::TextEditorSettings::instance();
- textEditorSettings->unregisterCodeStyle(Constants::CPP_SETTINGS_ID);
- textEditorSettings->unregisterCodeStylePool(Constants::CPP_SETTINGS_ID);
- textEditorSettings->unregisterCodeStyleFactory(Constants::CPP_SETTINGS_ID);
+ TextEditorSettings::unregisterCodeStyle(Constants::CPP_SETTINGS_ID);
+ TextEditorSettings::unregisterCodeStylePool(Constants::CPP_SETTINGS_ID);
+ TextEditorSettings::unregisterCodeStyleFactory(Constants::CPP_SETTINGS_ID);
delete d;
diff --git a/src/plugins/cpptools/includeutils.cpp b/src/plugins/cpptools/includeutils.cpp
index da0e3ce3db..9de8f5fe76 100644
--- a/src/plugins/cpptools/includeutils.cpp
+++ b/src/plugins/cpptools/includeutils.cpp
@@ -42,6 +42,8 @@
#include <QTextBlock>
#include <QTextDocument>
+#include <algorithm>
+
using namespace CPlusPlus;
using namespace CppTools;
using namespace CppTools::IncludeUtils;
@@ -275,13 +277,11 @@ QList<IncludeGroup> IncludeGroup::detectIncludeGroupsByNewLines(QList<Document::
if (isFirst) {
isFirst = false;
currentIncludes << include;
- }
// Include belongs to current group
- else if (lastLine + 1 == include.line()) {
+ } else if (lastLine + 1 == include.line()) {
currentIncludes << include;
- }
// Include is member of new group
- else {
+ } else {
result << IncludeGroup(currentIncludes);
currentIncludes.clear();
currentIncludes << include;
@@ -310,13 +310,11 @@ QList<IncludeGroup> IncludeGroup::detectIncludeGroupsByIncludeDir(const QList<In
if (isFirst) {
isFirst = false;
currentIncludes << include;
- }
// Include belongs to current group
- else if (lastDir == currentDirPrefix) {
+ } else if (lastDir == currentDirPrefix) {
currentIncludes << include;
- }
// Include is member of new group
- else {
+ } else {
result << IncludeGroup(currentIncludes);
currentIncludes.clear();
currentIncludes << include;
@@ -345,13 +343,11 @@ QList<IncludeGroup> IncludeGroup::detectIncludeGroupsByIncludeType(const QList<I
if (isFirst) {
isFirst = false;
currentIncludes << include;
- }
// Include belongs to current group
- else if (lastIncludeType == currentIncludeType) {
+ } else if (lastIncludeType == currentIncludeType) {
currentIncludes << include;
- }
// Include is member of new group
- else {
+ } else {
result << IncludeGroup(currentIncludes);
currentIncludes.clear();
currentIncludes << include;
diff --git a/src/plugins/cpptools/insertionpointlocator.cpp b/src/plugins/cpptools/insertionpointlocator.cpp
index 48fc824f15..21dc5138c9 100644
--- a/src/plugins/cpptools/insertionpointlocator.cpp
+++ b/src/plugins/cpptools/insertionpointlocator.cpp
@@ -356,7 +356,7 @@ class FindMethodDefinitionInsertPoint : protected ASTVisitor
{
QList<const Identifier *> _namespaceNames;
int _currentDepth;
- HighestValue<int, int> _bestToken;
+ HighestValue<int, unsigned> _bestToken;
public:
FindMethodDefinitionInsertPoint(TranslationUnit *translationUnit)
@@ -366,10 +366,10 @@ public:
void operator()(Symbol *decl, unsigned *line, unsigned *column)
{
// default to end of file
- _bestToken.maybeSet(-1, translationUnit()->ast()->lastToken());
-
- if (translationUnit()->ast()->lastToken() >= 2) {
+ const unsigned lastToken = translationUnit()->ast()->lastToken();
+ _bestToken.maybeSet(-1, lastToken);
+ if (lastToken >= 2) {
QList<const Name *> names = LookupContext::fullyQualifiedName(decl);
foreach (const Name *name, names) {
const Identifier *id = name->asNameId();
@@ -381,7 +381,11 @@ public:
accept(translationUnit()->ast());
}
- translationUnit()->getTokenEndPosition(_bestToken.get(), line, column);
+
+ if (lastToken == _bestToken.get()) // No matching namespace found
+ translationUnit()->getTokenStartPosition(lastToken, line, column);
+ else // Insert at end of matching namespace
+ translationUnit()->getTokenEndPosition(_bestToken.get(), line, column);
}
protected:
diff --git a/src/plugins/cpptools/modelmanagertesthelper.cpp b/src/plugins/cpptools/modelmanagertesthelper.cpp
index 46f2a91723..4d7590e130 100644
--- a/src/plugins/cpptools/modelmanagertesthelper.cpp
+++ b/src/plugins/cpptools/modelmanagertesthelper.cpp
@@ -55,6 +55,7 @@ ModelManagerTestHelper::ModelManagerTestHelper(QObject *parent) :
connect(this, SIGNAL(aboutToRemoveProject(ProjectExplorer::Project*)), mm, SLOT(onAboutToRemoveProject(ProjectExplorer::Project*)));
connect(this, SIGNAL(projectAdded(ProjectExplorer::Project*)), mm, SLOT(onProjectAdded(ProjectExplorer::Project*)));
connect(mm, SIGNAL(sourceFilesRefreshed(QStringList)), this, SLOT(sourceFilesRefreshed(QStringList)));
+ connect(mm, SIGNAL(gcFinished()), this, SLOT(gcFinished()));
cleanup();
verifyClean();
@@ -74,6 +75,9 @@ void ModelManagerTestHelper::cleanup()
QList<ProjectInfo> pies = mm->projectInfos();
foreach (const ProjectInfo &pie, pies)
emit aboutToRemoveProject(pie.project().data());
+
+ if (!pies.isEmpty())
+ waitForFinishedGc();
}
void ModelManagerTestHelper::verifyClean()
@@ -108,9 +112,21 @@ QStringList ModelManagerTestHelper::waitForRefreshedSourceFiles()
return m_lastRefreshedSourceFiles;
}
+void ModelManagerTestHelper::waitForFinishedGc()
+{
+ m_gcFinished = false;
+
+ while (!m_gcFinished)
+ QCoreApplication::processEvents();
+}
void ModelManagerTestHelper::sourceFilesRefreshed(const QStringList &files)
{
m_lastRefreshedSourceFiles = files;
m_refreshHappened = true;
}
+
+void ModelManagerTestHelper::gcFinished()
+{
+ m_gcFinished = true;
+}
diff --git a/src/plugins/cpptools/modelmanagertesthelper.h b/src/plugins/cpptools/modelmanagertesthelper.h
index b2b042c445..d4ac671bc1 100644
--- a/src/plugins/cpptools/modelmanagertesthelper.h
+++ b/src/plugins/cpptools/modelmanagertesthelper.h
@@ -84,6 +84,7 @@ public:
Project *createProject(const QString &name);
QStringList waitForRefreshedSourceFiles();
+ void waitForFinishedGc();
signals:
void aboutToRemoveProject(ProjectExplorer::Project *project);
@@ -91,8 +92,10 @@ signals:
public slots:
void sourceFilesRefreshed(const QStringList &files);
+ void gcFinished();
private:
+ bool m_gcFinished;
bool m_refreshHappened;
QStringList m_lastRefreshedSourceFiles;
};
diff --git a/src/plugins/cpptools/searchsymbols.cpp b/src/plugins/cpptools/searchsymbols.cpp
index 1350888e0e..6f548710a4 100644
--- a/src/plugins/cpptools/searchsymbols.cpp
+++ b/src/plugins/cpptools/searchsymbols.cpp
@@ -42,9 +42,8 @@ SearchSymbols::SymbolTypes SearchSymbols::AllTypes =
| SymbolSearcher::Enums
| SymbolSearcher::Declarations;
-SearchSymbols::SearchSymbols():
- symbolsToSearchFor(SymbolSearcher::Classes | SymbolSearcher::Functions | SymbolSearcher::Enums),
- separateScope(false)
+SearchSymbols::SearchSymbols() :
+ symbolsToSearchFor(SymbolSearcher::Classes | SymbolSearcher::Functions | SymbolSearcher::Enums)
{
}
@@ -53,11 +52,6 @@ void SearchSymbols::setSymbolsToSearchFor(SymbolTypes types)
symbolsToSearchFor = types;
}
-void SearchSymbols::setSeparateScope(bool separateScope)
-{
- this->separateScope = separateScope;
-}
-
QList<ModelItemInfo> SearchSymbols::operator()(Document::Ptr doc, int sizeHint, const QString &scope)
{
QString previousScope = switchScope(scope);
@@ -89,9 +83,7 @@ bool SearchSymbols::visit(Enum *symbol)
QString name = symbolName(symbol);
QString scopedName = scopedSymbolName(name);
QString previousScope = switchScope(scopedName);
- appendItem(separateScope ? name : scopedName,
- separateScope ? previousScope : QString(),
- ModelItemInfo::Enum, symbol);
+ appendItem(name, QString(), previousScope, ModelItemInfo::Enum, symbol);
for (unsigned i = 0; i < symbol->memberCount(); ++i) {
accept(symbol->memberAt(i));
}
@@ -103,25 +95,9 @@ bool SearchSymbols::visit(Function *symbol)
{
if (!(symbolsToSearchFor & SymbolSearcher::Functions))
return false;
-
- QString extraScope;
- if (const Name *name = symbol->name()) {
- if (const QualifiedNameId *q = name->asQualifiedNameId()) {
- if (q->base())
- extraScope = overview.prettyName(q->base());
- }
- }
- QString fullScope = _scope;
- if (!_scope.isEmpty() && !extraScope.isEmpty())
- fullScope += QLatin1String("::");
- fullScope += extraScope;
QString name = symbolName(symbol);
- QString scopedName = scopedSymbolName(name);
- QString type = overview.prettyType(symbol->type(),
- separateScope ? symbol->unqualifiedName() : 0);
- appendItem(separateScope ? type : scopedName,
- separateScope ? fullScope : type,
- ModelItemInfo::Method, symbol);
+ QString type = overview.prettyType(symbol->type());
+ appendItem(name, type, _scope, ModelItemInfo::Method, symbol);
return false;
}
@@ -152,11 +128,8 @@ bool SearchSymbols::visit(Declaration *symbol)
}
QString name = symbolName(symbol);
- QString scopedName = scopedSymbolName(name);
- QString type = overview.prettyType(symbol->type(),
- separateScope ? symbol->unqualifiedName() : 0);
- appendItem(separateScope ? type : scopedName,
- separateScope ? _scope : type,
+ QString type = overview.prettyType(symbol->type());
+ appendItem(name, type, _scope,
symbol->type()->asFunctionType() ? ModelItemInfo::Method
: ModelItemInfo::Declaration,
symbol);
@@ -169,9 +142,7 @@ bool SearchSymbols::visit(Class *symbol)
QString scopedName = scopedSymbolName(name);
QString previousScope = switchScope(scopedName);
if (symbolsToSearchFor & SymbolSearcher::Classes) {
- appendItem(separateScope ? name : scopedName,
- separateScope ? previousScope : QString(),
- ModelItemInfo::Class, symbol);
+ appendItem(name, QString(), previousScope, ModelItemInfo::Class, symbol);
}
for (unsigned i = 0; i < symbol->memberCount(); ++i) {
accept(symbol->memberAt(i));
@@ -305,18 +276,13 @@ QString SearchSymbols::symbolName(const Symbol *symbol) const
return symbolName;
}
-void SearchSymbols::appendItem(const QString &name,
- const QString &info,
- ModelItemInfo::ItemType type,
+void SearchSymbols::appendItem(const QString &symbolName, const QString &symbolType,
+ const QString &symbolScope, ModelItemInfo::ItemType itemType,
Symbol *symbol)
{
- if (!symbol->name())
+ if (!symbol->name() || symbol->isGenerated())
return;
- QStringList fullyQualifiedName;
- foreach (const Name *name, LookupContext::fullyQualifiedName(symbol))
- fullyQualifiedName.append(findOrInsert(overview.prettyName(name)));
-
QString path = m_paths.value(symbol->fileId(), QString());
if (path.isEmpty()) {
path = QString::fromUtf8(symbol->fileName(), symbol->fileNameLength());
@@ -324,8 +290,10 @@ void SearchSymbols::appendItem(const QString &name,
}
const QIcon icon = icons.iconForSymbol(symbol);
- items.append(ModelItemInfo(findOrInsert(name), findOrInsert(info), type,
- fullyQualifiedName,
+ items.append(ModelItemInfo(findOrInsert(symbolName),
+ findOrInsert(symbolType),
+ findOrInsert(symbolScope),
+ itemType,
path,
symbol->line(),
symbol->column() - 1, // 1-based vs 0-based column
diff --git a/src/plugins/cpptools/searchsymbols.h b/src/plugins/cpptools/searchsymbols.h
index f811781bcb..e47b78b2ce 100644
--- a/src/plugins/cpptools/searchsymbols.h
+++ b/src/plugins/cpptools/searchsymbols.h
@@ -37,6 +37,8 @@
#include <cplusplus/Icons.h>
#include <cplusplus/Overview.h>
+#include <utils/fileutils.h>
+
#include <QIcon>
#include <QString>
#include <QSet>
@@ -58,15 +60,15 @@ struct CPPTOOLS_EXPORT ModelItemInfo
ModelItemInfo(const QString &symbolName,
const QString &symbolType,
+ const QString &symbolScope,
ItemType type,
- QStringList fullyQualifiedName,
const QString &fileName,
int line,
int column,
const QIcon &icon)
: symbolName(symbolName),
symbolType(symbolType),
- fullyQualifiedName(fullyQualifiedName),
+ symbolScope(symbolScope),
fileName(fileName),
icon(icon),
type(type),
@@ -77,17 +79,50 @@ struct CPPTOOLS_EXPORT ModelItemInfo
ModelItemInfo(const ModelItemInfo &otherInfo)
: symbolName(otherInfo.symbolName),
symbolType(otherInfo.symbolType),
- fullyQualifiedName(otherInfo.fullyQualifiedName),
+ symbolScope(otherInfo.symbolScope),
fileName(otherInfo.fileName),
icon(otherInfo.icon),
type(otherInfo.type),
line(otherInfo.line),
column(otherInfo.column)
- { }
+ { }
- QString symbolName;
+ QString scopedSymbolName() const
+ {
+ return symbolScope.isEmpty()
+ ? symbolName
+ : symbolScope + QLatin1String("::") + symbolName;
+ }
+
+ void unqualifiedNameAndScope(const QString &defaultName, QString *name, QString *scope) const
+ {
+ *name = defaultName;
+ *scope = symbolScope;
+ const QString qualifiedName = scopedSymbolName();
+ const int colonColonPosition = qualifiedName.lastIndexOf(QLatin1String("::"));
+ if (colonColonPosition != -1) {
+ *name = qualifiedName.mid(colonColonPosition + 2);
+ *scope = qualifiedName.left(colonColonPosition);
+ }
+ }
+
+ static QString representDeclaration(const QString &name, const QString &type)
+ {
+ if (type.isEmpty())
+ return QString();
+
+ const QString padding = type.endsWith(QLatin1Char('*'))
+ ? QString()
+ : QString(QLatin1Char(' '));
+ return type + padding + name;
+ }
+
+ QString shortNativeFilePath() const
+ { return Utils::FileUtils::shortNativePath(Utils::FileName::fromString(fileName)); }
+
+ QString symbolName; // as found in the code, therefore might be qualified
QString symbolType;
- QStringList fullyQualifiedName;
+ QString symbolScope;
QString fileName;
QIcon icon;
ItemType type;
@@ -106,7 +141,6 @@ public:
SearchSymbols();
void setSymbolsToSearchFor(SymbolTypes types);
- void setSeparateScope(bool separateScope);
QList<ModelItemInfo> operator()(CPlusPlus::Document::Ptr doc, int sizeHint = 500)
{ return operator()(doc, sizeHint, QString()); }
@@ -149,8 +183,9 @@ protected:
QString scopedSymbolName(const QString &symbolName) const;
QString scopedSymbolName(const CPlusPlus::Symbol *symbol) const;
QString symbolName(const CPlusPlus::Symbol *symbol) const;
- void appendItem(const QString &name,
- const QString &info,
+ void appendItem(const QString &symbolName,
+ const QString &symbolType,
+ const QString &symbolScope,
ModelItemInfo::ItemType type,
CPlusPlus::Symbol *symbol);
@@ -166,7 +201,6 @@ private:
QList<ModelItemInfo> items;
SymbolTypes symbolsToSearchFor;
QHash<const CPlusPlus::StringLiteral *, QString> m_paths;
- bool separateScope;
};
} // namespace CppTools
diff --git a/src/plugins/cpptools/symbolfinder.cpp b/src/plugins/cpptools/symbolfinder.cpp
index 9acd841121..d3565d7b15 100644
--- a/src/plugins/cpptools/symbolfinder.cpp
+++ b/src/plugins/cpptools/symbolfinder.cpp
@@ -106,13 +106,13 @@ Function *SymbolFinder::findMatchingDefinition(Symbol *declaration,
QString declFile = QString::fromUtf8(declaration->fileName(), declaration->fileNameLength());
Document::Ptr thisDocument = snapshot.document(declFile);
- if (! thisDocument) {
+ if (!thisDocument) {
qWarning() << "undefined document:" << declaration->fileName();
return 0;
}
Function *declarationTy = declaration->type()->asFunctionType();
- if (! declarationTy) {
+ if (!declarationTy) {
qWarning() << "not a function:" << declaration->fileName()
<< declaration->line() << declaration->column();
return 0;
@@ -126,7 +126,7 @@ Function *SymbolFinder::findMatchingDefinition(Symbol *declaration,
}
const Identifier *id = declaration->identifier();
- if (id && ! doc->control()->findIdentifier(id->chars(), id->size()))
+ if (id && !doc->control()->findIdentifier(id->chars(), id->size()))
continue;
if (!id) {
@@ -143,13 +143,13 @@ Function *SymbolFinder::findMatchingDefinition(Symbol *declaration,
candidates.accept(doc->globalNamespace());
const QList<Function *> result = candidates.result();
- if (! result.isEmpty()) {
+ if (!result.isEmpty()) {
LookupContext context(doc, snapshot);
QList<Function *> viableFunctions;
ClassOrNamespace *enclosingType = context.lookupType(declaration);
- if (! enclosingType)
+ if (!enclosingType)
continue; // nothing to do
foreach (Function *fun, result) {
@@ -168,16 +168,18 @@ Function *SymbolFinder::findMatchingDefinition(Symbol *declaration,
if (viableFunctions.isEmpty())
continue;
- else if (! strict && viableFunctions.length() == 1)
+ else if (!strict && viableFunctions.length() == 1)
return viableFunctions.first();
Function *best = 0;
foreach (Function *fun, viableFunctions) {
- if (! (fun->unqualifiedName() && fun->unqualifiedName()->isEqualTo(declaration->unqualifiedName())))
+ if (!(fun->unqualifiedName()
+ && fun->unqualifiedName()->isEqualTo(declaration->unqualifiedName()))) {
continue;
- else if (fun->argumentCount() == declarationTy->argumentCount()) {
- if (! strict && ! best)
+ }
+ if (fun->argumentCount() == declarationTy->argumentCount()) {
+ if (!strict && !best)
best = fun;
const unsigned argc = declarationTy->argumentCount();
@@ -185,7 +187,7 @@ Function *SymbolFinder::findMatchingDefinition(Symbol *declaration,
for (; argIt < argc; ++argIt) {
Symbol *arg = fun->argumentAt(argIt);
Symbol *otherArg = declarationTy->argumentAt(argIt);
- if (! arg->type().isEqualTo(otherArg->type()))
+ if (!arg->type().isEqualTo(otherArg->type()))
break;
}
@@ -197,10 +199,10 @@ Function *SymbolFinder::findMatchingDefinition(Symbol *declaration,
}
}
- if (strict && ! best)
+ if (strict && !best)
continue;
- if (! best)
+ if (!best)
best = viableFunctions.first();
return best;
}
@@ -211,7 +213,7 @@ Function *SymbolFinder::findMatchingDefinition(Symbol *declaration,
Class *SymbolFinder::findMatchingClassDeclaration(Symbol *declaration, const Snapshot &snapshot)
{
- if (! declaration->identifier())
+ if (!declaration->identifier())
return 0;
QString declFile = QString::fromUtf8(declaration->fileName(), declaration->fileNameLength());
@@ -223,8 +225,8 @@ Class *SymbolFinder::findMatchingClassDeclaration(Symbol *declaration, const Sna
continue;
}
- if (! doc->control()->findIdentifier(declaration->identifier()->chars(),
- declaration->identifier()->size()))
+ if (!doc->control()->findIdentifier(declaration->identifier()->chars(),
+ declaration->identifier()->size()))
continue;
LookupContext context(doc, snapshot);
@@ -252,12 +254,12 @@ void SymbolFinder::findMatchingDeclaration(const LookupContext &context,
return;
Scope *enclosingScope = functionType->enclosingScope();
- while (! (enclosingScope->isNamespace() || enclosingScope->isClass()))
+ while (!(enclosingScope->isNamespace() || enclosingScope->isClass()))
enclosingScope = enclosingScope->enclosingScope();
QTC_ASSERT(enclosingScope != 0, return);
const Name *functionName = functionType->name();
- if (! functionName)
+ if (!functionName)
return; // anonymous function names are not valid c++
ClassOrNamespace *binding = 0;
@@ -287,13 +289,9 @@ void SymbolFinder::findMatchingDeclaration(const LookupContext &context,
continue;
for (Symbol *s = scope->find(funcId); s; s = s->next()) {
- if (! s->name())
- continue;
- else if (! funcId->isEqualTo(s->identifier()))
- continue;
- else if (! s->type()->isFunctionType())
+ if (!s->name() || !funcId->isEqualTo(s->identifier()) || !s->type()->isFunctionType())
continue;
- else if (Declaration *decl = s->asDeclaration()) {
+ if (Declaration *decl = s->asDeclaration()) {
if (Function *declFunTy = decl->type()->asFunctionType()) {
if (functionType->isEqualTo(declFunTy))
typeMatch->prepend(decl);
diff --git a/src/plugins/cpptools/symbolsearcher_test.cpp b/src/plugins/cpptools/symbolsearcher_test.cpp
new file mode 100644
index 0000000000..c5529b7b46
--- /dev/null
+++ b/src/plugins/cpptools/symbolsearcher_test.cpp
@@ -0,0 +1,298 @@
+/****************************************************************************
+**
+** 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 "builtinindexingsupport.h"
+#include "cppmodelmanager.h"
+#include "searchsymbols.h"
+
+#include <coreplugin/testdatadir.h>
+#include <utils/runextensions.h>
+
+#include <QtTest>
+
+using namespace CppTools;
+using namespace CppTools::Internal;
+
+namespace {
+
+class MyTestDataDir : public Core::Internal::Tests::TestDataDir
+{
+public:
+ MyTestDataDir(const QString &testDataDirectory)
+ : TestDataDir(QLatin1String(SRCDIR "/../../../tests/cppsymbolsearcher/")
+ + testDataDirectory)
+ {}
+};
+
+class ResultData
+{
+public:
+ typedef QList<ResultData> ResultDataList;
+
+ ResultData() {}
+ ResultData(const QString &symbolName, const QString &scope)
+ : m_symbolName(symbolName), m_scope(scope) {}
+
+ bool operator==(const ResultData &other) const
+ {
+ return m_symbolName == other.m_symbolName && m_scope == other.m_scope;
+ }
+
+ static ResultDataList fromSearchResultList(const QList<Find::SearchResultItem> &entries)
+ {
+ ResultDataList result;
+ foreach (const Find::SearchResultItem &entry, entries)
+ result << ResultData(entry.text, entry.path.join(QLatin1String("::")));
+ return result;
+ }
+
+ /// For debugging and creating reference data
+ static void printFilterEntries(const ResultDataList &entries)
+ {
+ QTextStream out(stdout);
+ foreach (const ResultData entry, entries) {
+ out << "<< ResultData(_(\"" << entry.m_symbolName << "\"), _(\""
+ << entry.m_scope << "\"))" << endl;
+ }
+ }
+
+ QString m_symbolName;
+ QString m_scope;
+};
+
+typedef ResultData::ResultDataList ResultDataList;
+
+class SymbolSearcherTest
+{
+public:
+ /// Takes no ownership of indexingSupportToUse
+ SymbolSearcherTest(const QString &testFile, CppIndexingSupport *indexingSupportToUse)
+ : m_modelManager(CppModelManager::instance())
+ , m_indexingSupportToUse(indexingSupportToUse)
+ , m_testFile(testFile)
+ {
+ QVERIFY(m_indexingSupportToUse);
+ QVERIFY(m_modelManager->snapshot().isEmpty());
+ m_modelManager->updateSourceFiles(QStringList() << m_testFile).waitForFinished();
+ QVERIFY(m_modelManager->snapshot().contains(m_testFile));
+
+ m_indexingSupportToRestore = m_modelManager->indexingSupport();
+ m_modelManager->setIndexingSupport(m_indexingSupportToUse);
+ QCoreApplication::processEvents();
+ }
+
+ ResultDataList run(const SymbolSearcher::Parameters &searchParameters) const
+ {
+ CppIndexingSupport *indexingSupport = m_modelManager->indexingSupport();
+ SymbolSearcher *symbolSearcher
+ = indexingSupport->createSymbolSearcher(searchParameters, QSet<QString>() << m_testFile);
+ QFuture<Find::SearchResultItem> search
+ = QtConcurrent::run(&SymbolSearcher::runSearch, symbolSearcher);
+ search.waitForFinished();
+ ResultDataList results = ResultData::fromSearchResultList(search.results());
+ return results;
+ }
+
+ ~SymbolSearcherTest()
+ {
+ m_modelManager->setIndexingSupport(m_indexingSupportToRestore);
+ m_modelManager->GC();
+ QVERIFY(m_modelManager->snapshot().isEmpty());
+ }
+
+private:
+ CppModelManager *m_modelManager;
+ CppIndexingSupport *m_indexingSupportToRestore;
+ CppIndexingSupport *m_indexingSupportToUse;
+ const QString m_testFile;
+};
+
+inline QString _(const QByteArray &ba) { return QString::fromLatin1(ba, ba.size()); }
+
+} // anonymous namespace
+
+Q_DECLARE_METATYPE(ResultData)
+Q_DECLARE_METATYPE(ResultDataList)
+
+QT_BEGIN_NAMESPACE
+namespace QTest {
+
+template<> char *toString(const ResultData &data)
+{
+ QByteArray ba = "\"" + data.m_symbolName.toUtf8() + "\", \"" + data.m_scope.toUtf8() + "\"";
+ return qstrdup(ba.data());
+}
+
+} // namespace QTest
+QT_END_NAMESPACE
+
+void CppToolsPlugin::test_builtinsymbolsearcher()
+{
+ QFETCH(QString, testFile);
+ QFETCH(SymbolSearcher::Parameters, searchParameters);
+ QFETCH(ResultDataList, expectedResults);
+
+ QScopedPointer<CppIndexingSupport> builtinIndexingSupport(new BuiltinIndexingSupport);
+
+ SymbolSearcherTest test(testFile, builtinIndexingSupport.data());
+ const ResultDataList results = test.run(searchParameters);
+ QCOMPARE(results, expectedResults);
+}
+
+void CppToolsPlugin::test_builtinsymbolsearcher_data()
+{
+ QTest::addColumn<QString>("testFile");
+ QTest::addColumn<SymbolSearcher::Parameters>("searchParameters");
+ QTest::addColumn<ResultDataList>("expectedResults");
+
+ MyTestDataDir testDirectory(QLatin1String("testdata_basic"));
+ const QString testFile = testDirectory.file(QLatin1String("file1.cpp"));
+
+ QScopedPointer<CppIndexingSupport> builtinIndexingSupport(new BuiltinIndexingSupport);
+
+ SymbolSearcher::Parameters searchParameters;
+
+ // Check All Symbol Types
+ searchParameters = SymbolSearcher::Parameters();
+ searchParameters.text = _("");
+ searchParameters.flags = 0;
+ searchParameters.types = SearchSymbols::AllTypes;
+ searchParameters.scope = SymbolSearcher::SearchGlobal;
+ QTest::newRow("BuiltinSymbolSearcher::AllTypes")
+ << testFile
+ << searchParameters
+ << (ResultDataList()
+ << ResultData(_("int myVariable"), _(""))
+ << ResultData(_("myFunction(bool, int)"), _(""))
+ << ResultData(_("MyEnum"), _(""))
+ << ResultData(_("int V1"), _("MyEnum"))
+ << ResultData(_("int V2"), _("MyEnum"))
+ << ResultData(_("MyClass"), _(""))
+ << ResultData(_("MyClass()"), _("MyClass"))
+ << ResultData(_("functionDeclaredOnly()"), _("MyClass"))
+ << ResultData(_("functionDefinedInClass(bool, int)"), _("MyClass"))
+ << ResultData(_("functionDefinedOutSideClass(char)"), _("MyClass"))
+ << ResultData(_("functionDefinedOutSideClass(char)"), _("MyClass"))
+ << ResultData(_("int myVariable"), _("MyNamespace"))
+ << ResultData(_("myFunction(bool, int)"), _("MyNamespace"))
+ << ResultData(_("MyEnum"), _("MyNamespace"))
+ << ResultData(_("int V1"), _("MyNamespace::MyEnum"))
+ << ResultData(_("int V2"), _("MyNamespace::MyEnum"))
+ << ResultData(_("MyClass"), _("MyNamespace"))
+ << ResultData(_("MyClass()"), _("MyNamespace::MyClass"))
+ << ResultData(_("functionDeclaredOnly()"), _("MyNamespace::MyClass"))
+ << ResultData(_("functionDefinedInClass(bool, int)"), _("MyNamespace::MyClass"))
+ << ResultData(_("functionDefinedOutSideClass(char)"), _("MyNamespace::MyClass"))
+ << ResultData(_("functionDefinedOutSideClassAndNamespace(float)"), _("MyNamespace::MyClass"))
+ << ResultData(_("functionDefinedOutSideClass(char)"), _("MyNamespace::MyClass"))
+ << ResultData(_("functionDefinedOutSideClassAndNamespace(float)"), _("MyNamespace::MyClass"))
+ << ResultData(_("int myVariable"), _("<anonymous namespace>"))
+ << ResultData(_("myFunction(bool, int)"), _("<anonymous namespace>"))
+ << ResultData(_("MyEnum"), _("<anonymous namespace>"))
+ << ResultData(_("int V1"), _("<anonymous namespace>::MyEnum"))
+ << ResultData(_("int V2"), _("<anonymous namespace>::MyEnum"))
+ << ResultData(_("MyClass"), _("<anonymous namespace>"))
+ << ResultData(_("MyClass()"), _("<anonymous namespace>::MyClass"))
+ << ResultData(_("functionDeclaredOnly()"), _("<anonymous namespace>::MyClass"))
+ << ResultData(_("functionDefinedInClass(bool, int)"), _("<anonymous namespace>::MyClass"))
+ << ResultData(_("functionDefinedOutSideClass(char)"), _("<anonymous namespace>::MyClass"))
+ << ResultData(_("functionDefinedOutSideClass(char)"), _("<anonymous namespace>::MyClass"))
+ << ResultData(_("main()"), _(""))
+
+ );
+
+ // Check Classes
+ searchParameters = SymbolSearcher::Parameters();
+ searchParameters.text = _("myclass");
+ searchParameters.flags = 0;
+ searchParameters.types = SymbolSearcher::Classes;
+ searchParameters.scope = SymbolSearcher::SearchGlobal;
+ QTest::newRow("BuiltinSymbolSearcher::Classes")
+ << testFile
+ << searchParameters
+ << (ResultDataList()
+ << ResultData(_("MyClass"), _(""))
+ << ResultData(_("MyClass"), _("MyNamespace"))
+ << ResultData(_("MyClass"), _("<anonymous namespace>"))
+ );
+
+ // Check Functions
+ searchParameters = SymbolSearcher::Parameters();
+ searchParameters.text = _("fun");
+ searchParameters.flags = 0;
+ searchParameters.types = SymbolSearcher::Functions;
+ searchParameters.scope = SymbolSearcher::SearchGlobal;
+ QTest::newRow("BuiltinSymbolSearcher::Functions")
+ << testFile
+ << searchParameters
+ << (ResultDataList()
+ << ResultData(_("myFunction(bool, int)"), _(""))
+ << ResultData(_("functionDefinedInClass(bool, int)"), _("MyClass"))
+ << ResultData(_("functionDefinedOutSideClass(char)"), _("MyClass"))
+ << ResultData(_("myFunction(bool, int)"), _("MyNamespace"))
+ << ResultData(_("functionDefinedInClass(bool, int)"), _("MyNamespace::MyClass"))
+ << ResultData(_("functionDefinedOutSideClass(char)"), _("MyNamespace::MyClass"))
+ << ResultData(_("functionDefinedOutSideClassAndNamespace(float)"), _("MyNamespace::MyClass"))
+ << ResultData(_("myFunction(bool, int)"), _("<anonymous namespace>"))
+ << ResultData(_("functionDefinedInClass(bool, int)"), _("<anonymous namespace>::MyClass"))
+ << ResultData(_("functionDefinedOutSideClass(char)"), _("<anonymous namespace>::MyClass"))
+ );
+
+ // Check Enums
+ searchParameters = SymbolSearcher::Parameters();
+ searchParameters.text = _("enum");
+ searchParameters.flags = 0;
+ searchParameters.types = SymbolSearcher::Enums;
+ searchParameters.scope = SymbolSearcher::SearchGlobal;
+ QTest::newRow("BuiltinSymbolSearcher::Enums")
+ << testFile
+ << searchParameters
+ << (ResultDataList()
+ << ResultData(_("MyEnum"), _(""))
+ << ResultData(_("MyEnum"), _("MyNamespace"))
+ << ResultData(_("MyEnum"), _("<anonymous namespace>"))
+ );
+
+ // Check Declarations
+ searchParameters = SymbolSearcher::Parameters();
+ searchParameters.text = _("myvar");
+ searchParameters.flags = 0;
+ searchParameters.types = SymbolSearcher::Declarations;
+ searchParameters.scope = SymbolSearcher::SearchGlobal;
+ QTest::newRow("BuiltinSymbolSearcher::Declarations")
+ << testFile
+ << searchParameters
+ << (ResultDataList()
+ << ResultData(_("int myVariable"), _(""))
+ << ResultData(_("int myVariable"), _("MyNamespace"))
+ << ResultData(_("int myVariable"), _("<anonymous namespace>"))
+ );
+}
diff --git a/src/plugins/cpptools/symbolsfindfilter.cpp b/src/plugins/cpptools/symbolsfindfilter.cpp
index 290b5bd5fd..ad15b7d6bc 100644
--- a/src/plugins/cpptools/symbolsfindfilter.cpp
+++ b/src/plugins/cpptools/symbolsfindfilter.cpp
@@ -45,14 +45,14 @@
#include <QLabel>
#include <QButtonGroup>
-using namespace CppTools;
-using namespace CppTools::Internal;
+using namespace Core;
-namespace {
- const char * const SETTINGS_GROUP = "CppSymbols";
- const char * const SETTINGS_SYMBOLTYPES = "SymbolsToSearchFor";
- const char * const SETTINGS_SEARCHSCOPE = "SearchScope";
-} // anonymous namespace
+namespace CppTools {
+namespace Internal {
+
+const char SETTINGS_GROUP[] = "CppSymbols";
+const char SETTINGS_SYMBOLTYPES[] = "SymbolsToSearchFor";
+const char SETTINGS_SEARCHSCOPE[] = "SearchScope";
SymbolsFindFilter::SymbolsFindFilter(CppModelManager *manager)
: m_manager(manager),
@@ -61,10 +61,10 @@ SymbolsFindFilter::SymbolsFindFilter(CppModelManager *manager)
m_scope(SymbolSearcher::SearchProjectsOnly)
{
// for disabling while parser is running
- connect(Core::ICore::progressManager(), SIGNAL(taskStarted(QString)),
- this, SLOT(onTaskStarted(QString)));
- connect(Core::ICore::progressManager(), SIGNAL(allTasksFinished(QString)),
- this, SLOT(onAllTasksFinished(QString)));
+ connect(ProgressManager::instance(), SIGNAL(taskStarted(Core::Id)),
+ this, SLOT(onTaskStarted(Core::Id)));
+ connect(ProgressManager::instance(), SIGNAL(allTasksFinished(Core::Id)),
+ this, SLOT(onAllTasksFinished(Core::Id)));
}
QString SymbolsFindFilter::id() const
@@ -117,7 +117,7 @@ void SymbolsFindFilter::findAll(const QString &txt, Find::FindFlags findFlags)
connect(search, SIGNAL(paused(bool)), this, SLOT(setPaused(bool)));
connect(search, SIGNAL(searchAgainRequested()), this, SLOT(searchAgain()));
connect(this, SIGNAL(enabledChanged(bool)), search, SLOT(setSearchAgainEnabled(bool)));
- window->popup(Core::IOutputPane::ModeSwitch | Core::IOutputPane::WithFocus);
+ window->popup(IOutputPane::ModeSwitch | IOutputPane::WithFocus);
SymbolSearcher::Parameters parameters;
parameters.text = txt;
@@ -133,10 +133,8 @@ void SymbolsFindFilter::startSearch(Find::SearchResult *search)
SymbolSearcher::Parameters parameters = search->userData().value<SymbolSearcher::Parameters>();
QSet<QString> projectFileNames;
if (parameters.scope == SymbolSearcher::SearchProjectsOnly) {
- foreach (ProjectExplorer::Project *project,
- ProjectExplorer::ProjectExplorerPlugin::instance()->session()->projects()) {
+ foreach (ProjectExplorer::Project *project, ProjectExplorer::SessionManager::projects())
projectFileNames += project->files(ProjectExplorer::Project::AllFiles).toSet();
- }
}
QFutureWatcher<Find::SearchResultItem> *watcher = new QFutureWatcher<Find::SearchResultItem>();
@@ -149,9 +147,8 @@ void SymbolsFindFilter::startSearch(Find::SearchResult *search)
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"),
- QLatin1String(Find::Constants::TASK_SEARCH));
+ FutureProgress *progress = ProgressManager::addTask(watcher->future(), tr("Searching"),
+ Find::Constants::TASK_SEARCH);
connect(progress, SIGNAL(clicked()), search, SLOT(popup()));
}
@@ -187,9 +184,7 @@ void SymbolsFindFilter::openEditor(const Find::SearchResultItem &item)
if (!item.userData.canConvert<ModelItemInfo>())
return;
ModelItemInfo info = item.userData.value<ModelItemInfo>();
- Core::EditorManager::openEditorAt(info.fileName,
- info.line,
- info.column);
+ EditorManager::openEditorAt(info.fileName, info.line, info.column);
}
QWidget *SymbolsFindFilter::createConfigWidget()
@@ -216,17 +211,17 @@ void SymbolsFindFilter::readSettings(QSettings *settings)
emit symbolsToSearchChanged();
}
-void SymbolsFindFilter::onTaskStarted(const QString &type)
+void SymbolsFindFilter::onTaskStarted(Id type)
{
- if (type == QLatin1String(CppTools::Constants::TASK_INDEX)) {
+ if (type == CppTools::Constants::TASK_INDEX) {
m_enabled = false;
emit enabledChanged(m_enabled);
}
}
-void SymbolsFindFilter::onAllTasksFinished(const QString &type)
+void SymbolsFindFilter::onAllTasksFinished(Core::Id type)
{
- if (type == QLatin1String(CppTools::Constants::TASK_INDEX)) {
+ if (type == CppTools::Constants::TASK_INDEX) {
m_enabled = true;
emit enabledChanged(m_enabled);
}
@@ -346,3 +341,6 @@ void SymbolsFindFilterConfigWidget::setState() const
else
m_filter->setSearchScope(SymbolSearcher::SearchGlobal);
}
+
+} // namespace Internal
+} // namespace CppTools
diff --git a/src/plugins/cpptools/symbolsfindfilter.h b/src/plugins/cpptools/symbolsfindfilter.h
index 744323e623..2a45a3fc19 100644
--- a/src/plugins/cpptools/symbolsfindfilter.h
+++ b/src/plugins/cpptools/symbolsfindfilter.h
@@ -82,8 +82,8 @@ private slots:
void finish();
void cancel();
void setPaused(bool paused);
- void onTaskStarted(const QString &type);
- void onAllTasksFinished(const QString &type);
+ void onTaskStarted(Core::Id type);
+ void onAllTasksFinished(Core::Id type);
void searchAgain();
private:
diff --git a/src/plugins/cpptools/uicodecompletionsupport.cpp b/src/plugins/cpptools/uicodecompletionsupport.cpp
deleted file mode 100644
index 54403f9a93..0000000000
--- a/src/plugins/cpptools/uicodecompletionsupport.cpp
+++ /dev/null
@@ -1,246 +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 "uicodecompletionsupport.h"
-
-#include <QProcess>
-#include <QFile>
-#include <QFileInfo>
-
-enum { debug = 0 };
-
-using namespace CppTools;
-using namespace CPlusPlus;
-
-UiCodeModelSupport::UiCodeModelSupport(CppModelManagerInterface *modelmanager,
- const QString &source,
- const QString &uiHeaderFile)
- : AbstractEditorSupport(modelmanager),
- m_sourceName(source),
- m_fileName(uiHeaderFile),
- m_state(BARE)
-{
- if (debug)
- qDebug()<<"ctor UiCodeModelSupport for"<<m_sourceName<<uiHeaderFile;
- connect(&m_process, SIGNAL(finished(int)),
- this, SLOT(finishProcess()));
-}
-
-UiCodeModelSupport::~UiCodeModelSupport()
-{
- if (debug)
- qDebug()<<"dtor ~UiCodeModelSupport for"<<m_sourceName;
-}
-
-void UiCodeModelSupport::init() const
-{
- if (m_state != BARE)
- return;
- QDateTime sourceTime = QFileInfo(m_sourceName).lastModified();
- QFileInfo uiHeaderFileInfo(m_fileName);
- QDateTime uiHeaderTime = uiHeaderFileInfo.exists() ? uiHeaderFileInfo.lastModified() : QDateTime();
- if (uiHeaderTime.isValid() && (uiHeaderTime > sourceTime)) {
- QFile file(m_fileName);
- if (file.open(QFile::ReadOnly | QFile::Text)) {
- if (debug)
- qDebug()<<"ui*h file is more recent then source file, using information from ui*h file"<<m_fileName;
- QTextStream stream(&file);
- m_contents = stream.readAll().toUtf8();
- m_cacheTime = uiHeaderTime;
- m_state = FINISHED;
- return;
- }
- }
-
- if (debug)
- qDebug()<<"ui*h file not found, or not recent enough, trying to create it on the fly";
- QFile file(m_sourceName);
- if (file.open(QFile::ReadOnly | QFile::Text)) {
- QTextStream stream(&file);
- const QString contents = stream.readAll();
- if (runUic(contents)) {
- if (debug)
- qDebug()<<"created on the fly";
- return;
- } else {
- // uic run was unsuccesfull
- if (debug)
- qDebug()<<"uic run wasn't succesfull";
- m_cacheTime = QDateTime ();
- m_contents = QByteArray();
- m_state = FINISHED;
- return;
- }
- } else {
- if (debug)
- qDebug()<<"Could open "<<m_sourceName<<"needed for the cpp model";
- m_contents = QByteArray();
- m_state = FINISHED;
- }
-}
-
-QByteArray UiCodeModelSupport::contents() const
-{
- // Check the common case first
- if (m_state == FINISHED)
- return m_contents;
- if (m_state == BARE)
- init();
- if (m_state == RUNNING)
- finishProcess();
-
- return m_contents;
-}
-
-QString UiCodeModelSupport::fileName() const
-{
- return m_fileName;
-}
-
-void UiCodeModelSupport::setFileName(const QString &name)
-{
- if (m_fileName == name && m_cacheTime.isValid())
- return;
-
- if (m_state == RUNNING)
- finishProcess();
-
- if (debug)
- qDebug() << "UiCodeModelSupport::setFileName"<<name;
-
- m_fileName = name;
- m_contents.clear();
- m_cacheTime = QDateTime();
- m_state = BARE;
-}
-
-bool UiCodeModelSupport::runUic(const QString &ui) const
-{
- const QString uic = uicCommand();
- if (uic.isEmpty())
- return false;
- m_process.setEnvironment(environment());
-
- if (debug)
- qDebug() << "UiCodeModelSupport::runUic " << uic << " on " << ui.size() << " bytes";
- m_process.start(uic, QStringList(), QIODevice::ReadWrite);
- if (!m_process.waitForStarted())
- return false;
- m_process.write(ui.toUtf8());
- if (!m_process.waitForBytesWritten(3000))
- goto error;
- m_process.closeWriteChannel();
- m_state = RUNNING;
- return true;
-
-error:
- if (debug)
- qDebug() << "failed" << m_process.readAllStandardError();
- m_process.kill();
- m_state = FINISHED;
- return false;
-}
-
-void UiCodeModelSupport::updateFromEditor(const QString &formEditorContents)
-{
- if (m_state == BARE)
- init();
- if (m_state == RUNNING)
- finishProcess();
- if (runUic(formEditorContents))
- if (finishProcess())
- updateDocument();
-}
-
-bool UiCodeModelSupport::finishProcess() const
-{
- if (m_state != RUNNING)
- return false;
- if (!m_process.waitForFinished(3000)
- && m_process.exitStatus() != QProcess::NormalExit
- && m_process.exitCode() != 0) {
- if (m_state != RUNNING) // waitForFinished can recurse into finishProcess
- return false;
-
- if (debug)
- qDebug() << "failed" << m_process.readAllStandardError();
- m_process.kill();
- m_state = FINISHED;
- return false;
- }
-
- if (m_state != RUNNING) // waitForFinished can recurse into finishProcess
- return true;
-
- m_contents = m_process.readAllStandardOutput();
- m_cacheTime = QDateTime::currentDateTime();
- if (debug)
- qDebug() << "ok" << m_contents.size() << "bytes.";
- m_state = FINISHED;
- return true;
-}
-
-void UiCodeModelSupport::updateFromBuild()
-{
- if (debug)
- qDebug()<<"UiCodeModelSupport::updateFromBuild() for file"<<m_sourceName;
- if (m_state == BARE)
- init();
- if (m_state == RUNNING)
- finishProcess();
- // This is mostly a fall back for the cases when uic couldn't be run
- // it pays special attention to the case where a ui_*h was newly created
- QDateTime sourceTime = QFileInfo(m_sourceName).lastModified();
- if (m_cacheTime.isValid() && m_cacheTime >= sourceTime) {
- if (debug)
- qDebug()<<"Cache is still more recent then source";
- return;
- } else {
- QFileInfo fi(m_fileName);
- QDateTime uiHeaderTime = fi.exists() ? fi.lastModified() : QDateTime();
- if (uiHeaderTime.isValid() && (uiHeaderTime > sourceTime)) {
- if (m_cacheTime >= uiHeaderTime)
- return;
- if (debug)
- qDebug()<<"found ui*h updating from it";
-
- QFile file(m_fileName);
- if (file.open(QFile::ReadOnly | QFile::Text)) {
- QTextStream stream(&file);
- m_contents = stream.readAll().toUtf8();
- m_cacheTime = uiHeaderTime;
- updateDocument();
- return;
- }
- }
- if (debug)
- qDebug()<<"ui*h not found or not more recent then source not changing anything";
- }
-}
-
diff --git a/src/plugins/cvs/CVS.pluginspec.in b/src/plugins/cvs/CVS.pluginspec.in
index cf30f50e60..49e4653d75 100644
--- a/src/plugins/cvs/CVS.pluginspec.in
+++ b/src/plugins/cvs/CVS.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"CVS\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"CVS\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/cvs/annotationhighlighter.cpp b/src/plugins/cvs/annotationhighlighter.cpp
index 50dc595dc3..d528394a2c 100644
--- a/src/plugins/cvs/annotationhighlighter.cpp
+++ b/src/plugins/cvs/annotationhighlighter.cpp
@@ -33,9 +33,8 @@ using namespace Cvs;
using namespace Cvs::Internal;
CvsAnnotationHighlighter::CvsAnnotationHighlighter(const ChangeNumbers &changeNumbers,
- const QColor &bg,
QTextDocument *document) :
- VcsBase::BaseAnnotationHighlighter(changeNumbers, bg, document),
+ VcsBase::BaseAnnotationHighlighter(changeNumbers, document),
m_blank(QLatin1Char(' '))
{
}
diff --git a/src/plugins/cvs/annotationhighlighter.h b/src/plugins/cvs/annotationhighlighter.h
index 7932da4e98..9ded8cc148 100644
--- a/src/plugins/cvs/annotationhighlighter.h
+++ b/src/plugins/cvs/annotationhighlighter.h
@@ -41,7 +41,7 @@ class CvsAnnotationHighlighter : public VcsBase::BaseAnnotationHighlighter
Q_OBJECT
public:
- explicit CvsAnnotationHighlighter(const ChangeNumbers &changeNumbers, const QColor &bg,
+ explicit CvsAnnotationHighlighter(const ChangeNumbers &changeNumbers,
QTextDocument *document = 0);
private:
diff --git a/src/plugins/cvs/checkoutwizard.cpp b/src/plugins/cvs/checkoutwizard.cpp
index 0fa3882847..e2a3bb327c 100644
--- a/src/plugins/cvs/checkoutwizard.cpp
+++ b/src/plugins/cvs/checkoutwizard.cpp
@@ -32,35 +32,20 @@
#include "cvsplugin.h"
#include <coreplugin/iversioncontrol.h>
-#include <vcsbase/checkoutjobs.h>
+#include <vcsbase/command.h>
#include <vcsbase/vcsbaseconstants.h>
#include <vcsbase/vcsconfigurationpage.h>
#include <utils/qtcassert.h>
-#include <QIcon>
-
namespace Cvs {
namespace Internal {
-CheckoutWizard::CheckoutWizard(QObject *parent) :
- VcsBase::BaseCheckoutWizard(parent)
+CheckoutWizard::CheckoutWizard()
{
setId(QLatin1String(VcsBase::Constants::VCS_ID_CVS));
-}
-
-QIcon CheckoutWizard::icon() const
-{
- return QIcon(QLatin1String(":/cvs/images/cvs.png"));
-}
-
-QString CheckoutWizard::description() const
-{
- return tr("Checks out a CVS repository and tries to load the contained project.");
-}
-
-QString CheckoutWizard::displayName() const
-{
- return tr("CVS Checkout");
+ setIcon(QIcon(QLatin1String(":/cvs/images/cvs.png")));
+ setDescription(tr("Checks out a CVS repository and tries to load the contained project."));
+ setDisplayName(tr("CVS Checkout"));
}
QList<QWizardPage*> CheckoutWizard::createParameterPages(const QString &path)
@@ -75,13 +60,13 @@ QList<QWizardPage*> CheckoutWizard::createParameterPages(const QString &path)
return rc;
}
-QSharedPointer<VcsBase::AbstractCheckoutJob> CheckoutWizard::createJob(const QList<QWizardPage*> &parameterPages,
- QString *checkoutPath)
+VcsBase::Command *CheckoutWizard::createCommand(const QList<QWizardPage*> &parameterPages,
+ QString *checkoutPath)
{
// Collect parameters for the checkout command.
// CVS does not allow for checking out into a different directory.
const CheckoutWizardPage *cwp = qobject_cast<const CheckoutWizardPage *>(parameterPages.front());
- QTC_ASSERT(cwp, return QSharedPointer<VcsBase::AbstractCheckoutJob>());
+ QTC_ASSERT(cwp, return 0);
const CvsSettings settings = CvsPlugin::instance()->settings();
const QString binary = settings.cvsBinaryPath;
QStringList args;
@@ -90,9 +75,10 @@ QSharedPointer<VcsBase::AbstractCheckoutJob> CheckoutWizard::createJob(const QLi
const QString workingDirectory = cwp->path();
*checkoutPath = workingDirectory + QLatin1Char('/') + repository;
- VcsBase::ProcessCheckoutJob *job = new VcsBase::ProcessCheckoutJob;
- job->addStep(binary, settings.addOptions(args), workingDirectory);
- return QSharedPointer<VcsBase::AbstractCheckoutJob>(job);
+ VcsBase::Command *command = new VcsBase::Command(binary, workingDirectory,
+ QProcessEnvironment::systemEnvironment());
+ command->addJob(settings.addOptions(args), -1);
+ return command;
}
} // namespace Internal
diff --git a/src/plugins/cvs/checkoutwizard.h b/src/plugins/cvs/checkoutwizard.h
index 28068c1e1f..d6fc525218 100644
--- a/src/plugins/cvs/checkoutwizard.h
+++ b/src/plugins/cvs/checkoutwizard.h
@@ -38,19 +38,15 @@ namespace Internal {
class CheckoutWizard : public VcsBase::BaseCheckoutWizard
{
Q_OBJECT
-public:
- explicit CheckoutWizard(QObject *parent = 0);
- // IWizard
- QIcon icon() const;
- QString description() const;
- QString displayName() const;
+public:
+ CheckoutWizard();
-protected:
+private:
// BaseCheckoutWizard
QList<QWizardPage*> createParameterPages(const QString &path);
- QSharedPointer<VcsBase::AbstractCheckoutJob> createJob(const QList<QWizardPage*> &parameterPage,
- QString *checkoutPath);
+ VcsBase::Command *createCommand(const QList<QWizardPage*> &parameterPage,
+ QString *checkoutPath);
};
} // namespace Internal
diff --git a/src/plugins/cvs/cvseditor.cpp b/src/plugins/cvs/cvseditor.cpp
index f5a3539440..d34dc18f86 100644
--- a/src/plugins/cvs/cvseditor.cpp
+++ b/src/plugins/cvs/cvseditor.cpp
@@ -87,7 +87,7 @@ QSet<QString> CvsEditor::annotationChanges() const
changes.insert(r.cap(1));
}
}
- if (Cvs::Constants::debug)
+ if (Constants::debug)
qDebug() << "CVSEditor::annotationChanges() returns #" << changes.size();
return changes;
}
@@ -123,10 +123,9 @@ QString CvsEditor::changeUnderCursor(const QTextCursor &c) const
return QString();
}
-VcsBase::BaseAnnotationHighlighter *CvsEditor::createAnnotationHighlighter(const QSet<QString> &changes,
- const QColor &bg) const
+VcsBase::BaseAnnotationHighlighter *CvsEditor::createAnnotationHighlighter(const QSet<QString> &changes) const
{
- return new CvsAnnotationHighlighter(changes, bg);
+ return new CvsAnnotationHighlighter(changes);
}
QStringList CvsEditor::annotationPreviousVersions(const QString &revision) const
diff --git a/src/plugins/cvs/cvseditor.h b/src/plugins/cvs/cvseditor.h
index 6e6895f651..82621f18f0 100644
--- a/src/plugins/cvs/cvseditor.h
+++ b/src/plugins/cvs/cvseditor.h
@@ -48,7 +48,7 @@ public:
private:
QSet<QString> annotationChanges() const;
QString changeUnderCursor(const QTextCursor &) const;
- VcsBase::BaseAnnotationHighlighter *createAnnotationHighlighter(const QSet<QString> &changes, const QColor &bg) const;
+ VcsBase::BaseAnnotationHighlighter *createAnnotationHighlighter(const QSet<QString> &changes) 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 85ffd0a65c..070ea7e088 100644
--- a/src/plugins/cvs/cvsplugin.cpp
+++ b/src/plugins/cvs/cvsplugin.cpp
@@ -225,12 +225,13 @@ bool CvsPlugin::initialize(const QStringList &arguments, QString *errorMessage)
using namespace Core::Constants;
using namespace ExtensionSystem;
+ using Core::Command;
initializeVcs(new CvsControl(this));
m_cvsPluginInstance = this;
- if (!ICore::mimeDatabase()->addMimeTypes(QLatin1String(":/trolltech.cvs/CVS.mimetypes.xml"), errorMessage))
+ if (!MimeDatabase::addMimeTypes(QLatin1String(":/trolltech.cvs/CVS.mimetypes.xml"), errorMessage))
return false;
m_settings.fromSettings(ICore::settings());
@@ -457,7 +458,7 @@ bool CvsPlugin::submitEditorAboutToClose()
// Submit editor closing. Make it write out the commit message
// and retrieve files
- const QFileInfo editorFile(editorDocument->fileName());
+ const QFileInfo editorFile(editorDocument->filePath());
const QFileInfo changeFile(m_commitMessageFileName);
if (editorFile.absoluteFilePath() != changeFile.absoluteFilePath())
return true; // Oops?!
@@ -559,9 +560,9 @@ void CvsPlugin::cvsDiff(const QString &workingDir, const QStringList &files)
cvsDiff(p);
}
-void CvsPlugin::cvsDiff(const CvsDiffParameters &p)
+void CvsPlugin::cvsDiff(const Cvs::Internal::CvsDiffParameters &p)
{
- if (Cvs::Constants::debug)
+ if (Constants::debug)
qDebug() << Q_FUNC_INFO << p.files;
const QString source = VcsBaseEditorWidget::getSource(p.workingDir, p.files);
QTextCodec *codec = VcsBaseEditorWidget::getCodec(p.workingDir, p.files);
@@ -591,7 +592,7 @@ void CvsPlugin::cvsDiff(const CvsDiffParameters &p)
// Show in the same editor if diff has been executed before
const QString tag = VcsBaseEditorWidget::editorTag(DiffOutput, p.workingDir, p.files);
if (IEditor *existingEditor = VcsBaseEditorWidget::locateEditorByTag(tag)) {
- existingEditor->createNew(output);
+ existingEditor->document()->setContents(output.toUtf8());
EditorManager::activateEditor(existingEditor);
setDiffBaseDirectory(existingEditor, p.workingDir);
return;
@@ -724,7 +725,9 @@ void CvsPlugin::diffProject()
{
const VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasProject(), return);
- cvsDiff(state.currentProjectTopLevel(), state.relativeCurrentProject());
+ const QString relativeProject = state.relativeCurrentProject();
+ cvsDiff(state.currentProjectTopLevel(),
+ relativeProject.isEmpty() ? QStringList() : QStringList(relativeProject));
}
void CvsPlugin::diffCurrentFile()
@@ -738,7 +741,7 @@ void CvsPlugin::startCommitCurrentFile()
{
const VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasFile(), return);
- startCommit(state.currentFileTopLevel(), QStringList(state.relativeCurrentFile()));
+ startCommit(state.currentFileTopLevel(), state.relativeCurrentFile());
}
void CvsPlugin::startCommitAll()
@@ -751,7 +754,7 @@ void CvsPlugin::startCommitAll()
/* Start commit of files of a single repository by displaying
* template and files in a submit editor. On closing, the real
* commit will start. */
-void CvsPlugin::startCommit(const QString &workingDir, const QStringList &files)
+void CvsPlugin::startCommit(const QString &workingDir, const QString &file)
{
if (raiseSubmitEditor())
return;
@@ -770,16 +773,16 @@ void CvsPlugin::startCommit(const QString &workingDir, const QStringList &files)
// Get list of added/modified/deleted files and purge out undesired ones
// (do not run status with relative arguments as it will omit the directories)
StateList statusOutput = parseStatusOutput(QString(), response.stdOut);
- if (!files.isEmpty()) {
+ if (!file.isEmpty()) {
for (StateList::iterator it = statusOutput.begin(); it != statusOutput.end() ; ) {
- if (files.contains(it->second))
+ if (file == it->second)
++it;
else
it = statusOutput.erase(it);
}
}
if (statusOutput.empty()) {
- VcsBaseOutputWindow::instance()->append(tr("There are no modified files."));
+ VcsBaseOutputWindow::instance()->appendWarning(tr("There are no modified files."));
return;
}
m_commitRepository = workingDir;
@@ -806,7 +809,7 @@ void CvsPlugin::startCommit(const QString &workingDir, const QStringList &files)
bool CvsPlugin::commit(const QString &messageFile,
const QStringList &fileList)
{
- if (Cvs::Constants::debug)
+ if (Constants::debug)
qDebug() << Q_FUNC_INFO << messageFile << fileList;
QStringList args = QStringList(QLatin1String("commit"));
args << QLatin1String("-F") << messageFile;
@@ -821,7 +824,7 @@ void CvsPlugin::filelogCurrentFile()
{
const VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasFile(), return);
- filelog(state.currentFileTopLevel(), QStringList(state.relativeCurrentFile()), true);
+ filelog(state.currentFileTopLevel(), state.relativeCurrentFile(), true);
}
void CvsPlugin::logProject()
@@ -839,16 +842,16 @@ void CvsPlugin::logRepository()
}
void CvsPlugin::filelog(const QString &workingDir,
- const QStringList &files,
+ const QString &file,
bool enableAnnotationContextMenu)
{
- QTextCodec *codec = VcsBaseEditorWidget::getCodec(workingDir, files);
+ QTextCodec *codec = VcsBaseEditorWidget::getCodec(workingDir, QStringList(file));
// no need for temp file
- const QString id = VcsBaseEditorWidget::getTitleId(workingDir, files);
- const QString source = VcsBaseEditorWidget::getSource(workingDir, files);
+ const QString id = VcsBaseEditorWidget::getTitleId(workingDir, QStringList(file));
+ const QString source = VcsBaseEditorWidget::getSource(workingDir, file);
QStringList args;
args << QLatin1String("log");
- args.append(files);
+ args.append(file);
const CvsResponse response =
runCvs(workingDir, args, m_settings.timeOutMS(),
SshPasswordPrompt, codec);
@@ -857,9 +860,9 @@ void CvsPlugin::filelog(const QString &workingDir,
// Re-use an existing view if possible to support
// the common usage pattern of continuously changing and diffing a file
- const QString tag = VcsBaseEditorWidget::editorTag(LogOutput, workingDir, files);
+ const QString tag = VcsBaseEditorWidget::editorTag(LogOutput, workingDir, QStringList(file));
if (Core::IEditor *editor = VcsBaseEditorWidget::locateEditorByTag(tag)) {
- editor->createNew(response.stdOut);
+ editor->document()->setContents(response.stdOut.toUtf8());
Core::EditorManager::activateEditor(editor);
} else {
const QString title = QString::fromLatin1("cvs log %1").arg(id);
@@ -877,11 +880,12 @@ void CvsPlugin::updateProject()
update(state.currentProjectTopLevel(), state.relativeCurrentProject());
}
-bool CvsPlugin::update(const QString &topLevel, const QStringList &files)
+bool CvsPlugin::update(const QString &topLevel, const QString &file)
{
QStringList args(QLatin1String("update"));
args.push_back(QLatin1String("-dR"));
- args.append(files);
+ if (!file.isEmpty())
+ args.append(file);
const CvsResponse response =
runCvs(topLevel, args, m_settings.longTimeOutMS(),
SshPasswordPrompt|ShowStdOutInLogWindow);
@@ -1001,7 +1005,7 @@ void CvsPlugin::annotate(const QString &workingDir, const QString &file,
const QString tag = VcsBaseEditorWidget::editorTag(AnnotateOutput, workingDir, QStringList(file), revision);
if (IEditor *editor = VcsBaseEditorWidget::locateEditorByTag(tag)) {
- editor->createNew(response.stdOut);
+ editor->document()->setContents(response.stdOut.toUtf8());
VcsBaseEditorWidget::gotoLineOfEditor(editor, lineNumber);
EditorManager::activateEditor(editor);
} else {
@@ -1012,10 +1016,11 @@ void CvsPlugin::annotate(const QString &workingDir, const QString &file,
}
}
-bool CvsPlugin::status(const QString &topLevel, const QStringList &files, const QString &title)
+bool CvsPlugin::status(const QString &topLevel, const QString &file, const QString &title)
{
QStringList args(QLatin1String("status"));
- args.append(files);
+ if (!file.isEmpty())
+ args.append(file);
const CvsResponse response =
runCvs(topLevel, args, m_settings.timeOutMS(), 0);
const bool ok = response.result == CvsResponse::Ok;
@@ -1049,14 +1054,14 @@ void CvsPlugin::statusRepository()
{
const VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasTopLevel(), return);
- status(state.topLevel(), QStringList(), tr("Repository status"));
+ status(state.topLevel(), QString(), tr("Repository status"));
}
void CvsPlugin::updateRepository()
{
const VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasTopLevel(), return);
- update(state.topLevel(), QStringList());
+ update(state.topLevel(), QString());
}
@@ -1089,7 +1094,7 @@ bool CvsPlugin::describe(const QString &toplevel, const QString &file, const
// This function makes use of it to find all files related to
// a commit in order to emulate a "describe global change" functionality
// if desired.
- if (Cvs::Constants::debug)
+ if (Constants::debug)
qDebug() << Q_FUNC_INFO << file << changeNr;
// Number must be > 1
if (isFirstRevision(changeNr)) {
@@ -1197,7 +1202,7 @@ bool CvsPlugin::describe(const QString &repositoryPath,
// the common usage pattern of continuously changing and diffing a file
const QString commitId = entries.front().revisions.front().commitId;
if (IEditor *editor = VcsBaseEditorWidget::locateEditorByTag(commitId)) {
- editor->createNew(output);
+ editor->document()->setContents(output.toUtf8());
EditorManager::activateEditor(editor);
setDiffBaseDirectory(editor, repositoryPath);
} else {
@@ -1212,8 +1217,7 @@ bool CvsPlugin::describe(const QString &repositoryPath,
void CvsPlugin::submitCurrentLog()
{
m_submitActionTriggered = true;
- EditorManager::instance()->closeEditors(QList<IEditor*>()
- << EditorManager::currentEditor());
+ EditorManager::closeEditor(EditorManager::currentEditor());
}
// Run CVS. At this point, file arguments must be relative to
@@ -1233,8 +1237,7 @@ CvsResponse CvsPlugin::runCvs(const QString &workingDirectory,
}
// Run, connect stderr to the output window
const Utils::SynchronousProcessResponse sp_resp =
- runVcs(workingDirectory, executable,
- m_settings.addOptions(arguments),
+ runVcs(workingDirectory, executable, m_settings.addOptions(arguments),
timeOut, flags, outputCodec);
response.result = CvsResponse::OtherError;
@@ -1266,11 +1269,11 @@ IEditor *CvsPlugin::showOutputInEditor(const QString& title, const QString &outp
const VcsBaseEditorParameters *params = findType(editorType);
QTC_ASSERT(params, return 0);
const Id id = params->id;
- if (Cvs::Constants::debug)
+ if (Constants::debug)
qDebug() << "CVSPlugin::showOutputInEditor" << title << id.name()
<< "source=" << source << "Size= " << output.size() << " Type=" << editorType << debugCodec(codec);
QString s = title;
- IEditor *editor = EditorManager::openEditorWithContents(id, &s, output);
+ IEditor *editor = EditorManager::openEditorWithContents(id, &s, output.toUtf8());
connect(editor, SIGNAL(annotateRevisionRequested(QString,QString,int)),
this, SLOT(vcsAnnotate(QString,QString,int)));
CvsEditor *e = qobject_cast<CvsEditor*>(editor->widget());
@@ -1353,7 +1356,7 @@ bool CvsPlugin::managesDirectory(const QString &directory, QString *topLevel /*
}
}
} while (false);
- if (Cvs::Constants::debug) {
+ if (Constants::debug) {
QDebug nsp = qDebug().nospace();
nsp << "CVSPlugin::managesDirectory" << directory << manages;
if (topLevel)
diff --git a/src/plugins/cvs/cvsplugin.h b/src/plugins/cvs/cvsplugin.h
index 09b8a43522..9608cd2e1b 100644
--- a/src/plugins/cvs/cvsplugin.h
+++ b/src/plugins/cvs/cvsplugin.h
@@ -150,16 +150,16 @@ private:
bool describe(const QString &toplevel, const QString &source, const QString &changeNr, QString *errorMessage);
bool describe(const QString &repository, QList<CvsLogEntry> entries, QString *errorMessage);
void filelog(const QString &workingDir,
- const QStringList &files = QStringList(),
+ const QString &file = QString(),
bool enableAnnotationContextMenu = false);
bool unedit(const QString &topLevel, const QStringList &files);
- bool status(const QString &topLevel, const QStringList &files, const QString &title);
- bool update(const QString &topLevel, const QStringList &files);
+ bool status(const QString &topLevel, const QString &file, const QString &title);
+ bool update(const QString &topLevel, const QString &file);
bool checkCVSDirectory(const QDir &directory) const;
// Quick check if files are modified
bool diffCheckModified(const QString &topLevel, const QStringList &files, bool *modified);
QString findTopLevelForDirectoryI(const QString &directory) const;
- void startCommit(const QString &workingDir, const QStringList &files = QStringList());
+ void startCommit(const QString &workingDir, const QString &file = QString());
bool commit(const QString &messageFile, const QStringList &subVersionFileList);
void cleanCommitMessageFile();
inline CvsControl *cvsVersionControl() const;
diff --git a/src/plugins/debugger/Debugger.pluginspec.in b/src/plugins/debugger/Debugger.pluginspec.in
index 22d8107569..1ebcdb21b2 100644
--- a/src/plugins/debugger/Debugger.pluginspec.in
+++ b/src/plugins/debugger/Debugger.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"Debugger\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"Debugger\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/debugger/breakhandler.cpp b/src/plugins/debugger/breakhandler.cpp
index 88df5dae22..597c06480a 100644
--- a/src/plugins/debugger/breakhandler.cpp
+++ b/src/plugins/debugger/breakhandler.cpp
@@ -40,7 +40,7 @@
#include <utils/qtcassert.h>
#if USE_BREAK_MODEL_TEST
-#include "modeltest.h"
+#include <modeltest.h>
#endif
#include <QTimerEvent>
@@ -335,7 +335,7 @@ void BreakHandler::saveBreakpoints()
map.insert(_("message"), data.message);
list.append(map);
}
- debuggerCore()->setSessionValue(QLatin1String("Breakpoints"), list);
+ DebuggerCore::setSessionValue("Breakpoints", list);
//qDebug() << "SAVED BREAKPOINTS" << this << list.size();
}
@@ -343,7 +343,7 @@ void BreakHandler::loadBreakpoints()
{
QTC_ASSERT(debuggerCore(), return);
//qDebug() << "LOADING BREAKPOINTS...";
- QVariant value = debuggerCore()->sessionValue(QLatin1String("Breakpoints"));
+ QVariant value = DebuggerCore::sessionValue("Breakpoints");
QList<QVariant> list = value.toList();
//clear();
foreach (const QVariant &var, list) {
@@ -986,6 +986,8 @@ void BreakHandler::notifyBreakpointReleased(BreakpointModelId id)
|| it->data.type == WatchpointAtExpression
|| it->data.type == BreakpointByAddress)
it->data.enabled = false;
+ else
+ it->data.address = 0;
layoutChanged();
}
@@ -1073,7 +1075,7 @@ void BreakHandler::handleAlienBreakpoint(const BreakpointResponse &response, Deb
else
setResponse(id, response);
} else {
- BreakpointModelId id(++currentId);
+ id = BreakpointModelId(++currentId);
const int row = m_storage.size();
beginInsertRows(QModelIndex(), row, row);
diff --git a/src/plugins/debugger/breakpoint.cpp b/src/plugins/debugger/breakpoint.cpp
index 8f050b4ed9..2d1dd15c12 100644
--- a/src/plugins/debugger/breakpoint.cpp
+++ b/src/plugins/debugger/breakpoint.cpp
@@ -29,7 +29,7 @@
#include "breakpoint.h"
-#include "utils/qtcassert.h"
+#include <utils/qtcassert.h>
#include <QDebug>
#include <QFileInfo>
diff --git a/src/plugins/debugger/breakwindow.cpp b/src/plugins/debugger/breakwindow.cpp
index cbac9c8800..66443ef1f3 100644
--- a/src/plugins/debugger/breakwindow.cpp
+++ b/src/plugins/debugger/breakwindow.cpp
@@ -748,11 +748,14 @@ void BreakTreeView::contextMenuEvent(QContextMenuEvent *ev)
selectedIndices.append(indexUnderMouse);
BreakHandler *handler = breakHandler();
- BreakpointModelIds selectedIds = handler->findBreakpointsByIndex(selectedIndices);
+ BreakpointModelIds selectedIds;
+ foreach (BreakpointModelId id, handler->findBreakpointsByIndex(selectedIndices))
+ if (id.isMajor())
+ selectedIds.append(id);
const int rowCount = model()->rowCount();
QAction *deleteAction = new QAction(tr("Delete Breakpoint"), &menu);
- deleteAction->setEnabled(!selectedIds.isEmpty());
+ deleteAction->setEnabled(!selectedIds.empty());
QAction *deleteAllAction = new QAction(tr("Delete All Breakpoints"), &menu);
deleteAllAction->setEnabled(model()->rowCount() > 0);
diff --git a/src/plugins/debugger/cdb/cdb.pri b/src/plugins/debugger/cdb/cdb.pri
index f1928c0b3c..2191c4150b 100644
--- a/src/plugins/debugger/cdb/cdb.pri
+++ b/src/plugins/debugger/cdb/cdb.pri
@@ -10,4 +10,3 @@ SOURCES += $$PWD/cdbengine.cpp \
FORMS += cdb/cdboptionspagewidget.ui
-INCLUDEPATH*=$$PWD
diff --git a/src/plugins/debugger/cdb/cdbengine.cpp b/src/plugins/debugger/cdb/cdbengine.cpp
index 1ca5f428ea..a77480e6f1 100644
--- a/src/plugins/debugger/cdb/cdbengine.cpp
+++ b/src/plugins/debugger/cdb/cdbengine.cpp
@@ -29,28 +29,29 @@
#include "cdbengine.h"
-#include "breakhandler.h"
#include "bytearrayinputstream.h"
#include "cdboptionspage.h"
#include "cdbparsehelpers.h"
-#include "debuggeractions.h"
-#include "debuggercore.h"
-#include "debuggerprotocol.h"
-#include "debuggermainwindow.h"
-#include "debuggerstartparameters.h"
-#include "debuggertooltipmanager.h"
-#include "disassembleragent.h"
-#include "disassemblerlines.h"
-#include "memoryagent.h"
-#include "moduleshandler.h"
-#include "registerhandler.h"
-#include "stackhandler.h"
-#include "threadshandler.h"
-#include "watchhandler.h"
-#include "shared/cdbsymbolpathlisteditor.h"
-#include "shared/hostutils.h"
-#include "procinterrupt.h"
-#include "sourceutils.h"
+
+#include <debugger/breakhandler.h>
+#include <debugger/debuggeractions.h>
+#include <debugger/debuggercore.h>
+#include <debugger/debuggerprotocol.h>
+#include <debugger/debuggermainwindow.h>
+#include <debugger/debuggerstartparameters.h>
+#include <debugger/debuggertooltipmanager.h>
+#include <debugger/disassembleragent.h>
+#include <debugger/disassemblerlines.h>
+#include <debugger/memoryagent.h>
+#include <debugger/moduleshandler.h>
+#include <debugger/registerhandler.h>
+#include <debugger/stackhandler.h>
+#include <debugger/threadshandler.h>
+#include <debugger/watchhandler.h>
+#include <debugger/procinterrupt.h>
+#include <debugger/sourceutils.h>
+#include <debugger/shared/cdbsymbolpathlisteditor.h>
+#include <debugger/shared/hostutils.h>
#include <coreplugin/icore.h>
#include <projectexplorer/taskhub.h>
@@ -150,6 +151,7 @@ enum HandleLocalsFlags
*/
using namespace ProjectExplorer;
+using namespace Utils;
namespace Debugger {
namespace Internal {
@@ -315,7 +317,7 @@ static inline bool validMode(DebuggerStartMode sm)
// Accessed by RunControlFactory
DebuggerEngine *createCdbEngine(const DebuggerStartParameters &sp, QString *errorMessage)
{
- if (Utils::HostOsInfo::isWindowsHost()) {
+ if (HostOsInfo::isWindowsHost()) {
if (validMode(sp.startMode))
return new CdbEngine(sp);
*errorMessage = QLatin1String("Internal error: Invalid start parameters passed for thee CDB engine.");
@@ -327,7 +329,7 @@ DebuggerEngine *createCdbEngine(const DebuggerStartParameters &sp, QString *erro
void addCdbOptionPages(QList<Core::IOptionsPage *> *opts)
{
- if (Utils::HostOsInfo::isWindowsHost()) {
+ if (HostOsInfo::isWindowsHost()) {
opts->push_back(new CdbOptionsPage);
opts->push_back(new CdbPathsPage);
}
@@ -413,7 +415,7 @@ void CdbEngine::init()
}
// update source path maps from debugger start params
mergeStartParametersSourcePathMap();
- QTC_ASSERT(m_process.state() != QProcess::Running, Utils::SynchronousProcess::stopProcess(m_process));
+ QTC_ASSERT(m_process.state() != QProcess::Running, SynchronousProcess::stopProcess(m_process));
}
CdbEngine::~CdbEngine()
@@ -538,8 +540,8 @@ bool CdbEngine::startConsole(const DebuggerStartParameters &sp, QString *errorMe
{
if (debug)
qDebug("startConsole %s", qPrintable(sp.executable));
- m_consoleStub.reset(new Utils::ConsoleProcess);
- m_consoleStub->setMode(Utils::ConsoleProcess::Suspend);
+ m_consoleStub.reset(new ConsoleProcess);
+ m_consoleStub->setMode(ConsoleProcess::Suspend);
connect(m_consoleStub.data(), SIGNAL(processError(QString)),
SLOT(consoleStubError(QString)));
connect(m_consoleStub.data(), SIGNAL(processStarted()),
@@ -701,8 +703,7 @@ bool CdbEngine::launchCDB(const DebuggerStartParameters &sp, QString *errorMessa
case StartExternal:
if (!nativeArguments.isEmpty())
nativeArguments.push_back(blank);
- Utils::QtcProcess::addArgs(&nativeArguments,
- QStringList(QDir::toNativeSeparators(sp.executable)));
+ QtcProcess::addArgs(&nativeArguments, QStringList(QDir::toNativeSeparators(sp.executable)));
break;
case AttachToRemoteServer:
break;
@@ -754,11 +755,8 @@ bool CdbEngine::launchCDB(const DebuggerStartParameters &sp, QString *errorMessa
arg(QDir::toNativeSeparators(executable), m_process.errorString());
return false;
}
-#ifdef Q_OS_WIN
- const unsigned long pid = Utils::winQPidToPid(m_process.pid());
-#else
- const unsigned long pid = 0;
-#endif
+
+ const unsigned long pid = Utils::qPidToPid(m_process.pid());
showMessage(QString::fromLatin1("%1 running as %2").
arg(QDir::toNativeSeparators(executable)).arg(pid), LogMisc);
m_hasDebuggee = true;
@@ -944,7 +942,7 @@ void CdbEngine::shutdownEngine()
} else {
// Remote process. No can do, currently
m_notifyEngineShutdownOnTermination = true;
- Utils::SynchronousProcess::stopProcess(m_process);
+ SynchronousProcess::stopProcess(m_process);
return;
}
// Lost debuggee, debugger should quit anytime now
@@ -2473,13 +2471,12 @@ void CdbEngine::handleExtensionMessage(char t, int token, const QByteArray &what
&& exception.exceptionCode != winExceptionSetThreadName) {
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).trimmed(),
- fileName, exception.lineNumber,
- Core::Id(Debugger::Constants::TASK_CATEGORY_DEBUGGER_RUNTIME));
- taskHub()->addTask(task);
+ const FileName fileName = exception.file.isEmpty() ?
+ FileName() :
+ FileName::fromUserInput(QString::fromLocal8Bit(exception.file));
+ TaskHub::addTask(type, exception.toString(false).trimmed(),
+ Debugger::Constants::TASK_CATEGORY_DEBUGGER_RUNTIME,
+ fileName, exception.lineNumber);
}
return;
}
@@ -2705,13 +2702,13 @@ static CPlusPlus::Document::Ptr getParsedDocument(const QString &fileName,
const CppTools::CppModelManagerInterface::WorkingCopy &workingCopy,
const CPlusPlus::Snapshot &snapshot)
{
- QString src;
+ QByteArray src;
if (workingCopy.contains(fileName)) {
src = workingCopy.source(fileName);
} else {
- Utils::FileReader reader;
+ FileReader reader;
if (reader.fetch(fileName)) // ### FIXME error reporting
- src = QString::fromLocal8Bit(reader.data()); // ### FIXME encoding
+ src = QString::fromLocal8Bit(reader.data()).toUtf8();
}
CPlusPlus::Document::Ptr doc = snapshot.preprocessedDocument(src, fileName);
diff --git a/src/plugins/debugger/cdb/cdbengine.h b/src/plugins/debugger/cdb/cdbengine.h
index 48af1aa464..097407c3f8 100644
--- a/src/plugins/debugger/cdb/cdbengine.h
+++ b/src/plugins/debugger/cdb/cdbengine.h
@@ -30,7 +30,7 @@
#ifndef DEBUGGER_CDBENGINE_H
#define DEBUGGER_CDBENGINE_H
-#include "debuggerengine.h"
+#include <debugger/debuggerengine.h>
#include <QSharedPointer>
#include <QProcess>
diff --git a/src/plugins/debugger/cdb/cdboptionspage.cpp b/src/plugins/debugger/cdb/cdboptionspage.cpp
index 648a4cd746..e3b6c4cd33 100644
--- a/src/plugins/debugger/cdb/cdboptionspage.cpp
+++ b/src/plugins/debugger/cdb/cdboptionspage.cpp
@@ -28,12 +28,12 @@
****************************************************************************/
#include "cdboptionspage.h"
-#include "commonoptionspage.h"
-#include "debuggeractions.h"
-#include "debuggercore.h"
-#include "debuggerinternalconstants.h"
#include "cdbengine.h"
-#include "cdbsymbolpathlisteditor.h"
+#include <debugger/commonoptionspage.h>
+#include <debugger/debuggeractions.h>
+#include <debugger/debuggercore.h>
+#include <debugger/debuggerinternalconstants.h>
+#include <debugger/shared/cdbsymbolpathlisteditor.h>
#include <coreplugin/icore.h>
diff --git a/src/plugins/debugger/cdb/cdbparsehelpers.cpp b/src/plugins/debugger/cdb/cdbparsehelpers.cpp
index f99a8ef387..fe7a28166a 100644
--- a/src/plugins/debugger/cdb/cdbparsehelpers.cpp
+++ b/src/plugins/debugger/cdb/cdbparsehelpers.cpp
@@ -30,10 +30,11 @@
#include "cdbparsehelpers.h"
#include "bytearrayinputstream.h"
-#include "debuggerprotocol.h"
-#include "disassemblerlines.h"
-#include "shared/hostutils.h"
-#include "threaddata.h"
+
+#include <debugger/debuggerprotocol.h>
+#include <debugger/disassemblerlines.h>
+#include <debugger/shared/hostutils.h>
+#include <debugger/threaddata.h>
#include <utils/qtcassert.h>
@@ -259,42 +260,6 @@ QVariant cdbIntegerValue(const QByteArray &t)
return converted;
}
-/* \code
-0:002> ~ [Debugger-Id] Id: <hex pid> <hex tid> Suspends count thread environment block add state name
- 0 Id: 133c.1374 Suspend: 1 Teb: 000007ff`fffdd000 Unfrozen
-. 2 Id: 133c.1160 Suspend: 1 Teb: 000007ff`fffd9000 Unfrozen "QThread"
- 3 Id: 133c.38c Suspend: 1 Teb: 000007ff`fffd7000 Unfrozen "QThread"
-\endcode */
-
-static inline bool parseThread(QByteArray line, ThreadData *thread, bool *current)
-{
- *current = false;
- if (line.size() < 5)
- return false;
- *current = line.at(0) == '.';
- if (*current)
- line[0] = ' ';
- const QList<QByteArray> tokens = simplify(line).split(' ');
- if (tokens.size() < 8 || tokens.at(1) != "Id:")
- return false;
- switch (tokens.size()) { // fallthru intended
- case 9:
- thread->name = QString::fromLocal8Bit(tokens.at(8));
- case 8:
- thread->state = QString::fromLocal8Bit(tokens.at(7));
- case 3: {
- const QByteArray &pidTid = tokens.at(2);
- const int dotPos = pidTid.indexOf('.');
- if (dotPos != -1)
- thread->targetId = QLatin1String("0x") + QString::fromLatin1(pidTid.mid(dotPos + 1));
- }
- case 1:
- thread->id = ThreadId(tokens.at(0).toInt());
- break;
- } // switch size
- return true;
-}
-
// Helper to retrieve an int child from GDBMI
static inline bool gdbmiChildToInt(const GdbMi &parent, const char *childName, int *target)
{
@@ -458,7 +423,7 @@ QDebug operator<<(QDebug s, const WinException &e)
}
/*!
- \fn DisassemblerLines parseCdbDisassembler(const QList<QByteArray> &a)
+ \fn DisassemblerLines Debugger::Internal::parseCdbDisassembler(const QList<QByteArray> &a)
Parses CDB disassembler output into DisassemblerLines (with helpers).
diff --git a/src/plugins/debugger/cdb/cdbparsehelpers.h b/src/plugins/debugger/cdb/cdbparsehelpers.h
index 2d95fc8904..4d046f30fe 100644
--- a/src/plugins/debugger/cdb/cdbparsehelpers.h
+++ b/src/plugins/debugger/cdb/cdbparsehelpers.h
@@ -30,7 +30,7 @@
#ifndef CDBPARSEHELPERS_H
#define CDBPARSEHELPERS_H
-#include "breakpoint.h"
+#include <debugger/breakpoint.h>
#include <QPair>
diff --git a/src/plugins/debugger/commonoptionspage.cpp b/src/plugins/debugger/commonoptionspage.cpp
index 8b6efe5ee6..b75581e001 100644
--- a/src/plugins/debugger/commonoptionspage.cpp
+++ b/src/plugins/debugger/commonoptionspage.cpp
@@ -178,6 +178,7 @@ CommonOptionsPageWidget::CommonOptionsPageWidget
m_group->insert(dc->action(AlwaysAdjustBreakpointsColumnWidths), 0);
m_group->insert(dc->action(AlwaysAdjustModulesColumnWidths), 0);
m_group->insert(dc->action(UseToolTipsInBreakpointsView), 0);
+ m_group->insert(dc->action(UseToolTipsInStackView), 0);
m_group->insert(dc->action(UseAddressInBreakpointsView), 0);
m_group->insert(dc->action(UseAddressInStackView), 0);
m_group->insert(dc->action(AlwaysAdjustStackColumnWidths), 0);
@@ -260,13 +261,12 @@ void CommonOptionsPage::apply()
{
QTC_ASSERT(!m_widget.isNull() && !m_group.isNull(), return);
- QSettings *settings = ICore::settings();
- m_group->apply(settings);
+ m_group->apply(ICore::settings());
const GlobalDebuggerOptions newGlobalOptions = m_widget->globalOptions();
if (newGlobalOptions != *m_options) {
*m_options = newGlobalOptions;
- m_options->toSettings(settings);
+ m_options->toSettings();
}
}
diff --git a/src/plugins/debugger/debugger.pro b/src/plugins/debugger/debugger.pro
index 952586b537..ce31216535 100644
--- a/src/plugins/debugger/debugger.pro
+++ b/src/plugins/debugger/debugger.pro
@@ -141,7 +141,6 @@ LIBS *= -lole32 \
}
include(cdb/cdb.pri)
include(gdb/gdb.pri)
-include(script/script.pri)
include(pdb/pdb.pri)
include(lldb/lldb.pri)
include(lldblib/lldbhost.pri)
@@ -149,22 +148,3 @@ include(qml/qml.pri)
include(namedemangler/namedemangler.pri)
include(shared/shared.pri)
-
-equals(TEST, 1):!isEmpty(copydata) {
- TEST_DIR = tests/manual/debugger/simple
- INPUT_FILE = $$IDE_SOURCE_TREE/$$TEST_DIR/simple.pro
- macx: OUTPUT_DIR = $$IDE_DATA_PATH/$$TEST_DIR
- else: OUTPUT_DIR = $$IDE_BUILD_TREE/$$TEST_DIR
- testfile.target = $$OUTPUT_DIR/$$basename(INPUT_FILE)
- testfile.depends = $$INPUT_FILE
- win32:isEmpty(QMAKE_SH) {
- INPUT_FILE ~= s,/,\\\\,g
- OUTPUT_DIR ~= s,/,\\\\,g
- } else {
- isEmpty(QMAKE_CHK_EXISTS_GLUE):QMAKE_CHK_EXISTS_GLUE = "|| "
- }
- testfile.commands = ($$QMAKE_CHK_DIR_EXISTS \"$$OUTPUT_DIR\" $$QMAKE_CHK_EXISTS_GLUE $$QMAKE_MKDIR \"$$OUTPUT_DIR\") \
- && $$QMAKE_COPY \"$$INPUT_FILE\" \"$$OUTPUT_DIR\"
- QMAKE_EXTRA_TARGETS += testfile
- PRE_TARGETDEPS += $$testfile.target
-}
diff --git a/src/plugins/debugger/debugger.qbs b/src/plugins/debugger/debugger.qbs
index e4aabbb7f8..5666ea467f 100644
--- a/src/plugins/debugger/debugger.qbs
+++ b/src/plugins/debugger/debugger.qbs
@@ -1,7 +1,6 @@
import qbs.base 1.0
import "../QtcPlugin.qbs" as QtcPlugin
-import "../../../qbs/defaults.js" as Defaults
QtcPlugin {
name: "Debugger"
@@ -16,255 +15,214 @@ QtcPlugin {
Depends { name: "QmlJS" }
Depends { name: "QmlDebug" }
Depends { name: "QtcSsh" }
+ Depends { name: "Utils" }
- cpp.includePaths: base.concat([
- "shared",
- "lldblib",
- "../../shared/json",
- "../../shared/registryaccess"
- ])
+ cpp.includePaths: base.concat(["../../shared/registryaccess"])
pluginRecommends: [
"CppEditor"
]
Group {
- name: "Tests"
- condition: Defaults.testsEnabled(qbs)
- qbs.install: true
- qbs.installDir: "tests/manual/debugger/simple/"
- files: ["../../../tests/manual/debugger/simple/simple.pro"]
+ name: "General"
+ files: [
+ "basewindow.cpp", "basewindow.h",
+ "breakhandler.cpp", "breakhandler.h",
+ "breakpoint.cpp", "breakpoint.h",
+ "breakpointmarker.cpp", "breakpointmarker.h",
+ "breakwindow.cpp", "breakwindow.h",
+ "commonoptionspage.cpp", "commonoptionspage.h",
+ "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",
+ "debuggerrunconfigurationaspect.cpp", "debuggerrunconfigurationaspect.h",
+ "debuggerrunner.cpp", "debuggerrunner.h",
+ "debuggersourcepathmappingwidget.cpp", "debuggersourcepathmappingwidget.h",
+ "debuggerstartparameters.h",
+ "debuggerstreamops.cpp", "debuggerstreamops.h",
+ "debuggerstringutils.h",
+ "debuggertooltipmanager.cpp", "debuggertooltipmanager.h",
+ "disassembleragent.cpp", "disassembleragent.h",
+ "disassemblerlines.cpp", "disassemblerlines.h",
+ "imageviewer.cpp", "imageviewer.h",
+ "loadcoredialog.cpp", "loadcoredialog.h",
+ "localsandexpressionsoptionspage.ui",
+ "localsandexpressionswindow.cpp", "localsandexpressionswindow.h",
+ "logwindow.cpp", "logwindow.h",
+ "memoryagent.cpp", "memoryagent.h",
+ "memoryview.cpp", "memoryview.h",
+ "moduleshandler.cpp", "moduleshandler.h",
+ "moduleswindow.cpp", "moduleswindow.h",
+ "outputcollector.cpp", "outputcollector.h",
+ "procinterrupt.cpp", "procinterrupt.h",
+ "registerhandler.cpp", "registerhandler.h",
+ "registerwindow.cpp", "registerwindow.h",
+ "snapshothandler.cpp", "snapshothandler.h",
+ "snapshotwindow.cpp", "snapshotwindow.h",
+ "sourceagent.cpp", "sourceagent.h",
+ "sourcefileshandler.cpp", "sourcefileshandler.h",
+ "sourcefileswindow.cpp", "sourcefileswindow.h",
+ "sourceutils.cpp", "sourceutils.h",
+ "stackframe.cpp", "stackframe.h",
+ "stackhandler.cpp", "stackhandler.h",
+ "stackwindow.cpp", "stackwindow.h",
+ "threaddata.h",
+ "threadshandler.cpp", "threadshandler.h",
+ "threadswindow.cpp", "threadswindow.h",
+ "watchdata.cpp", "watchdata.h",
+ "watchdelegatewidgets.cpp", "watchdelegatewidgets.h",
+ "watchhandler.cpp", "watchhandler.h",
+ "watchutils.cpp", "watchutils.h",
+ "watchwindow.cpp", "watchwindow.h",
+ ]
}
- files: [
- "basewindow.cpp",
- "basewindow.h",
- "breakhandler.cpp",
- "breakhandler.h",
- "breakpoint.cpp",
- "breakpoint.h",
- "breakpointmarker.cpp",
- "breakpointmarker.h",
- "breakwindow.cpp",
- "breakwindow.h",
- "commonoptionspage.cpp",
- "commonoptionspage.h",
- "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",
- "debuggerrunconfigurationaspect.cpp",
- "debuggerrunconfigurationaspect.h",
- "debuggerrunner.cpp",
- "debuggerrunner.h",
- "debuggersourcepathmappingwidget.cpp",
- "debuggersourcepathmappingwidget.h",
- "debuggerstartparameters.h",
- "debuggerstreamops.cpp",
- "debuggerstreamops.h",
- "debuggerstringutils.h",
- "debuggertooltipmanager.cpp",
- "debuggertooltipmanager.h",
- "disassembleragent.cpp",
- "disassembleragent.h",
- "disassemblerlines.cpp",
- "disassemblerlines.h",
- "imageviewer.cpp",
- "imageviewer.h",
- "loadcoredialog.cpp",
- "loadcoredialog.h",
- "localsandexpressionsoptionspage.ui",
- "localsandexpressionswindow.cpp",
- "localsandexpressionswindow.h",
- "logwindow.cpp",
- "logwindow.h",
- "memoryagent.cpp",
- "memoryagent.h",
- "memoryview.cpp",
- "memoryview.h",
- "moduleshandler.cpp",
- "moduleshandler.h",
- "moduleswindow.cpp",
- "moduleswindow.h",
- "outputcollector.cpp",
- "outputcollector.h",
- "procinterrupt.cpp",
- "procinterrupt.h",
- "registerhandler.cpp",
- "registerhandler.h",
- "registerwindow.cpp",
- "registerwindow.h",
- "snapshothandler.cpp",
- "snapshothandler.h",
- "snapshotwindow.cpp",
- "snapshotwindow.h",
- "sourceagent.cpp",
- "sourceagent.h",
- "sourcefileshandler.cpp",
- "sourcefileshandler.h",
- "sourcefileswindow.cpp",
- "sourcefileswindow.h",
- "sourceutils.cpp",
- "sourceutils.h",
- "stackframe.cpp",
- "stackframe.h",
- "stackhandler.cpp",
- "stackhandler.h",
- "stackwindow.cpp",
- "stackwindow.h",
- "threaddata.h",
- "threadshandler.cpp",
- "threadshandler.h",
- "threadswindow.cpp",
- "threadswindow.h",
- "watchdata.cpp",
- "watchdata.h",
- "watchdelegatewidgets.cpp",
- "watchdelegatewidgets.h",
- "watchhandler.cpp",
- "watchhandler.h",
- "watchutils.cpp",
- "watchutils.h",
- "watchwindow.cpp",
- "watchwindow.h",
- "cdb/bytearrayinputstream.cpp",
- "cdb/bytearrayinputstream.h",
- "cdb/cdbengine.cpp",
- "cdb/cdbengine.h",
- "cdb/cdboptionspage.cpp",
- "cdb/cdboptionspage.h",
- "cdb/cdboptionspagewidget.ui",
- "cdb/cdbparsehelpers.cpp",
- "cdb/cdbparsehelpers.h",
- "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/gdbengine.h",
- "gdb/gdboptionspage.cpp",
- "gdb/gdboptionspage.h",
- "gdb/localgdbprocess.cpp",
- "gdb/localgdbprocess.h",
- "gdb/localplaingdbadapter.cpp",
- "gdb/localplaingdbadapter.h",
- "gdb/pythongdbengine.cpp",
- "gdb/remotegdbprocess.cpp",
- "gdb/remotegdbprocess.h",
- "gdb/remotegdbserveradapter.cpp",
- "gdb/remotegdbserveradapter.h",
- "gdb/remoteplaingdbadapter.cpp",
- "gdb/remoteplaingdbadapter.h",
- "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",
- "images/breakpoint_disabled_24.png",
- "images/breakpoint_disabled_32.png",
- "images/breakpoint_pending_16.png",
- "images/breakpoint_pending_24.png",
- "images/debugger_breakpoints.png",
- "images/debugger_continue.png",
- "images/debugger_continue_32.png",
- "images/debugger_continue_small.png",
- "images/debugger_empty_14.png",
- "images/debugger_interrupt.png",
- "images/debugger_interrupt_32.png",
- "images/debugger_interrupt_small.png",
- "images/debugger_reversemode_16.png",
- "images/debugger_singleinstructionmode.png",
- "images/debugger_snapshot_small.png",
- "images/debugger_start.png",
- "images/debugger_start_small.png",
- "images/debugger_stepinto_small.png",
- "images/debugger_steponeproc_small.png",
- "images/debugger_stepout_small.png",
- "images/debugger_stepover_small.png",
- "images/debugger_stepoverproc_small.png",
- "images/debugger_stop.png",
- "images/debugger_stop_32.png",
- "images/debugger_stop_small.png",
- "images/location_16.png",
- "images/location_24.png",
- "images/tracepoint.png",
- "images/watchpoint.png",
- "lldb/lldbengine.cpp",
- "lldb/lldbengine.h",
- "lldblib/ipcenginehost.cpp",
- "lldblib/ipcenginehost.h",
- "lldblib/lldbenginehost.cpp",
- "lldblib/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/baseqmldebuggerclient.cpp",
- "qml/baseqmldebuggerclient.h",
- "qml/interactiveinterpreter.cpp",
- "qml/interactiveinterpreter.h",
- "qml/qmladapter.cpp",
- "qml/qmladapter.h",
- "qml/qmlcppengine.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",
- "shared/backtrace.h",
- "shared/cdbsymbolpathlisteditor.cpp",
- "shared/cdbsymbolpathlisteditor.h",
- "shared/hostutils.cpp",
- "shared/hostutils.h",
- "shared/peutils.cpp",
- "shared/peutils.h",
- "shared/symbolpathsdialog.ui",
- "shared/symbolpathsdialog.cpp",
- "shared/symbolpathsdialog.h",
- ]
+ Group {
+ name: "cdb"
+ prefix: "cdb/"
+ files: [
+ "bytearrayinputstream.cpp", "bytearrayinputstream.h",
+ "cdbengine.cpp", "cdbengine.h",
+ "cdboptionspage.cpp", "cdboptionspage.h",
+ "cdboptionspagewidget.ui",
+ "cdbparsehelpers.cpp", "cdbparsehelpers.h"
+ ]
+ }
+
+ Group {
+ name: "gdb"
+ prefix: "gdb/"
+ files: [
+ "attachgdbadapter.cpp", "attachgdbadapter.h",
+ "classicgdbengine.cpp",
+ "coregdbadapter.cpp", "coregdbadapter.h",
+ "gdb.qrc",
+ "gdbengine.cpp", "gdbengine.h",
+ "gdboptionspage.cpp", "gdboptionspage.h",
+ "gdbprocess.cpp", "gdbprocess.h",
+ "gdbplainengine.cpp", "gdbplainengine.h",
+ "pythongdbengine.cpp",
+ "remotegdbserveradapter.cpp", "remotegdbserveradapter.h",
+ "startgdbserverdialog.cpp", "startgdbserverdialog.h",
+ "termgdbadapter.cpp", "termgdbadapter.h"
+ ]
+ }
+
+ Group {
+ name: "lldb"
+ prefix: "lldb/"
+ files: [
+ "lldbengine.cpp", "lldbengine.h"
+ ]
+ }
+
+ Group {
+ name: "lldblib"
+ id: lldblib
+ prefix: "lldblib/"
+ files: [
+ "ipcenginehost.cpp", "ipcenginehost.h",
+ "lldbenginehost.cpp", "lldbenginehost.h"
+ ]
+ }
+
+ Group {
+ name: "pdb"
+ prefix: "pdb/"
+ files: ["pdbengine.cpp", "pdbengine.h"]
+ }
+
+ Group {
+ name: "Name Demangler"
+ prefix: "namedemangler/"
+ files: [
+ "demanglerexceptions.h",
+ "globalparsestate.cpp", "globalparsestate.h",
+ "namedemangler.cpp", "namedemangler.h",
+ "parsetreenodes.cpp", "parsetreenodes.h",
+ ]
+ }
+
+ Group {
+ name: "QML Debugger"
+ prefix: "qml/"
+ files: [
+ "baseqmldebuggerclient.cpp", "baseqmldebuggerclient.h",
+ "interactiveinterpreter.cpp", "interactiveinterpreter.h",
+ "qmladapter.cpp", "qmladapter.h",
+ "qmlcppengine.cpp", "qmlcppengine.h",
+ "qmlengine.cpp", "qmlengine.h",
+ "qmlinspectoradapter.cpp", "qmlinspectoradapter.h",
+ "qmlinspectoragent.cpp", "qmlinspectoragent.h",
+ "qmllivetextpreview.cpp", "qmllivetextpreview.h",
+ "qmlv8debuggerclient.cpp", "qmlv8debuggerclient.h",
+ "qmlv8debuggerclientconstants.h",
+ "qscriptdebuggerclient.cpp", "qscriptdebuggerclient.h"
+ ]
+ }
+
+ Group {
+ name: "shared"
+ prefix: "shared/"
+ files: [
+ "backtrace.cpp", "backtrace.h",
+ "cdbsymbolpathlisteditor.cpp",
+ "cdbsymbolpathlisteditor.h",
+ "hostutils.cpp", "hostutils.h",
+ "peutils.cpp", "peutils.h",
+ "symbolpathsdialog.ui", "symbolpathsdialog.cpp", "symbolpathsdialog.h"
+ ]
+ }
+
+ Group {
+ name: "Images"
+ prefix: "images/"
+ files: [
+ "breakpoint_16.png",
+ "breakpoint_24.png",
+ "breakpoint_disabled_16.png",
+ "breakpoint_disabled_24.png",
+ "breakpoint_disabled_32.png",
+ "breakpoint_pending_16.png",
+ "breakpoint_pending_24.png",
+ "debugger_breakpoints.png",
+ "debugger_continue.png",
+ "debugger_continue_32.png",
+ "debugger_continue_small.png",
+ "debugger_empty_14.png",
+ "debugger_interrupt.png",
+ "debugger_interrupt_32.png",
+ "debugger_interrupt_small.png",
+ "debugger_reversemode_16.png",
+ "debugger_singleinstructionmode.png",
+ "debugger_snapshot_small.png",
+ "debugger_start.png",
+ "debugger_start_small.png",
+ "debugger_stepinto_small.png",
+ "debugger_steponeproc_small.png",
+ "debugger_stepout_small.png",
+ "debugger_stepover_small.png",
+ "debugger_stepoverproc_small.png",
+ "debugger_stop.png",
+ "debugger_stop_32.png",
+ "debugger_stop_small.png",
+ "location_16.png",
+ "location_24.png",
+ "tracepoint.png",
+ "watchpoint.png",
+ ]
+ }
Group {
name: "RegistryAccess"
@@ -305,8 +263,6 @@ QtcPlugin {
}
Export {
- Depends { name: "cpp" }
Depends { name: "QtcSsh" }
- cpp.includePaths: ["."]
}
}
diff --git a/src/plugins/debugger/debuggeractions.cpp b/src/plugins/debugger/debuggeractions.cpp
index c042217885..a8d4de09f5 100644
--- a/src/plugins/debugger/debuggeractions.cpp
+++ b/src/plugins/debugger/debuggeractions.cpp
@@ -33,6 +33,7 @@
#include "registerpostmortemaction.h"
#endif
+#include <coreplugin/icore.h>
#include <utils/savedaction.h>
#include <utils/qtcassert.h>
@@ -50,8 +51,9 @@ static const char sourcePathMappingTargetKeyC[] = "Target";
namespace Debugger {
namespace Internal {
-void GlobalDebuggerOptions::toSettings(QSettings *s) const
+void GlobalDebuggerOptions::toSettings() const
{
+ QSettings *s = Core::ICore::settings();
s->beginWriteArray(QLatin1String(sourcePathMappingArrayNameC));
if (!sourcePathMap.isEmpty()) {
const QString sourcePathMappingSourceKey = QLatin1String(sourcePathMappingSourceKeyC);
@@ -67,8 +69,9 @@ void GlobalDebuggerOptions::toSettings(QSettings *s) const
s->endArray();
}
-void GlobalDebuggerOptions::fromSettings(QSettings *s)
+void GlobalDebuggerOptions::fromSettings()
{
+ QSettings *s = Core::ICore::settings();
sourcePathMap.clear();
if (const int count = s->beginReadArray(QLatin1String(sourcePathMappingArrayNameC))) {
const QString sourcePathMappingSourceKey = QLatin1String(sourcePathMappingSourceKeyC);
@@ -88,9 +91,8 @@ void GlobalDebuggerOptions::fromSettings(QSettings *s)
//
//////////////////////////////////////////////////////////////////////////
-DebuggerSettings::DebuggerSettings(QSettings *settings)
+DebuggerSettings::DebuggerSettings()
{
- m_settings = settings;
const QString debugModeGroup = QLatin1String(debugModeSettingsGroupC);
const QString cdbSettingsGroup = QLatin1String(cdbSettingsGroupC);
@@ -541,6 +543,15 @@ DebuggerSettings::DebuggerSettings(QSettings *settings)
insertItem(UseToolTipsInBreakpointsView, item);
item = new SavedAction(this);
+ item->setSettingsKey(debugModeGroup, QLatin1String("UseToolTipsInBreakpointsView"));
+ item->setText(tr("Use Tooltips in Stack View when Debugging"));
+ item->setToolTip(tr("Checking this will enable tooltips in the stack "
+ "view during debugging."));
+ item->setCheckable(true);
+ item->setDefaultValue(true);
+ insertItem(UseToolTipsInStackView, item);
+
+ item = new SavedAction(this);
item->setSettingsKey(debugModeGroup, QLatin1String("UseAddressInBreakpointsView"));
item->setText(tr("Show Address Data in Breakpoints View when Debugging"));
item->setToolTip(tr("Checking this will show a column with address "
@@ -667,14 +678,16 @@ void DebuggerSettings::insertItem(int code, SavedAction *item)
void DebuggerSettings::readSettings()
{
+ QSettings *settings = Core::ICore::settings();
foreach (SavedAction *item, m_items)
- item->readSettings(m_settings);
+ item->readSettings(settings);
}
void DebuggerSettings::writeSettings() const
{
+ QSettings *settings = Core::ICore::settings();
foreach (SavedAction *item, m_items)
- item->writeSettings(m_settings);
+ item->writeSettings(settings);
}
SavedAction *DebuggerSettings::item(int code) const
diff --git a/src/plugins/debugger/debuggeractions.h b/src/plugins/debugger/debuggeractions.h
index 2abc5dddf4..f4398c5645 100644
--- a/src/plugins/debugger/debuggeractions.h
+++ b/src/plugins/debugger/debuggeractions.h
@@ -34,13 +34,7 @@
#include <QHash>
#include <QMap>
-QT_BEGIN_NAMESPACE
-class QSettings;
-QT_END_NAMESPACE
-
-namespace Utils {
-class SavedAction;
-}
+namespace Utils { class SavedAction; }
namespace Debugger {
namespace Internal {
@@ -51,8 +45,8 @@ class GlobalDebuggerOptions
public:
typedef QMap<QString, QString> SourcePathMap;
- void toSettings(QSettings *) const;
- void fromSettings(QSettings *);
+ void toSettings() const;
+ void fromSettings();
bool operator==(const GlobalDebuggerOptions &rhs) const
{ return sourcePathMap == rhs.sourcePathMap; }
bool operator!=(const GlobalDebuggerOptions &rhs) const
@@ -66,7 +60,7 @@ class DebuggerSettings : public QObject
Q_OBJECT // For tr().
public:
- explicit DebuggerSettings(QSettings *setting);
+ explicit DebuggerSettings();
~DebuggerSettings();
void insertItem(int code, Utils::SavedAction *item);
@@ -79,7 +73,6 @@ public:
private:
QHash<int, Utils::SavedAction *> m_items;
- QSettings *m_settings;
};
///////////////////////////////////////////////////////////
diff --git a/src/plugins/debugger/debuggerconstants.h b/src/plugins/debugger/debuggerconstants.h
index 313e36587d..a8848a50aa 100644
--- a/src/plugins/debugger/debuggerconstants.h
+++ b/src/plugins/debugger/debuggerconstants.h
@@ -187,7 +187,6 @@ enum DebuggerEngineType
{
NoEngineType = 0,
GdbEngineType = 0x001,
- ScriptEngineType = 0x002,
CdbEngineType = 0x004,
PdbEngineType = 0x008,
QmlEngineType = 0x020,
@@ -195,7 +194,6 @@ enum DebuggerEngineType
LldbLibEngineType = 0x080,
LldbEngineType = 0x100,
AllEngineTypes = GdbEngineType
- | ScriptEngineType
| CdbEngineType
| PdbEngineType
| QmlEngineType
diff --git a/src/plugins/debugger/debuggercore.h b/src/plugins/debugger/debuggercore.h
index c613f4c63d..d8119edea8 100644
--- a/src/plugins/debugger/debuggercore.h
+++ b/src/plugins/debugger/debuggercore.h
@@ -81,10 +81,11 @@ class DebuggerCore : public QObject
public:
DebuggerCore() {}
- virtual QVariant sessionValue(const QString &name) = 0;
- virtual void setSessionValue(const QString &name, const QVariant &value) = 0;
- virtual QVariant configValue(const QString &name) const = 0;
- virtual void setConfigValue(const QString &name, const QVariant &value) = 0;
+ static QVariant sessionValue(const QByteArray &name);
+ static void setSessionValue(const QByteArray &name, const QVariant &value);
+ static QVariant configValue(const QByteArray &name);
+ static void setConfigValue(const QByteArray &name, const QVariant &value);
+
virtual void updateState(DebuggerEngine *engine) = 0;
virtual void updateWatchersWindow(bool showWatch, bool showReturn) = 0;
virtual QIcon locationMarkIcon() const = 0;
diff --git a/src/plugins/debugger/debuggerdialogs.cpp b/src/plugins/debugger/debuggerdialogs.cpp
index 7aee285ea4..13f292de99 100644
--- a/src/plugins/debugger/debuggerdialogs.cpp
+++ b/src/plugins/debugger/debuggerdialogs.cpp
@@ -43,6 +43,7 @@
#include <QButtonGroup>
#include <QCheckBox>
+#include <QComboBox>
#include <QDebug>
#include <QDialogButtonBox>
#include <QDir>
@@ -73,6 +74,8 @@ class StartApplicationDialogPrivate
public:
KitChooser *kitChooser;
QLabel *serverPortLabel;
+ QLabel *serverAddressLabel;
+ QLineEdit *serverAddressEdit;
QSpinBox *serverPortSpinBox;
PathChooser *localExecutablePathChooser;
FancyLineEdit *arguments;
@@ -121,7 +124,7 @@ bool DebuggerKitChooser::kitMatches(const ProjectExplorer::Kit *k) const
QString DebuggerKitChooser::kitToolTip(Kit *k) const
{
- return DebuggerKitInformation::userOutput(DebuggerKitInformation::debuggerItem(k));
+ return DebuggerKitInformation::displayString(k);
}
///////////////////////////////////////////////////////////////////////
@@ -144,6 +147,7 @@ public:
Id kitId;
uint serverPort;
+ QString serverAddress;
QString localExecutable;
QString processArgs;
QString workingDirectory;
@@ -168,7 +172,8 @@ bool StartApplicationParameters::equals(const StartApplicationParameters &rhs) c
&& runInTerminal == rhs.runInTerminal
&& serverStartScript == rhs.serverStartScript
&& kitId == rhs.kitId
- && debugInfoLocation == rhs.debugInfoLocation;
+ && debugInfoLocation == rhs.debugInfoLocation
+ && serverAddress == rhs.serverAddress;
}
QString StartApplicationParameters::displayName() const
@@ -184,7 +189,7 @@ QString StartApplicationParameters::displayName() const
name += QLatin1String("...");
}
- if (Kit *kit = KitManager::instance()->find(kitId))
+ if (Kit *kit = KitManager::find(kitId))
name += QString::fromLatin1(" (%1)").arg(kit->displayName());
return name;
@@ -194,6 +199,7 @@ void StartApplicationParameters::toSettings(QSettings *settings) const
{
settings->setValue(_("LastKitId"), kitId.toSetting());
settings->setValue(_("LastServerPort"), serverPort);
+ settings->setValue(_("LastServerAddress"), serverAddress);
settings->setValue(_("LastExternalExecutable"), localExecutable);
settings->setValue(_("LastExternalExecutableArguments"), processArgs);
settings->setValue(_("LastExternalWorkingDirectory"), workingDirectory);
@@ -207,6 +213,7 @@ void StartApplicationParameters::fromSettings(const QSettings *settings)
{
kitId = Id::fromSetting(settings->value(_("LastKitId")));
serverPort = settings->value(_("LastServerPort")).toUInt();
+ serverAddress = settings->value(_("LastServerAddress")).toString();
localExecutable = settings->value(_("LastExternalExecutable")).toString();
processArgs = settings->value(_("LastExternalExecutableArguments")).toString();
workingDirectory = settings->value(_("LastExternalWorkingDirectory")).toString();
@@ -235,6 +242,9 @@ StartApplicationDialog::StartApplicationDialog(QWidget *parent)
d->serverPortSpinBox = new QSpinBox(this);
d->serverPortSpinBox->setRange(1, 65535);
+ d->serverAddressLabel = new QLabel(tr("Override server address"), this);
+ d->serverAddressEdit = new QLineEdit(this);
+
d->localExecutablePathChooser = new PathChooser(this);
d->localExecutablePathChooser->setExpectedKind(PathChooser::File);
d->localExecutablePathChooser->setPromptDialogTitle(tr("Select Executable"));
@@ -288,6 +298,7 @@ StartApplicationDialog::StartApplicationDialog(QWidget *parent)
formLayout->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow);
formLayout->addRow(tr("&Kit:"), d->kitChooser);
formLayout->addRow(d->serverPortLabel, d->serverPortSpinBox);
+ formLayout->addRow(d->serverAddressLabel, d->serverAddressEdit);
formLayout->addRow(tr("Local &executable:"), d->localExecutablePathChooser);
formLayout->addRow(tr("Command line &arguments:"), d->arguments);
formLayout->addRow(tr("&Working directory:"), d->workingDirectory);
@@ -343,13 +354,14 @@ void StartApplicationDialog::updateState()
d->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(okEnabled);
}
-bool StartApplicationDialog::run(QWidget *parent, QSettings *settings, DebuggerStartParameters *sp)
+bool StartApplicationDialog::run(QWidget *parent, DebuggerStartParameters *sp)
{
const bool attachRemote = sp->startMode == AttachToRemoteServer;
const QString settingsGroup = QLatin1String("DebugMode");
const QString arrayName = QLatin1String("StartApplication");
QList<StartApplicationParameters> history;
+ QSettings *settings = ICore::settings();
settings->beginGroup(settingsGroup);
if (const int arraySize = settings->beginReadArray(arrayName)) {
for (int i = 0; i < arraySize; ++i) {
@@ -372,6 +384,8 @@ bool StartApplicationDialog::run(QWidget *parent, QSettings *settings, DebuggerS
dialog.d->serverStartScriptLabel->setVisible(false);
dialog.d->serverPortSpinBox->setVisible(false);
dialog.d->serverPortLabel->setVisible(false);
+ dialog.d->serverAddressLabel->setVisible(false);
+ dialog.d->serverAddressEdit->setVisible(false);
}
if (dialog.exec() != QDialog::Accepted)
return false;
@@ -395,7 +409,12 @@ bool StartApplicationDialog::run(QWidget *parent, QSettings *settings, DebuggerS
QTC_ASSERT(kit && fillParameters(sp, kit), return false);
sp->executable = newParameters.localExecutable;
- sp->remoteChannel = sp->connParams.host + QLatin1Char(':') + QString::number(newParameters.serverPort);
+ const QString inputAddress = dialog.d->serverAddressEdit->text();
+ if (!inputAddress.isEmpty())
+ sp->remoteChannel = inputAddress;
+ else
+ sp->remoteChannel = sp->connParams.host;
+ sp->remoteChannel += QLatin1Char(':') + QString::number(newParameters.serverPort);
sp->displayName = newParameters.displayName();
sp->workingDirectory = newParameters.workingDirectory;
sp->useTerminal = newParameters.runInTerminal;
@@ -416,6 +435,7 @@ StartApplicationParameters StartApplicationDialog::parameters() const
{
StartApplicationParameters result;
result.serverPort = d->serverPortSpinBox->value();
+ result.serverAddress = d->serverAddressEdit->text();
result.localExecutable = d->localExecutablePathChooser->path();
result.serverStartScript = d->serverStartScriptPathChooser->path();
result.kitId = d->kitChooser->currentKitId();
@@ -431,6 +451,7 @@ void StartApplicationDialog::setParameters(const StartApplicationParameters &p)
{
d->kitChooser->setCurrentKitId(p.kitId);
d->serverPortSpinBox->setValue(p.serverPort);
+ d->serverAddressEdit->setText(p.serverAddress);
d->localExecutablePathChooser->setPath(p.localExecutable);
d->serverStartScriptPathChooser->setPath(p.serverStartScript);
d->debuginfoPathChooser->setPath(p.debugInfoLocation);
diff --git a/src/plugins/debugger/debuggerdialogs.h b/src/plugins/debugger/debuggerdialogs.h
index df3887c2ea..385462bc3e 100644
--- a/src/plugins/debugger/debuggerdialogs.h
+++ b/src/plugins/debugger/debuggerdialogs.h
@@ -82,8 +82,7 @@ public:
explicit StartApplicationDialog(QWidget *parent);
~StartApplicationDialog();
- static bool run(QWidget *parent, QSettings *settings,
- DebuggerStartParameters *sp);
+ static bool run(QWidget *parent, DebuggerStartParameters *sp);
private slots:
void historyIndexChanged(int);
diff --git a/src/plugins/debugger/debuggerengine.cpp b/src/plugins/debugger/debuggerengine.cpp
index 0daecf7c90..0b7fa892a5 100644
--- a/src/plugins/debugger/debuggerengine.cpp
+++ b/src/plugins/debugger/debuggerengine.cpp
@@ -40,14 +40,13 @@
#include "disassembleragent.h"
#include "memoryagent.h"
#include "moduleshandler.h"
-#include "peutils.h"
#include "registerhandler.h"
#include "sourcefileshandler.h"
#include "stackhandler.h"
#include "threadshandler.h"
#include "watchhandler.h"
+#include <debugger/shared/peutils.h>
-#include <coreplugin/icore.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/editormanager/ieditor.h>
#include <coreplugin/progressmanager/progressmanager.h>
@@ -167,8 +166,7 @@ public:
m_watchHandler(engine),
m_disassemblerAgent(engine),
m_memoryAgent(engine),
- m_isStateDebugging(false),
- m_taskHub(0)
+ m_isStateDebugging(false)
{
connect(&m_locationTimer, SIGNAL(timeout()), SLOT(resetLocation()));
}
@@ -255,8 +253,6 @@ public slots:
m_disassemblerAgent.resetLocation();
}
- TaskHub *taskHub();
-
public:
DebuggerState state() const { return m_state; }
RemoteSetupState remoteSetupState() const { return m_remoteSetupState; }
@@ -301,7 +297,6 @@ public:
bool m_isStateDebugging;
Utils::FileInProjectFinder m_fileFinder;
- TaskHub *m_taskHub;
};
@@ -420,59 +415,22 @@ SourceFilesHandler *DebuggerEngine::sourceFilesHandler() const
QAbstractItemModel *DebuggerEngine::modulesModel() const
{
- QAbstractItemModel *model = modulesHandler()->model();
- if (model->objectName().isEmpty()) // Make debugging easier.
- model->setObjectName(objectName() + QLatin1String("ModulesModel"));
- return model;
+ return modulesHandler()->model();
}
QAbstractItemModel *DebuggerEngine::registerModel() const
{
- QAbstractItemModel *model = registerHandler()->model();
- if (model->objectName().isEmpty()) // Make debugging easier.
- model->setObjectName(objectName() + QLatin1String("RegisterModel"));
- return model;
+ return registerHandler()->model();
}
QAbstractItemModel *DebuggerEngine::stackModel() const
{
- QAbstractItemModel *model = stackHandler()->model();
- if (model->objectName().isEmpty()) // Make debugging easier.
- model->setObjectName(objectName() + QLatin1String("StackModel"));
- return model;
+ return stackHandler()->model();
}
QAbstractItemModel *DebuggerEngine::threadsModel() const
{
- QAbstractItemModel *model = threadsHandler()->model();
- if (model->objectName().isEmpty()) // Make debugging easier.
- model->setObjectName(objectName() + QLatin1String("ThreadsModel"));
- return model;
-}
-
-QAbstractItemModel *DebuggerEngine::localsModel() const
-{
- return watchHandler()->model();
-}
-
-QAbstractItemModel *DebuggerEngine::watchersModel() const
-{
- return watchHandler()->model();
-}
-
-QAbstractItemModel *DebuggerEngine::returnModel() const
-{
- return watchHandler()->model();
-}
-
-QAbstractItemModel *DebuggerEngine::inspectorModel() const
-{
- return watchHandler()->model();
-}
-
-QAbstractItemModel *DebuggerEngine::toolTipsModel() const
-{
- return watchHandler()->model();
+ return threadsHandler()->model();
}
QAbstractItemModel *DebuggerEngine::watchModel() const
@@ -482,10 +440,7 @@ QAbstractItemModel *DebuggerEngine::watchModel() const
QAbstractItemModel *DebuggerEngine::sourceFilesModel() const
{
- QAbstractItemModel *model = sourceFilesHandler()->model();
- if (model->objectName().isEmpty()) // Make debugging easier.
- model->setObjectName(objectName() + QLatin1String("SourceFilesModel"));
- return model;
+ return sourceFilesHandler()->model();
}
void DebuggerEngine::fetchMemory(MemoryAgent *, QObject *,
@@ -533,10 +488,9 @@ void DebuggerEngine::startDebugger(DebuggerRunControl *runControl)
QTC_ASSERT(!d->m_runControl, notifyEngineSetupFailed(); return);
d->m_progress.setProgressRange(0, 1000);
- Core::FutureProgress *fp = Core::ICore::progressManager()
- ->addTask(d->m_progress.future(),
- tr("Launching"), _("Debugger.Launcher"));
- fp->setKeepOnFinish(Core::FutureProgress::HideOnFinish);
+ FutureProgress *fp = ProgressManager::addTask(d->m_progress.future(),
+ tr("Launching"), "Debugger.Launcher");
+ fp->setKeepOnFinish(FutureProgress::HideOnFinish);
d->m_progress.reportStarted();
d->m_runControl = runControl;
@@ -582,20 +536,13 @@ void DebuggerEngine::gotoLocation(const Location &loc)
const QString file = loc.fileName();
const int line = loc.lineNumber();
- QList<IEditor *> editors = EditorManager::instance()->editorsForFileName(file);
- IEditor *editor = 0;
- if (editors.isEmpty()) {
- editor = EditorManager::openEditor(file, Core::Id(),
- EditorManager::IgnoreNavigationHistory);
- QTC_ASSERT(editor, return); // Unreadable file?
- editor->setProperty(Constants::OPENED_BY_DEBUGGER, true);
- } else {
- editor = editors.back();
- }
-
- ITextEditor *texteditor = qobject_cast<ITextEditor *>(editor);
- if (texteditor)
- texteditor->gotoLine(line, 0);
+ bool newEditor = false;
+ IEditor *editor = EditorManager::openEditor(file, Id(),
+ EditorManager::IgnoreNavigationHistory, &newEditor);
+ QTC_ASSERT(editor, return); // Unreadable file?
+ editor->gotoLine(line, 0);
+ if (newEditor)
+ editor->document()->setProperty(Constants::OPENED_BY_DEBUGGER, true);
if (loc.needsMarker()) {
d->m_locationMark.reset(new TextEditor::BaseTextMark(file, line));
@@ -604,9 +551,6 @@ void DebuggerEngine::gotoLocation(const Location &loc)
d->m_locationMark->init();
}
- // FIXME: Breaks with split views.
- if (!d->m_memoryAgent.hasVisibleEditor() || loc.needsRaise())
- EditorManager::activateEditor(editor);
//qDebug() << "MEMORY: " << d->m_memoryAgent.hasVisibleEditor();
}
@@ -1462,7 +1406,7 @@ void DebuggerEngine::reloadDebuggingHelpers()
{
}
-void DebuggerEngine::addOptionPages(QList<Core::IOptionsPage*> *) const
+void DebuggerEngine::addOptionPages(QList<IOptionsPage*> *) const
{
}
@@ -1868,25 +1812,6 @@ void DebuggerEngine::checkForReleaseBuild(const DebuggerStartParameters &sp)
"Setting breakpoints by file name and line number may fail.\n").append(detailedWarning));
}
-TaskHub *DebuggerEnginePrivate::taskHub()
-{
- if (!m_taskHub) {
- m_taskHub = ProjectExplorerPlugin::instance()->taskHub();
- 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;
-}
-
-TaskHub *DebuggerEngine::taskHub()
-{
- return d->taskHub();
-}
-
} // namespace Debugger
#include "debuggerengine.moc"
diff --git a/src/plugins/debugger/debuggerengine.h b/src/plugins/debugger/debuggerengine.h
index 74626857f7..99ece70f58 100644
--- a/src/plugins/debugger/debuggerengine.h
+++ b/src/plugins/debugger/debuggerengine.h
@@ -46,7 +46,6 @@ QT_END_NAMESPACE
namespace TextEditor { class ITextEditor; }
namespace Core { class IOptionsPage; }
-namespace ProjectExplorer { class TaskHub; }
namespace Debugger {
@@ -196,7 +195,6 @@ public:
virtual void createSnapshot();
virtual void updateAll();
- ProjectExplorer::TaskHub *taskHub();
typedef Internal::BreakpointModelId BreakpointModelId;
virtual bool stateAcceptsBreakpointChanges() const { return true; }
@@ -223,11 +221,6 @@ public:
virtual QAbstractItemModel *registerModel() const;
virtual QAbstractItemModel *stackModel() const;
virtual QAbstractItemModel *threadsModel() const;
- virtual QAbstractItemModel *localsModel() const; // Deprecated, FIXME: use watchModel
- virtual QAbstractItemModel *watchersModel() const; // Deprecated, FIXME: use watchModel
- virtual QAbstractItemModel *returnModel() const; // Deprecated, FIXME: use watchModel
- virtual QAbstractItemModel *inspectorModel() const; // Deprecated, FIXME: use watchModel
- virtual QAbstractItemModel *toolTipsModel() const; // Deprecated, FIXME: use watchModel
virtual QAbstractItemModel *watchModel() const;
virtual QAbstractItemModel *sourceFilesModel() const;
diff --git a/src/plugins/debugger/debuggerinternalconstants.h b/src/plugins/debugger/debuggerinternalconstants.h
index 98118808b7..b5ed7da1b7 100644
--- a/src/plugins/debugger/debuggerinternalconstants.h
+++ b/src/plugins/debugger/debuggerinternalconstants.h
@@ -46,7 +46,6 @@ namespace Internal {
const char OPENED_BY_DEBUGGER[] = "OpenedByDebugger";
const char OPENED_WITH_DISASSEMBLY[] = "DisassemblerView";
-const char OPENED_WITH_MEMORY[] = "MemoryView";
// Debug action
const char DEBUG[] = "Debugger.Debug";
diff --git a/src/plugins/debugger/debuggerkitconfigwidget.cpp b/src/plugins/debugger/debuggerkitconfigwidget.cpp
index 4992bdc789..bf50f7b085 100644
--- a/src/plugins/debugger/debuggerkitconfigwidget.cpp
+++ b/src/plugins/debugger/debuggerkitconfigwidget.cpp
@@ -32,59 +32,872 @@
#include <coreplugin/icore.h>
#include <projectexplorer/abi.h>
+#include <projectexplorer/projectexplorerconstants.h>
+#include <projectexplorer/toolchain.h>
+#include <projectexplorer/toolchainmanager.h>
-#include <utils/pathchooser.h>
#include <utils/elidinglabel.h>
+#include <utils/environment.h>
+#include <utils/pathchooser.h>
+#include <utils/persistentsettings.h>
+#include <utils/qtcassert.h>
#ifdef Q_OS_WIN
#include <utils/winutils.h>
#endif
-#include <QFormLayout>
+#include <QApplication>
#include <QComboBox>
+#include <QDirIterator>
+#include <QFileInfo>
+#include <QFormLayout>
+#include <QHeaderView>
+#include <QLineEdit>
#include <QPushButton>
-#include <QDialogButtonBox>
+#include <QStandardItem>
+#include <QStandardItemModel>
+#include <QTreeView>
+#include <QUuid>
+
+using namespace ProjectExplorer;
+using namespace Utils;
+using namespace Debugger::Internal;
namespace Debugger {
-namespace Internal {
static const char debuggingToolsWikiLinkC[] = "http://qt-project.org/wiki/Qt_Creator_Windows_Debugging";
+static const char DEBUGGER_DATA_KEY[] = "DebuggerItem.";
+static const char DEBUGGER_COUNT_KEY[] = "DebuggerItem.Count";
+static const char DEBUGGER_FILE_VERSION_KEY[] = "Version";
+static const char DEBUGGER_FILENAME[] = "/qtcreator/debuggers.xml";
+static const char DEBUGGER_LEGACY_FILENAME[] = "/qtcreator/profiles.xml";
+
+// --------------------------------------------------------------------------
+// Helpers
+// --------------------------------------------------------------------------
+
+static DebuggerItemManager *theDebuggerItemManager()
+{
+ static DebuggerItemManager *manager = new DebuggerItemManager(0);
+ return manager;
+}
+// --------------------------------------------------------------------------
+// DebuggerKitInformation
+// --------------------------------------------------------------------------
+
+DebuggerKitInformation::DebuggerKitInformation()
+{
+ setObjectName(QLatin1String("DebuggerKitInformation"));
+ setId(DebuggerKitInformation::id());
+ setPriority(28000);
+}
+
+QVariant DebuggerKitInformation::defaultValue(Kit *k) const
+{
+// This is only called from Kit::Kit()
+// if (isValidDebugger(k)) {
+// DebuggerItem *item = DebuggerItemManager::debuggerFromKit(k);
+// QTC_ASSERT(item, return QVariant());
+// return item->id;
+// }
+ ToolChain *tc = ToolChainKitInformation::toolChain(k);
+ return theDebuggerItemManager()->defaultDebugger(tc);
+}
+
+void DebuggerKitInformation::setup(Kit *k)
+{
+ k->setValue(DebuggerKitInformation::id(), defaultValue(k));
+}
+
+// Check the configuration errors and return a flag mask. Provide a quick check and
+// a verbose one with a list of errors.
+
+enum DebuggerConfigurationErrors {
+ NoDebugger = 0x1,
+ DebuggerNotFound = 0x2,
+ DebuggerNotExecutable = 0x4,
+ DebuggerNeedsAbsolutePath = 0x8
+};
+
+static QVariant debuggerPathOrId(const Kit *k)
+{
+ QTC_ASSERT(k, return QString());
+ QVariant id = k->value(DebuggerKitInformation::id());
+ if (!id.isValid())
+ return id; // Invalid.
+
+ // With 3.0 we have:
+ // <value type="QString" key="Debugger.Information">{75ecf347-f221-44c3-b613-ea1d29929cd4}</value>
+ if (id.type() == QVariant::String)
+ return id;
+
+ // Before we had:
+ // <valuemap type="QVariantMap" key="Debugger.Information">
+ // <value type="QString" key="Binary">/data/dev/debugger/gdb-git/gdb/gdb</value>
+ // <value type="int" key="EngineType">1</value>
+ // </valuemap>
+ return id.toMap().value(QLatin1String("Binary"));
+}
+
+static unsigned debuggerConfigurationErrors(const Kit *k)
+{
+ QTC_ASSERT(k, return NoDebugger);
+
+ const DebuggerItem *item = DebuggerItemManager::debuggerFromKit(k);
+ if (!item)
+ return NoDebugger;
+
+ if (item->command().isEmpty())
+ return NoDebugger;
+
+ unsigned result = 0;
+ const QFileInfo fi = item->command().toFileInfo();
+ if (!fi.exists() || fi.isDir())
+ result |= DebuggerNotFound;
+ else if (!fi.isExecutable())
+ result |= DebuggerNotExecutable;
+
+ if (!fi.exists() || fi.isDir()) {
+ if (item->engineType() == NoEngineType)
+ return NoDebugger;
+
+ // We need an absolute path to be able to locate Python on Windows.
+ if (item->engineType() == GdbEngineType)
+ if (const ToolChain *tc = ToolChainKitInformation::toolChain(k))
+ if (tc->targetAbi().os() == Abi::WindowsOS && !fi.isAbsolute())
+ result |= DebuggerNeedsAbsolutePath;
+ }
+ return result;
+}
+
+bool DebuggerKitInformation::isValidDebugger(const Kit *k)
+{
+ return debuggerConfigurationErrors(k) == 0;
+}
+
+QList<Task> DebuggerKitInformation::validateDebugger(const Kit *k)
+{
+ QList<Task> result;
+
+ const unsigned errors = debuggerConfigurationErrors(k);
+ if (!errors)
+ return result;
+
+ QString path;
+ if (const DebuggerItem *item = DebuggerItemManager::debuggerFromKit(k))
+ path = item->command().toUserOutput();
+
+ const Core::Id id = ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM;
+ if (errors & NoDebugger)
+ result << Task(Task::Warning, tr("No debugger set up."), FileName(), -1, id);
+
+ if (errors & DebuggerNotFound)
+ result << Task(Task::Error, tr("Debugger '%1' not found.").arg(path),
+ FileName(), -1, id);
+ if (errors & DebuggerNotExecutable)
+ result << Task(Task::Error, tr("Debugger '%1' not executable.").arg(path), FileName(), -1, id);
+
+ if (errors & DebuggerNeedsAbsolutePath) {
+ const QString message =
+ tr("The debugger location must be given as an "
+ "absolute path (%1).").arg(path);
+ result << Task(Task::Error, message, FileName(), -1, id);
+ }
+ return result;
+}
+
+KitConfigWidget *DebuggerKitInformation::createConfigWidget(Kit *k) const
+{
+ return new Internal::DebuggerKitConfigWidget(k, this);
+}
+
+KitInformation::ItemList DebuggerKitInformation::toUserOutput(const Kit *k) const
+{
+ return ItemList() << qMakePair(tr("Debugger"), displayString(k));
+}
+
+FileName DebuggerKitInformation::debuggerCommand(const ProjectExplorer::Kit *k)
+{
+ const DebuggerItem *item = DebuggerItemManager::debuggerFromKit(k);
+ QTC_ASSERT(item, return FileName());
+ return item->command();
+}
+
+DebuggerEngineType DebuggerKitInformation::engineType(const ProjectExplorer::Kit *k)
+{
+ const DebuggerItem *item = DebuggerItemManager::debuggerFromKit(k);
+ QTC_ASSERT(item, return NoEngineType);
+ return item->engineType();
+}
+
+QString DebuggerKitInformation::displayString(const Kit *k)
+{
+ const DebuggerItem *item = DebuggerItemManager::debuggerFromKit(k);
+ if (!item)
+ return tr("No Debugger");
+ QString binary = item->command().toUserOutput();
+ QString name = tr("%1 Engine").arg(item->engineTypeName());
+ return binary.isEmpty() ? tr("%1 <None>").arg(name) : tr("%1 using \"%2\"").arg(name, binary);
+}
+
+void DebuggerKitInformation::setDebugger(Kit *k, const DebuggerItem &item)
+{
+ DebuggerItemManager *manager = theDebuggerItemManager();
+ // Only register reasonably complete debuggers.
+ QTC_ASSERT(!item.id().isValid(), return);
+ QTC_ASSERT(!item.command().isEmpty(), return);
+ QTC_ASSERT(!item.displayName().isEmpty(), return);
+ QTC_ASSERT(item.engineType() != NoEngineType, return);
+ QVariant id = manager->registerDebugger(item);
+ QTC_CHECK(id.isValid());
+ k->setValue(DebuggerKitInformation::id(), id);
+}
+
+void DebuggerKitInformation::setDebugger(Kit *k, const FileName &command)
+{
+ DebuggerItem item;
+ item.setEngineType(GdbEngineType);
+ item.setCommand(command);
+ setDebugger(k, item);
+}
+
+Core::Id DebuggerKitInformation::id()
+{
+ return "Debugger.Information";
+}
+
+namespace Internal {
+
+static FileName userSettingsFileName()
+{
+ QFileInfo settingsLocation(Core::ICore::settings()->fileName());
+ return FileName::fromString(settingsLocation.absolutePath() + QLatin1String(DEBUGGER_FILENAME));
+}
+
+static QList<QStandardItem *> describeItem(const DebuggerItem &item)
+{
+ QList<QStandardItem *> row;
+ row.append(new QStandardItem(item.displayName()));
+ row.append(new QStandardItem(item.command().toUserOutput()));
+ row.append(new QStandardItem(item.engineTypeName()));
+ row.at(0)->setData(item.id());
+ row.at(0)->setEditable(false);
+ row.at(1)->setEditable(false);
+ row.at(2)->setEditable(false);
+ row.at(0)->setSelectable(true);
+ row.at(1)->setSelectable(true);
+ row.at(2)->setSelectable(true);
+ return row;
+}
+
+static QList<QStandardItem *> createRow(const QString &display)
+{
+ QList<QStandardItem *> row;
+ row.append(new QStandardItem(display));
+ row.append(new QStandardItem());
+ row.append(new QStandardItem());
+ row.at(0)->setEditable(false);
+ row.at(1)->setEditable(false);
+ row.at(2)->setEditable(false);
+ row.at(0)->setSelectable(false);
+ row.at(1)->setSelectable(false);
+ row.at(2)->setSelectable(false);
+ return row;
+}
+
+class DebuggerItemConfigWidget;
+
+// --------------------------------------------------------------------------
+// DebuggerItemManager
+// --------------------------------------------------------------------------
+
+DebuggerItemManager::DebuggerItemManager(QObject *parent)
+ : QStandardItemModel(parent)
+{
+ setColumnCount(3);
+
+ QList<QStandardItem *> row = createRow(tr("Auto-detected"));
+ m_autoRoot = row.at(0);
+ appendRow(row);
+
+ row = createRow(tr("Manual"));
+ m_manualRoot = row.at(0);
+ appendRow(row);
+
+ m_writer = new PersistentSettingsWriter(userSettingsFileName(), QLatin1String("QtCreatorDebugger"));
+
+ connect(Core::ICore::instance(), SIGNAL(saveSettingsRequested()),
+ this, SLOT(saveDebuggers()));
+}
+
+DebuggerItemManager::~DebuggerItemManager()
+{
+ disconnect(Core::ICore::instance(), SIGNAL(saveSettingsRequested()),
+ this, SLOT(saveDebuggers()));
+ delete m_writer;
+}
+
+QVariant DebuggerItemManager::headerData(int section, Qt::Orientation orientation, int role) const
+{
+ if (role == Qt::DisplayRole && orientation == Qt::Horizontal) {
+ switch (section) {
+ case 0:
+ return tr("Name");
+ case 1:
+ return tr("Path");
+ case 2:
+ return tr("Type");
+ }
+ }
+ return QVariant();
+}
+
+QString DebuggerItemManager::uniqueDisplayName(const QString &base) const
+{
+ foreach (const DebuggerItem &item, m_debuggers)
+ if (item.displayName() == base)
+ return uniqueDisplayName(base + QLatin1String(" (1)"));
+
+ return base;
+}
+
+void DebuggerItemManager::autoDetectCdbDebugger()
+{
+ QList<FileName> cdbs;
+
+ QStringList programDirs;
+ programDirs.append(QString::fromLocal8Bit(qgetenv("ProgramFiles")));
+ programDirs.append(QString::fromLocal8Bit(qgetenv("ProgramFiles(x86)")));
+ programDirs.append(QString::fromLocal8Bit(qgetenv("ProgramW6432")));
+
+ foreach (const QString &dirName, programDirs) {
+ if (dirName.isEmpty())
+ continue;
+ QDir dir(dirName);
+ // Windows SDK's starting from version 8 live in
+ // "ProgramDir\Windows Kits\<version>"
+ const QString windowsKitsFolderName = QLatin1String("Windows Kits");
+ if (dir.exists(windowsKitsFolderName)) {
+ QDir windowKitsFolder = dir;
+ if (windowKitsFolder.cd(windowsKitsFolderName)) {
+ // Check in reverse order (latest first)
+ const QFileInfoList kitFolders =
+ windowKitsFolder.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot,
+ QDir::Time | QDir::Reversed);
+ foreach (const QFileInfo &kitFolderFi, kitFolders) {
+ const QString path = kitFolderFi.absoluteFilePath();
+ const QFileInfo cdb32(path + QLatin1String("/Debuggers/x86/cdb.exe"));
+ if (cdb32.isExecutable())
+ cdbs.append(FileName::fromString(cdb32.absoluteFilePath()));
+ const QFileInfo cdb64(path + QLatin1String("/Debuggers/x64/cdb.exe"));
+ if (cdb64.isExecutable())
+ cdbs.append(FileName::fromString(cdb64.absoluteFilePath()));
+ }
+ }
+ }
+
+ // Pre Windows SDK 8: Check 'Debugging Tools for Windows'
+ foreach (const QFileInfo &fi, dir.entryInfoList(QStringList(QLatin1String("Debugging Tools for Windows*")),
+ QDir::Dirs | QDir::NoDotAndDotDot)) {
+ FileName filePath(fi);
+ filePath.appendPath(QLatin1String("cdb.exe"));
+ if (!cdbs.contains(filePath))
+ cdbs.append(filePath);
+ }
+ }
+
+ foreach (const FileName &cdb, cdbs) {
+ if (findByCommand(cdb))
+ continue;
+ DebuggerItem item;
+ item.setAutoDetected(true);
+ item.setAbis(Abi::abisOfBinary(cdb));
+ item.setCommand(cdb);
+ item.setEngineType(CdbEngineType);
+ item.setDisplayName(uniqueDisplayName(tr("Auto-detected CDB at %1").arg(cdb.toUserOutput())));
+ doAddDebugger(item);
+ }
+}
+
+void DebuggerItemManager::autoDetectDebuggers()
+{
+ autoDetectCdbDebugger();
+
+ QStringList filters;
+ filters.append(QLatin1String("gdb-i686-pc-mingw32"));
+ filters.append(QLatin1String("gdb"));
+ filters.append(QLatin1String("lldb"));
+ filters.append(QLatin1String("lldb-*"));
+
+ QFileInfoList suspects;
+
+ QStringList path = Environment::systemEnvironment().path();
+ foreach (const QString &base, path) {
+ QDir dir(base);
+ dir.setNameFilters(filters);
+ suspects += dir.entryInfoList();
+ }
+
+ foreach (const QFileInfo &fi, suspects) {
+ if (fi.exists()) {
+ FileName command = FileName::fromString(fi.absoluteFilePath());
+ if (findByCommand(command))
+ continue;
+ DebuggerItem item;
+ item.setCommand(command);
+ item.reinitializeFromFile();
+ item.setDisplayName(tr("System %1 at %2")
+ .arg(item.engineTypeName()).arg(fi.absoluteFilePath()));
+ item.setAutoDetected(true);
+ doAddDebugger(item);
+ }
+ }
+}
+
+void DebuggerItemManager::readLegacyDebuggers()
+{
+ QFileInfo settingsLocation(Core::ICore::settings()->fileName());
+ FileName legacyKits = FileName::fromString(settingsLocation.absolutePath() + QLatin1String(DEBUGGER_LEGACY_FILENAME));
+
+ PersistentSettingsReader reader;
+ if (!reader.load(legacyKits))
+ return;
+
+ foreach (const QVariant &v, reader.restoreValues()) {
+ QVariantMap data1 = v.toMap();
+ QString kitName = data1.value(QLatin1String("PE.Profile.Name")).toString();
+ QVariantMap data2 = data1.value(QLatin1String("PE.Profile.Data")).toMap();
+ QVariant v3 = data2.value(DebuggerKitInformation::id().toString());
+ QString fn;
+ if (v3.type() == QVariant::String)
+ fn = v3.toString();
+ else
+ fn = v3.toMap().value(QLatin1String("Binary")).toString();
+ if (fn.isEmpty())
+ continue;
+ if (fn.startsWith(QLatin1Char('{')))
+ continue;
+ FileName command = FileName::fromUserInput(fn);
+ if (findByCommand(command))
+ continue;
+ DebuggerItem item;
+ item.setCommand(command);
+ item.setAutoDetected(true);
+ item.reinitializeFromFile();
+ item.setDisplayName(tr("Extracted from Kit %1").arg(kitName));
+ doAddDebugger(item);
+ }
+}
+
+QVariant DebuggerItemManager::doAddDebugger(const DebuggerItem &item0)
+{
+ DebuggerItem item = item0;
+ if (item.id().isNull())
+ item.setId(QUuid::createUuid().toString());
+ QList<QStandardItem *> row = describeItem(item);
+ (item.isAutoDetected() ? m_autoRoot : m_manualRoot)->appendRow(row);
+ m_debuggers.append(item);
+ emit debuggerAdded(item.id(), item.displayName());
+ return item.id();
+}
+
+const DebuggerItem *DebuggerItemManager::findByCommand(const FileName &command)
+{
+ foreach (const DebuggerItem &item, m_debuggers)
+ if (item.command() == command)
+ return &item;
+
+ return 0;
+}
+
+const DebuggerItem *DebuggerItemManager::findById(const QVariant &id)
+{
+ foreach (const DebuggerItem &item, m_debuggers)
+ if (item.id() == id)
+ return &item;
+
+ return 0;
+}
+
+QStandardItem *DebuggerItemManager::currentStandardItem() const
+{
+ for (int i = 0, n = m_autoRoot->rowCount(); i != n; ++i) {
+ QStandardItem *sitem = m_autoRoot->child(i);
+ if (sitem->data() == m_currentDebugger)
+ return sitem;
+ }
+ for (int i = 0, n = m_manualRoot->rowCount(); i != n; ++i) {
+ QStandardItem *sitem = m_manualRoot->child(i);
+ if (sitem->data() == m_currentDebugger)
+ return sitem;
+ }
+ return 0;
+}
+
+static QList<DebuggerItem> readDebuggers(const FileName &fileName)
+{
+ QList<DebuggerItem> result;
+
+ PersistentSettingsReader reader;
+ if (!reader.load(fileName))
+ return result;
+ QVariantMap data = reader.restoreValues();
+
+ // Check version
+ int version = data.value(QLatin1String(DEBUGGER_FILE_VERSION_KEY), 0).toInt();
+ if (version < 1)
+ return result;
+
+ // Read default debugger settings (if any)
+// int count = data.value(QLatin1String(DEFAULT_DEBUGGER_COUNT_KEY)).toInt();
+// for (int i = 0; i < count; ++i) {
+// const QString abiKey = QString::fromLatin1(DEFAULT_DEBUGGER_ABI_KEY) + QString::number(i);
+// if (!data.contains(abiKey))
+// continue;
+// const QString pathKey = QString::fromLatin1(DEFAULT_DEBUGGER_PATH_KEY) + QString::number(i);
+// if (!data.contains(pathKey))
+// continue;
+// m_abiToDebugger.insert(data.value(abiKey).toString(),
+// FileName::fromString(data.value(pathKey).toString()));
+// }
+
+// QList<DebuggerFactory *> factories = ExtensionSystem::PluginManager::getObjects<DebuggerFactory>();
+
+ int count = data.value(QLatin1String(DEBUGGER_COUNT_KEY), 0).toInt();
+ for (int i = 0; i < count; ++i) {
+ const QString key = QString::fromLatin1(DEBUGGER_DATA_KEY) + QString::number(i);
+ if (!data.contains(key))
+ break;
+ const QVariantMap dbMap = data.value(key).toMap();
+ DebuggerItem item;
+ item.fromMap(dbMap);
+ result.append(item);
+ }
+
+ return result;
+}
+
+void DebuggerItemManager::restoreDebuggers()
+{
+ QList<DebuggerItem> dbsToCheck;
+
+ // Read debuggers from SDK
+ QFileInfo systemSettingsFile(Core::ICore::settings(QSettings::SystemScope)->fileName());
+ QList<DebuggerItem> dbsToRegister =
+ readDebuggers(FileName::fromString(systemSettingsFile.absolutePath() + QLatin1String(DEBUGGER_FILENAME)));
+
+ // These are autodetected.
+ for (int i = 0, n = dbsToRegister.size(); i != n; ++i)
+ dbsToRegister[i].setAutoDetected(true);
+
+ // SDK debuggers are always considered to be up-to-date, so no need to recheck them.
+
+ // Read all debuggers from user file.
+ foreach (const DebuggerItem &item, readDebuggers(userSettingsFileName())) {
+ if (item.isAutoDetected())
+ dbsToCheck.append(item);
+ else
+ dbsToRegister.append(item);
+ }
+
+ // Remove debuggers configured by the SDK.
+// foreach (const DebuggerItem &item, dbsToRegister) {
+// for (int i = dbsToCheck.count(); --i >= 0; ) {
+// if (dbsToCheck.at(i).id == item.id)
+// dbsToCheck.removeAt(i);
+// }
+// }
+
+// QList<DebuggerItem *> detectedDbs;
+// QList<DebuggerFactory *> factories = ExtensionSystem::PluginManager::getObjects<DebuggerFactory>();
+// foreach (DebuggerFactory *f, factories)
+// detectedDbs.append(f->autoDetect());
+
+ // Find/update autodetected debuggers
+// DebuggerItem *toStore = 0;
+// foreach (DebuggerItem *currentDetected, detectedDbs) {
+// toStore = currentDetected;
+
+// // Check whether we had this debugger stored and prefer the old one with the old id:
+// for (int i = 0; i < dbsToCheck.count(); ++i) {
+// if (*(dbsToCheck.at(i)) == *currentDetected) {
+// toStore = dbsToCheck.at(i);
+// dbsToCheck.removeAt(i);
+// delete currentDetected;
+// break;
+// }
+// }
+// dbsToRegister += toStore;
+// }
+
+ // Keep debuggers that were not rediscovered but are still executable and delete the rest
+ foreach (const DebuggerItem &item, dbsToCheck) {
+ if (!item.isValid()) {
+ qWarning() << QString::fromLatin1("DebuggerItem \"%1\" (%2) dropped since it is not valid")
+ .arg(item.command().toString()).arg(item.id().toString());
+ } else {
+ dbsToRegister.append(item);
+ }
+ }
+
+ // Store manual debuggers
+ DebuggerItemManager *manager = theDebuggerItemManager();
+ for (int i = 0, n = dbsToRegister.size(); i != n; ++i) {
+ DebuggerItem item = dbsToRegister.at(i);
+ if (manager->findByCommand(item.command()))
+ continue;
+ manager->doAddDebugger(item);
+ }
+
+ // Auto detect current.
+ manager->autoDetectDebuggers();
+
+ // Add debuggers from pre-3.x profiles.xml
+ manager->readLegacyDebuggers();
+}
+
+void DebuggerItemManager::saveDebuggers()
+{
+ QTC_ASSERT(m_writer, return);
+ QVariantMap data;
+ data.insert(QLatin1String(DEBUGGER_FILE_VERSION_KEY), 1);
+
+ int count = 0;
+ foreach (const DebuggerItem &item, m_debuggers) {
+ if (item.isValid()) {
+ QVariantMap tmp = item.toMap();
+ if (tmp.isEmpty())
+ continue;
+ data.insert(QString::fromLatin1(DEBUGGER_DATA_KEY) + QString::number(count), tmp);
+ ++count;
+ }
+ }
+ data.insert(QLatin1String(DEBUGGER_COUNT_KEY), count);
+ m_writer->save(data, Core::ICore::mainWindow());
+
+ // Do not save default debuggers as they are set by the SDK.
+}
+
+const DebuggerItem *DebuggerItemManager::debuggerFromKit(const Kit *kit)
+{
+ if (!kit)
+ return 0;
+ QVariant pathOrId = debuggerPathOrId(kit);
+ foreach (const DebuggerItem &item, theDebuggerItemManager()->m_debuggers) {
+ if (item.id() == pathOrId)
+ return &item;
+ if (item.command() == FileName::fromUserInput(pathOrId.toString()))
+ return &item;
+ }
+ return 0;
+}
+
+QVariant DebuggerItemManager::registerDebugger(const DebuggerItem &item)
+{
+ if (const DebuggerItem *found = findByCommand(item.command()))
+ return found->id();
+
+ return doAddDebugger(item);
+}
+
+QModelIndex DebuggerItemManager::currentIndex() const
+{
+ QStandardItem *current = currentStandardItem();
+ return current ? current->index() : QModelIndex();
+}
+
+void DebuggerItemManager::addDebugger()
+{
+ DebuggerItem item;
+ item.setEngineType(NoEngineType);
+ item.setDisplayName(uniqueDisplayName(tr("New Debugger")));
+ item.setAutoDetected(false);
+ doAddDebugger(item);
+}
+
+void DebuggerItemManager::cloneDebugger()
+{
+ const DebuggerItem *item = findById(m_currentDebugger);
+ QTC_ASSERT(item, return);
+ DebuggerItem newItem = *item;
+ newItem.setDisplayName(uniqueDisplayName(tr("Clone of %1").arg(item->displayName())));
+ newItem.setAutoDetected(false);
+ doAddDebugger(newItem);
+}
+
+void DebuggerItemManager::removeDebugger()
+{
+ QTC_ASSERT(m_currentDebugger.isValid(), return);
+ QVariant id = m_currentDebugger;
+ bool ok = false;
+ for (int i = 0, n = m_debuggers.size(); i != n; ++i) {
+ if (m_debuggers.at(i).id() == id) {
+ m_debuggers.removeAt(i);
+ ok = true;
+ break;
+ }
+ }
+ QTC_ASSERT(ok, return);
+ QStandardItem *sitem = currentStandardItem();
+ QTC_ASSERT(sitem, return);
+ QStandardItem *parent = sitem->parent();
+ QTC_ASSERT(parent, return);
+ // This will trigger a change of m_currentDebugger via changing the
+ // view selection.
+ parent->removeRow(sitem->row());
+ emit debuggerRemoved(id);
+}
+
+void DebuggerItemManager::markCurrentDirty()
+{
+ QStandardItem *sitem = currentStandardItem();
+ QTC_ASSERT(sitem, return);
+ QFont font = sitem->font();
+ font.setBold(true);
+ sitem->setFont(font);
+}
+
+void DebuggerItemManager::setCurrentIndex(const QModelIndex &index)
+{
+ QStandardItem *sit = itemFromIndex(index);
+ m_currentDebugger = sit ? sit->data() : QVariant();
+}
+
+void DebuggerItemManager::setCurrentData(const QString &displayName, const FileName &fileName)
+{
+ for (int i = 0, n = m_debuggers.size(); i != n; ++i) {
+ DebuggerItem &item = m_debuggers[i];
+ if (item.id() == m_currentDebugger) {
+ item.setDisplayName(displayName);
+ item.setCommand(fileName);
+ item.reinitializeFromFile();
+ QStandardItem *sitem = currentStandardItem();
+ QTC_ASSERT(sitem, return);
+ QStandardItem *parent = sitem->parent();
+ QTC_ASSERT(parent, return);
+ int row = sitem->row();
+ QFont font = sitem->font();
+ font.setBold(false);
+ parent->child(row, 0)->setData(item.displayName(), Qt::DisplayRole);
+ parent->child(row, 0)->setFont(font);
+ parent->child(row, 1)->setData(item.command().toUserOutput(), Qt::DisplayRole);
+ parent->child(row, 1)->setFont(font);
+ parent->child(row, 2)->setData(item.engineTypeName(), Qt::DisplayRole);
+ parent->child(row, 2)->setFont(font);
+ emit debuggerUpdated(m_currentDebugger, displayName);
+ return;
+ }
+ }
+}
+
+QVariant DebuggerItemManager::defaultDebugger(ToolChain *tc)
+{
+ QTC_ASSERT(tc, return QVariant());
+
+ DebuggerItem result;
+ result.setAutoDetected(true);
+ result.setDisplayName(tr("Auto-detected for Tool Chain %1").arg(tc->displayName()));
+
+ Abi abi = Abi::hostAbi();
+ if (tc)
+ abi = tc->targetAbi();
+
+// if (abis.first().wordWidth() == 32)
+// result.first = cdb.toString();
+// else if (abis.first().wordWidth() == 64)
+// result.second = cdb.toString();
+// // prefer 64bit debugger, even for 32bit binaries:
+// if (!result.second.isEmpty())
+// result.first = result.second;
+
+
+ foreach (const DebuggerItem &item, m_debuggers)
+ foreach (const Abi targetAbi, item.abis())
+ if (targetAbi.isCompatibleWith(abi))
+ return item.id();
+
+ return QVariant();
+
+ /*
+ // CDB for windows:
+ if (abi.os() == Abi::WindowsOS && abi.osFlavor() != Abi::WindowsMSysFlavor) {
+ QPair<QString, QString> cdbs = autoDetectCdbDebugger();
+ result.command = FileName::fromString(abi.wordWidth() == 32 ? cdbs.first : cdbs.second);
+ result.engineType = CdbEngineType;
+ return maybeAddDebugger(result, false);
+ }
+
+ // Check suggestions from the SDK.
+ Environment env = Environment::systemEnvironment();
+ if (tc) {
+ tc->addToEnvironment(env); // Find MinGW gdb in toolchain environment.
+ QString path = tc->suggestedDebugger().toString();
+ if (!path.isEmpty()) {
+ const QFileInfo fi(path);
+ if (!fi.isAbsolute())
+ path = env.searchInPath(path);
+ result.command = FileName::fromString(path);
+ result.engineType = engineTypeFromBinary(path);
+ return maybeAddDebugger(result, false);
+ }
+ }
+
+ // Default to GDB, system GDB
+ result.engineType = GdbEngineType;
+ QString gdb;
+ const QString systemGdb = QLatin1String("gdb");
+ // MinGW: Search for the python-enabled gdb first.
+ if (abi.os() == Abi::WindowsOS && abi.osFlavor() == Abi::WindowsMSysFlavor)
+ gdb = env.searchInPath(QLatin1String("gdb-i686-pc-mingw32"));
+ if (gdb.isEmpty())
+ gdb = env.searchInPath(systemGdb);
+ result.command = FileName::fromString(env.searchInPath(gdb.isEmpty() ? systemGdb : gdb));
+ return maybeAddDebugger(result, false);
+ */
+}
+
// -----------------------------------------------------------------------
-// DebuggerKitConfigWidget:
+// DebuggerKitConfigWidget
// -----------------------------------------------------------------------
-DebuggerKitConfigWidget::DebuggerKitConfigWidget(ProjectExplorer::Kit *workingCopy, bool sticky)
- : KitConfigWidget(workingCopy, sticky),
- m_main(new QWidget),
- m_label(new Utils::ElidingLabel(m_main)),
- m_autoDetectButton(new QPushButton(tr("Auto-detect"))),
- m_editButton(new QPushButton(tr("Edit...")))
-{
- QHBoxLayout *mainLayout = new QHBoxLayout(m_main);
- mainLayout->addWidget(m_label);
- mainLayout->setMargin(0);
- mainLayout->addWidget(m_autoDetectButton);
- m_autoDetectButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);
-
- connect(m_autoDetectButton, SIGNAL(pressed()), SLOT(autoDetectDebugger()));
- connect(m_editButton, SIGNAL(pressed()), SLOT(showDialog()));
+DebuggerKitConfigWidget::DebuggerKitConfigWidget(Kit *workingCopy, const KitInformation *ki)
+ : KitConfigWidget(workingCopy, ki)
+{
+ DebuggerItemManager *manager = theDebuggerItemManager();
+ QTC_CHECK(manager);
+
+ m_comboBox = new QComboBox;
+ m_comboBox->setEnabled(true);
+ m_comboBox->setToolTip(toolTip());
+ m_comboBox->addItem(tr("None"), QString());
+ foreach (const DebuggerItem &item, manager->m_debuggers)
+ m_comboBox->addItem(item.displayName(), item.id());
+
refresh();
-}
+ connect(m_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(currentDebuggerChanged(int)));
-QString DebuggerKitConfigWidget::toolTip() const
-{
- return tr("The debugger to use for this kit.");
+ m_manageButton = new QPushButton(tr("Manage..."));
+ m_manageButton->setContentsMargins(0, 0, 0, 0);
+ connect(m_manageButton, SIGNAL(clicked()), this, SLOT(manageDebuggers()));
+
+ connect(manager, SIGNAL(debuggerAdded(QVariant,QString)),
+ this, SLOT(onDebuggerAdded(QVariant,QString)));
+ connect(manager, SIGNAL(debuggerUpdated(QVariant,QString)),
+ this, SLOT(onDebuggerUpdated(QVariant,QString)));
+ connect(manager, SIGNAL(debuggerRemoved(QVariant)),
+ this, SLOT(onDebuggerRemoved(QVariant)));
}
-QWidget *DebuggerKitConfigWidget::mainWidget() const
+DebuggerKitConfigWidget::~DebuggerKitConfigWidget()
{
- return m_main;
+ delete m_comboBox;
+ delete m_manageButton;
}
-QWidget *DebuggerKitConfigWidget::buttonWidget() const
+QString DebuggerKitConfigWidget::toolTip() const
{
- return m_editButton;
+ return tr("The debugger to use for this kit.");
}
QString DebuggerKitConfigWidget::displayName() const
@@ -94,109 +907,172 @@ QString DebuggerKitConfigWidget::displayName() const
void DebuggerKitConfigWidget::makeReadOnly()
{
- m_editButton->setEnabled(false);
- m_autoDetectButton->setEnabled(false);
+ m_manageButton->setEnabled(false);
+ m_comboBox->setEnabled(false);
}
void DebuggerKitConfigWidget::refresh()
{
- m_label->setText(DebuggerKitInformation::userOutput(DebuggerKitInformation::debuggerItem(m_kit)));
+ const DebuggerItem *item = DebuggerItemManager::debuggerFromKit(m_kit);
+ updateComboBox(item ? item->id() : QVariant());
}
-void DebuggerKitConfigWidget::autoDetectDebugger()
+QWidget *DebuggerKitConfigWidget::buttonWidget() const
{
- DebuggerKitInformation::setDebuggerItem(m_kit, DebuggerKitInformation::autoDetectItem(m_kit));
+ return m_manageButton;
}
-void DebuggerKitConfigWidget::showDialog()
+QWidget *DebuggerKitConfigWidget::mainWidget() const
{
- DebuggerKitConfigDialog dialog(Core::ICore::mainWindow());
- dialog.setWindowTitle(tr("Debugger for \"%1\"").arg(m_kit->displayName()));
- dialog.setDebuggerItem(DebuggerKitInformation::debuggerItem(m_kit));
- if (dialog.exec() == QDialog::Accepted)
- DebuggerKitInformation::setDebuggerItem(m_kit, dialog.item());
+ return m_comboBox;
}
-// -----------------------------------------------------------------------
-// DebuggerKitConfigDialog:
-// -----------------------------------------------------------------------
+void DebuggerKitConfigWidget::manageDebuggers()
+{
+ Core::ICore::showOptionsDialog(ProjectExplorer::Constants::PROJECTEXPLORER_SETTINGS_CATEGORY,
+ ProjectExplorer::Constants::DEBUGGER_SETTINGS_PAGE_ID);
+}
-DebuggerKitConfigDialog::DebuggerKitConfigDialog(QWidget *parent)
- : QDialog(parent)
- , m_comboBox(new QComboBox(this))
- , m_label(new QLabel(this))
- , m_chooser(new Utils::PathChooser(this))
+void DebuggerKitConfigWidget::currentDebuggerChanged(int)
{
- setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
- QVBoxLayout *layout = new QVBoxLayout(this);
- QFormLayout *formLayout = new QFormLayout;
- formLayout->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow);
+ m_kit->setValue(DebuggerKitInformation::id(), m_comboBox->itemData(m_comboBox->currentIndex()));
+}
- m_comboBox->addItem(DebuggerKitInformation::debuggerEngineName(GdbEngineType), QVariant(int(GdbEngineType)));
- if (ProjectExplorer::Abi::hostAbi().os() == ProjectExplorer::Abi::WindowsOS) {
- m_comboBox->addItem(DebuggerKitInformation::debuggerEngineName(CdbEngineType), QVariant(int(CdbEngineType)));
- } else {
- m_comboBox->addItem(DebuggerKitInformation::debuggerEngineName(LldbEngineType), QVariant(int(LldbEngineType)));
- m_comboBox->addItem(DebuggerKitInformation::debuggerEngineName(LldbLibEngineType), QVariant(int(LldbLibEngineType)));
- }
- connect(m_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(refreshLabel()));
- QLabel *engineTypeLabel = new QLabel(tr("&Engine:"));
- engineTypeLabel->setBuddy(m_comboBox);
- formLayout->addRow(engineTypeLabel, m_comboBox);
+void DebuggerKitConfigWidget::onDebuggerAdded(const QVariant &id, const QString &displayName)
+{
+ m_comboBox->setEnabled(true);
+ m_comboBox->addItem(displayName, id);
+ updateComboBox(id);
+}
- m_label->setTextInteractionFlags(Qt::TextBrowserInteraction);
- m_label->setOpenExternalLinks(true);
- formLayout->addRow(m_label);
+void DebuggerKitConfigWidget::onDebuggerUpdated(const QVariant &id, const QString &displayName)
+{
+ m_comboBox->setEnabled(true);
+ const int pos = indexOf(id);
+ if (pos < 0)
+ return;
+ m_comboBox->setItemText(pos, displayName);
+}
- QLabel *binaryLabel = new QLabel(tr("&Binary:"));
- m_chooser->setExpectedKind(Utils::PathChooser::ExistingCommand);
- m_chooser->setMinimumWidth(400);
- binaryLabel->setBuddy(m_chooser);
- formLayout->addRow(binaryLabel, m_chooser);
- layout->addLayout(formLayout);
+void DebuggerKitConfigWidget::onDebuggerRemoved(const QVariant &id)
+{
+ if (const int pos = indexOf(id)) {
+ m_comboBox->removeItem(pos);
+ updateComboBox(id);
+ }
+}
- 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);
+int DebuggerKitConfigWidget::indexOf(const QVariant &id)
+{
+ QTC_ASSERT(id.isValid(), return -1);
+ for (int i = 0; i < m_comboBox->count(); ++i) {
+ if (id == m_comboBox->itemData(i))
+ return i;
+ }
+ return -1;
}
-DebuggerEngineType DebuggerKitConfigDialog::engineType() const
+QVariant DebuggerKitConfigWidget::currentId() const
{
- const int index = m_comboBox->currentIndex();
- return static_cast<DebuggerEngineType>(m_comboBox->itemData(index).toInt());
+ return m_comboBox->itemData(m_comboBox->currentIndex());
}
-void DebuggerKitConfigDialog::setEngineType(DebuggerEngineType et)
+void DebuggerKitConfigWidget::updateComboBox(const QVariant &id)
{
- const int size = m_comboBox->count();
- for (int i = 0; i < size; ++i) {
- if (m_comboBox->itemData(i).toInt() == et) {
+ for (int i = 0; i < m_comboBox->count(); ++i) {
+ if (id == m_comboBox->itemData(i)) {
m_comboBox->setCurrentIndex(i);
- refreshLabel();
- break;
+ return;
}
}
+ m_comboBox->setCurrentIndex(0);
+}
+
+// -----------------------------------------------------------------------
+// DebuggerItemConfigWidget
+// -----------------------------------------------------------------------
+
+class DebuggerItemConfigWidget : public QWidget
+{
+ Q_DECLARE_TR_FUNCTIONS(Debugger::Internal::DebuggerItemConfigWidget)
+public:
+ explicit DebuggerItemConfigWidget();
+ void loadItem();
+ void saveItem();
+ void connectDirty();
+ void disconnectDirty();
+
+private:
+ QLineEdit *m_displayNameLineEdit;
+ QLabel *m_cdbLabel;
+ PathChooser *m_binaryChooser;
+ QLineEdit *m_abis;
+};
+
+DebuggerItemConfigWidget::DebuggerItemConfigWidget()
+{
+ m_displayNameLineEdit = new QLineEdit(this);
+
+ m_binaryChooser = new PathChooser(this);
+ m_binaryChooser->setExpectedKind(PathChooser::ExistingCommand);
+ m_binaryChooser->setMinimumWidth(400);
+
+ m_cdbLabel = new QLabel(this);
+ m_cdbLabel->setTextInteractionFlags(Qt::TextBrowserInteraction);
+ m_cdbLabel->setOpenExternalLinks(true);
+
+ m_abis = new QLineEdit(this);
+ m_abis->setEnabled(false);
+
+ QFormLayout *formLayout = new QFormLayout(this);
+ formLayout->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow);
+ formLayout->addRow(new QLabel(tr("Name:")), m_displayNameLineEdit);
+// formLayout->addRow(new QLabel(tr("Type:")), m_engineTypeComboBox);
+ formLayout->addRow(m_cdbLabel);
+ formLayout->addRow(new QLabel(tr("Path:")), m_binaryChooser);
+ formLayout->addRow(new QLabel(tr("Abis:")), m_abis);
+
+ connectDirty();
}
-Utils::FileName DebuggerKitConfigDialog::fileName() const
+void DebuggerItemConfigWidget::connectDirty()
{
- return m_chooser->fileName();
+ DebuggerItemManager *manager = theDebuggerItemManager();
+ connect(m_displayNameLineEdit, SIGNAL(textChanged(QString)),
+ manager, SLOT(markCurrentDirty()));
+ connect(m_binaryChooser, SIGNAL(changed(QString)),
+ manager, SLOT(markCurrentDirty()));
}
-void DebuggerKitConfigDialog::setFileName(const Utils::FileName &fn)
+void DebuggerItemConfigWidget::disconnectDirty()
{
- m_chooser->setFileName(fn);
+ DebuggerItemManager *manager = theDebuggerItemManager();
+ disconnect(m_displayNameLineEdit, SIGNAL(textChanged(QString)),
+ manager, SLOT(markCurrentDirty()));
+ disconnect(m_binaryChooser, SIGNAL(changed(QString)),
+ manager, SLOT(markCurrentDirty()));
}
-void DebuggerKitConfigDialog::refreshLabel()
+void DebuggerItemConfigWidget::loadItem()
{
+ DebuggerItemManager *manager = theDebuggerItemManager();
+ const DebuggerItem *item = manager->findById(manager->m_currentDebugger);
+ if (!item)
+ return;
+
+ disconnectDirty();
+ m_displayNameLineEdit->setEnabled(!item->isAutoDetected());
+ m_displayNameLineEdit->setText(item->displayName());
+
+ m_binaryChooser->setEnabled(!item->isAutoDetected());
+ m_binaryChooser->setFileName(item->command());
+ connectDirty();
+
QString text;
- const DebuggerEngineType type = engineType();
- switch (type) {
- case CdbEngineType: {
+ QString versionCommand;
+ if (item->engineType() == CdbEngineType) {
#ifdef Q_OS_WIN
- const bool is64bit = Utils::winIs64BitSystem();
+ const bool is64bit = winIs64BitSystem();
#else
const bool is64bit = false;
#endif
@@ -206,22 +1082,184 @@ void DebuggerKitConfigDialog::refreshLabel()
"<a href=\"%1\">Windows Console Debugger executable</a>"
" (%2) here.</p>""</body></html>").
arg(QLatin1String(debuggingToolsWikiLinkC), versionString);
+ versionCommand = QLatin1String("-version");
+ } else {
+ versionCommand = QLatin1String("--version");
}
- break;
- default:
- break;
- }
- m_label->setText(text);
- m_label->setVisible(!text.isEmpty());
- m_chooser->setCommandVersionArguments(type == CdbEngineType ?
- QStringList(QLatin1String("-version")) :
- QStringList(QLatin1String("--version")));
+
+ m_cdbLabel->setText(text);
+ m_cdbLabel->setVisible(!text.isEmpty());
+ m_binaryChooser->setCommandVersionArguments(QStringList(versionCommand));
+
+ m_abis->setText(item->abiNames().join(QLatin1String(", ")));
}
-void DebuggerKitConfigDialog::setDebuggerItem(const DebuggerKitInformation::DebuggerItem &item)
+void DebuggerItemConfigWidget::saveItem()
+{
+ theDebuggerItemManager()->setCurrentData(m_displayNameLineEdit->text(), m_binaryChooser->fileName());
+}
+
+// --------------------------------------------------------------------------
+// DebuggerOptionsPage
+// --------------------------------------------------------------------------
+
+DebuggerOptionsPage::DebuggerOptionsPage()
{
- setEngineType(item.engineType);
- setFileName(item.binary);
+ m_manager = 0;
+ m_debuggerView = 0;
+ m_container = 0;
+ m_addButton = 0;
+ m_cloneButton = 0;
+ m_delButton = 0;
+
+ setId(ProjectExplorer::Constants::DEBUGGER_SETTINGS_PAGE_ID);
+ setDisplayName(tr("Debuggers"));
+ setCategory(ProjectExplorer::Constants::PROJECTEXPLORER_SETTINGS_CATEGORY);
+ setDisplayCategory(QCoreApplication::translate("ProjectExplorer",
+ ProjectExplorer::Constants::PROJECTEXPLORER_SETTINGS_TR_CATEGORY));
+ setCategoryIcon(QLatin1String(ProjectExplorer::Constants::PROJECTEXPLORER_SETTINGS_CATEGORY_ICON));
+}
+
+QWidget *DebuggerOptionsPage::createPage(QWidget *parent)
+{
+ m_configWidget = new QWidget(parent);
+
+ m_addButton = new QPushButton(tr("Add"), m_configWidget);
+ m_cloneButton = new QPushButton(tr("Clone"), m_configWidget);
+ m_delButton = new QPushButton(tr("Remove"), m_configWidget);
+
+ m_container = new DetailsWidget(m_configWidget);
+ m_container->setState(DetailsWidget::NoSummary);
+ m_container->setVisible(false);
+
+ m_manager = theDebuggerItemManager();
+
+ m_debuggerView = new QTreeView(m_configWidget);
+ m_debuggerView->setModel(m_manager);
+ m_debuggerView->setUniformRowHeights(true);
+ m_debuggerView->setSelectionMode(QAbstractItemView::SingleSelection);
+ m_debuggerView->setSelectionBehavior(QAbstractItemView::SelectRows);
+ m_debuggerView->expandAll();
+
+ QHeaderView *header = m_debuggerView->header();
+ header->setStretchLastSection(false);
+ header->setResizeMode(0, QHeaderView::ResizeToContents);
+ header->setResizeMode(1, QHeaderView::ResizeToContents);
+ header->setResizeMode(2, QHeaderView::Stretch);
+
+ QVBoxLayout *buttonLayout = new QVBoxLayout();
+ buttonLayout->setSpacing(6);
+ buttonLayout->setContentsMargins(0, 0, 0, 0);
+ buttonLayout->addWidget(m_addButton);
+ buttonLayout->addWidget(m_cloneButton);
+ buttonLayout->addWidget(m_delButton);
+ buttonLayout->addItem(new QSpacerItem(10, 40, QSizePolicy::Minimum, QSizePolicy::Expanding));
+
+ QVBoxLayout *verticalLayout = new QVBoxLayout();
+ verticalLayout->addWidget(m_debuggerView);
+ verticalLayout->addWidget(m_container);
+
+ QHBoxLayout *horizontalLayout = new QHBoxLayout(m_configWidget);
+ horizontalLayout->addLayout(verticalLayout);
+ horizontalLayout->addLayout(buttonLayout);
+
+ connect(m_debuggerView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
+ this, SLOT(debuggerSelectionChanged()));
+
+ connect(m_addButton, SIGNAL(clicked()), this, SLOT(addDebugger()), Qt::QueuedConnection);
+ connect(m_cloneButton, SIGNAL(clicked()), this, SLOT(cloneDebugger()), Qt::QueuedConnection);
+ connect(m_delButton, SIGNAL(clicked()), this, SLOT(removeDebugger()), Qt::QueuedConnection);
+
+ m_searchKeywords = tr("Debuggers");
+
+ m_itemConfigWidget = new DebuggerItemConfigWidget;
+ m_container->setWidget(m_itemConfigWidget);
+
+ updateState();
+
+ return m_configWidget;
+}
+
+void DebuggerOptionsPage::apply()
+{
+ m_itemConfigWidget->saveItem();
+ debuggerModelChanged();
+}
+
+void DebuggerOptionsPage::cloneDebugger()
+{
+ m_manager->cloneDebugger();
+ debuggerModelChanged();
+}
+
+void DebuggerOptionsPage::addDebugger()
+{
+ m_manager->addDebugger();
+ debuggerModelChanged();
+}
+
+void DebuggerOptionsPage::removeDebugger()
+{
+ m_manager->removeDebugger();
+ debuggerModelChanged();
+}
+
+void DebuggerOptionsPage::finish()
+{
+ // Deleted by settingsdialog.
+ m_configWidget = 0;
+
+ // Children of m_configWidget.
+ m_container = 0;
+ m_debuggerView = 0;
+ m_addButton = 0;
+ m_cloneButton = 0;
+ m_delButton = 0;
+}
+
+bool DebuggerOptionsPage::matches(const QString &s) const
+{
+ return m_searchKeywords.contains(s, Qt::CaseInsensitive);
+}
+
+void DebuggerOptionsPage::debuggerSelectionChanged()
+{
+ QTC_ASSERT(m_container, return);
+
+ QModelIndex mi = m_debuggerView->currentIndex();
+ mi = mi.sibling(mi.row(), 0);
+ m_manager->setCurrentIndex(mi);
+
+ m_itemConfigWidget->loadItem();
+ m_container->setVisible(m_manager->m_currentDebugger.isValid());
+ updateState();
+}
+
+void DebuggerOptionsPage::debuggerModelChanged()
+{
+ QTC_ASSERT(m_container, return);
+
+ m_itemConfigWidget->loadItem();
+ m_container->setVisible(m_manager->m_currentDebugger.isValid());
+ m_debuggerView->setCurrentIndex(m_manager->currentIndex());
+ updateState();
+}
+
+void DebuggerOptionsPage::updateState()
+{
+ if (!m_cloneButton)
+ return;
+
+ bool canCopy = false;
+ bool canDelete = false;
+
+ if (const DebuggerItem *item = m_manager->findById(m_manager->m_currentDebugger)) {
+ canCopy = item->isValid() && item->canClone();
+ canDelete = !item->isAutoDetected();
+ canDelete = true; // Do we want to remove auto-detected items?
+ }
+ m_cloneButton->setEnabled(canCopy);
+ m_delButton->setEnabled(canDelete);
}
} // namespace Internal
diff --git a/src/plugins/debugger/debuggerkitconfigwidget.h b/src/plugins/debugger/debuggerkitconfigwidget.h
index 9a5fbc9e83..9f83613949 100644
--- a/src/plugins/debugger/debuggerkitconfigwidget.h
+++ b/src/plugins/debugger/debuggerkitconfigwidget.h
@@ -30,29 +30,95 @@
#ifndef DEBUGGER_DEBUGGERKITCONFIGWIDGET_H
#define DEBUGGER_DEBUGGERKITCONFIGWIDGET_H
-#include <projectexplorer/kitconfigwidget.h>
-
#include "debuggerkitinformation.h"
+#include <coreplugin/dialogs/ioptionspage.h>
+#include <projectexplorer/kitconfigwidget.h>
+#include <projectexplorer/abi.h>
+#include <utils/detailswidget.h>
+#include <utils/fileutils.h>
+#include <utils/pathchooser.h>
+#include <utils/persistentsettings.h>
+
#include <QDialog>
+#include <QStandardItemModel>
+#include <QTreeView>
QT_BEGIN_NAMESPACE
-class QLabel;
class QComboBox;
+class QLabel;
class QPushButton;
QT_END_NAMESPACE
-namespace ProjectExplorer { class Kit; }
-namespace Utils {
-class PathChooser;
-class FileName;
-}
-
namespace Debugger {
-
namespace Internal {
+
+class DebuggerItemConfigWidget;
+class DebuggerKitConfigWidget;
+
// -----------------------------------------------------------------------
-// DebuggerKitConfigWidget:
+// DebuggerItemManager
+// -----------------------------------------------------------------------
+
+class DebuggerItemManager : public QStandardItemModel
+{
+ Q_OBJECT
+
+public:
+ DebuggerItemManager(QObject *parent);
+ ~DebuggerItemManager();
+
+ static const DebuggerItem *debuggerFromKit(const ProjectExplorer::Kit *kit);
+ // Returns id.
+ QVariant registerDebugger(const DebuggerItem &item);
+
+ QModelIndex currentIndex() const;
+ void setCurrentIndex(const QModelIndex &index);
+ void setCurrentData(const QString &displayName, const Utils::FileName &fileName);
+
+ // Returns id.
+ QVariant defaultDebugger(ProjectExplorer::ToolChain *tc);
+ static void restoreDebuggers();
+
+public slots:
+ void saveDebuggers();
+ void autoDetectDebuggers();
+ void readLegacyDebuggers();
+ void addDebugger();
+ void cloneDebugger();
+ void removeDebugger();
+ void markCurrentDirty();
+
+signals:
+ void debuggerAdded(const QVariant &id, const QString &display);
+ void debuggerUpdated(const QVariant &id, const QString &display);
+ void debuggerRemoved(const QVariant &id);
+
+private:
+ friend class Debugger::DebuggerKitInformation;
+ friend class DebuggerKitConfigWidget;
+ friend class DebuggerItemConfigWidget;
+ friend class DebuggerOptionsPage;
+
+ QVariant doAddDebugger(const DebuggerItem &item);
+ const DebuggerItem *findByCommand(const Utils::FileName &command);
+ const DebuggerItem *findById(const QVariant &id);
+ QStandardItem *currentStandardItem() const;
+ QVariant headerData(int section, Qt::Orientation orientation, int role) const;
+ QString uniqueDisplayName(const QString &base) const;
+ void autoDetectCdbDebugger();
+
+ Utils::PersistentSettingsWriter *m_writer;
+ QList<DebuggerItem> m_debuggers;
+ QVariant m_currentDebugger;
+
+ QStandardItem *m_autoRoot;
+ QStandardItem *m_manualRoot;
+ QStringList removed;
+};
+
+// -----------------------------------------------------------------------
+// DebuggerKitConfigWidget
// -----------------------------------------------------------------------
class DebuggerKitConfigWidget : public ProjectExplorer::KitConfigWidget
@@ -60,52 +126,69 @@ class DebuggerKitConfigWidget : public ProjectExplorer::KitConfigWidget
Q_OBJECT
public:
- DebuggerKitConfigWidget(ProjectExplorer::Kit *workingCopy, bool sticky);
+ DebuggerKitConfigWidget(ProjectExplorer::Kit *workingCopy,
+ const ProjectExplorer::KitInformation *ki);
+ ~DebuggerKitConfigWidget();
QString displayName() const;
QString toolTip() const;
-
void makeReadOnly();
-
void refresh();
-
QWidget *buttonWidget() const;
QWidget *mainWidget() const;
private slots:
- void autoDetectDebugger();
- void showDialog();
+ void manageDebuggers();
+ void currentDebuggerChanged(int idx);
+ void onDebuggerAdded(const QVariant &id, const QString &displayName);
+ void onDebuggerUpdated(const QVariant &id, const QString &displayName);
+ void onDebuggerRemoved(const QVariant &id);
private:
- QWidget *m_main;
- QLabel *m_label;
- QPushButton *m_autoDetectButton;
- QPushButton *m_editButton;
+ int indexOf(const QVariant &id);
+ QVariant currentId() const;
+ void updateComboBox(const QVariant &id);
+
+ bool m_isReadOnly;
+ QComboBox *m_comboBox;
+ QPushButton *m_manageButton;
};
-class DebuggerKitConfigDialog : public QDialog
+// --------------------------------------------------------------------------
+// DebuggerOptionsPage
+// --------------------------------------------------------------------------
+
+class DebuggerOptionsPage : public Core::IOptionsPage
{
Q_OBJECT
+
public:
- explicit DebuggerKitConfigDialog(QWidget *parent = 0);
+ DebuggerOptionsPage();
- void setDebuggerItem(const DebuggerKitInformation::DebuggerItem &item);
- DebuggerKitInformation::DebuggerItem item() const
- { return DebuggerKitInformation::DebuggerItem(engineType(), fileName()); }
+ QWidget *createPage(QWidget *parent);
+ void apply();
+ void finish();
+ bool matches(const QString &) const;
private slots:
- void refreshLabel();
+ void debuggerSelectionChanged();
+ void debuggerModelChanged();
+ void updateState();
+ void cloneDebugger();
+ void addDebugger();
+ void removeDebugger();
private:
- DebuggerEngineType engineType() const;
- void setEngineType(DebuggerEngineType et);
-
- Utils::FileName fileName() const;
- void setFileName(const Utils::FileName &fn);
-
- QComboBox *m_comboBox;
- QLabel *m_label;
- Utils::PathChooser *m_chooser;
+ QWidget *m_configWidget;
+ QString m_searchKeywords;
+
+ DebuggerItemManager *m_manager;
+ DebuggerItemConfigWidget *m_itemConfigWidget;
+ QTreeView *m_debuggerView;
+ Utils::DetailsWidget *m_container;
+ QPushButton *m_addButton;
+ QPushButton *m_cloneButton;
+ QPushButton *m_delButton;
};
} // namespace Internal
diff --git a/src/plugins/debugger/debuggerkitinformation.cpp b/src/plugins/debugger/debuggerkitinformation.cpp
index d74f69161c..271b48d7a8 100644
--- a/src/plugins/debugger/debuggerkitinformation.cpp
+++ b/src/plugins/debugger/debuggerkitinformation.cpp
@@ -28,351 +28,159 @@
****************************************************************************/
#include "debuggerkitinformation.h"
-
#include "debuggerkitconfigwidget.h"
#include <projectexplorer/abi.h>
-#include <projectexplorer/projectexplorerconstants.h>
-#include <projectexplorer/toolchain.h>
-#include <projectexplorer/toolchainmanager.h>
-
-#include <utils/environment.h>
-#include <utils/qtcassert.h>
+#include <utils/fileutils.h>
-#include <QDir>
+#include <QProcess>
+using namespace Debugger::Internal;
using namespace ProjectExplorer;
using namespace Utils;
-// --------------------------------------------------------------------------
-// Helpers:
-// --------------------------------------------------------------------------
-
-static QPair<QString, QString> autoDetectCdbDebugger()
-{
- QPair<QString, QString> result;
- QList<FileName> cdbs;
-
- QStringList programDirs;
- programDirs.append(QString::fromLocal8Bit(qgetenv("ProgramFiles")));
- programDirs.append(QString::fromLocal8Bit(qgetenv("ProgramFiles(x86)")));
- programDirs.append(QString::fromLocal8Bit(qgetenv("ProgramW6432")));
-
- foreach (const QString &dirName, programDirs) {
- if (dirName.isEmpty())
- continue;
- QDir dir(dirName);
- // Windows SDK's starting from version 8 live in
- // "ProgramDir\Windows Kits\<version>"
- const QString windowsKitsFolderName = QLatin1String("Windows Kits");
- if (dir.exists(windowsKitsFolderName)) {
- QDir windowKitsFolder = dir;
- if (windowKitsFolder.cd(windowsKitsFolderName)) {
- // Check in reverse order (latest first)
- const QFileInfoList kitFolders =
- windowKitsFolder.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot,
- QDir::Time | QDir::Reversed);
- foreach (const QFileInfo &kitFolderFi, kitFolders) {
- const QString path = kitFolderFi.absoluteFilePath();
- const QFileInfo cdb32(path + QLatin1String("/Debuggers/x86/cdb.exe"));
- if (cdb32.isExecutable())
- cdbs.push_back(FileName::fromString(cdb32.absoluteFilePath()));
- const QFileInfo cdb64(path + QLatin1String("/Debuggers/x64/cdb.exe"));
- if (cdb64.isExecutable())
- cdbs.push_back(FileName::fromString(cdb64.absoluteFilePath()));
- } // for Kits
- } // can cd to "Windows Kits"
- } // "Windows Kits" exists
-
- // Pre Windows SDK 8: Check 'Debugging Tools for Windows'
- foreach (const QFileInfo &fi, dir.entryInfoList(QStringList(QLatin1String("Debugging Tools for Windows*")),
- QDir::Dirs | QDir::NoDotAndDotDot)) {
- FileName filePath(fi);
- filePath.appendPath(QLatin1String("cdb.exe"));
- if (!cdbs.contains(filePath))
- cdbs.append(filePath);
- }
- }
-
- foreach (const FileName &cdb, cdbs) {
- QList<Abi> abis = Abi::abisOfBinary(cdb);
- if (abis.isEmpty())
- continue;
- if (abis.first().wordWidth() == 32)
- result.first = cdb.toString();
- else if (abis.first().wordWidth() == 64)
- result.second = cdb.toString();
- }
-
- // prefer 64bit debugger, even for 32bit binaries:
- if (!result.second.isEmpty())
- result.first = result.second;
-
- return result;
-}
+static const char DEBUGGER_INFORMATION_COMMAND[] = "Binary";
+static const char DEBUGGER_INFORMATION_DISPLAYNAME[] = "DisplayName";
+static const char DEBUGGER_INFORMATION_ID[] = "Id";
+static const char DEBUGGER_INFORMATION_ENGINETYPE[] = "EngineType";
+static const char DEBUGGER_INFORMATION_AUTODETECTED[] = "AutoDetected";
+static const char DEBUGGER_INFORMATION_ABIS[] = "Abis";
namespace Debugger {
-static DebuggerEngineType engineTypeFromBinary(const QString &binary)
-{
- if (binary.contains(QLatin1String("cdb"), Qt::CaseInsensitive))
- return CdbEngineType;
- if (binary.contains(QLatin1String("lldb"), Qt::CaseInsensitive))
- return LldbEngineType;
- return GdbEngineType;
-}
-
// --------------------------------------------------------------------------
-// DebuggerKitInformation:
+// DebuggerItem
// --------------------------------------------------------------------------
-static const char DEBUGGER_INFORMATION[] = "Debugger.Information";
-
-DebuggerKitInformation::DebuggerItem::DebuggerItem()
- : engineType(NoEngineType)
-{
-}
-
-DebuggerKitInformation::DebuggerItem::DebuggerItem(DebuggerEngineType et, const Utils::FileName &fn)
- : engineType(et)
- , binary(fn)
-{
-}
-
-DebuggerKitInformation::DebuggerKitInformation()
-{
- setObjectName(QLatin1String("DebuggerKitInformation"));
-}
-
-Core::Id DebuggerKitInformation::dataId() const
-{
- static Core::Id id = Core::Id(DEBUGGER_INFORMATION);
- return id;
-}
-
-unsigned int DebuggerKitInformation::priority() const
-{
- return 28000;
-}
-
-DebuggerKitInformation::DebuggerItem DebuggerKitInformation::autoDetectItem(const Kit *k)
-{
- if (DebuggerKitInformation::isValidDebugger(k))
- return DebuggerKitInformation::debuggerItem(k);
-
- DebuggerItem result;
- const ToolChain *tc = ToolChainKitInformation::toolChain(k);
- Abi abi = Abi::hostAbi();
- if (tc)
- abi = tc->targetAbi();
-
- // CDB for windows:
- if (abi.os() == Abi::WindowsOS && abi.osFlavor() != Abi::WindowsMSysFlavor) {
- QPair<QString, QString> cdbs = autoDetectCdbDebugger();
- result.binary = Utils::FileName::fromString(abi.wordWidth() == 32 ? cdbs.first : cdbs.second);
- result.engineType = CdbEngineType;
- return result;
+DebuggerItem::DebuggerItem()
+{
+ m_engineType = NoEngineType;
+ m_isAutoDetected = false;
+}
+
+void DebuggerItem::reinitializeFromFile()
+{
+ QProcess proc;
+ proc.start(m_command.toString(), QStringList() << QLatin1String("--version"));
+ proc.waitForStarted();
+ proc.waitForFinished();
+ QByteArray ba = proc.readAll();
+ if (ba.contains("gdb")) {
+ m_engineType = GdbEngineType;
+// const char needle[] = "This GDB was configured as \"";
+// int pos1 = ba.indexOf(needle);
+// if (pos1 != -1) {
+// pos1 += sizeof(needle);
+// int pos2 = ba.indexOf('"', pos1 + 1);
+// QByteArray target = ba.mid(pos1, pos2 - pos1);
+// abis.append(Abi::abiFromTargetTriplet(target)); // FIXME: Doesn't exist yet.
+// }
+ m_abis = Abi::abisOfBinary(m_command); // FIXME: Wrong.
+ return;
}
-
- // Check suggestions from the SDK.
- Environment env = Environment::systemEnvironment();
- if (tc) {
- tc->addToEnvironment(env); // Find MinGW gdb in toolchain environment.
- QString path = tc->suggestedDebugger().toString();
- if (!path.isEmpty()) {
- const QFileInfo fi(path);
- if (!fi.isAbsolute())
- path = env.searchInPath(path);
- result.binary = Utils::FileName::fromString(path);
- result.engineType = engineTypeFromBinary(path);
- return result;
- }
+ if (ba.contains("lldb")) {
+ m_engineType = LldbEngineType;
+ m_abis = Abi::abisOfBinary(m_command);
+ return;
}
-
- // Default to GDB, system GDB
- result.engineType = GdbEngineType;
- QString gdb;
- const QString systemGdb = QLatin1String("gdb");
- // MinGW: Search for the python-enabled gdb first.
- if (abi.os() == Abi::WindowsOS && abi.osFlavor() == Abi::WindowsMSysFlavor)
- gdb = env.searchInPath(QLatin1String("gdb-i686-pc-mingw32"));
- if (gdb.isEmpty())
- gdb = env.searchInPath(systemGdb);
- result.binary = Utils::FileName::fromString(env.searchInPath(gdb.isEmpty() ? systemGdb : gdb));
- return result;
+ if (ba.startsWith("Python")) {
+ m_engineType = PdbEngineType;
+ return;
+ }
+ m_engineType = NoEngineType;
}
-void DebuggerKitInformation::setup(Kit *k)
+QString DebuggerItem::engineTypeName() const
{
- QTC_ASSERT(ToolChainManager::instance()->isLoaded(), return);
- setDebuggerItem(k, autoDetectItem(k));
+ switch (m_engineType) {
+ case Debugger::NoEngineType:
+ return DebuggerOptionsPage::tr("Not recognized");
+ case Debugger::GdbEngineType:
+ return QLatin1String("GDB");
+ case Debugger::CdbEngineType:
+ return QLatin1String("CDB");
+ case Debugger::LldbEngineType:
+ return QLatin1String("LLDB");
+ default:
+ return QString();
+ }
}
-// Check the configuration errors and return a flag mask. Provide a quick check and
-// a verbose one with a list of errors.
-
-enum DebuggerConfigurationErrors {
- NoDebugger = 0x1,
- DebuggerNotFound = 0x2,
- DebuggerNotExecutable = 0x4,
- DebuggerNeedsAbsolutePath = 0x8
-};
-
-static unsigned debuggerConfigurationErrors(const ProjectExplorer::Kit *k)
+QStringList DebuggerItem::abiNames() const
{
- unsigned result = 0;
- const DebuggerKitInformation::DebuggerItem item = DebuggerKitInformation::debuggerItem(k);
- if (item.engineType == NoEngineType || item.binary.isEmpty())
- return NoDebugger;
-
- const QFileInfo fi = item.binary.toFileInfo();
- if (!fi.exists() || fi.isDir())
- result |= DebuggerNotFound;
- else if (!fi.isExecutable())
- result |= DebuggerNotExecutable;
-
- if (!fi.exists() || fi.isDir())
- // We need an absolute path to be able to locate Python on Windows.
- if (item.engineType == GdbEngineType)
- if (const ToolChain *tc = ToolChainKitInformation::toolChain(k))
- if (tc->targetAbi().os() == Abi::WindowsOS && !fi.isAbsolute())
- result |= DebuggerNeedsAbsolutePath;
- return result;
+ QStringList list;
+ foreach (const Abi &abi, m_abis)
+ list.append(abi.toString());
+ return list;
}
-bool DebuggerKitInformation::isValidDebugger(const ProjectExplorer::Kit *k)
+QVariantMap DebuggerItem::toMap() const
{
- return debuggerConfigurationErrors(k) == 0;
+ QVariantMap data;
+ data.insert(QLatin1String(DEBUGGER_INFORMATION_DISPLAYNAME), m_displayName);
+ data.insert(QLatin1String(DEBUGGER_INFORMATION_ID), m_id);
+ data.insert(QLatin1String(DEBUGGER_INFORMATION_COMMAND), m_command.toUserOutput());
+ data.insert(QLatin1String(DEBUGGER_INFORMATION_ENGINETYPE), int(m_engineType));
+ data.insert(QLatin1String(DEBUGGER_INFORMATION_AUTODETECTED), m_isAutoDetected);
+ data.insert(QLatin1String(DEBUGGER_INFORMATION_ABIS), abiNames());
+ return data;
}
-QList<ProjectExplorer::Task> DebuggerKitInformation::validateDebugger(const ProjectExplorer::Kit *k)
+void DebuggerItem::fromMap(const QVariantMap &data)
{
- const unsigned errors = debuggerConfigurationErrors(k);
- const Core::Id id(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM);
- QList<Task> result;
- if (errors & NoDebugger)
- result << Task(Task::Warning, tr("No debugger set up."), FileName(), -1, id);
+ m_command = FileName::fromUserInput(data.value(QLatin1String(DEBUGGER_INFORMATION_COMMAND)).toString());
+ m_id = data.value(QLatin1String(DEBUGGER_INFORMATION_ID)).toString();
+ m_displayName = data.value(QLatin1String(DEBUGGER_INFORMATION_DISPLAYNAME)).toString();
+ m_isAutoDetected = data.value(QLatin1String(DEBUGGER_INFORMATION_AUTODETECTED)).toBool();
+ m_engineType = DebuggerEngineType(data.value(QLatin1String(DEBUGGER_INFORMATION_ENGINETYPE)).toInt());
- if (errors & DebuggerNotFound) {
- const QString path = DebuggerKitInformation::debuggerCommand(k).toUserOutput();
- result << Task(Task::Error, tr("Debugger '%1' not found.").arg(path),
- FileName(), -1, id);
+ m_abis.clear();
+ foreach (const QString &a, data.value(QLatin1String(DEBUGGER_INFORMATION_ABIS)).toStringList()) {
+ Abi abi(a);
+ if (abi.isValid())
+ m_abis.append(abi);
}
- if (errors & DebuggerNotExecutable) {
- const QString path = DebuggerKitInformation::debuggerCommand(k).toUserOutput();
- result << Task(Task::Error, tr("Debugger '%1' not executable.").arg(path), FileName(), -1, id);
- }
- if (errors & DebuggerNeedsAbsolutePath) {
- const QString path = DebuggerKitInformation::debuggerCommand(k).toUserOutput();
- const QString message =
- tr("The debugger location must be given as an "
- "absolute path (%1).").arg(path);
- result << Task(Task::Error, message, FileName(), -1, id);
- }
- return result;
-}
-
-KitConfigWidget *DebuggerKitInformation::createConfigWidget(Kit *k) const
-{
- return new Internal::DebuggerKitConfigWidget(k, isSticky(k));
-}
-
-QString DebuggerKitInformation::userOutput(const DebuggerItem &item)
-{
- const QString binary = item.binary.toUserOutput();
- const QString name = debuggerEngineName(item.engineType);
- return binary.isEmpty() ? tr("%1 <None>").arg(name) : tr("%1 using \"%2\"").arg(name, binary);
}
-KitInformation::ItemList DebuggerKitInformation::toUserOutput(const Kit *k) const
+void DebuggerItem::setId(const QVariant &id)
{
- return ItemList() << qMakePair(tr("Debugger"), DebuggerKitInformation::userOutput(DebuggerKitInformation::debuggerItem(k)));
+ m_id = id;
}
-static const char engineTypeKeyC[] = "EngineType";
-static const char binaryKeyC[] = "Binary";
-
-DebuggerKitInformation::DebuggerItem DebuggerKitInformation::variantToItem(const QVariant &v)
+void DebuggerItem::setDisplayName(const QString &displayName)
{
- DebuggerItem result;
- if (v.isNull())
- return result;
- if (v.type() == QVariant::String) { // Convert legacy config items, remove later.
- const QString binary = v.toString();
- result.binary = Utils::FileName::fromString(binary);
- result.engineType = engineTypeFromBinary(binary);
- return result;
- }
- QTC_ASSERT(v.type() == QVariant::Map, return result);
- const QVariantMap vmap = v.toMap();
- result.engineType = static_cast<DebuggerEngineType>(vmap.value(QLatin1String(engineTypeKeyC)).toInt());
- QString binary = vmap.value(QLatin1String(binaryKeyC)).toString();
- // Check for special 'auto' entry for binary written by the sdktool during
- // installation. Try to autodetect.
- if (binary == QLatin1String("auto")) {
- binary.clear();
- switch (result.engineType) {
- case Debugger::GdbEngineType: // Auto-detect system gdb on Unix
- if (Abi::hostAbi().os() != Abi::WindowsOS)
- binary = Environment::systemEnvironment().searchInPath(QLatin1String("gdb"));
- break;
- case Debugger::CdbEngineType: { // Auto-detect system CDB on Windows.
- const QPair<QString, QString> cdbs = autoDetectCdbDebugger();
- binary = cdbs.second.isEmpty() ? cdbs.first : cdbs.second;
- }
- break;
- default:
- break;
- }
- }
- result.binary = Utils::FileName::fromUserInput(binary);
- return result;
+ m_displayName = displayName;
}
-QVariant DebuggerKitInformation::itemToVariant(const DebuggerItem &i)
+void DebuggerItem::setEngineType(const DebuggerEngineType &engineType)
{
- QVariantMap vmap;
- vmap.insert(QLatin1String(binaryKeyC), QVariant(i.binary.toString()));
- vmap.insert(QLatin1String(engineTypeKeyC), QVariant(int(i.engineType)));
- return QVariant(vmap);
+ m_engineType = engineType;
}
-DebuggerKitInformation::DebuggerItem DebuggerKitInformation::debuggerItem(const ProjectExplorer::Kit *k)
+void DebuggerItem::setCommand(const Utils::FileName &command)
{
- return k ?
- DebuggerKitInformation::variantToItem(k->value(Core::Id(DEBUGGER_INFORMATION))) :
- DebuggerItem();
+ m_command = command;
}
-void DebuggerKitInformation::setDebuggerItem(ProjectExplorer::Kit *k, const DebuggerItem &item)
+void DebuggerItem::setAutoDetected(bool isAutoDetected)
{
- QTC_ASSERT(k, return);
- k->setValue(Core::Id(DEBUGGER_INFORMATION), itemToVariant(item));
+ m_isAutoDetected = isAutoDetected;
}
-void DebuggerKitInformation::setDebuggerCommand(ProjectExplorer::Kit *k, const FileName &command)
+void DebuggerItem::setAbis(const QList<ProjectExplorer::Abi> &abis)
{
- setDebuggerItem(k, DebuggerItem(engineType(k), command));
+ m_abis = abis;
}
-void DebuggerKitInformation::setEngineType(ProjectExplorer::Kit *k, DebuggerEngineType type)
+void DebuggerItem::setAbi(const Abi &abi)
{
- setDebuggerItem(k, DebuggerItem(type, debuggerCommand(k)));
+ m_abis.clear();
+ m_abis.append(abi);
}
-QString DebuggerKitInformation::debuggerEngineName(DebuggerEngineType t)
+bool Debugger::DebuggerItem::isValid() const
{
- switch (t) {
- case Debugger::GdbEngineType:
- return tr("GDB Engine");
- case Debugger::CdbEngineType:
- return tr("CDB Engine");
- case Debugger::LldbEngineType:
- return tr("LLDB Engine");
- default:
- break;
- }
- return QString();
+ return m_engineType != NoEngineType;
}
-} // namespace Debugger
+} // namespace Debugger;
diff --git a/src/plugins/debugger/debuggerkitinformation.h b/src/plugins/debugger/debuggerkitinformation.h
index eff4f385a6..30623bdae0 100644
--- a/src/plugins/debugger/debuggerkitinformation.h
+++ b/src/plugins/debugger/debuggerkitinformation.h
@@ -33,34 +33,66 @@
#include "debugger_global.h"
#include "debuggerconstants.h"
+#include <projectexplorer/abi.h>
#include <projectexplorer/kitinformation.h>
namespace Debugger {
-class DEBUGGER_EXPORT DebuggerKitInformation : public ProjectExplorer::KitInformation
-{
- Q_OBJECT
+namespace Internal { class DebuggerItemManager; }
+class DEBUGGER_EXPORT DebuggerItem
+{
public:
- class DEBUGGER_EXPORT DebuggerItem {
- public:
- DebuggerItem();
- DebuggerItem(DebuggerEngineType engineType, const Utils::FileName &fn);
- bool equals(const DebuggerItem &rhs) const { return engineType == rhs.engineType && binary == rhs.binary; }
+ DebuggerItem();
- DebuggerEngineType engineType;
- Utils::FileName binary;
- };
+ bool canClone() const { return true; }
+ bool isValid() const;
+ QString engineTypeName() const;
- DebuggerKitInformation();
+ QVariantMap toMap() const;
+ void fromMap(const QVariantMap &data);
+ void reinitializeFromFile();
+
+ QVariant id() const { return m_id; }
+
+ QString displayName() const { return m_displayName; }
+ void setDisplayName(const QString &displayName);
- Core::Id dataId() const;
+ DebuggerEngineType engineType() const { return m_engineType; }
+ void setEngineType(const DebuggerEngineType &engineType);
- unsigned int priority() const; // the higher the closer to the top.
+ Utils::FileName command() const { return m_command; }
+ void setCommand(const Utils::FileName &command);
- static DebuggerItem autoDetectItem(const ProjectExplorer::Kit *k);
- QVariant defaultValue(ProjectExplorer::Kit *k) const
- { return DebuggerKitInformation::itemToVariant(DebuggerKitInformation::autoDetectItem(k)); }
+ bool isAutoDetected() const { return m_isAutoDetected; }
+ void setAutoDetected(bool isAutoDetected);
+
+ QList<ProjectExplorer::Abi> abis() const { return m_abis; }
+ void setAbis(const QList<ProjectExplorer::Abi> &abis);
+ void setAbi(const ProjectExplorer::Abi &abi);
+
+ QStringList abiNames() const;
+
+private:
+ friend class Debugger::Internal::DebuggerItemManager;
+ void setId(const QVariant &id);
+
+ QVariant m_id;
+ QString m_displayName;
+ DebuggerEngineType m_engineType;
+ Utils::FileName m_command;
+ bool m_isAutoDetected;
+ QList<ProjectExplorer::Abi> m_abis;
+};
+
+class DEBUGGER_EXPORT DebuggerKitInformation : public ProjectExplorer::KitInformation
+{
+ Q_OBJECT
+
+public:
+ DebuggerKitInformation();
+
+ QVariant defaultValue(ProjectExplorer::Kit *k) const;
QList<ProjectExplorer::Task> validate(const ProjectExplorer::Kit *k) const
{ return DebuggerKitInformation::validateDebugger(k); }
@@ -73,33 +105,16 @@ public:
ProjectExplorer::KitConfigWidget *createConfigWidget(ProjectExplorer::Kit *k) const;
ItemList toUserOutput(const ProjectExplorer::Kit *k) const;
- static QString userOutput(const DebuggerItem &item);
-
- static DebuggerItem debuggerItem(const ProjectExplorer::Kit *k);
- static void setDebuggerItem(ProjectExplorer::Kit *k, const DebuggerItem &item);
- static Utils::FileName debuggerCommand(const ProjectExplorer::Kit *k)
- { return debuggerItem(k).binary; }
+ static void setDebugger(ProjectExplorer::Kit *k, const DebuggerItem &item);
+ static void setDebugger(ProjectExplorer::Kit *k, const Utils::FileName &command);
- static void setDebuggerCommand(ProjectExplorer::Kit *k, const Utils::FileName &command);
-
- static DebuggerEngineType engineType(const ProjectExplorer::Kit *k)
- { return debuggerItem(k).engineType; }
-
- static void setEngineType(ProjectExplorer::Kit *k, DebuggerEngineType type);
-
- static QString debuggerEngineName(DebuggerEngineType t);
-
-private:
- static DebuggerItem variantToItem(const QVariant &v);
- static QVariant itemToVariant(const DebuggerItem &i);
+ static Core::Id id();
+ static Utils::FileName debuggerCommand(const ProjectExplorer::Kit *k);
+ static DebuggerEngineType engineType(const ProjectExplorer::Kit *k);
+ static QString displayString(const ProjectExplorer::Kit *k);
};
-inline bool operator==(const DebuggerKitInformation::DebuggerItem &i1, const DebuggerKitInformation::DebuggerItem &i2)
- { return i1.equals(i2); }
-inline bool operator!=(const DebuggerKitInformation::DebuggerItem &i1, const DebuggerKitInformation::DebuggerItem &i2)
- { return !i1.equals(i2); }
-
} // namespace Debugger
#endif // DEBUGGER_DEBUGGERKITINFORMATION_H
diff --git a/src/plugins/debugger/debuggermainwindow.cpp b/src/plugins/debugger/debuggermainwindow.cpp
index 4158b313d9..ab1fef4557 100644
--- a/src/plugins/debugger/debuggermainwindow.cpp
+++ b/src/plugins/debugger/debuggermainwindow.cpp
@@ -48,7 +48,6 @@
#include <coreplugin/rightpane.h>
#include <projectexplorer/project.h>
-#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/runconfiguration.h>
#include <projectexplorer/session.h>
#include <projectexplorer/target.h>
@@ -204,14 +203,14 @@ void DebuggerMainWindowPrivate::updateUiForRunConfiguration(RunConfiguration *rc
{
if (m_previousRunConfiguration)
disconnect(m_previousRunConfiguration->extraAspect<Debugger::DebuggerRunConfigurationAspect>(),
- SIGNAL(debuggersChanged()),
+ SIGNAL(requestRunActionsUpdate()),
this, SLOT(updateUiForCurrentRunConfiguration()));
m_previousRunConfiguration = rc;
updateUiForCurrentRunConfiguration();
if (!rc)
return;
connect(m_previousRunConfiguration->extraAspect<Debugger::DebuggerRunConfigurationAspect>(),
- SIGNAL(debuggersChanged()),
+ SIGNAL(requestRunActionsUpdate()),
SLOT(updateUiForCurrentRunConfiguration()));
}
@@ -224,15 +223,13 @@ void DebuggerMainWindowPrivate::updateActiveLanguages()
{
DebuggerLanguages newLanguages = AnyLanguage;
- if (m_engineDebugLanguages != AnyLanguage)
+ if (m_engineDebugLanguages != AnyLanguage) {
newLanguages = m_engineDebugLanguages;
- else {
- if (m_previousRunConfiguration) {
- if (m_previousRunConfiguration->extraAspect<Debugger::DebuggerRunConfigurationAspect>()->useCppDebugger())
- newLanguages |= CppLanguage;
- if (m_previousRunConfiguration->extraAspect<Debugger::DebuggerRunConfigurationAspect>()->useQmlDebugger())
- newLanguages |= QmlLanguage;
- }
+ } else if (m_previousRunConfiguration) {
+ if (m_previousRunConfiguration->extraAspect<Debugger::DebuggerRunConfigurationAspect>()->useCppDebugger())
+ newLanguages |= CppLanguage;
+ if (m_previousRunConfiguration->extraAspect<Debugger::DebuggerRunConfigurationAspect>()->useQmlDebugger())
+ newLanguages |= QmlLanguage;
}
if (newLanguages != m_activeDebugLanguages) {
@@ -272,10 +269,10 @@ DebuggerMainWindow::~DebuggerMainWindow()
void DebuggerMainWindow::setCurrentEngine(DebuggerEngine *engine)
{
if (d->m_engine)
- disconnect(d->m_engine, SIGNAL(raiseWindow()), ICore::appMainWindow(), SLOT(raiseWindow()));
+ disconnect(d->m_engine, SIGNAL(raiseWindow()), ICore::mainWindow(), SLOT(raiseWindow()));
d->m_engine = engine;
if (d->m_engine)
- connect(d->m_engine, SIGNAL(raiseWindow()), ICore::appMainWindow(), SLOT(raiseWindow()));
+ connect(d->m_engine, SIGNAL(raiseWindow()), ICore::mainWindow(), SLOT(raiseWindow()));
}
DebuggerLanguages DebuggerMainWindow::activeDebugLanguages() const
@@ -324,25 +321,24 @@ void DebuggerMainWindowPrivate::createViewsMenuItems()
// Add menu items
Command *cmd = 0;
cmd = Core::ActionManager::registerAction(openMemoryEditorAction,
- Core::Id("Debugger.Views.OpenMemoryEditor"),
- debugcontext);
+ "Debugger.Views.OpenMemoryEditor", debugcontext);
cmd->setAttribute(Command::CA_Hide);
m_viewsMenu->addAction(cmd, Core::Constants::G_DEFAULT_THREE);
cmd = Core::ActionManager::registerAction(q->menuSeparator1(),
- Core::Id("Debugger.Views.Separator1"), debugcontext);
+ "Debugger.Views.Separator1", debugcontext);
cmd->setAttribute(Command::CA_Hide);
m_viewsMenu->addAction(cmd, Core::Constants::G_DEFAULT_THREE);
cmd = Core::ActionManager::registerAction(q->toggleLockedAction(),
- Core::Id("Debugger.Views.ToggleLocked"), debugcontext);
+ "Debugger.Views.ToggleLocked", debugcontext);
cmd->setAttribute(Command::CA_Hide);
m_viewsMenu->addAction(cmd, Core::Constants::G_DEFAULT_THREE);
cmd = Core::ActionManager::registerAction(q->menuSeparator2(),
- Core::Id("Debugger.Views.Separator2"), debugcontext);
+ "Debugger.Views.Separator2", debugcontext);
cmd->setAttribute(Command::CA_Hide);
m_viewsMenu->addAction(cmd, Core::Constants::G_DEFAULT_THREE);
cmd = Core::ActionManager::registerAction(q->resetLayoutAction(),
- Core::Id("Debugger.Views.ResetSimple"), debugcontext);
+ "Debugger.Views.ResetSimple", debugcontext);
cmd->setAttribute(Command::CA_Hide);
m_viewsMenu->addAction(cmd, Core::Constants::G_DEFAULT_THREE);
}
@@ -472,8 +468,7 @@ void DebuggerMainWindow::addStagedMenuEntries()
QWidget *DebuggerMainWindow::createContents(IMode *mode)
{
- ProjectExplorerPlugin *pe = ProjectExplorerPlugin::instance();
- connect(pe->session(), SIGNAL(startupProjectChanged(ProjectExplorer::Project*)),
+ connect(SessionManager::instance(), SIGNAL(startupProjectChanged(ProjectExplorer::Project*)),
d, SLOT(updateUiForProject(ProjectExplorer::Project*)));
d->m_viewsMenu = Core::ActionManager::actionContainer(Core::Id(Core::Constants::M_WINDOW_VIEWS));
diff --git a/src/plugins/debugger/debuggerplugin.cpp b/src/plugins/debugger/debuggerplugin.cpp
index b22901fc37..6e4606e884 100644
--- a/src/plugins/debugger/debuggerplugin.cpp
+++ b/src/plugins/debugger/debuggerplugin.cpp
@@ -33,6 +33,7 @@
#include "debuggeractions.h"
#include "debuggerinternalconstants.h"
#include "debuggercore.h"
+#include "debuggerkitconfigwidget.h"
#include "debuggerdialogs.h"
#include "debuggerengine.h"
#include "debuggermainwindow.h"
@@ -60,8 +61,8 @@
#include "debuggertooltipmanager.h"
#include "localsandexpressionswindow.h"
#include "loadcoredialog.h"
-#include "hostutils.h"
#include "sourceutils.h"
+#include <debugger/shared/hostutils.h>
#include "snapshothandler.h"
#include "threadshandler.h"
@@ -83,6 +84,7 @@
#include <projectexplorer/localapplicationrunconfiguration.h>
#include <projectexplorer/buildmanager.h>
+#include <projectexplorer/taskhub.h>
#include <projectexplorer/toolchain.h>
#include <projectexplorer/devicesupport/deviceprocesslist.h>
#include <projectexplorer/devicesupport/deviceprocessesdialog.h>
@@ -107,6 +109,7 @@
# include <utils/winutils.h>
#endif
+#include <QComboBox>
#include <QDockWidget>
#include <QFileDialog>
#include <QInputDialog>
@@ -425,11 +428,6 @@ void addTcfOptionPages(QList<IOptionsPage*> *opts);
void addLldbOptionPages(QList<IOptionsPage*> *opts);
#endif
-static SessionManager *sessionManager()
-{
- return ProjectExplorerPlugin::instance()->session();
-}
-
static QToolButton *toolButton(QAction *action)
{
QToolButton *button = new QToolButton;
@@ -529,7 +527,7 @@ public:
static QString executableForPid(qint64 pid)
{
- foreach (const DeviceProcess &p, DeviceProcessList::localProcesses())
+ foreach (const DeviceProcessItem &p, DeviceProcessList::localProcesses())
if (p.pid == pid)
return p.exe;
return QString();
@@ -594,12 +592,12 @@ public:
#ifdef Q_OS_WIN
if (Utils::winIs64BitSystem()) {
CdbMatcher matcher64(64);
- if (Kit *cdb64Kit = KitManager::instance()->find(&matcher64))
+ if (Kit *cdb64Kit = KitManager::find(matcher64))
return cdb64Kit;
}
#endif
CdbMatcher matcher;
- return KitManager::instance()->find(&matcher);
+ return KitManager::find(matcher);
}
private:
@@ -625,15 +623,12 @@ bool fillParameters(DebuggerStartParameters *sp, const Kit *kit, QString *errorM
abis = Abi::abisOfBinary(Utils::FileName::fromString(sp->executable));
}
if (!abis.isEmpty()) {
- AbiKitMatcher matcher(abis);
- kit = KitManager::instance()->find(&matcher);
- if (!kit) {
- CompatibleAbiKitMatcher matcher(abis);
- kit = KitManager::instance()->find(&matcher);
- }
+ kit = KitManager::find(AbiKitMatcher(abis));
+ if (!kit)
+ kit = KitManager::find(CompatibleAbiKitMatcher(abis));
}
if (!kit)
- kit = KitManager::instance()->defaultKit();
+ kit = KitManager::defaultKit();
}
// Verify that debugger and profile are valid
@@ -688,7 +683,7 @@ static bool currentTextEditorPosition(ContextData *data)
return false;
const IDocument *document = textEditor->document();
QTC_ASSERT(document, return false);
- data->fileName = document->fileName();
+ data->fileName = document->filePath();
if (textEditor->property("DisassemblerView").toBool()) {
int lineNumber = textEditor->currentLine();
QString line = textEditor->textDocument()->contents()
@@ -816,7 +811,7 @@ public slots:
{
const QAction *act = qobject_cast<QAction *>(sender());
QTC_ASSERT(act, return);
- BreakpointModelId id = act->data().value<BreakpointModelId>();;
+ BreakpointModelId id = act->data().value<BreakpointModelId>();
breakHandler()->setEnabled(id, false);
}
@@ -922,9 +917,6 @@ public slots:
BreakHandler *breakHandler() const { return m_breakHandler; }
SnapshotHandler *snapshotHandler() const { return m_snapshotHandler; }
- void setConfigValue(const QString &name, const QVariant &value);
- QVariant configValue(const QString &name) const;
-
void displayDebugger(DebuggerEngine *engine, bool updateEngine = true);
void dumpLog();
@@ -956,9 +948,9 @@ public slots:
void testRunProject(const DebuggerStartParameters &sp, const TestCallBack &cb);
void testRunControlFinished();
- void testStateMachine1();
- void testStateMachine2();
- void testStateMachine3();
+// void testStateMachine1();
+// void testStateMachine2();
+// void testStateMachine3();
void testBenchmark1();
@@ -1181,8 +1173,6 @@ public slots:
return m_mainWindow->activeDebugLanguages() & lang;
}
- QVariant sessionValue(const QString &name);
- void setSessionValue(const QString &name, const QVariant &value);
QIcon locationMarkIcon() const { return m_locationMarkIcon; }
void openTextEditor(const QString &titlePattern0, const QString &contents);
@@ -1283,7 +1273,6 @@ public:
bool m_shuttingDown;
DebuggerEngine *m_currentEngine;
DebuggerSettings *m_debuggerSettings;
- QSettings *m_coreSettings;
QStringList m_arguments;
DebuggerToolTipManager *m_toolTipManager;
CommonOptionsPage *m_commonOptionsPage;
@@ -1407,11 +1396,11 @@ bool DebuggerPluginPrivate::parseArgument(QStringList::const_iterator &it,
QString key = arg.section(QLatin1Char('='), 0, 0);
QString val = arg.section(QLatin1Char('='), 1, 1);
if (val.isEmpty()) {
- if (key.isEmpty())
+ if (key.isEmpty()) {
continue;
- else if (sp.executable.isEmpty())
+ } else if (sp.executable.isEmpty()) {
sp.executable = key;
- else {
+ } else {
*errorMessage = DebuggerPlugin::tr("Only one executable allowed!");
return false;
}
@@ -1421,16 +1410,14 @@ bool DebuggerPluginPrivate::parseArgument(QStringList::const_iterator &it,
sp.remoteChannel = val;
sp.displayName = tr("Remote: \"%1\"").arg(sp.remoteChannel);
sp.startMessage = tr("Attaching to remote server %1.").arg(sp.remoteChannel);
- }
- else if (key == QLatin1String("core")) {
+ } else if (key == QLatin1String("core")) {
sp.startMode = AttachCore;
sp.closeMode = DetachAtClose;
sp.coreFile = val;
sp.displayName = tr("Core file \"%1\"").arg(sp.coreFile);
sp.startMessage = tr("Attaching to core file %1.").arg(sp.coreFile);
- }
- else if (key == QLatin1String("kit")) {
- kit = KitManager::instance()->find(Id::fromString(val));
+ } else if (key == QLatin1String("kit")) {
+ kit = KitManager::find(Id::fromString(val));
}
}
}
@@ -1492,7 +1479,7 @@ void DebuggerPluginPrivate::parseCommandLineArguments()
errorMessage = tr("Error evaluating command line arguments: %1")
.arg(errorMessage);
qWarning("%s\n", qPrintable(errorMessage));
- Core::MessageManager::instance()->printToOutputPane(errorMessage, Core::MessageManager::NoModeSwitch);
+ MessageManager::write(errorMessage);
}
if (!m_scheduledStarts.isEmpty())
QTimer::singleShot(0, this, SLOT(runScheduled()));
@@ -1508,21 +1495,24 @@ bool DebuggerPluginPrivate::initialize(const QStringList &arguments,
// Cpp/Qml ui setup
m_mainWindow = new DebuggerMainWindow;
+ TaskHub::addCategory(Debugger::Constants::TASK_CATEGORY_DEBUGGER_DEBUGINFO,
+ tr("Debug Information"));
+ TaskHub::addCategory(Debugger::Constants::TASK_CATEGORY_DEBUGGER_TEST,
+ tr("Debugger Test"));
+ TaskHub::addCategory(Debugger::Constants::TASK_CATEGORY_DEBUGGER_RUNTIME,
+ tr("Debugger Runtime"));
+
return true;
}
-void DebuggerPluginPrivate::setConfigValue(const QString &name, const QVariant &value)
+void DebuggerCore::setConfigValue(const QByteArray &name, const QVariant &value)
{
- m_coreSettings->setValue(_("DebugMode/") + name, value);
+ ICore::settings()->setValue(_("DebugMode/" + name), value);
}
-QVariant DebuggerPluginPrivate::configValue(const QString &name) const
+QVariant DebuggerCore::configValue(const QByteArray &name)
{
- const QVariant value = m_coreSettings->value(_("DebugMode/") + name);
- if (value.isValid())
- return value;
- // Legacy (pre-2.1): Check old un-namespaced-settings.
- return m_coreSettings->value(name);
+ return ICore::settings()->value(_("DebugMode/" + name));
}
void DebuggerPluginPrivate::onCurrentProjectChanged(Project *project)
@@ -1570,29 +1560,26 @@ void DebuggerPluginPrivate::languagesChanged()
void DebuggerPluginPrivate::debugProject()
{
- ProjectExplorerPlugin *pe = ProjectExplorerPlugin::instance();
- if (Project *pro = pe->startupProject())
- pe->runProject(pro, DebugRunMode);
+ if (Project *pro = SessionManager::startupProject())
+ ProjectExplorerPlugin::instance()->runProject(pro, DebugRunMode);
}
void DebuggerPluginPrivate::debugProjectWithoutDeploy()
{
- ProjectExplorerPlugin *pe = ProjectExplorerPlugin::instance();
- if (Project *pro = pe->startupProject())
- pe->runProject(pro, DebugRunMode, true);
+ if (Project *pro = SessionManager::startupProject())
+ ProjectExplorerPlugin::instance()->runProject(pro, DebugRunMode, true);
}
void DebuggerPluginPrivate::debugProjectBreakMain()
{
- ProjectExplorerPlugin *pe = ProjectExplorerPlugin::instance();
- if (Project *pro = pe->startupProject())
- pe->runProject(pro, DebugRunModeWithBreakOnMain);
+ if (Project *pro = SessionManager::startupProject())
+ ProjectExplorerPlugin::instance()->runProject(pro, DebugRunModeWithBreakOnMain);
}
void DebuggerPluginPrivate::startAndDebugApplication()
{
DebuggerStartParameters sp;
- if (StartApplicationDialog::run(mainWindow(), m_coreSettings, &sp))
+ if (StartApplicationDialog::run(mainWindow(), &sp))
DebuggerRunControlFactory::createAndScheduleRun(sp);
}
@@ -1600,30 +1587,29 @@ void DebuggerPluginPrivate::attachCore()
{
AttachCoreDialog dlg(mainWindow());
- const QString lastExternalKit = configValue(_("LastExternalKit")).toString();
+ const QString lastExternalKit = configValue("LastExternalKit").toString();
if (!lastExternalKit.isEmpty())
dlg.setKitId(Id::fromString(lastExternalKit));
- dlg.setLocalExecutableFile(configValue(_("LastExternalExecutableFile")).toString());
- dlg.setLocalCoreFile(configValue(_("LastLocalCoreFile")).toString());
- dlg.setRemoteCoreFile(configValue(_("LastRemoteCoreFile")).toString());
- dlg.setOverrideStartScript(configValue(_("LastExternalStartScript")).toString());
- dlg.setForceLocalCoreFile(configValue(_("LastForceLocalCoreFile")).toBool());
+ dlg.setLocalExecutableFile(configValue("LastExternalExecutableFile").toString());
+ dlg.setLocalCoreFile(configValue("LastLocalCoreFile").toString());
+ dlg.setRemoteCoreFile(configValue("LastRemoteCoreFile").toString());
+ dlg.setOverrideStartScript(configValue("LastExternalStartScript").toString());
+ dlg.setForceLocalCoreFile(configValue("LastForceLocalCoreFile").toBool());
if (dlg.exec() != QDialog::Accepted)
return;
- setConfigValue(_("LastExternalExecutableFile"), dlg.localExecutableFile());
- setConfigValue(_("LastLocalCoreFile"), dlg.localCoreFile());
- setConfigValue(_("LastRemoteCoreFile"), dlg.remoteCoreFile());
- setConfigValue(_("LastExternalKit"), dlg.kit()->id().toSetting());
- setConfigValue(_("LastExternalStartScript"), dlg.overrideStartScript());
- setConfigValue(_("LastForceLocalCoreFile"), dlg.forcesLocalCoreFile());
+ setConfigValue("LastExternalExecutableFile", dlg.localExecutableFile());
+ setConfigValue("LastLocalCoreFile", dlg.localCoreFile());
+ setConfigValue("LastRemoteCoreFile", dlg.remoteCoreFile());
+ setConfigValue("LastExternalKit", dlg.kit()->id().toSetting());
+ setConfigValue("LastExternalStartScript", dlg.overrideStartScript());
+ setConfigValue("LastForceLocalCoreFile", dlg.forcesLocalCoreFile());
DebuggerStartParameters sp;
QString display = dlg.useLocalCoreFile() ? dlg.localCoreFile() : dlg.remoteCoreFile();
QTC_ASSERT(fillParameters(&sp, dlg.kit()), return);
- DebuggerKitInformation::DebuggerItem info = DebuggerKitInformation::debuggerItem(dlg.kit());
- sp.masterEngineType = info.engineType;
+ sp.masterEngineType = DebuggerKitInformation::engineType(dlg.kit());
sp.executable = dlg.localExecutableFile();
sp.coreFile = dlg.localCoreFile();
sp.displayName = tr("Core file \"%1\"").arg(display);
@@ -1635,7 +1621,7 @@ void DebuggerPluginPrivate::attachCore()
void DebuggerPluginPrivate::startRemoteCdbSession()
{
- const QString connectionKey = _("CdbRemoteConnection");
+ const QByteArray connectionKey = "CdbRemoteConnection";
DebuggerStartParameters sp;
Kit *kit = CdbMatcher::findUniversalCdbKit();
QTC_ASSERT(kit && fillParameters(&sp, kit), return);
@@ -1657,7 +1643,7 @@ void DebuggerPluginPrivate::attachToRemoteServer()
{
DebuggerStartParameters sp;
sp.startMode = AttachToRemoteServer;
- if (StartApplicationDialog::run(mainWindow(), m_coreSettings, &sp)) {
+ if (StartApplicationDialog::run(mainWindow(), &sp)) {
sp.closeMode = KillAtClose;
sp.serverStartScript.clear();
DebuggerRunControlFactory::createAndScheduleRun(sp);
@@ -1692,7 +1678,7 @@ void DebuggerPluginPrivate::attachToProcess(bool startServerOnly)
QTC_ASSERT(kit, return);
IDevice::ConstPtr device = DeviceKitInformation::device(kit);
QTC_ASSERT(device, return);
- DeviceProcess process = dlg->currentProcess();
+ DeviceProcessItem process = dlg->currentProcess();
if (process.pid == 0) {
QMessageBox::warning(mainWindow(), tr("Warning"),
tr("Cannot attach to process with PID 0"));
@@ -1745,13 +1731,13 @@ void DebuggerPluginPrivate::attachToQmlPort()
DebuggerStartParameters sp;
AttachToQmlPortDialog dlg(mainWindow());
- const QVariant qmlServerPort = configValue(_("LastQmlServerPort"));
+ const QVariant qmlServerPort = configValue("LastQmlServerPort");
if (qmlServerPort.isValid())
dlg.setPort(qmlServerPort.toInt());
else
dlg.setPort(sp.qmlServerPort);
- const Id kitId = Id::fromSetting(configValue(_("LastProfile")));
+ const Id kitId = Id::fromSetting(configValue("LastProfile"));
if (kitId.isValid())
dlg.setKitId(kitId);
@@ -1760,8 +1746,8 @@ void DebuggerPluginPrivate::attachToQmlPort()
Kit *kit = dlg.kit();
QTC_ASSERT(kit && fillParameters(&sp, kit), return);
- setConfigValue(_("LastQmlServerPort"), dlg.port());
- setConfigValue(_("LastProfile"), kit->id().toSetting());
+ setConfigValue("LastQmlServerPort", dlg.port());
+ setConfigValue("LastProfile", kit->id().toSetting());
IDevice::ConstPtr device = DeviceKitInformation::device(kit);
if (device) {
@@ -1782,11 +1768,10 @@ void DebuggerPluginPrivate::attachToQmlPort()
//
// get files from all the projects in the session
//
- SessionManager *sessionManager = ProjectExplorerPlugin::instance()->session();
- QList<Project *> projects = sessionManager->projects();
- if (Project *startupProject = ProjectExplorerPlugin::instance()->startupProject()) {
+ QList<Project *> projects = SessionManager::projects();
+ if (Project *startupProject = SessionManager::startupProject()) {
// startup project first
- projects.removeOne(ProjectExplorerPlugin::instance()->startupProject());
+ projects.removeOne(startupProject);
projects.insert(0, startupProject);
}
QStringList sourceFiles;
@@ -1812,7 +1797,8 @@ void DebuggerPluginPrivate::startRemoteEngine()
sp.connParams.password = dlg.password();
sp.connParams.timeout = 5;
- sp.connParams.authenticationType = QSsh::SshConnectionParameters::AuthenticationByPassword;
+ sp.connParams.authenticationType
+ = QSsh::SshConnectionParameters::AuthenticationTypeTryAllPasswordBasedMethods;
sp.connParams.port = 22;
sp.connParams.options = QSsh::SshIgnoreDefaultProxy;
@@ -1863,7 +1849,7 @@ void DebuggerPluginPrivate::requestContextMenu(ITextEditor *editor,
bool contextUsable = true;
BreakpointModelId id = BreakpointModelId();
- const QString fileName = editor->document()->fileName();
+ const QString fileName = editor->document()->filePath();
if (editor->property("DisassemblerView").toBool()) {
args.fileName = fileName;
QString line = editor->textDocument()->contents()
@@ -1876,7 +1862,7 @@ void DebuggerPluginPrivate::requestContextMenu(ITextEditor *editor,
id = breakHandler()->findSimilarBreakpoint(needle);
contextUsable = args.address != 0;
} else {
- args.fileName = editor->document()->fileName();
+ args.fileName = editor->document()->filePath();
id = breakHandler()
->findBreakpointByFileAndLine(args.fileName, lineNumber);
if (!id)
@@ -1985,7 +1971,7 @@ void DebuggerPluginPrivate::toggleBreakpoint()
quint64 address = DisassemblerLine::addressFromDisassemblyLine(line);
toggleBreakpointByAddress(address);
} else if (lineNumber >= 0) {
- toggleBreakpointByFileAndLine(textEditor->document()->fileName(), lineNumber);
+ toggleBreakpointByFileAndLine(textEditor->document()->filePath(), lineNumber);
}
}
@@ -2042,7 +2028,7 @@ void DebuggerPluginPrivate::requestMark(ITextEditor *editor,
quint64 address = DisassemblerLine::addressFromDisassemblyLine(line);
toggleBreakpointByAddress(address);
} else if (editor->document()) {
- toggleBreakpointByFileAndLine(editor->document()->fileName(), lineNumber);
+ toggleBreakpointByFileAndLine(editor->document()->filePath(), lineNumber);
}
}
@@ -2069,15 +2055,15 @@ void DebuggerPluginPrivate::connectEngine(DebuggerEngine *engine)
m_currentEngine->resetLocation();
m_currentEngine = engine;
- m_localsWindow->setModel(engine->localsModel());
+ m_localsWindow->setModel(engine->watchModel());
m_modulesWindow->setModel(engine->modulesModel());
m_registerWindow->setModel(engine->registerModel());
- m_returnWindow->setModel(engine->returnModel());
+ m_returnWindow->setModel(engine->watchModel());
m_sourceFilesWindow->setModel(engine->sourceFilesModel());
m_stackWindow->setModel(engine->stackModel());
m_threadsWindow->setModel(engine->threadsModel());
- m_watchersWindow->setModel(engine->watchersModel());
- m_inspectorWindow->setModel(engine->inspectorModel());
+ m_watchersWindow->setModel(engine->watchModel());
+ m_inspectorWindow->setModel(engine->watchModel());
engine->watchHandler()->rebuildModel();
@@ -2120,29 +2106,26 @@ void DebuggerPluginPrivate::cleanupViews()
if (!boolSetting(CloseBuffersOnExit))
return;
- EditorManager *editorManager = EditorManager::instance();
- QTC_ASSERT(editorManager, return);
- QList<IEditor *> toClose;
- foreach (IEditor *editor, editorManager->openedEditors()) {
- if (editor->property(Constants::OPENED_BY_DEBUGGER).toBool()) {
- IDocument *doc = editor->document();
+ QList<IDocument *> toClose;
+ foreach (IDocument *document, EditorManager::documentModel()->openedDocuments()) {
+ if (document->property(Constants::OPENED_BY_DEBUGGER).toBool()) {
bool keepIt = true;
- if (editor->property(Constants::OPENED_WITH_DISASSEMBLY).toBool())
+ if (document->property(Constants::OPENED_WITH_DISASSEMBLY).toBool())
keepIt = false;
- else if (doc->isModified())
+ else if (document->isModified())
keepIt = true;
- else if (doc->fileName().contains(_("qeventdispatcher")))
+ else if (document->filePath().contains(_("qeventdispatcher")))
keepIt = false;
else
- keepIt = (editor == EditorManager::currentEditor());
+ keepIt = (document == EditorManager::currentDocument());
if (keepIt)
- editor->setProperty(Constants::OPENED_BY_DEBUGGER, false);
+ document->setProperty(Constants::OPENED_BY_DEBUGGER, false);
else
- toClose.append(editor);
+ toClose.append(document);
}
}
- editorManager->closeEditors(toClose);
+ EditorManager::closeDocuments(toClose);
}
void DebuggerPluginPrivate::setBusyCursor(bool busy)
@@ -2362,7 +2345,7 @@ void DebuggerPluginPrivate::updateDebugActions()
return;
ProjectExplorerPlugin *pe = ProjectExplorerPlugin::instance();
- Project *project = pe->startupProject();
+ Project *project = SessionManager::startupProject();
const bool canRun = pe->canRun(project, DebugRunMode);
m_startAction->setEnabled(canRun);
m_startAction->setToolTip(canRun ? QString() : pe->cannotRunReason(project, DebugRunMode));
@@ -2420,7 +2403,7 @@ void DebuggerPluginPrivate::showSettingsDialog()
void DebuggerPluginPrivate::updateDebugWithoutDeployMenu()
{
- const bool state = ProjectExplorerPlugin::instance()->projectExplorerSettings().deployBeforeRun;
+ const bool state = ProjectExplorerPlugin::projectExplorerSettings().deployBeforeRun;
m_debugWithoutDeployAction->setVisible(state);
}
@@ -2513,18 +2496,14 @@ const CPlusPlus::Snapshot &DebuggerPluginPrivate::cppCodeModelSnapshot() const
return m_codeModelSnapshot;
}
-void DebuggerPluginPrivate::setSessionValue(const QString &name, const QVariant &value)
+void DebuggerCore::setSessionValue(const QByteArray &key, const QVariant &value)
{
- QTC_ASSERT(sessionManager(), return);
- sessionManager()->setValue(name, value);
- //qDebug() << "SET SESSION VALUE: " << name;
+ SessionManager::setValue(QString::fromUtf8(key), value);
}
-QVariant DebuggerPluginPrivate::sessionValue(const QString &name)
+QVariant DebuggerCore::sessionValue(const QByteArray &key)
{
- QTC_ASSERT(sessionManager(), return QVariant());
- //qDebug() << "GET SESSION VALUE: " << name;
- return sessionManager()->value(name);
+ return SessionManager::value(QString::fromUtf8(key));
}
void DebuggerPluginPrivate::openTextEditor(const QString &titlePattern0,
@@ -2534,7 +2513,7 @@ void DebuggerPluginPrivate::openTextEditor(const QString &titlePattern0,
return;
QString titlePattern = titlePattern0;
IEditor *editor = EditorManager::openEditorWithContents(
- CC::K_DEFAULT_TEXT_EDITOR_ID, &titlePattern, contents);
+ CC::K_DEFAULT_TEXT_EDITOR_ID, &titlePattern, contents.toUtf8());
QTC_ASSERT(editor, return);
EditorManager::activateEditor(editor, EditorManager::IgnoreNavigationHistory);
}
@@ -2706,9 +2685,7 @@ void DebuggerPluginPrivate::extensionsInitialized()
{
const QKeySequence debugKey = QKeySequence(UseMacShortcuts ? tr("Ctrl+Y") : tr("F5"));
- m_coreSettings = ICore::settings();
-
- m_debuggerSettings = new DebuggerSettings(m_coreSettings);
+ m_debuggerSettings = new DebuggerSettings;
m_debuggerSettings->readSettings();
connect(ICore::instance(), SIGNAL(coreAboutToClose()), this, SLOT(coreShutdown()));
@@ -3180,6 +3157,7 @@ void DebuggerPluginPrivate::extensionsInitialized()
foreach (IOptionsPage *op, engineOptionPages)
m_plugin->addAutoReleasedObject(op);
m_plugin->addAutoReleasedObject(new LocalsAndExpressionsOptionsPage);
+ m_plugin->addAutoReleasedObject(new DebuggerOptionsPage);
connect(ModeManager::instance(), SIGNAL(currentModeChanged(Core::IMode*)),
SLOT(onModeChanged(Core::IMode*)));
@@ -3209,20 +3187,19 @@ void DebuggerPluginPrivate::extensionsInitialized()
SLOT(fontSettingsChanged(TextEditor::FontSettings)));
// ProjectExplorer
- connect(sessionManager(), SIGNAL(sessionLoaded(QString)),
+ connect(SessionManager::instance(), SIGNAL(sessionLoaded(QString)),
SLOT(sessionLoaded()));
- connect(sessionManager(), SIGNAL(aboutToSaveSession()),
+ connect(SessionManager::instance(), SIGNAL(aboutToSaveSession()),
SLOT(aboutToSaveSession()));
- connect(sessionManager(), SIGNAL(aboutToUnloadSession(QString)),
+ connect(SessionManager::instance(), SIGNAL(aboutToUnloadSession(QString)),
SLOT(aboutToUnloadSession()));
connect(ProjectExplorerPlugin::instance(), SIGNAL(updateRunActions()),
SLOT(updateDebugActions()));
// EditorManager
- QObject *editorManager = ICore::editorManager();
- connect(editorManager, SIGNAL(editorOpened(Core::IEditor*)),
+ connect(EditorManager::instance(), SIGNAL(editorOpened(Core::IEditor*)),
SLOT(editorOpened(Core::IEditor*)));
- connect(editorManager, SIGNAL(currentEditorChanged(Core::IEditor*)),
+ connect(EditorManager::instance(), SIGNAL(currentEditorChanged(Core::IEditor*)),
SLOT(updateBreakMenuItem(Core::IEditor*)));
// Application interaction
@@ -3264,7 +3241,7 @@ void DebuggerPluginPrivate::extensionsInitialized()
m_mainWindow->setToolBar(CppLanguage, toolbarContainer);
- QWidget *qmlToolbar = new QWidget;
+ QWidget *qmlToolbar = new QWidget(m_mainWindow);
hbox = new QHBoxLayout(qmlToolbar);
hbox->setMargin(0);
hbox->setSpacing(0);
@@ -3285,15 +3262,14 @@ void DebuggerPluginPrivate::extensionsInitialized()
setInitialState();
connectEngine(0);
- connect(sessionManager(),
+ connect(SessionManager::instance(),
SIGNAL(startupProjectChanged(ProjectExplorer::Project*)),
SLOT(onCurrentProjectChanged(ProjectExplorer::Project*)));
m_commonOptionsPage = new CommonOptionsPage(m_globalDebuggerOptions);
m_plugin->addAutoReleasedObject(m_commonOptionsPage);
- QTC_CHECK(m_coreSettings);
- m_globalDebuggerOptions->fromSettings(m_coreSettings);
+ m_globalDebuggerOptions->fromSettings();
m_watchersWindow->setVisible(false);
m_returnWindow->setVisible(false);
@@ -3383,7 +3359,7 @@ void DebuggerPluginPrivate::showModuleSections(const QString &moduleName,
void DebuggerPluginPrivate::aboutToShutdown()
{
m_plugin->removeObject(this);
- disconnect(sessionManager(),
+ disconnect(SessionManager::instance(),
SIGNAL(startupProjectChanged(ProjectExplorer::Project*)),
this, 0);
}
@@ -3434,7 +3410,9 @@ bool DebuggerPlugin::initialize(const QStringList &arguments, QString *errorMess
mstart->addSeparator(globalcontext, Constants::G_GENERAL);
mstart->addSeparator(globalcontext, Constants::G_SPECIAL);
- KitManager::instance()->registerKitInformation(new DebuggerKitInformation);
+ DebuggerItemManager::restoreDebuggers();
+
+ KitManager::registerKitInformation(new DebuggerKitInformation);
return theDebuggerCore->initialize(arguments, errorMessage);
}
@@ -3509,11 +3487,10 @@ void DebuggerPluginPrivate::testProjectLoaded(Project *project)
void DebuggerPluginPrivate::testProjectEvaluated()
{
- QString fileName = m_testProject->document()->fileName();
+ QString fileName = m_testProject->projectFilePath();
QVERIFY(!fileName.isEmpty());
qWarning("Project %s loaded", qPrintable(fileName));
- connect(ProjectExplorerPlugin::instance()->buildManager(),
- SIGNAL(buildQueueFinished(bool)),
+ connect(BuildManager::instance(), SIGNAL(buildQueueFinished(bool)),
SLOT(testProjectBuilt(bool)));
ProjectExplorerPlugin::instance()->buildProject(m_testProject);
}
@@ -3532,25 +3509,25 @@ void DebuggerPluginPrivate::testUnloadProject()
invoke<void>(pe, "unloadProject");
}
-static Target *activeTarget()
-{
- Project *project = ProjectExplorerPlugin::instance()->currentProject();
- return project->activeTarget();
-}
+//static Target *activeTarget()
+//{
+// Project *project = ProjectExplorerPlugin::instance()->currentProject();
+// return project->activeTarget();
+//}
-static Kit *currentKit()
-{
- Target *t = activeTarget();
- if (!t || !t->isEnabled())
- return 0;
- return t->kit();
-}
+//static Kit *currentKit()
+//{
+// Target *t = activeTarget();
+// if (!t || !t->isEnabled())
+// return 0;
+// return t->kit();
+//}
-static LocalApplicationRunConfiguration *activeLocalRunConfiguration()
-{
- Target *t = activeTarget();
- return t ? qobject_cast<LocalApplicationRunConfiguration *>(t->activeRunConfiguration()) : 0;
-}
+//static LocalApplicationRunConfiguration *activeLocalRunConfiguration()
+//{
+// Target *t = activeTarget();
+// return t ? qobject_cast<LocalApplicationRunConfiguration *>(t->activeRunConfiguration()) : 0;
+//}
void DebuggerPluginPrivate::testRunProject(const DebuggerStartParameters &sp, const TestCallBack &cb)
{
@@ -3575,37 +3552,37 @@ void DebuggerPluginPrivate::testFinished()
///////////////////////////////////////////////////////////////////////////
-void DebuggerPlugin::testStateMachine()
-{
- theDebuggerCore->testStateMachine1();
-}
-
-void DebuggerPluginPrivate::testStateMachine1()
-{
- m_testSuccess = true;
- QString proFile = ICore::resourcePath();
- if (Utils::HostOsInfo::isMacHost())
- proFile += QLatin1String("/../..");
- proFile += QLatin1String("/../../tests/manual/debugger/simple/simple.pro");
- testLoadProject(proFile, TestCallBack(this, "testStateMachine2"));
- QVERIFY(m_testSuccess);
- QTestEventLoop::instance().enterLoop(20);
-}
-
-void DebuggerPluginPrivate::testStateMachine2()
-{
- DebuggerStartParameters sp;
- fillParameters(&sp, currentKit());
- sp.executable = activeLocalRunConfiguration()->executable();
- sp.testCase = TestNoBoundsOfCurrentFunction;
- testRunProject(sp, TestCallBack(this, "testStateMachine3"));
-}
-
-void DebuggerPluginPrivate::testStateMachine3()
-{
- testUnloadProject();
- testFinished();
-}
+//void DebuggerPlugin::testStateMachine()
+//{
+// theDebuggerCore->testStateMachine1();
+//}
+
+//void DebuggerPluginPrivate::testStateMachine1()
+//{
+// m_testSuccess = true;
+// QString proFile = ICore::resourcePath();
+// if (Utils::HostOsInfo::isMacHost())
+// proFile += QLatin1String("/../..");
+// proFile += QLatin1String("/../../tests/manual/debugger/simple/simple.pro");
+// testLoadProject(proFile, TestCallBack(this, "testStateMachine2"));
+// QVERIFY(m_testSuccess);
+// QTestEventLoop::instance().enterLoop(20);
+//}
+
+//void DebuggerPluginPrivate::testStateMachine2()
+//{
+// DebuggerStartParameters sp;
+// fillParameters(&sp, currentKit());
+// sp.executable = activeLocalRunConfiguration()->executable();
+// sp.testCase = TestNoBoundsOfCurrentFunction;
+// testRunProject(sp, TestCallBack(this, "testStateMachine3"));
+//}
+
+//void DebuggerPluginPrivate::testStateMachine3()
+//{
+// testUnloadProject();
+// testFinished();
+//}
///////////////////////////////////////////////////////////////////////////
diff --git a/src/plugins/debugger/debuggerplugin.h b/src/plugins/debugger/debuggerplugin.h
index 1c461c8b76..c0f6429742 100644
--- a/src/plugins/debugger/debuggerplugin.h
+++ b/src/plugins/debugger/debuggerplugin.h
@@ -77,7 +77,7 @@ private:
#ifdef WITH_TESTS
private slots:
void testBenchmark();
- void testStateMachine();
+// void testStateMachine();
#endif
};
diff --git a/src/plugins/debugger/debuggerprotocol.cpp b/src/plugins/debugger/debuggerprotocol.cpp
index b837ef80ce..1333577332 100644
--- a/src/plugins/debugger/debuggerprotocol.cpp
+++ b/src/plugins/debugger/debuggerprotocol.cpp
@@ -32,6 +32,7 @@
#include <QCoreApplication>
#include <QDateTime>
#include <QDebug>
+#include <QHostAddress>
#include <ctype.h>
@@ -611,6 +612,22 @@ QString decodeData(const QByteArray &ba, int encoding)
const QTime time = timeFromData(ba.mid(p + 1 ).toInt());
return QDateTime(date, time).toString(Qt::TextDate);
}
+ case IPv6AddressAndHexScopeId: { // 27, 16 hex-encoded bytes, "%" and the string-encoded scope
+ const int p = ba.indexOf('%');
+ QHostAddress ip6(QString::fromLatin1(p == -1 ? ba : ba.left(p)));
+ if (ip6.isNull())
+ break;
+
+ const QByteArray scopeId = p == -1 ? QByteArray() : QByteArray::fromHex(ba.mid(p + 1));
+ if (!scopeId.isEmpty())
+ ip6.setScopeId(QString::fromUtf16(reinterpret_cast<const ushort *>(scopeId.constData()),
+ scopeId.length() / 2));
+ return ip6.toString();
+ }
+ case Hex2EncodedUtf8WithoutQuotes: { // 28, %02x encoded 8 bit UTF-8 data without quotes
+ const QByteArray decodedBa = QByteArray::fromHex(ba);
+ return QString::fromUtf8(decodedBa);
+ }
}
qDebug() << "ENCODING ERROR: " << encoding;
return QCoreApplication::translate("Debugger", "<Encoding error>");
diff --git a/src/plugins/debugger/debuggerprotocol.h b/src/plugins/debugger/debuggerprotocol.h
index dd668e86ad..6bce7e1aec 100644
--- a/src/plugins/debugger/debuggerprotocol.h
+++ b/src/plugins/debugger/debuggerprotocol.h
@@ -202,7 +202,9 @@ enum DebuggerEncoding
Hex2EncodedUInt4 = 23,
Hex2EncodedUInt8 = 24,
Hex2EncodedFloat4 = 25,
- Hex2EncodedFloat8 = 26
+ Hex2EncodedFloat8 = 26,
+ IPv6AddressAndHexScopeId = 27,
+ Hex2EncodedUtf8WithoutQuotes = 28
};
// Keep in sync with dumper.py, symbolgroupvalue.cpp of CDB
diff --git a/src/plugins/debugger/debuggerrunconfigurationaspect.cpp b/src/plugins/debugger/debuggerrunconfigurationaspect.cpp
index bdafb8c80a..90c4c1b248 100644
--- a/src/plugins/debugger/debuggerrunconfigurationaspect.cpp
+++ b/src/plugins/debugger/debuggerrunconfigurationaspect.cpp
@@ -194,48 +194,32 @@ void DebuggerRunConfigWidget::useMultiProcessToggled(bool on)
DebuggerRunConfigurationAspect::DebuggerRunConfigurationAspect(
ProjectExplorer::RunConfiguration *rc) :
- m_runConfiguration(rc),
+ IRunConfigurationAspect(rc),
m_useCppDebugger(AutoEnabledLanguage),
m_useQmlDebugger(AutoEnabledLanguage),
m_qmlDebugServerPort(Constants::QML_DEFAULT_DEBUG_SERVER_PORT),
m_useMultiProcess(false)
{
- ctor();
-}
-
-DebuggerRunConfigurationAspect::DebuggerRunConfigurationAspect(
- ProjectExplorer::RunConfiguration *runConfiguration,
- const 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)
-{
- ctor();
-}
-
-ProjectExplorer::RunConfiguration *DebuggerRunConfigurationAspect::runConfiguration()
-{
- return m_runConfiguration;
+ setId("DebuggerAspect");
+ setDisplayName(tr("Debugger settings"));
}
void DebuggerRunConfigurationAspect::setUseQmlDebugger(bool value)
{
m_useQmlDebugger = value ? EnabledLanguage : DisabledLanguage;
- emit debuggersChanged();
+ emit requestRunActionsUpdate();
}
void DebuggerRunConfigurationAspect::setUseCppDebugger(bool value)
{
m_useCppDebugger = value ? EnabledLanguage : DisabledLanguage;
- emit debuggersChanged();
+ emit requestRunActionsUpdate();
}
bool DebuggerRunConfigurationAspect::useCppDebugger() const
{
if (m_useCppDebugger == DebuggerRunConfigurationAspect::AutoEnabledLanguage)
- return m_runConfiguration->target()->project()->projectLanguages().contains(
+ return runConfiguration()->target()->project()->projectLanguages().contains(
ProjectExplorer::Constants::LANG_CXX);
return m_useCppDebugger == DebuggerRunConfigurationAspect::EnabledLanguage;
}
@@ -243,7 +227,7 @@ bool DebuggerRunConfigurationAspect::useCppDebugger() const
bool DebuggerRunConfigurationAspect::useQmlDebugger() const
{
if (m_useQmlDebugger == DebuggerRunConfigurationAspect::AutoEnabledLanguage)
- return m_runConfiguration->target()->project()->projectLanguages().contains(
+ return runConfiguration()->target()->project()->projectLanguages().contains(
ProjectExplorer::Constants::LANG_QMLJS);
return m_useQmlDebugger == DebuggerRunConfigurationAspect::EnabledLanguage;
}
@@ -270,28 +254,21 @@ void DebuggerRunConfigurationAspect::setUseMultiProcess(bool value)
bool DebuggerRunConfigurationAspect::isQmlDebuggingSpinboxSuppressed() const
{
- ProjectExplorer::Kit *k = m_runConfiguration->target()->kit();
+ ProjectExplorer::Kit *k = runConfiguration()->target()->kit();
ProjectExplorer::IDevice::ConstPtr dev = ProjectExplorer::DeviceKitInformation::device(k);
if (dev.isNull())
return false;
return dev->canAutoDetectPorts();
}
-QString DebuggerRunConfigurationAspect::displayName() const
+void DebuggerRunConfigurationAspect::toMap(QVariantMap &map) const
{
- return tr("Debugger settings");
-}
-
-QVariantMap DebuggerRunConfigurationAspect::toMap() const
-{
- QVariantMap map;
map.insert(QLatin1String(USE_CPP_DEBUGGER_KEY), m_useCppDebugger == EnabledLanguage);
map.insert(QLatin1String(USE_CPP_DEBUGGER_AUTO_KEY), m_useCppDebugger == AutoEnabledLanguage);
map.insert(QLatin1String(USE_QML_DEBUGGER_KEY), m_useQmlDebugger == EnabledLanguage);
map.insert(QLatin1String(USE_QML_DEBUGGER_AUTO_KEY), m_useQmlDebugger == AutoEnabledLanguage);
map.insert(QLatin1String(QML_DEBUG_SERVER_PORT_KEY), m_qmlDebugServerPort);
map.insert(QLatin1String(USE_MULTIPROCESS_KEY), m_useMultiProcess);
- return map;
}
void DebuggerRunConfigurationAspect::fromMap(const QVariantMap &map)
@@ -311,10 +288,10 @@ void DebuggerRunConfigurationAspect::fromMap(const QVariantMap &map)
m_useMultiProcess = map.value(QLatin1String(USE_MULTIPROCESS_KEY), false).toBool();
}
-DebuggerRunConfigurationAspect *DebuggerRunConfigurationAspect::clone(
- ProjectExplorer::RunConfiguration *parent) const
+DebuggerRunConfigurationAspect *DebuggerRunConfigurationAspect::create
+ (ProjectExplorer::RunConfiguration *runConfiguration) const
{
- return new DebuggerRunConfigurationAspect(parent, this);
+ return new DebuggerRunConfigurationAspect(runConfiguration);
}
ProjectExplorer::RunConfigWidget *DebuggerRunConfigurationAspect::createConfigurationWidget()
@@ -322,12 +299,6 @@ ProjectExplorer::RunConfigWidget *DebuggerRunConfigurationAspect::createConfigur
return new Internal::DebuggerRunConfigWidget(this);
}
-void DebuggerRunConfigurationAspect::ctor()
-{
- connect(this, SIGNAL(debuggersChanged()),
- m_runConfiguration, SIGNAL(requestRunActionsUpdate()));
-}
-
} // namespace Debugger
diff --git a/src/plugins/debugger/debuggerrunconfigurationaspect.h b/src/plugins/debugger/debuggerrunconfigurationaspect.h
index 0dcbb18fc1..ab1c53838c 100644
--- a/src/plugins/debugger/debuggerrunconfigurationaspect.h
+++ b/src/plugins/debugger/debuggerrunconfigurationaspect.h
@@ -39,14 +39,13 @@ namespace Debugger {
namespace Internal { class DebuggerRunConfigWidget; }
class DEBUGGER_EXPORT DebuggerRunConfigurationAspect
- : public QObject, public ProjectExplorer::IRunConfigurationAspect
+ : public ProjectExplorer::IRunConfigurationAspect
{
Q_OBJECT
public:
DebuggerRunConfigurationAspect(ProjectExplorer::RunConfiguration *runConfiguration);
- DebuggerRunConfigurationAspect(ProjectExplorer::RunConfiguration *runConfiguration,
- const DebuggerRunConfigurationAspect *other);
+ DebuggerRunConfigurationAspect *create(ProjectExplorer::RunConfiguration *runConfiguration) const;
enum DebuggerLanguageStatus {
DisabledLanguage = 0,
@@ -54,14 +53,11 @@ public:
AutoEnabledLanguage
};
- QVariantMap toMap() const;
void fromMap(const QVariantMap &map);
+ void toMap(QVariantMap &map) const;
- DebuggerRunConfigurationAspect *clone(ProjectExplorer::RunConfiguration *parent) const;
ProjectExplorer::RunConfigWidget *createConfigurationWidget();
- QString displayName() const;
-
bool useCppDebugger() const;
void setUseCppDebugger(bool value);
bool useQmlDebugger() const;
@@ -71,15 +67,8 @@ public:
bool useMultiProcess() const;
void setUseMultiProcess(bool on);
bool isQmlDebuggingSpinboxSuppressed() const;
- ProjectExplorer::RunConfiguration *runConfiguration();
-
-signals:
- void debuggersChanged();
private:
- void ctor();
-
- ProjectExplorer::RunConfiguration *m_runConfiguration;
DebuggerLanguageStatus m_useCppDebugger;
DebuggerLanguageStatus m_useQmlDebugger;
uint m_qmlDebugServerPort;
diff --git a/src/plugins/debugger/debuggerrunner.cpp b/src/plugins/debugger/debuggerrunner.cpp
index 1e45604c9a..eeba0d25c1 100644
--- a/src/plugins/debugger/debuggerrunner.cpp
+++ b/src/plugins/debugger/debuggerrunner.cpp
@@ -42,7 +42,7 @@
#include "breakhandler.h"
#ifdef Q_OS_WIN
-# include "peutils.h"
+# include "shared/peutils.h"
# include <utils/winutils.h>
#endif
@@ -54,11 +54,11 @@
#include <projectexplorer/target.h>
#include <projectexplorer/taskhub.h>
+#include <utils/checkablemessagebox.h>
#include <utils/qtcassert.h>
#include <utils/qtcprocess.h>
#include <coreplugin/icore.h>
-#include <QErrorMessage>
#include <QTcpServer>
using namespace Debugger::Internal;
@@ -72,7 +72,6 @@ namespace Internal {
DebuggerEngine *createCdbEngine(const DebuggerStartParameters &sp, QString *error);
DebuggerEngine *createGdbEngine(const DebuggerStartParameters &sp);
-DebuggerEngine *createScriptEngine(const DebuggerStartParameters &sp);
DebuggerEngine *createPdbEngine(const DebuggerStartParameters &sp);
DebuggerEngine *createQmlEngine(const DebuggerStartParameters &sp);
DebuggerEngine *createQmlCppEngine(const DebuggerStartParameters &sp, QString *error);
@@ -86,8 +85,6 @@ static const char *engineTypeName(DebuggerEngineType et)
break;
case Debugger::GdbEngineType:
return "Gdb engine";
- case Debugger::ScriptEngineType:
- return "Script engine";
case Debugger::CdbEngineType:
return "Cdb engine";
case Debugger::PdbEngineType:
@@ -212,9 +209,14 @@ void DebuggerRunControl::start()
debuggerCore()->showMessage(warningMessage, LogWarning);
- QErrorMessage *msgBox = new QErrorMessage(debuggerCore()->mainWindow());
- msgBox->setAttribute(Qt::WA_DeleteOnClose);
- msgBox->showMessage(warningMessage);
+ static bool checked = true;
+ if (!checked)
+ break;
+ CheckableMessageBox::information(debuggerCore()->mainWindow(),
+ tr("Debugger"),
+ warningMessage,
+ tr("&Show this message again."),
+ &checked, QDialogButtonBox::Ok);
break;
}
}
@@ -338,7 +340,7 @@ static DebuggerStartParameters localStartParameters(RunConfiguration *runConfigu
return sp;
Target *target = runConfiguration->target();
- Kit *kit = target ? target->kit() : KitManager::instance()->defaultKit();
+ Kit *kit = target ? target->kit() : KitManager::defaultKit();
if (!fillParameters(&sp, kit, errorMessage))
return sp;
sp.environment = environment->environment();
@@ -362,7 +364,7 @@ static DebuggerStartParameters localStartParameters(RunConfiguration *runConfigu
if (const Project *project = target->project()) {
sp.projectSourceDirectory = project->projectDirectory();
if (const BuildConfiguration *buildConfig = target->activeBuildConfiguration())
- sp.projectBuildDirectory = buildConfig->buildDirectory();
+ sp.projectBuildDirectory = buildConfig->buildDirectory().toString();
sp.projectSourceFiles = project->files(Project::ExcludeGeneratedFiles);
}
}
@@ -428,11 +430,6 @@ static bool fixupEngineTypes(DebuggerStartParameters &sp, RunConfiguration *rc,
if (sp.masterEngineType != NoEngineType)
return true;
- if (sp.executable.endsWith(_(".js"))) {
- sp.masterEngineType = ScriptEngineType;
- return true;
- }
-
if (sp.executable.endsWith(_(".py"))) {
sp.masterEngineType = PdbEngineType;
return true;
@@ -466,10 +463,9 @@ static bool fixupEngineTypes(DebuggerStartParameters &sp, RunConfiguration *rc,
DebuggerRunControl *DebuggerRunControlFactory::doCreate
(const DebuggerStartParameters &sp0, RunConfiguration *rc, QString *errorMessage)
{
- TaskHub *th = ProjectExplorerPlugin::instance()->taskHub();
- th->clearTasks(Debugger::Constants::TASK_CATEGORY_DEBUGGER_DEBUGINFO);
- th->clearTasks(Debugger::Constants::TASK_CATEGORY_DEBUGGER_TEST);
- th->clearTasks(Debugger::Constants::TASK_CATEGORY_DEBUGGER_RUNTIME);
+ TaskHub::clearTasks(Debugger::Constants::TASK_CATEGORY_DEBUGGER_DEBUGINFO);
+ TaskHub::clearTasks(Debugger::Constants::TASK_CATEGORY_DEBUGGER_TEST);
+ TaskHub::clearTasks(Debugger::Constants::TASK_CATEGORY_DEBUGGER_RUNTIME);
DebuggerStartParameters sp = sp0;
if (!debuggerCore()->boolSetting(AutoEnrichParameters)) {
@@ -518,8 +514,6 @@ DebuggerEngine *DebuggerRunControlFactory::createEngine(DebuggerEngineType et,
switch (et) {
case GdbEngineType:
return createGdbEngine(sp);
- case ScriptEngineType:
- return createScriptEngine(sp);
case CdbEngineType:
return createCdbEngine(sp, errorMessage);
case PdbEngineType:
diff --git a/src/plugins/debugger/debuggerstartparameters.h b/src/plugins/debugger/debuggerstartparameters.h
index 0f510e18f1..88f5a72e91 100644
--- a/src/plugins/debugger/debuggerstartparameters.h
+++ b/src/plugins/debugger/debuggerstartparameters.h
@@ -68,6 +68,7 @@ public:
qmlServerAddress(QLatin1String("127.0.0.1")),
qmlServerPort(Constants::QML_DEFAULT_DEBUG_SERVER_PORT),
remoteSetupNeeded(false),
+ useContinueInsteadOfRun(false),
startMode(NoStartMode),
closeMode(KillAtClose),
testReceiver(0),
@@ -123,6 +124,10 @@ public:
bool remoteSetupNeeded;
QMap<QString, QString> sourcePathMap;
+ // Used by baremetal plugin
+ bool useContinueInsteadOfRun; // if connected to a hw debugger run is not possible but continue is used
+ QByteArray commandsAfterConnect; // additional commands to post after connection to debug target
+
QString dumperLibrary;
QStringList solibSearchPath;
QStringList dumperLibraryLocations;
diff --git a/src/plugins/debugger/debuggertooltipmanager.cpp b/src/plugins/debugger/debuggertooltipmanager.cpp
index 7e45c758cd..f61ceffe9e 100644
--- a/src/plugins/debugger/debuggertooltipmanager.cpp
+++ b/src/plugins/debugger/debuggertooltipmanager.cpp
@@ -36,6 +36,7 @@
#include <coreplugin/icore.h>
#include <coreplugin/coreconstants.h>
+#include <coreplugin/editormanager/documentmodel.h>
#include <texteditor/basetexteditor.h>
#include <utils/tooltip/tooltip.h>
@@ -192,7 +193,7 @@ public:
explicit DebuggerToolTipEditor(IEditor *ie = 0);
bool isValid() const { return textEditor && baseTextEditor && document; }
operator bool() const { return isValid(); }
- QString fileName() const { return document ? document->fileName() : QString(); }
+ QString fileName() const { return document ? document->filePath() : QString(); }
static DebuggerToolTipEditor currentToolTipEditor();
@@ -478,16 +479,6 @@ private:
StandardItemTreeModelBuilder m_builder;
};
-void DebuggerToolTipWidget::addWidget(QWidget *w)
-{
- w->setFocusPolicy(Qt::NoFocus);
- m_mainVBoxLayout->addWidget(w);
-}
-
-void DebuggerToolTipWidget::addToolBarWidget(QWidget *w)
-{
- m_toolBar->addWidget(w);
-}
void DebuggerToolTipWidget::pin()
{
@@ -535,7 +526,7 @@ DebuggerToolTipContext DebuggerToolTipContext::fromEditor(IEditor *ie, int pos)
DebuggerToolTipContext rc;
if (const IDocument *document = ie->document()) {
if (const ITextEditor *te = qobject_cast<const ITextEditor *>(ie)) {
- rc.fileName = document->fileName();
+ rc.fileName = document->filePath();
rc.position = pos;
te->convertPosition(pos, &rc.line, &rc.column);
}
@@ -605,33 +596,34 @@ DebuggerToolTipWidget::DebuggerToolTipWidget(QWidget *parent) :
m_treeView(new DebuggerToolTipTreeView),
m_defaultModel(new QStandardItemModel(this))
{
- m_mainVBoxLayout->setSizeConstraint(QLayout::SetFixedSize);
- m_mainVBoxLayout->setContentsMargins(0, 0, 0, 0);
-
const QIcon pinIcon(QLatin1String(":/debugger/images/pin.xpm"));
const QList<QSize> pinIconSizes = pinIcon.availableSizes();
m_toolButton->setIcon(pinIcon);
connect(m_toolButton, SIGNAL(clicked()), this, SLOT(toolButtonClicked()));
- m_toolBar->setProperty("_q_custom_style_disabled", QVariant(true));
- if (!pinIconSizes.isEmpty())
- m_toolBar->setIconSize(pinIconSizes.front());
- m_toolBar->addWidget(m_toolButton);
-
- m_mainVBoxLayout->addWidget(m_toolBar);
-
- setLayout(m_mainVBoxLayout);
QToolButton *copyButton = new QToolButton;
copyButton->setIcon(QIcon(QLatin1String(Core::Constants::ICON_COPY)));
connect(copyButton, SIGNAL(clicked()), this, SLOT(copy()));
- addToolBarWidget(copyButton);
m_titleLabel->setText(msgReleasedText());
m_titleLabel->setMinimumWidth(40); // Ensure a draggable area even if text is empty.
connect(m_titleLabel, SIGNAL(dragged(QPoint)), this, SLOT(slotDragged(QPoint)));
- addToolBarWidget(m_titleLabel);
- addWidget(m_treeView);
+
+ m_toolBar->setProperty("_q_custom_style_disabled", QVariant(true));
+ if (!pinIconSizes.isEmpty())
+ m_toolBar->setIconSize(pinIconSizes.front());
+ m_toolBar->addWidget(m_toolButton);
+ m_toolBar->addWidget(m_titleLabel);
+ m_toolBar->addWidget(copyButton);
+
+ m_treeView->setFocusPolicy(Qt::NoFocus);
+
+ m_mainVBoxLayout->setSizeConstraint(QLayout::SetFixedSize);
+ m_mainVBoxLayout->setContentsMargins(0, 0, 0, 0);
+ m_mainVBoxLayout->addWidget(m_toolBar);
+ m_mainVBoxLayout->addWidget(m_treeView);
+ setLayout(m_mainVBoxLayout);
}
bool DebuggerToolTipWidget::matches(const QString &fileName,
@@ -764,7 +756,7 @@ DebuggerToolTipWidget *DebuggerToolTipWidget::loadSessionDataI(QXmlStreamReader
if (attributes.hasAttribute(offsetYAttribute))
offset.setY(attributes.value(offsetYAttribute).toString().toInt());
- const QString className = attributes.value(QLatin1String(toolTipClassAttributeC)).toString();
+ const QStringRef className = attributes.value(QLatin1String(toolTipClassAttributeC));
const QString engineType = attributes.value(QLatin1String(engineTypeAttributeC)).toString();
const QDate creationDate = dateFromString(attributes.value(QLatin1String(dateAttributeC)).toString());
if (!creationDate.isValid() || creationDate.daysTo(QDate::currentDate()) > toolTipsExpiryDays) {
@@ -788,7 +780,7 @@ DebuggerToolTipWidget *DebuggerToolTipWidget::loadSessionDataI(QXmlStreamReader
rc->setOffset(offset);
rc->pin();
} else {
- qWarning("Unable to create debugger tool tip widget of class %s", qPrintable(className));
+ qWarning("Unable to create debugger tool tip widget of class %s", qPrintable(className.toString()));
r.readElementText(QXmlStreamReader::SkipChildElements); // Skip
}
return rc;
@@ -1122,7 +1114,7 @@ void DebuggerToolTipManager::showToolTip(const QPoint &p, IEditor *editor,
if (debugToolTipPositioning)
qDebug() << "DebuggerToolTipManager::showToolTip" << p << " Mouse at " << QCursor::pos();
const Utils::WidgetContent widgetContent(toolTipWidget, true);
- Utils::ToolTip::instance()->show(p, widgetContent, widget);
+ Utils::ToolTip::show(p, widgetContent, widget);
registerToolTip(toolTipWidget);
}
@@ -1184,7 +1176,7 @@ void DebuggerToolTipManager::sessionAboutToChange()
void DebuggerToolTipManager::loadSessionData()
{
- const QString data = debuggerCore()->sessionValue(QLatin1String(sessionSettingsKeyC)).toString();
+ const QString data = DebuggerCore::sessionValue(sessionSettingsKeyC).toString();
if (data.isEmpty())
return;
QXmlStreamReader r(data);
@@ -1217,7 +1209,7 @@ void DebuggerToolTipManager::saveSessionData()
}
if (debugToolTips)
qDebug() << "DebuggerToolTipManager::saveSessionData" << m_tooltips.size() << data ;
- debuggerCore()->setSessionValue(QLatin1String(sessionSettingsKeyC), QVariant(data));
+ DebuggerCore::setSessionValue(sessionSettingsKeyC, QVariant(data));
}
void DebuggerToolTipManager::closeAllToolTips()
@@ -1367,12 +1359,13 @@ void DebuggerToolTipManager::debugModeEntered()
m_debugModeActive = true;
QWidget *topLevel = ICore::mainWindow()->topLevelWidget();
topLevel->installEventFilter(this);
- EditorManager *em = EditorManager::instance();
+ QObject *em = EditorManager::instance();
connect(em, SIGNAL(currentEditorChanged(Core::IEditor*)),
this, SLOT(slotUpdateVisibleToolTips()));
connect(em, SIGNAL(editorOpened(Core::IEditor*)),
this, SLOT(slotEditorOpened(Core::IEditor*)));
- foreach (IEditor *e, em->openedEditors())
+ DocumentModel *documentModel = EditorManager::documentModel();
+ foreach (IEditor *e, documentModel->editorsForDocuments(documentModel->openedDocuments()))
slotEditorOpened(e);
// Position tooltips delayed once all the editor placeholder layouting is done.
if (!m_tooltips.isEmpty())
@@ -1391,15 +1384,14 @@ void DebuggerToolTipManager::leavingDebugMode()
hide();
if (QWidget *topLevel = ICore::mainWindow()->topLevelWidget())
topLevel->removeEventFilter(this);
- if (EditorManager *em = EditorManager::instance()) {
- foreach (IEditor *e, em->openedEditors()) {
- if (DebuggerToolTipEditor toolTipEditor = DebuggerToolTipEditor(e)) {
- toolTipEditor.baseTextEditor->verticalScrollBar()->disconnect(this);
- toolTipEditor.textEditor->disconnect(this);
- }
+ DocumentModel *documentModel = EditorManager::documentModel();
+ foreach (IEditor *e, documentModel->editorsForDocuments(documentModel->openedDocuments())) {
+ if (DebuggerToolTipEditor toolTipEditor = DebuggerToolTipEditor(e)) {
+ toolTipEditor.baseTextEditor->verticalScrollBar()->disconnect(this);
+ toolTipEditor.textEditor->disconnect(this);
}
- em->disconnect(this);
}
+ EditorManager::instance()->disconnect(this);
m_lastToolTipEditor = 0;
m_lastToolTipPoint = QPoint(-1, -1);
}
diff --git a/src/plugins/debugger/debuggertooltipmanager.h b/src/plugins/debugger/debuggertooltipmanager.h
index 05721d4931..8465436ad8 100644
--- a/src/plugins/debugger/debuggertooltipmanager.h
+++ b/src/plugins/debugger/debuggertooltipmanager.h
@@ -88,9 +88,6 @@ class DebuggerToolTipWidget : public QWidget
public:
bool isPinned() const { return m_isPinned; }
- void addWidget(QWidget *w);
- void addToolBarWidget(QWidget *w);
-
explicit DebuggerToolTipWidget(QWidget *parent = 0);
bool engineAcquired() const { return m_engineAcquired; }
diff --git a/src/plugins/debugger/disassembleragent.cpp b/src/plugins/debugger/disassembleragent.cpp
index a45dbf3fa8..3dd14440bb 100644
--- a/src/plugins/debugger/disassembleragent.cpp
+++ b/src/plugins/debugger/disassembleragent.cpp
@@ -124,10 +124,7 @@ DisassemblerAgentPrivate::DisassemblerAgentPrivate()
DisassemblerAgentPrivate::~DisassemblerAgentPrivate()
{
- if (editor) {
- EditorManager *editorManager = EditorManager::instance();
- editorManager->closeEditors(QList<IEditor *>() << editor);
- }
+ EditorManager::closeEditor(editor);
editor = 0;
delete locationMark;
qDeleteAll(breakpointMarks);
@@ -258,7 +255,7 @@ void DisassemblerAgentPrivate::configureMimeType()
qobject_cast<TextEditor::PlainTextEditorWidget *>(editor->widget());
QTC_ASSERT(pe, return);
- MimeType mtype = ICore::mimeDatabase()->findByType(mimeType);
+ MimeType mtype = MimeDatabase::findByType(mimeType);
if (mtype)
pe->configure(mtype);
else
@@ -310,8 +307,9 @@ void DisassemblerAgent::setContentsToEditor(const DisassemblerLines &contents)
Core::Constants::K_DEFAULT_TEXT_EDITOR_ID,
&titlePattern));
QTC_ASSERT(d->editor, return);
- d->editor->setProperty(Debugger::Constants::OPENED_BY_DEBUGGER, true);
- d->editor->setProperty(Debugger::Constants::OPENED_WITH_DISASSEMBLY, true);
+ IDocument *document = d->editor->document();
+ document->setProperty(Debugger::Constants::OPENED_BY_DEBUGGER, true);
+ document->setProperty(Debugger::Constants::OPENED_WITH_DISASSEMBLY, true);
d->configureMimeType();
BaseTextEditorWidget *baseTextEdit =
@@ -334,7 +332,7 @@ void DisassemblerAgent::setContentsToEditor(const DisassemblerLines &contents)
plainTextEdit->setPlainText(str);
plainTextEdit->setReadOnly(true);
- d->editor->setDisplayName(_("Disassembler (%1)")
+ d->editor->document()->setDisplayName(_("Disassembler (%1)")
.arg(d->location.functionName()));
updateBreakpointMarkers();
diff --git a/src/plugins/debugger/dumper.pro b/src/plugins/debugger/dumper.pro
index df72e7e970..80898b06b5 100644
--- a/src/plugins/debugger/dumper.pro
+++ b/src/plugins/debugger/dumper.pro
@@ -20,5 +20,5 @@ true {
QT = core gui
}
-SOURCES += ../../../share/qtcreator/dumper/dumper.cpp
+SOURCES += ../../../share/qtcreator/debugger/dumper.cpp
diff --git a/src/plugins/debugger/gdb/attachgdbadapter.cpp b/src/plugins/debugger/gdb/attachgdbadapter.cpp
index bd4cd51694..038b90c94e 100644
--- a/src/plugins/debugger/gdb/attachgdbadapter.cpp
+++ b/src/plugins/debugger/gdb/attachgdbadapter.cpp
@@ -29,9 +29,9 @@
#include "attachgdbadapter.h"
-#include "debuggerprotocol.h"
-#include "debuggerstringutils.h"
-#include "debuggerstartparameters.h"
+#include <debugger/debuggerprotocol.h>
+#include <debugger/debuggerstringutils.h>
+#include <debugger/debuggerstartparameters.h>
#include <utils/qtcassert.h>
@@ -60,9 +60,9 @@ void GdbAttachEngine::setupEngine()
showMessage(_("TRYING TO START ADAPTER"));
if (!startParameters().workingDirectory.isEmpty())
- m_gdbProc.setWorkingDirectory(startParameters().workingDirectory);
+ m_gdbProc->setWorkingDirectory(startParameters().workingDirectory);
if (startParameters().environment.size())
- m_gdbProc.setEnvironment(startParameters().environment.toStringList());
+ m_gdbProc->setEnvironment(startParameters().environment.toStringList());
startGdb();
}
diff --git a/src/plugins/debugger/gdb/attachgdbadapter.h b/src/plugins/debugger/gdb/attachgdbadapter.h
index ce2f281aba..045c238afd 100644
--- a/src/plugins/debugger/gdb/attachgdbadapter.h
+++ b/src/plugins/debugger/gdb/attachgdbadapter.h
@@ -31,7 +31,7 @@
#define DEBUGGER_ATTACHGDBADAPTER_H
#include "gdbengine.h"
-#include "localgdbprocess.h"
+#include "gdbprocess.h"
namespace Debugger {
namespace Internal {
@@ -58,10 +58,7 @@ private:
void interruptInferior2();
void shutdownEngine();
- AbstractGdbProcess *gdbProc() { return &m_gdbProc; }
void handleAttach(const GdbResponse &response);
-
- LocalGdbProcess m_gdbProc;
};
} // namespace Internal
diff --git a/src/plugins/debugger/gdb/classicgdbengine.cpp b/src/plugins/debugger/gdb/classicgdbengine.cpp
index baede63b58..8e01de03d3 100644
--- a/src/plugins/debugger/gdb/classicgdbengine.cpp
+++ b/src/plugins/debugger/gdb/classicgdbengine.cpp
@@ -29,13 +29,13 @@
#include "gdbengine.h"
-#include "debuggeractions.h"
-#include "debuggercore.h"
-#include "debuggerprotocol.h"
-#include "debuggerstartparameters.h"
-#include "debuggerstringutils.h"
-#include "sourceutils.h"
-#include "stackhandler.h"
+#include <debugger/debuggeractions.h>
+#include <debugger/debuggercore.h>
+#include <debugger/debuggerprotocol.h>
+#include <debugger/debuggerstartparameters.h>
+#include <debugger/debuggerstringutils.h>
+#include <debugger/sourceutils.h>
+#include <debugger/stackhandler.h>
#include <coreplugin/icore.h>
#include <projectexplorer/projectexplorerconstants.h>
diff --git a/src/plugins/debugger/gdb/coregdbadapter.cpp b/src/plugins/debugger/gdb/coregdbadapter.cpp
index b50f6c6e19..ce66963e52 100644
--- a/src/plugins/debugger/gdb/coregdbadapter.cpp
+++ b/src/plugins/debugger/gdb/coregdbadapter.cpp
@@ -29,10 +29,10 @@
#include "coregdbadapter.h"
-#include "debuggercore.h"
-#include "debuggerprotocol.h"
-#include "debuggerstartparameters.h"
-#include "debuggerstringutils.h"
+#include <debugger/debuggercore.h>
+#include <debugger/debuggerprotocol.h>
+#include <debugger/debuggerstartparameters.h>
+#include <debugger/debuggerstringutils.h>
#include <utils/qtcassert.h>
@@ -150,9 +150,9 @@ void GdbCoreEngine::continueSetupEngine()
}
}
}
- if (isCore)
+ if (isCore) {
startGdb();
- else {
+ } else {
showMessageBox(QMessageBox::Warning,
tr("Error Loading Core File"),
tr("The specified file does not appear to be a core file."));
diff --git a/src/plugins/debugger/gdb/coregdbadapter.h b/src/plugins/debugger/gdb/coregdbadapter.h
index 38ae2cf691..f1168b1320 100644
--- a/src/plugins/debugger/gdb/coregdbadapter.h
+++ b/src/plugins/debugger/gdb/coregdbadapter.h
@@ -31,7 +31,6 @@
#define DEBUGGER_COREGDBADAPTER_H
#include "gdbengine.h"
-#include "localgdbprocess.h"
#include <QFile>
@@ -61,8 +60,6 @@ private:
void interruptInferior();
void shutdownEngine();
- AbstractGdbProcess *gdbProc() { return &m_gdbProc; }
-
void handleFileExecAndSymbols(const GdbResponse &response);
void handleTargetCore(const GdbResponse &response);
void handleRoundTrip(const GdbResponse &response);
@@ -78,7 +75,6 @@ private slots:
private:
QString m_executable;
QString m_coreName;
- LocalGdbProcess m_gdbProc;
QString m_tempCoreName;
QProcess *m_coreUnpackProcess;
QFile m_tempCoreFile;
diff --git a/src/plugins/debugger/gdb/gdb.pri b/src/plugins/debugger/gdb/gdb.pri
index 7a100e6851..64607124f8 100644
--- a/src/plugins/debugger/gdb/gdb.pri
+++ b/src/plugins/debugger/gdb/gdb.pri
@@ -3,14 +3,10 @@ HEADERS += \
$$PWD/gdboptionspage.h \
$$PWD/attachgdbadapter.h \
$$PWD/coregdbadapter.h \
- $$PWD/localplaingdbadapter.h \
$$PWD/termgdbadapter.h \
$$PWD/remotegdbserveradapter.h \
- $$PWD/abstractgdbprocess.h \
- $$PWD/localgdbprocess.h \
- $$PWD/remotegdbprocess.h \
- $$PWD/remoteplaingdbadapter.h \
- $$PWD/abstractplaingdbadapter.h \
+ $$PWD/gdbplainengine.h \
+ $$PWD/gdbprocess.h \
$$PWD/startgdbserverdialog.h
SOURCES += \
@@ -20,14 +16,10 @@ SOURCES += \
$$PWD/gdboptionspage.cpp \
$$PWD/attachgdbadapter.cpp \
$$PWD/coregdbadapter.cpp \
- $$PWD/localplaingdbadapter.cpp \
$$PWD/termgdbadapter.cpp \
$$PWD/remotegdbserveradapter.cpp \
- $$PWD/abstractgdbprocess.cpp \
- $$PWD/localgdbprocess.cpp \
- $$PWD/remotegdbprocess.cpp \
- $$PWD/remoteplaingdbadapter.cpp \
- $$PWD/abstractplaingdbadapter.cpp \
+ $$PWD/gdbprocess.cpp \
+ $$PWD/gdbplainengine.cpp \
$$PWD/startgdbserverdialog.cpp
RESOURCES += $$PWD/gdb.qrc
diff --git a/src/plugins/debugger/gdb/gdbengine.cpp b/src/plugins/debugger/gdb/gdbengine.cpp
index df3d06a9d5..b2cab00f27 100644
--- a/src/plugins/debugger/gdb/gdbengine.cpp
+++ b/src/plugins/debugger/gdb/gdbengine.cpp
@@ -29,39 +29,40 @@
#include "gdbengine.h"
-#include "debuggerstartparameters.h"
-#include "debuggerinternalconstants.h"
-#include "debuggerruncontrolfactory.h"
-#include "disassemblerlines.h"
#include "attachgdbadapter.h"
#include "coregdbadapter.h"
-#include "localplaingdbadapter.h"
+#include "gdbplainengine.h"
#include "termgdbadapter.h"
#include "remotegdbserveradapter.h"
-#include "remoteplaingdbadapter.h"
-
-#include "debuggeractions.h"
-#include "debuggercore.h"
-#include "debuggermainwindow.h"
-#include "debuggerplugin.h"
-#include "debuggerprotocol.h"
-#include "debuggerstringutils.h"
-#include "debuggertooltipmanager.h"
-#include "disassembleragent.h"
+
#include "gdboptionspage.h"
-#include "memoryagent.h"
-#include "sourceutils.h"
-
-#include "breakhandler.h"
-#include "moduleshandler.h"
-#include "registerhandler.h"
-#include "sourcefileshandler.h"
-#include "stackhandler.h"
-#include "threadshandler.h"
-#include "debuggersourcepathmappingwidget.h"
-#include "hostutils.h"
-#include "logwindow.h"
-#include "procinterrupt.h"
+
+#include <debugger/debuggerstartparameters.h>
+#include <debugger/debuggerinternalconstants.h>
+#include <debugger/debuggerruncontrolfactory.h>
+#include <debugger/disassemblerlines.h>
+
+#include <debugger/debuggeractions.h>
+#include <debugger/debuggercore.h>
+#include <debugger/debuggermainwindow.h>
+#include <debugger/debuggerplugin.h>
+#include <debugger/debuggerprotocol.h>
+#include <debugger/debuggerstringutils.h>
+#include <debugger/debuggertooltipmanager.h>
+#include <debugger/disassembleragent.h>
+#include <debugger/memoryagent.h>
+#include <debugger/sourceutils.h>
+
+#include <debugger/breakhandler.h>
+#include <debugger/moduleshandler.h>
+#include <debugger/registerhandler.h>
+#include <debugger/sourcefileshandler.h>
+#include <debugger/stackhandler.h>
+#include <debugger/threadshandler.h>
+#include <debugger/debuggersourcepathmappingwidget.h>
+#include <debugger/logwindow.h>
+#include <debugger/procinterrupt.h>
+#include <debugger/shared/hostutils.h>
#include <coreplugin/icore.h>
#include <projectexplorer/taskhub.h>
@@ -244,6 +245,7 @@ GdbEngine::GdbEngine(const DebuggerStartParameters &startParameters)
m_systemDumpersLoaded = false;
m_forceAsyncModel = false;
m_pythonAttemptedToLoad = false;
+ m_gdbProc = new GdbProcess(this);
invalidateSourcesList();
@@ -310,6 +312,11 @@ QString GdbEngine::errorMessage(QProcess::ProcessError error)
}
}
+GdbProcess *GdbEngine::gdbProc() const
+{
+ return m_gdbProc;
+}
+
#if 0
static void dump(const char *first, const char *middle, const QString & to)
{
@@ -687,9 +694,7 @@ void GdbEngine::handleResponse(const QByteArray &buff)
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);
+ TaskHub::addTask(type, m_lastWinException, Constants::TASK_CATEGORY_DEBUGGER_RUNTIME);
}
if (data.startsWith("QMLBP:")) {
@@ -734,7 +739,7 @@ void GdbEngine::handleResponse(const QByteArray &buff)
.arg(m_lastMissingDebugInfo).arg(cmd),
FileName(), 0, Core::Id(Debugger::Constants::TASK_CATEGORY_DEBUGGER_DEBUGINFO));
- taskHub()->addTask(task);
+ TaskHub::addTask(task);
DebugInfoTask dit;
dit.command = cmd;
@@ -1748,7 +1753,6 @@ void GdbEngine::handleStop2(const GdbMi &data)
reasontr = msgStoppedBySignal(_(meaning), _(name));
}
}
-
if (reason.isEmpty())
showStatusMessage(msgStopped());
else
@@ -2519,6 +2523,18 @@ void GdbEngine::updateResponse(BreakpointResponse &response, const GdbMi &bkpt)
response.type = WatchpointAtExpression;
response.expression = QString::fromLocal8Bit(what);
}
+ } else if (child.data() == "breakpoint") {
+ QByteArray catchType = bkpt["catch-type"].data();
+ if (catchType == "throw")
+ response.type = BreakpointAtThrow;
+ else if (catchType == "catch")
+ response.type = BreakpointAtCatch;
+ else if (catchType == "fork")
+ response.type = BreakpointAtFork;
+ else if (catchType == "exec")
+ response.type = BreakpointAtExec;
+ else if (catchType == "syscall")
+ response.type = BreakpointAtSysCall;
}
} else if (child.hasName("original-location")) {
originalLocation = child.data();
@@ -4854,12 +4870,12 @@ void GdbEngine::startGdb(const QStringList &args)
postCommand("set width 0");
postCommand("set height 0");
+ // FIXME: Provide proper Gui settings for these:
//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 remotecache on", ConsoleCommand);
+ //postCommand("set remotecache on", ConsoleCommand);
//postCommand("set non-stop on", ConsoleCommand);
typedef GlobalDebuggerOptions::SourcePathMap SourcePathMap;
@@ -4971,11 +4987,10 @@ void GdbEngine::tryLoadPythonDumpers()
m_pythonAttemptedToLoad = true;
const QByteArray dumperSourcePath =
- Core::ICore::resourcePath().toLocal8Bit() + "/dumper/";
-
- postCommand("python execfile('" + dumperSourcePath + "gbridge.py')",
- ConsoleCommand, CB(handlePythonSetup));
+ Core::ICore::resourcePath().toLocal8Bit() + "/debugger/";
+ postCommand("python sys.path.insert(1, '" + dumperSourcePath + "')", ConsoleCommand);
+ postCommand("python from gdbbridge import *", ConsoleCommand, CB(handlePythonSetup));
}
void GdbEngine::reloadDebuggingHelpers()
@@ -5084,6 +5099,12 @@ void GdbEngine::handleInferiorPrepared()
QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
+ if (!sp.commandsAfterConnect.isEmpty()) {
+ foreach (QByteArray command, sp.commandsAfterConnect.split('\n')) {
+ postCommand(command);
+ }
+ }
+
if (debuggerCore()->boolSetting(IntelFlavor)) {
//postCommand("set follow-exec-mode new");
postCommand("set disassembly-flavor intel");
@@ -5460,14 +5481,12 @@ DebuggerEngine *createGdbEngine(const DebuggerStartParameters &sp)
case StartRemoteProcess:
case AttachToRemoteServer:
return new GdbRemoteServerEngine(sp);
- case StartRemoteGdb:
- return new GdbRemotePlainEngine(sp);
case AttachExternal:
return new GdbAttachEngine(sp);
default:
if (sp.useTerminal)
return new GdbTermEngine(sp);
- return new GdbLocalPlainEngine(sp);
+ return new GdbPlainEngine(sp);
}
}
diff --git a/src/plugins/debugger/gdb/gdbengine.h b/src/plugins/debugger/gdb/gdbengine.h
index de3f99c4ac..3ef37d89ea 100644
--- a/src/plugins/debugger/gdb/gdbengine.h
+++ b/src/plugins/debugger/gdb/gdbengine.h
@@ -30,10 +30,10 @@
#ifndef DEBUGGER_GDBENGINE_H
#define DEBUGGER_GDBENGINE_H
-#include "debuggerengine.h"
+#include <debugger/debuggerengine.h>
-#include "watchhandler.h"
-#include "watchutils.h"
+#include <debugger/watchhandler.h>
+#include <debugger/watchutils.h>
#include <coreplugin/id.h>
@@ -45,7 +45,7 @@
namespace Debugger {
namespace Internal {
-class AbstractGdbProcess;
+class GdbProcess;
class DebugInfoTask;
class DebugInfoTaskHandler;
class GdbResponse;
@@ -650,7 +650,7 @@ protected:
// Convenience Functions
//
QString errorMessage(QProcess::ProcessError error);
- AbstractGdbProcess *gdbProc() const;
+ GdbProcess *gdbProc() const;
void showExecutionError(const QString &message);
static QByteArray tooltipIName(const QString &exp);
@@ -722,12 +722,13 @@ protected:
virtual void write(const QByteArray &data);
- virtual AbstractGdbProcess *gdbProc() = 0;
virtual DumperHandling dumperHandling() const = 0;
protected:
bool prepareCommand();
void interruptLocalInferior(qint64 pid);
+
+ GdbProcess *m_gdbProc;
};
diff --git a/src/plugins/debugger/gdb/gdboptionspage.cpp b/src/plugins/debugger/gdb/gdboptionspage.cpp
index 162abfdf10..a4a336418f 100644
--- a/src/plugins/debugger/gdb/gdboptionspage.cpp
+++ b/src/plugins/debugger/gdb/gdboptionspage.cpp
@@ -28,10 +28,10 @@
****************************************************************************/
#include "gdboptionspage.h"
-#include "commonoptionspage.h"
-#include "debuggeractions.h"
-#include "debuggercore.h"
-#include "debuggerinternalconstants.h"
+#include <debugger/commonoptionspage.h>
+#include <debugger/debuggeractions.h>
+#include <debugger/debuggercore.h>
+#include <debugger/debuggerinternalconstants.h>
#include <coreplugin/icore.h>
diff --git a/src/plugins/debugger/gdb/abstractplaingdbadapter.cpp b/src/plugins/debugger/gdb/gdbplainengine.cpp
index dc39a49f67..eaa992ec75 100644
--- a/src/plugins/debugger/gdb/abstractplaingdbadapter.cpp
+++ b/src/plugins/debugger/gdb/gdbplainengine.cpp
@@ -27,28 +27,37 @@
**
****************************************************************************/
-#include "abstractplaingdbadapter.h"
+#include "gdbplainengine.h"
+#include "gdbprocess.h"
-#include "debuggeractions.h"
-#include "debuggercore.h"
-#include "debuggerprotocol.h"
-#include "debuggerstartparameters.h"
-#include "debuggerstringutils.h"
+#include <debugger/debuggeractions.h>
+#include <debugger/debuggercore.h>
+#include <debugger/debuggerprotocol.h>
+#include <debugger/debuggerstartparameters.h>
+#include <debugger/debuggerstringutils.h>
+#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
+#include <QFileInfo>
+
namespace Debugger {
namespace Internal {
#define CB(callback) \
- static_cast<GdbEngine::GdbCommandCallback>(&GdbAbstractPlainEngine::callback), \
+ static_cast<GdbEngine::GdbCommandCallback>(&GdbPlainEngine::callback), \
STRINGIFY(callback)
-GdbAbstractPlainEngine::GdbAbstractPlainEngine(const DebuggerStartParameters &startParameters)
+GdbPlainEngine::GdbPlainEngine(const DebuggerStartParameters &startParameters)
: GdbEngine(startParameters)
-{}
+{
+ // Output
+ connect(&m_outputCollector, SIGNAL(byteDelivery(QByteArray)),
+ this, SLOT(readDebugeeOutput(QByteArray)));
+}
-void GdbAbstractPlainEngine::setupInferior()
+
+void GdbPlainEngine::setupInferior()
{
QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
if (!startParameters().processArgs.isEmpty()) {
@@ -59,7 +68,7 @@ void GdbAbstractPlainEngine::setupInferior()
CB(handleFileExecAndSymbols));
}
-void GdbAbstractPlainEngine::handleFileExecAndSymbols(const GdbResponse &response)
+void GdbPlainEngine::handleFileExecAndSymbols(const GdbResponse &response)
{
QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
if (response.resultClass == GdbResultDone) {
@@ -74,12 +83,15 @@ void GdbAbstractPlainEngine::handleFileExecAndSymbols(const GdbResponse &respons
}
}
-void GdbAbstractPlainEngine::runEngine()
+void GdbPlainEngine::runEngine()
{
- postCommand("-exec-run", GdbEngine::RunRequest, CB(handleExecRun));
+ if (startParameters().useContinueInsteadOfRun)
+ postCommand("-exec-continue", GdbEngine::RunRequest, CB(handleExecuteContinue));
+ else
+ postCommand("-exec-run", GdbEngine::RunRequest, CB(handleExecRun));
}
-void GdbAbstractPlainEngine::handleExecRun(const GdbResponse &response)
+void GdbPlainEngine::handleExecRun(const GdbResponse &response)
{
QTC_ASSERT(state() == EngineRunRequested, qDebug() << state());
if (response.resultClass == GdbResultRunning) {
@@ -100,5 +112,70 @@ void GdbAbstractPlainEngine::handleExecRun(const GdbResponse &response)
}
}
+GdbEngine::DumperHandling GdbPlainEngine::dumperHandling() const
+{
+ // LD_PRELOAD fails for System-Qt on Mac.
+ return Utils::HostOsInfo::isWindowsHost() || Utils::HostOsInfo::isMacHost()
+ ? DumperLoadedByGdb : DumperLoadedByGdbPreload;
+}
+
+void GdbPlainEngine::setupEngine()
+{
+ QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state());
+ showMessage(_("TRYING TO START ADAPTER"));
+
+ if (!prepareCommand())
+ return;
+
+ QStringList gdbArgs;
+
+ if (!m_outputCollector.listen()) {
+ handleAdapterStartFailed(tr("Cannot set up communication with child process: %1")
+ .arg(m_outputCollector.errorString()));
+ return;
+ }
+ gdbArgs.append(_("--tty=") + m_outputCollector.serverName());
+
+ if (!startParameters().workingDirectory.isEmpty())
+ m_gdbProc->setWorkingDirectory(startParameters().workingDirectory);
+ if (startParameters().environment.size())
+ m_gdbProc->setEnvironment(startParameters().environment.toStringList());
+
+ startGdb(gdbArgs);
+}
+
+void GdbPlainEngine::handleGdbStartFailed()
+{
+ m_outputCollector.shutdown();
+}
+
+void GdbPlainEngine::interruptInferior2()
+{
+ interruptLocalInferior(inferiorPid());
+}
+
+void GdbPlainEngine::shutdownEngine()
+{
+ showMessage(_("PLAIN ADAPTER SHUTDOWN %1").arg(state()));
+ m_outputCollector.shutdown();
+ notifyAdapterShutdownOk();
+}
+
+QByteArray GdbPlainEngine::execFilePath() const
+{
+ return QFileInfo(startParameters().executable)
+ .absoluteFilePath().toLocal8Bit();
+}
+
+QByteArray GdbPlainEngine::toLocalEncoding(const QString &s) const
+{
+ return s.toLocal8Bit();
+}
+
+QString GdbPlainEngine::fromLocalEncoding(const QByteArray &b) const
+{
+ return QString::fromLocal8Bit(b);
+}
+
} // namespace Debugger
} // namespace Internal
diff --git a/src/plugins/debugger/gdb/localplaingdbadapter.h b/src/plugins/debugger/gdb/gdbplainengine.h
index 7163b199f3..1bbc3e5677 100644
--- a/src/plugins/debugger/gdb/localplaingdbadapter.h
+++ b/src/plugins/debugger/gdb/gdbplainengine.h
@@ -27,47 +27,44 @@
**
****************************************************************************/
-#ifndef LOCALPLAINGDBADAPTER_H
-#define LOCALPLAINGDBADAPTER_H
+#ifndef GDBPLAINENGINE_H
+#define GDBPLAINENGINE_H
-#include "abstractplaingdbadapter.h"
-#include "localgdbprocess.h"
-#include <outputcollector.h>
+#include "gdbengine.h"
+#include <debugger/outputcollector.h>
namespace Debugger {
namespace Internal {
-///////////////////////////////////////////////////////////////////////
-//
-// PlainGdbAdapter
-//
-///////////////////////////////////////////////////////////////////////
-
-class GdbLocalPlainEngine : public GdbAbstractPlainEngine
+class GdbPlainEngine : public GdbEngine
{
+ // Needs tr - Context
Q_OBJECT
public:
- explicit GdbLocalPlainEngine(const DebuggerStartParameters &startParameters);
+ explicit GdbPlainEngine(const DebuggerStartParameters &startParameters);
private:
+ void handleExecRun(const GdbResponse &response);
+ void handleFileExecAndSymbols(const GdbResponse &response);
+
+ void setupInferior();
+ void runEngine();
void setupEngine();
void handleGdbStartFailed();
void interruptInferior2();
void shutdownEngine();
DumperHandling dumperHandling() const;
- AbstractGdbProcess *gdbProc() { return &m_gdbProc; }
QByteArray execFilePath() const;
QByteArray toLocalEncoding(const QString &s) const;
QString fromLocalEncoding(const QByteArray &b) const;
OutputCollector m_outputCollector;
- LocalGdbProcess m_gdbProc;
};
-} // namespace Internal
} // namespace Debugger
+} // namespace Internal
-#endif // LOCALPLAINGDBADAPTER_H
+#endif // GDBPLAINENGINE_H
diff --git a/src/plugins/debugger/gdb/localgdbprocess.cpp b/src/plugins/debugger/gdb/gdbprocess.cpp
index 486c372df8..4ee38308ba 100644
--- a/src/plugins/debugger/gdb/localgdbprocess.cpp
+++ b/src/plugins/debugger/gdb/gdbprocess.cpp
@@ -27,19 +27,15 @@
**
****************************************************************************/
-#include "localgdbprocess.h"
+#include "gdbprocess.h"
-#include "procinterrupt.h"
-#include "debuggerconstants.h"
-
-#ifdef Q_OS_WIN
-#include <utils/winutils.h>
-#endif
+#include <debugger/debuggerconstants.h>
+#include <debugger/procinterrupt.h>
namespace Debugger {
namespace Internal {
-LocalGdbProcess::LocalGdbProcess(QObject *parent) : AbstractGdbProcess(parent)
+GdbProcess::GdbProcess(QObject *parent) : QObject(parent)
{
connect(&m_gdbProc, SIGNAL(error(QProcess::ProcessError)),
this, SIGNAL(error(QProcess::ProcessError)));
@@ -51,89 +47,83 @@ LocalGdbProcess::LocalGdbProcess(QObject *parent) : AbstractGdbProcess(parent)
this, SIGNAL(readyReadStandardError()));
}
-QByteArray LocalGdbProcess::readAllStandardOutput()
+QByteArray GdbProcess::readAllStandardOutput()
{
return m_gdbProc.readAllStandardOutput();
}
-QByteArray LocalGdbProcess::readAllStandardError()
+QByteArray GdbProcess::readAllStandardError()
{
return m_gdbProc.readAllStandardError();
}
-void LocalGdbProcess::start(const QString &cmd, const QStringList &args)
+void GdbProcess::start(const QString &cmd, const QStringList &args)
{
m_gdbProc.setCommand(cmd, Utils::QtcProcess::joinArgs(args));
m_gdbProc.start();
}
-bool LocalGdbProcess::waitForStarted()
+bool GdbProcess::waitForStarted()
{
return m_gdbProc.waitForStarted();
}
-qint64 LocalGdbProcess::write(const QByteArray &data)
+qint64 GdbProcess::write(const QByteArray &data)
{
return m_gdbProc.write(data);
}
-void LocalGdbProcess::kill()
+void GdbProcess::kill()
{
m_gdbProc.kill();
}
-bool LocalGdbProcess::interrupt()
+bool GdbProcess::interrupt()
{
- long pid;
-#ifdef Q_OS_WIN
- pid = Utils::winQPidToPid(m_gdbProc.pid());
-#else
- pid = m_gdbProc.pid();
-#endif
+ long pid = Utils::qPidToPid(m_gdbProc.pid());
return interruptProcess(pid, GdbEngineType, &m_errorString);
}
-#ifdef Q_OS_WIN
-void LocalGdbProcess::setUseCtrlCStub(bool enable)
+void GdbProcess::setUseCtrlCStub(bool enable)
{
m_gdbProc.setUseCtrlCStub(enable);
}
-void LocalGdbProcess::winInterruptByCtrlC()
+void GdbProcess::winInterruptByCtrlC()
{
m_gdbProc.interrupt();
}
-#endif
-QProcess::ProcessState LocalGdbProcess::state() const
+QProcess::ProcessState GdbProcess::state() const
{
return m_gdbProc.state();
}
-QString LocalGdbProcess::errorString() const
+QString GdbProcess::errorString() const
{
return m_errorString + m_gdbProc.errorString();
}
-QProcessEnvironment LocalGdbProcess::processEnvironment() const
+QProcessEnvironment GdbProcess::processEnvironment() const
{
return m_gdbProc.processEnvironment();
}
-void LocalGdbProcess::setProcessEnvironment(const QProcessEnvironment &env)
+void GdbProcess::setProcessEnvironment(const QProcessEnvironment &env)
{
m_gdbProc.setProcessEnvironment(env);
}
-void LocalGdbProcess::setEnvironment(const QStringList &env)
+void GdbProcess::setEnvironment(const QStringList &env)
{
m_gdbProc.setEnvironment(Utils::Environment(env));
}
-void LocalGdbProcess::setWorkingDirectory(const QString &dir)
+void GdbProcess::setWorkingDirectory(const QString &dir)
{
m_gdbProc.setWorkingDirectory(dir);
}
} // namespace Internal
} // namespace Debugger
+
diff --git a/src/plugins/debugger/gdb/localgdbprocess.h b/src/plugins/debugger/gdb/gdbprocess.h
index 46db7356cf..dc356c608c 100644
--- a/src/plugins/debugger/gdb/localgdbprocess.h
+++ b/src/plugins/debugger/gdb/gdbprocess.h
@@ -27,41 +27,45 @@
**
****************************************************************************/
-#ifndef LOCALGDBPROCESS_H
-#define LOCALGDBPROCESS_H
-
-#include "abstractgdbprocess.h"
+#ifndef GDBPROCESS_H
+#define GDBPROCESS_H
#include <utils/qtcprocess.h>
namespace Debugger {
namespace Internal {
-class LocalGdbProcess : public AbstractGdbProcess
+class GdbProcess : public QObject
{
+ Q_OBJECT
+
public:
- explicit LocalGdbProcess(QObject *parent = 0);
+ explicit GdbProcess(QObject *parent = 0);
- virtual QByteArray readAllStandardOutput();
- virtual QByteArray readAllStandardError();
+ QByteArray readAllStandardOutput();
+ QByteArray readAllStandardError();
- virtual void start(const QString &cmd, const QStringList &args);
- virtual bool waitForStarted();
- virtual qint64 write(const QByteArray &data);
- virtual void kill();
- virtual bool interrupt();
-#ifdef Q_OS_WIN
+ void start(const QString &cmd, const QStringList &args);
+ bool waitForStarted();
+ qint64 write(const QByteArray &data);
+ void kill();
+ bool interrupt();
void setUseCtrlCStub(bool enable);
void winInterruptByCtrlC();
-#endif
- virtual QProcess::ProcessState state() const;
- virtual QString errorString() const;
+ QProcess::ProcessState state() const;
+ QString errorString() const;
+
+ QProcessEnvironment processEnvironment() const;
+ void setProcessEnvironment(const QProcessEnvironment &env);
+ void setEnvironment(const QStringList &env);
+ void setWorkingDirectory(const QString &dir);
- virtual QProcessEnvironment processEnvironment() const;
- virtual void setProcessEnvironment(const QProcessEnvironment &env);
- virtual void setEnvironment(const QStringList &env);
- virtual void setWorkingDirectory(const QString &dir);
+signals:
+ void error(QProcess::ProcessError);
+ void finished(int exitCode, QProcess::ExitStatus exitStatus);
+ void readyReadStandardError();
+ void readyReadStandardOutput();
private:
Utils::QtcProcess m_gdbProc;
@@ -71,4 +75,4 @@ private:
} // namespace Internal
} // namespace Debugger
-#endif // LOCALGDBPROCESS_H
+#endif // GDBPROCESS_H
diff --git a/src/plugins/debugger/gdb/localplaingdbadapter.cpp b/src/plugins/debugger/gdb/localplaingdbadapter.cpp
deleted file mode 100644
index ad68efbd17..0000000000
--- a/src/plugins/debugger/gdb/localplaingdbadapter.cpp
+++ /dev/null
@@ -1,123 +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 "localplaingdbadapter.h"
-
-#include "debuggerstartparameters.h"
-#include "debuggerstringutils.h"
-
-#include <utils/hostosinfo.h>
-#include <utils/qtcassert.h>
-
-#include <QFileInfo>
-
-namespace Debugger {
-namespace Internal {
-
-///////////////////////////////////////////////////////////////////////
-//
-// PlainGdbAdapter
-//
-///////////////////////////////////////////////////////////////////////
-
-GdbLocalPlainEngine::GdbLocalPlainEngine(const DebuggerStartParameters &startParameters)
- : GdbAbstractPlainEngine(startParameters)
-{
- // Output
- connect(&m_outputCollector, SIGNAL(byteDelivery(QByteArray)),
- this, SLOT(readDebugeeOutput(QByteArray)));
-}
-
-GdbEngine::DumperHandling GdbLocalPlainEngine::dumperHandling() const
-{
- // LD_PRELOAD fails for System-Qt on Mac.
- return Utils::HostOsInfo::isWindowsHost() || Utils::HostOsInfo::isMacHost()
- ? DumperLoadedByGdb : DumperLoadedByGdbPreload;
-}
-
-void GdbLocalPlainEngine::setupEngine()
-{
- QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state());
- showMessage(_("TRYING TO START ADAPTER"));
-
- if (!prepareCommand())
- return;
-
- QStringList gdbArgs;
-
- if (!m_outputCollector.listen()) {
- handleAdapterStartFailed(tr("Cannot set up communication with child process: %1")
- .arg(m_outputCollector.errorString()));
- return;
- }
- gdbArgs.append(_("--tty=") + m_outputCollector.serverName());
-
- if (!startParameters().workingDirectory.isEmpty())
- m_gdbProc.setWorkingDirectory(startParameters().workingDirectory);
- if (startParameters().environment.size())
- m_gdbProc.setEnvironment(startParameters().environment.toStringList());
-
- startGdb(gdbArgs);
-}
-
-void GdbLocalPlainEngine::handleGdbStartFailed()
-{
- m_outputCollector.shutdown();
-}
-
-void GdbLocalPlainEngine::shutdownEngine()
-{
- showMessage(_("PLAIN ADAPTER SHUTDOWN %1").arg(state()));
- m_outputCollector.shutdown();
- notifyAdapterShutdownOk();
-}
-
-void GdbLocalPlainEngine::interruptInferior2()
-{
- interruptLocalInferior(inferiorPid());
-}
-
-QByteArray GdbLocalPlainEngine::execFilePath() const
-{
- return QFileInfo(startParameters().executable)
- .absoluteFilePath().toLocal8Bit();
-}
-
-QByteArray GdbLocalPlainEngine::toLocalEncoding(const QString &s) const
-{
- return s.toLocal8Bit();
-}
-
-QString GdbLocalPlainEngine::fromLocalEncoding(const QByteArray &b) const
-{
- return QString::fromLocal8Bit(b);
-}
-
-} // namespace Internal
-} // namespace Debugger
diff --git a/src/plugins/debugger/gdb/pythongdbengine.cpp b/src/plugins/debugger/gdb/pythongdbengine.cpp
index 0963d1e9c1..459b4ecfaa 100644
--- a/src/plugins/debugger/gdb/pythongdbengine.cpp
+++ b/src/plugins/debugger/gdb/pythongdbengine.cpp
@@ -29,13 +29,13 @@
#include "gdbengine.h"
-#include "debuggerprotocol.h"
-#include "debuggeractions.h"
-#include "debuggercore.h"
-#include "debuggerstringutils.h"
-#include "debuggertooltipmanager.h"
+#include <debugger/debuggerprotocol.h>
+#include <debugger/debuggeractions.h>
+#include <debugger/debuggercore.h>
+#include <debugger/debuggerstringutils.h>
+#include <debugger/debuggertooltipmanager.h>
-#include "stackhandler.h"
+#include <debugger/stackhandler.h>
#include <utils/qtcassert.h>
diff --git a/src/plugins/debugger/gdb/remotegdbprocess.cpp b/src/plugins/debugger/gdb/remotegdbprocess.cpp
deleted file mode 100644
index 123457d465..0000000000
--- a/src/plugins/debugger/gdb/remotegdbprocess.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 "remotegdbprocess.h"
-
-#include "remoteplaingdbadapter.h"
-
-#include <utils/qtcassert.h>
-#include <utils/qtcprocess.h>
-#include <ssh/sshconnectionmanager.h>
-
-#include <QFileInfo>
-
-#include <ctype.h>
-
-using namespace QSsh;
-using namespace Utils;
-
-namespace Debugger {
-namespace Internal {
-
-RemoteGdbProcess::RemoteGdbProcess(const QSsh::SshConnectionParameters &connParams,
- GdbRemotePlainEngine *adapter, QObject *parent)
- : AbstractGdbProcess(parent), m_connParams(connParams), m_conn(0),
- m_state(Inactive), m_adapter(adapter)
-{
-}
-
-QByteArray RemoteGdbProcess::readAllStandardOutput()
-{
- QByteArray output = m_gdbOutput;
- m_gdbOutput.clear();
- return output;
-}
-
-QByteArray RemoteGdbProcess::readAllStandardError()
-{
- QByteArray errorOutput = m_errorOutput;
- m_errorOutput.clear();
- return errorOutput;
-}
-
-void RemoteGdbProcess::start(const QString &cmd, const QStringList &args)
-{
- Q_UNUSED(cmd);
- Q_UNUSED(args);
- QTC_ASSERT(m_state == RunningGdb, return);
-}
-
-void RemoteGdbProcess::realStart(const QString &cmd, const QStringList &args,
- const QString &executableFilePath)
-{
- QTC_ASSERT(m_state == Inactive, return);
- setState(Connecting);
-
- m_command = cmd;
- m_cmdArgs = args;
- m_appOutputFileName = "app_output_"
- + QFileInfo(executableFilePath).fileName().toUtf8();
- m_error.clear();
- m_lastSeqNr.clear();
- m_currentGdbOutput.clear();
- m_gdbOutput.clear();
- m_errorOutput.clear();
- m_inputToSend.clear();
- m_conn = SshConnectionManager::instance().acquireConnection(m_connParams);
- connect(m_conn, SIGNAL(error(QSsh::SshError)), this, SLOT(handleConnectionError()));
- if (m_conn->state() == SshConnection::Connected) {
- handleConnected();
- } else {
- connect(m_conn, SIGNAL(connected()), this, SLOT(handleConnected()));
- if (m_conn->state() == SshConnection::Unconnected)
- m_conn->connectToHost();
- }
-}
-
-void RemoteGdbProcess::handleConnected()
-{
- if (m_state == Inactive)
- return;
-
- QTC_ASSERT(m_state == Connecting, return);
- setState(CreatingFifo);
-
- m_fifoCreator = m_conn->createRemoteProcess( "rm -f "
- + m_appOutputFileName + " && mkfifo " + m_appOutputFileName);
- connect(m_fifoCreator.data(), SIGNAL(closed(int)), this,
- SLOT(handleFifoCreationFinished(int)));
- m_fifoCreator->start();
-}
-
-void RemoteGdbProcess::handleConnectionError()
-{
- if (m_state != Inactive)
- emitErrorExit(tr("Connection failure: %1.").arg(m_conn->errorString()));
-}
-
-void RemoteGdbProcess::handleFifoCreationFinished(int exitStatus)
-{
- if (m_state == Inactive)
- return;
- QTC_ASSERT(m_state == CreatingFifo, return);
-
- if (exitStatus != QSsh::SshRemoteProcess::NormalExit) {
- emitErrorExit(tr("Could not create FIFO."));
- } else {
- setState(StartingFifoReader);
- m_appOutputReader = m_conn->createRemoteProcess("cat "
- + m_appOutputFileName + " && rm -f " + m_appOutputFileName);
- connect(m_appOutputReader.data(), SIGNAL(started()), this,
- SLOT(handleAppOutputReaderStarted()));
- connect(m_appOutputReader.data(), SIGNAL(closed(int)), this,
- SLOT(handleAppOutputReaderFinished(int)));
- m_appOutputReader->start();
- }
-}
-
-void RemoteGdbProcess::handleAppOutputReaderStarted()
-{
- if (m_state == Inactive)
- return;
- QTC_ASSERT(m_state == StartingFifoReader, return);
- setState(StartingGdb);
-
- connect(m_appOutputReader.data(), SIGNAL(readyReadStandardOutput()),
- this, SLOT(handleAppOutput()));
- QByteArray cmdLine = "DISPLAY=:0.0 " + m_command.toUtf8() + ' '
- + Utils::QtcProcess::joinArgsUnix(m_cmdArgs).toUtf8()
- + " -tty=" + m_appOutputFileName;
- if (!m_wd.isEmpty())
- cmdLine.prepend("cd " + Utils::QtcProcess::quoteArgUnix(m_wd).toUtf8() + " && ");
- m_gdbProc = m_conn->createRemoteProcess(cmdLine);
- connect(m_gdbProc.data(), SIGNAL(started()), this,
- SLOT(handleGdbStarted()));
- connect(m_gdbProc.data(), SIGNAL(closed(int)), this,
- SLOT(handleGdbFinished(int)));
- connect(m_gdbProc.data(), SIGNAL(readyReadStandardOutput()), this,
- SLOT(handleGdbOutput()));
- connect(m_gdbProc.data(), SIGNAL(readyReadStandardError()), this,
- SLOT(handleErrOutput()));
- m_gdbProc->start();
-}
-
-void RemoteGdbProcess::handleAppOutputReaderFinished(int exitStatus)
-{
- if (exitStatus != QSsh::SshRemoteProcess::NormalExit)
- emitErrorExit(tr("Application output reader unexpectedly finished."));
-}
-
-void RemoteGdbProcess::handleGdbStarted()
-{
- if (m_state == Inactive)
- return;
- QTC_ASSERT(m_state == StartingGdb, return);
- setState(RunningGdb);
- emit started();
-}
-
-void RemoteGdbProcess::handleGdbFinished(int exitStatus)
-{
- if (m_state == Inactive)
- return;
- QTC_ASSERT(m_state == RunningGdb, return);
-
- switch (exitStatus) {
- case QSsh::SshRemoteProcess::FailedToStart:
- m_error = tr("Remote GDB failed to start.");
- setState(Inactive);
- emit startFailed();
- break;
- case QSsh::SshRemoteProcess::CrashExit:
- emitErrorExit(tr("Remote GDB crashed."));
- break;
- case QSsh::SshRemoteProcess::NormalExit:
- const int exitCode = m_gdbProc->exitCode();
- setState(Inactive);
- emit finished(exitCode, QProcess::NormalExit);
- break;
- }
-}
-
-bool RemoteGdbProcess::waitForStarted()
-{
- if (m_state == Inactive)
- return false;
- QTC_ASSERT(m_state == RunningGdb, return false);
- return true;
-}
-
-qint64 RemoteGdbProcess::write(const QByteArray &data)
-{
- if (m_state != RunningGdb || !m_inputToSend.isEmpty()
- || !m_lastSeqNr.isEmpty())
- m_inputToSend.enqueue(data);
- else
- sendInput(data);
- return data.size();
-}
-
-void RemoteGdbProcess::kill()
-{
- if (m_state == RunningGdb) {
- QSsh::SshRemoteProcess::Ptr killProc
- = m_conn->createRemoteProcess("pkill -SIGKILL -x gdb");
- killProc->start();
- } else {
- setState(Inactive);
- }
-}
-
-bool RemoteGdbProcess::interrupt()
-{
- return false;
-}
-
-void RemoteGdbProcess::interruptInferior()
-{
- QTC_ASSERT(m_state == RunningGdb, return);
-
- QSsh::SshRemoteProcess::Ptr intProc
- = m_conn->createRemoteProcess("pkill -x -SIGINT gdb");
- intProc->start();
-}
-
-QProcess::ProcessState RemoteGdbProcess::state() const
-{
- switch (m_state) {
- case RunningGdb: return QProcess::Running;
- case Inactive: return QProcess::NotRunning;
- default: return QProcess::Starting;
- }
-}
-
-QString RemoteGdbProcess::errorString() const
-{
- return m_error;
-}
-
-void RemoteGdbProcess::handleGdbOutput()
-{
- if (m_state == Inactive)
- return;
- QTC_ASSERT(m_state == RunningGdb, return);
-
- const QByteArray &output = m_gdbProc->readAllStandardOutput();
- // TODO: Carriage return removal still necessary?
- m_currentGdbOutput += removeCarriageReturn(output);
-#if 0
- qDebug("%s: complete unread output is '%s'", Q_FUNC_INFO, m_currentGdbOutput.data());
-#endif
- if (!m_currentGdbOutput.endsWith('\n'))
- return;
-
- if (m_currentGdbOutput.contains(m_lastSeqNr + '^'))
- m_lastSeqNr.clear();
-
- if (m_lastSeqNr.isEmpty() && !m_inputToSend.isEmpty()) {
-#if 0
- qDebug("Sending queued command: %s", m_inputToSend.head().data());
-#endif
- sendInput(m_inputToSend.dequeue());
- }
-
- if (!m_currentGdbOutput.isEmpty()) {
- const int startPos
- = m_gdbOutput.isEmpty() ? findAnchor(m_currentGdbOutput) : 0;
- if (startPos != -1) {
- m_gdbOutput += m_currentGdbOutput.mid(startPos);
- m_currentGdbOutput.clear();
- emit readyReadStandardOutput();
- }
- }
-}
-
-QProcessEnvironment RemoteGdbProcess::processEnvironment() const
-{
- return QProcessEnvironment(); // TODO: Provide actual environment.
-}
-
-void RemoteGdbProcess::setProcessEnvironment(const QProcessEnvironment & /* env */)
-{
- // TODO: Do something. (if remote process exists: set, otherwise queue)
-}
-
-void RemoteGdbProcess::setEnvironment(const QStringList & /* env */)
-{
- // TODO: Do something.
-}
-
-void RemoteGdbProcess::setWorkingDirectory(const QString &dir)
-{
- m_wd = dir;
-}
-
-int RemoteGdbProcess::findAnchor(const QByteArray &data) const
-{
- for (int pos = 0; pos < data.count(); ++pos) {
- const char c = data.at(pos);
- if (isdigit(c) || c == '*' || c == '+' || c == '=' || c == '~'
- || c == '@' || c == '&' || c == '^')
- return pos;
- }
- return -1;
-}
-
-void RemoteGdbProcess::sendInput(const QByteArray &data)
-{
- QTC_ASSERT(m_state == RunningGdb, return);
-
- int pos;
- for (pos = 0; pos < data.size(); ++pos)
- if (!isdigit(data.at(pos)))
- break;
- m_lastSeqNr = data.left(pos);
- m_gdbProc->write(data);
-}
-
-void RemoteGdbProcess::handleAppOutput()
-{
- if (m_state == RunningGdb)
- m_adapter->handleApplicationOutput(m_appOutputReader->readAllStandardOutput());
-}
-
-void RemoteGdbProcess::handleErrOutput()
-{
- if (m_state == RunningGdb) {
- m_errorOutput += m_gdbProc->readAllStandardError();
- emit readyReadStandardError();
- }
-}
-
-QByteArray RemoteGdbProcess::removeCarriageReturn(const QByteArray &data)
-{
- QByteArray output;
- for (int i = 0; i < data.size(); ++i) {
- const char c = data.at(i);
- if (c != '\r')
- output += c;
- }
- return output;
-}
-
-void RemoteGdbProcess::emitErrorExit(const QString &error)
-{
- if (m_error.isEmpty()) {
- m_error = error;
- setState(Inactive);
- emit finished(-1, QProcess::CrashExit);
- }
-}
-
-void RemoteGdbProcess::setState(State newState)
-{
- if (m_state == newState)
- return;
- m_state = newState;
- if (m_state == Inactive) {
- if (m_gdbProc) {
- disconnect(m_gdbProc.data(), 0, this, 0);
- m_gdbProc = QSsh::SshRemoteProcess::Ptr();
- }
- if (m_appOutputReader) {
- disconnect(m_appOutputReader.data(), 0, this, 0);
- m_appOutputReader = QSsh::SshRemoteProcess::Ptr();
- }
- if (m_fifoCreator) {
- disconnect(m_fifoCreator.data(), 0, this, 0);
- m_fifoCreator = QSsh::SshRemoteProcess::Ptr();
- }
- disconnect(m_conn, 0, this, 0);
- SshConnectionManager::instance().releaseConnection(m_conn);
- m_conn = 0;
- }
-}
-
-const QByteArray RemoteGdbProcess::CtrlC = QByteArray(1, 0x3);
-
-} // namespace Internal
-} // namespace Debugger
diff --git a/src/plugins/debugger/gdb/remotegdbprocess.h b/src/plugins/debugger/gdb/remotegdbprocess.h
deleted file mode 100644
index cafd366497..0000000000
--- a/src/plugins/debugger/gdb/remotegdbprocess.h
+++ /dev/null
@@ -1,128 +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 REMOTEGDBPROCESS_H
-#define REMOTEGDBPROCESS_H
-
-#include "abstractgdbprocess.h"
-
-#include <ssh/sshconnection.h>
-#include <ssh/sshremoteprocess.h>
-
-#include <QQueue>
-
-namespace Debugger {
-namespace Internal {
-
-class GdbRemotePlainEngine;
-
-class RemoteGdbProcess : public AbstractGdbProcess
-{
- Q_OBJECT
-public:
- RemoteGdbProcess(const QSsh::SshConnectionParameters &server,
- GdbRemotePlainEngine *adapter, QObject *parent = 0);
-
- virtual QByteArray readAllStandardOutput();
- virtual QByteArray readAllStandardError();
-
- virtual void start(const QString &cmd, const QStringList &args);
- virtual bool waitForStarted();
- virtual qint64 write(const QByteArray &data);
- virtual void kill();
- virtual bool interrupt();
-
- virtual QProcess::ProcessState state() const;
- virtual QString errorString() const;
-
- virtual QProcessEnvironment processEnvironment() const;
- virtual void setProcessEnvironment(const QProcessEnvironment &env);
- virtual void setEnvironment(const QStringList &env);
- virtual void setWorkingDirectory(const QString &dir);
-
- void interruptInferior();
- void realStart(const QString &cmd, const QStringList &args,
- const QString &executableFilePath);
-
- static const QByteArray CtrlC;
-
-signals:
- void started();
- void startFailed();
-
-private slots:
- void handleConnected();
- void handleConnectionError();
- void handleFifoCreationFinished(int exitStatus);
- void handleAppOutputReaderStarted();
- void handleAppOutputReaderFinished(int exitStatus);
- void handleGdbStarted();
- void handleGdbFinished(int exitStatus);
- void handleGdbOutput();
- void handleAppOutput();
- void handleErrOutput();
-
-private:
- enum State {
- Inactive, Connecting, CreatingFifo, StartingFifoReader,
- StartingGdb, RunningGdb
- };
-
- static QByteArray readerCmdLine(const QByteArray &file);
-
- int findAnchor(const QByteArray &data) const;
- void sendInput(const QByteArray &data);
- QByteArray removeCarriageReturn(const QByteArray &data);
- void emitErrorExit(const QString &error);
- void setState(State newState);
-
- QSsh::SshConnectionParameters m_connParams;
- QSsh::SshConnection *m_conn;
- QSsh::SshRemoteProcess::Ptr m_gdbProc;
- QSsh::SshRemoteProcess::Ptr m_appOutputReader;
- QSsh::SshRemoteProcess::Ptr m_fifoCreator;
- QByteArray m_gdbOutput;
- QByteArray m_errorOutput;
- QString m_command;
- QStringList m_cmdArgs;
- QString m_wd;
- QQueue<QByteArray> m_inputToSend;
- QByteArray m_currentGdbOutput;
- QByteArray m_lastSeqNr;
- QString m_error;
- QByteArray m_appOutputFileName;
- State m_state;
-
- GdbRemotePlainEngine *m_adapter;
-};
-
-} // namespace Internal
-} // namespace Debugger
-
-#endif // REMOTEGDBPROCESS_H
diff --git a/src/plugins/debugger/gdb/remotegdbserveradapter.cpp b/src/plugins/debugger/gdb/remotegdbserveradapter.cpp
index 1761e5a898..fe1913d64e 100644
--- a/src/plugins/debugger/gdb/remotegdbserveradapter.cpp
+++ b/src/plugins/debugger/gdb/remotegdbserveradapter.cpp
@@ -29,11 +29,13 @@
#include "remotegdbserveradapter.h"
-#include "debuggeractions.h"
-#include "debuggercore.h"
-#include "debuggerprotocol.h"
-#include "debuggerstartparameters.h"
-#include "debuggerstringutils.h"
+#include "gdbprocess.h"
+
+#include <debugger/debuggeractions.h>
+#include <debugger/debuggercore.h>
+#include <debugger/debuggerprotocol.h>
+#include <debugger/debuggerstartparameters.h>
+#include <debugger/debuggerstringutils.h>
#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
@@ -61,7 +63,7 @@ GdbRemoteServerEngine::GdbRemoteServerEngine(const DebuggerStartParameters &star
m_isMulti = false;
m_targetPid = -1;
#ifdef Q_OS_WIN
- m_gdbProc.setUseCtrlCStub(!startParameters.remoteExecutable.isEmpty()); // This is only set for QNX
+ m_gdbProc->setUseCtrlCStub(!startParameters.remoteExecutable.isEmpty()); // This is only set for QNX
#endif
connect(&m_uploadProc, SIGNAL(error(QProcess::ProcessError)),
SLOT(uploadProcError(QProcess::ProcessError)));
@@ -99,9 +101,9 @@ void GdbRemoteServerEngine::setupEngine()
m_uploadProc.waitForStarted();
}
if (!startParameters().workingDirectory.isEmpty())
- m_gdbProc.setWorkingDirectory(startParameters().workingDirectory);
+ m_gdbProc->setWorkingDirectory(startParameters().workingDirectory);
if (startParameters().environment.size())
- m_gdbProc.setEnvironment(startParameters().environment.toStringList());
+ m_gdbProc->setEnvironment(startParameters().environment.toStringList());
if (startParameters().remoteSetupNeeded)
notifyEngineRequestRemoteSetup();
@@ -433,12 +435,10 @@ void GdbRemoteServerEngine::interruptInferior2()
if (debuggerCore()->boolSetting(TargetAsync)) {
postCommand("-exec-interrupt", GdbEngine::Immediate,
CB(handleInterruptInferior));
-#ifdef Q_OS_WIN
- } else if (m_isQnxGdb) {
- m_gdbProc.winInterruptByCtrlC();
-#endif
+ } else if (m_isQnxGdb && Utils::HostOsInfo::isWindowsHost()) {
+ m_gdbProc->winInterruptByCtrlC();
} else {
- bool ok = m_gdbProc.interrupt();
+ bool ok = m_gdbProc->interrupt();
if (!ok) {
// FIXME: Extra state needed?
showMessage(_("NOTE: INFERIOR STOP NOT POSSIBLE"));
diff --git a/src/plugins/debugger/gdb/remotegdbserveradapter.h b/src/plugins/debugger/gdb/remotegdbserveradapter.h
index 8af780dfbe..e70b00ba40 100644
--- a/src/plugins/debugger/gdb/remotegdbserveradapter.h
+++ b/src/plugins/debugger/gdb/remotegdbserveradapter.h
@@ -31,7 +31,6 @@
#define REMOTEGDBSERVERADAPTER_H
#include "gdbengine.h"
-#include "localgdbprocess.h"
namespace Debugger {
namespace Internal {
@@ -58,8 +57,6 @@ private:
void interruptInferior2();
void shutdownEngine();
- AbstractGdbProcess *gdbProc() { return &m_gdbProc; }
-
signals:
/*
* For "external" clients of a debugger run control that need to do
@@ -95,7 +92,6 @@ private:
void handleExecRun(const GdbResponse &response);
QProcess m_uploadProc;
- LocalGdbProcess m_gdbProc;
bool m_isMulti;
int m_targetPid;
QByteArray m_serverChannel;
diff --git a/src/plugins/debugger/gdb/remoteplaingdbadapter.cpp b/src/plugins/debugger/gdb/remoteplaingdbadapter.cpp
deleted file mode 100644
index d97ac2370b..0000000000
--- a/src/plugins/debugger/gdb/remoteplaingdbadapter.cpp
+++ /dev/null
@@ -1,126 +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 "remoteplaingdbadapter.h"
-#include "debuggerstartparameters.h"
-
-#include <utils/qtcassert.h>
-
-namespace Debugger {
-namespace Internal {
-
-GdbRemotePlainEngine::GdbRemotePlainEngine(const DebuggerStartParameters &startParameters)
- : GdbAbstractPlainEngine(startParameters),
- m_gdbProc(startParameters.connParams, this)
-{
- connect(&m_gdbProc, SIGNAL(started()), this, SLOT(handleGdbStarted()));
- connect(&m_gdbProc, SIGNAL(startFailed()), this,
- SLOT(handleGdbStartFailed1()));
-}
-
-void GdbRemotePlainEngine::setupEngine()
-{
- QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state());
- showMessage(QLatin1String("TRYING TO START ADAPTER"));
-
- if (!startParameters().workingDirectory.isEmpty())
- m_gdbProc.setWorkingDirectory(startParameters().workingDirectory);
- if (startParameters().environment.size())
- m_gdbProc.setEnvironment(startParameters().environment.toStringList());
-
- notifyEngineRemoteSetupDone(startParameters().connParams.port, startParameters().qmlServerPort);
-}
-
-void GdbRemotePlainEngine::setupInferior()
-{
- GdbAbstractPlainEngine::setupInferior();
- postCommand("directory " + startParameters().remoteSourcesDir);
-}
-
-void GdbRemotePlainEngine::interruptInferior2()
-{
- m_gdbProc.interruptInferior();
-}
-
-QByteArray GdbRemotePlainEngine::execFilePath() const
-{
- return startParameters().executable.toUtf8();
-}
-
-QByteArray GdbRemotePlainEngine::toLocalEncoding(const QString &s) const
-{
- return s.toUtf8();
-}
-
-QString GdbRemotePlainEngine::fromLocalEncoding(const QByteArray &b) const
-{
- return QString::fromUtf8(b);
-}
-
-void GdbRemotePlainEngine::handleApplicationOutput(const QByteArray &output)
-{
- showMessage(QString::fromUtf8(output), AppOutput);
-}
-
-void GdbRemotePlainEngine::shutdownEngine()
-{
- notifyAdapterShutdownOk();
-}
-
-void GdbRemotePlainEngine::notifyEngineRemoteSetupDone(int gdbServerPort, int qmlPort)
-{
- Q_UNUSED(gdbServerPort);
- QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state());
-
- DebuggerStartParameters &sp = startParameters();
- if (qmlPort != -1)
- sp.qmlServerPort = qmlPort;
- m_gdbProc.realStart(sp.debuggerCommand,
- QStringList() << QLatin1String("-i") << QLatin1String("mi"),
- sp.executable);
-}
-
-void GdbRemotePlainEngine::handleGdbStarted()
-{
- startGdb();
-}
-
-void GdbRemotePlainEngine::handleGdbStartFailed1()
-{
- handleAdapterStartFailed(m_gdbProc.errorString());
-}
-
-void GdbRemotePlainEngine::notifyEngineRemoteSetupFailed(const QString &reason)
-{
- QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state());
- handleAdapterStartFailed(reason);
-}
-
-} // namespace Internal
-} // namespace Debugger
diff --git a/src/plugins/debugger/gdb/startgdbserverdialog.cpp b/src/plugins/debugger/gdb/startgdbserverdialog.cpp
index 117cb28277..dc6f4fe2d6 100644
--- a/src/plugins/debugger/gdb/startgdbserverdialog.cpp
+++ b/src/plugins/debugger/gdb/startgdbserverdialog.cpp
@@ -29,11 +29,11 @@
#include "startgdbserverdialog.h"
-#include "debuggermainwindow.h"
-#include "debuggerplugin.h"
-#include "debuggerkitinformation.h"
-#include "debuggerruncontrolfactory.h"
-#include "debuggerstartparameters.h"
+#include <debugger/debuggermainwindow.h>
+#include <debugger/debuggerplugin.h>
+#include <debugger/debuggerkitinformation.h>
+#include <debugger/debuggerruncontrolfactory.h>
+#include <debugger/debuggerstartparameters.h>
#include <projectexplorer/kitchooser.h>
#include <projectexplorer/devicesupport/deviceprocesslist.h>
@@ -62,7 +62,7 @@ public:
DeviceProcessesDialog *dialog;
bool startServerOnly;
- DeviceProcess process;
+ DeviceProcessItem process;
Kit *kit;
IDevice::ConstPtr device;
@@ -122,7 +122,10 @@ void GdbServerStarter::portListReady()
connect(&d->runner, SIGNAL(readyReadStandardError()), SLOT(handleProcessErrorOutput()));
connect(&d->runner, SIGNAL(processClosed(int)), SLOT(handleProcessClosed(int)));
- QByteArray cmd = "gdbserver --attach :"
+ QByteArray gdbServerPath = d->device->debugServerPath().toUtf8();
+ if (gdbServerPath.isEmpty())
+ gdbServerPath = "gdbserver";
+ QByteArray cmd = gdbServerPath + " --attach :"
+ QByteArray::number(port) + ' ' + QByteArray::number(d->process.pid);
logMessage(tr("Running command: %1").arg(QString::fromLatin1(cmd)));
d->runner.run(cmd, d->device->sshParameters());
diff --git a/src/plugins/debugger/gdb/termgdbadapter.cpp b/src/plugins/debugger/gdb/termgdbadapter.cpp
index 65e783238c..48e5ef4378 100644
--- a/src/plugins/debugger/gdb/termgdbadapter.cpp
+++ b/src/plugins/debugger/gdb/termgdbadapter.cpp
@@ -29,11 +29,11 @@
#include "termgdbadapter.h"
-#include "debuggercore.h"
-#include "debuggerprotocol.h"
-#include "debuggerstartparameters.h"
-#include "debuggerstringutils.h"
-#include "shared/hostutils.h"
+#include <debugger/debuggercore.h>
+#include <debugger/debuggerprotocol.h>
+#include <debugger/debuggerstartparameters.h>
+#include <debugger/debuggerstringutils.h>
+#include <debugger/shared/hostutils.h>
#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
diff --git a/src/plugins/debugger/gdb/termgdbadapter.h b/src/plugins/debugger/gdb/termgdbadapter.h
index 32e1c4d584..67e17ce127 100644
--- a/src/plugins/debugger/gdb/termgdbadapter.h
+++ b/src/plugins/debugger/gdb/termgdbadapter.h
@@ -31,7 +31,6 @@
#define DEBUGGER_TERMGDBADAPTER_H
#include "gdbengine.h"
-#include "localgdbprocess.h"
#include <utils/consoleprocess.h>
@@ -62,8 +61,6 @@ private:
void interruptInferior2();
void shutdownEngine();
- AbstractGdbProcess *gdbProc() { return &m_gdbProc; }
-
void handleStubAttached(const GdbResponse &response);
Q_SLOT void stubStarted();
@@ -71,7 +68,6 @@ private:
Q_SLOT void stubError(const QString &msg);
Utils::ConsoleProcess m_stubProc;
- LocalGdbProcess m_gdbProc;
};
} // namespace Internal
diff --git a/src/plugins/debugger/imageviewer.cpp b/src/plugins/debugger/imageviewer.cpp
index 26d96ad406..e7fe110a83 100644
--- a/src/plugins/debugger/imageviewer.cpp
+++ b/src/plugins/debugger/imageviewer.cpp
@@ -139,8 +139,8 @@ static void openImageViewer(const QImage &image)
fileName = temporaryFile.fileName();
temporaryFile.close();
}
- if (Core::IEditor *e = Core::EditorManager::instance()->openEditor(fileName))
- e->setProperty(Debugger::Constants::OPENED_BY_DEBUGGER, QVariant(true));
+ if (Core::IEditor *e = Core::EditorManager::openEditor(fileName))
+ e->document()->setProperty(Debugger::Constants::OPENED_BY_DEBUGGER, QVariant(true));
}
void ImageViewer::contextMenuEvent(QContextMenuEvent *ev)
diff --git a/src/plugins/debugger/lldb/lldb.pri b/src/plugins/debugger/lldb/lldb.pri
index 4d8fd071cb..a60318a624 100644
--- a/src/plugins/debugger/lldb/lldb.pri
+++ b/src/plugins/debugger/lldb/lldb.pri
@@ -1,5 +1,3 @@
HEADERS += $$PWD/lldbengine.h
SOURCES += $$PWD/lldbengine.cpp
-
-INCLUDEPATH *= $$PWD
diff --git a/src/plugins/debugger/lldb/lldbengine.cpp b/src/plugins/debugger/lldb/lldbengine.cpp
index 020dfc669f..8c2334c32c 100644
--- a/src/plugins/debugger/lldb/lldbengine.cpp
+++ b/src/plugins/debugger/lldb/lldbengine.cpp
@@ -29,24 +29,24 @@
#include "lldbengine.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"
-
-#include "breakhandler.h"
-#include "disassemblerlines.h"
-#include "moduleshandler.h"
-#include "registerhandler.h"
-#include "stackhandler.h"
-#include "sourceutils.h"
-#include "threadshandler.h"
-#include "watchhandler.h"
-#include "watchutils.h"
+#include <debugger/debuggeractions.h>
+#include <debugger/debuggercore.h>
+#include <debugger/debuggerdialogs.h>
+#include <debugger/debuggerplugin.h>
+#include <debugger/debuggerprotocol.h>
+#include <debugger/debuggerstartparameters.h>
+#include <debugger/debuggerstringutils.h>
+#include <debugger/debuggertooltipmanager.h>
+
+#include <debugger/breakhandler.h>
+#include <debugger/disassemblerlines.h>
+#include <debugger/moduleshandler.h>
+#include <debugger/registerhandler.h>
+#include <debugger/stackhandler.h>
+#include <debugger/sourceutils.h>
+#include <debugger/threadshandler.h>
+#include <debugger/watchhandler.h>
+#include <debugger/watchutils.h>
#include <utils/qtcassert.h>
#include <utils/savedaction.h>
@@ -148,7 +148,7 @@ void LldbEngine::setupEngine()
SLOT(handleResponse(QByteArray)), Qt::QueuedConnection);
m_lldbProc.start(_("python"), QStringList() << _("-i")
- << (Core::ICore::resourcePath() + _("/dumper/lbridge.py")) << m_lldbCmd);
+ << (Core::ICore::resourcePath() + _("/debugger/lldbbridge.py")) << m_lldbCmd);
if (!m_lldbProc.waitForStarted()) {
const QString msg = tr("Unable to start lldb '%1': %2")
@@ -1031,7 +1031,7 @@ void LldbEngine::fetchMemory(MemoryAgent *agent, QObject *editorToken,
m_memoryAgents.insert(agent, id);
m_memoryAgentTokens.insert(id, editorToken);
}
- runCommand(Command("readMemory")
+ runCommand(Command("fetchMemory")
.arg("address", addr)
.arg("length", length)
.arg("cookie", id));
diff --git a/src/plugins/debugger/lldb/lldbengine.h b/src/plugins/debugger/lldb/lldbengine.h
index ff239aeee3..aa8d445074 100644
--- a/src/plugins/debugger/lldb/lldbengine.h
+++ b/src/plugins/debugger/lldb/lldbengine.h
@@ -30,9 +30,9 @@
#ifndef DEBUGGER_LLDBENGINE
#define DEBUGGER_LLDBENGINE
-#include "debuggerengine.h"
-#include "disassembleragent.h"
-#include "memoryagent.h"
+#include <debugger/debuggerengine.h>
+#include <debugger/disassembleragent.h>
+#include <debugger/memoryagent.h>
#include <QPointer>
#include <QProcess>
diff --git a/src/plugins/debugger/lldblib/guest/lldbengineguest.cpp b/src/plugins/debugger/lldblib/guest/lldbengineguest.cpp
index 312a6cb457..7a5cd176e1 100644
--- a/src/plugins/debugger/lldblib/guest/lldbengineguest.cpp
+++ b/src/plugins/debugger/lldblib/guest/lldbengineguest.cpp
@@ -750,9 +750,9 @@ void LldbEngineGuest::lldbEvent(lldb::SBEvent *ev)
qDebug("unexpected ProcessEvent");
break;
}
- break;;
+ break;
default:
- break;;
+ break;
};
}
diff --git a/src/plugins/debugger/lldblib/ipcengineguest.h b/src/plugins/debugger/lldblib/ipcengineguest.h
index 88442a67ca..505328aa85 100644
--- a/src/plugins/debugger/lldblib/ipcengineguest.h
+++ b/src/plugins/debugger/lldblib/ipcengineguest.h
@@ -30,11 +30,11 @@
#ifndef IPCENGINEGUEST_H
#define IPCENGINEGUEST_H
-#include "breakhandler.h"
-#include "debuggerengine.h"
-#include "disassemblerlines.h"
-#include "stackhandler.h"
-#include "threadshandler.h"
+#include <debugger/breakhandler.h>
+#include <debugger/debuggerengine.h>
+#include <debugger/disassemblerlines.h>
+#include <debugger/stackhandler.h>
+#include <debugger/threadshandler.h>
#include <QQueue>
#include <QThread>
diff --git a/src/plugins/debugger/lldblib/ipcenginehost.cpp b/src/plugins/debugger/lldblib/ipcenginehost.cpp
index 0562939916..da48218ee3 100644
--- a/src/plugins/debugger/lldblib/ipcenginehost.cpp
+++ b/src/plugins/debugger/lldblib/ipcenginehost.cpp
@@ -30,20 +30,20 @@
#include "ipcenginehost.h"
#include "ipcengineguest.h"
-#include "debuggerstartparameters.h"
-#include "breakhandler.h"
-#include "breakpoint.h"
-#include "disassemblerlines.h"
-#include "moduleshandler.h"
-#include "registerhandler.h"
-#include "stackhandler.h"
-#include "watchhandler.h"
-#include "watchutils.h"
-#include "threadshandler.h"
-#include "disassembleragent.h"
-#include "memoryagent.h"
-#include "debuggerstreamops.h"
-#include "debuggercore.h"
+#include <debugger/debuggerstartparameters.h>
+#include <debugger/breakhandler.h>
+#include <debugger/breakpoint.h>
+#include <debugger/disassemblerlines.h>
+#include <debugger/moduleshandler.h>
+#include <debugger/registerhandler.h>
+#include <debugger/stackhandler.h>
+#include <debugger/watchhandler.h>
+#include <debugger/watchutils.h>
+#include <debugger/threadshandler.h>
+#include <debugger/disassembleragent.h>
+#include <debugger/memoryagent.h>
+#include <debugger/debuggerstreamops.h>
+#include <debugger/debuggercore.h>
#include <utils/qtcassert.h>
diff --git a/src/plugins/debugger/lldblib/ipcenginehost.h b/src/plugins/debugger/lldblib/ipcenginehost.h
index 8364d50657..92f847ca44 100644
--- a/src/plugins/debugger/lldblib/ipcenginehost.h
+++ b/src/plugins/debugger/lldblib/ipcenginehost.h
@@ -30,11 +30,11 @@
#ifndef DEBUGGER_IPCENGINE_HOST_H
#define DEBUGGER_IPCENGINE_HOST_H
-#include "debuggerengine.h"
-#include "threadshandler.h"
-#include "stackhandler.h"
-#include "breakhandler.h"
-#include "sourceagent.h"
+#include <debugger/debuggerengine.h>
+#include <debugger/threadshandler.h>
+#include <debugger/stackhandler.h>
+#include <debugger/breakhandler.h>
+#include <debugger/sourceagent.h>
#include <QQueue>
#include <QVariant>
diff --git a/src/plugins/debugger/lldblib/lldbenginehost.cpp b/src/plugins/debugger/lldblib/lldbenginehost.cpp
index 9b622057b5..538ba66e12 100644
--- a/src/plugins/debugger/lldblib/lldbenginehost.cpp
+++ b/src/plugins/debugger/lldblib/lldbenginehost.cpp
@@ -29,23 +29,23 @@
#include "lldbenginehost.h"
-#include "debuggerstartparameters.h"
-#include "debuggeractions.h"
-#include "debuggerconstants.h"
-#include "debuggerdialogs.h"
-#include "debuggerplugin.h"
-#include "debuggerstringutils.h"
-
-#include "breakhandler.h"
-#include "breakpoint.h"
-#include "moduleshandler.h"
-#include "registerhandler.h"
-#include "stackhandler.h"
-#include "watchhandler.h"
-#include "watchutils.h"
-#include "threadshandler.h"
-#include "disassembleragent.h"
-#include "memoryagent.h"
+#include <debugger/debuggerstartparameters.h>
+#include <debugger/debuggeractions.h>
+#include <debugger/debuggerconstants.h>
+#include <debugger/debuggerdialogs.h>
+#include <debugger/debuggerplugin.h>
+#include <debugger/debuggerstringutils.h>
+
+#include <debugger/breakhandler.h>
+#include <debugger/breakpoint.h>
+#include <debugger/moduleshandler.h>
+#include <debugger/registerhandler.h>
+#include <debugger/stackhandler.h>
+#include <debugger/watchhandler.h>
+#include <debugger/watchutils.h>
+#include <debugger/threadshandler.h>
+#include <debugger/disassembleragent.h>
+#include <debugger/memoryagent.h>
#include <coreplugin/icore.h>
#include <utils/qtcassert.h>
diff --git a/src/plugins/debugger/lldblib/lldboptionspage.cpp b/src/plugins/debugger/lldblib/lldboptionspage.cpp
index 19b4591b84..5ce79b33ad 100644
--- a/src/plugins/debugger/lldblib/lldboptionspage.cpp
+++ b/src/plugins/debugger/lldblib/lldboptionspage.cpp
@@ -28,8 +28,8 @@
****************************************************************************/
#include "lldboptionspage.h"
-#include "debuggerconstants.h"
-#include "debuggerinternalconstants.h"
+#include <debugger/debuggerconstants.h>
+#include <debugger/debuggerinternalconstants.h>
#include <coreplugin/icore.h>
@@ -70,7 +70,7 @@ void LldbOptionsPageWidget::load()
LldbOptionsPage::LldbOptionsPage()
{
// m_options->fromSettings(Core::ICore::settings());
- setId(Core::Id("F.Lldb"));
+ setId("F.Lldb");
setDisplayName(tr("LLDB"));
setCategory(Debugger::Constants::DEBUGGER_SETTINGS_CATEGORY);
setDisplayCategory(QCoreApplication::translate("Debugger", Constants::DEBUGGER_SETTINGS_TR_CATEGORY));
diff --git a/src/plugins/debugger/loadcoredialog.cpp b/src/plugins/debugger/loadcoredialog.cpp
index 8d4a4879da..8a07d6c6c8 100644
--- a/src/plugins/debugger/loadcoredialog.cpp
+++ b/src/plugins/debugger/loadcoredialog.cpp
@@ -292,7 +292,7 @@ int AttachCoreDialog::exec()
connect(d->localExecFileName, SIGNAL(changed(QString)), SLOT(changed()));
connect(d->localCoreFileName, SIGNAL(changed(QString)), SLOT(changed()));
connect(d->forceLocalCheckBox, SIGNAL(stateChanged(int)), SLOT(changed()));
- connect(d->kitChooser, SIGNAL(activated(int)), SLOT(changed()));
+ connect(d->kitChooser, SIGNAL(currentIndexChanged(int)), SLOT(changed()));
connect(d->buttonBox, SIGNAL(rejected()), SLOT(reject()));
connect(d->buttonBox, SIGNAL(accepted()), SLOT(accept()));
changed();
@@ -316,7 +316,7 @@ bool AttachCoreDialog::useLocalCoreFile() const
void AttachCoreDialog::changed()
{
- bool isValid = d->kitChooser->currentIndex() >= 0 && d->localExecFileName->isValid();
+ bool isValid = d->kitChooser->currentKit() && d->localExecFileName->isValid();
bool isKitLocal = isLocalKit();
d->forceLocalLabel->setVisible(!isKitLocal);
diff --git a/src/plugins/debugger/logwindow.cpp b/src/plugins/debugger/logwindow.cpp
index 32e702bc41..68fca7500c 100644
--- a/src/plugins/debugger/logwindow.cpp
+++ b/src/plugins/debugger/logwindow.cpp
@@ -41,7 +41,9 @@
#include <QMenu>
#include <QSyntaxHighlighter>
#include <QPlainTextEdit>
+#include <QPushButton>
#include <QFileDialog>
+#include <QToolButton>
#include <aggregation/aggregate.h>
#include <coreplugin/findplaceholder.h>
@@ -367,12 +369,18 @@ LogWindow::LogWindow(QWidget *parent)
m_inputText->setSizePolicy(QSizePolicy::MinimumExpanding,
QSizePolicy::MinimumExpanding);
- m_commandLabel = new QLabel(tr("Command:"), this);
m_commandEdit = new Utils::FancyLineEdit(this);
m_commandEdit->setFrame(false);
m_commandEdit->setHistoryCompleter(QLatin1String("DebuggerInput"));
+
+ QToolButton *repeatButton = new QToolButton(this);
+ repeatButton->setIcon(QIcon(QLatin1String(":/debugger/images/debugger_stepover_small.png")));
+ repeatButton->setIconSize(QSize(12, 12));
+ repeatButton->setToolTip(tr("Repeat last command for debug reasons"));
+
QHBoxLayout *commandBox = new QHBoxLayout;
- commandBox->addWidget(m_commandLabel);
+ commandBox->addWidget(repeatButton);
+ commandBox->addWidget(new QLabel(tr("Command:"), this));
commandBox->addWidget(m_commandEdit);
commandBox->setMargin(2);
commandBox->setSpacing(6);
@@ -414,6 +422,8 @@ LogWindow::LogWindow(QWidget *parent)
SLOT(sendCommand()));
connect(m_inputText, SIGNAL(executeLineRequested()),
SLOT(executeLine()));
+ connect(repeatButton, SIGNAL(clicked()),
+ SLOT(repeatLastCommand()));
connect(&m_outputTimer, SIGNAL(timeout()), SLOT(doOutput()));
@@ -427,6 +437,20 @@ void LogWindow::executeLine()
CppLanguage);
}
+void LogWindow::repeatLastCommand()
+{
+ QTextCursor tc = m_inputText->textCursor();
+ QRegExp re = QRegExp(QLatin1String("^\\d+(bb options:)(.*)$"));
+ for (QTextBlock block = tc.block(); block.isValid(); block = block.previous()) {
+ QString line = block.text();
+ if (re.exactMatch(line)) {
+ QString cmd = re.cap(1) + QLatin1String("pe,") + re.cap(2);
+ debuggerCore()->executeDebuggerCommand(cmd, CppLanguage);
+ return;
+ }
+ }
+}
+
void LogWindow::sendCommand()
{
debuggerCore()->executeDebuggerCommand(m_commandEdit->text(), CppLanguage);
diff --git a/src/plugins/debugger/logwindow.h b/src/plugins/debugger/logwindow.h
index f01ac44719..2f1f3e179a 100644
--- a/src/plugins/debugger/logwindow.h
+++ b/src/plugins/debugger/logwindow.h
@@ -77,6 +77,7 @@ public slots:
void showOutput(int channel, const QString &output);
void showInput(int channel, const QString &input);
void doOutput();
+ void repeatLastCommand();
signals:
void showPage();
@@ -88,7 +89,6 @@ private:
QTimer m_outputTimer;
QString m_queuedOutput;
Utils::FancyLineEdit *m_commandEdit;
- QLabel *m_commandLabel;
bool m_ignoreNextInputEcho;
};
diff --git a/src/plugins/debugger/memoryagent.cpp b/src/plugins/debugger/memoryagent.cpp
index 5289b50272..00c25af006 100644
--- a/src/plugins/debugger/memoryagent.cpp
+++ b/src/plugins/debugger/memoryagent.cpp
@@ -83,8 +83,6 @@ namespace Internal {
\sa Debugger::MemoryView, Debugger::RegisterMemoryView
*/
-namespace { const int DataRange = 1024 * 1024; }
-
MemoryAgent::MemoryAgent(DebuggerEngine *engine)
: QObject(engine), m_engine(engine)
{
@@ -110,7 +108,7 @@ void MemoryAgent::closeEditors()
foreach (QPointer<IEditor> editor, m_editors)
if (editor)
editors.append(editor.data());
- EditorManager::instance()->closeEditors(editors);
+ EditorManager::closeEditors(editors);
m_editors.clear();
}
@@ -181,8 +179,8 @@ bool MemoryAgent::doCreateBinEditor(quint64 addr, unsigned flags,
Core::Constants::K_DEFAULT_BINARY_EDITOR_ID, &title);
if (!editor)
return false;
- editor->setProperty(Constants::OPENED_BY_DEBUGGER, QVariant(true));
- editor->setProperty(Constants::OPENED_WITH_MEMORY, QVariant(true));
+ editor->document()->setProperty(Constants::OPENED_BY_DEBUGGER, QVariant(true));
+ editor->document()->setTemporary(true);
QWidget *editorBinEditor = editor->widget();
connectBinEditorWidget(editorBinEditor);
MemoryView::setBinEditorReadOnly(editorBinEditor, readOnly);
@@ -254,7 +252,7 @@ void MemoryAgent::updateContents()
bool MemoryAgent::hasVisibleEditor() const
{
- QList<IEditor *> visible = EditorManager::instance()->visibleEditors();
+ QList<IEditor *> visible = EditorManager::visibleEditors();
foreach (QPointer<IEditor> editor, m_editors)
if (visible.contains(editor.data()))
return true;
diff --git a/src/plugins/debugger/moduleshandler.cpp b/src/plugins/debugger/moduleshandler.cpp
index e35c8d1b20..3d22c888f6 100644
--- a/src/plugins/debugger/moduleshandler.cpp
+++ b/src/plugins/debugger/moduleshandler.cpp
@@ -262,7 +262,9 @@ ModulesHandler::ModulesHandler(DebuggerEngine *engine)
{
m_engine = engine;
m_model = new ModulesModel(this);
+ m_model->setObjectName(QLatin1String("ModulesModel"));
m_proxyModel = new QSortFilterProxyModel(this);
+ m_proxyModel->setObjectName(QLatin1String("ModulesProxyModel"));
m_proxyModel->setSourceModel(m_model);
}
diff --git a/src/plugins/debugger/pdb/pdbengine.cpp b/src/plugins/debugger/pdb/pdbengine.cpp
index 8ff71c8d9e..702bd1cefa 100644
--- a/src/plugins/debugger/pdb/pdbengine.cpp
+++ b/src/plugins/debugger/pdb/pdbengine.cpp
@@ -29,22 +29,22 @@
#include "pdbengine.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"
-
-#include "breakhandler.h"
-#include "moduleshandler.h"
-#include "registerhandler.h"
-#include "stackhandler.h"
-#include "sourceutils.h"
-#include "watchhandler.h"
-#include "watchutils.h"
+#include <debugger/debuggeractions.h>
+#include <debugger/debuggercore.h>
+#include <debugger/debuggerdialogs.h>
+#include <debugger/debuggerplugin.h>
+#include <debugger/debuggerprotocol.h>
+#include <debugger/debuggerstartparameters.h>
+#include <debugger/debuggerstringutils.h>
+#include <debugger/debuggertooltipmanager.h>
+
+#include <debugger/breakhandler.h>
+#include <debugger/moduleshandler.h>
+#include <debugger/registerhandler.h>
+#include <debugger/stackhandler.h>
+#include <debugger/sourceutils.h>
+#include <debugger/watchhandler.h>
+#include <debugger/watchutils.h>
#include <utils/qtcassert.h>
@@ -211,7 +211,7 @@ void PdbEngine::runEngine()
QTC_ASSERT(state() == EngineRunRequested, qDebug() << state());
showStatusMessage(tr("Running requested..."), 5000);
const QByteArray dumperSourcePath =
- Core::ICore::resourcePath().toLocal8Bit() + "/dumper/";
+ Core::ICore::resourcePath().toLocal8Bit() + "/debugger/";
QString fileName = QFileInfo(startParameters().executable).absoluteFilePath();
postDirectCommand("import sys");
postDirectCommand("sys.argv.append('" + fileName.toLocal8Bit() + "')");
diff --git a/src/plugins/debugger/pdb/pdbengine.h b/src/plugins/debugger/pdb/pdbengine.h
index 356b38f7f3..556729f6c7 100644
--- a/src/plugins/debugger/pdb/pdbengine.h
+++ b/src/plugins/debugger/pdb/pdbengine.h
@@ -30,7 +30,7 @@
#ifndef DEBUGGER_PDBENGINE_H
#define DEBUGGER_PDBENGINE_H
-#include "debuggerengine.h"
+#include <debugger/debuggerengine.h>
#include <QProcess>
#include <QQueue>
diff --git a/src/plugins/debugger/procinterrupt.cpp b/src/plugins/debugger/procinterrupt.cpp
index 0ad32373af..178f6a823e 100644
--- a/src/plugins/debugger/procinterrupt.cpp
+++ b/src/plugins/debugger/procinterrupt.cpp
@@ -93,51 +93,70 @@ bool Debugger::Internal::interruptProcess(int pID, int engineType, QString *erro
arg(pID).arg(Utils::winErrorMessage(GetLastError()));
break;
}
- // Try DebugBreakProcess if either Qt Creator is compiled 64 bit or
- // both Qt Creator and application are 32 bit.
-#ifdef Q_OS_WIN64
- // Qt-Creator compiled 64 bit
- // Windows must be 64 bit
- // CDB 64 bit: use DebugBreakProcess for 32 an 64 bit processes.
- // 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)
- Q_UNUSED(engineType)
+ enum DebugBreakApi {
+ UseDebugBreakApi,
+ UseWin64Interrupt,
+ UseWin32Interrupt
+ };
+/*
+ Windows 64 bit has a 32 bit subsystem (WOW64) which makes it possible to run a
+ 32 bit application inside a 64 bit environment.
+ When GDB is used DebugBreakProcess must be called from the same system (32/64 bit) running
+ the inferior. If CDB is used we could in theory break wow64 processes,
+ but the break is actually a wow64 breakpoint. CDB is configured to ignore these
+ breakpoints, because they also appear on module loading.
+ Therefore we need helper executables (win(32/64)interrupt.exe) on Windows 64 bit calling
+ DebugBreakProcess from the correct system.
+
+ DebugBreak matrix for windows
+
+ Api = UseDebugBreakApi
+ Win64 = UseWin64Interrupt
+ Win32 = UseWin32Interrupt
+ N/A = This configuration is not possible
+
+ | Windows 32bit | Windows 64bit
+ | QtCreator 32bit | QtCreator 32bit | QtCreator 64bit
+ | Inferior 32bit | Inferior 32bit | Inferior 64bit | Inferior 32bit | Inferior 64bit |
+----------|-----------------|-----------------|-----------------|-----------------|----------------|
+CDB 32bit | Api | Api | NA | Win32 | NA |
+ 64bit | NA | Win64 | Win64 | Api | Api |
+----------|-----------------|-----------------|-----------------|-----------------|----------------|
+GDB 32bit | Api | Api | NA | Win32 | NA |
+ 64bit | NA | Api | Win64 | Win32 | Api |
+----------|-----------------|-----------------|-----------------|-----------------|----------------|
+
+*/
+
+ DebugBreakApi breakApi = UseDebugBreakApi;
+#ifdef Q_OS_WIN64
+ if ((engineType == GdbEngineType && isWow64Process(inferior))
+ || (engineType == CdbEngineType && !engineExecutableIs64Bit)) {
+ breakApi = UseWin32Interrupt;
+ }
#else
- // Qt-Creator compiled 32 bit:
-
- bool useDebugBreakApi;
- if (isWow64Process(GetCurrentProcess())) {
- // Windows is 64 bit
- if (engineType == CdbEngineType) {
- // CDB 64 bit: If Qt-Creator is a WOW64 process (meaning a 32bit process
- // running in emulation), always use win64interrupt.exe for native
- // 64 bit processes and WOW64 processes. While DebugBreakProcess()
- // 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: 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.
- useDebugBreakApi = isWow64Process(inferior);
- }
- } else {
- // Windows is 32 bit
- // All processes are 32 bit, so DebugBreakProcess can be used in all cases.
- useDebugBreakApi = true;
+ if (isWow64Process(GetCurrentProcess())
+ && ((engineType == CdbEngineType && engineExecutableIs64Bit)
+ || (engineType == GdbEngineType && !isWow64Process(inferior)))) {
+ breakApi = UseWin64Interrupt;
}
#endif
- if (useDebugBreakApi) {
+ if (breakApi == UseDebugBreakApi) {
ok = DebugBreakProcess(inferior);
if (!ok)
*errorMessage = QLatin1String("DebugBreakProcess failed: ") + Utils::winErrorMessage(GetLastError());
} else {
- const QString executable = QCoreApplication::applicationDirPath() + QLatin1String("/win64interrupt.exe");
+ const QString executable = breakApi == UseWin32Interrupt
+ ? QCoreApplication::applicationDirPath() + QLatin1String("/win32interrupt.exe")
+ : QCoreApplication::applicationDirPath() + QLatin1String("/win64interrupt.exe");
+ if (!QFile::exists(executable)) {
+ *errorMessage = QString::fromLatin1("%1 does not exist. If you have built QtCreator "
+ "on your own ,checkout "
+ "http://qt.gitorious.org/qt-creator/binary-artifacts.").
+ arg(QDir::toNativeSeparators(executable));
+ break;
+ }
switch (QProcess::execute(executable, QStringList(QString::number(pID)))) {
case -2:
*errorMessage = QString::fromLatin1("Cannot start %1. Check src\\tools\\win64interrupt\\win64interrupt.c for more information.").
diff --git a/src/plugins/debugger/qml/baseqmldebuggerclient.h b/src/plugins/debugger/qml/baseqmldebuggerclient.h
index 9aa85a57f8..f356139e77 100644
--- a/src/plugins/debugger/qml/baseqmldebuggerclient.h
+++ b/src/plugins/debugger/qml/baseqmldebuggerclient.h
@@ -30,7 +30,7 @@
#ifndef BASEQMLDEBUGGERCLIENT_H
#define BASEQMLDEBUGGERCLIENT_H
-#include "debuggerengine.h"
+#include <debugger/debuggerengine.h>
#include <qmldebug/qmldebugclient.h>
namespace Debugger {
diff --git a/src/plugins/debugger/qml/qmladapter.cpp b/src/plugins/debugger/qml/qmladapter.cpp
index a5c5810c20..ef7a7434d3 100644
--- a/src/plugins/debugger/qml/qmladapter.cpp
+++ b/src/plugins/debugger/qml/qmladapter.cpp
@@ -29,7 +29,7 @@
#include "qmladapter.h"
-#include "debuggerstringutils.h"
+#include <debugger/debuggerstringutils.h>
#include "qmlengine.h"
#include "qmlv8debuggerclient.h"
#include "qscriptdebuggerclient.h"
diff --git a/src/plugins/debugger/qml/qmlcppengine.cpp b/src/plugins/debugger/qml/qmlcppengine.cpp
index 28179ba96b..00f79348b3 100644
--- a/src/plugins/debugger/qml/qmlcppengine.cpp
+++ b/src/plugins/debugger/qml/qmlcppengine.cpp
@@ -28,11 +28,11 @@
****************************************************************************/
#include "qmlcppengine.h"
-#include "debuggerruncontrolfactory.h"
-#include "debuggerstartparameters.h"
-#include "stackhandler.h"
#include "qmlengine.h"
-#include "watchhandler.h"
+#include <debugger/debuggerruncontrolfactory.h>
+#include <debugger/debuggerstartparameters.h>
+#include <debugger/stackhandler.h>
+#include <debugger/watchhandler.h>
#include <utils/qtcassert.h>
#include <texteditor/itexteditor.h>
@@ -47,8 +47,6 @@ enum { debug = 0 };
#define EDEBUG(s) do { if (debug) qDebug() << s; } while (0)
-const int ConnectionWaitTimeMs = 5000;
-
DebuggerEngine *createQmlCppEngine(const DebuggerStartParameters &sp,
QString *errorMessage)
{
@@ -699,9 +697,9 @@ void QmlCppEngine::slaveEngineStateChanged
break;
}
case InferiorShutdownOk: {
- if (state() == InferiorShutdownRequested)
+ if (state() == InferiorShutdownRequested) {
notifyInferiorShutdownOk();
- else {
+ } else {
// we got InferiorExitOk before, but ignored it ...
notifyInferiorExited();
}
diff --git a/src/plugins/debugger/qml/qmlcppengine.h b/src/plugins/debugger/qml/qmlcppengine.h
index c0a0226782..761194f74d 100644
--- a/src/plugins/debugger/qml/qmlcppengine.h
+++ b/src/plugins/debugger/qml/qmlcppengine.h
@@ -30,7 +30,7 @@
#ifndef QMLCPPENGINE_H
#define QMLCPPENGINE_H
-#include "debuggerengine.h"
+#include <debugger/debuggerengine.h>
namespace Debugger {
namespace Internal {
diff --git a/src/plugins/debugger/qml/qmlengine.cpp b/src/plugins/debugger/qml/qmlengine.cpp
index 0e07172d0f..7c33d83f59 100644
--- a/src/plugins/debugger/qml/qmlengine.cpp
+++ b/src/plugins/debugger/qml/qmlengine.cpp
@@ -31,21 +31,21 @@
#include "baseqmldebuggerclient.h"
#include "qmlinspectoragent.h"
-#include "debuggerstartparameters.h"
-#include "debuggeractions.h"
-#include "debuggercore.h"
-#include "debuggerinternalconstants.h"
-#include "debuggermainwindow.h"
-#include "debuggerrunner.h"
-#include "debuggerstringutils.h"
-#include "debuggertooltipmanager.h"
-#include "localsandexpressionswindow.h"
-#include "watchwindow.h"
-
-#include "breakhandler.h"
-#include "stackhandler.h"
-#include "watchhandler.h"
-#include "sourcefileshandler.h"
+#include <debugger/debuggerstartparameters.h>
+#include <debugger/debuggeractions.h>
+#include <debugger/debuggercore.h>
+#include <debugger/debuggerinternalconstants.h>
+#include <debugger/debuggermainwindow.h>
+#include <debugger/debuggerrunner.h>
+#include <debugger/debuggerstringutils.h>
+#include <debugger/debuggertooltipmanager.h>
+#include <debugger/localsandexpressionswindow.h>
+#include <debugger/watchwindow.h>
+
+#include <debugger/breakhandler.h>
+#include <debugger/stackhandler.h>
+#include <debugger/watchhandler.h>
+#include <debugger/sourcefileshandler.h>
#include <qmljseditor/qmljseditorconstants.h>
#include <qmljs/parser/qmljsast_p.h>
#include <qmljs/qmljsmodelmanagerinterface.h>
@@ -53,7 +53,7 @@
#include <utils/qtcassert.h>
-#include <texteditor/itexteditor.h>
+#include <texteditor/basetextdocument.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/helpmanager.h>
#include <coreplugin/icore.h>
@@ -292,7 +292,7 @@ QmlEngine::QmlEngine(const DebuggerStartParameters &startParameters, DebuggerEng
connect(&m_applicationLauncher,
- SIGNAL(processExited(int)),
+ SIGNAL(processExited(int, QProcess::ExitStatus)),
SLOT(disconnected()));
connect(&m_applicationLauncher,
SIGNAL(appendMessage(QString,Utils::OutputFormat)),
@@ -342,7 +342,7 @@ QmlEngine::~QmlEngine()
if (textEditPtr)
editorsToClose << textEditPtr.data();
}
- Core::EditorManager::instance()->closeEditors(editorsToClose);
+ Core::EditorManager::closeEditors(editorsToClose);
}
void QmlEngine::notifyInferiorSetupOk()
@@ -372,7 +372,7 @@ void QmlEngine::connectionEstablished()
if (!watchHandler()->watcherNames().isEmpty())
synchronizeWatchers();
- connect(watchersModel(),SIGNAL(layoutChanged()),this,SLOT(synchronizeWatchers()));
+ connect(watchModel(),SIGNAL(layoutChanged()),this,SLOT(synchronizeWatchers()));
if (state() == EngineRunRequested)
notifyEngineRunAndInferiorRunOk();
@@ -479,8 +479,7 @@ void QmlEngine::errorMessageBoxFinished(int result)
break;
}
case QMessageBox::Help: {
- Core::HelpManager *helpManager = Core::HelpManager::instance();
- helpManager->handleHelpRequest(QLatin1String("qthelp://org.qt-project.qtcreator/doc/creator-debugging-qml.html"));
+ Core::HelpManager::handleHelpRequest(QLatin1String("qthelp://org.qt-project.qtcreator/doc/creator-debugging-qml.html"));
// fall through
}
default:
@@ -534,28 +533,25 @@ void QmlEngine::gotoLocation(const Location &location)
if (QUrl(fileName).isLocalFile()) {
// internal file from source files -> show generated .js
QTC_ASSERT(m_sourceDocuments.contains(fileName), return);
- Core::IEditor *editor = 0;
- Core::EditorManager *editorManager = Core::EditorManager::instance();
QString titlePattern = tr("JS Source for %1").arg(fileName);
- //Check if there are open editors with the same title
- QList<Core::IEditor *> editors = editorManager->openedEditors();
- foreach (Core::IEditor *ed, editors) {
- if (ed->displayName() == titlePattern) {
- editor = ed;
- break;
+ //Check if there are open documents with the same title
+ foreach (Core::IDocument *document, Core::EditorManager::documentModel()->openedDocuments()) {
+ if (document->displayName() == titlePattern) {
+ Core::EditorManager::activateEditorForDocument(document);
+ return;
}
}
- if (!editor) {
- editor = Core::EditorManager::openEditorWithContents(QmlJSEditor::Constants::C_QMLJSEDITOR_ID,
- &titlePattern);
- if (editor)
- editor->setProperty(Constants::OPENED_BY_DEBUGGER, true);
-
- updateEditor(editor, m_sourceDocuments.value(fileName));
+ Core::IEditor *editor = Core::EditorManager::openEditorWithContents(
+ QmlJSEditor::Constants::C_QMLJSEDITOR_ID, &titlePattern);
+ if (editor) {
+ editor->document()->setProperty(Constants::OPENED_BY_DEBUGGER, true);
+ QPlainTextEdit *plainTextEdit =
+ qobject_cast<QPlainTextEdit *>(editor->widget());
+ if (plainTextEdit)
+ plainTextEdit->setReadOnly(true);
+ updateDocument(editor->document(), m_sourceDocuments.value(fileName));
}
- Core::EditorManager::activateEditor(editor);
-
} else {
DebuggerEngine::gotoLocation(location);
}
@@ -563,7 +559,7 @@ void QmlEngine::gotoLocation(const Location &location)
void QmlEngine::closeConnection()
{
- disconnect(watchersModel(),SIGNAL(layoutChanged()),this,SLOT(synchronizeWatchers()));
+ disconnect(watchModel(),SIGNAL(layoutChanged()),this,SLOT(synchronizeWatchers()));
m_adapter.closeConnection();
}
@@ -600,7 +596,7 @@ void QmlEngine::startApplicationLauncher()
void QmlEngine::stopApplicationLauncher()
{
if (m_applicationLauncher.isRunning()) {
- disconnect(&m_applicationLauncher, SIGNAL(processExited(int)),
+ disconnect(&m_applicationLauncher, SIGNAL(processExited(int,QProcess::ExitStatus)),
this, SLOT(disconnected()));
m_applicationLauncher.stop();
}
@@ -1308,27 +1304,22 @@ void QmlEngine::updateScriptSource(const QString &fileName, int lineOffset, int
//update open editors
QString titlePattern = tr("JS Source for %1").arg(fileName);
//Check if there are open editors with the same title
- QList<Core::IEditor *> editors = Core::EditorManager::instance()->openedEditors();
- foreach (Core::IEditor *editor, editors) {
- if (editor->displayName() == titlePattern) {
- updateEditor(editor, document);
+ foreach (Core::IDocument *doc, Core::EditorManager::documentModel()->openedDocuments()) {
+ if (doc->displayName() == titlePattern) {
+ updateDocument(doc, document);
break;
}
}
}
-void QmlEngine::updateEditor(Core::IEditor *editor, const QTextDocument *document)
+void QmlEngine::updateDocument(Core::IDocument *document, const QTextDocument *textDocument)
{
- TextEditor::ITextEditor *textEditor = qobject_cast<TextEditor::ITextEditor*>(editor);
- if (!textEditor)
+ TextEditor::BaseTextDocument *baseTextDocument
+ = qobject_cast<TextEditor::BaseTextDocument *>(document);
+ if (!baseTextDocument)
return;
- QPlainTextEdit *plainTextEdit =
- qobject_cast<QPlainTextEdit *>(editor->widget());
- if (!plainTextEdit)
- return;
- plainTextEdit->setPlainText(document->toPlainText());
- plainTextEdit->setReadOnly(true);
+ baseTextDocument->document()->setPlainText(textDocument->toPlainText());
}
bool QmlEngine::canEvaluateScript(const QString &script)
diff --git a/src/plugins/debugger/qml/qmlengine.h b/src/plugins/debugger/qml/qmlengine.h
index 0c8ef50b47..d9b5cd0b84 100644
--- a/src/plugins/debugger/qml/qmlengine.h
+++ b/src/plugins/debugger/qml/qmlengine.h
@@ -30,10 +30,10 @@
#ifndef QMLENGINE_H
#define QMLENGINE_H
-#include "debuggerengine.h"
#include "interactiveinterpreter.h"
#include "qmladapter.h"
#include "qmlinspectoradapter.h"
+#include <debugger/debuggerengine.h>
#include <projectexplorer/applicationlauncher.h>
#include <qmldebug/qdebugmessageclient.h>
@@ -43,7 +43,7 @@
#include <QTextDocument>
namespace Core {
-class IEditor;
+class IDocument;
}
namespace Debugger {
@@ -181,7 +181,7 @@ private:
const QString &oldBasePath, const QString &newBasePath) const;
QString qmlImportPath() const;
- void updateEditor(Core::IEditor *editor, const QTextDocument *document);
+ void updateDocument(Core::IDocument *document, const QTextDocument *textDocument);
bool canEvaluateScript(const QString &script);
bool adjustBreakpointLineAndColumn(const QString &filePath, quint32 *line,
quint32 *column, bool *valid);
diff --git a/src/plugins/debugger/qml/qmlinspectoradapter.cpp b/src/plugins/debugger/qml/qmlinspectoradapter.cpp
index 20d9219b6a..57ddb45cb0 100644
--- a/src/plugins/debugger/qml/qmlinspectoradapter.cpp
+++ b/src/plugins/debugger/qml/qmlinspectoradapter.cpp
@@ -29,13 +29,13 @@
#include "qmlinspectoradapter.h"
-#include "debuggeractions.h"
-#include "debuggercore.h"
-#include "debuggerstringutils.h"
#include "qmladapter.h"
-#include "debuggerengine.h"
#include "qmlinspectoragent.h"
#include "qmllivetextpreview.h"
+#include <debugger/debuggeractions.h>
+#include <debugger/debuggercore.h>
+#include <debugger/debuggerstringutils.h>
+#include <debugger/debuggerengine.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/icore.h>
@@ -298,7 +298,7 @@ void QmlInspectorAdapter::createPreviewForEditor(Core::IEditor *newEditor)
!= QmlJSEditor::Constants::C_QMLJSEDITOR_ID)
return;
- QString filename = newEditor->document()->fileName();
+ QString filename = newEditor->document()->filePath();
QmlJS::ModelManagerInterface *modelManager =
QmlJS::ModelManagerInterface::instance();
if (modelManager) {
@@ -330,7 +330,7 @@ void QmlInspectorAdapter::createPreviewForEditor(Core::IEditor *newEditor)
connect(preview, SIGNAL(reloadRequest()),
this, SLOT(onReload()));
- m_textPreviews.insert(newEditor->document()->fileName(), preview);
+ m_textPreviews.insert(newEditor->document()->filePath(), preview);
preview->associateEditor(newEditor);
preview->updateDebugIds();
}
@@ -340,7 +340,7 @@ void QmlInspectorAdapter::createPreviewForEditor(Core::IEditor *newEditor)
void QmlInspectorAdapter::removePreviewForEditor(Core::IEditor *editor)
{
if (QmlLiveTextPreview *preview
- = m_textPreviews.value(editor->document()->fileName())) {
+ = m_textPreviews.value(editor->document()->filePath())) {
preview->unassociateEditor(editor);
}
}
@@ -353,9 +353,8 @@ void QmlInspectorAdapter::updatePendingPreviewDocuments(QmlJS::Document::Ptr doc
if (idx == -1)
return;
- Core::EditorManager *em = Core::EditorManager::instance();
QList<Core::IEditor *> editors
- = em->editorsForFileName(doc->fileName());
+ = Core::EditorManager::documentModel()->editorsForFilePath(doc->fileName());
if (editors.isEmpty())
return;
@@ -365,7 +364,7 @@ void QmlInspectorAdapter::updatePendingPreviewDocuments(QmlJS::Document::Ptr doc
Core::IEditor *editor = editors.takeFirst();
createPreviewForEditor(editor);
QmlLiveTextPreview *preview
- = m_textPreviews.value(editor->document()->fileName());
+ = m_textPreviews.value(editor->document()->filePath());
foreach (Core::IEditor *editor, editors)
preview->associateEditor(editor);
}
@@ -439,7 +438,6 @@ void QmlInspectorAdapter::setActiveEngineClient(BaseEngineDebugClient *client)
void QmlInspectorAdapter::initializePreviews()
{
- Core::EditorManager *em = Core::EditorManager::instance();
QmlJS::ModelManagerInterface *modelManager
= QmlJS::ModelManagerInterface::instance();
if (modelManager) {
@@ -447,6 +445,7 @@ void QmlInspectorAdapter::initializePreviews()
if (!m_listeningToEditorManager) {
m_listeningToEditorManager = true;
+ QObject *em = Core::EditorManager::instance();
connect(em, SIGNAL(editorAboutToClose(Core::IEditor*)),
this, SLOT(removePreviewForEditor(Core::IEditor*)));
connect(em, SIGNAL(editorOpened(Core::IEditor*)),
@@ -457,8 +456,15 @@ void QmlInspectorAdapter::initializePreviews()
}
// initial update
- foreach (Core::IEditor *editor, em->openedEditors())
- createPreviewForEditor(editor);
+ Core::DocumentModel *documentModel = Core::EditorManager::documentModel();
+ foreach (Core::IDocument *document, documentModel->openedDocuments()) {
+ QList<Core::IEditor *> editors = documentModel->editorsForDocument(document);
+ createPreviewForEditor(editors.takeFirst());
+ QmlLiveTextPreview *preview
+ = m_textPreviews.value(document->filePath());
+ foreach (Core::IEditor *editor, editors)
+ preview->associateEditor(editor);
+ }
}
}
diff --git a/src/plugins/debugger/qml/qmlinspectoradapter.h b/src/plugins/debugger/qml/qmlinspectoradapter.h
index b94e37d542..1bdae26a76 100644
--- a/src/plugins/debugger/qml/qmlinspectoradapter.h
+++ b/src/plugins/debugger/qml/qmlinspectoradapter.h
@@ -30,7 +30,7 @@
#ifndef QMLINSPECTORADAPTER_H
#define QMLINSPECTORADAPTER_H
-#include "debuggerconstants.h"
+#include <debugger/debuggerconstants.h>
#include <coreplugin/icontext.h>
#include <qmldebug/qmldebugclient.h>
diff --git a/src/plugins/debugger/qml/qmlinspectoragent.cpp b/src/plugins/debugger/qml/qmlinspectoragent.cpp
index 8a65a59ab0..68974bf9d4 100644
--- a/src/plugins/debugger/qml/qmlinspectoragent.cpp
+++ b/src/plugins/debugger/qml/qmlinspectoragent.cpp
@@ -29,11 +29,11 @@
#include "qmlinspectoragent.h"
-#include "debuggeractions.h"
-#include "debuggercore.h"
-#include "debuggerengine.h"
-#include "debuggerstringutils.h"
-#include "watchhandler.h"
+#include <debugger/debuggeractions.h>
+#include <debugger/debuggercore.h>
+#include <debugger/debuggerengine.h>
+#include <debugger/debuggerstringutils.h>
+#include <debugger/watchhandler.h>
#include <qmldebug/qmldebugconstants.h>
#include <utils/qtcassert.h>
diff --git a/src/plugins/debugger/qml/qmlv8debuggerclient.cpp b/src/plugins/debugger/qml/qmlv8debuggerclient.cpp
index 9a3677d61a..916beae49e 100644
--- a/src/plugins/debugger/qml/qmlv8debuggerclient.cpp
+++ b/src/plugins/debugger/qml/qmlv8debuggerclient.cpp
@@ -29,14 +29,14 @@
#include "qmlv8debuggerclient.h"
#include "qmlv8debuggerclientconstants.h"
-#include "debuggerstringutils.h"
-
-#include "watchhandler.h"
-#include "breakhandler.h"
#include "qmlengine.h"
-#include "stackhandler.h"
-#include "debuggercore.h"
-#include "debuggeractions.h"
+
+#include <debugger/debuggerstringutils.h>
+#include <debugger/watchhandler.h>
+#include <debugger/breakhandler.h>
+#include <debugger/stackhandler.h>
+#include <debugger/debuggercore.h>
+#include <debugger/debuggeractions.h>
#include <utils/qtcassert.h>
#include <texteditor/basetexteditor.h>
@@ -254,13 +254,14 @@ void QmlV8DebuggerClientPrivate::evaluate(const QString expr, bool global,
args.setProperty(_(DISABLE_BREAK), QScriptValue(disableBreak));
if (addContext) {
- QAbstractItemModel *localsModel = engine->localsModel();
- int rowCount = localsModel->rowCount();
+ WatchHandler *watchHandler = engine->watchHandler();
+ QAbstractItemModel *watchModel = watchHandler->model();
+ int rowCount = watchModel->rowCount();
QScriptValue ctxtList = parser.call(QScriptValue(), QScriptValueList() << _(ARRAY ));
while (rowCount) {
- QModelIndex index = localsModel->index(--rowCount, 0);
- const WatchData *data = engine->watchHandler()->watchData(index);
+ QModelIndex index = watchModel->index(--rowCount, 0);
+ const WatchData *data = watchHandler->watchData(index);
QScriptValue ctxt = parser.call(QScriptValue(), QScriptValueList() << QScriptValue(_(OBJECT)));
ctxt.setProperty(_(NAME), QScriptValue(data->name));
ctxt.setProperty(_(HANDLE), QScriptValue(int(data->id)));
@@ -1904,7 +1905,7 @@ void QmlV8DebuggerClient::updateBreakpoints(const QVariant &bodyVal)
const QVariantList actualLocations = breakpointData.value(_("actual_locations")).toList();
foreach (const QVariant &location, actualLocations) {
const QVariantMap locationData = location.toMap();
- br.lineNumber = locationData.value(_("line")).toInt() + 1;;
+ br.lineNumber = locationData.value(_("line")).toInt() + 1;
br.enabled = breakpointData.value(_("active")).toBool();
br.hitCount = breakpointData.value(_("hit_count")).toInt();
br.ignoreCount = breakpointData.value(_("ignoreCount")).toInt();
@@ -1998,50 +1999,47 @@ void QmlV8DebuggerClient::highlightExceptionCode(int lineNumber,
const QString &filePath,
const QString &errorMessage)
{
- EditorManager *editorManager = EditorManager::instance();
- QList<IEditor *> openedEditors = editorManager->openedEditors();
+ QList<IEditor *> editors = EditorManager::documentModel()->editorsForFilePath(filePath);
// set up the format for the errors
QTextCharFormat errorFormat;
errorFormat.setUnderlineStyle(QTextCharFormat::WaveUnderline);
errorFormat.setUnderlineColor(Qt::red);
- foreach (IEditor *editor, openedEditors) {
- if (editor->document()->fileName() == filePath) {
- TextEditor::BaseTextEditorWidget *ed = qobject_cast<TextEditor::BaseTextEditorWidget *>(editor->widget());
- if (!ed)
- continue;
+ foreach (IEditor *editor, editors) {
+ TextEditor::BaseTextEditorWidget *ed = qobject_cast<TextEditor::BaseTextEditorWidget *>(editor->widget());
+ if (!ed)
+ continue;
- QList<QTextEdit::ExtraSelection> selections;
- QTextEdit::ExtraSelection sel;
- sel.format = errorFormat;
- QTextCursor c(ed->document()->findBlockByNumber(lineNumber - 1));
- const QString text = c.block().text();
- for (int i = 0; i < text.size(); ++i) {
- if (! text.at(i).isSpace()) {
- c.setPosition(c.position() + i);
- break;
- }
+ QList<QTextEdit::ExtraSelection> selections;
+ QTextEdit::ExtraSelection sel;
+ sel.format = errorFormat;
+ QTextCursor c(ed->document()->findBlockByNumber(lineNumber - 1));
+ const QString text = c.block().text();
+ for (int i = 0; i < text.size(); ++i) {
+ if (! text.at(i).isSpace()) {
+ c.setPosition(c.position() + i);
+ break;
}
- c.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
- sel.cursor = c;
+ }
+ c.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
+ sel.cursor = c;
- sel.format.setToolTip(errorMessage);
+ sel.format.setToolTip(errorMessage);
- selections.append(sel);
- ed->setExtraSelections(TextEditor::BaseTextEditorWidget::DebuggerExceptionSelection, selections);
+ selections.append(sel);
+ ed->setExtraSelections(TextEditor::BaseTextEditorWidget::DebuggerExceptionSelection, selections);
- QString message = QString(_("%1: %2: %3")).arg(filePath).arg(lineNumber)
- .arg(errorMessage);
- d->engine->showMessage(message, ConsoleOutput);
- }
+ QString message = QString(_("%1: %2: %3")).arg(filePath).arg(lineNumber)
+ .arg(errorMessage);
+ d->engine->showMessage(message, ConsoleOutput);
}
}
void QmlV8DebuggerClient::clearExceptionSelection()
{
- EditorManager *editorManager = EditorManager::instance();
- QList<IEditor *> openedEditors = editorManager->openedEditors();
+ DocumentModel *documentModel = EditorManager::documentModel();
+ QList<IEditor *> openedEditors = documentModel->editorsForDocuments(documentModel->openedDocuments());
QList<QTextEdit::ExtraSelection> selections;
foreach (IEditor *editor, openedEditors) {
diff --git a/src/plugins/debugger/qml/qscriptdebuggerclient.cpp b/src/plugins/debugger/qml/qscriptdebuggerclient.cpp
index 2910f895f3..e01d0e4f9c 100644
--- a/src/plugins/debugger/qml/qscriptdebuggerclient.cpp
+++ b/src/plugins/debugger/qml/qscriptdebuggerclient.cpp
@@ -28,12 +28,12 @@
****************************************************************************/
#include "qscriptdebuggerclient.h"
-#include "watchhandler.h"
-#include "breakhandler.h"
#include "qmlengine.h"
-#include "stackhandler.h"
-#include "debuggercore.h"
-#include "debuggerstringutils.h"
+#include <debugger/watchhandler.h>
+#include <debugger/breakhandler.h>
+#include <debugger/stackhandler.h>
+#include <debugger/debuggercore.h>
+#include <debugger/debuggerstringutils.h>
#include <QFileInfo>
#include <QMessageBox>
diff --git a/src/plugins/debugger/registerhandler.cpp b/src/plugins/debugger/registerhandler.cpp
index 4d342a928f..c33435fbfa 100644
--- a/src/plugins/debugger/registerhandler.cpp
+++ b/src/plugins/debugger/registerhandler.cpp
@@ -31,7 +31,7 @@
#include "watchdelegatewidgets.h"
#if USE_REGISTER_MODEL_TEST
-#include "modeltest.h"
+#include <modeltest.h>
#endif
#include <utils/qtcassert.h>
@@ -314,6 +314,7 @@ Register::Register(const QByteArray &name_)
RegisterHandler::RegisterHandler()
{
+ setObjectName(QLatin1String("RegisterModel"));
m_base = 16;
calculateWidth();
#if USE_REGISTER_MODEL_TEST
diff --git a/src/plugins/debugger/registerpostmortemaction.cpp b/src/plugins/debugger/registerpostmortemaction.cpp
index 9e00b42c99..d7edfa3220 100644
--- a/src/plugins/debugger/registerpostmortemaction.cpp
+++ b/src/plugins/debugger/registerpostmortemaction.cpp
@@ -33,7 +33,7 @@
#include "registerpostmortemaction.h"
-#include "registryaccess.h"
+#include <registryaccess.h>
#include <QCoreApplication>
#include <QDir>
diff --git a/src/plugins/debugger/registerpostmortemaction.h b/src/plugins/debugger/registerpostmortemaction.h
index 8fd374aa20..ac06ec8b7e 100644
--- a/src/plugins/debugger/registerpostmortemaction.h
+++ b/src/plugins/debugger/registerpostmortemaction.h
@@ -30,7 +30,7 @@
#ifndef REGISTERPOSTMORTEMACTION_H
#define REGISTERPOSTMORTEMACTION_H
-#include "utils/savedaction.h"
+#include <utils/savedaction.h>
namespace Debugger {
namespace Internal {
diff --git a/src/plugins/debugger/registerwindow.cpp b/src/plugins/debugger/registerwindow.cpp
index 6e53eaef57..a489f35a6b 100644
--- a/src/plugins/debugger/registerwindow.cpp
+++ b/src/plugins/debugger/registerwindow.cpp
@@ -230,9 +230,9 @@ void RegisterTreeView::contextMenuEvent(QContextMenuEvent *ev)
const QPoint position = ev->globalPos();
QAction *act = menu.exec(position);
- if (act == actReload)
+ if (act == actReload) {
engine->reloadRegisters();
- else if (act == actEditMemory) {
+ } else if (act == actEditMemory) {
const QString registerName = QString::fromLatin1(aRegister.name);
engine->openMemoryView(address, 0,
RegisterMemoryView::registerMarkup(address, registerName),
diff --git a/src/plugins/debugger/script/script.pri b/src/plugins/debugger/script/script.pri
deleted file mode 100644
index 48d9460aa5..0000000000
--- a/src/plugins/debugger/script/script.pri
+++ /dev/null
@@ -1,9 +0,0 @@
-HEADERS += \
- $$PWD/scriptengine.h \
-
-SOURCES += \
- $$PWD/scriptengine.cpp \
-
-FORMS +=
-
-RESOURCES +=
diff --git a/src/plugins/debugger/script/scriptengine.cpp b/src/plugins/debugger/script/scriptengine.cpp
deleted file mode 100644
index eb31b8f701..0000000000
--- a/src/plugins/debugger/script/scriptengine.cpp
+++ /dev/null
@@ -1,815 +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 "scriptengine.h"
-
-#include "debuggerstartparameters.h"
-#include "breakhandler.h"
-#include "debuggerconstants.h"
-#include "debuggercore.h"
-#include "debuggerdialogs.h"
-#include "debuggerstringutils.h"
-#include "moduleshandler.h"
-#include "registerhandler.h"
-#include "sourceutils.h"
-#include "stackhandler.h"
-#include "watchhandler.h"
-#include "watchutils.h"
-#include "debuggertooltipmanager.h"
-
-#include <utils/qtcassert.h>
-
-#include <texteditor/itexteditor.h>
-#include <coreplugin/idocument.h>
-#include <coreplugin/scriptmanager/scriptmanager.h>
-#include <coreplugin/icore.h>
-
-#include <QDateTime>
-#include <QDebug>
-#include <QDir>
-#include <QFileInfo>
-#include <QTimer>
-
-#include <QApplication>
-#include <QMessageBox>
-#include <QToolTip>
-
-#include <QScriptContext>
-#include <QScriptClassPropertyIterator>
-#include <QScriptContextInfo>
-#include <QScriptEngine>
-#include <QScriptEngineAgent>
-#include <QScriptValue>
-#include <QScriptValueIterator>
-
-
-namespace Debugger {
-namespace Internal {
-
-enum { debugScript = 0 };
-
-#define SDEBUG(s) do { if (debugScript) qDebug() << s; } while (0)
-#define XSDEBUG(s) qDebug() << s
-
-///////////////////////////////////////////////////////////////////////
-//
-// ScriptEngine
-//
-///////////////////////////////////////////////////////////////////////
-
-class ScriptAgent : public QScriptEngineAgent
-{
-public:
- ScriptAgent(ScriptEngine *debugger, QScriptEngine *script);
- ~ScriptAgent() {}
-
- void contextPop();
- void contextPush();
- void exceptionCatch(qint64 scriptId, const QScriptValue &exception);
- void exceptionThrow(qint64 scriptId, const QScriptValue & exception,
- bool hasHandler);
- void functionEntry(qint64 scriptId);
- void functionExit(qint64 scriptId, const QScriptValue &returnValue);
- void positionChange(qint64 scriptId, int lineNumber, int columnNumber);
- void scriptLoad(qint64 id, const QString &program, const QString &fileName,
- int baseLineNumber);
- void scriptUnload(qint64 id);
-
- void showMessage(const QString &msg);
-
-private:
- void maybeBreakNow(bool byFunction);
-
- ScriptEngine *q;
- int m_depth;
- int m_contextDepth;
-};
-
-ScriptAgent::ScriptAgent(ScriptEngine *debugger, QScriptEngine *script)
- : QScriptEngineAgent(script), q(debugger), m_depth(0), m_contextDepth(0)
-{}
-
-void ScriptAgent::showMessage(const QString &msg)
-{
- SDEBUG(msg);
- q->showMessage(msg, LogMisc);
-}
-
-void ScriptAgent::contextPop()
-{
- //showMessage(_("ContextPop: %1").arg(m_contextDepth));
- --m_contextDepth;
-}
-
-void ScriptAgent::contextPush()
-{
- ++m_contextDepth;
- //showMessage(_("ContextPush: %1 ").arg(m_contextDepth));
-}
-
-void ScriptAgent::exceptionCatch(qint64 scriptId, const QScriptValue & exception)
-{
- Q_UNUSED(scriptId)
- Q_UNUSED(exception)
- showMessage(_("An exception was caught on %1: '%2'").
- arg(scriptId).arg(exception.toString()));
-}
-
-void ScriptAgent::exceptionThrow(qint64 scriptId, const QScriptValue &exception,
- bool hasHandler)
-{
- Q_UNUSED(scriptId)
- Q_UNUSED(exception)
- Q_UNUSED(hasHandler)
- showMessage(_("An exception occurred on %1: '%2'").
- arg(scriptId).arg(exception.toString()));
-}
-
-void ScriptAgent::functionEntry(qint64 scriptId)
-{
- Q_UNUSED(scriptId)
- ++m_depth;
- //showMessage(_("Function entry occurred on %1, depth: %2").arg(scriptId));
- q->checkForBreakCondition(true);
-}
-
-void ScriptAgent::functionExit(qint64 scriptId, const QScriptValue &returnValue)
-{
- Q_UNUSED(scriptId)
- Q_UNUSED(returnValue)
- --m_depth;
- //showMessage(_("Function exit occurred on %1: '%2'").
- // arg(scriptId).arg(returnValue.toString()));
-}
-
-void ScriptAgent::positionChange(qint64 scriptId, int lineNumber, int columnNumber)
-{
- Q_UNUSED(scriptId)
- Q_UNUSED(lineNumber)
- Q_UNUSED(columnNumber)
- //showMessage(_("Position: %1").arg(lineNumber));
- q->checkForBreakCondition(false);
-}
-
-void ScriptAgent::scriptLoad(qint64 scriptId, const QString &program,
- const QString &fileName, int baseLineNumber)
-{
- Q_UNUSED(scriptId)
- Q_UNUSED(program)
- Q_UNUSED(fileName)
- Q_UNUSED(baseLineNumber)
- showMessage(_("Loaded: %1 id: %2").arg(fileName).arg(scriptId));
-}
-
-void ScriptAgent::scriptUnload(qint64 scriptId)
-{
- Q_UNUSED(scriptId)
- showMessage(_("Unload script id %1 ").arg(scriptId));
-}
-
-
-///////////////////////////////////////////////////////////////////////
-//
-// ScriptEngine
-//
-///////////////////////////////////////////////////////////////////////
-
-ScriptEngine::ScriptEngine(const DebuggerStartParameters &startParameters)
- : DebuggerEngine(startParameters)
-{
- setObjectName(QLatin1String("ScriptEngine"));
-}
-
-ScriptEngine::~ScriptEngine()
-{
-}
-
-void ScriptEngine::executeDebuggerCommand(const QString &command, DebuggerLanguages languages)
-{
- Q_UNUSED(command)
- Q_UNUSED(languages)
- XSDEBUG("FIXME: ScriptEngine::executeDebuggerCommand()");
-}
-
-void ScriptEngine::shutdownInferior()
-{
- QTC_ASSERT(state() == InferiorShutdownRequested, qDebug() << state());
- SDEBUG("ScriptEngine::shutdownInferior()");
- m_scriptEngine->setAgent(0);
- //m_scriptAgent.reset(0);
- m_stopped = false;
- m_stopOnNextLine = false;
- if (m_scriptEngine->isEvaluating())
- m_scriptEngine->abortEvaluation();
- notifyInferiorShutdownOk();
-}
-
-void ScriptEngine::shutdownEngine()
-{
- QTC_ASSERT(state() == EngineShutdownRequested, qDebug() << state());
- m_scriptEngine->setAgent(0);
- notifyEngineShutdownOk();
-}
-
-void ScriptEngine::setupEngine()
-{
- QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state());
- showMessage(_("STARTING SCRIPT DEBUGGER"), LogMisc);
- if (m_scriptEngine.isNull())
- m_scriptEngine = Core::ICore::scriptManager()->scriptEngine();
- QTC_CHECK(!m_scriptAgent);
- m_scriptAgent.reset(new ScriptAgent(this, m_scriptEngine.data()));
- m_scriptEngine->setAgent(m_scriptAgent.data());
- //m_scriptEngine->setAgent(new ScriptAgent(this, m_scriptEngine.data()));
- /* Keep the gui alive (have the engine call processEvents() while the script
- * is run in the foreground). */
- m_scriptEngine->setProcessEventsInterval(1 /*ms*/);
-
- m_stopped = false;
- m_stopOnNextLine = false;
- m_scriptEngine->abortEvaluation();
-
- notifyEngineSetupOk();
-}
-
-void ScriptEngine::setupInferior()
-{
- QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
- m_scriptFileName = QFileInfo(startParameters().executable).absoluteFilePath();
- showMessage(_("SCRIPT FILE: ") + m_scriptFileName);
- QFile scriptFile(m_scriptFileName);
- if (!scriptFile.open(QIODevice::ReadOnly|QIODevice::Text)) {
- showMessageBox(QMessageBox::Critical, tr("Error:"),
- _("Cannot open script file %1:\n%2").
- arg(m_scriptFileName, scriptFile.errorString()));
- notifyInferiorSetupFailed();
- return;
- }
- QTextStream stream(&scriptFile);
- m_scriptContents = stream.readAll();
- scriptFile.close();
- attemptBreakpointSynchronization();
- notifyInferiorSetupOk();
-}
-
-void ScriptEngine::continueInferior()
-{
- QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
- notifyInferiorRunRequested();
- SDEBUG("ScriptEngine::continueInferior()");
- m_stopped = false;
- m_stopOnNextLine = false;
-}
-
-static const char *qtExtensionsC[] = {
- "qt.core", "qt.gui", "qt.xml", "qt.svg", "qt.network",
- "qt.sql", "qt.opengl", "qt.webkit", "qt.xmlpatterns", "qt.uitools"
-};
-
-void ScriptEngine::importExtensions()
-{
- SDEBUG("ScriptEngine::importExtensions()");
- QStringList extensions;
- const int extCount = sizeof(qtExtensionsC)/sizeof(const char *);
- for (int e = 0; e < extCount; e++)
- extensions.append(QLatin1String(qtExtensionsC[e]));
- if (m_scriptEngine->importedExtensions().contains(extensions.front()))
- return; // true;
- QDir dir(QLatin1String("/home/apoenitz/dev/qtscriptgenerator"));
- if (!dir.cd(QLatin1String("plugins"))) {
- fprintf(stderr, "plugins folder does not exist -- did you build the bindings?\n");
- return; // false;
- }
- QStringList paths = qApp->libraryPaths();
- paths << dir.absolutePath();
- qApp->setLibraryPaths(paths);
- QStringList failExtensions;
- foreach (const QString &ext, extensions) {
- QScriptValue ret = m_scriptEngine->importExtension(ext);
- if (ret.isError())
- failExtensions.append(ext);
- }
- if (!failExtensions.isEmpty()) {
- if (failExtensions.size() == extensions.size()) {
- qWarning("Failed to import Qt bindings!\n"
- "Plugins directory searched: %s/script\n"
- "Make sure that the bindings have been built, "
- "and that this executable and the plugins are "
- "using compatible Qt libraries.", qPrintable(dir.absolutePath()));
- } else {
- qWarning("Failed to import some Qt bindings: %s\n"
- "Plugins directory searched: %s/script\n"
- "Make sure that the bindings have been built, "
- "and that this executable and the plugins are "
- "using compatible Qt libraries.",
- qPrintable(failExtensions.join(QLatin1String(", "))),
- qPrintable(dir.absolutePath()));
- }
- }
- return; // failExtensions.isEmpty();
-}
-
-void ScriptEngine::runEngine()
-{
- QTC_ASSERT(state() == EngineRunRequested, qDebug() << state());
- notifyEngineRunAndInferiorRunOk();
- showStatusMessage(tr("Running requested..."), 5000);
- showMessage(QLatin1String("Running: ") + m_scriptFileName, LogMisc);
- importExtensions();
- const QScriptValue result =
- m_scriptEngine->evaluate(m_scriptContents, m_scriptFileName);
- QString msg;
- if (m_scriptEngine->hasUncaughtException()) {
- msg = _("An exception occurred during execution at line: %1\n%2\n")
- .arg(m_scriptEngine->uncaughtExceptionLineNumber())
- .arg(m_scriptEngine->uncaughtException().toString());
- msg += m_scriptEngine->uncaughtExceptionBacktrace()
- .join(QString(QLatin1Char('\n')));
- } else {
- msg = _("Evaluation returns '%1'").arg(result.toString());
- }
- showMessage(msg, LogMisc);
- showMessage(_("This was the outermost function."));
- notifyInferiorExited();
-}
-
-void ScriptEngine::interruptInferior()
-{
- m_stopOnNextLine = true;
- XSDEBUG("ScriptEngine::interruptInferior()");
-}
-
-void ScriptEngine::executeStep()
-{
- QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
- notifyInferiorRunRequested();
- //SDEBUG("ScriptEngine::stepExec()");
- m_stopped = false;
- m_stopOnNextLine = true;
-}
-
-void ScriptEngine::executeStepI()
-{
- QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
- notifyInferiorRunRequested();
- //SDEBUG("ScriptEngine::stepIExec()");
- m_stopped = false;
- m_stopOnNextLine = true;
-}
-
-void ScriptEngine::executeStepOut()
-{
- QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
- notifyInferiorRunRequested();
- //SDEBUG("ScriptEngine::stepOutExec()");
- m_stopped = false;
- m_stopOnNextLine = true;
-}
-
-void ScriptEngine::executeNext()
-{
- QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
- notifyInferiorRunRequested();
- //SDEBUG("ScriptEngine::nextExec()");
- m_stopped = false;
- m_stopOnNextLine = true;
-}
-
-void ScriptEngine::executeNextI()
-{
- QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
- notifyInferiorRunRequested();
- //SDEBUG("ScriptEngine::nextIExec()");
- m_stopped = false;
- m_stopOnNextLine = true;
-}
-
-void ScriptEngine::executeRunToLine(const ContextData &data)
-{
- QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
- notifyInferiorRunRequested();
- Q_UNUSED(data)
- SDEBUG("FIXME: ScriptEngine::runToLineExec()");
-}
-
-void ScriptEngine::executeRunToFunction(const QString &functionName)
-{
- QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
- notifyInferiorRunRequested();
- Q_UNUSED(functionName)
- XSDEBUG("FIXME: ScriptEngine::runToFunctionExec()");
-}
-
-void ScriptEngine::executeJumpToLine(const ContextData &data)
-{
- QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
- notifyInferiorRunRequested();
- Q_UNUSED(data)
- XSDEBUG("FIXME: ScriptEngine::jumpToLineExec()");
-}
-
-void ScriptEngine::activateFrame(int index)
-{
- Q_UNUSED(index)
-}
-
-void ScriptEngine::selectThread(ThreadId threadId)
-{
- Q_UNUSED(threadId)
-}
-
-bool ScriptEngine::acceptsBreakpoint(BreakpointModelId id) const
-{
- const QString fileName = breakHandler()->fileName(id);
- return fileName.endsWith(QLatin1String(".js"));
-}
-
-void ScriptEngine::attemptBreakpointSynchronization()
-{
- QTC_ASSERT(false, /* FIXME */);
-/*
- BreakHandler *handler = breakHandler();
- bool updateNeeded = false;
- for (int index = 0; index != handler->size(); ++index) {
- BreakpointData *data = handler->at(index);
- if (data->pending) {
- data->pending = false; // FIXME
- updateNeeded = true;
- }
- if (data->bpNumber.isEmpty()) {
- data->bpNumber = QByteArray::number(index + 1);
- updateNeeded = true;
- }
- if (!data->fileName.isEmpty() && data->markerFileName().isEmpty()) {
- data->setMarkerFileName(data->fileName);
- data->setMarkerLineNumber(data->lineNumber);
- updateNeeded = true;
- }
- }
- if (updateNeeded)
- handler->updateMarkers();
-*/
-}
-
-void ScriptEngine::loadSymbols(const QString &moduleName)
-{
- Q_UNUSED(moduleName)
-}
-
-void ScriptEngine::loadAllSymbols()
-{
-}
-
-void ScriptEngine::reloadModules()
-{
-}
-
-void ScriptEngine::requestModuleSymbols(const QString & /*moduleName*/)
-{
-}
-
-
-//////////////////////////////////////////////////////////////////////
-//
-// Tooltip specific stuff
-//
-//////////////////////////////////////////////////////////////////////
-
-
-static WatchData m_toolTip;
-static QPoint m_toolTipPos;
-static QHash<QString, WatchData> m_toolTipCache;
-
-bool ScriptEngine::setToolTipExpression(const QPoint &mousePos,
- TextEditor::ITextEditor *editor, const DebuggerToolTipContext &ctx)
-{
- Q_UNUSED(mousePos)
- Q_UNUSED(editor)
-
- if (state() != InferiorStopOk) {
- //SDEBUG("SUPPRESSING DEBUGGER TOOLTIP, INFERIOR NOT STOPPED");
- return false;
- }
- // Check mime type and get expression (borrowing some C++ - functions)
- const QString javaScriptMimeType =
- QLatin1String("application/javascript");
- if (!editor->document() || editor->document()->mimeType() != javaScriptMimeType)
- return false;
-
- int line;
- int column;
- QString exp = cppExpressionAt(editor, ctx.position, &line, &column);
-
-/*
- if (m_toolTipCache.contains(exp)) {
- const WatchData & data = m_toolTipCache[exp];
- q->watchHandler()->removeChildren(data.iname);
- insertData(data);
- return;
- }
-*/
-
- QToolTip::hideText();
- if (exp.isEmpty() || exp.startsWith(QLatin1Char('#'))) {
- QToolTip::hideText();
- return false;
- }
-
- if (!hasLetterOrNumber(exp)) {
- QToolTip::showText(m_toolTipPos, tr("'%1' contains no identifier.").arg(exp));
- return false;
- }
-
- if (exp.startsWith(QLatin1Char('"')) && exp.endsWith(QLatin1Char('"'))) {
- QToolTip::showText(m_toolTipPos, tr("String literal %1.").arg(exp));
- return false;
- }
-
- if (exp.startsWith(QLatin1String("++")) || exp.startsWith(QLatin1String("--")))
- exp.remove(0, 2);
-
- if (exp.endsWith(QLatin1String("++")) || exp.endsWith(QLatin1String("--")))
- exp.remove(0, 2);
-
- if (exp.startsWith(QLatin1Char('<')) || exp.startsWith(QLatin1Char('[')))
- return false;
-
- if (hasSideEffects(exp)) {
- QToolTip::showText(m_toolTipPos,
- tr("Cowardly refusing to evaluate expression '%1' "
- "with potential side effects.").arg(exp));
- return false;
- }
-
-#if 0
- //if (m_manager->status() != InferiorStopOk)
- // return;
-
- // FIXME: 'exp' can contain illegal characters
- m_toolTip = WatchData();
- m_toolTip.exp = exp;
- m_toolTip.name = exp;
- m_toolTip.iname = tooltipIName;
- insertData(m_toolTip);
-#endif
- return false;
-}
-
-
-//////////////////////////////////////////////////////////////////////
-//
-// Watch specific stuff
-//
-//////////////////////////////////////////////////////////////////////
-
-void ScriptEngine::assignValueInDebugger(const Internal::WatchData *,
- const QString &expression, const QVariant &value)
-{
- SDEBUG("ASSIGNING: " << (expression + QLatin1Char('=') + value.toString()));
- m_scriptEngine->evaluate(expression + QLatin1Char('=') + value.toString());
- updateLocals();
-}
-
-bool ScriptEngine::checkForBreakCondition(bool byFunction)
-{
- // FIXME: Should that ever happen after setAgent(0) in shutdownInferior()?
- // In practice, it does, so chicken out.
- if (targetState() == DebuggerFinished)
- return false;
-
- const QScriptContext *context = m_scriptEngine->currentContext();
- const QScriptContextInfo info(context);
-
- // Update breakpoints
- const QString functionName = info.functionName();
- const QString fileName = info.fileName();
- const int lineNumber = byFunction
- ? info.functionStartLineNumber() : info.lineNumber();
- SDEBUG(Q_FUNC_INFO << byFunction << functionName << lineNumber << fileName);
- if (m_stopOnNextLine) {
- // Interrupt inferior
- m_stopOnNextLine = false;
- } else {
- if (byFunction && functionName.isEmpty())
- return false;
- BreakHandler *handler = breakHandler();
- BreakpointModelId id = byFunction ?
- handler->findBreakpointByFunction(functionName) :
- handler->findBreakpointByFileAndLine(fileName, lineNumber, false);
-
- // Skip disabled breakpoint.
- if (!handler->isEnabled(id))
- return false;
-
- BreakpointResponse br;
- // We just run into a breakpoint.
- //SDEBUG("RESOLVING BREAKPOINT AT " << fileName << lineNumber);
- br.lineNumber = lineNumber;
- br.fileName = fileName;
- br.functionName = functionName;
- handler->notifyBreakpointInsertOk(id);
- handler->setResponse(id, br);
- }
- notifyInferiorSpontaneousStop();
- SDEBUG("Stopped at " << lineNumber << fileName);
- showStatusMessage(tr("Stopped at %1:%2.").arg(fileName).arg(lineNumber), 5000);
- gotoLocation(Location(fileName, lineNumber));
- updateLocals();
- return true;
-}
-
-void ScriptEngine::updateLocals()
-{
- QScriptContext *context = m_scriptEngine->currentContext();
- SDEBUG(Q_FUNC_INFO);
-
- //
- // Build stack
- //
- QList<StackFrame> stackFrames;
- int i = 0;
- for (QScriptContext *c = context; c; c = c->parentContext(), ++i) {
- const QScriptContextInfo info(c);
- StackFrame frame;
- frame.level = i;
- frame.file = info.fileName();
- frame.function = info.functionName();
- frame.from = QString::number(info.functionStartLineNumber());
- frame.to = QString::number(info.functionEndLineNumber());
- frame.line = info.lineNumber();
- if (frame.function.isEmpty())
- frame.function = QLatin1String("<global scope>");
- //frame.address = ...;
- stackFrames.append(frame);
- }
- stackHandler()->setFrames(stackFrames);
-
- //
- // Build locals, deactivate agent meanwhile.
- //
- m_scriptEngine->setAgent(0);
-
- WatchData data;
- data.id = m_watchIdCounter++;
- m_watchIdToScriptValue.insert(data.id, context->activationObject());
- data.iname = "local";
- data.name = _(data.iname);
-
- updateSubItem(data);
- // FIXME: Use an extra thread. This here is evil.
- m_stopped = true;
- showStatusMessage(tr("Stopped."), 5000);
- while (m_stopped) {
- //SDEBUG("LOOPING");
- QApplication::processEvents();
- }
- // Clear any exceptions occurred during locals evaluation.
- m_scriptEngine->clearExceptions();
- m_scriptEngine->setAgent(m_scriptAgent.data());
- notifyInferiorRunOk();
-}
-
-void ScriptEngine::updateWatchData(const WatchData &data, const WatchUpdateFlags &flags)
-{
- Q_UNUSED(flags);
- updateSubItem(data);
-}
-
-static inline QString msgDebugInsert(const WatchData &d0, const QList<WatchData>& children)
-{
- QString rc;
- QTextStream str(&rc);
- str << "INSERTING " << d0.toString() << '\n';
- foreach (const WatchData &c, children)
- str << " " << c.toString() << '\n';
- return rc;
-}
-
-void ScriptEngine::updateSubItem(const WatchData &data0)
-{
- WatchData data = data0;
- QList<WatchData> children;
- //SDEBUG("\nUPDATE SUBITEM: " << data.toString() << data.scriptValue.toString());
- QTC_ASSERT(data.isValid(), return);
-
- const QScriptValue &ob = m_watchIdToScriptValue.value(data.id);
- if (data.isTypeNeeded() || data.isValueNeeded()) {
- if (ob.isArray()) {
- data.setType("Array", false);
- data.setValue(QString(QLatin1Char(' ')));
- } else if (ob.isBool()) {
- data.setType("Bool", false);
- data.setValue(ob.toBool() ? QLatin1String("true") : QLatin1String("false"));
- data.setHasChildren(false);
- } else if (ob.isDate()) {
- data.setType("Date", false);
- data.setValue(ob.toDateTime().toString());
- data.setHasChildren(false);
- } else if (ob.isError()) {
- data.setType("Error", false);
- data.setValue(QString(QLatin1Char(' ')));
- } else if (ob.isFunction()) {
- data.setType("Function", false);
- data.setValue(QString(QLatin1Char(' ')));
- } else if (ob.isNull()) {
- const QString nullValue = QLatin1String("<null>");
- data.setType("<null>", false);
- data.setValue(nullValue);
- } else if (ob.isNumber()) {
- data.setType("Number", false);
- data.setValue(QString::number(ob.toNumber()));
- data.setHasChildren(false);
- } else if (ob.isObject()) {
- data.setType("Object", false);
- data.setValue(QString(QLatin1Char(' ')));
- } else if (ob.isQMetaObject()) {
- data.setType("QMetaObject", false);
- data.setValue(QString(QLatin1Char(' ')));
- } else if (ob.isQObject()) {
- data.setType("QObject", false);
- data.setValue(QString(QLatin1Char(' ')));
- } else if (ob.isRegExp()) {
- data.setType("RegExp", false);
- data.setValue(ob.toRegExp().pattern());
- } else if (ob.isString()) {
- data.setType("String", false);
- data.setValue(ob.toString());
- } else if (ob.isVariant()) {
- data.setType("Variant", false);
- data.setValue(QString(QLatin1Char(' ')));
- } else if (ob.isUndefined()) {
- data.setType("<undefined>", false);
- data.setValue(QLatin1String("<unknown>"));
- data.setHasChildren(false);
- } else {
- const QString unknown = QLatin1String("<unknown>");
- data.setType("<unknown>", false);
- data.setValue(unknown);
- data.setHasChildren(false);
- }
- }
-
- if (data.isChildrenNeeded()) {
- QScriptValueIterator it(ob);
- while (it.hasNext()) {
- it.next();
- WatchData data1;
- data1.iname = data.iname + '.' + it.name().toLatin1();
- data1.exp = it.name().toLatin1();
- data1.name = it.name();
- data.id = m_watchIdCounter++;
- m_watchIdToScriptValue.insert(data.id, it.value());
- if (watchHandler()->isExpandedIName(data1.iname))
- data1.setChildrenNeeded();
- else
- data1.setChildrenUnneeded();
- children.push_back(data1);
- }
- data.setHasChildren(!children.isEmpty());
- data.setChildrenUnneeded();
- }
-
- if (data.isHasChildrenNeeded()) {
- QScriptValueIterator it(ob);
- data.setHasChildren(it.hasNext());
- }
-
- SDEBUG(msgDebugInsert(data, children));
- watchHandler()->insertIncompleteData(data);
- if (!children.isEmpty())
- watchHandler()->insertData(children);
-}
-
-DebuggerEngine *createScriptEngine(const DebuggerStartParameters &sp)
-{
- return new ScriptEngine(sp);
-}
-
-} // namespace Internal
-} // namespace Debugger
diff --git a/src/plugins/debugger/script/scriptengine.h b/src/plugins/debugger/script/scriptengine.h
deleted file mode 100644
index 1526a67568..0000000000
--- a/src/plugins/debugger/script/scriptengine.h
+++ /dev/null
@@ -1,129 +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 DEBUGGER_SCRIPTENGINE_H
-#define DEBUGGER_SCRIPTENGINE_H
-
-#include "debuggerengine.h"
-
-#include <QSharedPointer>
-#include <QHash>
-
-QT_BEGIN_NAMESPACE
-class QScriptEngine;
-class QScriptValue;
-QT_END_NAMESPACE
-
-namespace Debugger {
-namespace Internal {
-
-class ScriptAgent;
-class WatchData;
-
-/* A debugger engine for a QScriptEngine implemented using a QScriptEngineAgent.
- * listening on script events. The engine has a special execution model:
- * The script is executed in the foreground, while the debugger runs in
- * processEvents() triggered by QScriptEngine::setProcessEventsInterval().
- * Stopping is emulated by manually calling processEvents() from the debugger engine. */
-
-class ScriptEngine : public Debugger::DebuggerEngine
-{
- Q_OBJECT
-
-public:
- explicit ScriptEngine(const DebuggerStartParameters &startParameters);
- virtual ~ScriptEngine();
-
-private:
- // DebuggerEngine implementation
- void executeStep();
- void executeStepOut();
- void executeNext();
- void executeStepI();
- void executeNextI();
-
- bool setToolTipExpression(const QPoint &mousePos,
- TextEditor::ITextEditor *editor, const DebuggerToolTipContext &);
- void setupEngine();
- void setupInferior();
- void runEngine();
- void shutdownInferior();
- void shutdownEngine();
-
- void continueInferior();
- void interruptInferior();
-
- void executeRunToLine(const ContextData &data);
- void executeRunToFunction(const QString &functionName);
- void executeJumpToLine(const ContextData &data);
-
- void activateFrame(int index);
- void selectThread(ThreadId threadId);
-
- bool acceptsBreakpoint(BreakpointModelId id) const;
- void attemptBreakpointSynchronization();
-
- void assignValueInDebugger(const WatchData *w,
- const QString &expr, const QVariant &value);
- void executeDebuggerCommand(const QString &command, DebuggerLanguages languages);
-
- void loadSymbols(const QString &moduleName);
- void loadAllSymbols();
- void requestModuleSymbols(const QString &moduleName);
- void reloadModules();
- void reloadRegisters() {}
- void reloadSourceFiles() {}
- void reloadFullStack() {}
-
- bool checkForBreakCondition(bool byFunction);
- void updateWatchData(const WatchData &data, const WatchUpdateFlags &flags);
- void updateLocals();
- void updateSubItem(const WatchData &data);
- bool hasCapability(unsigned) const { return false; }
-
-private:
- friend class ScriptAgent;
-
- void importExtensions();
-
- QSharedPointer<QScriptEngine> m_scriptEngine;
- QString m_scriptContents;
- QString m_scriptFileName;
- QScopedPointer<ScriptAgent> m_scriptAgent;
- QHash<quint64,QScriptValue> m_watchIdToScriptValue;
- quint64 m_watchIdCounter;
-
- bool m_stopped;
- bool m_stopOnNextLine;
-};
-
-} // namespace Internal
-} // namespace Debugger
-
-#endif // DEBUGGER_SCRIPTENGINE_H
diff --git a/src/plugins/debugger/shared/cdbsymbolpathlisteditor.cpp b/src/plugins/debugger/shared/cdbsymbolpathlisteditor.cpp
index 617a7c2994..93e06d10b8 100644
--- a/src/plugins/debugger/shared/cdbsymbolpathlisteditor.cpp
+++ b/src/plugins/debugger/shared/cdbsymbolpathlisteditor.cpp
@@ -34,7 +34,7 @@
#include <utils/pathchooser.h>
#include <utils/checkablemessagebox.h>
-#include <symbolpathsdialog.h>
+#include "symbolpathsdialog.h"
#include <QCheckBox>
#include <QDir>
diff --git a/src/plugins/debugger/shared/shared.pri b/src/plugins/debugger/shared/shared.pri
index a0021f598b..d465345522 100644
--- a/src/plugins/debugger/shared/shared.pri
+++ b/src/plugins/debugger/shared/shared.pri
@@ -10,8 +10,6 @@ HEADERS += $$PWD/backtrace.h \
$$PWD/peutils.h \
shared/symbolpathsdialog.h
-INCLUDEPATH += $$PWD
-
win32-msvc* {
# For the Privilege manipulation functions in sharedlibraryinjector.cpp.
LIBS += -ladvapi32
diff --git a/src/plugins/debugger/shared/symbolpathsdialog.cpp b/src/plugins/debugger/shared/symbolpathsdialog.cpp
index 8d42050962..8510568996 100644
--- a/src/plugins/debugger/shared/symbolpathsdialog.cpp
+++ b/src/plugins/debugger/shared/symbolpathsdialog.cpp
@@ -29,7 +29,8 @@
#include "symbolpathsdialog.h"
#include "ui_symbolpathsdialog.h"
-#include "QMessageBox"
+
+#include <QMessageBox>
using namespace Debugger;
using namespace Internal;
diff --git a/src/plugins/debugger/sourceagent.cpp b/src/plugins/debugger/sourceagent.cpp
index 16132473fc..210528bf13 100644
--- a/src/plugins/debugger/sourceagent.cpp
+++ b/src/plugins/debugger/sourceagent.cpp
@@ -76,10 +76,7 @@ SourceAgentPrivate::SourceAgentPrivate()
SourceAgentPrivate::~SourceAgentPrivate()
{
- if (editor) {
- EditorManager *editorManager = EditorManager::instance();
- editorManager->closeEditors(QList<IEditor *>() << editor);
- }
+ EditorManager::closeEditor(editor);
editor = 0;
delete locationMark;
}
@@ -115,9 +112,9 @@ void SourceAgent::setContent(const QString &filePath, const QString &content)
d->editor = qobject_cast<ITextEditor *>(
EditorManager::openEditorWithContents(
CppEditor::Constants::CPPEDITOR_ID,
- &titlePattern, content));
+ &titlePattern, content.toUtf8()));
QTC_ASSERT(d->editor, return);
- d->editor->setProperty(Debugger::Constants::OPENED_BY_DEBUGGER, true);
+ d->editor->document()->setProperty(Debugger::Constants::OPENED_BY_DEBUGGER, true);
BaseTextEditorWidget *baseTextEdit =
qobject_cast<BaseTextEditorWidget *>(d->editor->widget());
diff --git a/src/plugins/debugger/sourcefileshandler.cpp b/src/plugins/debugger/sourcefileshandler.cpp
index 21b7047f88..e1d916e68c 100644
--- a/src/plugins/debugger/sourcefileshandler.cpp
+++ b/src/plugins/debugger/sourcefileshandler.cpp
@@ -39,7 +39,9 @@ namespace Internal {
SourceFilesHandler::SourceFilesHandler()
{
+ setObjectName(QLatin1String("SourceFilesModel"));
QSortFilterProxyModel *proxy = new QSortFilterProxyModel(this);
+ proxy->setObjectName(QLatin1String("SourceFilesProxyModel"));
proxy->setSourceModel(this);
m_proxyModel = proxy;
}
diff --git a/src/plugins/debugger/sourceutils.cpp b/src/plugins/debugger/sourceutils.cpp
index 12072d2197..ec3e72a2cd 100644
--- a/src/plugins/debugger/sourceutils.cpp
+++ b/src/plugins/debugger/sourceutils.cpp
@@ -318,7 +318,7 @@ bool isCppEditor(Core::IEditor *editor)
if (!document)
return false;
- return CppTools::ProjectFile::classify(document->fileName()) != CppTools::ProjectFile::Unclassified;
+ return CppTools::ProjectFile::classify(document->filePath()) != CppTools::ProjectFile::Unclassified;
}
// Return the Cpp expression, and, if desired, the function
@@ -359,7 +359,7 @@ QString cppExpressionAt(TextEditor::ITextEditor *editor, int pos,
if (const Core::IDocument *document= editor->document())
if (modelManager)
*function = AbstractEditorSupport::functionAt(modelManager,
- document->fileName(), *line, *column);
+ document->filePath(), *line, *column);
return expr;
}
@@ -368,7 +368,7 @@ QString cppExpressionAt(TextEditor::ITextEditor *editor, int pos,
// free debugger expression.
QString fixCppExpression(const QString &expIn)
{
- QString exp = expIn.trimmed();;
+ QString exp = expIn.trimmed();
// Extract the first identifier, everything else is considered
// too dangerous.
int pos1 = 0, pos2 = exp.size();
diff --git a/src/plugins/debugger/stackhandler.cpp b/src/plugins/debugger/stackhandler.cpp
index 138a6663c9..984ea555a9 100644
--- a/src/plugins/debugger/stackhandler.cpp
+++ b/src/plugins/debugger/stackhandler.cpp
@@ -57,6 +57,7 @@ StackHandler::StackHandler()
: m_positionIcon(QIcon(QLatin1String(":/debugger/images/location_16.png"))),
m_emptyIcon(QIcon(QLatin1String(":/debugger/images/debugger_empty_14.png")))
{
+ setObjectName(QLatin1String("StackModel"));
m_resetLocationScheduled = false;
m_contentsValid = false;
m_currentIndex = -1;
@@ -121,7 +122,7 @@ QVariant StackHandler::data(const QModelIndex &index, int role) const
? m_positionIcon : m_emptyIcon;
}
- if (role == Qt::ToolTipRole)
+ if (role == Qt::ToolTipRole && debuggerCore()->boolSetting(UseToolTipsInStackView))
return frame.toToolTip();
return QVariant();
diff --git a/src/plugins/debugger/stackwindow.cpp b/src/plugins/debugger/stackwindow.cpp
index fed2e8031f..35c3358f9a 100644
--- a/src/plugins/debugger/stackwindow.cpp
+++ b/src/plugins/debugger/stackwindow.cpp
@@ -175,6 +175,8 @@ void StackTreeView::contextMenuEvent(QContextMenuEvent *ev)
menu.addAction(debuggerCore()->action(UseAddressInStackView));
menu.addSeparator();
+ menu.addAction(debuggerCore()->action(UseToolTipsInStackView));
+ menu.addSeparator();
addBaseContextActions(&menu);
@@ -182,9 +184,9 @@ void StackTreeView::contextMenuEvent(QContextMenuEvent *ev)
if (!act)
return;
- if (act == actCopyContents)
+ if (act == actCopyContents) {
copyContentsToClipboard();
- else if (act == actShowMemory) {
+ } else if (act == actShowMemory) {
const QString title = tr("Memory at Frame #%1 (%2) 0x%3").
arg(row).arg(frame.function).arg(address, 0, 16);
QList<MemoryMarkup> ml;
diff --git a/src/plugins/debugger/threadshandler.cpp b/src/plugins/debugger/threadshandler.cpp
index 4f7522e71f..45504decd6 100644
--- a/src/plugins/debugger/threadshandler.cpp
+++ b/src/plugins/debugger/threadshandler.cpp
@@ -135,6 +135,7 @@ ThreadsHandler::ThreadsHandler()
m_emptyIcon(QLatin1String(":/debugger/images/debugger_empty_14.png"))
{
m_resetLocationScheduled = false;
+ setObjectName(QLatin1String("ThreadsModel"));
// m_proxyModel = new QSortFilterProxyModel(this);
// m_proxyModel->setSourceModel(this);
}
diff --git a/src/plugins/debugger/watchdata.cpp b/src/plugins/debugger/watchdata.cpp
index 5478e735c7..9cbe253d7e 100644
--- a/src/plugins/debugger/watchdata.cpp
+++ b/src/plugins/debugger/watchdata.cpp
@@ -98,6 +98,7 @@ bool isIntType(const QByteArray &type)
( type == "unsigned char"
|| type == "unsigned short"
|| type == "unsigned short int"
+ || type == "unsigned int"
|| type == "unsigned long"
|| type == "unsigned long int"
|| type == "unsigned long long"
diff --git a/src/plugins/debugger/watchhandler.cpp b/src/plugins/debugger/watchhandler.cpp
index 45e109aad9..bd40997ce8 100644
--- a/src/plugins/debugger/watchhandler.cpp
+++ b/src/plugins/debugger/watchhandler.cpp
@@ -47,6 +47,7 @@
#include <QDebug>
#include <QProcess>
#include <QtAlgorithms>
+#include <QTabWidget>
#include <QTextEdit>
#include <ctype.h>
@@ -55,7 +56,7 @@
//#define USE_EXPENSIVE_CHECKS 0
#if USE_WATCH_MODEL_TEST
-#include "modeltest.h"
+#include <modeltest.h>
#endif
namespace Debugger {
@@ -274,6 +275,7 @@ private:
WatchModel::WatchModel(WatchHandler *handler)
: m_handler(handler)
{
+ setObjectName(QLatin1String("WatchModel"));
m_root = createItem(QByteArray(), tr("Root"), 0);
// Note: Needs to stay
m_localsRoot = createItem("local", tr("Locals"), m_root);
@@ -1441,8 +1443,7 @@ WatchHandler::WatchHandler(DebuggerEngine *engine)
{
m_separateWindow = 0;
m_engine = engine;
- m_watcherCounter = debuggerCore()->sessionValue(QLatin1String("Watchers"))
- .toStringList().count();
+ m_watcherCounter = DebuggerCore::sessionValue("Watchers").toStringList().count();
m_model = new WatchModel(this);
m_contentsValid = false;
m_contentsValid = true; // FIXME
@@ -1452,7 +1453,7 @@ WatchHandler::WatchHandler(DebuggerEngine *engine)
WatchHandler::~WatchHandler()
{
if (m_separateWindow) {
- debuggerCore()->setSessionValue(QLatin1String("DebuggerSeparateWidgetGeometry"),
+ DebuggerCore::setSessionValue("DebuggerSeparateWidgetGeometry",
m_separateWindow->geometry());
delete m_separateWindow;
m_separateWindow = 0;
@@ -1643,8 +1644,7 @@ void WatchHandler::showSeparateWidget(QWidget *w)
{
if (m_separateWindow.isNull()) {
m_separateWindow = new SeparateViewWidget(debuggerCore()->mainWindow());
- QVariant geometry = debuggerCore()->
- sessionValue(QLatin1String("DebuggerSeparateWidgetGeometry"));
+ QVariant geometry = DebuggerCore::sessionValue("DebuggerSeparateWidgetGeometry");
if (geometry.isValid())
m_separateWindow->setGeometry(geometry.toRect());
}
@@ -1802,12 +1802,12 @@ QStringList WatchHandler::watchedExpressions()
void WatchHandler::saveWatchers()
{
- debuggerCore()->setSessionValue(QLatin1String("Watchers"), QVariant(watchedExpressions()));
+ DebuggerCore::setSessionValue("Watchers", watchedExpressions());
}
void WatchHandler::loadTypeFormats()
{
- QVariant value = debuggerCore()->sessionValue(QLatin1String("DefaultFormats"));
+ QVariant value = DebuggerCore::sessionValue("DefaultFormats");
QMap<QString, QVariant> typeFormats = value.toMap();
QMapIterator<QString, QVariant> it(typeFormats);
while (it.hasNext()) {
@@ -1830,8 +1830,7 @@ void WatchHandler::saveTypeFormats()
typeFormats.insert(QLatin1String(key), format);
}
}
- debuggerCore()->setSessionValue(QLatin1String("DefaultFormats"),
- QVariant(typeFormats));
+ DebuggerCore::setSessionValue("DefaultFormats", typeFormats);
}
void WatchHandler::saveSessionData()
@@ -1845,7 +1844,7 @@ void WatchHandler::loadSessionData()
loadTypeFormats();
theWatcherNames.clear();
m_watcherCounter = 0;
- QVariant value = debuggerCore()->sessionValue(QLatin1String("Watchers"));
+ QVariant value = DebuggerCore::sessionValue("Watchers");
m_model->destroyChildren(m_model->m_watchRoot);
foreach (const QString &exp, value.toStringList())
watchExpression(exp);
diff --git a/src/plugins/designer/Designer.pluginspec.in b/src/plugins/designer/Designer.pluginspec.in
index 69dc9b93ad..6f96561a30 100644
--- a/src/plugins/designer/Designer.pluginspec.in
+++ b/src/plugins/designer/Designer.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"Designer\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"Designer\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/designer/README.txt b/src/plugins/designer/README.txt
index 44ef03b875..bc6108425b 100644
--- a/src/plugins/designer/README.txt
+++ b/src/plugins/designer/README.txt
@@ -38,7 +38,7 @@ We need to update resources of the opened form in following cases:
slot)
- the opened form is being saved as... with new name, what causes the editor
for the form points to a new file which is not in the project (we connect
- changed() to updateResources() slot)
+ filePathChanged(QString,QString) to updateResources() slot)
Changes to qrc file contents are not needed to be handled here, since
designer's internal file watcher updates the changes to qrc files silently.
diff --git a/src/plugins/designer/codemodelhelpers.cpp b/src/plugins/designer/codemodelhelpers.cpp
index ffb136080b..5b26c45d1e 100644
--- a/src/plugins/designer/codemodelhelpers.cpp
+++ b/src/plugins/designer/codemodelhelpers.cpp
@@ -50,8 +50,7 @@ static const char setupUiC[] = "setupUi";
// Find the generated "ui_form.h" header of the form via project.
static QString generatedHeaderOf(const QString &uiFileName)
{
- const ProjectExplorer::SessionManager *sessionMgr = ProjectExplorer::ProjectExplorerPlugin::instance()->session();
- if (const ProjectExplorer::Project *uiProject = sessionMgr->projectForFile(uiFileName))
+ if (const ProjectExplorer::Project *uiProject = ProjectExplorer::SessionManager::projectForFile(uiFileName))
return uiProject->generatedUiHeader(uiFileName);
return QString();
}
diff --git a/src/plugins/designer/cpp/cpp.pri b/src/plugins/designer/cpp/cpp.pri
index a30a794022..690ca7fc9f 100644
--- a/src/plugins/designer/cpp/cpp.pri
+++ b/src/plugins/designer/cpp/cpp.pri
@@ -1,5 +1,3 @@
-INCLUDEPATH+=$$PWD
-
DEFINES+=CPP_ENABLED
HEADERS+=$$PWD/formclasswizardpage.h \
diff --git a/src/plugins/designer/cpp/cppsettingspage.cpp b/src/plugins/designer/cpp/cppsettingspage.cpp
index 346c9167ca..cc24f2ca89 100644
--- a/src/plugins/designer/cpp/cppsettingspage.cpp
+++ b/src/plugins/designer/cpp/cppsettingspage.cpp
@@ -28,7 +28,7 @@
****************************************************************************/
#include "cppsettingspage.h"
-#include "designerconstants.h"
+#include <designer/designerconstants.h>
#include <QCoreApplication>
#include <QTextStream>
diff --git a/src/plugins/designer/cpp/cppsettingspage.h b/src/plugins/designer/cpp/cppsettingspage.h
index 52fd6751cb..647c7d7d19 100644
--- a/src/plugins/designer/cpp/cppsettingspage.h
+++ b/src/plugins/designer/cpp/cppsettingspage.h
@@ -31,7 +31,7 @@
#define CPPSETTINGSPAGE_H
#include "ui_cppsettingspagewidget.h"
-#include "qtdesignerformclasscodegenerator.h"
+#include <designer/qtdesignerformclasscodegenerator.h>
#include <coreplugin/dialogs/ioptionspage.h>
diff --git a/src/plugins/designer/cpp/formclasswizard.cpp b/src/plugins/designer/cpp/formclasswizard.cpp
index 582318b54f..56202924b8 100644
--- a/src/plugins/designer/cpp/formclasswizard.cpp
+++ b/src/plugins/designer/cpp/formclasswizard.cpp
@@ -29,8 +29,8 @@
#include "formclasswizard.h"
#include "formclasswizarddialog.h"
-#include "designerconstants.h"
-#include "qtdesignerformclasscodegenerator.h"
+#include <designer/designerconstants.h>
+#include <designer/qtdesignerformclasscodegenerator.h>
#include <qtsupport/qtsupportconstants.h>
#include <cppeditor/cppeditorconstants.h>
@@ -40,9 +40,9 @@
namespace Designer {
namespace Internal {
-FormClassWizard::FormClassWizard(const BaseFileWizardParameters &parameters, QObject *parent)
- : Core::BaseFileWizard(parameters, parent)
+FormClassWizard::FormClassWizard()
{
+ setRequiredFeatures(Core::Feature(QtSupport::Constants::FEATURE_QWIDGETS));
}
QString FormClassWizard::headerSuffix() const
@@ -60,11 +60,6 @@ QString FormClassWizard::formSuffix() const
return preferredSuffix(QLatin1String(Constants::FORM_MIMETYPE));
}
-Core::FeatureSet FormClassWizard::requiredFeatures() const
-{
- return Core::Feature(QtSupport::Constants::FEATURE_QWIDGETS);
-}
-
QWizard *FormClassWizard::createWizardDialog(QWidget *parent,
const Core::WizardDialogParameters &wizardDialogParameters) const
{
diff --git a/src/plugins/designer/cpp/formclasswizard.h b/src/plugins/designer/cpp/formclasswizard.h
index 9c6635f945..d8ee46c721 100644
--- a/src/plugins/designer/cpp/formclasswizard.h
+++ b/src/plugins/designer/cpp/formclasswizard.h
@@ -37,28 +37,22 @@
namespace Designer {
namespace Internal {
-class FormClassWizardParameters;
-
class FormClassWizard : public Core::BaseFileWizard
{
Q_OBJECT
public:
- typedef Core::BaseFileWizardParameters BaseFileWizardParameters;
-
- FormClassWizard(const BaseFileWizardParameters &parameters, QObject *parent);
+ FormClassWizard();
QString headerSuffix() const;
QString sourceSuffix() const;
QString formSuffix() const;
- virtual Core::FeatureSet requiredFeatures() const;
-
-protected:
- virtual QWizard *createWizardDialog(QWidget *parent,
+private:
+ QWizard *createWizardDialog(QWidget *parent,
const Core::WizardDialogParameters &wizardDialogParameters) const;
- virtual Core::GeneratedFiles generateFiles(const QWizard *w,
+ Core::GeneratedFiles generateFiles(const QWizard *w,
QString *errorMessage) const;
};
diff --git a/src/plugins/designer/cpp/formclasswizarddialog.cpp b/src/plugins/designer/cpp/formclasswizarddialog.cpp
index 67c636044f..5d62e35ee9 100644
--- a/src/plugins/designer/cpp/formclasswizarddialog.cpp
+++ b/src/plugins/designer/cpp/formclasswizarddialog.cpp
@@ -28,9 +28,9 @@
****************************************************************************/
#include "formclasswizarddialog.h"
-#include "formtemplatewizardpage.h"
#include "formclasswizardpage.h"
#include "formclasswizardparameters.h"
+#include <designer/formtemplatewizardpage.h>
#include <coreplugin/basefilewizard.h>
diff --git a/src/plugins/designer/cpp/formclasswizardpage.cpp b/src/plugins/designer/cpp/formclasswizardpage.cpp
index 7feb379f77..c62746ad5e 100644
--- a/src/plugins/designer/cpp/formclasswizardpage.cpp
+++ b/src/plugins/designer/cpp/formclasswizardpage.cpp
@@ -79,9 +79,8 @@ bool FormClassWizardPage::lowercaseHeaderFiles()
// Set up new class widget from settings
void FormClassWizardPage::initFileGenerationSettings()
{
- const Core::MimeDatabase *mdb = Core::ICore::mimeDatabase();
- m_ui->newClassWidget->setHeaderExtension(mdb->preferredSuffixByType(QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE)));
- m_ui->newClassWidget->setSourceExtension(mdb->preferredSuffixByType(QLatin1String(CppTools::Constants::CPP_SOURCE_MIMETYPE)));
+ m_ui->newClassWidget->setHeaderExtension(Core::MimeDatabase::preferredSuffixByType(QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE)));
+ m_ui->newClassWidget->setSourceExtension(Core::MimeDatabase::preferredSuffixByType(QLatin1String(CppTools::Constants::CPP_SOURCE_MIMETYPE)));
m_ui->newClassWidget->setLowerCaseFiles(lowercaseHeaderFiles());
}
diff --git a/src/plugins/designer/cpp/formclasswizardparameters.cpp b/src/plugins/designer/cpp/formclasswizardparameters.cpp
index 78717c9b3d..f64c097c95 100644
--- a/src/plugins/designer/cpp/formclasswizardparameters.cpp
+++ b/src/plugins/designer/cpp/formclasswizardparameters.cpp
@@ -28,5 +28,5 @@
****************************************************************************/
#include "formclasswizardparameters.h"
-#include "formtemplatewizardpage.h"
+#include <designer/formtemplatewizardpage.h>
diff --git a/src/plugins/designer/designer.pro b/src/plugins/designer/designer.pro
index 09648d581e..c0915e57fc 100644
--- a/src/plugins/designer/designer.pro
+++ b/src/plugins/designer/designer.pro
@@ -4,8 +4,6 @@ include(../../qtcreatorplugin.pri)
include(../../shared/designerintegrationv2/designerintegration.pri)
include(cpp/cpp.pri)
-INCLUDEPATH += ../../tools/utils
-
greaterThan(QT_MAJOR_VERSION, 4) {
QT += printsupport designer designercomponents-private
} else {
@@ -36,12 +34,12 @@ HEADERS += formeditorplugin.h \
formwizarddialog.h \
codemodelhelpers.h \
designer_export.h \
- designerxmleditor.h \
designercontext.h \
formeditorstack.h \
editordata.h \
resourcehandler.h \
- qtdesignerformclasscodegenerator.h
+ qtdesignerformclasscodegenerator.h \
+ designerxmleditorwidget.h
SOURCES += formeditorplugin.cpp \
formeditorfactory.cpp \
@@ -56,11 +54,16 @@ SOURCES += formeditorplugin.cpp \
formtemplatewizardpage.cpp \
formwizarddialog.cpp \
codemodelhelpers.cpp \
- designerxmleditor.cpp \
designercontext.cpp \
formeditorstack.cpp \
resourcehandler.cpp \
- qtdesignerformclasscodegenerator.cpp
+ qtdesignerformclasscodegenerator.cpp \
+ designerxmleditorwidget.cpp
+
+equals(TEST, 1) {
+ SOURCES += gotoslot_test.cpp
+ DEFINES += SRCDIR=\\\"$$PWD\\\"
+}
RESOURCES += designer.qrc
diff --git a/src/plugins/designer/designer.qbs b/src/plugins/designer/designer.qbs
index 36102c3efc..68b211c745 100644
--- a/src/plugins/designer/designer.qbs
+++ b/src/plugins/designer/designer.qbs
@@ -1,4 +1,5 @@
import qbs.base 1.0
+import qbs.FileInfo
import "../QtcPlugin.qbs" as QtcPlugin
@@ -14,71 +15,69 @@ QtcPlugin {
cpp.defines: base.concat(["CPP_ENABLED"])
cpp.includePaths: base.concat([
- "../../libs/3rdparty",
- "cpp",
- "../../shared/designerintegrationv2"
+ sharedSources.prefix
])
- files: [
- "README.txt",
- "codemodelhelpers.cpp",
- "codemodelhelpers.h",
- "designer.qrc",
- "designer_export.h",
- "designerconstants.h",
- "designercontext.cpp",
- "designercontext.h",
- "designerxmleditor.cpp",
- "designerxmleditor.h",
- "editordata.h",
- "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",
- "formwizard.h",
- "formwizarddialog.cpp",
- "formwizarddialog.h",
- "qtcreatorintegration.cpp",
- "qtcreatorintegration.h",
- "qtdesignerformclasscodegenerator.cpp",
- "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",
- "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",
- ]
+ Group {
+ name: "General"
+ files: [
+ "README.txt",
+ "codemodelhelpers.cpp", "codemodelhelpers.h",
+ "designer.qrc",
+ "designer_export.h",
+ "designerconstants.h",
+ "designercontext.cpp", "designercontext.h",
+ "designerxmleditorwidget.cpp", "designerxmleditorwidget.h",
+ "editordata.h",
+ "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", "formwizard.h",
+ "formwizarddialog.cpp", "formwizarddialog.h",
+ "qtcreatorintegration.cpp", "qtcreatorintegration.h",
+ "qtdesignerformclasscodegenerator.cpp", "qtdesignerformclasscodegenerator.h",
+ "resourcehandler.cpp", "resourcehandler.h",
+ "settingsmanager.cpp", "settingsmanager.h",
+ "settingspage.cpp", "settingspage.h",
+ ]
+ }
+
+ Group {
+ name: "Shared Sources"
+ id: sharedSources
+ prefix: "../../shared/designerintegrationv2/"
+ files: [
+ "formresizer.cpp", "formresizer.h",
+ "sizehandlerect.cpp", "sizehandlerect.h",
+ "widgethost.cpp", "widgethost.h",
+ "widgethostconstants.h",
+ ]
+ }
+
+ Group {
+ name: "cpp"
+ prefix: "cpp/"
+ files: [
+ "cppsettingspage.cpp", "cppsettingspage.h",
+ "cppsettingspagewidget.ui",
+ "formclasswizard.cpp", "formclasswizard.h",
+ "formclasswizarddialog.cpp", "formclasswizarddialog.h",
+ "formclasswizardpage.cpp", "formclasswizardpage.h", "formclasswizardpage.ui",
+ "formclasswizardparameters.cpp", "formclasswizardparameters.h",
+ ]
+ }
+
+ Group {
+ name: "Tests"
+ condition: project.testsEnabled
+ files: [ "gotoslot_test.cpp" ]
+
+ cpp.defines: outer.concat(['SRCDIR="' + FileInfo.path(filePath) + '"'])
+ }
+
}
diff --git a/src/plugins/designer/designerxmleditor.cpp b/src/plugins/designer/designerxmleditorwidget.cpp
index b98d3c3f1b..202f65c565 100644
--- a/src/plugins/designer/designerxmleditor.cpp
+++ b/src/plugins/designer/designerxmleditorwidget.cpp
@@ -27,7 +27,7 @@
**
****************************************************************************/
-#include "designerxmleditor.h"
+#include "designerxmleditorwidget.h"
#include "formwindoweditor.h"
#include "designerconstants.h"
@@ -37,26 +37,34 @@
namespace Designer {
namespace Internal {
-DesignerXmlEditor::DesignerXmlEditor(QDesignerFormWindowInterface *form,
- QWidget *parent) :
+DesignerXmlEditorWidget::DesignerXmlEditorWidget(QDesignerFormWindowInterface *form,
+ QWidget *parent) :
TextEditor::PlainTextEditorWidget(parent),
- m_designerEditor(new FormWindowEditor(this, form))
+ m_file(new FormWindowFile(form, this)),
+ m_designerEditor(new FormWindowEditor(this))
{
+ setBaseTextDocument(m_file);
setReadOnly(true);
+ configure(m_file->mimeType());
}
-TextEditor::BaseTextEditor *DesignerXmlEditor::createEditor()
+TextEditor::BaseTextEditor *DesignerXmlEditorWidget::createEditor()
{
if (Designer::Constants::Internal::debug)
qDebug() << "DesignerXmlEditor::createEditableInterface()";
- return m_designerEditor->textEditor();
+ return m_designerEditor;
}
-FormWindowEditor *DesignerXmlEditor::designerEditor() const
+FormWindowEditor *DesignerXmlEditorWidget::designerEditor() const
{
return m_designerEditor;
}
+Internal::FormWindowFile *DesignerXmlEditorWidget::formWindowFile() const
+{
+ return m_file.data();
+}
+
} // namespace Internal
} // namespace Designer
diff --git a/src/plugins/designer/designerxmleditor.h b/src/plugins/designer/designerxmleditorwidget.h
index 9e97b3ccdf..9c0780d705 100644
--- a/src/plugins/designer/designerxmleditor.h
+++ b/src/plugins/designer/designerxmleditorwidget.h
@@ -27,11 +27,15 @@
**
****************************************************************************/
-#ifndef DESIGNERXMLEDITOR_H
-#define DESIGNERXMLEDITOR_H
+#ifndef DESIGNERXMLEDITORWIDGET_H
+#define DESIGNERXMLEDITORWIDGET_H
+
+#include "formwindowfile.h"
#include <texteditor/plaintexteditor.h>
+#include <QSharedPointer>
+
QT_BEGIN_NAMESPACE
class QDesignerFormWindowInterface;
QT_END_NAMESPACE
@@ -49,23 +53,25 @@ namespace Internal {
* Internally manages a FormWindowEditor and uses the plain text
* editable embedded in it. */
-class DesignerXmlEditor : public TextEditor::PlainTextEditorWidget
+class DesignerXmlEditorWidget : public TextEditor::PlainTextEditorWidget
{
Q_OBJECT
public:
- explicit DesignerXmlEditor(QDesignerFormWindowInterface *form,
+ explicit DesignerXmlEditorWidget(QDesignerFormWindowInterface *form,
QWidget *parent = 0);
FormWindowEditor *designerEditor() const;
+ Internal::FormWindowFile *formWindowFile() const;
protected:
virtual TextEditor::BaseTextEditor *createEditor();
private:
+ QSharedPointer<Internal::FormWindowFile> m_file;
FormWindowEditor *m_designerEditor;
};
} // Internal
} // Designer
-#endif // DESIGNERXMLEDITOR_H
+#endif // DESIGNERXMLEDITORWIDGET_H
diff --git a/src/plugins/designer/formeditorfactory.cpp b/src/plugins/designer/formeditorfactory.cpp
index 3da34f486a..3939d0ae24 100644
--- a/src/plugins/designer/formeditorfactory.cpp
+++ b/src/plugins/designer/formeditorfactory.cpp
@@ -31,7 +31,7 @@
#include "formeditorw.h"
#include "formwindoweditor.h"
#include "editordata.h"
-#include "designerxmleditor.h"
+#include "designerxmleditorwidget.h"
#include <coreplugin/coreconstants.h>
#include <coreplugin/icore.h>
@@ -48,22 +48,13 @@ namespace Designer {
namespace Internal {
FormEditorFactory::FormEditorFactory()
- : Core::IEditorFactory(Core::ICore::instance()),
- m_mimeTypes(QLatin1String(FORM_MIMETYPE))
+ : Core::IEditorFactory(Core::ICore::instance())
{
- Core::FileIconProvider *iconProvider = Core::FileIconProvider::instance();
- iconProvider->registerIconOverlayForSuffix(QIcon(QLatin1String(":/formeditor/images/qt_ui.png")),
- QLatin1String("ui"));
-}
+ setId(K_DESIGNER_XML_EDITOR_ID);
+ setDisplayName(qApp->translate("Designer", C_DESIGNER_XML_DISPLAY_NAME));
+ addMimeType(FORM_MIMETYPE);
-Core::Id FormEditorFactory::id() const
-{
- return Core::Id(K_DESIGNER_XML_EDITOR_ID);
-}
-
-QString FormEditorFactory::displayName() const
-{
- return qApp->translate("Designer", C_DESIGNER_XML_DISPLAY_NAME);
+ Core::FileIconProvider::registerIconOverlayForSuffix(":/formeditor/images/qt_ui.png", "ui");
}
Core::IEditor *FormEditorFactory::createEditor(QWidget *parent)
@@ -78,11 +69,6 @@ Core::IEditor *FormEditorFactory::createEditor(QWidget *parent)
return data.formWindowEditor;
}
-QStringList FormEditorFactory::mimeTypes() const
-{
- return m_mimeTypes;
-}
-
void FormEditorFactory::designerModeClicked()
{
Core::ModeManager::activateMode(Core::Constants::MODE_DESIGN);
@@ -90,5 +76,3 @@ void FormEditorFactory::designerModeClicked()
} // namespace Internal
} // namespace Designer
-
-
diff --git a/src/plugins/designer/formeditorfactory.h b/src/plugins/designer/formeditorfactory.h
index d1183fbfc5..a17446d18b 100644
--- a/src/plugins/designer/formeditorfactory.h
+++ b/src/plugins/designer/formeditorfactory.h
@@ -32,8 +32,6 @@
#include <coreplugin/editormanager/ieditorfactory.h>
-#include <QStringList>
-
namespace Designer {
namespace Internal {
@@ -44,17 +42,10 @@ class FormEditorFactory : public Core::IEditorFactory
public:
FormEditorFactory();
- // IEditorFactory
- QStringList mimeTypes() const;
- Core::Id id() const;
- QString displayName() const;
Core::IEditor *createEditor(QWidget *parent);
private slots:
void designerModeClicked();
-
-private:
- const QStringList m_mimeTypes;
};
} // namespace Internal
diff --git a/src/plugins/designer/formeditorplugin.cpp b/src/plugins/designer/formeditorplugin.cpp
index ce8bb2df7b..ce5c6da2b9 100644
--- a/src/plugins/designer/formeditorplugin.cpp
+++ b/src/plugins/designer/formeditorplugin.cpp
@@ -33,8 +33,8 @@
#include "formwizard.h"
#ifdef CPP_ENABLED
-# include "formclasswizard.h"
-# include "cppsettingspage.h"
+# include "cpp/formclasswizard.h"
+# include "cpp/cppsettingspage.h"
#endif
#include "settingspage.h"
@@ -50,6 +50,7 @@
#include <QTranslator>
#include <QtPlugin>
+using namespace Core;
using namespace Designer::Internal;
using namespace Designer::Constants;
@@ -70,9 +71,8 @@ FormEditorPlugin::~FormEditorPlugin()
bool FormEditorPlugin::initialize(const QStringList &arguments, QString *error)
{
Q_UNUSED(arguments)
- Q_UNUSED(error)
- if (!Core::ICore::mimeDatabase()->addMimeTypes(QLatin1String(":/formeditor/Designer.mimetypes.xml"), error))
+ if (!MimeDatabase::addMimeTypes(QLatin1String(":/formeditor/Designer.mimetypes.xml"), error))
return false;
initializeTemplates();
@@ -81,11 +81,11 @@ bool FormEditorPlugin::initialize(const QStringList &arguments, QString *error)
addAutoReleasedObject(new SettingsPageProvider);
addAutoReleasedObject(new QtDesignerFormClassCodeGenerator);
// Ensure that loading designer translations is done before FormEditorW is instantiated
- const QString locale = Core::ICore::userInterfaceLanguage();
+ const QString locale = ICore::userInterfaceLanguage();
if (!locale.isEmpty()) {
QTranslator *qtr = new QTranslator(this);
const QString &creatorTrPath =
- Core::ICore::resourcePath() + QLatin1String("/translations");
+ ICore::resourcePath() + QLatin1String("/translations");
const QString &qtTrPath = QLibraryInfo::location(QLibraryInfo::TranslationsPath);
const QString &trFile = QLatin1String("designer_") + locale;
if (qtr->load(trFile, qtTrPath) || qtr->load(trFile, creatorTrPath))
@@ -97,7 +97,7 @@ bool FormEditorPlugin::initialize(const QStringList &arguments, QString *error)
void FormEditorPlugin::extensionsInitialized()
{
- Core::DesignMode::instance()->setDesignModeIsRequired();
+ DesignMode::instance()->setDesignModeIsRequired();
// 4) test and make sure everything works (undo, saving, editors, opening/closing multiple files, dirtiness etc)
}
@@ -109,23 +109,27 @@ void FormEditorPlugin::extensionsInitialized()
void FormEditorPlugin::initializeTemplates()
{
- FormWizard::BaseFileWizardParameters wizardParameters(Core::IWizard::FileWizard);
- wizardParameters.setCategory(QLatin1String(Core::Constants::WIZARD_CATEGORY_QT));
- wizardParameters.setDisplayCategory(QCoreApplication::translate("Core", Core::Constants::WIZARD_TR_CATEGORY_QT));
- const QString formFileType = QLatin1String(Constants::FORM_FILE_TYPE);
- wizardParameters.setDisplayName(tr("Qt Designer Form"));
- wizardParameters.setId(QLatin1String("D.Form"));
- wizardParameters.setDescription(tr("Creates a Qt Designer form that you can add to a Qt Widget Project. "
+ IWizard *wizard = new FormWizard;
+ wizard->setWizardKind(IWizard::FileWizard);
+ wizard->setCategory(QLatin1String(Core::Constants::WIZARD_CATEGORY_QT));
+ wizard->setDisplayCategory(QCoreApplication::translate("Core", Core::Constants::WIZARD_TR_CATEGORY_QT));
+ wizard->setDisplayName(tr("Qt Designer Form"));
+ wizard->setId(QLatin1String("D.Form"));
+ wizard->setDescription(tr("Creates a Qt Designer form that you can add to a Qt Widget Project. "
"This is useful if you already have an existing class for the UI business logic."));
- addAutoReleasedObject(new FormWizard(wizardParameters, this));
+ addAutoReleasedObject(wizard);
#ifdef CPP_ENABLED
- wizardParameters.setKind(Core::IWizard::ClassWizard);
- wizardParameters.setDisplayName(tr("Qt Designer Form Class"));
- wizardParameters.setId(QLatin1String("C.FormClass"));
- wizardParameters.setDescription(tr("Creates a Qt Designer form along with a matching class (C++ header and source file) "
+ wizard = new FormClassWizard;
+ wizard->setWizardKind(IWizard::ClassWizard);
+ wizard->setCategory(QLatin1String(Core::Constants::WIZARD_CATEGORY_QT));
+ wizard->setDisplayCategory(QCoreApplication::translate("Core", Core::Constants::WIZARD_TR_CATEGORY_QT));
+ wizard->setDisplayName(tr("Qt Designer Form Class"));
+ wizard->setId(QLatin1String("C.FormClass"));
+ wizard->setDescription(tr("Creates a Qt Designer form along with a matching class (C++ header and source file) "
"for implementation purposes. You can add the form and class to an existing Qt Widget Project."));
- addAutoReleasedObject(new FormClassWizard(wizardParameters, this));
+ addAutoReleasedObject(wizard);
+
addAutoReleasedObject(new CppSettingsPage);
#endif
}
diff --git a/src/plugins/designer/formeditorplugin.h b/src/plugins/designer/formeditorplugin.h
index 36a900104c..ad77112c96 100644
--- a/src/plugins/designer/formeditorplugin.h
+++ b/src/plugins/designer/formeditorplugin.h
@@ -50,6 +50,11 @@ public:
private:
void initializeTemplates();
+
+private slots:
+#ifdef WITH_TESTS
+ void test_gotoslot_withoutProject();
+#endif
};
} // namespace Internal
diff --git a/src/plugins/designer/formeditorw.cpp b/src/plugins/designer/formeditorw.cpp
index e435c95cdb..aa0064eb5f 100644
--- a/src/plugins/designer/formeditorw.cpp
+++ b/src/plugins/designer/formeditorw.cpp
@@ -34,7 +34,7 @@
#include "editorwidget.h"
#include "editordata.h"
#include "qtcreatorintegration.h"
-#include "designerxmleditor.h"
+#include "designerxmleditorwidget.h"
#include "designercontext.h"
#include "resourcehandler.h"
#include <widgethost.h>
@@ -113,6 +113,7 @@ static inline QIcon designerIcon(const QString &iconName)
return icon;
}
+using namespace Core;
using namespace Designer::Constants;
namespace Designer {
@@ -150,7 +151,7 @@ FormEditorW::FormEditorW() :
qFill(m_designerSubWindows, m_designerSubWindows + Designer::Constants::DesignerSubWindowCount,
static_cast<QWidget *>(0));
- m_formeditor->setTopLevel(Core::ICore::mainWindow());
+ m_formeditor->setTopLevel(ICore::mainWindow());
m_formeditor->setSettingsManager(new SettingsManager());
#if QT_VERSION >= 0x050000
@@ -169,7 +170,7 @@ FormEditorW::FormEditorW() :
m_settingsPages.append(settingsPage);
}
- connect(Core::ICore::editorManager(), SIGNAL(currentEditorChanged(Core::IEditor*)),
+ connect(EditorManager::instance(), SIGNAL(currentEditorChanged(Core::IEditor*)),
this, SLOT(currentEditorChanged(Core::IEditor*)));
connect(m_shortcutMapper, SIGNAL(mapped(QObject*)),
this, SLOT(updateShortcut(QObject*)));
@@ -178,9 +179,9 @@ FormEditorW::FormEditorW() :
FormEditorW::~FormEditorW()
{
if (m_context)
- Core::ICore::removeContextObject(m_context);
+ ICore::removeContextObject(m_context);
if (m_initStage == FullyInitialized) {
- QSettings *s = Core::ICore::settings();
+ QSettings *s = ICore::settings();
s->beginGroup(QLatin1String(settingsGroupC));
m_editorWidget->saveSettings(s);
s->endGroup();
@@ -199,51 +200,51 @@ FormEditorW::~FormEditorW()
}
// Add an actioon to toggle the view state of a dock window
-void FormEditorW::addDockViewAction(Core::ActionContainer *viewMenu,
- int index, const Core::Context &context,
- const QString &title, const Core::Id &id)
+void FormEditorW::addDockViewAction(ActionContainer *viewMenu,
+ int index, const Context &context,
+ const QString &title, const Id &id)
{
if (const QDockWidget *dw = m_editorWidget->designerDockWidgets()[index]) {
QAction *action = dw->toggleViewAction();
action->setText(title);
- Core::Command *cmd = addToolAction(action, context, id, viewMenu, QString());
- cmd->setAttribute(Core::Command::CA_Hide);
+ Command *cmd = addToolAction(action, context, id, viewMenu, QString());
+ cmd->setAttribute(Command::CA_Hide);
}
}
void FormEditorW::setupViewActions()
{
// Populate "View" menu of form editor menu
- Core::ActionContainer *viewMenu = Core::ActionManager::actionContainer(Core::Id(Core::Constants::M_WINDOW_VIEWS));
+ ActionContainer *viewMenu = ActionManager::actionContainer(Core::Constants::M_WINDOW_VIEWS);
QTC_ASSERT(viewMenu, return);
addDockViewAction(viewMenu, WidgetBoxSubWindow, m_contexts,
- tr("Widget box"), Core::Id("FormEditor.WidgetBox"));
+ tr("Widget box"), "FormEditor.WidgetBox");
addDockViewAction(viewMenu, ObjectInspectorSubWindow, m_contexts,
- tr("Object Inspector"), Core::Id("FormEditor.ObjectInspector"));
+ tr("Object Inspector"), "FormEditor.ObjectInspector");
addDockViewAction(viewMenu, PropertyEditorSubWindow, m_contexts,
- tr("Property Editor"), Core::Id("FormEditor.PropertyEditor"));
+ tr("Property Editor"), "FormEditor.PropertyEditor");
addDockViewAction(viewMenu, SignalSlotEditorSubWindow, m_contexts,
- tr("Signals && Slots Editor"), Core::Id("FormEditor.SignalsAndSlotsEditor"));
+ tr("Signals && Slots Editor"), "FormEditor.SignalsAndSlotsEditor");
addDockViewAction(viewMenu, ActionEditorSubWindow, m_contexts,
- tr("Action Editor"), Core::Id("FormEditor.ActionEditor"));
+ tr("Action Editor"), "FormEditor.ActionEditor");
// Lock/Reset
- Core::Command *cmd = addToolAction(m_editorWidget->menuSeparator1(), m_contexts, Core::Id("FormEditor.SeparatorLock"), viewMenu, QString());
- cmd->setAttribute(Core::Command::CA_Hide);
+ Command *cmd = addToolAction(m_editorWidget->menuSeparator1(), m_contexts, "FormEditor.SeparatorLock", viewMenu);
+ cmd->setAttribute(Command::CA_Hide);
- cmd = addToolAction(m_editorWidget->toggleLockedAction(), m_contexts, Core::Id("FormEditor.Locked"), viewMenu, QString());
- cmd->setAttribute(Core::Command::CA_Hide);
+ cmd = addToolAction(m_editorWidget->toggleLockedAction(), m_contexts, "FormEditor.Locked", viewMenu);
+ cmd->setAttribute(Command::CA_Hide);
- cmd = addToolAction(m_editorWidget->menuSeparator2(), m_contexts, Core::Id("FormEditor.SeparatorReset"), viewMenu, QString());
- cmd->setAttribute(Core::Command::CA_Hide);
+ cmd = addToolAction(m_editorWidget->menuSeparator2(), m_contexts, "FormEditor.SeparatorReset", viewMenu);
+ cmd->setAttribute(Command::CA_Hide);
- cmd = addToolAction(m_editorWidget->resetLayoutAction(), m_contexts, Core::Id("FormEditor.ResetToDefaultLayout"), viewMenu, QString());
+ cmd = addToolAction(m_editorWidget->resetLayoutAction(), m_contexts, "FormEditor.ResetToDefaultLayout", viewMenu);
connect(m_editorWidget, SIGNAL(resetLayout()), m_editorWidget, SLOT(resetToDefaultLayout()));
- cmd->setAttribute(Core::Command::CA_Hide);
+ cmd->setAttribute(Command::CA_Hide);
}
void FormEditorW::fullInit()
@@ -263,7 +264,7 @@ void FormEditorW::fullInit()
m_formeditor->setIntegration(m_integration);
// Connect Qt Designer help request to HelpManager.
connect(m_integration, SIGNAL(creatorHelpRequested(QUrl)),
- Core::HelpManager::instance(), SIGNAL(helpRequested(QUrl)));
+ HelpManager::instance(), SIGNAL(helpRequested(QUrl)));
/**
* This will initialize our TabOrder, Signals and slots and Buddy editors.
@@ -289,22 +290,22 @@ void FormEditorW::fullInit()
delete initTime;
}
- connect(Core::ICore::editorManager(), SIGNAL(editorsClosed(QList<Core::IEditor*>)),
+ connect(EditorManager::instance(), SIGNAL(editorsClosed(QList<Core::IEditor*>)),
SLOT(closeFormEditorsForXmlEditors(QList<Core::IEditor*>)));
// Nest toolbar and editor widget
m_editorWidget = new EditorWidget(this);
- QSettings *settings = Core::ICore::settings();
+ QSettings *settings = ICore::settings();
settings->beginGroup(QLatin1String(settingsGroupC));
m_editorWidget->restoreSettings(settings);
settings->endGroup();
m_editorToolBar = createEditorToolBar();
- m_toolBar = Core::EditorManager::createToolBar();
- m_toolBar->setToolbarCreationFlags(Core::EditorToolBar::FlagsStandalone);
+ m_toolBar = EditorManager::createToolBar();
+ m_toolBar->setToolbarCreationFlags(EditorToolBar::FlagsStandalone);
m_toolBar->setNavigationVisible(false);
m_toolBar->addCenterToolBar(m_editorToolBar);
- m_designMode = Core::DesignMode::instance();
+ m_designMode = DesignMode::instance();
m_modeWidget = new QWidget;
m_modeWidget->setObjectName(QLatin1String("DesignerModeWidget"));
QVBoxLayout *layout = new QVBoxLayout;
@@ -313,18 +314,18 @@ void FormEditorW::fullInit()
layout->addWidget(m_toolBar);
// Avoid mode switch to 'Edit' mode when the application started by
// 'Run' in 'Design' mode emits output.
- Core::MiniSplitter *splitter = new Core::MiniSplitter(Qt::Vertical);
+ MiniSplitter *splitter = new MiniSplitter(Qt::Vertical);
splitter->addWidget(m_editorWidget);
- QWidget *outputPane = new Core::OutputPanePlaceHolder(m_designMode, splitter);
+ QWidget *outputPane = new OutputPanePlaceHolder(m_designMode, splitter);
outputPane->setObjectName(QLatin1String("DesignerOutputPanePlaceHolder"));
splitter->addWidget(outputPane);
layout->addWidget(splitter);
m_modeWidget->setLayout(layout);
- Core::Context designerContexts = m_contexts;
+ Context designerContexts = m_contexts;
designerContexts.add(Core::Constants::C_EDITORMANAGER);
m_context = new DesignerContext(designerContexts, m_modeWidget, this);
- Core::ICore::addContextObject(m_context);
+ ICore::addContextObject(m_context);
m_designMode->registerDesignWidget(m_modeWidget, QStringList(QLatin1String(FORM_MIMETYPE)), m_contexts);
@@ -398,37 +399,33 @@ void FormEditorW::deleteInstance()
void FormEditorW::setupActions()
{
- Core::Command *command;
-
//menus
- Core::ActionContainer *medit =
- Core::ActionManager::actionContainer(Core::Constants::M_EDIT);
- Core::ActionContainer *mtools =
- Core::ActionManager::actionContainer(Core::Constants::M_TOOLS);
+ ActionContainer *medit = ActionManager::actionContainer(Core::Constants::M_EDIT);
+ ActionContainer *mtools = ActionManager::actionContainer(Core::Constants::M_TOOLS);
- Core::ActionContainer *mformtools =
- Core::ActionManager::createMenu(M_FORMEDITOR);
+ ActionContainer *mformtools = ActionManager::createMenu(M_FORMEDITOR);
mformtools->menu()->setTitle(tr("For&m Editor"));
mtools->addMenu(mformtools);
//overridden actions
- bindShortcut(Core::ActionManager::registerAction(m_fwm->actionUndo(), Core::Constants::UNDO, m_contexts), m_fwm->actionUndo());
- bindShortcut(Core::ActionManager::registerAction(m_fwm->actionRedo(), Core::Constants::REDO, m_contexts), m_fwm->actionRedo());
- bindShortcut(Core::ActionManager::registerAction(m_fwm->actionCut(), Core::Constants::CUT, m_contexts), m_fwm->actionCut());
- bindShortcut(Core::ActionManager::registerAction(m_fwm->actionCopy(), Core::Constants::COPY, m_contexts), m_fwm->actionCopy());
- bindShortcut(Core::ActionManager::registerAction(m_fwm->actionPaste(), Core::Constants::PASTE, m_contexts), m_fwm->actionPaste());
- bindShortcut(Core::ActionManager::registerAction(m_fwm->actionSelectAll(), Core::Constants::SELECTALL, m_contexts), m_fwm->actionSelectAll());
+ bindShortcut(ActionManager::registerAction(m_fwm->actionUndo(), Core::Constants::UNDO, m_contexts), m_fwm->actionUndo());
+ bindShortcut(ActionManager::registerAction(m_fwm->actionRedo(), Core::Constants::REDO, m_contexts), m_fwm->actionRedo());
+ bindShortcut(ActionManager::registerAction(m_fwm->actionCut(), Core::Constants::CUT, m_contexts), m_fwm->actionCut());
+ bindShortcut(ActionManager::registerAction(m_fwm->actionCopy(), Core::Constants::COPY, m_contexts), m_fwm->actionCopy());
+ bindShortcut(ActionManager::registerAction(m_fwm->actionPaste(), Core::Constants::PASTE, m_contexts), m_fwm->actionPaste());
+ bindShortcut(ActionManager::registerAction(m_fwm->actionSelectAll(), Core::Constants::SELECTALL, m_contexts), m_fwm->actionSelectAll());
m_actionPrint = new QAction(this);
- bindShortcut(Core::ActionManager::registerAction(m_actionPrint, Core::Constants::PRINT, m_contexts), m_actionPrint);
+ bindShortcut(ActionManager::registerAction(m_actionPrint, Core::Constants::PRINT, m_contexts), m_actionPrint);
connect(m_actionPrint, SIGNAL(triggered()), this, SLOT(print()));
//'delete' action. Do not set a shortcut as Designer handles
// the 'Delete' key by event filter. Setting a shortcut triggers
// buggy behaviour on Mac (Pressing Delete in QLineEdit removing the widget).
- command = Core::ActionManager::registerAction(m_fwm->actionDelete(), Core::Id("FormEditor.Edit.Delete"), m_contexts);
+ Command *command;
+ command = ActionManager::registerAction(m_fwm->actionDelete(), "FormEditor.Edit.Delete", m_contexts);
bindShortcut(command, m_fwm->actionDelete());
- command->setAttribute(Core::Command::CA_Hide);
+ command->setAttribute(Command::CA_Hide);
medit->addAction(command, Core::Constants::G_EDIT_COPYPASTE);
m_actionGroupEditMode = new QActionGroup(this);
@@ -437,74 +434,71 @@ void FormEditorW::setupActions()
medit->addSeparator(m_contexts, Core::Constants::G_EDIT_OTHER);
- m_toolActionIds.push_back(Core::Id("FormEditor.WidgetEditor"));
+ m_toolActionIds.push_back("FormEditor.WidgetEditor");
createEditModeAction(m_actionGroupEditMode, m_contexts, medit,
tr("Edit Widgets"), m_toolActionIds.back(),
EditModeWidgetEditor, QLatin1String("widgettool.png"), tr("F3"));
- m_toolActionIds.push_back(Core::Id("FormEditor.SignalsSlotsEditor"));
+ m_toolActionIds.push_back("FormEditor.SignalsSlotsEditor");
createEditModeAction(m_actionGroupEditMode, m_contexts, medit,
tr("Edit Signals/Slots"), m_toolActionIds.back(),
EditModeSignalsSlotEditor, QLatin1String("signalslottool.png"), tr("F4"));
- m_toolActionIds.push_back(Core::Id("FormEditor.BuddyEditor"));
+ m_toolActionIds.push_back("FormEditor.BuddyEditor");
createEditModeAction(m_actionGroupEditMode, m_contexts, medit,
tr("Edit Buddies"), m_toolActionIds.back(),
EditModeBuddyEditor, QLatin1String("buddytool.png"));
- m_toolActionIds.push_back(Core::Id("FormEditor.TabOrderEditor"));
+ m_toolActionIds.push_back("FormEditor.TabOrderEditor");
createEditModeAction(m_actionGroupEditMode, m_contexts, medit,
tr("Edit Tab Order"), m_toolActionIds.back(),
EditModeTabOrderEditor, QLatin1String("tabordertool.png"));
//tool actions
- m_toolActionIds.push_back(Core::Id("FormEditor.LayoutHorizontally"));
- const QString horizLayoutShortcut = Core::UseMacShortcuts ? tr("Meta+Shift+H") : tr("Ctrl+H");
+ m_toolActionIds.push_back("FormEditor.LayoutHorizontally");
+ const QString horizLayoutShortcut = UseMacShortcuts ? tr("Meta+Shift+H") : tr("Ctrl+H");
addToolAction(m_fwm->actionHorizontalLayout(), m_contexts,
m_toolActionIds.back(), mformtools, horizLayoutShortcut);
- m_toolActionIds.push_back(Core::Id("FormEditor.LayoutVertically"));
- const QString vertLayoutShortcut = Core::UseMacShortcuts ? tr("Meta+L") : tr("Ctrl+L");
+ m_toolActionIds.push_back("FormEditor.LayoutVertically");
+ const QString vertLayoutShortcut = UseMacShortcuts ? tr("Meta+L") : tr("Ctrl+L");
addToolAction(m_fwm->actionVerticalLayout(), m_contexts,
m_toolActionIds.back(), mformtools, vertLayoutShortcut);
- m_toolActionIds.push_back(Core::Id("FormEditor.SplitHorizontal"));
+ m_toolActionIds.push_back("FormEditor.SplitHorizontal");
addToolAction(m_fwm->actionSplitHorizontal(), m_contexts,
m_toolActionIds.back(), mformtools);
- m_toolActionIds.push_back(Core::Id("FormEditor.SplitVertical"));
+ m_toolActionIds.push_back("FormEditor.SplitVertical");
addToolAction(m_fwm->actionSplitVertical(), m_contexts,
m_toolActionIds.back(), mformtools);
- m_toolActionIds.push_back(Core::Id("FormEditor.LayoutForm"));
+ m_toolActionIds.push_back("FormEditor.LayoutForm");
addToolAction(m_fwm->actionFormLayout(), m_contexts,
m_toolActionIds.back(), mformtools);
- m_toolActionIds.push_back(Core::Id("FormEditor.LayoutGrid"));
- const QString gridShortcut = Core::UseMacShortcuts ? tr("Meta+Shift+G") : tr("Ctrl+G");
+ m_toolActionIds.push_back("FormEditor.LayoutGrid");
+ const QString gridShortcut = UseMacShortcuts ? tr("Meta+Shift+G") : tr("Ctrl+G");
addToolAction(m_fwm->actionGridLayout(), m_contexts,
m_toolActionIds.back(), mformtools, gridShortcut);
- m_toolActionIds.push_back(Core::Id("FormEditor.LayoutBreak"));
+ m_toolActionIds.push_back("FormEditor.LayoutBreak");
addToolAction(m_fwm->actionBreakLayout(), m_contexts,
m_toolActionIds.back(), mformtools);
- m_toolActionIds.push_back(Core::Id("FormEditor.LayoutAdjustSize"));
- const QString adjustShortcut = Core::UseMacShortcuts ? tr("Meta+J") : tr("Ctrl+J");
+ m_toolActionIds.push_back("FormEditor.LayoutAdjustSize");
+ const QString adjustShortcut = UseMacShortcuts ? tr("Meta+J") : tr("Ctrl+J");
addToolAction(m_fwm->actionAdjustSize(), m_contexts,
m_toolActionIds.back(), mformtools, adjustShortcut);
- m_toolActionIds.push_back(Core::Id("FormEditor.SimplifyLayout"));
+ m_toolActionIds.push_back("FormEditor.SimplifyLayout");
addToolAction(m_fwm->actionSimplifyLayout(), m_contexts,
m_toolActionIds.back(), mformtools);
mformtools->addSeparator(m_contexts);
- addToolAction(m_fwm->actionLower(), m_contexts,
- Core::Id("FormEditor.Lower"), mformtools);
-
- addToolAction(m_fwm->actionRaise(), m_contexts,
- Core::Id("FormEditor.Raise"), mformtools);
+ addToolAction(m_fwm->actionLower(), m_contexts, "FormEditor.Lower", mformtools);
+ addToolAction(m_fwm->actionRaise(), m_contexts, "FormEditor.Raise", mformtools);
// Commands that do not go into the editor toolbar
mformtools->addSeparator(m_contexts);
@@ -515,8 +509,7 @@ void FormEditorW::setupActions()
m_actionPreview = m_fwm->actionDefaultPreview();
#endif
QTC_ASSERT(m_actionPreview, return);
- addToolAction(m_actionPreview, m_contexts,
- Core::Id("FormEditor.Preview"), mformtools, tr("Alt+Shift+R"));
+ addToolAction(m_actionPreview, m_contexts, "FormEditor.Preview", mformtools, tr("Alt+Shift+R"));
// Preview in style...
#if QT_VERSION >= 0x050000
@@ -525,7 +518,7 @@ void FormEditorW::setupActions()
m_actionGroupPreviewInStyle = m_fwm->actionGroupPreviewInStyle();
#endif
- Core::ActionContainer *previewAC = createPreviewStyleMenu(m_actionGroupPreviewInStyle);
+ ActionContainer *previewAC = createPreviewStyleMenu(m_actionGroupPreviewInStyle);
m_previewInStyleMenu = previewAC->menu();
mformtools->addMenu(previewAC);
setPreviewMenuEnabled(false);
@@ -539,10 +532,9 @@ void FormEditorW::setupActions()
connect(m_actionSwitchSource, SIGNAL(triggered()), this, SLOT(switchSourceForm()));
// Switch form/source in editor/design contexts.
- Core::Context switchContexts = m_contexts;
+ Context switchContexts = m_contexts;
switchContexts.add(Core::Constants::C_EDITORMANAGER);
- addToolAction(m_actionSwitchSource, switchContexts, Core::Id("FormEditor.FormSwitchSource"), mformtools,
- tr("Shift+F4"));
+ addToolAction(m_actionSwitchSource, switchContexts, "FormEditor.FormSwitchSource", mformtools, tr("Shift+F4"));
mformtools->addSeparator(m_contexts);
#if QT_VERSION >= 0x050000
@@ -550,13 +542,12 @@ void FormEditorW::setupActions()
#else
QAction *actionFormSettings = m_fwm->actionShowFormWindowSettingsDialog();
#endif
- addToolAction(actionFormSettings, m_contexts, Core::Id("FormEditor.FormSettings"), mformtools);
+ addToolAction(actionFormSettings, m_contexts, "FormEditor.FormSettings", mformtools);
mformtools->addSeparator(m_contexts);
m_actionAboutPlugins = new QAction(tr("About Qt Designer Plugins..."), this);
m_actionAboutPlugins->setMenuRole(QAction::NoRole);
- addToolAction(m_actionAboutPlugins, m_contexts,
- Core::Id("FormEditor.AboutPlugins"), mformtools);
+ addToolAction(m_actionAboutPlugins, m_contexts, "FormEditor.AboutPlugins", mformtools);
connect(m_actionAboutPlugins, SIGNAL(triggered()), m_fwm,
#if QT_VERSION >= 0x050000
SLOT(showPluginDialog())
@@ -573,9 +564,9 @@ void FormEditorW::setupActions()
QToolBar *FormEditorW::createEditorToolBar() const
{
QToolBar *editorToolBar = new QToolBar;
- const QList<Core::Id>::const_iterator cend = m_toolActionIds.constEnd();
- for (QList<Core::Id>::const_iterator it = m_toolActionIds.constBegin(); it != cend; ++it) {
- Core::Command *cmd = Core::ActionManager::command(*it);
+ const QList<Id>::const_iterator cend = m_toolActionIds.constEnd();
+ for (QList<Id>::const_iterator it = m_toolActionIds.constBegin(); it != cend; ++it) {
+ Command *cmd = ActionManager::command(*it);
QTC_ASSERT(cmd, continue);
QAction *action = cmd->action();
if (!action->icon().isNull()) // Simplify grid has no action yet
@@ -587,10 +578,10 @@ QToolBar *FormEditorW::createEditorToolBar() const
return editorToolBar;
}
-Core::ActionContainer *FormEditorW::createPreviewStyleMenu(QActionGroup *actionGroup)
+ActionContainer *FormEditorW::createPreviewStyleMenu(QActionGroup *actionGroup)
{
const QString menuId = QLatin1String(M_FORMEDITOR_PREVIEW);
- Core::ActionContainer *menuPreviewStyle = Core::ActionManager::createMenu(M_FORMEDITOR_PREVIEW);
+ ActionContainer *menuPreviewStyle = ActionManager::createMenu(M_FORMEDITOR_PREVIEW);
menuPreviewStyle->menu()->setTitle(tr("Preview in"));
// The preview menu is a list of invisible actions for the embedded design
@@ -612,11 +603,11 @@ Core::ActionContainer *FormEditorW::createPreviewStyleMenu(QActionGroup *actionG
name += dot;
}
name += data.toString();
- Core::Command *command = Core::ActionManager::registerAction(a, Core::Id::fromString(name), m_contexts);
+ Command *command = ActionManager::registerAction(a, Id::fromString(name), m_contexts);
bindShortcut(command, a);
if (isDeviceProfile) {
- command->setAttribute(Core::Command::CA_UpdateText);
- command->setAttribute(Core::Command::CA_NonConfigurable);
+ command->setAttribute(Command::CA_UpdateText);
+ command->setAttribute(Command::CA_NonConfigurable);
}
menuPreviewStyle->addAction(command);
}
@@ -638,11 +629,11 @@ void FormEditorW::saveSettings(QSettings *s)
void FormEditorW::critical(const QString &errorMessage)
{
- QMessageBox::critical(Core::ICore::mainWindow(), tr("Designer"), errorMessage);
+ QMessageBox::critical(ICore::mainWindow(), tr("Designer"), errorMessage);
}
// Apply the command shortcut to the action and connects to the command's keySequenceChanged signal
-void FormEditorW::bindShortcut(Core::Command *command, QAction *action)
+void FormEditorW::bindShortcut(Command *command, QAction *action)
{
m_commandToDesignerAction.insert(command, action);
connect(command, SIGNAL(keySequenceChanged()),
@@ -653,10 +644,10 @@ void FormEditorW::bindShortcut(Core::Command *command, QAction *action)
// Create an action to activate a designer tool
QAction *FormEditorW::createEditModeAction(QActionGroup *ag,
- const Core::Context &context,
- Core::ActionContainer *medit,
+ const Context &context,
+ ActionContainer *medit,
const QString &actionName,
- const Core::Id &id,
+ const Id &id,
int toolNumber,
const QString &iconName,
const QString &keySequence)
@@ -665,7 +656,7 @@ QAction *FormEditorW::createEditModeAction(QActionGroup *ag,
rc->setCheckable(true);
if (!iconName.isEmpty())
rc->setIcon(designerIcon(iconName));
- Core::Command *command = Core::ActionManager::registerAction(rc, id, context);
+ Command *command = ActionManager::registerAction(rc, id, context);
command->setAttribute(Core::Command::CA_Hide);
if (!keySequence.isEmpty())
command->setDefaultKeySequence(QKeySequence(keySequence));
@@ -677,11 +668,10 @@ QAction *FormEditorW::createEditModeAction(QActionGroup *ag,
}
// Create a tool action
-Core::Command *FormEditorW::addToolAction(QAction *a,
- const Core::Context &context, const Core::Id &id,
- Core::ActionContainer *c1, const QString &keySequence)
+Command *FormEditorW::addToolAction(QAction *a, const Context &context, const Id &id,
+ ActionContainer *c1, const QString &keySequence)
{
- Core::Command *command = Core::ActionManager::registerAction(a, id, context);
+ Command *command = ActionManager::registerAction(a, id, context);
if (!keySequence.isEmpty())
command->setDefaultKeySequence(QKeySequence(keySequence));
if (!a->isSeparator())
@@ -710,12 +700,12 @@ EditorData FormEditorW::createEditor(QWidget *parent)
qdesigner_internal::FormWindowBase::setupDefaultAction(form);
#endif
data.widgetHost = new SharedTools::WidgetHost( /* parent */ 0, form);
- DesignerXmlEditor *xmlEditor = new DesignerXmlEditor(form, parent);
- TextEditor::TextEditorSettings::instance()->initializeEditor(xmlEditor);
+ DesignerXmlEditorWidget *xmlEditor = new DesignerXmlEditorWidget(form, parent);
+ TextEditor::TextEditorSettings::initializeEditor(xmlEditor);
data.formWindowEditor = xmlEditor->designerEditor();
connect(data.widgetHost, SIGNAL(formWindowSizeChanged(int,int)),
xmlEditor, SIGNAL(changed()));
- connect(data.formWindowEditor->document(), SIGNAL(changed()),
+ connect(data.formWindowEditor->document(), SIGNAL(filePathChanged(QString,QString)),
resourceHandler, SLOT(updateResources()));
m_editorWidget->add(data);
@@ -726,7 +716,7 @@ EditorData FormEditorW::createEditor(QWidget *parent)
void FormEditorW::updateShortcut(QObject *command)
{
- Core::Command *c = qobject_cast<Core::Command *>(command);
+ Command *c = qobject_cast<Command *>(command);
if (!c)
return;
QAction *a = m_commandToDesignerAction.value(c);
@@ -735,7 +725,7 @@ void FormEditorW::updateShortcut(QObject *command)
a->setShortcut(c->action()->shortcut());
}
-void FormEditorW::currentEditorChanged(Core::IEditor *editor)
+void FormEditorW::currentEditorChanged(IEditor *editor)
{
if (Designer::Constants::Internal::debug)
qDebug() << Q_FUNC_INFO << editor << " of " << m_fwm->formWindowCount();
@@ -794,11 +784,10 @@ void FormEditorW::toolChanged(int t)
}
}
-void FormEditorW::closeFormEditorsForXmlEditors(QList<Core::IEditor*> editors)
+void FormEditorW::closeFormEditorsForXmlEditors(QList<IEditor*> editors)
{
- foreach (Core::IEditor *editor, editors) {
+ foreach (IEditor *editor, editors)
m_editorWidget->removeFormWindowEditor(editor);
- }
}
void FormEditorW::print()
@@ -808,7 +797,7 @@ void FormEditorW::print()
if (!fw)
return;
- QPrinter *printer = Core::ICore::printer();
+ QPrinter *printer = ICore::printer();
const bool oldFullPage = printer->fullPage();
const QPrinter::Orientation oldOrientation = printer->orientation ();
printer->setFullPage(false);
@@ -833,7 +822,7 @@ void FormEditorW::print()
if (!dialog.exec())
break;
- QWidget *mainWindow = Core::ICore::mainWindow();
+ QWidget *mainWindow = ICore::mainWindow();
const QCursor oldCursor = mainWindow->cursor();
mainWindow->setCursor(Qt::WaitCursor);
// Estimate of required scaling to make form look the same on screen and printer.
@@ -864,12 +853,11 @@ void FormEditorW::print()
// Find out current existing editor file
static QString currentFile()
{
- if (Core::IEditor *editor = Core::EditorManager::currentEditor())
- if (const Core::IDocument *document = editor->document()) {
- const QString fileName = document->fileName();
- if (!fileName.isEmpty() && QFileInfo(fileName).isFile())
- return fileName;
- }
+ if (const IDocument *document = EditorManager::currentDocument()) {
+ const QString fileName = document->filePath();
+ if (!fileName.isEmpty() && QFileInfo(fileName).isFile())
+ return fileName;
+ }
return QString();
}
@@ -881,18 +869,17 @@ static QString otherFile()
const QString current = currentFile();
if (current.isEmpty())
return QString();
- const Core::MimeDatabase *mdb = Core::ICore::mimeDatabase();
- const Core::MimeType currentMimeType = mdb->findByFile(current);
+ const MimeType currentMimeType = MimeDatabase::findByFile(current);
if (!currentMimeType)
return QString();
// Determine potential suffixes of candidate files
// 'ui' -> 'cpp', 'cpp/h' -> 'ui'.
QStringList candidateSuffixes;
if (currentMimeType.type() == QLatin1String(FORM_MIMETYPE)) {
- candidateSuffixes += mdb->findByType(QLatin1String(CppTools::Constants::CPP_SOURCE_MIMETYPE)).suffixes();
+ candidateSuffixes += MimeDatabase::findByType(QLatin1String(CppTools::Constants::CPP_SOURCE_MIMETYPE)).suffixes();
} else if (currentMimeType.type() == QLatin1String(CppTools::Constants::CPP_SOURCE_MIMETYPE)
|| currentMimeType.type() == QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE)) {
- candidateSuffixes += mdb->findByType(QLatin1String(FORM_MIMETYPE)).suffixes();
+ candidateSuffixes += MimeDatabase::findByType(QLatin1String(FORM_MIMETYPE)).suffixes();
} else {
return QString();
}
@@ -912,7 +899,7 @@ void FormEditorW::switchSourceForm()
{
const QString fileToOpen = otherFile();
if (!fileToOpen.isEmpty())
- Core::EditorManager::openEditor(fileToOpen);
+ EditorManager::openEditor(fileToOpen);
}
} // namespace Internal
diff --git a/src/plugins/designer/formwindoweditor.cpp b/src/plugins/designer/formwindoweditor.cpp
index d6234089ee..d6a46c29de 100644
--- a/src/plugins/designer/formwindoweditor.cpp
+++ b/src/plugins/designer/formwindoweditor.cpp
@@ -31,53 +31,36 @@
#include "formwindowfile.h"
#include "designerconstants.h"
#include "resourcehandler.h"
-#include "designerxmleditor.h"
+#include "designerxmleditorwidget.h"
#include <coreplugin/coreconstants.h>
#include <texteditor/basetextdocument.h>
#include <utils/qtcassert.h>
-#if QT_VERSION >= 0x050000
-# include <QDesignerFormWindowInterface>
-# include <QBuffer>
-#else
-# include "qt_private/formwindowbase_p.h"
-#endif
-
+#include <QBuffer>
#include <QDebug>
+#include <QDesignerFormWindowInterface>
#include <QFileInfo>
-#include <QApplication>
namespace Designer {
struct FormWindowEditorPrivate
{
- FormWindowEditorPrivate(Internal::DesignerXmlEditor *editor,
- QDesignerFormWindowInterface *form)
- : m_textEditor(editor), m_file(form)
- {}
-
- TextEditor::PlainTextEditor m_textEditor;
- Internal::FormWindowFile m_file;
+ Internal::DesignerXmlEditorWidget *m_widget;
};
-FormWindowEditor::FormWindowEditor(Internal::DesignerXmlEditor *editor,
- QDesignerFormWindowInterface *form,
- QObject *parent) :
- Core::IEditor(parent),
- d(new FormWindowEditorPrivate(editor, form))
+FormWindowEditor::FormWindowEditor(Internal::DesignerXmlEditorWidget *editor) :
+ TextEditor::PlainTextEditor(editor),
+ d(new FormWindowEditorPrivate)
{
+ d->m_widget = editor;
setContext(Core::Context(Designer::Constants::K_DESIGNER_XML_EDITOR_ID,
Designer::Constants::C_DESIGNER_XML_EDITOR));
- setWidget(d->m_textEditor.widget());
- connect(form, SIGNAL(changed()), this, SIGNAL(changed()));
// Revert to saved/load externally modified files.
- connect(&d->m_file, SIGNAL(reload(QString*,QString)), this, SLOT(slotOpen(QString*,QString)));
- // Force update of open editors model.
- connect(&d->m_file, SIGNAL(saved()), this, SIGNAL(changed()));
- connect(&d->m_file, SIGNAL(changed()), this, SIGNAL(changed()));
+ connect(d->m_widget->formWindowFile(), SIGNAL(reloadRequested(QString*,QString)),
+ this, SLOT(slotOpen(QString*,QString)), Qt::DirectConnection);
}
FormWindowEditor::~FormWindowEditor()
@@ -85,47 +68,6 @@ FormWindowEditor::~FormWindowEditor()
delete d;
}
-bool FormWindowEditor::createNew(const QString &contents)
-{
- if (Designer::Constants::Internal::debug)
- qDebug() << "FormWindowEditor::createNew" << contents.size();
-
- syncXmlEditor(QString());
-
- QDesignerFormWindowInterface *form = d->m_file.formWindow();
- QTC_ASSERT(form, return false);
-
- if (contents.isEmpty())
- return false;
-
- // If we have an override cursor, reset it over Designer loading,
- // should it pop up messages about missing resources or such.
- const bool hasOverrideCursor = QApplication::overrideCursor();
- QCursor overrideCursor;
- if (hasOverrideCursor) {
- overrideCursor = QCursor(*QApplication::overrideCursor());
- QApplication::restoreOverrideCursor();
- }
-
-#if QT_VERSION >= 0x050000
- const bool success = form->setContents(contents);
-#else
- form->setContents(contents);
- const bool success = form->mainContainer() != 0;
-#endif
-
- if (hasOverrideCursor)
- QApplication::setOverrideCursor(overrideCursor);
-
- if (!success)
- return false;
-
- syncXmlEditor(contents);
- d->m_file.setFileName(QString());
- d->m_file.setShouldAutoSave(false);
- return true;
-}
-
void FormWindowEditor::slotOpen(QString *errorString, const QString &fileName)
{
open(errorString, fileName, fileName);
@@ -136,19 +78,17 @@ bool FormWindowEditor::open(QString *errorString, const QString &fileName, const
if (Designer::Constants::Internal::debug)
qDebug() << "FormWindowEditor::open" << fileName;
- QDesignerFormWindowInterface *form = d->m_file.formWindow();
+ QDesignerFormWindowInterface *form = d->m_widget->formWindowFile()->formWindow();
QTC_ASSERT(form, return false);
- if (fileName.isEmpty()) {
- setDisplayName(tr("untitled"));
+ if (fileName.isEmpty())
return true;
- }
const QFileInfo fi(fileName);
const QString absfileName = fi.absoluteFilePath();
QString contents;
- if (d->m_file.read(absfileName, &contents, errorString) != Utils::TextFileFormat::ReadSuccess)
+ if (d->m_widget->formWindowFile()->read(absfileName, &contents, errorString) != Utils::TextFileFormat::ReadSuccess)
return false;
form->setFileName(absfileName);
@@ -165,16 +105,13 @@ bool FormWindowEditor::open(QString *errorString, const QString &fileName, const
return false;
#endif
form->setDirty(fileName != realFileName);
- syncXmlEditor(contents);
+ d->m_widget->formWindowFile()->syncXmlFromFormWindow();
- setDisplayName(fi.fileName());
- d->m_file.setFileName(absfileName);
- d->m_file.setShouldAutoSave(false);
+ d->m_widget->formWindowFile()->setFilePath(absfileName);
+ d->m_widget->formWindowFile()->setShouldAutoSave(false);
if (Internal::ResourceHandler *rh = form->findChild<Designer::Internal::ResourceHandler*>())
- rh->updateResources();
-
- emit changed();
+ rh->updateResources(true);
return true;
}
@@ -182,21 +119,8 @@ bool FormWindowEditor::open(QString *errorString, const QString &fileName, const
void FormWindowEditor::syncXmlEditor()
{
if (Designer::Constants::Internal::debug)
- qDebug() << "FormWindowEditor::syncXmlEditor" << d->m_file.fileName();
- syncXmlEditor(contents());
-}
-
-void FormWindowEditor::syncXmlEditor(const QString &contents)
-{
- d->m_textEditor.editorWidget()->setPlainText(contents);
- d->m_textEditor.editorWidget()->setReadOnly(true);
- static_cast<TextEditor::PlainTextEditorWidget *>
- (d->m_textEditor.editorWidget())->configure(document()->mimeType());
-}
-
-Core::IDocument *FormWindowEditor::document()
-{
- return &d->m_file;
+ qDebug() << "FormWindowEditor::syncXmlEditor" << d->m_widget->formWindowFile()->filePath();
+ d->m_widget->formWindowFile()->syncXmlFromFormWindow();
}
Core::Id FormWindowEditor::id() const
@@ -204,32 +128,6 @@ Core::Id FormWindowEditor::id() const
return Core::Id(Designer::Constants::K_DESIGNER_XML_EDITOR_ID);
}
-QString FormWindowEditor::displayName() const
-{
- return d->m_textEditor.displayName();
-}
-
-void FormWindowEditor::setDisplayName(const QString &title)
-{
- d->m_textEditor.setDisplayName(title);
- emit changed();
-}
-
-QByteArray FormWindowEditor::saveState() const
-{
- return d->m_textEditor.saveState();
-}
-
-bool FormWindowEditor::restoreState(const QByteArray &state)
-{
- return d->m_textEditor.restoreState(state);
-}
-
-bool FormWindowEditor::isTemporary() const
-{
- return false;
-}
-
QWidget *FormWindowEditor::toolBar()
{
return 0;
@@ -237,26 +135,7 @@ QWidget *FormWindowEditor::toolBar()
QString FormWindowEditor::contents() const
{
-#if QT_VERSION >= 0x050000 // TODO: No warnings about spacers here
- const QDesignerFormWindowInterface *fw = d->m_file.formWindow();
- QTC_ASSERT(fw, return QString());
- return fw->contents();
-#else
- // No warnings about spacers here
- const qdesigner_internal::FormWindowBase *fw = qobject_cast<const qdesigner_internal::FormWindowBase *>(d->m_file.formWindow());
- QTC_ASSERT(fw, return QString());
- return fw->fileContents();
-#endif
-}
-
-TextEditor::BaseTextDocument *FormWindowEditor::textDocument()
-{
- return qobject_cast<TextEditor::BaseTextDocument*>(d->m_textEditor.document());
-}
-
-TextEditor::PlainTextEditor *FormWindowEditor::textEditor()
-{
- return &d->m_textEditor;
+ return d->m_widget->formWindowFile()->formWindowContents();
}
bool FormWindowEditor::isDesignModePreferred() const
diff --git a/src/plugins/designer/formwindoweditor.h b/src/plugins/designer/formwindoweditor.h
index a04f417d16..a2f0549d86 100644
--- a/src/plugins/designer/formwindoweditor.h
+++ b/src/plugins/designer/formwindoweditor.h
@@ -32,6 +32,7 @@
#include "designer_export.h"
#include <coreplugin/editormanager/ieditor.h>
+#include <texteditor/plaintexteditor.h>
QT_BEGIN_NAMESPACE
class QDesignerFormWindowInterface;
@@ -45,39 +46,28 @@ namespace TextEditor {
namespace Designer {
namespace Internal {
- class DesignerXmlEditor;
+ class DesignerXmlEditorWidget;
}
struct FormWindowEditorPrivate;
-// The actual Core::IEditor belonging to Qt Designer. Uses FormWindowFile
-// as the Core::IDocument to do the isModified() handling,
-// which needs to be done by Qt Designer.
-// However, to make the read-only XML text editor work,
-// a TextEditor::PlainTextEditorEditable (IEditor) is also required.
-// It is aggregated and some functions are delegated to it.
+// IEditor that is used for the QDesignerFormWindowInterface
+// It is a read-only PlainTextEditor that shows the XML of the form.
+// DesignerXmlEditorWidget is the corresponding PlainTextEditorWidget,
+// FormWindowFile the corresponding BaseTextDocument.
+// The content from the QDesignerFormWindowInterface is synced to the
+// content of the XML editor.
-class DESIGNER_EXPORT FormWindowEditor : public Core::IEditor
+class DESIGNER_EXPORT FormWindowEditor : public TextEditor::PlainTextEditor
{
Q_PROPERTY(QString contents READ contents)
Q_OBJECT
public:
- explicit FormWindowEditor(Internal::DesignerXmlEditor *editor,
- QDesignerFormWindowInterface *form,
- QObject *parent = 0);
+ explicit FormWindowEditor(Internal::DesignerXmlEditorWidget *editor);
virtual ~FormWindowEditor();
// IEditor
- virtual bool createNew(const QString &contents = QString());
virtual bool open(QString *errorString, const QString &fileName, const QString &realFileName);
- virtual Core::IDocument *document();
virtual Core::Id id() const;
- virtual QString displayName() const;
- virtual void setDisplayName(const QString &title);
-
- virtual QByteArray saveState() const;
- virtual bool restoreState(const QByteArray &state);
-
- virtual bool isTemporary() const;
virtual QWidget *toolBar();
@@ -86,9 +76,6 @@ public:
// For uic code model support
QString contents() const;
- TextEditor::BaseTextDocument *textDocument();
- TextEditor::PlainTextEditor *textEditor();
-
public slots:
void syncXmlEditor();
@@ -96,8 +83,6 @@ private slots:
void slotOpen(QString *errorString, const QString &fileName);
private:
- void syncXmlEditor(const QString &contents);
-
FormWindowEditorPrivate *d;
};
diff --git a/src/plugins/designer/formwindowfile.cpp b/src/plugins/designer/formwindowfile.cpp
index 1aa35fc472..45a966569f 100644
--- a/src/plugins/designer/formwindowfile.cpp
+++ b/src/plugins/designer/formwindowfile.cpp
@@ -32,13 +32,16 @@
#include <utils/qtcassert.h>
+#include <QApplication>
#include <QDesignerFormWindowInterface>
#include <QDesignerFormWindowManagerInterface>
#include <QDesignerFormEditorInterface>
#if QT_VERSION < 0x050000
# include "qt_private/qsimpleresource_p.h"
+# include "qt_private/formwindowbase_p.h"
#endif
+#include <QTextDocument>
#include <QUndoStack>
#include <QFileInfo>
@@ -49,22 +52,24 @@ namespace Designer {
namespace Internal {
FormWindowFile::FormWindowFile(QDesignerFormWindowInterface *form, QObject *parent)
- : Core::TextDocument(parent),
- m_mimeType(QLatin1String(Designer::Constants::FORM_MIMETYPE)),
+ : m_mimeType(QLatin1String(Designer::Constants::FORM_MIMETYPE)),
m_shouldAutoSave(false),
- m_formWindow(form)
+ m_formWindow(form),
+ m_isModified(false)
{
+ setParent(parent);
// Designer needs UTF-8 regardless of settings.
setCodec(QTextCodec::codecForName("UTF-8"));
connect(m_formWindow->core()->formWindowManager(), SIGNAL(formWindowRemoved(QDesignerFormWindowInterface*)),
this, SLOT(slotFormWindowRemoved(QDesignerFormWindowInterface*)));
connect(m_formWindow->commandHistory(), SIGNAL(indexChanged(int)),
this, SLOT(setShouldAutoSave()));
+ connect(m_formWindow, SIGNAL(changed()), SLOT(updateIsModified()));
}
bool FormWindowFile::save(QString *errorString, const QString &name, bool autoSave)
{
- const QString actualName = name.isEmpty() ? fileName() : name;
+ const QString actualName = name.isEmpty() ? filePath() : name;
if (Designer::Constants::Internal::debug)
qDebug() << Q_FUNC_INFO << name << "->" << actualName;
@@ -94,31 +99,65 @@ bool FormWindowFile::save(QString *errorString, const QString &name, bool autoSa
return false;
}
- const QString oldFileName = m_fileName;
- m_fileName = fi.absoluteFilePath();
- emit setDisplayName(fi.fileName());
m_formWindow->setDirty(false);
- emit fileNameChanged(oldFileName, m_fileName);
+ setFilePath(fi.absoluteFilePath());
emit changed();
- emit saved();
return true;
}
-void FormWindowFile::rename(const QString &newName)
+bool FormWindowFile::setContents(const QByteArray &contents)
+{
+ if (Designer::Constants::Internal::debug)
+ qDebug() << Q_FUNC_INFO << contents.size();
+
+ document()->setPlainText(QString());
+
+ QTC_ASSERT(m_formWindow, return false);
+
+ if (contents.isEmpty())
+ return false;
+
+ // If we have an override cursor, reset it over Designer loading,
+ // should it pop up messages about missing resources or such.
+ const bool hasOverrideCursor = QApplication::overrideCursor();
+ QCursor overrideCursor;
+ if (hasOverrideCursor) {
+ overrideCursor = QCursor(*QApplication::overrideCursor());
+ QApplication::restoreOverrideCursor();
+ }
+
+#if QT_VERSION >= 0x050000
+ const bool success = m_formWindow->setContents(QString::fromUtf8(contents));
+#else
+ m_formWindow->setContents(QString::fromUtf8(contents));
+ const bool success = m_formWindow->mainContainer() != 0;
+#endif
+
+ if (hasOverrideCursor)
+ QApplication::setOverrideCursor(overrideCursor);
+
+ if (!success)
+ return false;
+
+ syncXmlFromFormWindow();
+ setShouldAutoSave(false);
+ return true;
+}
+
+void FormWindowFile::setFilePath(const QString &newName)
{
m_formWindow->setFileName(newName);
- QFileInfo fi(newName);
- const QString oldFileName = m_fileName;
- m_fileName = fi.absoluteFilePath();
- emit setDisplayName(fi.fileName());
- emit fileNameChanged(oldFileName, m_fileName);
- emit changed();
+ IDocument::setFilePath(newName);
}
-QString FormWindowFile::fileName() const
+void FormWindowFile::updateIsModified()
{
- return m_fileName;
+ bool value = m_formWindow && m_formWindow->isDirty();
+ if (value == m_isModified)
+ return;
+ m_isModified = value;
+ emit changed();
}
bool FormWindowFile::shouldAutoSave() const
@@ -144,7 +183,7 @@ bool FormWindowFile::reload(QString *errorString, ReloadFlag flag, ChangeType ty
emit changed();
} else {
emit aboutToReload();
- emit reload(errorString, m_fileName);
+ emit reloadRequested(errorString, filePath());
const bool success = errorString->isEmpty();
emit reloadFinished(success);
return success;
@@ -157,12 +196,12 @@ QString FormWindowFile::defaultPath() const
return QString();
}
-void FormWindowFile::setSuggestedFileName(const QString &fileName)
+void FormWindowFile::setSuggestedFileName(const QString &fn)
{
if (Designer::Constants::Internal::debug)
- qDebug() << Q_FUNC_INFO << m_fileName << fileName;
+ qDebug() << Q_FUNC_INFO << filePath() << fn;
- m_suggestedName = fileName;
+ m_suggestedName = fn;
}
QString FormWindowFile::suggestedFileName() const
@@ -175,21 +214,35 @@ QString FormWindowFile::mimeType() const
return m_mimeType;
}
-bool FormWindowFile::writeFile(const QString &fileName, QString *errorString) const
+bool FormWindowFile::writeFile(const QString &fn, QString *errorString) const
{
if (Designer::Constants::Internal::debug)
- qDebug() << Q_FUNC_INFO << m_fileName << fileName;
- return write(fileName, format(), m_formWindow->contents(), errorString);
+ qDebug() << Q_FUNC_INFO << filePath() << fn;
+ return write(fn, format(), m_formWindow->contents(), errorString);
}
-void FormWindowFile::setFileName(const QString &fname)
+QDesignerFormWindowInterface *FormWindowFile::formWindow() const
{
- m_fileName = fname;
+ return m_formWindow;
}
-QDesignerFormWindowInterface *FormWindowFile::formWindow() const
+void FormWindowFile::syncXmlFromFormWindow()
{
- return m_formWindow;
+ document()->setPlainText(formWindowContents());
+}
+
+QString FormWindowFile::formWindowContents() const
+{
+#if QT_VERSION >= 0x050000 // TODO: No warnings about spacers here
+ QTC_ASSERT(m_formWindow, return QString());
+ return m_formWindow->contents();
+#else
+ // No warnings about spacers here
+ const qdesigner_internal::FormWindowBase *fw =
+ qobject_cast<const qdesigner_internal::FormWindowBase *>(m_formWindow);
+ QTC_ASSERT(fw, return QString());
+ return fw->fileContents();
+#endif
}
void FormWindowFile::slotFormWindowRemoved(QDesignerFormWindowInterface *w)
diff --git a/src/plugins/designer/formwindowfile.h b/src/plugins/designer/formwindowfile.h
index 9df02334b7..6edbc37418 100644
--- a/src/plugins/designer/formwindowfile.h
+++ b/src/plugins/designer/formwindowfile.h
@@ -30,7 +30,7 @@
#ifndef FORMWINDOWFILE_H
#define FORMWINDOWFILE_H
-#include <coreplugin/textdocument.h>
+#include <texteditor/basetextdocument.h>
#include <QPointer>
@@ -42,24 +42,24 @@ QT_END_NAMESPACE
namespace Designer {
namespace Internal {
-class FormWindowFile : public Core::TextDocument
+class FormWindowFile : public TextEditor::BaseTextDocument
{
Q_OBJECT
public:
explicit FormWindowFile(QDesignerFormWindowInterface *form, QObject *parent = 0);
+ ~FormWindowFile() { }
// IDocument
- virtual bool save(QString *errorString, const QString &fileName, bool autoSave);
- virtual QString fileName() const;
- virtual bool shouldAutoSave() const;
- virtual bool isModified() const;
- virtual bool isSaveAsAllowed() const;
+ bool save(QString *errorString, const QString &fileName, bool autoSave);
+ bool setContents(const QByteArray &contents);
+ bool shouldAutoSave() const;
+ bool isModified() const;
+ bool isSaveAsAllowed() const;
bool reload(QString *errorString, ReloadFlag flag, ChangeType type);
- virtual QString defaultPath() const;
- virtual QString suggestedFileName() const;
- virtual QString mimeType() const;
- virtual void rename(const QString &newName);
+ QString defaultPath() const;
+ QString suggestedFileName() const;
+ QString mimeType() const;
// Internal
void setSuggestedFileName(const QString &fileName);
@@ -67,16 +67,17 @@ public:
bool writeFile(const QString &fileName, QString *errorString) const;
QDesignerFormWindowInterface *formWindow() const;
+ void syncXmlFromFormWindow();
+ QString formWindowContents() const;
signals:
// Internal
- void saved();
- void reload(QString *errorString, const QString &);
- void setDisplayName(const QString &);
+ void reloadRequested(QString *errorString, const QString &);
public slots:
- void setFileName(const QString &);
+ void setFilePath(const QString &);
void setShouldAutoSave(bool sad = true) { m_shouldAutoSave = sad; }
+ void updateIsModified();
private slots:
void slotFormWindowRemoved(QDesignerFormWindowInterface *w);
@@ -84,12 +85,12 @@ private slots:
private:
const QString m_mimeType;
- QString m_fileName;
QString m_suggestedName;
bool m_shouldAutoSave;
// Might actually go out of scope before the IEditor due
// to deleting the WidgetHost which owns it.
QPointer<QDesignerFormWindowInterface> m_formWindow;
+ bool m_isModified;
};
} // namespace Internal
diff --git a/src/plugins/designer/formwizard.cpp b/src/plugins/designer/formwizard.cpp
index 0057c7bc21..ac26d732cc 100644
--- a/src/plugins/designer/formwizard.cpp
+++ b/src/plugins/designer/formwizard.cpp
@@ -37,14 +37,9 @@
using namespace Designer;
using namespace Designer::Internal;
-FormWizard::FormWizard(const BaseFileWizardParameters &parameters, QObject *parent)
- : Core::BaseFileWizard(parameters, parent)
+FormWizard::FormWizard()
{
-}
-
-Core::FeatureSet FormWizard::requiredFeatures() const
-{
- return Core::Feature(QtSupport::Constants::FEATURE_QWIDGETS);
+ addRequiredFeature(Core::Id(QtSupport::Constants::FEATURE_QWIDGETS));
}
QWizard *FormWizard::createWizardDialog(QWidget *parent,
diff --git a/src/plugins/designer/formwizard.h b/src/plugins/designer/formwizard.h
index 24bbdf4073..988a9b11f7 100644
--- a/src/plugins/designer/formwizard.h
+++ b/src/plugins/designer/formwizard.h
@@ -40,17 +40,13 @@ class FormWizard : public Core::BaseFileWizard
Q_OBJECT
public:
- typedef Core::BaseFileWizardParameters BaseFileWizardParameters;
+ FormWizard();
- FormWizard(const BaseFileWizardParameters &parameters, QObject *parent);
-
- virtual Core::FeatureSet requiredFeatures() const;
-
-protected:
- virtual QWizard *createWizardDialog(QWidget *parent,
+private:
+ QWizard *createWizardDialog(QWidget *parent,
const Core::WizardDialogParameters &wizardDialogParameters) const;
- virtual Core::GeneratedFiles generateFiles(const QWizard *w,
+ Core::GeneratedFiles generateFiles(const QWizard *w,
QString *errorMessage) const;
};
diff --git a/src/plugins/designer/gotoslot_test.cpp b/src/plugins/designer/gotoslot_test.cpp
new file mode 100644
index 0000000000..ef9ed56828
--- /dev/null
+++ b/src/plugins/designer/gotoslot_test.cpp
@@ -0,0 +1,161 @@
+/****************************************************************************
+**
+** 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 "formeditorplugin.h"
+
+#if QT_VERSION < 0x050000
+#include <QtTest>
+#else
+#include "formeditorw.h"
+
+#include <coreplugin/testdatadir.h>
+#include <coreplugin/editormanager/editormanager.h>
+#include <cpptools/cppmodelmanager.h>
+
+#include <cplusplus/CppDocument.h>
+#include <cplusplus/Overview.h>
+
+#include <QDesignerFormEditorInterface>
+#include <QDesignerIntegrationInterface>
+#include <QStringList>
+#include <QtTest>
+
+using namespace Core;
+using namespace Core::Internal::Tests;
+using namespace CppTools;
+using namespace CPlusPlus;
+using namespace Designer;
+using namespace Designer::Internal;
+
+namespace {
+
+class MyTestDataDir : public Core::Internal::Tests::TestDataDir {
+public:
+ MyTestDataDir(const QString &dir)
+ : TestDataDir(QLatin1String(SRCDIR "/../../../tests/designer/") + dir)
+ {}
+};
+
+bool containsSymbol(Scope *scope, const QString &functionName)
+{
+ Overview oo;
+ for (int i = 0, end = scope->memberCount(); i < end; ++i) {
+ Symbol *symbol = scope->memberAt(i);
+ const QString symbolName = oo.prettyName(symbol->name());
+ if (symbolName == functionName)
+ return true;
+ }
+ return false;
+}
+
+class GoToSlotTest
+{
+public:
+ GoToSlotTest() : m_modelManager(CppModelManagerInterface::instance()) { cleanup(); }
+ ~GoToSlotTest() { cleanup(); }
+
+ void run() const
+ {
+ MyTestDataDir testData(QLatin1String("gotoslot_withoutProject"));
+ const QString cppFile = testData.file(QLatin1String("form.cpp"));
+ const QString hFile = testData.file(QLatin1String("form.h"));
+ const QString uiFile = testData.file(QLatin1String("form.ui"));
+ const QStringList files = QStringList() << cppFile << hFile << uiFile;
+
+ const QString functionName = QLatin1String("on_pushButton_clicked");
+ const QString qualifiedFunctionName = QLatin1String("Form::") + functionName;
+
+ foreach (const QString &file, files)
+ QVERIFY(EditorManager::openEditor(file));
+ QCOMPARE(EditorManager::documentModel()->openedDocuments().size(), files.size());
+ while (!m_modelManager->snapshot().contains(cppFile)
+ || !m_modelManager->snapshot().contains(hFile)) {
+ QApplication::processEvents();
+ }
+
+ // Checks before
+ Document::Ptr cppDocumentBefore = m_modelManager->snapshot().document(cppFile);
+ QCOMPARE(cppDocumentBefore->globalSymbolCount(), 2U);
+ QVERIFY(!containsSymbol(cppDocumentBefore->globalNamespace(), qualifiedFunctionName));
+
+ Document::Ptr hDocumentBefore = m_modelManager->snapshot().document(hFile);
+ QCOMPARE(hDocumentBefore->globalSymbolAt(1)->asScope()->memberCount(), 3U);
+ QVERIFY(!containsSymbol(hDocumentBefore->globalSymbolAt(1)->asScope(), functionName));
+
+ // Execute "Go To Slot"
+ FormEditorW *few = FormEditorW::instance();
+ QDesignerIntegrationInterface *integration = few->designerEditor()->integration();
+ QVERIFY(integration);
+ integration->emitNavigateToSlot(QLatin1String("pushButton"), QLatin1String("clicked()"),
+ QStringList());
+ QApplication::processEvents();
+
+ // Checks after
+ m_modelManager->updateSourceFiles(QStringList() << cppFile << hFile).waitForFinished();
+
+ QCOMPARE(EditorManager::currentDocument()->filePath(), cppFile);
+ QVERIFY(EditorManager::currentDocument()->isModified());
+
+ Document::Ptr cppDocumentAfter = m_modelManager->snapshot().document(cppFile);
+ QCOMPARE(cppDocumentAfter->globalSymbolCount(), 3U);
+ QVERIFY(containsSymbol(cppDocumentAfter->globalNamespace(), qualifiedFunctionName));
+
+ Document::Ptr hDocumentAfter = m_modelManager->snapshot().document(hFile);
+ QCOMPARE(hDocumentAfter->globalSymbolAt(1)->asScope()->memberCount(), 4U);
+ QVERIFY(containsSymbol(hDocumentAfter->globalSymbolAt(1)->asScope(), functionName));
+ }
+
+private:
+ void cleanup()
+ {
+ EditorManager::closeAllEditors(/*askAboutModifiedEditors =*/ false);
+ QVERIFY(EditorManager::documentModel()->openedDocuments().isEmpty());
+
+ m_modelManager->GC();
+ QVERIFY(m_modelManager->snapshot().isEmpty());
+ }
+
+private:
+ CppModelManagerInterface *m_modelManager;
+};
+
+} // anonymous namespace
+#endif
+
+/// Check: Executes "Go To Slot..." on a QPushButton in a *.ui file and checks if the respective
+/// header and source files are updated.
+void Designer::Internal::FormEditorPlugin::test_gotoslot_withoutProject()
+{
+#if QT_VERSION >= 0x050000
+ GoToSlotTest test;
+ test.run();
+#else
+ QSKIP("Available only with >= Qt5", SkipSingle);
+#endif
+}
diff --git a/src/plugins/designer/qtcreatorintegration.cpp b/src/plugins/designer/qtcreatorintegration.cpp
index 956c1bc51d..1297a7f4ac 100644
--- a/src/plugins/designer/qtcreatorintegration.cpp
+++ b/src/plugins/designer/qtcreatorintegration.cpp
@@ -29,11 +29,12 @@
#include "qtcreatorintegration.h"
#include "formwindoweditor.h"
-#include "formclasswizardpage.h"
#include "formeditorw.h"
#include "editordata.h"
#include <widgethost.h>
+#include <designer/cpp/formclasswizardpage.h>
+#include <cpptools/cppmodelmanagerinterface.h>
#include <cpptools/cpptoolsconstants.h>
#include <cpptools/insertionpointlocator.h>
#include <cpptools/symbolfinder.h>
@@ -59,6 +60,7 @@ enum { indentation = 4 };
using namespace Designer::Internal;
using namespace CPlusPlus;
using namespace TextEditor;
+using namespace ProjectExplorer;
static QString msgClassNotFound(const QString &uiClassName, const QList<Document::Ptr> &docList)
{
@@ -131,15 +133,16 @@ static QList<Document::Ptr> findDocumentsIncluding(const Snapshot &docTable,
{
QList<Document::Ptr> docList;
foreach (const Document::Ptr &doc, docTable) { // we go through all documents
- const QStringList includes = doc->includedFiles();
- foreach (const QString &include, includes) {
+ const QList<Document::Include> includes = doc->resolvedIncludes()
+ + doc->unresolvedIncludes();
+ foreach (const Document::Include &include, includes) {
if (checkFileNameOnly) {
- const QFileInfo fi(include);
+ const QFileInfo fi(include.unresolvedFileName());
if (fi.fileName() == fileName) { // we are only interested in docs which includes fileName only
docList.append(doc);
}
} else {
- if (include == fileName)
+ if (include.resolvedFileName() == fileName)
docList.append(doc);
}
}
@@ -490,13 +493,13 @@ static Document::Ptr getParsedDocument(const QString &fileName,
CppTools::CppModelManagerInterface::WorkingCopy &workingCopy,
Snapshot &snapshot)
{
- QString src;
+ QByteArray src;
if (workingCopy.contains(fileName)) {
src = workingCopy.source(fileName);
} else {
Utils::FileReader reader;
if (reader.fetch(fileName)) // ### FIXME error reporting
- src = QString::fromLocal8Bit(reader.data()); // ### FIXME encoding
+ src = QString::fromLocal8Bit(reader.data()).toUtf8();
}
Document::Ptr doc = snapshot.preprocessedDocument(src, fileName);
@@ -517,7 +520,7 @@ bool QtCreatorIntegration::navigateToSlot(const QString &objectName,
const EditorData ed = m_few->activeEditor();
QTC_ASSERT(ed, return false);
- const QString currentUiFile = ed.formWindowEditor->document()->fileName();
+ const QString currentUiFile = ed.formWindowEditor->document()->filePath();
#if 0
return Designer::Internal::navigateToSlot(currentUiFile, objectName, signalSignature, parameterNames, errorMessage);
#endif
@@ -530,21 +533,28 @@ bool QtCreatorIntegration::navigateToSlot(const QString &objectName,
const QString uiFolder = fi.absolutePath();
const QString uicedName = QLatin1String("ui_") + fi.completeBaseName() + QLatin1String(".h");
- // Retrieve code model snapshot restricted to project of ui file.
- const ProjectExplorer::Project *uiProject = ProjectExplorer::ProjectExplorerPlugin::instance()->session()->projectForFile(currentUiFile);
- if (!uiProject) {
- *errorMessage = tr("Internal error: No project could be found for %1.").arg(currentUiFile);
- return false;
- }
+ // Retrieve code model snapshot restricted to project of ui file or the working copy.
Snapshot docTable = CppTools::CppModelManagerInterface::instance()->snapshot();
Snapshot newDocTable;
-
- for (Snapshot::iterator it = docTable.begin(); it != docTable.end(); ++it) {
- const ProjectExplorer::Project *project = ProjectExplorer::ProjectExplorerPlugin::instance()->session()->projectForFile(it.key());
- if (project == uiProject)
- newDocTable.insert(it.value());
+ const Project *uiProject = SessionManager::projectForFile(currentUiFile);
+ if (uiProject) {
+ Snapshot::const_iterator end = docTable.end();
+ for (Snapshot::iterator it = docTable.begin(); it != end; ++it) {
+ const Project *project = SessionManager::projectForFile(it.key());
+ if (project == uiProject)
+ newDocTable.insert(it.value());
+ }
+ } else {
+ const CppTools::CppModelManagerInterface::WorkingCopy workingCopy =
+ CppTools::CppModelManagerInterface::instance()->workingCopy();
+ QHashIterator<QString, QPair<QByteArray, unsigned> > it = workingCopy.iterator();
+ while (it.hasNext()) {
+ it.next();
+ const QString fileName = it.key();
+ if (fileName != CppTools::CppModelManagerInterface::configurationFileName())
+ newDocTable.insert(docTable.document(fileName));
+ }
}
-
docTable = newDocTable;
// take all docs, find the ones that include the ui_xx.h.
@@ -637,8 +647,7 @@ void QtCreatorIntegration::slotSyncSettingsToDesigner()
{
#if QT_VERSION > 0x040800
// Set promotion-relevant parameters on integration.
- const Core::MimeDatabase *mdb = Core::ICore::mimeDatabase();
- setHeaderSuffix(mdb->preferredSuffixByType(QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE)));
+ setHeaderSuffix(Core::MimeDatabase::preferredSuffixByType(QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE)));
setHeaderLowercase(FormClassWizardPage::lowercaseHeaderFiles());
#endif
}
diff --git a/src/plugins/designer/qtdesignerformclasscodegenerator.cpp b/src/plugins/designer/qtdesignerformclasscodegenerator.cpp
index 3ba68a498a..fb08bfb1d8 100644
--- a/src/plugins/designer/qtdesignerformclasscodegenerator.cpp
+++ b/src/plugins/designer/qtdesignerformclasscodegenerator.cpp
@@ -28,8 +28,8 @@
****************************************************************************/
#include "qtdesignerformclasscodegenerator.h"
-#include "formclasswizardparameters.h"
#include "formtemplatewizardpage.h"
+#include <designer/cpp/formclasswizardparameters.h>
#include <utils/codegeneration.h>
#include <coreplugin/icore.h>
diff --git a/src/plugins/designer/resourcehandler.cpp b/src/plugins/designer/resourcehandler.cpp
index bde77e5edb..aafa532698 100644
--- a/src/plugins/designer/resourcehandler.cpp
+++ b/src/plugins/designer/resourcehandler.cpp
@@ -45,10 +45,7 @@
#include <utils/qtcassert.h>
-using ProjectExplorer::NodesVisitor;
-using ProjectExplorer::ProjectNode;
-using ProjectExplorer::FolderNode;
-using ProjectExplorer::FileNode;
+using namespace ProjectExplorer;
namespace Designer {
namespace Internal {
@@ -92,7 +89,8 @@ ResourceHandler::ResourceHandler(qdesigner_internal::FormWindowBase *fw) :
QObject(fw),
m_form(fw),
m_sessionNode(0),
- m_sessionWatcher(0)
+ m_sessionWatcher(0),
+ m_handlingResources(false)
{
}
@@ -100,8 +98,8 @@ void ResourceHandler::ensureInitialized()
{
if (m_sessionNode)
return;
- ProjectExplorer::ProjectExplorerPlugin *pe = ProjectExplorer::ProjectExplorerPlugin::instance();
- m_sessionNode = pe->session()->sessionNode();
+
+ m_sessionNode = ProjectExplorer::SessionManager::sessionNode();
m_sessionWatcher = new ProjectExplorer::NodesWatcher();
connect(m_sessionWatcher, SIGNAL(filesAdded()), this, SLOT(updateResources()));
@@ -127,8 +125,11 @@ ResourceHandler::~ResourceHandler()
}
}
-void ResourceHandler::updateResources()
+void ResourceHandler::updateResources(bool updateProjectResources)
{
+ if (m_handlingResources)
+ return;
+
ensureInitialized();
const QString fileName = m_form->fileName();
@@ -137,9 +138,11 @@ void ResourceHandler::updateResources()
if (Designer::Constants::Internal::debug)
qDebug() << "ResourceHandler::updateResources()" << fileName;
- ProjectExplorer::ProjectExplorerPlugin *pe = ProjectExplorer::ProjectExplorerPlugin::instance();
- // filename could change in the meantime.
- ProjectExplorer::Project *project = pe->session()->projectForFile(fileName);
+ // Filename could change in the meantime.
+ Project *project = SessionManager::projectForFile(fileName);
+ const bool dirty = m_form->property("_q_resourcepathchanged").toBool();
+ if (dirty)
+ m_form->setDirty(true);
// Does the file belong to a project?
if (project) {
@@ -147,7 +150,29 @@ void ResourceHandler::updateResources()
ProjectNode *root = project->rootProjectNode();
QrcFilesVisitor qrcVisitor;
root->accept(&qrcVisitor);
- const QStringList projectQrcFiles = qrcVisitor.qrcFiles();
+ QStringList projectQrcFiles = qrcVisitor.qrcFiles();
+ // Check if the user has chosen to update the lacking resource inside designer
+ if (dirty && updateProjectResources) {
+ QStringList qrcPathsToBeAdded;
+ foreach (const QString &originalQrcPath, m_originalUiQrcPaths) {
+ if (!projectQrcFiles.contains(originalQrcPath) && !qrcPathsToBeAdded.contains(originalQrcPath))
+ qrcPathsToBeAdded.append(originalQrcPath);
+ }
+ if (!qrcPathsToBeAdded.isEmpty()) {
+ m_handlingResources = true;
+ root->addFiles(qrcPathsToBeAdded);
+ m_handlingResources = false;
+ projectQrcFiles += qrcPathsToBeAdded;
+ }
+ }
+
+ QStringList originalSorted = m_originalUiQrcPaths;
+ originalSorted.sort();
+ QStringList projectSorted = projectQrcFiles;
+ projectSorted.sort();
+ if (originalSorted != projectSorted)
+ m_form->setDirty(true);
+
#if QT_VERSION >= 0x050000
m_form->activateResourceFilePaths(projectQrcFiles);
m_form->setResourceFileSaveMode(QDesignerFormWindowInterface::SaveOnlyUsedResourceFiles);
diff --git a/src/plugins/designer/resourcehandler.h b/src/plugins/designer/resourcehandler.h
index 7249b0da49..400ecd7ab1 100644
--- a/src/plugins/designer/resourcehandler.h
+++ b/src/plugins/designer/resourcehandler.h
@@ -73,7 +73,7 @@ public:
virtual ~ResourceHandler();
public slots:
- void updateResources();
+ void updateResources(bool updateProjectResources = false);
private:
void ensureInitialized();
@@ -85,6 +85,7 @@ private:
QStringList m_originalUiQrcPaths;
ProjectExplorer::SessionNode *m_sessionNode;
ProjectExplorer::NodesWatcher *m_sessionWatcher;
+ bool m_handlingResources;
};
} // namespace Internal
diff --git a/src/plugins/diffeditor/DiffEditor.pluginspec.in b/src/plugins/diffeditor/DiffEditor.pluginspec.in
index a9e54ca481..2120f01108 100644
--- a/src/plugins/diffeditor/DiffEditor.pluginspec.in
+++ b/src/plugins/diffeditor/DiffEditor.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"DiffEditor\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"DiffEditor\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/diffeditor/diffeditor.cpp b/src/plugins/diffeditor/diffeditor.cpp
index 2c1245e439..32ae0c4f13 100644
--- a/src/plugins/diffeditor/diffeditor.cpp
+++ b/src/plugins/diffeditor/diffeditor.cpp
@@ -35,7 +35,6 @@
#include <coreplugin/icore.h>
#include <coreplugin/coreconstants.h>
-#include <QCoreApplication>
#include <QToolButton>
#include <QSpinBox>
#include <QStyle>
@@ -68,12 +67,6 @@ DiffEditor::~DiffEditor()
delete m_widget;
}
-bool DiffEditor::createNew(const QString &contents)
-{
- Q_UNUSED(contents)
- return true;
-}
-
bool DiffEditor::open(QString *errorString, const QString &fileName, const QString &realFileName)
{
Q_UNUSED(errorString)
@@ -87,19 +80,6 @@ Core::IDocument *DiffEditor::document()
return m_file;
}
-QString DiffEditor::displayName() const
-{
- if (m_displayName.isEmpty())
- m_displayName = QCoreApplication::translate("DiffEditor", Constants::DIFF_EDITOR_DISPLAY_NAME);
- return m_displayName;
-}
-
-void DiffEditor::setDisplayName(const QString &title)
-{
- m_displayName = title;
- emit changed();
-}
-
Core::Id DiffEditor::id() const
{
return Constants::DIFF_EDITOR_ID;
@@ -109,7 +89,7 @@ static QToolBar *createToolBar(const QWidget *someWidget)
{
// Create
QToolBar *toolBar = new QToolBar;
- toolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
+ toolBar->setToolButtonStyle(Qt::ToolButtonIconOnly);
const int size = someWidget->style()->pixelMetric(QStyle::PM_SmallIconSize);
toolBar->setIconSize(QSize(size, size));
diff --git a/src/plugins/diffeditor/diffeditor.h b/src/plugins/diffeditor/diffeditor.h
index 735b9a988d..0b469b4c79 100644
--- a/src/plugins/diffeditor/diffeditor.h
+++ b/src/plugins/diffeditor/diffeditor.h
@@ -60,13 +60,9 @@ public:
void clear(const QString &message);
// Core::IEditor
- bool createNew(const QString &contents);
bool open(QString *errorString, const QString &fileName, const QString &realFileName);
Core::IDocument *document();
- QString displayName() const;
- void setDisplayName(const QString &title);
Core::Id id() const;
- bool isTemporary() const { return true; }
DiffEditorWidget *editorWidget() const { return m_editorWidget; }
QWidget *toolBar();
@@ -86,7 +82,6 @@ private:
Internal::DiffEditorFile *m_file;
DiffEditorWidget *m_editorWidget;
QComboBox *m_entriesComboBox;
- mutable QString m_displayName;
};
} // namespace DiffEditor
diff --git a/src/plugins/diffeditor/diffeditorfactory.cpp b/src/plugins/diffeditor/diffeditorfactory.cpp
index 44363d69a7..1a84d13a08 100644
--- a/src/plugins/diffeditor/diffeditorfactory.cpp
+++ b/src/plugins/diffeditor/diffeditorfactory.cpp
@@ -39,19 +39,11 @@ namespace DiffEditor {
namespace Internal {
DiffEditorFactory::DiffEditorFactory(QObject *parent)
- : IEditorFactory(parent),
- m_mimeTypes(QLatin1String(Constants::DIFF_EDITOR_MIMETYPE))
+ : IEditorFactory(parent)
{
-}
-
-Core::Id DiffEditorFactory::id() const
-{
- return Constants::DIFF_EDITOR_ID;
-}
-
-QString DiffEditorFactory::displayName() const
-{
- return qApp->translate("DiffEditorFactory", Constants::DIFF_EDITOR_DISPLAY_NAME);
+ setId(Constants::DIFF_EDITOR_ID);
+ setDisplayName(qApp->translate("DiffEditorFactory", Constants::DIFF_EDITOR_DISPLAY_NAME));
+ addMimeType(QLatin1String(Constants::DIFF_EDITOR_MIMETYPE));
}
Core::IEditor *DiffEditorFactory::createEditor(QWidget *parent)
@@ -61,10 +53,5 @@ Core::IEditor *DiffEditorFactory::createEditor(QWidget *parent)
return editor;
}
-QStringList DiffEditorFactory::mimeTypes() const
-{
- return m_mimeTypes;
-}
-
} // namespace Internal
} // namespace DiffEditor
diff --git a/src/plugins/diffeditor/diffeditorfactory.h b/src/plugins/diffeditor/diffeditorfactory.h
index 28d702771f..a21af4d1fb 100644
--- a/src/plugins/diffeditor/diffeditorfactory.h
+++ b/src/plugins/diffeditor/diffeditorfactory.h
@@ -47,13 +47,7 @@ class DiffEditorFactory : public Core::IEditorFactory
public:
explicit DiffEditorFactory(QObject *parent);
- QStringList mimeTypes() const;
Core::IEditor *createEditor(QWidget *parent);
- Core::Id id() const;
- QString displayName() const;
-
-private:
- const QStringList m_mimeTypes;
};
} // namespace Internal
diff --git a/src/plugins/diffeditor/diffeditorfile.cpp b/src/plugins/diffeditor/diffeditorfile.cpp
index ede0392bd2..43eb5f70d3 100644
--- a/src/plugins/diffeditor/diffeditorfile.cpp
+++ b/src/plugins/diffeditor/diffeditorfile.cpp
@@ -28,6 +28,9 @@
****************************************************************************/
#include "diffeditorfile.h"
+#include "diffeditorconstants.h"
+
+#include <QCoreApplication>
namespace DiffEditor {
namespace Internal {
@@ -39,20 +42,14 @@ DiffEditorFile::DiffEditorFile(const QString &mimeType, QObject *parent) :
m_mimeType(mimeType),
m_modified(false)
{
+ setDisplayName(QCoreApplication::translate("DiffEditor", Constants::DIFF_EDITOR_DISPLAY_NAME));
+ setTemporary(true);
}
-void DiffEditorFile::rename(const QString &newName)
-{
- Q_UNUSED(newName);
- return;
-}
-
-void DiffEditorFile::setFileName(const QString &name)
+bool DiffEditorFile::setContents(const QByteArray &contents)
{
- if (m_fileName == name)
- return;
- m_fileName = name;
- emit changed();
+ Q_UNUSED(contents);
+ return true;
}
void DiffEditorFile::setModified(bool modified)
diff --git a/src/plugins/diffeditor/diffeditorfile.h b/src/plugins/diffeditor/diffeditorfile.h
index 4a45fb4aa5..261701c2bd 100644
--- a/src/plugins/diffeditor/diffeditorfile.h
+++ b/src/plugins/diffeditor/diffeditorfile.h
@@ -48,7 +48,7 @@ public:
explicit DiffEditorFile(const QString &mimeType,
QObject *parent = 0);
- QString fileName() const { return m_fileName; }
+ bool setContents(const QByteArray &contents);
QString defaultPath() const { return QString(); }
QString suggestedFileName() const { return QString(); }
@@ -58,9 +58,7 @@ public:
bool save(QString *errorString, const QString &fileName, bool autoSave);
ReloadBehavior reloadBehavior(ChangeTrigger state, ChangeType type) const;
bool reload(QString *errorString, ReloadFlag flag, ChangeType type);
- void rename(const QString &newName);
- void setFileName(const QString &name);
void setModified(bool modified = true);
signals:
@@ -69,7 +67,6 @@ signals:
private:
const QString m_mimeType;
bool m_modified;
- QString m_fileName;
};
} // namespace Internal
diff --git a/src/plugins/diffeditor/diffeditorplugin.cpp b/src/plugins/diffeditor/diffeditorplugin.cpp
index 784e0810e6..6bbf6cfbef 100644
--- a/src/plugins/diffeditor/diffeditorplugin.cpp
+++ b/src/plugins/diffeditor/diffeditorplugin.cpp
@@ -45,7 +45,6 @@
#include <coreplugin/editormanager/editormanager.h>
namespace DiffEditor {
-
namespace Internal {
DiffEditorPlugin::DiffEditorPlugin()
@@ -103,7 +102,7 @@ void DiffEditorPlugin::diff()
//: Editor title
QString title = tr("Diff \"%1\", \"%2\"").arg(fileName1).arg(fileName2);
DiffEditor *editor = qobject_cast<DiffEditor *>
- (Core::EditorManager::openEditorWithContents(editorId, &title, QString()));
+ (Core::EditorManager::openEditorWithContents(editorId, &title));
if (!editor)
return;
diff --git a/src/plugins/diffeditor/diffeditorwidget.cpp b/src/plugins/diffeditor/diffeditorwidget.cpp
index 1c80c97881..881423b97a 100644
--- a/src/plugins/diffeditor/diffeditorwidget.cpp
+++ b/src/plugins/diffeditor/diffeditorwidget.cpp
@@ -38,23 +38,28 @@
#include <QToolButton>
#include <texteditor/basetexteditor.h>
-#include <texteditor/snippets/snippeteditor.h>
#include <texteditor/basetextdocumentlayout.h>
+#include <texteditor/ihighlighterfactory.h>
#include <texteditor/syntaxhighlighter.h>
#include <texteditor/basetextdocument.h>
#include <texteditor/texteditorsettings.h>
#include <texteditor/fontsettings.h>
#include <texteditor/displaysettings.h>
+#include <texteditor/highlighterutils.h>
+#include <coreplugin/icore.h>
#include <coreplugin/minisplitter.h>
+#include <coreplugin/mimedatabase.h>
+
+#include <extensionsystem/pluginmanager.h>
#include <utils/tooltip/tipcontents.h>
#include <utils/tooltip/tooltip.h>
-static const int BASE_LEVEL = 0;
static const int FILE_LEVEL = 1;
static const int CHUNK_LEVEL = 2;
+using namespace Core;
using namespace TextEditor;
namespace DiffEditor {
@@ -103,7 +108,7 @@ struct FileData {
class DiffViewEditorEditable : public BaseTextEditor
{
-Q_OBJECT
+ Q_OBJECT
public:
DiffViewEditorEditable(BaseTextEditorWidget *editorWidget)
: BaseTextEditor(editorWidget)
@@ -113,34 +118,56 @@ public:
}
Core::Id id() const { return "DiffViewEditor"; }
- bool isTemporary() const { return false; }
private slots:
void slotTooltipRequested(TextEditor::ITextEditor *editor, const QPoint &globalPoint, int position);
};
+class MultiHighlighter : public SyntaxHighlighter
+{
+ Q_OBJECT
+public:
+ MultiHighlighter(DiffViewEditorWidget *editor, QTextDocument *document = 0);
+ ~MultiHighlighter();
+
+ virtual void setFontSettings(const TextEditor::FontSettings &fontSettings);
+ void setDocuments(const QList<QPair<DiffEditorWidget::DiffFileInfo, QString> > &documents);
+
+protected:
+ virtual void highlightBlock(const QString &text);
+
+private:
+ DiffViewEditorWidget *m_editor;
+ QMap<QString, IHighlighterFactory *> m_mimeTypeToHighlighterFactory;
+ QList<SyntaxHighlighter *> m_highlighters;
+ QList<QTextDocument *> m_documents;
+};
////////////////////////
-class DiffViewEditorWidget : public SnippetEditorWidget
+class DiffViewEditorWidget : public BaseTextEditorWidget
{
Q_OBJECT
public:
+ struct ExtendedFileInfo
+ {
+ DiffEditorWidget::DiffFileInfo fileInfo;
+ TextEditor::SyntaxHighlighter *highlighter;
+ };
+
DiffViewEditorWidget(QWidget *parent = 0);
- void setSyntaxHighlighter(SyntaxHighlighter *sh) {
- baseTextDocument()->setSyntaxHighlighter(sh);
- }
+ // TODO: remove me, codec should be taken from somewhere else
QTextCodec *codec() const {
return const_cast<QTextCodec *>(baseTextDocument()->codec());
}
- QMap<int, int> skippedLines() const { return m_skippedLines; }
+ // block number, file info
QMap<int, DiffEditorWidget::DiffFileInfo> fileInfo() const { return m_fileInfo; }
void setLineNumber(int blockNumber, int lineNumber);
- void setFileInfo(int blockNumber, const DiffEditorWidget::DiffFileInfo &fileInfo) { m_fileInfo[blockNumber] = fileInfo; setSeparator(blockNumber, true); }
+ void setFileInfo(int blockNumber, const DiffEditorWidget::DiffFileInfo &fileInfo);
void setSkippedLines(int blockNumber, int skippedLines) { m_skippedLines[blockNumber] = skippedLines; setSeparator(blockNumber, true); }
void setSeparator(int blockNumber, bool separator) { m_separators[blockNumber] = separator; }
bool isFileLine(int blockNumber) const { return m_fileInfo.contains(blockNumber); }
@@ -150,7 +177,8 @@ public:
void clearAll();
void clearAll(const QString &message);
void clearAllData();
- QTextBlock firstVisibleBlock() const { return SnippetEditorWidget::firstVisibleBlock(); }
+ QTextBlock firstVisibleBlock() const { return BaseTextEditorWidget::firstVisibleBlock(); }
+ void setDocuments(const QList<QPair<DiffEditorWidget::DiffFileInfo, QString> > &documents);
public slots:
void setDisplaySettings(const DisplaySettings &ds);
@@ -184,20 +212,104 @@ private:
const QTextBlock &block, int top);
void jumpToOriginalFile(const QTextCursor &cursor);
+ // block number, visual line number.
QMap<int, int> m_lineNumbers;
int m_lineNumberDigits;
- // block number, fileInfo
+ // block number, fileInfo. Set for file lines only.
QMap<int, DiffEditorWidget::DiffFileInfo> m_fileInfo;
- // block number, skipped lines
+ // block number, skipped lines. Set for chunk lines only.
QMap<int, int> m_skippedLines;
- // block number, separator. Separator used as lines alignment and inside skipped lines
+ // block number, separator. Set for file, chunk or span line.
QMap<int, bool> m_separators;
bool m_inPaintEvent;
QColor m_fileLineForeground;
QColor m_chunkLineForeground;
QColor m_textForeground;
+ MultiHighlighter *m_highlighter;
};
+MultiHighlighter::MultiHighlighter(DiffViewEditorWidget *editor, QTextDocument *document)
+ : SyntaxHighlighter(document),
+ m_editor(editor)
+{
+ const QList<IHighlighterFactory *> &factories =
+ ExtensionSystem::PluginManager::getObjects<TextEditor::IHighlighterFactory>();
+ foreach (IHighlighterFactory *factory, factories) {
+ QStringList mimeTypes = factory->mimeTypes();
+ foreach (const QString &mimeType, mimeTypes)
+ m_mimeTypeToHighlighterFactory.insert(mimeType, factory);
+ }
+}
+
+MultiHighlighter::~MultiHighlighter()
+{
+ setDocuments(QList<QPair<DiffEditorWidget::DiffFileInfo, QString> >());
+}
+
+void MultiHighlighter::setFontSettings(const TextEditor::FontSettings &fontSettings)
+{
+ foreach (SyntaxHighlighter *highlighter, m_highlighters) {
+ if (highlighter) {
+ highlighter->setFontSettings(fontSettings);
+ highlighter->rehighlight();
+ }
+ }
+}
+
+void MultiHighlighter::setDocuments(const QList<QPair<DiffEditorWidget::DiffFileInfo, QString> > &documents)
+{
+ // clear old documents
+ qDeleteAll(m_documents);
+ m_documents.clear();
+ qDeleteAll(m_highlighters);
+ m_highlighters.clear();
+
+ // create new documents
+ for (int i = 0; i < documents.count(); i++) {
+ DiffEditorWidget::DiffFileInfo fileInfo = documents.at(i).first;
+ const QString contents = documents.at(i).second;
+ QTextDocument *document = new QTextDocument(contents);
+ const MimeType mimeType = MimeDatabase::findByFile(QFileInfo(fileInfo.fileName));
+ SyntaxHighlighter *highlighter = 0;
+ if (const IHighlighterFactory *factory = m_mimeTypeToHighlighterFactory.value(mimeType.type())) {
+ highlighter = factory->createHighlighter();
+ if (highlighter)
+ highlighter->setDocument(document);
+ }
+ if (!highlighter) {
+ highlighter = createGenericSyntaxHighlighter(mimeType);
+ highlighter->setDocument(document);
+ }
+ m_documents.append(document);
+ m_highlighters.append(highlighter);
+ }
+}
+
+void MultiHighlighter::highlightBlock(const QString &text)
+{
+ Q_UNUSED(text)
+
+ QTextBlock block = currentBlock();
+ const int fileIndex = m_editor->fileIndexForBlockNumber(block.blockNumber());
+ if (fileIndex < 0)
+ return;
+
+ SyntaxHighlighter *currentHighlighter = m_highlighters.at(fileIndex);
+ if (!currentHighlighter)
+ return;
+
+ // find block in document
+ QTextDocument *currentDocument = m_documents.at(fileIndex);
+ if (!currentDocument)
+ return;
+
+ QTextBlock documentBlock = currentDocument->findBlockByNumber(
+ block.blockNumber() - m_editor->blockNumberForFileIndex(fileIndex));
+
+ QList<QTextLayout::FormatRange> formats = documentBlock.layout()->additionalFormats();
+ setExtraAdditionalFormats(block, formats);
+}
+
void DiffViewEditorEditable::slotTooltipRequested(TextEditor::ITextEditor *editor, const QPoint &globalPoint, int position)
{
DiffViewEditorWidget *ew = qobject_cast<DiffViewEditorWidget *>(editorWidget());
@@ -208,16 +320,15 @@ void DiffViewEditorEditable::slotTooltipRequested(TextEditor::ITextEditor *edito
QMap<int, DiffEditorWidget::DiffFileInfo>::const_iterator it
= fi.constFind(ew->document()->findBlock(position).blockNumber());
if (it != fi.constEnd()) {
- Utils::ToolTip::instance()->show(globalPoint,
- Utils::TextContent(it.value().fileName),
+ Utils::ToolTip::show(globalPoint, Utils::TextContent(it.value().fileName),
editor->widget());
} else {
- Utils::ToolTip::instance()->hide();
+ Utils::ToolTip::hide();
}
}
DiffViewEditorWidget::DiffViewEditorWidget(QWidget *parent)
- : SnippetEditorWidget(parent), m_lineNumberDigits(1), m_inPaintEvent(false)
+ : BaseTextEditorWidget(parent), m_lineNumberDigits(1), m_inPaintEvent(false)
{
DisplaySettings settings = displaySettings();
settings.m_textWrapping = false;
@@ -226,22 +337,25 @@ DiffViewEditorWidget::DiffViewEditorWidget(QWidget *parent)
settings.m_displayFoldingMarkers = true;
settings.m_markTextChanges = false;
settings.m_highlightBlocks = false;
- SnippetEditorWidget::setDisplaySettings(settings);
+ BaseTextEditorWidget::setDisplaySettings(settings);
setCodeFoldingSupported(true);
setFrameStyle(QFrame::NoFrame);
+
+ m_highlighter = new MultiHighlighter(this, baseTextDocument()->document());
+ baseTextDocument()->setSyntaxHighlighter(m_highlighter);
}
void DiffViewEditorWidget::setDisplaySettings(const DisplaySettings &ds)
{
DisplaySettings settings = displaySettings();
settings.m_visualizeWhitespace = ds.m_visualizeWhitespace;
- SnippetEditorWidget::setDisplaySettings(settings);
+ BaseTextEditorWidget::setDisplaySettings(settings);
}
void DiffViewEditorWidget::setFontSettings(const TextEditor::FontSettings &fs)
{
- SnippetEditorWidget::setFontSettings(fs);
+ BaseTextEditorWidget::setFontSettings(fs);
m_fileLineForeground = fs.formatFor(C_DIFF_FILE_LINE).foreground();
m_chunkLineForeground = fs.formatFor(C_DIFF_CONTEXT_LINE).foreground();
m_textForeground = fs.toTextCharFormat(C_TEXT).foreground().color();
@@ -319,6 +433,12 @@ void DiffViewEditorWidget::setLineNumber(int blockNumber, int lineNumber)
m_lineNumberDigits = qMax(m_lineNumberDigits, lineNumberString.count());
}
+void DiffViewEditorWidget::setFileInfo(int blockNumber, const DiffEditorWidget::DiffFileInfo &fileInfo)
+{
+ m_fileInfo[blockNumber] = fileInfo;
+ setSeparator(blockNumber, true);
+}
+
int DiffViewEditorWidget::blockNumberForFileIndex(int fileIndex) const
{
if (fileIndex < 0 || fileIndex >= m_fileInfo.count())
@@ -360,6 +480,7 @@ void DiffViewEditorWidget::clearAll(const QString &message)
clear();
clearAllData();
setPlainText(message);
+ m_highlighter->setDocuments(QList<QPair<DiffEditorWidget::DiffFileInfo, QString> >());
}
void DiffViewEditorWidget::clearAllData()
@@ -371,9 +492,14 @@ void DiffViewEditorWidget::clearAllData()
m_separators.clear();
}
+void DiffViewEditorWidget::setDocuments(const QList<QPair<DiffEditorWidget::DiffFileInfo, QString> > &documents)
+{
+ m_highlighter->setDocuments(documents);
+}
+
void DiffViewEditorWidget::scrollContentsBy(int dx, int dy)
{
- SnippetEditorWidget::scrollContentsBy(dx, dy);
+ BaseTextEditorWidget::scrollContentsBy(dx, dy);
// TODO: update only chunk lines
viewport()->update();
}
@@ -424,7 +550,7 @@ void DiffViewEditorWidget::mouseDoubleClickEvent(QMouseEvent *e)
e->accept();
return;
}
- SnippetEditorWidget::mouseDoubleClickEvent(e);
+ BaseTextEditorWidget::mouseDoubleClickEvent(e);
}
void DiffViewEditorWidget::jumpToOriginalFile(const QTextCursor &cursor)
@@ -445,7 +571,7 @@ void DiffViewEditorWidget::jumpToOriginalFile(const QTextCursor &cursor)
void DiffViewEditorWidget::paintEvent(QPaintEvent *e)
{
m_inPaintEvent = true;
- SnippetEditorWidget::paintEvent(e);
+ BaseTextEditorWidget::paintEvent(e);
m_inPaintEvent = false;
QPainter painter(viewport());
@@ -596,30 +722,31 @@ DiffEditorWidget::DiffEditorWidget(QWidget *parent)
m_syncScrollBars(true),
m_foldingBlocker(false)
{
- TextEditor::TextEditorSettings *settings = TextEditorSettings::instance();
-
m_leftEditor = new DiffViewEditorWidget(this);
m_leftEditor->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
m_leftEditor->setReadOnly(true);
- connect(settings, SIGNAL(displaySettingsChanged(TextEditor::DisplaySettings)),
+ connect(TextEditorSettings::instance(),
+ SIGNAL(displaySettingsChanged(TextEditor::DisplaySettings)),
m_leftEditor, SLOT(setDisplaySettings(TextEditor::DisplaySettings)));
- m_leftEditor->setDisplaySettings(settings->displaySettings());
- m_leftEditor->setCodeStyle(settings->codeStyle());
+ m_leftEditor->setDisplaySettings(TextEditorSettings::displaySettings());
+ m_leftEditor->setCodeStyle(TextEditorSettings::codeStyle());
connect(m_leftEditor, SIGNAL(jumpToOriginalFileRequested(int,int,int)),
this, SLOT(slotLeftJumpToOriginalFileRequested(int,int,int)));
m_rightEditor = new DiffViewEditorWidget(this);
m_rightEditor->setReadOnly(true);
- connect(settings, SIGNAL(displaySettingsChanged(TextEditor::DisplaySettings)),
+ connect(TextEditorSettings::instance(),
+ SIGNAL(displaySettingsChanged(TextEditor::DisplaySettings)),
m_rightEditor, SLOT(setDisplaySettings(TextEditor::DisplaySettings)));
- m_rightEditor->setDisplaySettings(settings->displaySettings());
- m_rightEditor->setCodeStyle(settings->codeStyle());
+ m_rightEditor->setDisplaySettings(TextEditorSettings::displaySettings());
+ m_rightEditor->setCodeStyle(TextEditorSettings::codeStyle());
connect(m_rightEditor, SIGNAL(jumpToOriginalFileRequested(int,int,int)),
this, SLOT(slotRightJumpToOriginalFileRequested(int,int,int)));
- connect(settings, SIGNAL(fontSettingsChanged(TextEditor::FontSettings)),
+ connect(TextEditorSettings::instance(),
+ SIGNAL(fontSettingsChanged(TextEditor::FontSettings)),
this, SLOT(setFontSettings(TextEditor::FontSettings)));
- setFontSettings(settings->fontSettings());
+ setFontSettings(TextEditorSettings::fontSettings());
connect(m_leftEditor->verticalScrollBar(), SIGNAL(valueChanged(int)),
this, SLOT(leftVSliderChanged()));
@@ -761,12 +888,22 @@ QTextCodec *DiffEditorWidget::codec() const
return const_cast<QTextCodec *>(m_leftEditor->codec());
}
-SnippetEditorWidget *DiffEditorWidget::leftEditor() const
+QString DiffEditorWidget::source() const
+{
+ return m_source;
+}
+
+void DiffEditorWidget::setSource(const QString &source)
+{
+ m_source = source;
+}
+
+BaseTextEditorWidget *DiffEditorWidget::leftEditor() const
{
return m_leftEditor;
}
-SnippetEditorWidget *DiffEditorWidget::rightEditor() const
+BaseTextEditorWidget *DiffEditorWidget::rightEditor() const
{
return m_rightEditor;
}
@@ -953,12 +1090,10 @@ ChunkData DiffEditorWidget::calculateOriginalData(const QList<Diff> &diffList) c
if (diff.command == Diff::Delete) {
leftLines.last() += line;
currentLeftPos += line.count();
- }
- else if (diff.command == Diff::Insert) {
+ } else if (diff.command == Diff::Insert) {
rightLines.last() += line;
currentRightPos += line.count();
- }
- else if (diff.command == Diff::Equal) {
+ } else if (diff.command == Diff::Equal) {
if ((line.count() || (j && j < lines.count() - 1)) && // don't treat empty ending line as a line to be aligned unless a line is a one char '/n' only.
currentLeftLine != lastAlignedLeftLine &&
currentRightLine != lastAlignedRightLine) {
@@ -1153,18 +1288,20 @@ void DiffEditorWidget::showDiff()
clear();
- QString leftText, rightText;
+ QList<QPair<DiffEditorWidget::DiffFileInfo, QString> > leftDocs, rightDocs;
+ QString leftTexts, rightTexts;
int blockNumber = 0;
QChar separator = QLatin1Char('\n');
for (int i = 0; i < m_contextFileData.count(); i++) {
+ QString leftText, rightText;
const FileData &contextFileData = m_contextFileData.at(i);
int leftLineNumber = 0;
int rightLineNumber = 0;
m_leftEditor->setFileInfo(blockNumber, contextFileData.leftFileInfo);
m_rightEditor->setFileInfo(blockNumber, contextFileData.rightFileInfo);
- leftText += separator;
- rightText += separator;
+ leftText = separator;
+ rightText = separator;
blockNumber++;
for (int j = 0; j < contextFileData.chunks.count(); j++) {
@@ -1202,13 +1339,20 @@ void DiffEditorWidget::showDiff()
blockNumber++;
}
}
+ leftTexts += leftText;
+ rightTexts += rightText;
+ leftDocs.append(qMakePair(contextFileData.leftFileInfo, leftText));
+ rightDocs.append(qMakePair(contextFileData.rightFileInfo, rightText));
}
- if (leftText.isEmpty() && rightText.isEmpty())
+ if (leftTexts.isEmpty() && rightTexts.isEmpty())
return;
- m_leftEditor->setPlainText(leftText);
- m_rightEditor->setPlainText(rightText);
+ m_leftEditor->setDocuments(leftDocs);
+ m_rightEditor->setDocuments(rightDocs);
+
+ m_leftEditor->setPlainText(leftTexts);
+ m_rightEditor->setPlainText(rightTexts);
colorDiff(m_contextFileData);
diff --git a/src/plugins/diffeditor/diffeditorwidget.h b/src/plugins/diffeditor/diffeditorwidget.h
index 3b82a4ccba..c1e11565ea 100644
--- a/src/plugins/diffeditor/diffeditorwidget.h
+++ b/src/plugins/diffeditor/diffeditorwidget.h
@@ -37,7 +37,6 @@
namespace TextEditor {
class BaseTextEditorWidget;
-class SnippetEditorWidget;
class FontSettings;
}
@@ -59,6 +58,7 @@ struct FileData;
class DIFFEDITOR_EXPORT DiffEditorWidget : public QWidget
{
+ Q_PROPERTY(QString source READ source WRITE setSource)
Q_OBJECT
public:
struct DiffFileInfo {
@@ -84,6 +84,9 @@ public:
void setDiff(const QList<DiffFilesContents> &diffFileList, const QString &workingDirectory = QString());
QTextCodec *codec() const;
+ QString source() const;
+ void setSource(const QString &source);
+
#ifdef WITH_TESTS
void testAssemblyRows();
#endif // WITH_TESTS
@@ -98,8 +101,8 @@ signals:
void navigatedToDiffFile(int diffFileIndex);
protected:
- TextEditor::SnippetEditorWidget *leftEditor() const;
- TextEditor::SnippetEditorWidget *rightEditor() const;
+ TextEditor::BaseTextEditorWidget *leftEditor() const;
+ TextEditor::BaseTextEditorWidget *rightEditor() const;
private slots:
void setFontSettings(const TextEditor::FontSettings &fontSettings);
@@ -152,6 +155,7 @@ private:
bool m_syncScrollBars;
bool m_foldingBlocker;
+ QString m_source;
QTextCharFormat m_fileLineFormat;
QTextCharFormat m_chunkLineFormat;
diff --git a/src/plugins/diffeditor/diffshoweditor.cpp b/src/plugins/diffeditor/diffshoweditor.cpp
index 9e586eebbb..3cc595f902 100644
--- a/src/plugins/diffeditor/diffshoweditor.cpp
+++ b/src/plugins/diffeditor/diffshoweditor.cpp
@@ -54,7 +54,6 @@ public:
DiffShowEditorWidgetEditable(BaseTextEditorWidget *editorWidget) : BaseTextEditor(editorWidget) {}
Core::Id id() const { return "DiffShowViewEditor"; }
- bool isTemporary() const { return false; }
};
class DiffShowEditorWidget : public BaseTextEditorWidget
@@ -110,6 +109,8 @@ void DiffShowEditorWidget::setDisplaySettings(const DisplaySettings &ds)
DiffShowEditor::DiffShowEditor(DiffEditorWidget *editorWidget)
: DiffEditor(editorWidget)
{
+ document()->setDisplayName(QCoreApplication::translate("DiffShowEditor",
+ Constants::DIFF_SHOW_EDITOR_DISPLAY_NAME));
QSplitter *splitter = new Core::MiniSplitter(Qt::Vertical);
m_diffShowWidget = new Internal::DiffShowEditorWidget(splitter);
m_diffShowWidget->setReadOnly(true);
@@ -117,14 +118,13 @@ DiffShowEditor::DiffShowEditor(DiffEditorWidget *editorWidget)
splitter->addWidget(editorWidget);
setWidget(splitter);
- TextEditorSettings *settings = TextEditorSettings::instance();
- connect(settings, SIGNAL(displaySettingsChanged(TextEditor::DisplaySettings)),
+ connect(TextEditorSettings::instance(), SIGNAL(displaySettingsChanged(TextEditor::DisplaySettings)),
m_diffShowWidget, SLOT(setDisplaySettings(TextEditor::DisplaySettings)));
- connect(settings, SIGNAL(fontSettingsChanged(TextEditor::FontSettings)),
+ connect(TextEditorSettings::instance(), SIGNAL(fontSettingsChanged(TextEditor::FontSettings)),
m_diffShowWidget, SLOT(setFontSettings(TextEditor::FontSettings)));
- m_diffShowWidget->setDisplaySettings(settings->displaySettings());
- m_diffShowWidget->setCodeStyle(settings->codeStyle());
- m_diffShowWidget->setFontSettings(settings->fontSettings());
+ m_diffShowWidget->setDisplaySettings(TextEditorSettings::displaySettings());
+ m_diffShowWidget->setCodeStyle(TextEditorSettings::codeStyle());
+ m_diffShowWidget->setFontSettings(TextEditorSettings::fontSettings());
}
DiffShowEditor::~DiffShowEditor()
@@ -136,19 +136,6 @@ void DiffShowEditor::setDescription(const QString &description)
m_diffShowWidget->setPlainText(description);
}
-QString DiffShowEditor::displayName() const
-{
- if (m_displayName.isEmpty())
- m_displayName = QCoreApplication::translate("DiffShowEditor", Constants::DIFF_SHOW_EDITOR_DISPLAY_NAME);
- return m_displayName;
-}
-
-void DiffShowEditor::setDisplayName(const QString &title)
-{
- m_displayName = title;
- emit changed();
-}
-
Core::Id DiffShowEditor::id() const
{
return Constants::DIFF_SHOW_EDITOR_ID;
diff --git a/src/plugins/diffeditor/diffshoweditor.h b/src/plugins/diffeditor/diffshoweditor.h
index c53a4c820a..cace93f73a 100644
--- a/src/plugins/diffeditor/diffshoweditor.h
+++ b/src/plugins/diffeditor/diffshoweditor.h
@@ -42,10 +42,6 @@ QT_END_NAMESPACE
namespace DiffEditor {
-namespace Internal {
-class DiffEditorFile;
-}
-
class DIFFEDITOR_EXPORT DiffShowEditor : public DiffEditor
{
Q_OBJECT
@@ -56,8 +52,6 @@ public:
public:
void setDescription(const QString &description);
// Core::IEditor
- QString displayName() const;
- void setDisplayName(const QString &title);
Core::Id id() const;
QWidget *toolBar();
@@ -69,7 +63,6 @@ private:
void updateEntryToolTip();
TextEditor::BaseTextEditorWidget *m_diffShowWidget;
- mutable QString m_displayName;
QToolButton *m_toggleDescriptionButton;
};
diff --git a/src/plugins/diffeditor/diffshoweditorfactory.cpp b/src/plugins/diffeditor/diffshoweditorfactory.cpp
index eaabf32268..6597795b50 100644
--- a/src/plugins/diffeditor/diffshoweditorfactory.cpp
+++ b/src/plugins/diffeditor/diffshoweditorfactory.cpp
@@ -39,19 +39,11 @@ namespace DiffEditor {
namespace Internal {
DiffShowEditorFactory::DiffShowEditorFactory(QObject *parent)
- : IEditorFactory(parent),
- m_mimeTypes(QLatin1String(Constants::DIFF_EDITOR_MIMETYPE))
+ : IEditorFactory(parent)
{
-}
-
-Core::Id DiffShowEditorFactory::id() const
-{
- return Constants::DIFF_SHOW_EDITOR_ID;
-}
-
-QString DiffShowEditorFactory::displayName() const
-{
- return qApp->translate("DiffEditorFactory", Constants::DIFF_SHOW_EDITOR_DISPLAY_NAME);
+ setId(Constants::DIFF_SHOW_EDITOR_ID);
+ setDisplayName(qApp->translate("DiffEditorFactory", Constants::DIFF_SHOW_EDITOR_DISPLAY_NAME));
+ setMimeTypes(QStringList() << QLatin1String(Constants::DIFF_EDITOR_MIMETYPE));
}
Core::IEditor *DiffShowEditorFactory::createEditor(QWidget *parent)
@@ -61,10 +53,5 @@ Core::IEditor *DiffShowEditorFactory::createEditor(QWidget *parent)
return editor;
}
-QStringList DiffShowEditorFactory::mimeTypes() const
-{
- return m_mimeTypes;
-}
-
} // namespace Internal
} // namespace DiffEditor
diff --git a/src/plugins/diffeditor/diffshoweditorfactory.h b/src/plugins/diffeditor/diffshoweditorfactory.h
index 520b42ff3e..25f5285dbe 100644
--- a/src/plugins/diffeditor/diffshoweditorfactory.h
+++ b/src/plugins/diffeditor/diffshoweditorfactory.h
@@ -47,13 +47,7 @@ class DiffShowEditorFactory : public Core::IEditorFactory
public:
explicit DiffShowEditorFactory(QObject *parent);
- QStringList mimeTypes() const;
Core::IEditor *createEditor(QWidget *parent);
- Core::Id id() const;
- QString displayName() const;
-
-private:
- const QStringList m_mimeTypes;
};
} // namespace Internal
diff --git a/src/plugins/fakevim/FakeVim.pluginspec.in b/src/plugins/fakevim/FakeVim.pluginspec.in
index 1717e5e680..f42f3a7175 100644
--- a/src/plugins/fakevim/FakeVim.pluginspec.in
+++ b/src/plugins/fakevim/FakeVim.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"FakeVim\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"FakeVim\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/fakevim/fakevim.qbs b/src/plugins/fakevim/fakevim.qbs
index 17fa0a7e88..fc9dfcbe7d 100644
--- a/src/plugins/fakevim/fakevim.qbs
+++ b/src/plugins/fakevim/fakevim.qbs
@@ -1,7 +1,6 @@
import qbs.base 1.0
import "../QtcPlugin.qbs" as QtcPlugin
-import "../../../qbs/defaults.js" as Defaults
QtcPlugin {
name: "FakeVim"
@@ -23,7 +22,7 @@ QtcPlugin {
Group {
name: "Tests"
- condition: Defaults.testsEnabled(qbs)
+ condition: project.testsEnabled
files: ["fakevim_test.cpp"]
}
}
diff --git a/src/plugins/fakevim/fakevim_test.cpp b/src/plugins/fakevim/fakevim_test.cpp
index e946ae20da..6b9144da5d 100644
--- a/src/plugins/fakevim/fakevim_test.cpp
+++ b/src/plugins/fakevim/fakevim_test.cpp
@@ -274,13 +274,16 @@ void FakeVimPlugin::setup(TestData *data)
{
setupTest(&data->title, &data->handler, &data->edit);
data->reset();
- data->doCommand("set nopasskeys | set nopasscontrolkey");
+ data->doCommand("| set nopasskeys"
+ "| set nopasscontrolkey"
+ "| set smartindent"
+ "| set autoindent");
}
void FakeVimPlugin::cleanup()
{
- Core::EditorManager::instance()->closeAllEditors(false);
+ Core::EditorManager::closeAllEditors(false);
}
@@ -397,6 +400,12 @@ void FakeVimPlugin::test_vim_movement()
KEYS("2B", X "123 " "456.789 " "abc " "def");
KEYS("4W", "123 " "456.789 " "abc " "de" X "f");
+ data.setText("assert(abc);");
+ KEYS("w", "assert" X "(abc);");
+ KEYS("w", "assert(" X "abc);");
+ KEYS("w", "assert(abc" X ");");
+ KEYS("w", "assert(abc)" X ";");
+
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.
@@ -454,6 +463,79 @@ void FakeVimPlugin::test_vim_movement()
data.setText("abc def");
KEYS("}", "abc de" X "f");
KEYS("{", X "abc def");
+
+ // bracket movement commands
+ data.setText(
+ "void a()" N
+ "{" N
+ "}" N "" N "int b()" N
+ "{ return 0; }" N "" N "int c()" N
+ "{ return 0;" N
+ "}" N
+ "");
+
+ KEYS("]]",
+ "void a()" N
+ X "{" N
+ "}" N "" N "int b()" N
+ "{ return 0; }" N "" N "int c()" N
+ "{ return 0;" N
+ "}" N
+ "");
+
+ KEYS("]]",
+ "void a()" N
+ "{" N
+ "}" N "" N "int b()" N
+ X "{ return 0; }" N "" N "int c()" N
+ "{ return 0;" N
+ "}" N
+ "");
+
+ KEYS("2[[",
+ X "void a()" N
+ "{" N
+ "}" N "" N "int b()" N
+ "{ return 0; }" N "" N "int c()" N
+ "{ return 0;" N
+ "}" N
+ "");
+
+ KEYS("4]]",
+ "void a()" N
+ "{" N
+ "}" N "" N "int b()" N
+ "{ return 0; }" N "" N "int c()" N
+ "{ return 0;" N
+ "}" N
+ X "");
+
+ KEYS("2[]",
+ "void a()" N
+ "{" N
+ X "}" N "" N "int b()" N
+ "{ return 0; }" N "" N "int c()" N
+ "{ return 0;" N
+ "}" N
+ "");
+
+ KEYS("][",
+ "void a()" N
+ "{" N
+ "}" N "" N "int b()" N
+ "{ return 0; }" N "" N "int c()" N
+ "{ return 0;" N
+ X "}" N
+ "");
+
+ KEYS("][",
+ "void a()" N
+ "{" N
+ "}" N "" N "int b()" N
+ "{ return 0; }" N "" N "int c()" N
+ "{ return 0;" N
+ "}" N
+ X "");
}
void FakeVimPlugin::test_vim_insert()
@@ -620,6 +702,17 @@ void FakeVimPlugin::test_vim_fFtT()
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");
+
+ data.setText("abc def" N "ghi " X "jkl");
+ KEYS("vFgx", "abc def" N X "kl");
+ KEYS("u", "abc def" N X "ghi jkl");
+ KEYS("tk", "abc def" N "ghi " X "jkl");
+ KEYS("dTg", "abc def" N "g" X "jkl");
+ INTEGRITY(false);
+ KEYS("u", "abc def" N "g" X "hi jkl");
+ KEYS("f .", "abc def" N "g" X " jkl");
+ KEYS("u", "abc def" N "g" X "hi jkl");
+ KEYS("rg$;", "abc def" N "gg" X "i jkl");
}
void FakeVimPlugin::test_vim_transform_numbers()
@@ -809,6 +902,61 @@ void FakeVimPlugin::test_vim_delete()
data.setText("abc" N "def");
KEYS("2lvox", "a" X "b" N "def");
KEYS("vlox", "a" X "def");
+
+ // bracket movement command
+ data.setText(
+ "void a()" N
+ "{" N
+ "}" N "" N "int b()" N
+ "{ return 0; }" N "" N "int c()" N
+ "{ return 0;" N
+ "}" N
+ "");
+
+ KEYS("d]]",
+ X "{" N
+ "}" N "" N "int b()" N
+ "{ return 0; }" N "" N "int c()" N
+ "{ return 0;" N
+ "}" N
+ "");
+
+ KEYS("u",
+ X "void a()" N
+ "{" N
+ "}" N "" N "int b()" N
+ "{ return 0; }" N "" N "int c()" N
+ "{ return 0;" N
+ "}" N
+ "");
+
+ // When ]] is used after an operator, then also stops below a '}' in the first column.
+ KEYS("jd]]",
+ "void a()" N
+ X "" N "int b()" N
+ "{ return 0; }" N "" N "int c()" N
+ "{ return 0;" N
+ "}" N
+ "");
+
+ KEYS("u",
+ "void a()" N
+ X "{" N
+ "}" N "" N "int b()" N
+ "{ return 0; }" N "" N "int c()" N
+ "{ return 0;" N
+ "}" N
+ "");
+
+ // do nothing on failed movement
+ KEYS("Gd5[[",
+ "void a()" N
+ "{" N
+ "}" N "" N "int b()" N
+ "{ return 0; }" N "" N "int c()" N
+ "{ return 0;" N
+ "}" N
+ X "");
}
void FakeVimPlugin::test_vim_delete_inner_word()
@@ -1324,6 +1472,32 @@ void FakeVimPlugin::test_vim_search()
KEYS("N", "abc" N X "def" N "ghi");
KEYS("N", X "abc" N "def" N "ghi");
KEYS("2n2N", X "abc" N "def" N "ghi");
+
+ // delete to match
+ data.setText("abc" N "def" N "abc" N "ghi abc jkl" N "xyz");
+ KEYS("2l" "d/ghi<CR>", "ab" X "ghi abc jkl" N "xyz");
+
+ data.setText("abc" N "def" N "abc" N "ghi abc jkl" N "xyz");
+ KEYS("l" "d2/abc<CR>", "a" X "abc jkl" N "xyz");
+
+ data.setText("abc" N "def" N "abc" N "ghi abc jkl" N "xyz");
+ KEYS("d/abc<CR>", X "abc" N "ghi abc jkl" N "xyz");
+ KEYS(".", "abc jkl" N "xyz");
+
+ data.setText("abc" N "def" N "abc" N "ghi abc jkl" N "xyz");
+ KEYS("/abc<CR>" "l" "dn", "abc" N "def" N "a" X "abc jkl" N "xyz");
+
+ data.setText("abc" N "def" N "abc" N "ghi abc jkl" N "xyz");
+ KEYS("2/abc<CR>" "h" "dN", "abc" N "def" N X " abc jkl" N "xyz");
+ KEYS("c/xxx<CR><ESC>" "h" "dN", "abc" N "def" N X " abc jkl" N "xyz");
+
+ data.setText("abc" N "def" N "abc" N "ghi abc jkl" N "xyz");
+ KEYS("l" "v2/abc<CR>" "x", "abc jkl" N "xyz");
+
+ // don't leave visual mode after search failed or is cancelled
+ data.setText("abc" N "def" N "abc" N "ghi abc jkl" N "xyz");
+ KEYS("vj" "/abc<ESC>" "x", X "ef" N "abc" N "ghi abc jkl" N "xyz");
+ KEYS("vj" "/xxx<CR>" "x", X "bc" N "ghi abc jkl" N "xyz");
}
void FakeVimPlugin::test_vim_indent()
@@ -2375,6 +2549,21 @@ void FakeVimPlugin::test_map()
KEYS("f<space>", "abc" N "x " X " z" N "def");
KEYS("t<space>", "abc" N "x " X " z" N "def");
data.doCommand("unmap <SPACE>");
+
+ // operator-pending mappings
+ data.setText("abc def" N "ghi jkl");
+ data.doCommand("omap <SPACE> aw");
+ KEYS("c<space>X<esc>", X "Xdef" N "ghi jkl");
+ data.doCommand("onoremap <SPACE> iwX");
+ KEYS("c<space>Y<esc>", "X" X "Y" N "ghi jkl");
+ data.doCommand("ono <SPACE> l");
+ KEYS("d<space>", X "X" N "ghi jkl");
+ data.doCommand("unmap <SPACE>");
+
+ data.setText("abc def" N "ghi jkl");
+ data.doCommand("onoremap iwwX 3iwX Y");
+ KEYS("ciwwX Z<esc>", "X Y " X "Z" N "ghi jkl");
+ data.doCommand("unmap <SPACE>X");
}
void FakeVimPlugin::test_vim_command_cc()
@@ -3020,6 +3209,10 @@ void FakeVimPlugin::test_macros()
KEYS("@x", "def" N X "abc");
KEYS("gg@x", "abc" N X "def");
data.doCommand("unmap <S-down>");
+
+ data.setText(" abc xyz>." N " def xyz>." N " ghi xyz>." N " jkl xyz>.");
+ KEYS("qq" "^wdf>j" "q", " abc ." N " def " X "xyz>." N " ghi xyz>." N " jkl xyz>.");
+ KEYS("2@q", " abc ." N " def ." N " ghi ." N " jkl " X "xyz>.");
}
void FakeVimPlugin::test_vim_qtcreator()
@@ -3292,8 +3485,16 @@ void FakeVimPlugin::test_vim_qtcreator()
"");
// Record long insert mode.
- KEYS("qb" "4s" "bool" "<down>" "Q_<insert>ASSERT" "<down><down>" "<insert><bs>2"
- "<c-o>2w<delete>1" "<c-o>:s/true/false<cr><esc>" "q",
+ KEYS("qb"
+ "4s" "bool" // 1
+ "<down>"
+ "Q_<insert>ASSERT" // 2
+ "<down><down>"
+ "<insert><bs>2" // 3
+ "<c-o>2w"
+ "<delete>1" // 4
+ "<c-o>:s/true/false<cr><esc>" // 5
+ "q",
"bool f(int arg1, int arg2 = 0) {" N
" Q_ASSERT(arg1 >= 0);" N
" if (arg1 > 0) return true;" N
@@ -3301,35 +3502,35 @@ void FakeVimPlugin::test_vim_qtcreator()
"}" N
"");
- KEYS("u",
+ KEYS("u", // 5
"bool f(int arg1, int arg2 = 0) {" N
" Q_ASSERT(arg1 >= 0);" N
" if (arg1 > 0) return true;" N
X " if (arg2 > 1) return true;" N
"}" N
"");
- KEYS("u",
+ KEYS("u", // 4
"bool f(int arg1, int arg2 = 0) {" N
" Q_ASSERT(arg1 >= 0);" N
" if (arg1 > 0) return true;" N
" if (arg2 > " X "0) return true;" N
"}" N
"");
- KEYS("u",
+ KEYS("u", // 3
"bool f(int arg1, int arg2 = 0) {" N
" Q_ASSERT(arg1 >= 0);" N
" if (arg1 > 0) return true;" N
" if (arg1" X " > 0) return true;" N
"}" N
"");
- KEYS("u",
+ KEYS("u", // 2
"bool f(int arg1, int arg2 = 0) {" N
" " X "assert(arg1 >= 0);" N
" if (arg1 > 0) return true;" N
" if (arg1 > 0) return true;" N
"}" N
"");
- KEYS("u",
+ KEYS("u", // 1
X "void f(int arg1, int arg2 = 0) {" N
" assert(arg1 >= 0);" N
" if (arg1 > 0) return true;" N
@@ -3374,4 +3575,28 @@ void FakeVimPlugin::test_vim_qtcreator()
" if (arg2 > 1) return false;" N
"}" N
"");
+
+ // Macros
+ data.setText(
+ "void f(int arg1) {" N
+ "}" N
+ "");
+ KEYS("2o" "#ifdef HAS_FEATURE<cr>doSomething();<cr>"
+ "#else<cr>"
+ "doSomethingElse<bs><bs><bs><bs>2();<cr>"
+ "#endif"
+ "<esc>",
+ "void f(int arg1) {" N
+ "#ifdef HAS_FEATURE" N
+ " doSomething();" N
+ "#else" N
+ " doSomething2();" N
+ "#endif" N
+ "#ifdef HAS_FEATURE" N
+ " doSomething();" N
+ "#else" N
+ " doSomething2();" N
+ "#endi" X "f" N
+ "}" N
+ "");
}
diff --git a/src/plugins/fakevim/fakevimactions.h b/src/plugins/fakevim/fakevimactions.h
index c0b37867f9..982296e476 100644
--- a/src/plugins/fakevim/fakevimactions.h
+++ b/src/plugins/fakevim/fakevimactions.h
@@ -47,6 +47,8 @@ namespace Utils {
class SavedAction : public QObject
{
+ Q_OBJECT
+
public:
SavedAction(QObject *parent);
void setValue(const QVariant &value);
diff --git a/src/plugins/fakevim/fakevimhandler.cpp b/src/plugins/fakevim/fakevimhandler.cpp
index 7716c0094f..db4e001253 100644
--- a/src/plugins/fakevim/fakevimhandler.cpp
+++ b/src/plugins/fakevim/fakevimhandler.cpp
@@ -288,16 +288,16 @@ typedef QHashIterator<QChar, Mark> MarksIterator;
struct State
{
- State() : revisions(0), position(), marks(), lastVisualMode(NoVisualMode),
+ State() : revision(-1), position(), marks(), lastVisualMode(NoVisualMode),
lastVisualModeInverted(false) {}
- State(const CursorPosition &position, const Marks &marks,
- VisualMode lastVisualMode, bool lastVisualModeInverted) : revisions(0),
+ State(int revision, const CursorPosition &position, const Marks &marks,
+ VisualMode lastVisualMode, bool lastVisualModeInverted) : revision(revision),
position(position), marks(marks), lastVisualMode(lastVisualMode),
lastVisualModeInverted(lastVisualModeInverted) {}
bool isValid() const { return position.isValid(); }
- int revisions;
+ int revision;
CursorPosition position;
Marks marks;
VisualMode lastVisualMode;
@@ -584,6 +584,40 @@ static void searchBackward(QTextCursor *tc, QRegExp &needleExp, int *repeat)
tc->setPosition(block.position() + i);
}
+// Commands [[, []
+static void bracketSearchBackward(QTextCursor *tc, const QString &needleExp, int repeat)
+{
+ QRegExp re(needleExp);
+ QTextCursor tc2 = *tc;
+ tc2.setPosition(tc2.position() - 1);
+ searchBackward(&tc2, re, &repeat);
+ if (repeat <= 1)
+ tc->setPosition(tc2.isNull() ? 0 : tc2.position(), KeepAnchor);
+}
+
+// Commands ][, ]]
+// When ]] is used after an operator, then also stops below a '}' in the first column.
+static void bracketSearchForward(QTextCursor *tc, const QString &needleExp, int repeat,
+ bool searchWithCommand)
+{
+ QRegExp re(searchWithCommand ? QString(_("^\\}|^\\{")) : needleExp);
+ QTextCursor tc2 = *tc;
+ tc2.setPosition(tc2.position() + 1);
+ searchForward(&tc2, re, &repeat);
+ if (repeat <= 1) {
+ if (tc2.isNull()) {
+ tc->setPosition(tc->document()->characterCount() - 1, KeepAnchor);
+ } else {
+ tc->setPosition(tc2.position() - 1, KeepAnchor);
+ if (searchWithCommand && tc->document()->characterAt(tc->position()).unicode() == '}') {
+ QTextBlock block = tc->block().next();
+ if (block.isValid())
+ tc->setPosition(block.position(), KeepAnchor);
+ }
+ }
+ }
+}
+
static bool substituteText(QString *text, QRegExp &pattern, const QString &replacement,
bool global)
{
@@ -691,6 +725,7 @@ static const QMap<QString, int> &vimKeyNames()
k.insert(_("RIGHT"), Key_Right);
k.insert(_("LT"), Key_Less);
+ k.insert(_("GT"), Key_Greater);
k.insert(_("F1"), Key_F1);
k.insert(_("F2"), Key_F2);
@@ -827,7 +862,10 @@ class Input
{
public:
// Remove some extra "information" on Mac.
- static int cleanModifier(int m) { return m & ~Qt::KeypadModifier; }
+ static Qt::KeyboardModifiers cleanModifier(Qt::KeyboardModifiers m)
+ {
+ return m & ~Qt::KeypadModifier;
+ }
Input()
: m_key(0), m_xkey(0), m_modifiers(0) {}
@@ -841,7 +879,7 @@ public:
m_key = x.toUpper().unicode();
}
- Input(int k, int m, const QString &t = QString())
+ Input(int k, Qt::KeyboardModifiers m, const QString &t = QString())
: m_key(k), m_modifiers(cleanModifier(m)), m_text(t)
{
if (m_text.size() == 1) {
@@ -858,7 +896,7 @@ public:
}
// Set text only if input is ascii key without control modifier.
- if (m_text.isEmpty() && k >= 0 && k <= 0x7f && (m & (HostOsInfo::controlModifier())) == 0) {
+ if (m_text.isEmpty() && k >= 0 && k <= 0x7f && (m & HostOsInfo::controlModifier()) == 0) {
QChar c = QChar::fromLatin1(k);
m_text = QString((m & ShiftModifier) != 0 ? c.toUpper() : c.toLower());
}
@@ -900,12 +938,12 @@ public:
bool is(int c) const
{
- return m_xkey == c && m_modifiers != int(HostOsInfo::controlModifier());
+ return m_xkey == c && m_modifiers != HostOsInfo::controlModifier();
}
bool isControl() const
{
- return m_modifiers & HostOsInfo::controlModifier();
+ return m_modifiers == HostOsInfo::controlModifier();
}
bool isControl(int c) const
@@ -951,7 +989,7 @@ public:
int key() const { return m_key; }
- int modifiers() const { return m_modifiers; }
+ Qt::KeyboardModifiers modifiers() const { return m_modifiers; }
// Return raw character for macro recording or dot command.
QChar raw() const
@@ -973,6 +1011,8 @@ public:
if (!namedKey) {
if (m_xkey == '<')
key = _("<LT>");
+ else if (m_xkey == '>')
+ key = _("<GT>");
else
key = QChar(m_xkey);
}
@@ -1000,12 +1040,12 @@ public:
private:
int m_key;
int m_xkey;
- int m_modifiers;
+ Qt::KeyboardModifiers m_modifiers;
QString m_text;
};
// mapping to <Nop> (do nothing)
-static const Input Nop(-1, -1, QString());
+static const Input Nop(-1, Qt::KeyboardModifiers(-1), QString());
QDebug operator<<(QDebug ts, const Input &input) { return input.dump(ts); }
@@ -1043,7 +1083,7 @@ static Input parseVimKeyName(const QString &keyName)
if (len == 1 && keys.at(0).toUpper() == _("NOP"))
return Nop;
- int mods = NoModifier;
+ Qt::KeyboardModifiers mods = NoModifier;
for (int i = 0; i < len - 1; ++i) {
const QString &key = keys[i].toUpper();
if (key == _("S"))
@@ -1458,8 +1498,9 @@ public:
void clearPendingInput();
void waitForMapping();
EventResult stopWaitForMapping(bool hasInput);
- EventResult handleInsertMode(const Input &);
- EventResult handleReplaceMode(const Input &);
+ EventResult handleInsertOrReplaceMode(const Input &);
+ void handleInsertMode(const Input &);
+ void handleReplaceMode(const Input &);
EventResult handleCommandMode(const Input &);
@@ -1486,21 +1527,22 @@ public:
EventResult handleSearchSubSubMode(const Input &);
bool handleCommandSubSubMode(const Input &);
void fixSelection(); // Fix selection according to current range, move and command modes.
+ bool finishSearch();
void finishMovement(const QString &dotCommandMovement = QString());
- void finishMovement(const QString &dotCommandMovement, int count);
void resetCommandMode();
void clearCommandMode();
QTextCursor search(const SearchData &sd, int startPos, int count, bool showMessages);
void search(const SearchData &sd, bool showMessages = true);
- void searchNext(bool forward = true);
+ bool searchNext(bool forward = true);
void searchBalanced(bool forward, QChar needle, QChar other);
void highlightMatches(const QString &needle);
void stopIncrementalFind();
void updateFind(bool isComplete);
+ void resetCount();
bool isInputCount(const Input &) const; // Return true if input can be used as count for commands.
- int mvCount() const { return m_mvcount.isEmpty() ? 1 : m_mvcount.toInt(); }
- int opCount() const { return m_opcount.isEmpty() ? 1 : m_opcount.toInt(); }
+ int mvCount() const { return qMax(1, g.mvcount); }
+ int opCount() const { return qMax(1, g.opcount); }
int count() const { return mvCount() * opCount(); }
QTextBlock block() const { return m_cursor.block(); }
int leftDist() const { return position() - block().position(); }
@@ -1524,6 +1566,7 @@ public:
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
+ QString textAt(int from, int to) const;
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
@@ -1603,7 +1646,7 @@ public:
qDebug() << msg << "POS: " << anchor() << position()
<< "EXT: " << m_oldExternalAnchor << m_oldExternalPosition
<< "INT: " << m_oldInternalAnchor << m_oldInternalPosition
- << "VISUAL: " << m_visualMode;
+ << "VISUAL: " << g.visualMode;
}
void moveRight(int n = 1) {
//dump("RIGHT 1");
@@ -1642,7 +1685,6 @@ public:
}
// Values to save when starting FakeVim processing.
- bool m_inFakeVim;
int m_firstVisibleLine;
QTextCursor m_cursor;
@@ -1651,9 +1693,10 @@ public:
bool handleFfTt(QString key);
- void enterInsertMode();
void initVisualInsertMode(QChar command);
void enterReplaceMode();
+ void enterInsertMode();
+ void enterInsertOrReplaceMode(Mode mode);
void enterCommandMode(Mode returnToMode = CommandMode);
void enterExMode(const QString &contents = QString());
void showMessage(MessageLevel level, const QString &msg);
@@ -1675,16 +1718,28 @@ public:
void endEditBlock();
void breakEditBlock() { m_breakEditBlock = true; }
- Q_SLOT void onContentsChanged();
+ Q_SLOT void onContentsChanged(int position, int charsRemoved, int charsAdded);
Q_SLOT void onUndoCommandAdded();
- bool isInsertMode() const { return m_mode == InsertMode || m_mode == ReplaceMode; }
-
- 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; }
+ bool isInsertMode() const { return g.mode == InsertMode || g.mode == ReplaceMode; }
+ // Waiting for movement operator.
+ bool isOperatorPending() const {
+ return g.submode == ChangeSubMode
+ || g.submode == DeleteSubMode
+ || g.submode == FilterSubMode
+ || g.submode == IndentSubMode
+ || g.submode == ShiftLeftSubMode
+ || g.submode == ShiftRightSubMode
+ || g.submode == InvertCaseSubMode
+ || g.submode == DownCaseSubMode
+ || g.submode == UpCaseSubMode
+ || g.submode == YankSubMode; }
+
+ bool isVisualMode() const { return g.visualMode != NoVisualMode; }
+ bool isNoVisualMode() const { return g.visualMode == NoVisualMode; }
+ bool isVisualCharMode() const { return g.visualMode == VisualCharMode; }
+ bool isVisualLineMode() const { return g.visualMode == VisualLineMode; }
+ bool isVisualBlockMode() const { return g.visualMode == VisualBlockMode; }
char currentModeCode() const;
void updateEditor();
@@ -1700,7 +1755,10 @@ public:
Q_SLOT void importSelection();
void exportSelection();
- void recordInsertion(const QString &insert = QString());
+ void commitInsertState();
+ void invalidateInsertState();
+ bool isInsertStateValid() const;
+ void clearLastInsertion();
void ensureCursorVisible();
void insertInInsertMode(const QString &text);
@@ -1716,30 +1774,31 @@ public:
bool m_wasReadOnly; // saves read-only state of document
FakeVimHandler *q;
- Mode m_mode;
- bool m_passing; // let the core see the next event
- SubMode m_submode;
- SubSubMode m_subsubmode;
- Input m_subsubdata;
int m_oldExternalPosition; // copy from last event to check for external changes
int m_oldExternalAnchor;
int m_oldInternalPosition; // copy from last event to check for external changes
int m_oldInternalAnchor;
int m_oldPosition; // FIXME: Merge with above.
- int m_oldDocumentLength;
int m_register;
- QString m_mvcount;
- QString m_opcount;
- MoveType m_movetype;
- RangeMode m_rangemode;
bool m_visualBlockInsert;
+ // Insert state to get last inserted text.
+ struct InsertState {
+ int pos1;
+ int pos2;
+ int backspaces;
+ int deletes;
+ QSet<int> spaces;
+ bool insertingSpaces;
+ QString textBeforeCursor;
+ bool newLineBefore;
+ bool newLineAfter;
+ } m_insertState;
+
bool m_fakeEnd;
bool m_anchorPastEnd;
bool m_positionPastEnd; // '$' & 'l' in visual mode can move past eol
- int m_gflag; // whether current command started with 'g'
-
QString m_currentFileName;
int m_findStartPosition;
@@ -1782,7 +1841,7 @@ public:
QString selectText(const Range &range) const;
void setCurrentRange(const Range &range);
- Range currentRange() const { return Range(position(), anchor(), m_rangemode); }
+ Range currentRange() const { return Range(position(), anchor(), g.rangemode); }
void yankText(const Range &range, int toregister = '"');
@@ -1792,13 +1851,11 @@ public:
void insertNewLine();
- bool handleInsertInEditor(const Input &input, QString *insert);
+ bool handleInsertInEditor(const Input &input);
bool passEventToEditor(QEvent &event); // Pass event to editor widget without filtering. Returns true if event was processed.
- // Guess insert command for text modification which happened externally (e.g. code-completion).
- QString guessInsertCommand(int pos1, int pos2, int len1, int len2);
// undo handling
- int revision() const { return document()->revision(); }
+ int revision() const { return document()->availableUndoSteps(); }
void undoRedo(bool undo);
void undo();
void redo();
@@ -1807,23 +1864,17 @@ public:
QStack<State> m_undo;
QStack<State> m_redo;
State m_undoState;
- int m_lastUndoSteps;
+ int m_lastRevision;
// extra data for '.'
- void replay(const QString &text);
+ void replay(const QString &text, int repeat = 1);
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;
- Input m_semicolonType; // 'f', 'F', 't', 'T'
- QString m_semicolonKey;
-
// visual modes
void toggleVisualMode(VisualMode visualMode);
void leaveVisualMode();
- VisualMode m_visualMode;
VisualMode m_lastVisualMode;
bool m_lastVisualModeInverted;
@@ -1849,9 +1900,7 @@ public:
QString tabExpand(int len) const;
Column indentation(const QString &line) const;
void insertAutomaticIndentation(bool goingDown, bool forceAutoIndent = false);
- bool removeAutomaticIndentation(); // true if something removed
// number of autoindented characters
- int m_justAutoIndented;
void handleStartOfLine();
// register handling
@@ -1870,7 +1919,7 @@ public:
QTextCursor m_searchCursor;
int m_searchStartPosition;
int m_searchFromScreenLine;
- QString m_oldNeedle;
+ QString m_highlighted; // currently highlighted text
bool handleExCommandHelper(ExCommand &cmd); // Returns success.
bool handleExPluginCommand(const ExCommand &cmd); // Handled by plugin?
@@ -1903,16 +1952,57 @@ public:
void miniBufferTextEdited(const QString &text, int cursorPos, int anchorPos);
+ // Data shared among all editors.
static struct GlobalData
{
GlobalData()
- : mappings(), currentMap(&mappings), inputTimer(-1), mapDepth(0),
- currentMessageLevel(MessageInfo), lastSearchForward(false), findPending(false),
- returnToMode(CommandMode), currentRegister(0), lastExecutedRegister(0)
+ : inFakeVim(false)
+ , passing(false)
+ , mode(CommandMode)
+ , submode(NoSubMode)
+ , subsubmode(NoSubSubMode)
+ , visualMode(NoVisualMode)
+ , mvcount(0)
+ , opcount(0)
+ , movetype(MoveInclusive)
+ , rangemode(RangeCharMode)
+ , gflag(false)
+ , mappings()
+ , currentMap(&mappings)
+ , inputTimer(-1)
+ , mapDepth(0)
+ , currentMessageLevel(MessageInfo)
+ , lastSearchForward(false)
+ , highlightsCleared(false)
+ , findPending(false)
+ , returnToMode(CommandMode)
+ , currentRegister(0)
+ , lastExecutedRegister(0)
{
commandBuffer.setPrompt(QLatin1Char(':'));
}
+ // Current state.
+ bool inFakeVim; // true if currently processing a key press or a command
+ bool passing; // let the core see the next event
+ Mode mode;
+ SubMode submode;
+ SubSubMode subsubmode;
+ Input subsubdata;
+ VisualMode visualMode;
+
+ // [count] for current command, 0 if no [count] available
+ int mvcount;
+ int opcount;
+
+ MoveType movetype;
+ RangeMode rangemode;
+ bool gflag; // whether current command started with 'g'
+
+ // Extra data for ';'.
+ Input semicolonType; // 'f', 'F', 't', 'T'
+ QString semicolonKey;
+
// Repetition.
QString dotCommand;
@@ -1938,9 +2028,11 @@ public:
QString currentCommand;
// Search state.
- QString lastSearch;
- bool lastSearchForward;
- bool findPending;
+ QString lastSearch; // last search expression as entered by user
+ QString lastNeedle; // last search expression translated with vimPatternToQtPattern()
+ bool lastSearchForward; // last search command was '/' or '*'
+ bool highlightsCleared; // ':nohlsearch' command is active until next search
+ bool findPending; // currently searching using external tool (until editor is focused again)
// Last substitution command.
QString lastSubstituteFlags;
@@ -1969,9 +2061,10 @@ FakeVimHandler::Private::Private(FakeVimHandler *parent, QWidget *widget)
m_textedit = qobject_cast<QTextEdit *>(widget);
m_plaintextedit = qobject_cast<QPlainTextEdit *>(widget);
if (editor()) {
- connect(EDITOR(document()), SIGNAL(contentsChanged()), SLOT(onContentsChanged()));
+ connect(EDITOR(document()), SIGNAL(contentsChange(int,int,int)),
+ SLOT(onContentsChanged(int,int,int)));
connect(EDITOR(document()), SIGNAL(undoCommandAdded()), SLOT(onUndoCommandAdded()));
- m_lastUndoSteps = document()->availableUndoSteps();
+ m_lastRevision = revision();
}
//new Highlighter(document(), &pythonRules);
init();
@@ -1979,39 +2072,27 @@ FakeVimHandler::Private::Private(FakeVimHandler *parent, QWidget *widget)
void FakeVimHandler::Private::init()
{
- m_mode = CommandMode;
- m_submode = NoSubMode;
- m_subsubmode = NoSubSubMode;
- m_passing = false;
- g.findPending = false;
m_findStartPosition = -1;
m_visualBlockInsert = false;
m_fakeEnd = false;
m_positionPastEnd = false;
m_anchorPastEnd = false;
- g.lastSearchForward = true;
m_register = '"';
- m_gflag = false;
- m_visualMode = NoVisualMode;
m_lastVisualMode = NoVisualMode;
m_lastVisualModeInverted = false;
m_targetColumn = 0;
m_visualTargetColumn = 0;
- m_movetype = MoveInclusive;
- m_justAutoIndented = 0;
- m_rangemode = RangeCharMode;
m_ctrlVActive = false;
m_oldInternalAnchor = -1;
m_oldInternalPosition = -1;
m_oldExternalAnchor = -1;
m_oldExternalPosition = -1;
m_oldPosition = -1;
- m_oldDocumentLength = -1;
+ m_insertState = InsertState();
m_breakEditBlock = false;
m_searchStartPosition = 0;
m_searchFromScreenLine = 0;
m_editBlockLevel = 0;
- m_inFakeVim = false;
m_firstVisibleLine = 0;
setupCharClass();
@@ -2019,21 +2100,40 @@ void FakeVimHandler::Private::init()
void FakeVimHandler::Private::focus()
{
+ if (g.inFakeVim)
+ return;
+
+ enterFakeVim();
+
stopIncrementalFind();
- if (m_mode == CommandMode && g.returnToMode != CommandMode && g.currentCommand.isEmpty()) {
- // Return to insert mode.
+ if (!isInsertMode()) {
+ if (g.subsubmode == SearchSubSubMode) {
+ setPosition(m_searchStartPosition);
+ scrollToLine(m_searchFromScreenLine);
+ setTargetColumn();
+ } else {
+ leaveVisualMode();
+ }
+
+ bool exitCommandLine = (g.subsubmode == SearchSubSubMode || g.mode == ExMode);
resetCommandMode();
- updateMiniBuffer();
- updateCursorShape();
+ if (exitCommandLine)
+ updateMiniBuffer();
}
+ updateCursorShape();
+ if (g.mode != CommandMode)
+ updateMiniBuffer();
+ updateHighlights();
+
+ leaveFakeVim();
}
void FakeVimHandler::Private::enterFakeVim()
{
- QTC_ASSERT(!m_inFakeVim, qDebug() << "enterFakeVim() shouldn't be called recursively!"; return);
+ QTC_ASSERT(!g.inFakeVim, qDebug() << "enterFakeVim() shouldn't be called recursively!"; return);
m_cursor = EDITOR(textCursor());
- m_inFakeVim = true;
+ g.inFakeVim = true;
updateFirstVisibleLine();
importSelection();
@@ -2054,15 +2154,15 @@ void FakeVimHandler::Private::enterFakeVim()
void FakeVimHandler::Private::leaveFakeVim(bool needUpdate)
{
- QTC_ASSERT(m_inFakeVim, qDebug() << "enterFakeVim() not called before leaveFakeVim()!"; return);
+ QTC_ASSERT(g.inFakeVim, qDebug() << "enterFakeVim() not called before leaveFakeVim()!"; return);
// 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()
+ m_fakeEnd = atEndOfLine() && g.mode == CommandMode && !isVisualBlockMode()
&& !isVisualCharMode();
- //QTC_ASSERT(m_mode == InsertMode || m_mode == ReplaceMode
+ //QTC_ASSERT(g.mode == InsertMode || g.mode == ReplaceMode
// || !atBlockEnd() || block().length() <= 1,
// qDebug() << "Cursor at EOL after key handler");
if (m_fakeEnd)
@@ -2080,7 +2180,7 @@ void FakeVimHandler::Private::leaveFakeVim(bool needUpdate)
// Move cursor line to middle of screen if it's not visible.
const int line = cursorLine();
- if (line < firstVisibleLine() || line >= firstVisibleLine() + linesOnScreen())
+ if (line < firstVisibleLine() || line > firstVisibleLine() + linesOnScreen())
scrollToLine(qMax(0, line - linesOnScreen() / 2));
else
scrollToLine(firstVisibleLine());
@@ -2088,22 +2188,22 @@ void FakeVimHandler::Private::leaveFakeVim(bool needUpdate)
}
}
- m_inFakeVim = false;
+ g.inFakeVim = false;
}
bool FakeVimHandler::Private::wantsOverride(QKeyEvent *ev)
{
const int key = ev->key();
- const int mods = ev->modifiers();
- KEY_DEBUG("SHORTCUT OVERRIDE" << key << " PASSING: " << m_passing);
+ const Qt::KeyboardModifiers mods = ev->modifiers();
+ KEY_DEBUG("SHORTCUT OVERRIDE" << key << " PASSING: " << g.passing);
if (key == Key_Escape) {
- if (m_subsubmode == SearchSubSubMode)
+ if (g.subsubmode == SearchSubSubMode)
return true;
// Not sure this feels good. People often hit Esc several times.
if (isNoVisualMode()
- && m_mode == CommandMode
- && m_submode == NoSubMode
+ && g.mode == CommandMode
+ && g.submode == NoSubMode
&& g.currentCommand.isEmpty()
&& g.returnToMode == CommandMode)
return false;
@@ -2111,15 +2211,15 @@ bool FakeVimHandler::Private::wantsOverride(QKeyEvent *ev)
}
// We are interested in overriding most Ctrl key combinations.
- if (mods == int(HostOsInfo::controlModifier())
+ if (mods == HostOsInfo::controlModifier()
&& !config(ConfigPassControlKey).toBool()
&& ((key >= Key_A && key <= Key_Z && key != Key_K)
|| key == Key_BracketLeft || key == Key_BracketRight)) {
// Ctrl-K is special as it is the Core's default notion of Locator
- if (m_passing) {
+ if (g.passing) {
KEY_DEBUG(" PASSING CTRL KEY");
// We get called twice on the same key
- //m_passing = false;
+ //g.passing = false;
return false;
}
KEY_DEBUG(" NOT PASSING CTRL KEY");
@@ -2134,7 +2234,7 @@ bool FakeVimHandler::Private::wantsOverride(QKeyEvent *ev)
EventResult FakeVimHandler::Private::handleEvent(QKeyEvent *ev)
{
const int key = ev->key();
- const int mods = ev->modifiers();
+ const Qt::KeyboardModifiers mods = ev->modifiers();
if (key == Key_Shift || key == Key_Alt || key == Key_Control
|| key == Key_Alt || key == Key_AltGr || key == Key_Meta)
@@ -2143,14 +2243,14 @@ EventResult FakeVimHandler::Private::handleEvent(QKeyEvent *ev)
return EventUnhandled;
}
- if (m_passing) {
+ if (g.passing) {
passShortcuts(false);
KEY_DEBUG("PASSING PLAIN KEY..." << ev->key() << ev->text());
//if (input.is(',')) { // use ',,' to leave, too.
// qDebug() << "FINISHED...";
// return EventHandled;
//}
- m_passing = false;
+ g.passing = false;
updateMiniBuffer();
KEY_DEBUG(" PASS TO CORE");
return EventPassedToCore;
@@ -2183,7 +2283,7 @@ EventResult FakeVimHandler::Private::handleEvent(QKeyEvent *ev)
// key = shift(key);
//}
- //QTC_ASSERT(m_mode == InsertMode || m_mode == ReplaceMode
+ //QTC_ASSERT(g.mode == InsertMode || g.mode == ReplaceMode
// || !atBlockEnd() || block().length() <= 1,
// qDebug() << "Cursor at EOL before key handler");
@@ -2208,7 +2308,6 @@ void FakeVimHandler::Private::removeEventFilter()
void FakeVimHandler::Private::setupWidget()
{
- m_mode = CommandMode;
resetCommandMode();
if (m_textedit)
m_textedit->setLineWrapMode(QTextEdit::NoWrap);
@@ -2218,7 +2317,8 @@ void FakeVimHandler::Private::setupWidget()
updateEditor();
importSelection();
- updateMiniBuffer();
+ if (!g.inFakeVim)
+ updateMiniBuffer();
updateCursorShape();
recordJump();
@@ -2239,23 +2339,18 @@ void FakeVimHandler::Private::exportSelection()
m_oldInternalAnchor = anc;
if (isVisualMode()) {
- if (m_visualMode == VisualBlockMode) {
+ if (g.visualMode == VisualBlockMode) {
const int col1 = anc - document()->findBlock(anc).position();
const int col2 = pos - document()->findBlock(pos).position();
if (col1 > col2)
++anc;
else
++pos;
- } else if (anc > pos) {
- ++anc;
- }
- setAnchorAndPosition(anc, pos);
-
- if (m_visualMode == VisualBlockMode) {
+ setAnchorAndPosition(anc, pos);
commitCursor();
emit q->requestSetBlockSelection(false);
emit q->requestSetBlockSelection(true);
- } else if (m_visualMode == VisualLineMode) {
+ } else if (g.visualMode == VisualLineMode) {
const int posLine = lineForPosition(pos);
const int ancLine = lineForPosition(anc);
if (anc < pos) {
@@ -2263,22 +2358,25 @@ void FakeVimHandler::Private::exportSelection()
anc = firstPositionInLine(ancLine);
} else {
pos = firstPositionInLine(posLine);
- anc = lastPositionInLine(ancLine);
+ anc = lastPositionInLine(ancLine) + 1;
}
// 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 if (g.visualMode == VisualCharMode) {
+ if (anc > pos)
+ ++anc;
} else {
QTC_CHECK(false);
}
+ setAnchorAndPosition(anc, pos);
+
setMark(QLatin1Char('<'), mark(QLatin1Char('<')).position);
setMark(QLatin1Char('>'), mark(QLatin1Char('>')).position);
} else {
- if (m_subsubmode == SearchSubSubMode && !m_searchCursor.isNull())
+ if (g.subsubmode == SearchSubSubMode && !m_searchCursor.isNull())
m_cursor = m_searchCursor;
else
setAnchorAndPosition(pos, pos);
@@ -2287,31 +2385,62 @@ void FakeVimHandler::Private::exportSelection()
m_oldExternalAnchor = anchor();
}
-void FakeVimHandler::Private::recordInsertion(const QString &insert)
+void FakeVimHandler::Private::commitInsertState()
{
- const int pos = position();
+ if (!isInsertStateValid())
+ return;
- if (insert.isNull()) {
- const int dist = pos - m_oldPosition;
+ // Get raw inserted text.
+ m_lastInsertion = textAt(m_insertState.pos1, m_insertState.pos2);
- 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;
+ // Escape special characters and spaces inserted by user (not by auto-indentation).
+ for (int i = m_lastInsertion.size() - 1; i >= 0; --i) {
+ const int pos = m_insertState.pos1 + i;
+ const ushort c = document()->characterAt(pos).unicode();
+ if (c == '<')
+ m_lastInsertion.replace(i, 1, _("<LT>"));
+ else if ((c == ' ' || c == '\t') && m_insertState.spaces.contains(pos))
+ m_lastInsertion.replace(i, 1, _(c == ' ' ? "<SPACE>" : "<TAB>"));
}
- if (m_oldPosition != pos) {
- m_oldPosition = pos;
- setTargetColumn();
- }
- m_oldDocumentLength = document()->characterCount();
+ // Remove unnecessary backspaces.
+ while (m_insertState.backspaces > 0 && !m_lastInsertion.isEmpty() && m_lastInsertion[0].isSpace())
+ --m_insertState.backspaces;
+
+ // backspaces in front of inserted text
+ m_lastInsertion.prepend(QString(_("<BS>")).repeated(m_insertState.backspaces));
+ // deletes after inserted text
+ m_lastInsertion.prepend(QString(_("<DELETE>")).repeated(m_insertState.deletes));
+
+ // Remove indentation.
+ m_lastInsertion.replace(QRegExp(_("(^|\n)[\\t ]+")), _("\\1"));
+}
+
+void FakeVimHandler::Private::invalidateInsertState()
+{
+ m_oldPosition = position();
+ m_insertState.pos1 = -1;
+ m_insertState.pos2 = m_oldPosition;
+ m_insertState.backspaces = 0;
+ m_insertState.deletes = 0;
+ m_insertState.spaces.clear();
+ m_insertState.insertingSpaces = false;
+ m_insertState.textBeforeCursor = textAt(document()->findBlock(m_oldPosition).position(),
+ m_oldPosition);
+ m_insertState.newLineBefore = false;
+ m_insertState.newLineAfter = false;
+}
+
+bool FakeVimHandler::Private::isInsertStateValid() const
+{
+ return m_insertState.pos1 != -1;
+}
+
+void FakeVimHandler::Private::clearLastInsertion()
+{
+ invalidateInsertState();
+ m_lastInsertion.clear();
+ m_insertState.pos1 = m_insertState.pos2;
}
void FakeVimHandler::Private::ensureCursorVisible()
@@ -2363,16 +2492,16 @@ void FakeVimHandler::Private::importSelection()
Qt::KeyboardModifiers mods = QApplication::keyboardModifiers();
if (m_cursor.hasSelection()) {
if (mods & HostOsInfo::controlModifier())
- m_visualMode = VisualBlockMode;
+ g.visualMode = VisualBlockMode;
else if (mods & Qt::AltModifier)
- m_visualMode = VisualBlockMode;
+ g.visualMode = VisualBlockMode;
else if (mods & Qt::ShiftModifier)
- m_visualMode = VisualLineMode;
+ g.visualMode = VisualLineMode;
else
- m_visualMode = VisualCharMode;
- m_lastVisualMode = m_visualMode;
+ g.visualMode = VisualCharMode;
+ m_lastVisualMode = g.visualMode;
} else {
- m_visualMode = NoVisualMode;
+ g.visualMode = NoVisualMode;
}
}
}
@@ -2392,7 +2521,7 @@ void FakeVimHandler::Private::restoreWidget(int tabSize)
//EDITOR(setReadOnly(m_wasReadOnly));
const int charWidth = QFontMetrics(EDITOR(font())).width(QLatin1Char(' '));
EDITOR(setTabStopWidth(charWidth * tabSize));
- m_visualMode = NoVisualMode;
+ g.visualMode = NoVisualMode;
// Force "ordinary" cursor.
EDITOR(setOverwriteMode(false));
updateSelection();
@@ -2454,15 +2583,13 @@ EventResult FakeVimHandler::Private::handleDefaultKey(const Input &input)
{
if (input == Nop)
return EventHandled;
- else if (m_subsubmode == SearchSubSubMode)
+ else if (g.subsubmode == SearchSubSubMode)
return handleSearchSubSubMode(input);
- else if (m_mode == CommandMode)
+ else if (g.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)
+ else if (g.mode == InsertMode || g.mode == ReplaceMode)
+ return handleInsertOrReplaceMode(input);
+ else if (g.mode == ExMode)
return handleExMode(input);
return EventUnhandled;
}
@@ -2544,14 +2671,14 @@ void FakeVimHandler::Private::endMapping()
bool FakeVimHandler::Private::canHandleMapping()
{
// Don't handle user mapping in sub-modes that cannot be followed by movement and in "noremap".
- return m_subsubmode == NoSubSubMode
- && m_submode != RegisterSubMode
- && m_submode != WindowSubMode
- && m_submode != ZSubMode
- && m_submode != CapitalZSubMode
- && m_submode != ReplaceSubMode
- && m_submode != MacroRecordSubMode
- && m_submode != MacroExecuteSubMode
+ return g.subsubmode == NoSubSubMode
+ && g.submode != RegisterSubMode
+ && g.submode != WindowSubMode
+ && g.submode != ZSubMode
+ && g.submode != CapitalZSubMode
+ && g.submode != ReplaceSubMode
+ && g.submode != MacroRecordSubMode
+ && g.submode != MacroExecuteSubMode
&& (g.mapStates.isEmpty() || !g.mapStates.last().noremap);
}
@@ -2620,20 +2747,28 @@ void FakeVimHandler::Private::updateFind(bool isComplete)
g.currentMessage.clear();
const QString &needle = g.searchBuffer.contents();
+ if (isComplete) {
+ setPosition(m_searchStartPosition);
+ if (!needle.isEmpty())
+ recordJump();
+ }
+
SearchData sd;
sd.needle = needle;
sd.forward = g.lastSearchForward;
sd.highlightMatches = isComplete;
- if (isComplete) {
- setPosition(m_searchStartPosition);
- recordJump();
- }
search(sd, isComplete);
}
+void FakeVimHandler::Private::resetCount()
+{
+ g.mvcount = 0;
+ g.opcount = 0;
+}
+
bool FakeVimHandler::Private::isInputCount(const Input &input) const
{
- return input.isDigit() && (!input.is('0') || !m_mvcount.isEmpty());
+ return input.isDigit() && (!input.is('0') || g.mvcount > 0);
}
bool FakeVimHandler::Private::atEmptyLine(const QTextCursor &tc) const
@@ -2692,15 +2827,15 @@ void FakeVimHandler::Private::pushUndoState(bool overwrite)
int pos = position();
if (!isInsertMode()) {
- if (isVisualMode() || m_submode == DeleteSubMode
- || (m_submode == ChangeSubMode && m_movetype != MoveLineWise)) {
+ if (isVisualMode() || g.submode == DeleteSubMode
+ || (g.submode == ChangeSubMode && g.movetype != MoveLineWise)) {
pos = qMin(pos, anchor());
if (isVisualLineMode())
pos = firstPositionInLine(lineForPosition(pos));
- } else if (m_movetype == MoveLineWise && hasConfig(ConfigStartOfLine)) {
+ } else if (g.movetype == MoveLineWise && hasConfig(ConfigStartOfLine)) {
QTextCursor tc = m_cursor;
- if (m_submode == ShiftLeftSubMode || m_submode == ShiftRightSubMode
- || m_submode == IndentSubMode) {
+ if (g.submode == ShiftLeftSubMode || g.submode == ShiftRightSubMode
+ || g.submode == IndentSubMode) {
pos = qMin(pos, anchor());
}
tc.setPosition(pos);
@@ -2715,7 +2850,7 @@ void FakeVimHandler::Private::pushUndoState(bool overwrite)
setMark(QLatin1Char('<'), mark(QLatin1Char('<')).position);
setMark(QLatin1Char('>'), mark(QLatin1Char('>')).position);
}
- m_undoState = State(m_lastChangePosition, m_marks, m_lastVisualMode,
+ m_undoState = State(revision(), m_lastChangePosition, m_marks, m_lastVisualMode,
m_lastVisualModeInverted);
}
@@ -2741,6 +2876,7 @@ void FakeVimHandler::Private::moveDown(int n)
setPosition(position);
moveToTargetColumn();
+ updateScrollOffset();
}
void FakeVimHandler::Private::movePageDown(int count)
@@ -2761,6 +2897,7 @@ bool FakeVimHandler::Private::moveToNextParagraph(int count)
{
const bool forward = count > 0;
int repeat = forward ? count : -count;
+ int pos = position();
QTextBlock block = this->block();
if (block.isValid() && block.length() == 1)
@@ -2782,8 +2919,9 @@ bool FakeVimHandler::Private::moveToNextParagraph(int count)
else
return false;
+ recordJump(pos);
setTargetColumn();
- m_movetype = MoveExclusive;
+ g.movetype = MoveExclusive;
return true;
}
@@ -2792,7 +2930,7 @@ void FakeVimHandler::Private::moveToEndOfLine()
{
// Additionally select (in visual mode) or apply current command on hidden lines following
// the current line.
- bool onlyVisibleLines = isVisualMode() || m_submode != NoSubMode;
+ bool onlyVisibleLines = isVisualMode() || g.submode != NoSubMode;
const int id = onlyVisibleLines ? lineNumber(block()) : block().blockNumber() + 1;
setPosition(lastPositionInLine(id, onlyVisibleLines));
}
@@ -2817,10 +2955,10 @@ void FakeVimHandler::Private::moveToStartOfLine()
void FakeVimHandler::Private::fixSelection()
{
- if (m_rangemode == RangeBlockMode)
+ if (g.rangemode == RangeBlockMode)
return;
- if (m_movetype == MoveInclusive) {
+ if (g.movetype == MoveInclusive) {
// If position or anchor is after end of non-empty line, include line break in selection.
if (document()->characterAt(position()) == ParagraphSeparator) {
if (!atEmptyLine()) {
@@ -2837,27 +2975,27 @@ void FakeVimHandler::Private::fixSelection()
}
}
- if (m_movetype == MoveExclusive) {
+ if (g.movetype == MoveExclusive && g.subsubmode == NoSubSubMode) {
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;
+ g.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;
+ g.movetype = MoveLineWise;
}
}
- if (m_movetype == MoveLineWise)
- m_rangemode = (m_submode == ChangeSubMode)
+ if (g.movetype == MoveLineWise)
+ g.rangemode = (g.submode == ChangeSubMode)
? RangeLineModeExclusive
: RangeLineMode;
- if (m_movetype == MoveInclusive) {
+ if (g.movetype == MoveInclusive) {
if (anchor() <= position()) {
if (!atBlockEnd())
setPosition(position() + 1); // correction
@@ -2867,7 +3005,7 @@ void FakeVimHandler::Private::fixSelection()
int end = position();
if (afterEndOfLine(document(), start) && start > 0) {
start = qMin(start + 1, end);
- if (m_submode == DeleteSubMode && !atDocumentEnd())
+ if (g.submode == DeleteSubMode && !atDocumentEnd())
setAnchorAndPosition(start, end + 1);
else
setAnchorAndPosition(start, end);
@@ -2876,12 +3014,12 @@ void FakeVimHandler::Private::fixSelection()
// 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) {
+ if (g.submode != ChangeSubMode) {
moveRight();
if (atEmptyLine())
moveRight();
}
- m_movetype = MoveLineWise;
+ g.movetype = MoveLineWise;
}
} else if (!m_anchorPastEnd) {
setAnchorAndPosition(anchor() + 1, position());
@@ -2889,25 +3027,35 @@ void FakeVimHandler::Private::fixSelection()
}
if (m_positionPastEnd) {
- const int anc = anchor();
moveBehindEndOfLine();
moveRight();
- setAnchorAndPosition(anc, position());
+ setAnchorAndPosition(anchor(), position());
}
- if (m_anchorPastEnd)
- setAnchorAndPosition(anchor() + 1, position());
+ if (m_anchorPastEnd) {
+ const int pos = position();
+ setPosition(anchor());
+ moveBehindEndOfLine();
+ moveRight();
+ setAnchorAndPosition(position(), pos);
+ }
}
-void FakeVimHandler::Private::finishMovement(const QString &dotCommandMovement, int count)
+bool FakeVimHandler::Private::finishSearch()
{
- finishMovement(dotCommandMovement.arg(count));
+ if (g.lastSearch.isEmpty()
+ || (!g.currentMessage.isEmpty() && g.currentMessageLevel == MessageError)) {
+ return false;
+ }
+ if (g.submode != NoSubMode)
+ setAnchorAndPosition(m_searchStartPosition, position());
+ return true;
}
void FakeVimHandler::Private::finishMovement(const QString &dotCommandMovement)
{
//dump("FINISH MOVEMENT");
- if (m_submode == FilterSubMode) {
+ if (g.submode == FilterSubMode) {
int beginLine = lineForPosition(anchor());
int endLine = lineForPosition(position());
setPosition(qMin(anchor(), position()));
@@ -2915,19 +3063,19 @@ void FakeVimHandler::Private::finishMovement(const QString &dotCommandMovement)
return;
}
- if (m_submode == ChangeSubMode
- || m_submode == DeleteSubMode
- || m_submode == YankSubMode
- || m_submode == InvertCaseSubMode
- || m_submode == DownCaseSubMode
- || m_submode == UpCaseSubMode) {
+ if (g.submode == ChangeSubMode
+ || g.submode == DeleteSubMode
+ || g.submode == YankSubMode
+ || g.submode == InvertCaseSubMode
+ || g.submode == DownCaseSubMode
+ || g.submode == UpCaseSubMode) {
fixSelection();
- if (m_submode != InvertCaseSubMode
- && m_submode != DownCaseSubMode
- && m_submode != UpCaseSubMode) {
+ if (g.submode != InvertCaseSubMode
+ && g.submode != DownCaseSubMode
+ && g.submode != UpCaseSubMode) {
yankText(currentRange(), m_register);
- if (m_movetype == MoveLineWise)
+ if (g.movetype == MoveLineWise)
setRegister(m_register, registerContents(m_register), RangeLineMode);
}
@@ -2935,79 +3083,77 @@ void FakeVimHandler::Private::finishMovement(const QString &dotCommandMovement)
}
QString dotCommand;
- if (m_submode == ChangeSubMode) {
+ if (g.submode == ChangeSubMode) {
pushUndoState(false);
beginEditBlock();
removeText(currentRange());
dotCommand = _("c");
- if (m_movetype == MoveLineWise)
+ if (g.movetype == MoveLineWise)
insertAutomaticIndentation(true);
endEditBlock();
setTargetColumn();
- m_lastInsertion.clear();
- g.returnToMode = InsertMode;
- } else if (m_submode == DeleteSubMode) {
+ } else if (g.submode == DeleteSubMode) {
pushUndoState(false);
beginEditBlock();
const int pos = position();
// Always delete something (e.g. 'dw' on an empty line deletes the line).
- if (pos == anchor() && m_movetype == MoveInclusive)
+ if (pos == anchor() && g.movetype == MoveInclusive)
removeText(Range(pos, pos + 1));
else
removeText(currentRange());
dotCommand = _("d");
- if (m_movetype == MoveLineWise)
+ if (g.movetype == MoveLineWise)
handleStartOfLine();
if (atEndOfLine())
moveLeft();
else
setTargetColumn();
endEditBlock();
- } else if (m_submode == YankSubMode) {
+ } else if (g.submode == YankSubMode) {
const QTextCursor tc = m_cursor;
- if (m_rangemode == RangeBlockMode) {
+ if (g.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 {
setPosition(qMin(position(), anchor()));
- if (m_rangemode == RangeLineMode) {
+ if (g.rangemode == RangeLineMode) {
if (isVisualMode())
moveToStartOfLine();
}
}
leaveVisualMode();
setTargetColumn();
- } else if (m_submode == InvertCaseSubMode
- || m_submode == UpCaseSubMode
- || m_submode == DownCaseSubMode) {
+ } else if (g.submode == InvertCaseSubMode
+ || g.submode == UpCaseSubMode
+ || g.submode == DownCaseSubMode) {
beginEditBlock();
- if (m_submode == InvertCaseSubMode) {
+ if (g.submode == InvertCaseSubMode) {
invertCase(currentRange());
dotCommand = QString::fromLatin1("g~");
- } else if (m_submode == DownCaseSubMode) {
+ } else if (g.submode == DownCaseSubMode) {
downCase(currentRange());
dotCommand = QString::fromLatin1("gu");
- } else if (m_submode == UpCaseSubMode) {
+ } else if (g.submode == UpCaseSubMode) {
upCase(currentRange());
dotCommand = QString::fromLatin1("gU");
}
- if (m_movetype == MoveLineWise)
+ if (g.movetype == MoveLineWise)
handleStartOfLine();
endEditBlock();
- } else if (m_submode == IndentSubMode
- || m_submode == ShiftRightSubMode
- || m_submode == ShiftLeftSubMode) {
+ } else if (g.submode == IndentSubMode
+ || g.submode == ShiftRightSubMode
+ || g.submode == ShiftLeftSubMode) {
recordJump();
pushUndoState(false);
- if (m_submode == IndentSubMode) {
+ if (g.submode == IndentSubMode) {
indentSelectedText();
dotCommand = _("=");
- } else if (m_submode == ShiftRightSubMode) {
+ } else if (g.submode == ShiftRightSubMode) {
shiftRegionRight(1);
dotCommand = _(">");
- } else if (m_submode == ShiftLeftSubMode) {
+ } else if (g.submode == ShiftLeftSubMode) {
shiftRegionLeft(1);
dotCommand = _("<");
}
@@ -3016,21 +3162,29 @@ void FakeVimHandler::Private::finishMovement(const QString &dotCommandMovement)
if (!dotCommand.isEmpty() && !dotCommandMovement.isEmpty())
setDotCommand(dotCommand + dotCommandMovement);
- resetCommandMode();
+ // Change command continues in insert mode.
+ if (g.submode == ChangeSubMode) {
+ clearCommandMode();
+ enterInsertMode();
+ } else {
+ resetCommandMode();
+ }
}
void FakeVimHandler::Private::resetCommandMode()
{
- clearCommandMode();
- if (g.returnToMode != CommandMode) {
+ if (g.returnToMode == CommandMode) {
+ enterCommandMode();
+ } else {
+ clearCommandMode();
const QString lastInsertion = m_lastInsertion;
if (g.returnToMode == InsertMode)
enterInsertMode();
else
enterReplaceMode();
moveToTargetColumn();
+ invalidateInsertState();
m_lastInsertion = lastInsertion;
- m_oldPosition = position();
}
if (isNoVisualMode())
setAnchor();
@@ -3038,15 +3192,14 @@ void FakeVimHandler::Private::resetCommandMode()
void FakeVimHandler::Private::clearCommandMode()
{
- m_submode = NoSubMode;
- m_subsubmode = NoSubSubMode;
- m_movetype = MoveInclusive;
- m_mvcount.clear();
- m_opcount.clear();
- m_gflag = false;
+ g.submode = NoSubMode;
+ g.subsubmode = NoSubSubMode;
+ g.movetype = MoveInclusive;
+ g.gflag = false;
m_register = '"';
- m_rangemode = RangeCharMode;
+ g.rangemode = RangeCharMode;
g.currentCommand.clear();
+ resetCount();
}
void FakeVimHandler::Private::updateSelection()
@@ -3072,8 +3225,17 @@ void FakeVimHandler::Private::updateSelection()
void FakeVimHandler::Private::updateHighlights()
{
- if (!hasConfig(ConfigUseCoreSearch))
- emit q->highlightMatches(m_oldNeedle);
+ if (hasConfig(ConfigUseCoreSearch) || !hasConfig(ConfigHlSearch) || g.highlightsCleared) {
+ if (m_highlighted.isEmpty())
+ return;
+ m_highlighted.clear();
+ } else if (m_highlighted != g.lastNeedle) {
+ m_highlighted = g.lastNeedle;
+ } else {
+ return;
+ }
+
+ emit q->highlightMatches(m_highlighted);
}
void FakeVimHandler::Private::updateMiniBuffer()
@@ -3089,15 +3251,15 @@ void FakeVimHandler::Private::updateMiniBuffer()
if (!g.mapStates.isEmpty() && g.mapStates.last().silent && g.currentMessageLevel < MessageInfo)
g.currentMessage.clear();
- if (m_passing) {
+ if (g.passing) {
msg = _("PASSING");
- } else if (m_subsubmode == SearchSubSubMode) {
+ } else if (g.subsubmode == SearchSubSubMode) {
msg = g.searchBuffer.display();
if (g.mapStates.isEmpty()) {
cursorPos = g.searchBuffer.cursorPos() + 1;
anchorPos = g.searchBuffer.anchorPos() + 1;
}
- } else if (m_mode == ExMode) {
+ } else if (g.mode == ExMode) {
msg = g.commandBuffer.display();
if (g.mapStates.isEmpty()) {
cursorPos = g.commandBuffer.cursorPos() + 1;
@@ -3110,22 +3272,22 @@ void FakeVimHandler::Private::updateMiniBuffer()
} else if (!g.mapStates.isEmpty() && !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)) {
+ } else if (g.mode == CommandMode && !g.currentCommand.isEmpty() && hasConfig(ConfigShowCmd)) {
msg = g.currentCommand;
messageLevel = MessageShowCmd;
- } else if (m_mode == CommandMode && isVisualMode()) {
+ } else if (g.mode == CommandMode && isVisualMode()) {
if (isVisualCharMode())
msg = _("-- VISUAL --");
else if (isVisualLineMode())
msg = _("-- VISUAL LINE --");
else if (isVisualBlockMode())
msg = _("VISUAL BLOCK");
- } else if (m_mode == InsertMode) {
+ } else if (g.mode == InsertMode) {
msg = _("-- INSERT --");
- } else if (m_mode == ReplaceMode) {
+ } else if (g.mode == ReplaceMode) {
msg = _("-- REPLACE --");
} else {
- QTC_CHECK(m_mode == CommandMode && m_subsubmode != SearchSubSubMode);
+ QTC_CHECK(g.mode == CommandMode && g.subsubmode != SearchSubSubMode);
if (g.returnToMode == CommandMode)
msg = _("-- COMMAND --");
else if (g.returnToMode == InsertMode)
@@ -3167,7 +3329,7 @@ void FakeVimHandler::Private::notImplementedYet()
void FakeVimHandler::Private::passShortcuts(bool enable)
{
- m_passing = enable;
+ g.passing = enable;
updateMiniBuffer();
if (enable)
QCoreApplication::instance()->installEventFilter(q);
@@ -3179,66 +3341,66 @@ bool FakeVimHandler::Private::handleCommandSubSubMode(const Input &input)
{
//const int key = input.key;
bool handled = true;
- if (m_subsubmode == FtSubSubMode) {
- m_semicolonType = m_subsubdata;
- m_semicolonKey = input.text();
- bool valid = handleFfTt(m_semicolonKey);
- m_subsubmode = NoSubSubMode;
+ if (g.subsubmode == FtSubSubMode) {
+ g.semicolonType = g.subsubdata;
+ g.semicolonKey = input.text();
+ bool valid = handleFfTt(g.semicolonKey);
+ g.subsubmode = NoSubSubMode;
if (!valid) {
- m_submode = NoSubMode;
+ g.submode = NoSubMode;
resetCommandMode();
handled = false;
} else {
finishMovement(QString::fromLatin1("%1%2%3")
.arg(count())
- .arg(m_semicolonType.text())
- .arg(m_semicolonKey));
+ .arg(g.semicolonType.text())
+ .arg(g.semicolonKey));
}
- } else if (m_subsubmode == TextObjectSubSubMode) {
+ } else if (g.subsubmode == TextObjectSubSubMode) {
bool ok = true;
if (input.is('w'))
- selectWordTextObject(m_subsubdata.is('i'));
+ selectWordTextObject(g.subsubdata.is('i'));
else if (input.is('W'))
- selectWORDTextObject(m_subsubdata.is('i'));
+ selectWORDTextObject(g.subsubdata.is('i'));
else if (input.is('s'))
- selectSentenceTextObject(m_subsubdata.is('i'));
+ selectSentenceTextObject(g.subsubdata.is('i'));
else if (input.is('p'))
- selectParagraphTextObject(m_subsubdata.is('i'));
+ selectParagraphTextObject(g.subsubdata.is('i'));
else if (input.is('[') || input.is(']'))
- ok = selectBlockTextObject(m_subsubdata.is('i'), '[', ']');
+ ok = selectBlockTextObject(g.subsubdata.is('i'), '[', ']');
else if (input.is('(') || input.is(')') || input.is('b'))
- ok = selectBlockTextObject(m_subsubdata.is('i'), '(', ')');
+ ok = selectBlockTextObject(g.subsubdata.is('i'), '(', ')');
else if (input.is('<') || input.is('>'))
- ok = selectBlockTextObject(m_subsubdata.is('i'), '<', '>');
+ ok = selectBlockTextObject(g.subsubdata.is('i'), '<', '>');
else if (input.is('{') || input.is('}') || input.is('B'))
- ok = selectBlockTextObject(m_subsubdata.is('i'), '{', '}');
+ ok = selectBlockTextObject(g.subsubdata.is('i'), '{', '}');
else if (input.is('"') || input.is('\'') || input.is('`'))
- ok = selectQuotedStringTextObject(m_subsubdata.is('i'), input.asChar());
+ ok = selectQuotedStringTextObject(g.subsubdata.is('i'), input.asChar());
else
ok = false;
- m_subsubmode = NoSubSubMode;
+ g.subsubmode = NoSubSubMode;
if (ok) {
finishMovement(QString::fromLatin1("%1%2%3")
.arg(count())
- .arg(m_subsubdata.text())
+ .arg(g.subsubdata.text())
.arg(input.text()));
} else {
resetCommandMode();
handled = false;
}
- } else if (m_subsubmode == MarkSubSubMode) {
+ } else if (g.subsubmode == MarkSubSubMode) {
setMark(input.asChar(), CursorPosition(m_cursor));
- m_subsubmode = NoSubSubMode;
- } else if (m_subsubmode == BackTickSubSubMode
- || m_subsubmode == TickSubSubMode) {
- if (jumpToMark(input.asChar(), m_subsubmode == BackTickSubSubMode)) {
+ g.subsubmode = NoSubSubMode;
+ } else if (g.subsubmode == BackTickSubSubMode
+ || g.subsubmode == TickSubSubMode) {
+ if (jumpToMark(input.asChar(), g.subsubmode == BackTickSubSubMode)) {
finishMovement();
} else {
resetCommandMode();
handled = false;
}
- m_subsubmode = NoSubSubMode;
- } else if (m_subsubmode == ZSubSubMode) {
+ g.subsubmode = NoSubSubMode;
+ } else if (g.subsubmode == ZSubSubMode) {
handled = false;
if (input.is('j') || input.is('k')) {
int pos = position();
@@ -3250,23 +3412,33 @@ bool FakeVimHandler::Private::handleCommandSubSubMode(const Input &input)
.arg(input.text()));
}
}
- } else if (m_subsubmode == OpenSquareSubSubMode || CloseSquareSubSubMode) {
+ } else if (g.subsubmode == OpenSquareSubSubMode || CloseSquareSubSubMode) {
int pos = position();
- if ((input.is('{') && m_subsubmode == OpenSquareSubSubMode))
+ if (input.is('{') && g.subsubmode == OpenSquareSubSubMode)
searchBalanced(false, QLatin1Char('{'), QLatin1Char('}'));
- else if ((input.is('}') && m_subsubmode == CloseSquareSubSubMode))
+ else if (input.is('}') && g.subsubmode == CloseSquareSubSubMode)
searchBalanced(true, QLatin1Char('}'), QLatin1Char('{'));
- else if ((input.is('(') && m_subsubmode == OpenSquareSubSubMode))
+ else if (input.is('(') && g.subsubmode == OpenSquareSubSubMode)
searchBalanced(false, QLatin1Char('('), QLatin1Char(')'));
- else if ((input.is(')') && m_subsubmode == CloseSquareSubSubMode))
+ else if (input.is(')') && g.subsubmode == CloseSquareSubSubMode)
searchBalanced(true, QLatin1Char(')'), QLatin1Char('('));
+ else if (input.is('[') && g.subsubmode == OpenSquareSubSubMode)
+ bracketSearchBackward(&m_cursor, _("^\\{"), count());
+ else if (input.is('[') && g.subsubmode == CloseSquareSubSubMode)
+ bracketSearchForward(&m_cursor, _("^\\}"), count(), false);
+ else if (input.is(']') && g.subsubmode == OpenSquareSubSubMode)
+ bracketSearchBackward(&m_cursor, _("^\\}"), count());
+ else if (input.is(']') && g.subsubmode == CloseSquareSubSubMode)
+ bracketSearchForward(&m_cursor, _("^\\{"), count(), g.submode != NoSubMode);
else if (input.is('z'))
- emit q->foldGoTo(m_subsubmode == OpenSquareSubSubMode ? -count() : count(), true);
+ emit q->foldGoTo(g.subsubmode == OpenSquareSubSubMode ? -count() : count(), true);
handled = pos != position();
if (handled) {
+ if (lineForPosition(pos) != lineForPosition(position()))
+ recordJump(pos);
finishMovement(QString::fromLatin1("%1%2%3")
.arg(count())
- .arg(m_subsubmode == OpenSquareSubSubMode ? '[' : ']')
+ .arg(g.subsubmode == OpenSquareSubSubMode ? '[' : ']')
.arg(input.text()));
}
} else {
@@ -3279,7 +3451,7 @@ bool FakeVimHandler::Private::handleCount(const Input &input)
{
if (!isInputCount(input))
return false;
- m_mvcount.append(input.text());
+ g.mvcount = g.mvcount * 10 + input.text().toInt();
return true;
}
@@ -3292,44 +3464,44 @@ bool FakeVimHandler::Private::handleMovement(const Input &input)
if (handleCount(input)) {
return true;
} else if (input.is('0')) {
- m_movetype = MoveExclusive;
+ g.movetype = MoveExclusive;
moveToStartOfLine();
setTargetColumn();
count = 1;
} else if (input.is('a') || input.is('i')) {
- m_subsubmode = TextObjectSubSubMode;
- m_subsubdata = input;
+ g.subsubmode = TextObjectSubSubMode;
+ g.subsubdata = input;
} else if (input.is('^') || input.is('_')) {
moveToFirstNonBlankOnLine();
setTargetColumn();
- m_movetype = MoveExclusive;
+ g.movetype = MoveExclusive;
} else if (0 && input.is(',')) {
// FIXME: fakevim uses ',' by itself, so it is incompatible
- m_subsubmode = FtSubSubMode;
+ g.subsubmode = FtSubSubMode;
// HACK: toggle 'f' <-> 'F', 't' <-> 'T'
- //m_subsubdata = m_semicolonType ^ 32;
- handleFfTt(m_semicolonKey);
- m_subsubmode = NoSubSubMode;
+ //g.subsubdata = g.semicolonType ^ 32;
+ handleFfTt(g.semicolonKey);
+ g.subsubmode = NoSubSubMode;
} else if (input.is(';')) {
- m_subsubmode = FtSubSubMode;
- m_subsubdata = m_semicolonType;
- handleFfTt(m_semicolonKey);
- m_subsubmode = NoSubSubMode;
+ g.subsubmode = FtSubSubMode;
+ g.subsubdata = g.semicolonType;
+ handleFfTt(g.semicolonKey);
+ g.subsubmode = NoSubSubMode;
} else if (input.is('/') || input.is('?')) {
g.lastSearchForward = input.is('/');
if (hasConfig(ConfigUseCoreSearch)) {
// re-use the core dialog.
g.findPending = true;
m_findStartPosition = position();
- m_movetype = MoveExclusive;
+ g.movetype = MoveExclusive;
setAnchor(); // clear selection: otherwise, search is restricted to selection
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.
g.currentMessage.clear();
- m_movetype = MoveExclusive;
- m_subsubmode = SearchSubSubMode;
+ g.movetype = MoveExclusive;
+ g.subsubmode = SearchSubSubMode;
g.searchBuffer.setPrompt(g.lastSearchForward ? QLatin1Char('/') : QLatin1Char('?'));
m_searchStartPosition = position();
m_searchFromScreenLine = firstVisibleLine();
@@ -3337,24 +3509,24 @@ bool FakeVimHandler::Private::handleMovement(const Input &input)
g.searchBuffer.clear();
}
} else if (input.is('`')) {
- m_subsubmode = BackTickSubSubMode;
+ g.subsubmode = BackTickSubSubMode;
} else if (input.is('#') || input.is('*')) {
// FIXME: That's not proper vim behaviour
QString needle;
QTextCursor tc = m_cursor;
tc.select(QTextCursor::WordUnderCursor);
needle = QRegExp::escape(tc.selection().toPlainText());
- if (!m_gflag)
+ if (!g.gflag)
needle = _("\\<") + needle + _("\\>");
setAnchorAndPosition(tc.position(), tc.anchor());
g.searchBuffer.historyPush(needle);
g.lastSearch = needle;
g.lastSearchForward = input.is('*');
- searchNext();
+ handled = searchNext();
} else if (input.is('\'')) {
- m_subsubmode = TickSubSubMode;
- if (m_submode != NoSubMode)
- m_movetype = MoveLineWise;
+ g.subsubmode = TickSubSubMode;
+ if (g.submode != NoSubMode)
+ g.movetype = MoveLineWise;
} else if (input.is('|')) {
moveToStartOfLine();
moveRight(qMin(count, rightDist()) - 1);
@@ -3367,17 +3539,17 @@ bool FakeVimHandler::Private::handleMovement(const Input &input)
moveToStartOfLine();
moveDown();
moveToFirstNonBlankOnLine();
- m_movetype = MoveLineWise;
+ g.movetype = MoveLineWise;
} else if (input.is('-')) {
moveToStartOfLine();
moveUp(count);
moveToFirstNonBlankOnLine();
- m_movetype = MoveLineWise;
+ g.movetype = MoveLineWise;
} else if (input.is('+')) {
moveToStartOfLine();
moveDown(count);
moveToFirstNonBlankOnLine();
- m_movetype = MoveLineWise;
+ g.movetype = MoveLineWise;
} else if (input.isKey(Key_Home)) {
moveToStartOfLine();
setTargetColumn();
@@ -3386,49 +3558,49 @@ bool FakeVimHandler::Private::handleMovement(const Input &input)
if (count > 1)
moveDown(count - 1);
moveToEndOfLine();
- m_movetype = atEmptyLine() ? MoveExclusive : MoveInclusive;
+ g.movetype = atEmptyLine() ? MoveExclusive : MoveInclusive;
setTargetColumn();
- if (m_submode == NoSubMode)
+ if (g.submode == NoSubMode)
m_targetColumn = -1;
if (isVisualMode())
m_visualTargetColumn = -1;
movement = _("$");
} else if (input.is('%')) {
recordJump();
- if (m_mvcount.isEmpty()) {
+ if (g.mvcount == 0) {
moveToMatchingParanthesis();
- m_movetype = MoveInclusive;
+ g.movetype = MoveInclusive;
} else {
// set cursor position in percentage - formula taken from Vim help
setPosition(firstPositionInLine((count * linesInDocument() + 99) / 100));
moveToTargetColumn();
handleStartOfLine();
- m_movetype = MoveLineWise;
+ g.movetype = MoveLineWise;
}
} else if (input.is('b') || input.isShift(Key_Left)) {
- m_movetype = MoveExclusive;
+ g.movetype = MoveExclusive;
moveToNextWordStart(count, false, false);
setTargetColumn();
movement = _("b");
} else if (input.is('B')) {
- m_movetype = MoveExclusive;
+ g.movetype = MoveExclusive;
moveToNextWordStart(count, true, false);
setTargetColumn();
- } else if (input.is('e') && m_gflag) {
- m_movetype = MoveInclusive;
+ } else if (input.is('e') && g.gflag) {
+ g.movetype = MoveInclusive;
moveToNextWordEnd(count, false, false);
setTargetColumn();
} else if (input.is('e') || input.isShift(Key_Right)) {
- m_movetype = MoveInclusive;
+ g.movetype = MoveInclusive;
moveToNextWordEnd(count, false, true, false);
setTargetColumn();
movement = _("e");
- } else if (input.is('E') && m_gflag) {
- m_movetype = MoveInclusive;
+ } else if (input.is('E') && g.gflag) {
+ g.movetype = MoveInclusive;
moveToNextWordEnd(count, true, false);
setTargetColumn();
} else if (input.is('E')) {
- m_movetype = MoveInclusive;
+ g.movetype = MoveInclusive;
moveToNextWordEnd(count, true, true, false);
setTargetColumn();
} else if (input.isControl('e')) {
@@ -3438,37 +3610,37 @@ bool FakeVimHandler::Private::handleMovement(const Input &input)
scrollDown(1);
movement = _("<C-E>");
} else if (input.is('f')) {
- m_subsubmode = FtSubSubMode;
- m_movetype = MoveInclusive;
- m_subsubdata = input;
+ g.subsubmode = FtSubSubMode;
+ g.movetype = MoveInclusive;
+ g.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;
+ g.subsubmode = FtSubSubMode;
+ g.movetype = MoveExclusive;
+ g.subsubdata = input;
+ } else if (!g.gflag && input.is('g')) {
+ g.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())
+ if (input.is('G') && g.mvcount == 0)
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) {
+ n = g.mvcount == 0 ? n : count;
+ if (g.submode == NoSubMode || g.submode == ZSubMode
+ || g.submode == CapitalZSubMode || g.submode == RegisterSubMode) {
setPosition(firstPositionInLine(n, false));
handleStartOfLine();
} else {
- m_movetype = MoveLineWise;
- m_rangemode = RangeLineMode;
+ g.movetype = MoveLineWise;
+ g.rangemode = RangeLineMode;
setAnchor();
setPosition(firstPositionInLine(n, false));
}
setTargetColumn();
updateScrollOffset();
} else if (input.is('h') || input.isKey(Key_Left) || input.isBackspace()) {
- m_movetype = MoveExclusive;
+ g.movetype = MoveExclusive;
int n = qMin(count, leftDist());
if (m_fakeEnd && block().length() > 1)
++n;
@@ -3481,17 +3653,17 @@ bool FakeVimHandler::Private::handleMovement(const Input &input)
handleStartOfLine();
} else if (input.is('j') || input.isKey(Key_Down)
|| input.isControl('j') || input.isControl('n')) {
- m_movetype = MoveLineWise;
+ g.movetype = MoveLineWise;
moveDown(count);
movement = _("j");
} else if (input.is('k') || input.isKey(Key_Up) || input.isControl('p')) {
- m_movetype = MoveLineWise;
+ g.movetype = MoveLineWise;
moveUp(count);
movement = _("k");
} else if (input.is('l') || input.isKey(Key_Right) || input.is(' ')) {
- m_movetype = MoveExclusive;
+ g.movetype = MoveExclusive;
bool pastEnd = count >= rightDist() - 1;
- moveRight(qMax(0, qMin(count, rightDist() - (m_submode == NoSubMode))));
+ moveRight(qMax(0, qMin(count, rightDist() - (g.submode == NoSubMode))));
setTargetColumn();
if (pastEnd && isVisualMode())
m_visualTargetColumn = -1;
@@ -3499,7 +3671,7 @@ bool FakeVimHandler::Private::handleMovement(const Input &input)
const CursorPosition pos(lineToBlockNumber(lineOnBottom(count)), 0);
setCursorPosition(&m_cursor, pos);
handleStartOfLine();
- } else if (m_gflag && input.is('m')) {
+ } else if (g.gflag && input.is('m')) {
moveToStartOfLine();
moveRight(qMin(columnsOnScreen() / 2, rightDist()) - 1);
setTargetColumn();
@@ -3517,41 +3689,41 @@ bool FakeVimHandler::Private::handleMovement(const Input &input)
}
setPosition(m_cursor.selectionStart());
} else {
- searchNext(input.is('n'));
+ handled = searchNext(input.is('n'));
}
} else if (input.is('t')) {
- m_movetype = MoveInclusive;
- m_subsubmode = FtSubSubMode;
- m_subsubdata = input;
+ g.movetype = MoveInclusive;
+ g.subsubmode = FtSubSubMode;
+ g.subsubdata = input;
} else if (input.is('T')) {
- m_movetype = MoveExclusive;
- m_subsubmode = FtSubSubMode;
- m_subsubdata = input;
+ g.movetype = MoveExclusive;
+ g.subsubmode = FtSubSubMode;
+ g.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) {
+ if (g.submode == ChangeSubMode) {
moveToWordEnd(count, simple, true);
- m_movetype = MoveInclusive;
+ g.movetype = MoveInclusive;
} else {
moveToNextWordStart(count, simple, true);
// Command 'dw' deletes to the next word on the same line or to end of line.
- if (m_submode == DeleteSubMode && count == 1) {
+ if (g.submode == DeleteSubMode && count == 1) {
const QTextBlock currentBlock = document()->findBlock(anchor());
setPosition(qMin(position(), currentBlock.position() + currentBlock.length()));
}
- m_movetype = MoveExclusive;
+ g.movetype = MoveExclusive;
}
setTargetColumn();
} else if (input.is('z')) {
- m_movetype = MoveLineWise;
- m_subsubmode = ZSubSubMode;
+ g.movetype = MoveLineWise;
+ g.subsubmode = ZSubSubMode;
} else if (input.is('[')) {
- m_subsubmode = OpenSquareSubSubMode;
+ g.subsubmode = OpenSquareSubSubMode;
} else if (input.is(']')) {
- m_subsubmode = CloseSquareSubSubMode;
+ g.subsubmode = CloseSquareSubSubMode;
} else if (input.isKey(Key_PageDown) || input.isControl('f')) {
movePageDown(count);
handleStartOfLine();
@@ -3560,20 +3732,18 @@ bool FakeVimHandler::Private::handleMovement(const Input &input)
movePageUp(count);
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) {
+ if (handled && g.subsubmode == NoSubSubMode) {
+ if (g.submode == NoSubMode) {
resetCommandMode();
} else {
// finish movement for sub modes
const QString dotMovement =
(count > 1 ? QString::number(count) : QString())
- + _(m_gflag ? "g" : "")
+ + _(g.gflag ? "g" : "")
+ (movement.isNull() ? QString(input.asChar()) : movement);
finishMovement(dotMovement);
setTargetColumn();
@@ -3587,65 +3757,66 @@ EventResult FakeVimHandler::Private::handleCommandMode(const Input &input)
{
bool handled = false;
- bool clearGflag = m_gflag;
- bool clearRegister = m_submode != RegisterSubMode;
- bool clearCount = m_submode != RegisterSubMode && !isInputCount(input);
+ bool clearGflag = g.gflag;
+ bool clearRegister = g.submode != RegisterSubMode;
+ bool clearCount = g.submode != RegisterSubMode && !isInputCount(input);
// Process input for a sub-mode.
if (input.isEscape()) {
handled = handleEscape();
- } else if (m_subsubmode != NoSubSubMode) {
+ } else if (g.subsubmode != NoSubSubMode) {
handled = handleCommandSubSubMode(input);
- } else if (m_submode == NoSubMode) {
+ } else if (g.submode == NoSubMode) {
handled = handleNoSubMode(input);
- } else if (m_submode == ChangeSubMode || m_submode == DeleteSubMode) {
+ } else if (g.submode == ChangeSubMode || g.submode == DeleteSubMode) {
handled = handleChangeDeleteSubModes(input);
- } else if (m_submode == ReplaceSubMode) {
+ } else if (g.submode == ReplaceSubMode) {
handled = handleReplaceSubMode(input);
- } else if (m_submode == FilterSubMode) {
+ } else if (g.submode == FilterSubMode) {
handled = handleFilterSubMode(input);
- } else if (m_submode == RegisterSubMode) {
+ } else if (g.submode == RegisterSubMode) {
handled = handleRegisterSubMode(input);
- } else if (m_submode == WindowSubMode) {
+ } else if (g.submode == WindowSubMode) {
handled = handleWindowSubMode(input);
- } else if (m_submode == YankSubMode) {
+ } else if (g.submode == YankSubMode) {
handled = handleYankSubMode(input);
- } else if (m_submode == ZSubMode) {
+ } else if (g.submode == ZSubMode) {
handled = handleZSubMode(input);
- } else if (m_submode == CapitalZSubMode) {
+ } else if (g.submode == CapitalZSubMode) {
handled = handleCapitalZSubMode(input);
- } else if (m_submode == MacroRecordSubMode) {
+ } else if (g.submode == MacroRecordSubMode) {
handled = handleMacroRecordSubMode(input);
- } else if (m_submode == MacroExecuteSubMode) {
+ } else if (g.submode == MacroExecuteSubMode) {
handled = handleMacroExecuteSubMode(input);
- } else if (m_submode == ShiftLeftSubMode
- || m_submode == ShiftRightSubMode
- || m_submode == IndentSubMode) {
+ } else if (g.submode == ShiftLeftSubMode
+ || g.submode == ShiftRightSubMode
+ || g.submode == IndentSubMode) {
handled = handleShiftSubMode(input);
- } else if (m_submode == InvertCaseSubMode
- || m_submode == DownCaseSubMode
- || m_submode == UpCaseSubMode) {
+ } else if (g.submode == InvertCaseSubMode
+ || g.submode == DownCaseSubMode
+ || g.submode == UpCaseSubMode) {
handled = handleChangeCaseSubMode(input);
}
+ if (!handled && isOperatorPending())
+ handled = handleMovement(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;
+ (g.mode == CommandMode && g.submode == NoSubMode && g.subsubmode == NoSubSubMode);
+ clearCount = clearCount && noMode && !g.gflag;
if (clearCount && clearRegister) {
resetCommandMode();
} else {
// Use gflag only for next input.
if (clearGflag)
- m_gflag = false;
+ g.gflag = false;
// Clear [count] and [register] if its no longer needed.
- if (clearCount) {
- m_mvcount.clear();
- m_opcount.clear();
- }
+ if (clearCount)
+ resetCount();
// Show or clear current command on minibuffer (showcmd).
- if (input.isEscape() || m_mode != CommandMode || clearCount)
+ if (input.isEscape() || g.mode != CommandMode || clearCount)
g.currentCommand.clear();
else
g.currentCommand.append(input.toString());
@@ -3653,7 +3824,7 @@ EventResult FakeVimHandler::Private::handleCommandMode(const Input &input)
} else {
resetCommandMode();
//qDebug() << "IGNORED IN COMMAND MODE: " << key << text
- // << " VISUAL: " << m_visualMode;
+ // << " VISUAL: " << g.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
@@ -3681,15 +3852,15 @@ bool FakeVimHandler::Private::handleNoSubMode(const Input &input)
bool handled = true;
if (input.is('&')) {
- handleExCommand(m_gflag ? _("%s//~/&") : _("s"));
+ handleExCommand(g.gflag ? _("%s//~/&") : _("s"));
} else if (input.is(':')) {
enterExMode();
} else if (input.is('!') && isNoVisualMode()) {
- m_submode = FilterSubMode;
+ g.submode = FilterSubMode;
} else if (input.is('!') && isVisualMode()) {
enterExMode(QString::fromLatin1("!"));
} else if (input.is('"')) {
- m_submode = RegisterSubMode;
+ g.submode = RegisterSubMode;
} else if (input.is(',')) {
passShortcuts(true);
} else if (input.is('.')) {
@@ -3705,11 +3876,11 @@ bool FakeVimHandler::Private::handleNoSubMode(const Input &input)
} else if (input.is('<') || input.is('>') || input.is('=')) {
if (isNoVisualMode()) {
if (input.is('<'))
- m_submode = ShiftLeftSubMode;
+ g.submode = ShiftLeftSubMode;
else if (input.is('>'))
- m_submode = ShiftRightSubMode;
+ g.submode = ShiftRightSubMode;
else
- m_submode = IndentSubMode;
+ g.submode = IndentSubMode;
setAnchor();
} else {
leaveVisualMode();
@@ -3746,22 +3917,22 @@ bool FakeVimHandler::Private::handleNoSubMode(const Input &input)
setDotCommand(_("%1<c-a>"), count());
} else if ((input.is('c') || input.is('d')) && isNoVisualMode()) {
setAnchor();
- m_opcount = m_mvcount;
- m_mvcount.clear();
- m_rangemode = RangeCharMode;
- m_movetype = MoveExclusive;
- m_submode = input.is('c') ? ChangeSubMode : DeleteSubMode;
+ g.opcount = g.mvcount;
+ g.mvcount = 0;
+ g.rangemode = RangeCharMode;
+ g.movetype = MoveExclusive;
+ g.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());
leaveVisualMode();
- m_submode = ChangeSubMode;
+ g.submode = ChangeSubMode;
finishMovement();
} else if (input.is('C')) {
setAnchor();
moveToEndOfLine();
- m_rangemode = RangeCharMode;
- m_submode = ChangeSubMode;
+ g.rangemode = RangeCharMode;
+ g.submode = ChangeSubMode;
setDotCommand(QString(QLatin1Char('C')));
finishMovement();
} else if (input.isControl('c')) {
@@ -3775,7 +3946,7 @@ bool FakeVimHandler::Private::handleNoSubMode(const Input &input)
setDotCommand(visualDotCommand() + QLatin1Char('x'));
if (isVisualCharMode()) {
leaveVisualMode();
- m_submode = DeleteSubMode;
+ g.submode = DeleteSubMode;
finishMovement();
} else if (isVisualLineMode()) {
leaveVisualMode();
@@ -3792,8 +3963,8 @@ bool FakeVimHandler::Private::handleNoSubMode(const Input &input)
pushUndoState();
if (atEndOfLine())
moveLeft();
- m_submode = DeleteSubMode;
- m_movetype = MoveInclusive;
+ g.submode = DeleteSubMode;
+ g.movetype = MoveInclusive;
setAnchorAndPosition(position(), lastPositionInLine(cursorLine() + count()));
setDotCommand(QString(QLatin1Char('D')));
finishMovement();
@@ -3802,15 +3973,15 @@ bool FakeVimHandler::Private::handleNoSubMode(const Input &input)
(isVisualCharMode() || isVisualLineMode())) {
setDotCommand(visualDotCommand() + QLatin1Char('X'));
leaveVisualMode();
- m_rangemode = RangeLineMode;
- m_submode = NoSubMode;
+ g.rangemode = RangeLineMode;
+ g.submode = NoSubMode;
yankText(currentRange(), m_register);
removeText(currentRange());
moveToFirstNonBlankOnLine();
} else if ((input.is('D') || input.is('X')) && isVisualBlockMode()) {
setDotCommand(visualDotCommand() + QLatin1Char('X'));
leaveVisualMode();
- m_rangemode = RangeBlockAndTailMode;
+ g.rangemode = RangeBlockAndTailMode;
yankText(currentRange(), m_register);
removeText(currentRange());
setPosition(qMin(position(), anchor()));
@@ -3821,8 +3992,8 @@ bool FakeVimHandler::Private::handleNoSubMode(const Input &input)
moveDown(linesOnScreen() / 2);
handleStartOfLine();
scrollToLine(cursorLine() - sline);
- } else if (!m_gflag && input.is('g')) {
- m_gflag = true;
+ } else if (!g.gflag && input.is('g')) {
+ g.gflag = true;
} else if (!isVisualMode() && (input.is('i') || input.isKey(Key_Insert))) {
setDotCommand(_("%1i"), count());
breakEditBlock();
@@ -3833,7 +4004,7 @@ bool FakeVimHandler::Private::handleNoSubMode(const Input &input)
if (isVisualMode()) {
initVisualInsertMode(QLatin1Char('I'));
} else {
- if (m_gflag) {
+ if (g.gflag) {
setDotCommand(_("%1gI"), count());
moveToStartOfLine();
} else {
@@ -3851,14 +4022,14 @@ bool FakeVimHandler::Private::handleNoSubMode(const Input &input)
pushUndoState();
moveBehindEndOfLine();
beginEditBlock();
- if (m_submode == NoSubMode)
- joinLines(count(), m_gflag);
+ if (g.submode == NoSubMode)
+ joinLines(count(), g.gflag);
endEditBlock();
setDotCommand(_("%1J"), count());
} else if (input.isControl('l')) {
// screen redraw. should not be needed
} else if (input.is('m')) {
- m_subsubmode = MarkSubSubMode;
+ g.subsubmode = MarkSubSubMode;
} else if (isVisualMode() && (input.is('o') || input.is('O'))) {
int pos = position();
setAnchorAndPosition(pos, anchor());
@@ -3881,19 +4052,20 @@ bool FakeVimHandler::Private::handleNoSubMode(const Input &input)
}
const int line = lineNumber(block());
- enterInsertMode();
beginEditBlock();
+ enterInsertMode();
+ setPosition(appendLine ? lastPositionInLine(line) : firstPositionInLine(line));
+ clearLastInsertion();
+ setAnchor();
+ insertNewLine();
if (appendLine) {
- setPosition(lastPositionInLine(line));
- setAnchor();
- insertNewLine();
+ m_insertState.newLineBefore = true;
} else {
- setPosition(firstPositionInLine(line));
- setAnchor();
- insertNewLine();
moveUp();
+ m_oldPosition = position();
+ m_insertState.pos1 = m_oldPosition;
+ m_insertState.newLineAfter = true;
}
- recordInsertion(QString::fromLatin1("\n"));
setTargetColumn();
endEditBlock();
@@ -3916,13 +4088,13 @@ bool FakeVimHandler::Private::handleNoSubMode(const Input &input)
// Recording shouldn't work in mapping or while executing register.
handled = g.mapStates.empty();
if (handled)
- m_submode = MacroRecordSubMode;
+ g.submode = MacroRecordSubMode;
} else {
// Stop recording.
stopRecording();
}
} else if (input.is('r')) {
- m_submode = ReplaceSubMode;
+ g.submode = ReplaceSubMode;
} else if (!isVisualMode() && input.is('R')) {
pushUndoState();
breakEditBlock();
@@ -3932,8 +4104,7 @@ bool FakeVimHandler::Private::handleNoSubMode(const Input &input)
while (--repeat >= 0)
redo();
} else if (input.is('s') && isVisualBlockMode()) {
- m_opcount.clear();
- m_mvcount.clear();
+ resetCount();
pushUndoState();
beginEditBlock();
initVisualInsertMode(QLatin1Char('s'));
@@ -3947,11 +4118,11 @@ bool FakeVimHandler::Private::handleNoSubMode(const Input &input)
setAnchor();
moveRight(qMin(count(), rightDist()));
setDotCommand(_("%1s"), count());
- m_submode = ChangeSubMode;
- m_movetype = MoveExclusive;
+ g.submode = ChangeSubMode;
+ g.movetype = MoveExclusive;
finishMovement();
} else if (input.is('S')) {
- m_movetype = MoveLineWise;
+ g.movetype = MoveLineWise;
pushUndoState();
if (!isVisualMode()) {
const int line = cursorLine() + 1;
@@ -3960,15 +4131,15 @@ bool FakeVimHandler::Private::handleNoSubMode(const Input &input)
setAnchorAndPosition(anc, pos);
}
setDotCommand(_("%1S"), count());
- m_submode = ChangeSubMode;
+ g.submode = ChangeSubMode;
finishMovement();
- } else if (m_gflag && input.is('t')) {
+ } else if (g.gflag && input.is('t')) {
handleExCommand(_("tabnext"));
- } else if (m_gflag && input.is('T')) {
+ } else if (g.gflag && input.is('T')) {
handleExCommand(_("tabprev"));
} else if (input.isControl('t')) {
handleExCommand(_("pop"));
- } else if (!m_gflag && input.is('u') && !isVisualMode()) {
+ } else if (!g.gflag && input.is('u') && !isVisualMode()) {
int repeat = count();
while (--repeat >= 0)
undo();
@@ -3978,7 +4149,7 @@ bool FakeVimHandler::Private::handleNoSubMode(const Input &input)
moveUp(linesOnScreen() / 2);
handleStartOfLine();
scrollToLine(cursorLine() - sline);
- } else if (m_gflag && input.is('v')) {
+ } else if (g.gflag && input.is('v')) {
if (m_lastVisualMode != NoVisualMode) {
CursorPosition from = mark(QLatin1Char('<')).position;
CursorPosition to = mark(QLatin1Char('>')).position;
@@ -3995,10 +4166,10 @@ bool FakeVimHandler::Private::handleNoSubMode(const Input &input)
} else if (input.isControl('v')) {
toggleVisualMode(VisualBlockMode);
} else if (input.isControl('w')) {
- m_submode = WindowSubMode;
+ g.submode = WindowSubMode;
} else if (input.is('x') && isNoVisualMode()) { // = _("dl")
- m_movetype = MoveExclusive;
- m_submode = DeleteSubMode;
+ g.movetype = MoveExclusive;
+ g.submode = DeleteSubMode;
const int n = qMin(count(), rightDist());
setAnchorAndPosition(position(), position() + n);
setDotCommand(_("%1x"), count());
@@ -4022,56 +4193,56 @@ bool FakeVimHandler::Private::handleNoSubMode(const Input &input)
scrollUp(1);
} else if (input.is('y') && isNoVisualMode()) {
setAnchor();
- m_rangemode = RangeCharMode;
- m_movetype = MoveExclusive;
- m_submode = YankSubMode;
+ g.rangemode = RangeCharMode;
+ g.movetype = MoveExclusive;
+ g.submode = YankSubMode;
} else if (input.is('y') && isVisualCharMode()) {
- m_rangemode = RangeCharMode;
- m_movetype = MoveInclusive;
- m_submode = YankSubMode;
+ g.rangemode = RangeCharMode;
+ g.movetype = MoveInclusive;
+ g.submode = YankSubMode;
finishMovement();
} else if ((input.is('y') && isVisualLineMode())
|| (input.is('Y') && isVisualLineMode())
|| (input.is('Y') && isVisualCharMode())) {
- m_rangemode = RangeLineMode;
- m_movetype = MoveLineWise;
- m_submode = YankSubMode;
+ g.rangemode = RangeLineMode;
+ g.movetype = MoveLineWise;
+ g.submode = YankSubMode;
finishMovement();
} else if ((input.is('y') || input.is('Y')) && isVisualBlockMode()) {
- m_rangemode = RangeBlockMode;
- m_movetype = MoveInclusive;
- m_submode = YankSubMode;
+ g.rangemode = RangeBlockMode;
+ g.movetype = MoveInclusive;
+ g.submode = YankSubMode;
finishMovement();
} else if (input.is('z')) {
- m_submode = ZSubMode;
+ g.submode = ZSubMode;
} else if (input.is('Z')) {
- m_submode = CapitalZSubMode;
+ g.submode = CapitalZSubMode;
} else if ((input.is('~') || input.is('u') || input.is('U'))) {
- m_movetype = MoveExclusive;
+ g.movetype = MoveExclusive;
if (isVisualMode()) {
if (isVisualLineMode())
- m_rangemode = RangeLineMode;
+ g.rangemode = RangeLineMode;
else if (isVisualBlockMode())
- m_rangemode = RangeBlockMode;
+ g.rangemode = RangeBlockMode;
leaveVisualMode();
if (input.is('~'))
- m_submode = InvertCaseSubMode;
+ g.submode = InvertCaseSubMode;
else if (input.is('u'))
- m_submode = DownCaseSubMode;
+ g.submode = DownCaseSubMode;
else if (input.is('U'))
- m_submode = UpCaseSubMode;
+ g.submode = UpCaseSubMode;
finishMovement();
- } else if (m_gflag || (input.is('~') && hasConfig(ConfigTildeOp))) {
+ } else if (g.gflag || (input.is('~') && hasConfig(ConfigTildeOp))) {
pushUndoState();
if (atEndOfLine())
moveLeft();
setAnchor();
if (input.is('~'))
- m_submode = InvertCaseSubMode;
+ g.submode = InvertCaseSubMode;
else if (input.is('u'))
- m_submode = DownCaseSubMode;
+ g.submode = DownCaseSubMode;
else if (input.is('U'))
- m_submode = UpCaseSubMode;
+ g.submode = UpCaseSubMode;
} else {
beginEditBlock();
if (atEndOfLine())
@@ -4091,7 +4262,7 @@ bool FakeVimHandler::Private::handleNoSubMode(const Input &input)
endEditBlock();
}
} else if (input.is('@')) {
- m_submode = MacroExecuteSubMode;
+ g.submode = MacroExecuteSubMode;
} else if (input.isKey(Key_Delete)) {
setAnchor();
moveRight(qMin(1, rightDist()));
@@ -4113,23 +4284,21 @@ 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;
+ if ((g.submode == ChangeSubMode && input.is('c'))
+ || (g.submode == DeleteSubMode && input.is('d'))) {
+ g.movetype = MoveLineWise;
pushUndoState();
const int anc = firstPositionInLine(cursorLine() + 1);
moveDown(count() - 1);
const int pos = lastPositionInLine(cursorLine() + 1);
setAnchorAndPosition(anc, pos);
- if (m_submode == ChangeSubMode)
+ if (g.submode == ChangeSubMode)
setDotCommand(_("%1cc"), count());
else
setDotCommand(_("%1dd"), count());
finishMovement();
- m_submode = NoSubMode;
+ g.submode = NoSubMode;
handled = true;
- } else {
- handled = handleMovement(input);
}
return handled;
@@ -4143,14 +4312,14 @@ bool FakeVimHandler::Private::handleReplaceSubMode(const Input &input)
if (isVisualMode()) {
pushUndoState();
if (isVisualLineMode())
- m_rangemode = RangeLineMode;
+ g.rangemode = RangeLineMode;
else if (isVisualBlockMode())
- m_rangemode = RangeBlockMode;
+ g.rangemode = RangeBlockMode;
else
- m_rangemode = RangeCharMode;
+ g.rangemode = RangeCharMode;
leaveVisualMode();
Range range = currentRange();
- if (m_rangemode == RangeCharMode)
+ if (g.rangemode == RangeCharMode)
++range.endPos;
Transformation tr =
&FakeVimHandler::Private::replaceByCharTransform;
@@ -4174,15 +4343,15 @@ bool FakeVimHandler::Private::handleReplaceSubMode(const Input &input)
} else {
handled = false;
}
- m_submode = NoSubMode;
+ g.submode = NoSubMode;
finishMovement();
return handled;
}
-bool FakeVimHandler::Private::handleFilterSubMode(const Input &input)
+bool FakeVimHandler::Private::handleFilterSubMode(const Input &)
{
- return handleMovement(input);
+ return false;
}
bool FakeVimHandler::Private::handleRegisterSubMode(const Input &input)
@@ -4192,10 +4361,10 @@ bool FakeVimHandler::Private::handleRegisterSubMode(const Input &input)
QChar reg = input.asChar();
if (QString::fromLatin1("*+.%#:-\"").contains(reg) || reg.isLetterOrNumber()) {
m_register = reg.unicode();
- m_rangemode = RangeLineMode;
+ g.rangemode = RangeLineMode;
handled = true;
}
- m_submode = NoSubMode;
+ g.submode = NoSubMode;
return handled;
}
@@ -4203,18 +4372,16 @@ bool FakeVimHandler::Private::handleRegisterSubMode(const Input &input)
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;
+ if ((g.submode == ShiftLeftSubMode && input.is('<'))
+ || (g.submode == ShiftRightSubMode && input.is('>'))
+ || (g.submode == IndentSubMode && input.is('='))) {
+ g.movetype = MoveLineWise;
pushUndoState();
moveDown(count() - 1);
setDotCommand(QString::fromLatin1("%2%1%1").arg(input.asChar()), count());
finishMovement();
handled = true;
- m_submode = NoSubMode;
- } else {
- handled = handleMovement(input);
+ g.submode = NoSubMode;
}
return handled;
}
@@ -4222,9 +4389,9 @@ bool FakeVimHandler::Private::handleShiftSubMode(const Input &input)
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 ((g.submode == InvertCaseSubMode && input.is('~'))
+ || (g.submode == DownCaseSubMode && input.is('u'))
+ || (g.submode == UpCaseSubMode && input.is('U'))) {
if (!isFirstNonBlankOnLine(position())) {
moveToStartOfLine();
moveToFirstNonBlankOnLine();
@@ -4235,9 +4402,7 @@ bool FakeVimHandler::Private::handleChangeCaseSubMode(const Input &input)
setPosition(lastPositionInLine(cursorLine() + count()) + 1);
finishMovement(QString::fromLatin1("%1%2").arg(count()).arg(input.raw()));
handled = true;
- m_submode = NoSubMode;
- } else {
- handled = handleMovement(input);
+ g.submode = NoSubMode;
}
return handled;
}
@@ -4247,9 +4412,10 @@ bool FakeVimHandler::Private::handleWindowSubMode(const Input &input)
if (handleCount(input))
return true;
+ leaveVisualMode();
emit q->windowCommandRequested(input.toString(), count());
- m_submode = NoSubMode;
+ g.submode = NoSubMode;
return true;
}
@@ -4257,14 +4423,12 @@ bool FakeVimHandler::Private::handleYankSubMode(const Input &input)
{
bool handled = false;
if (input.is('y')) {
- m_movetype = MoveLineWise;
+ g.movetype = MoveLineWise;
int endPos = firstPositionInLine(lineForPosition(position()) + count() - 1);
Range range(position(), endPos, RangeLineMode);
yankText(range, m_register);
- m_submode = NoSubMode;
+ g.submode = NoSubMode;
handled = true;
- } else {
- handled = handleMovement(input);
}
return handled;
}
@@ -4285,7 +4449,7 @@ bool FakeVimHandler::Private::handleZSubMode(const Input &input)
else
align = Qt::AlignBottom;
const bool moveToNonBlank = (input.is('.') || input.isReturn() || input.is('-'));
- const int line = m_mvcount.isEmpty() ? -1 : firstPositionInLine(count());
+ const int line = g.mvcount == 0 ? -1 : firstPositionInLine(count());
alignViewportToCursor(align, line, moveToNonBlank);
} else if (input.is('o') || input.is('c')) {
// Open/close current fold.
@@ -4310,7 +4474,7 @@ bool FakeVimHandler::Private::handleZSubMode(const Input &input)
}
if (foldMaybeClosed)
ensureCursorVisible();
- m_submode = NoSubMode;
+ g.submode = NoSubMode;
return handled;
}
@@ -4324,19 +4488,19 @@ bool FakeVimHandler::Private::handleCapitalZSubMode(const Input &input)
handleExCommand(_("q!"));
else
handled = false;
- m_submode = NoSubMode;
+ g.submode = NoSubMode;
return handled;
}
bool FakeVimHandler::Private::handleMacroRecordSubMode(const Input &input)
{
- m_submode = NoSubMode;
+ g.submode = NoSubMode;
return startRecording(input);
}
bool FakeVimHandler::Private::handleMacroExecuteSubMode(const Input &input)
{
- m_submode = NoSubMode;
+ g.submode = NoSubMode;
bool result = true;
int repeat = count();
@@ -4346,44 +4510,58 @@ bool FakeVimHandler::Private::handleMacroExecuteSubMode(const Input &input)
return result;
}
-EventResult FakeVimHandler::Private::handleReplaceMode(const Input &input)
+EventResult FakeVimHandler::Private::handleInsertOrReplaceMode(const Input &input)
{
- bool clearLastInsertion = m_breakEditBlock;
- if (m_oldPosition != position()) {
- if (clearLastInsertion) {
- clearLastInsertion = false;
- m_lastInsertion = _("<INSERT>");
- }
- recordInsertion();
+ if (position() < m_insertState.pos1 || position() > m_insertState.pos2) {
+ commitInsertState();
+ invalidateInsertState();
}
+ if (g.mode == InsertMode)
+ handleInsertMode(input);
+ else
+ handleReplaceMode(input);
+
+ if (!m_textedit && !m_plaintextedit)
+ return EventHandled;
+
+ if (!isInsertMode() || m_breakEditBlock
+ || position() < m_insertState.pos1 || position() > m_insertState.pos2) {
+ commitInsertState();
+ invalidateInsertState();
+ breakEditBlock();
+ } else if (m_oldPosition == position()) {
+ setTargetColumn();
+ }
+
+ updateMiniBuffer();
+
+ // We don't want fancy stuff in insert mode.
+ return EventHandled;
+}
+
+void FakeVimHandler::Private::handleReplaceMode(const Input &input)
+{
if (input.isEscape()) {
+ commitInsertState();
moveLeft(qMin(1, leftDist()));
enterCommandMode();
- g.dotCommand += m_lastInsertion;
- g.dotCommand += QChar(27);
+ g.dotCommand.append(m_lastInsertion + _("<ESC>"));
} else if (input.isKey(Key_Left)) {
- breakEditBlock();
- moveLeft(1);
+ moveLeft();
setTargetColumn();
} else if (input.isKey(Key_Right)) {
- breakEditBlock();
- moveRight(1);
+ moveRight();
setTargetColumn();
} else if (input.isKey(Key_Up)) {
- breakEditBlock();
- moveUp(1);
+ moveUp();
} else if (input.isKey(Key_Down)) {
- breakEditBlock();
- moveDown(1);
+ moveDown();
} else if (input.isKey(Key_Insert)) {
- m_mode = InsertMode;
- recordInsertion(_("<INSERT>"));
+ g.mode = InsertMode;
} else if (input.isControl('o')) {
enterCommandMode(ReplaceMode);
} else {
- if (clearLastInsertion)
- m_lastInsertion = _("<INSERT>");
joinPreviousEditBlock();
if (!atEndOfLine()) {
setAnchor();
@@ -4394,38 +4572,34 @@ EventResult FakeVimHandler::Private::handleReplaceMode(const Input &input)
setAnchor();
insertText(text);
endEditBlock();
- recordInsertion();
}
- m_oldPosition = position();
- updateMiniBuffer();
-
- return EventHandled;
}
-EventResult FakeVimHandler::Private::handleInsertMode(const Input &input)
+void FakeVimHandler::Private::handleInsertMode(const Input &input)
{
- bool clearLastInsertion = m_breakEditBlock && !m_lastInsertion.isEmpty();
- int pos2 = position();
- int len2 = document()->characterCount();
- if (m_oldPosition != pos2 || m_oldDocumentLength != len2) {
- if (clearLastInsertion) {
- clearLastInsertion = false;
- m_lastInsertion.clear();
- g.dotCommand = _("i");
- }
- recordInsertion(guessInsertCommand(m_oldPosition, pos2, m_oldDocumentLength, len2));
- }
-
- QString insert;
if (input.isEscape()) {
+ bool newLineAfter = m_insertState.newLineAfter;
+ bool newLineBefore = m_insertState.newLineBefore;
+
// Repeat insertion [count] times.
// One instance was already physically inserted while typing.
- if (!m_breakEditBlock && !m_lastInsertion.isEmpty()) {
- const QString text = m_lastInsertion;
- const int repeat = count();
+ if (!m_breakEditBlock && isInsertStateValid()) {
+ commitInsertState();
+
+ QString text = m_lastInsertion;
+ const QString dotCommand = g.dotCommand;
+ const int repeat = count() - 1;
m_lastInsertion.clear();
joinPreviousEditBlock();
- replay(text.repeated(repeat - 1));
+
+ if (newLineAfter) {
+ text.chop(1);
+ text.prepend(_("<END>\n"));
+ } else if (newLineBefore) {
+ text.prepend(_("<END>"));
+ }
+
+ replay(text, repeat);
if (m_visualBlockInsert && !text.contains(QLatin1Char('\n'))) {
const CursorPosition lastAnchor = mark(QLatin1Char('<')).position;
@@ -4433,7 +4607,7 @@ EventResult FakeVimHandler::Private::handleInsertMode(const Input &input)
CursorPosition startPos(lastAnchor.line,
qMin(lastPosition.column, lastAnchor.column));
CursorPosition pos = startPos;
- if (g.dotCommand.endsWith(QLatin1Char('A')))
+ if (dotCommand.endsWith(QLatin1Char('A')))
pos.column = qMax(lastPosition.column, lastAnchor.column) + 1;
while (pos.line < lastPosition.line) {
++pos.line;
@@ -4443,7 +4617,7 @@ EventResult FakeVimHandler::Private::handleInsertMode(const Input &input)
break;
m_cursor = tc;
if (tc.positionInBlock() == pos.column)
- replay(text.repeated(repeat));
+ replay(text, repeat + 1);
}
setCursorPosition(startPos);
@@ -4455,14 +4629,14 @@ EventResult FakeVimHandler::Private::handleInsertMode(const Input &input)
breakEditBlock();
m_lastInsertion = text;
+ g.dotCommand = dotCommand;
} else {
moveLeft(qMin(1, leftDist()));
}
- // 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>");
+ if (newLineBefore || newLineAfter)
+ m_lastInsertion.remove(0, m_lastInsertion.indexOf(QLatin1Char('\n')) + 1);
+ g.dotCommand.append(m_lastInsertion + _("<ESC>"));
enterCommandMode();
setTargetColumn();
@@ -4474,7 +4648,6 @@ EventResult FakeVimHandler::Private::handleInsertMode(const Input &input)
enterCommandMode(InsertMode);
} else if (input.isControl('v')) {
m_ctrlVActive = true;
- insert = _("<C-V>");
} else if (input.isControl('w')) {
const int blockNumber = m_cursor.blockNumber();
const int endPos = position();
@@ -4484,10 +4657,8 @@ EventResult FakeVimHandler::Private::handleInsertMode(const Input &input)
const int beginPos = position();
Range range(beginPos, endPos, RangeCharMode);
removeText(range);
- insert = _("<C-W>");
} else if (input.isKey(Key_Insert)) {
- m_mode = ReplaceMode;
- insert = _("<INSERT>");
+ g.mode = ReplaceMode;
} else if (input.isKey(Key_Left)) {
moveLeft();
setTargetColumn();
@@ -4495,12 +4666,10 @@ EventResult FakeVimHandler::Private::handleInsertMode(const Input &input)
moveToNextWordStart(1, false, false);
setTargetColumn();
} else if (input.isKey(Key_Down)) {
- //removeAutomaticIndentation();
- m_submode = NoSubMode;
+ g.submode = NoSubMode;
moveDown();
} else if (input.isKey(Key_Up)) {
- //removeAutomaticIndentation();
- m_submode = NoSubMode;
+ g.submode = NoSubMode;
moveUp();
} else if (input.isKey(Key_Right)) {
moveRight();
@@ -4517,17 +4686,15 @@ EventResult FakeVimHandler::Private::handleInsertMode(const Input &input)
setTargetColumn();
m_targetColumn = -1;
} else if (input.isReturn() || input.isControl('j') || input.isControl('m')) {
- if (!input.isReturn() || !handleInsertInEditor(input, &insert)) {
+ if (!input.isReturn() || !handleInsertInEditor(input)) {
joinPreviousEditBlock();
- m_submode = NoSubMode;
+ g.submode = NoSubMode;
insertNewLine();
- insert = _("\n");
endEditBlock();
}
} else if (input.isBackspace()) {
- if (!handleInsertInEditor(input, &insert)) {
+ if (!handleInsertInEditor(input)) {
joinPreviousEditBlock();
- m_justAutoIndented = 0;
if (!m_lastInsertion.isEmpty()
|| hasConfig(ConfigBackspace, "start")
|| hasConfig(ConfigBackspace, "2")) {
@@ -4548,34 +4715,29 @@ EventResult FakeVimHandler::Private::handleInsertMode(const Input &input)
m_cursor.deletePreviousChar();
}
}
- insert = _("<BS>");
endEditBlock();
}
} else if (input.isKey(Key_Delete)) {
- if (!handleInsertInEditor(input, &insert)) {
+ if (!handleInsertInEditor(input)) {
joinPreviousEditBlock();
m_cursor.deleteChar();
- insert = _("<DELETE>");
endEditBlock();
}
} else if (input.isKey(Key_PageDown) || input.isControl('f')) {
- removeAutomaticIndentation();
movePageDown();
} else if (input.isKey(Key_PageUp) || input.isControl('b')) {
- removeAutomaticIndentation();
movePageUp();
} else if (input.isKey(Key_Tab)) {
- m_justAutoIndented = 0;
+ m_insertState.insertingSpaces = true;
if (hasConfig(ConfigExpandTab)) {
const int ts = config(ConfigTabStop).toInt();
const int col = logicalCursorColumn();
QString str = QString(ts - col % ts, QLatin1Char(' '));
- m_lastInsertion.append(str);
insertText(str);
} else {
insertInInsertMode(input.raw());
}
- insert = _("\t");
+ m_insertState.insertingSpaces = false;
} else if (input.isControl('d')) {
// remove one level of indentation from the current line
int shift = config(ConfigShiftWidth).toInt();
@@ -4594,67 +4756,39 @@ EventResult FakeVimHandler::Private::handleInsertMode(const Input &input)
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 = m_cursor;
moveToNextWordStart(1, false, false);
QString str = selectText(Range(position(), tc.position()));
m_cursor = tc;
emit q->simpleCompletionRequested(str, input.isControl('n'));
- if (input.isControl('p'))
- insert = _("<C-P>");
- else
- insert = _("<C-N>");
} else if (input.isShift(Qt::Key_Insert)) {
// Insert text from clipboard.
QClipboard *clipboard = QApplication::clipboard();
const QMimeData *data = clipboard->mimeData();
if (data && data->hasText())
insertInInsertMode(data->text());
- insert = _("<S-INSERT>");
- } else {
- if (!handleInsertInEditor(input, &insert)) {
- insert = input.text();
- if (!insert.isEmpty()) {
- insertInInsertMode(insert);
- insert.replace(_("<"), _("<LT>"));
- } else {
- // We don't want fancy stuff in insert mode.
- return EventHandled;
- }
- }
- }
-
- if (insert.isNull()) {
- breakEditBlock();
- m_oldPosition = position();
- m_visualBlockInsert = false;
- m_mvcount.clear();
- m_opcount.clear();
} else {
- if (clearLastInsertion) {
- m_lastInsertion.clear();
- g.dotCommand = _("i");
+ m_insertState.insertingSpaces = input.isKey(Key_Space);
+ if (!handleInsertInEditor(input)) {
+ const QString toInsert = input.text();
+ if (toInsert.isEmpty())
+ return;
+ insertInInsertMode(toInsert);
}
- recordInsertion(insert);
+ m_insertState.insertingSpaces = false;
}
- updateMiniBuffer();
-
- return EventHandled;
}
void FakeVimHandler::Private::insertInInsertMode(const QString &text)
{
joinPreviousEditBlock();
- m_justAutoIndented = 0;
insertText(text);
if (hasConfig(ConfigSmartIndent) && isElectricCharacter(text.at(0))) {
const QString leftText = block().text()
.left(position() - 1 - block().position());
if (leftText.simplified().isEmpty()) {
- Range range(position(), position(), m_rangemode);
+ Range range(position(), position(), g.rangemode);
indentText(range, text.at(0));
}
}
@@ -4685,7 +4819,7 @@ void FakeVimHandler::Private::stopRecording()
{
// Remove q from end (stop recording command).
g.recording.remove(g.recording.size() - 1, 1);
- setRegister(g.currentRegister, g.recording, m_rangemode);
+ setRegister(g.currentRegister, g.recording, g.rangemode);
g.currentRegister = 0;
g.recording = QString();
}
@@ -4715,7 +4849,6 @@ EventResult FakeVimHandler::Private::handleExMode(const Input &input)
{
if (input.isEscape()) {
g.commandBuffer.clear();
- enterCommandMode(g.returnToMode);
resetCommandMode();
m_ctrlVActive = false;
} else if (m_ctrlVActive) {
@@ -4726,7 +4859,7 @@ EventResult FakeVimHandler::Private::handleExMode(const Input &input)
return EventHandled;
} else if (input.isBackspace()) {
if (g.commandBuffer.isEmpty()) {
- enterCommandMode(g.returnToMode);
+ leaveVisualMode();
resetCommandMode();
} else if (g.commandBuffer.hasSelection()) {
g.commandBuffer.deleteSelected();
@@ -4756,11 +4889,8 @@ EventResult FakeVimHandler::Private::handleSearchSubSubMode(const Input &input)
if (input.isEscape()) {
g.currentMessage.clear();
- g.searchBuffer.clear();
- setAnchorAndPosition(m_searchStartPosition, m_searchStartPosition);
+ setPosition(m_searchStartPosition);
scrollToLine(m_searchFromScreenLine);
- enterCommandMode(g.returnToMode);
- resetCommandMode();
} else if (input.isBackspace()) {
if (g.searchBuffer.isEmpty())
resetCommandMode();
@@ -4772,19 +4902,17 @@ EventResult FakeVimHandler::Private::handleSearchSubSubMode(const Input &input)
g.lastSearch = needle;
else
g.searchBuffer.setContents(g.lastSearch);
- if (!g.lastSearch.isEmpty()) {
- updateFind(true);
- finishMovement(g.searchBuffer.prompt() + g.lastSearch + QLatin1Char('\n'));
+
+ updateFind(true);
+
+ if (finishSearch()) {
+ if (g.submode != NoSubMode)
+ finishMovement(g.searchBuffer.prompt() + g.lastSearch + QLatin1Char('\n'));
+ if (g.currentMessage.isEmpty())
+ showMessage(MessageCommand, g.searchBuffer.display());
} else {
- finishMovement();
- }
- if (g.currentMessage.isEmpty())
- showMessage(MessageCommand, g.searchBuffer.display());
- else if (g.currentMessageLevel == MessageError)
handled = EventCancelled; // Not found so cancel mapping if any.
- enterCommandMode(g.returnToMode);
- resetCommandMode();
- g.searchBuffer.clear();
+ }
} else if (input.isKey(Key_Tab)) {
g.searchBuffer.insertChar(QChar(9));
} else if (!g.searchBuffer.handleInput(input)) {
@@ -4792,10 +4920,14 @@ EventResult FakeVimHandler::Private::handleSearchSubSubMode(const Input &input)
return EventUnhandled;
}
- updateMiniBuffer();
-
- if (!input.isReturn() && !input.isEscape())
+ if (input.isReturn() || input.isEscape()) {
+ g.searchBuffer.clear();
+ resetCommandMode();
+ updateMiniBuffer();
+ } else {
+ updateMiniBuffer();
updateFind(false);
+ }
return handled;
}
@@ -4888,7 +5020,7 @@ int FakeVimHandler::Private::parseLineAddress(QString *cmd)
void FakeVimHandler::Private::setCurrentRange(const Range &range)
{
setAnchorAndPosition(range.beginPos, range.endPos);
- m_rangemode = range.rangemode;
+ g.rangemode = range.rangemode;
}
bool FakeVimHandler::Private::parseExCommmand(QString *line, ExCommand *cmd)
@@ -5026,7 +5158,7 @@ bool FakeVimHandler::Private::handleExSubstituteCommand(const ExCommand &cmd)
int pos1 = findUnescaped(separator, line, 1);
if (pos1 == -1)
return false;
- int pos2 = findUnescaped(separator, line, pos1 + 1);;
+ int pos2 = findUnescaped(separator, line, pos1 + 1);
if (pos2 == -1)
pos2 = line.size();
@@ -5097,6 +5229,7 @@ bool FakeVimHandler::Private::handleExMapCommand(const ExCommand &cmd0) // :map
if (cmd == "vm" || cmd == "vmap") { modes = "v"; type = Map; } else
if (cmd == "xm" || cmd == "xmap") { modes = "x"; type = Map; } else
if (cmd == "smap") { modes = "s"; type = Map; } else
+ if (cmd == "omap") { modes = "o"; type = Map; } else
if (cmd == "map!") { modes = "ic"; type = Map; } else
if (cmd == "im" || cmd == "imap") { modes = "i"; type = Map; } else
if (cmd == "lm" || cmd == "lmap") { modes = "l"; type = Map; } else
@@ -5241,6 +5374,8 @@ bool FakeVimHandler::Private::handleExSetCommand(const ExCommand &cmd)
act->setValue(true);
else if (oldValue == true)
{} // nothing to do
+ if (g.highlightsCleared && (cmd.args == _("hls") || cmd.args == _("hlsearch")))
+ highlightMatches(g.lastNeedle);
} else if (act) {
// Non-boolean to show.
showMessage(MessageInfo, cmd.args + QLatin1Char('=') + act->value().toString());
@@ -5576,11 +5711,12 @@ bool FakeVimHandler::Private::handleExShiftCommand(const ExCommand &cmd)
bool FakeVimHandler::Private::handleExNohlsearchCommand(const ExCommand &cmd)
{
- // :nohlsearch
- if (!cmd.cmd.startsWith(_("noh")))
+ // :noh, :nohl, ..., :nohlsearch
+ if (cmd.cmd.size() < 3 || !QString(_("nohlsearch")).startsWith(cmd.cmd))
return false;
- highlightMatches(QString());
+ g.highlightsCleared = true;
+ updateHighlights();
return true;
}
@@ -5863,7 +5999,7 @@ void FakeVimHandler::Private::search(const SearchData &sd, bool showMessages)
setTargetColumn();
}
-void FakeVimHandler::Private::searchNext(bool forward)
+bool FakeVimHandler::Private::searchNext(bool forward)
{
SearchData sd;
sd.needle = g.lastSearch;
@@ -5873,14 +6009,13 @@ void FakeVimHandler::Private::searchNext(bool forward)
showMessage(MessageCommand, QLatin1Char(g.lastSearchForward ? '/' : '?') + sd.needle);
recordJump();
search(sd);
+ return finishSearch();
}
void FakeVimHandler::Private::highlightMatches(const QString &needle)
{
- if (!hasConfig(ConfigHlSearch) || needle == m_oldNeedle)
- return;
- m_oldNeedle = needle;
-
+ g.lastNeedle = needle;
+ g.highlightsCleared = false;
updateHighlights();
}
@@ -5909,7 +6044,7 @@ void FakeVimHandler::Private::indentSelectedText(QChar typedChar)
int beginLine = qMin(lineForPosition(position()), lineForPosition(anchor()));
int endLine = qMax(lineForPosition(position()), lineForPosition(anchor()));
- Range range(anchor(), position(), m_rangemode);
+ Range range(anchor(), position(), g.rangemode);
indentText(range, typedChar);
setPosition(firstPositionInLine(beginLine));
@@ -5929,7 +6064,11 @@ void FakeVimHandler::Private::indentText(const Range &range, QChar typedChar)
int endBlock = document()->findBlock(range.endPos).blockNumber();
if (beginBlock > endBlock)
qSwap(beginBlock, endBlock);
+
+ // Don't remember current indentation in last text insertion.
+ const QString lastInsertion = m_lastInsertion;
emit q->indentRegion(beginBlock, endBlock, typedChar);
+ m_lastInsertion = lastInsertion;
}
bool FakeVimHandler::Private::isElectricCharacter(QChar c) const
@@ -5952,7 +6091,7 @@ void FakeVimHandler::Private::shiftRegionRight(int repeat)
targetPos = firstPositionInLine(beginLine);
const int sw = config(ConfigShiftWidth).toInt();
- m_movetype = MoveLineWise;
+ g.movetype = MoveLineWise;
beginEditBlock();
QTextBlock block = document()->findBlockByLineNumber(beginLine - 1);
while (block.isValid() && lineNumber(block) <= endLine) {
@@ -6028,7 +6167,7 @@ int FakeVimHandler::Private::charClass(QChar c, bool simple) const
void FakeVimHandler::Private::miniBufferTextEdited(const QString &text, int cursorPos,
int anchorPos)
{
- if (m_subsubmode != SearchSubSubMode && m_mode != ExMode) {
+ if (g.subsubmode != SearchSubSubMode && g.mode != ExMode) {
editor()->setFocus();
} else if (text.isEmpty()) {
// editing cancelled
@@ -6039,7 +6178,7 @@ void FakeVimHandler::Private::miniBufferTextEdited(const QString &text, int curs
editor()->setFocus();
updateCursorShape();
} else {
- CommandBuffer &cmdBuf = (m_mode == ExMode) ? g.commandBuffer : g.searchBuffer;
+ CommandBuffer &cmdBuf = (g.mode == ExMode) ? g.commandBuffer : g.searchBuffer;
int pos = qMax(1, cursorPos);
int anchor = anchorPos == -1 ? pos : qMax(1, anchorPos);
QString buffer = text;
@@ -6054,7 +6193,7 @@ void FakeVimHandler::Private::miniBufferTextEdited(const QString &text, int curs
if (pos != cursorPos || anchor != anchorPos || buffer != text)
emit q->commandBufferChanged(buffer, pos, anchor, 0, q);
// update search expression
- if (m_subsubmode == SearchSubSubMode) {
+ if (g.subsubmode == SearchSubSubMode) {
updateFind(false);
exportSelection();
}
@@ -6180,42 +6319,34 @@ void FakeVimHandler::Private::moveToWordEnd(int count, bool simple, bool forward
bool FakeVimHandler::Private::handleFfTt(QString key)
{
int key0 = key.size() == 1 ? key.at(0).unicode() : 0;
- int oldPos = position();
- // m_subsubmode \in { 'f', 'F', 't', 'T' }
- bool forward = m_subsubdata.is('f') || m_subsubdata.is('t');
+ // g.subsubmode \in { 'f', 'F', 't', 'T' }
+ bool forward = g.subsubdata.is('f') || g.subsubdata.is('t');
+ bool exclusive = g.subsubdata.is('t') || g.subsubdata.is('T');
int repeat = count();
+ int n = block().position() + (forward ? block().length() : - 1);
QTextDocument *doc = document();
- int n = block().position();
- if (forward)
- n += block().length();
- int pos = position();
- while (pos != n) {
- pos += forward ? 1 : -1;
- if (pos == n)
- break;
+
+ for (int d = forward ? 1 : -1, pos = position() + d; pos != n; pos += d) {
int uc = doc->characterAt(pos).unicode();
if (uc == ParagraphSeparator)
break;
- if (uc == key0)
+ if (uc == key0) {
--repeat;
- if (repeat == 0) {
- if (m_subsubdata.is('t'))
- --pos;
- else if (m_subsubdata.is('T'))
- ++pos;
+ if (repeat == 0) {
+ if (exclusive)
+ pos -= d;
- if (forward)
- moveRight(pos - position());
- else
- moveLeft(position() - pos);
- break;
+ if (forward)
+ moveRight(pos - position());
+ else
+ moveLeft(position() - pos);
+
+ setTargetColumn();
+ return true;
+ }
}
}
- if (repeat == 0) {
- setTargetColumn();
- return true;
- }
- setPosition(oldPos);
+
return false;
}
@@ -6697,14 +6828,14 @@ void FakeVimHandler::Private::pasteText(bool afterCursor)
bool visualCharMode = isVisualCharMode();
if (visualCharMode) {
leaveVisualMode();
- m_rangemode = RangeCharMode;
+ g.rangemode = RangeCharMode;
Range range = currentRange();
range.endPos++;
yankText(range, m_register);
removeText(range);
} else if (isVisualLineMode()) {
leaveVisualMode();
- m_rangemode = RangeLineMode;
+ g.rangemode = RangeLineMode;
Range range = currentRange();
range.endPos++;
yankText(range, m_register);
@@ -6712,7 +6843,7 @@ void FakeVimHandler::Private::pasteText(bool afterCursor)
handleStartOfLine();
} else if (isVisualBlockMode()) {
leaveVisualMode();
- m_rangemode = RangeBlockMode;
+ g.rangemode = RangeBlockMode;
Range range = currentRange();
yankText(range, m_register);
removeText(range);
@@ -6823,7 +6954,7 @@ void FakeVimHandler::Private::joinLines(int count, bool preserveSpace)
void FakeVimHandler::Private::insertNewLine()
{
- if ( hasConfig(ConfigPassKeys) ) {
+ if ( m_editBlockLevel <= 1 && hasConfig(ConfigPassKeys) ) {
QKeyEvent event(QEvent::KeyPress, Qt::Key_Return, Qt::NoModifier, QLatin1String("\n"));
if (passEventToEditor(event))
return;
@@ -6833,26 +6964,17 @@ void FakeVimHandler::Private::insertNewLine()
insertAutomaticIndentation(true);
}
-bool FakeVimHandler::Private::handleInsertInEditor(const Input &input, QString *insert)
+bool FakeVimHandler::Private::handleInsertInEditor(const Input &input)
{
if (m_editBlockLevel > 0 || !hasConfig(ConfigPassKeys))
return false;
joinPreviousEditBlock();
- const int pos1 = position();
- const int len1 = lastPositionInDocument();
-
- QKeyEvent event(QEvent::KeyPress, input.key(),
- static_cast<Qt::KeyboardModifiers>(input.modifiers()), input.text());
+ QKeyEvent event(QEvent::KeyPress, input.key(), input.modifiers(), input.text());
setAnchor();
if (!passEventToEditor(event))
- return false;
-
- const int pos2 = position();
- const int len2 = lastPositionInDocument();
-
- *insert = guessInsertCommand(pos1, pos2, len1, len2);
+ return !m_textedit && !m_plaintextedit; // Mark event as handled if it has destroyed editor.
endEditBlock();
@@ -6868,6 +6990,8 @@ bool FakeVimHandler::Private::passEventToEditor(QEvent &event)
EDITOR(setOverwriteMode(false));
emit q->requestSetBlockSelection(false);
bool accepted = QApplication::sendEvent(editor(), &event);
+ if (!m_textedit && !m_plaintextedit)
+ return false;
if (isVisualBlockMode())
emit q->requestSetBlockSelection(true);
updateCursorShape();
@@ -6880,75 +7004,19 @@ bool FakeVimHandler::Private::passEventToEditor(QEvent &event)
return accepted;
}
-QString FakeVimHandler::Private::guessInsertCommand(int pos1, int pos2, int len1, int len2)
-{
- QString insert;
-
- // Guess the inserted/deleted text.
- if (len1 > len2) {
- // Text deleted.
- if (pos1 == pos2) {
- // Text after cursor deleted.
- insert = QString(_("<C-O>%1x")).arg(len1 - len2);
- } else if (pos1 > pos2) {
- // Text in front of cursor deleted.
- const int backspaces = pos1 - pos2;
- insert = QString(_("<BS>")).repeated(backspaces);
- // Some text after cursor may have beed deleted too.
- const int deletes = len1 - len2 - backspaces;
- if (deletes > 0)
- insert.append(QString(_("<C-O>%1x")).arg(deletes));
- }
- } else if (len1 < len2) {
- // Text inserted.
- if (pos1 < pos2) {
- QTextCursor tc = m_cursor;
- tc.setPosition(pos1);
- tc.setPosition(pos2, KeepAnchor);
- insert = QString(tc.selectedText()).replace(_("<"), _("<LT>"));
-
- const int textLen = pos2 - pos1;
- const int rest = len2 - len1 - textLen;
- if (rest > 0) {
- // Text inserted after new cursor position.
- // On dot command, cursor must insert the same text and move in front of it.
- tc.setPosition(pos2);
- tc.setPosition(pos2 + rest, KeepAnchor);
- insert.append(QString(tc.selectedText()).replace(_("<"), _("<LT>")));
-
- const int up = document()->findBlock(pos2).blockNumber()
- - document()->findBlock(pos1).blockNumber();
- if (up > 0) {
- insert.append(QString(_("<UP>")).repeated(up));
- insert.append(_("<END>"));
- const int right = rightDist();
- if (right > 0)
- insert.append(QString(_("<LEFT>")).repeated(right));
- } else {
- insert.append(QString(_("<LEFT>")).repeated(rest));
- }
- }
- }
- } else {
- // Document length is unchanged so assume that no text inserted or deleted.
- // Check if cursor moved.
- const int right = pos2 - pos1;
- if (right > 0)
- insert = QString(_("<RIGHT>")).repeated(right);
- else if (right < 0)
- insert = QString(_("<LEFT>")).repeated(-right);
- else
- insert = _(""); // Empty non-null string.
- }
-
- return insert;
-}
-
QString FakeVimHandler::Private::lineContents(int line) const
{
return document()->findBlockByLineNumber(line - 1).text();
}
+QString FakeVimHandler::Private::textAt(int from, int to) const
+{
+ QTextCursor tc(document());
+ tc.setPosition(from);
+ tc.setPosition(to, KeepAnchor);
+ return tc.selectedText().replace(ParagraphSeparator, QLatin1Char('\n'));
+}
+
void FakeVimHandler::Private::setLineContents(int line, const QString &contents)
{
QTextBlock block = document()->findBlockByLineNumber(line - 1);
@@ -7096,7 +7164,7 @@ void FakeVimHandler::Private::toggleVisualMode(VisualMode visualMode)
} else {
m_positionPastEnd = false;
m_anchorPastEnd = false;
- m_visualMode = visualMode;
+ g.visualMode = visualMode;
m_lastVisualMode = visualMode;
const int pos = position();
setAnchorAndPosition(pos, pos);
@@ -7113,17 +7181,17 @@ void FakeVimHandler::Private::leaveVisualMode()
setMark(QLatin1Char('>'), mark(QLatin1Char('>')).position);
m_lastVisualModeInverted = anchor() > position();
if (isVisualLineMode()) {
- m_rangemode = RangeLineMode;
- m_movetype = MoveLineWise;
+ g.rangemode = RangeLineMode;
+ g.movetype = MoveLineWise;
} else if (isVisualCharMode()) {
- m_rangemode = RangeCharMode;
- m_movetype = MoveInclusive;
+ g.rangemode = RangeCharMode;
+ g.movetype = MoveInclusive;
} else if (isVisualBlockMode()) {
- m_rangemode = RangeBlockMode;
- m_movetype = MoveInclusive;
+ g.rangemode = RangeBlockMode;
+ g.movetype = MoveInclusive;
}
- m_visualMode = NoVisualMode;
+ g.visualMode = NoVisualMode;
updateMiniBuffer();
}
@@ -7137,7 +7205,7 @@ QWidget *FakeVimHandler::Private::editor() const
void FakeVimHandler::Private::joinPreviousEditBlock()
{
UNDO_DEBUG("JOIN");
- if (m_breakEditBlock && m_editBlockLevel == 0) {
+ if (m_breakEditBlock) {
beginEditBlock();
QTextCursor tc(m_cursor);
tc.setPosition(tc.position());
@@ -7145,6 +7213,7 @@ void FakeVimHandler::Private::joinPreviousEditBlock()
tc.insertText(_("X"));
tc.deletePreviousChar();
tc.endEditBlock();
+ m_breakEditBlock = false;
} else {
if (m_editBlockLevel == 0 && !m_undo.empty())
m_undoState = m_undo.pop();
@@ -7157,8 +7226,9 @@ void FakeVimHandler::Private::beginEditBlock(bool largeEditBlock)
UNDO_DEBUG("BEGIN EDIT BLOCK");
if (!largeEditBlock && !m_undoState.isValid())
pushUndoState(false);
+ if (m_editBlockLevel == 0)
+ m_breakEditBlock = true;
++m_editBlockLevel;
- m_breakEditBlock = false;
}
void FakeVimHandler::Private::endEditBlock()
@@ -7167,59 +7237,93 @@ void FakeVimHandler::Private::endEditBlock()
QTC_ASSERT(m_editBlockLevel > 0,
qDebug() << "beginEditBlock() not called before endEditBlock()!"; return);
--m_editBlockLevel;
- if (m_editBlockLevel == 0 && m_undoState.isValid() && m_undoState.revisions > 0) {
+ if (m_editBlockLevel == 0 && m_undoState.isValid()) {
m_undo.push(m_undoState);
m_undoState = State();
}
+ if (m_editBlockLevel == 0)
+ m_breakEditBlock = false;
}
-void FakeVimHandler::Private::onContentsChanged()
+void FakeVimHandler::Private::onContentsChanged(int position, int charsRemoved, int charsAdded)
{
- if (!document()->isUndoAvailable())
- m_undo.clear();
-
- const int undoSteps = document()->availableUndoSteps();
+ // Record inserted and deleted text in insert mode.
+ if (isInsertMode() && (charsAdded > 0 || charsRemoved > 0)) {
+ if (!isInsertStateValid()) {
+ m_insertState.pos1 = m_oldPosition;
+ g.dotCommand = _("i");
+ resetCount();
+ }
+
+ // Ignore changes outside inserted text (e.g. renaming other occurrences of a variable).
+ if (position + charsRemoved >= m_insertState.pos1 && position <= m_insertState.pos2) {
+ if (charsRemoved > 0) {
+ if (position < m_insertState.pos1) {
+ // backspaces
+ const int bs = m_insertState.pos1 - position;
+ const QString inserted = textAt(position, m_oldPosition);
+ const QString removed = m_insertState.textBeforeCursor.right(bs);
+ // Ignore backspaces if same text was just inserted.
+ if ( !inserted.endsWith(removed) ) {
+ m_insertState.backspaces += bs;
+ m_insertState.pos1 = position;
+ m_insertState.pos2 = qMax(position, m_insertState.pos2 - bs);
+ }
+ } else if (position + charsRemoved > m_insertState.pos2) {
+ // deletes
+ m_insertState.deletes += position + charsRemoved - m_insertState.pos2;
+ }
+ } else if (charsAdded > 0 && m_insertState.insertingSpaces) {
+ for (int i = position; i < position + charsAdded; ++i) {
+ const QChar c = document()->characterAt(i);
+ if (c.unicode() == ' ' || c.unicode() == '\t')
+ m_insertState.spaces.insert(i);
+ }
+ }
- if (m_editBlockLevel == 0) {
- // Break undo/redo stacks on external undo/redo.
- if (m_lastUndoSteps > undoSteps && !m_undo.isEmpty()) {
- if ((--m_undo.top().revisions) <= 0)
- m_undo.pop();
- m_redo.push(State());
- } else if (m_lastUndoSteps < undoSteps && !m_redo.isEmpty()) {
- if ((--m_redo.top().revisions) <= 0)
- m_redo.pop();
- m_undo.push(State());
+ m_insertState.pos2 = qMax(m_insertState.pos2 + charsAdded - charsRemoved,
+ position + charsAdded);
+ m_oldPosition = position + charsAdded;
+ m_insertState.textBeforeCursor = textAt(document()->findBlock(m_oldPosition).position(),
+ m_oldPosition);
}
}
- m_lastUndoSteps = undoSteps;
+ if (!m_highlighted.isEmpty())
+ emit q->highlightMatches(m_highlighted);
}
void FakeVimHandler::Private::onUndoCommandAdded()
{
- m_redo.clear();
- // Remember chage so it can be correctly undone/redone with undo/redo commands.
- if (m_editBlockLevel == 0 && !m_undo.isEmpty()) {
- if (isInsertMode())
- ++m_undo.top().revisions; // External change in insert mode (auto-completion etc.)
- else
- m_undo.push(State()); // External change while FakeVim disabled.
- } else if (m_editBlockLevel > 0) {
- ++m_undoState.revisions; // Document revision increased in our edit block.
+ // Undo commands removed?
+ if (m_lastRevision >= revision()) {
+ const int removed = m_lastRevision - revision();
+ for (int i = m_undo.size() - 1; i >= 0; --i) {
+ if ((m_undo[i].revision -= removed) < 0) {
+ m_undo.remove(0, i + 1);
+ break;
+ }
+ }
}
+
+ m_redo.clear();
+ // External change while FakeVim disabled.
+ if (m_editBlockLevel == 0 && !m_undo.isEmpty() && !isInsertMode())
+ m_undo.push(State());
}
char FakeVimHandler::Private::currentModeCode() const
{
- if (m_submode != NoSubMode)
- return ' ';
- else if (m_mode == ExMode)
+ if (g.mode == ExMode)
return 'c';
else if (isVisualMode())
return 'v';
- else if (m_mode == CommandMode)
+ else if (isOperatorPending())
+ return 'o';
+ else if (g.mode == CommandMode)
return 'n';
+ else if (g.submode != NoSubMode)
+ return ' ';
else
return 'i';
}
@@ -7232,34 +7336,34 @@ void FakeVimHandler::Private::undoRedo(bool undo)
QStack<State> &stack = undo ? m_undo : m_redo;
QStack<State> &stack2 = undo ? m_redo : m_undo;
- State state = !stack.empty() ? stack.pop() : State();
+ State state = m_undoState.isValid() ? m_undoState
+ : !stack.empty() ? stack.pop() : State();
CursorPosition lastPos(m_cursor);
- const int current = revision();
+ if (undo ? !document()->isUndoAvailable() : !document()->isRedoAvailable()) {
+ const QString msg = undo ? FakeVimHandler::tr("Already at oldest change.")
+ : FakeVimHandler::tr("Already at newest change.");
+ showMessage(MessageInfo, msg);
+ return;
+ }
+ clearMessage();
++m_editBlockLevel;
// Do undo/redo [count] times to reach previous revision.
- int count = qMax(1, m_undoState.isValid() ? m_undoState.revisions
- : state.revisions);
- while (count-- > 0) {
- if (undo)
+ const int previousRevision = revision();
+ if (undo) {
+ do {
EDITOR(undo());
- else
+ } while (document()->isUndoAvailable() && state.revision >= 0 && state.revision < revision());
+ } else {
+ do {
EDITOR(redo());
+ } while (document()->isRedoAvailable() && state.revision > revision());
}
--m_editBlockLevel;
- if (current == revision()) {
- const QString msg = undo ? FakeVimHandler::tr("Already at oldest change.")
- : FakeVimHandler::tr("Already at newest change.");
- showMessage(MessageInfo, msg);
- stack.push(state);
- return;
- }
- clearMessage();
-
if (state.isValid()) {
m_lastChangePosition = state.position;
Marks marks = m_marks;
@@ -7271,6 +7375,7 @@ void FakeVimHandler::Private::undoRedo(bool undo)
setMark(QLatin1Char('`'), lastPos);
setCursorPosition(m_lastChangePosition);
setAnchor();
+ state.revision = previousRevision;
} else {
updateFirstVisibleLine();
m_cursor = EDITOR(textCursor());
@@ -7294,37 +7399,40 @@ void FakeVimHandler::Private::redo()
void FakeVimHandler::Private::updateCursorShape()
{
- bool thinCursor = m_mode == ExMode
- || m_subsubmode == SearchSubSubMode
- || m_mode == InsertMode
+ bool thinCursor = g.mode == ExMode
+ || g.subsubmode == SearchSubSubMode
+ || g.mode == InsertMode
|| (isVisualMode() && !isVisualCharMode());
EDITOR(setOverwriteMode(!thinCursor));
}
void FakeVimHandler::Private::enterReplaceMode()
{
- m_mode = ReplaceMode;
- m_submode = NoSubMode;
- m_subsubmode = NoSubSubMode;
- m_lastInsertion.clear();
- m_oldPosition = position();
- g.returnToMode = ReplaceMode;
+ enterInsertOrReplaceMode(ReplaceMode);
}
void FakeVimHandler::Private::enterInsertMode()
{
- m_mode = InsertMode;
- m_submode = NoSubMode;
- m_subsubmode = NoSubSubMode;
- m_lastInsertion.clear();
- m_oldPosition = position();
- m_oldDocumentLength = document()->characterCount();
- if (g.returnToMode != InsertMode) {
- g.returnToMode = InsertMode;
+ enterInsertOrReplaceMode(InsertMode);
+}
+
+void FakeVimHandler::Private::enterInsertOrReplaceMode(Mode mode)
+{
+ QTC_ASSERT(mode == InsertMode || mode == ReplaceMode, return);
+ if (g.mode == mode)
+ return;
+
+ if (mode == 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();
}
+
+ g.mode = mode;
+ g.submode = NoSubMode;
+ g.subsubmode = NoSubSubMode;
+ g.returnToMode = mode;
+ clearLastInsertion();
}
void FakeVimHandler::Private::initVisualInsertMode(QChar command)
@@ -7375,7 +7483,7 @@ void FakeVimHandler::Private::enterCommandMode(Mode returnToMode)
{
if (isNoVisualMode() && atEndOfLine())
moveLeft();
- m_mode = CommandMode;
+ g.mode = CommandMode;
clearCommandMode();
g.returnToMode = returnToMode;
}
@@ -7387,9 +7495,9 @@ void FakeVimHandler::Private::enterExMode(const QString &contents)
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;
+ g.mode = ExMode;
+ g.submode = NoSubMode;
+ g.subsubmode = NoSubSubMode;
}
void FakeVimHandler::Private::recordJump(int position)
@@ -7455,9 +7563,7 @@ void FakeVimHandler::Private::insertAutomaticIndentation(bool goingDown, bool fo
if (hasConfig(ConfigSmartIndent)) {
QTextBlock bl = block();
Range range(bl.position(), bl.position());
- const int oldSize = bl.text().size();
indentText(range, QLatin1Char('\n'));
- m_justAutoIndented = bl.text().size() - oldSize;
} else {
QTextBlock bl = goingDown ? block().previous() : block().next();
QString text = bl.text();
@@ -7468,37 +7574,28 @@ void FakeVimHandler::Private::insertAutomaticIndentation(bool goingDown, bool fo
text.truncate(pos);
// FIXME: handle 'smartindent' and 'cindent'
insertText(text);
- m_justAutoIndented = text.size();
}
}
-bool FakeVimHandler::Private::removeAutomaticIndentation()
-{
- if (!hasConfig(ConfigAutoIndent) || m_justAutoIndented == 0)
- return false;
-/*
- m_tc.movePosition(StartOfLine, KeepAnchor);
- m_tc.removeSelectedText();
- m_lastInsertion.chop(m_justAutoIndented);
-*/
- m_justAutoIndented = 0;
- return true;
-}
-
void FakeVimHandler::Private::handleStartOfLine()
{
if (hasConfig(ConfigStartOfLine))
moveToFirstNonBlankOnLine();
}
-void FakeVimHandler::Private::replay(const QString &command)
+void FakeVimHandler::Private::replay(const QString &command, int repeat)
{
+ if (repeat <= 0)
+ return;
+
//qDebug() << "REPLAY: " << quoteUnprintable(command);
clearCommandMode();
Inputs inputs(command);
- foreach (const Input &in, inputs) {
- if (handleDefaultKey(in) != EventHandled)
- break;
+ for (int i = 0; i < repeat; ++i) {
+ foreach (const Input &in, inputs) {
+ if (handleDefaultKey(in) != EventHandled)
+ return;
+ }
}
}
@@ -7544,7 +7641,7 @@ void FakeVimHandler::Private::selectTextObject(bool simple, bool inner)
if (setupAnchor) {
// Select nothing with 'inner' on empty line.
if (inner && atEmptyLine() && repeat == 1) {
- m_movetype = MoveExclusive;
+ g.movetype = MoveExclusive;
return;
}
moveToBoundaryStart(1, simple, false);
@@ -7614,15 +7711,15 @@ void FakeVimHandler::Private::selectTextObject(bool simple, bool inner)
}
if (inner) {
- m_movetype = MoveInclusive;
+ g.movetype = MoveInclusive;
} else {
- m_movetype = MoveExclusive;
+ g.movetype = MoveExclusive;
if (isNoVisualMode()) {
moveRight();
if (atEndOfLine())
moveRight();
} else if (isVisualLineMode()) {
- m_visualMode = VisualCharMode;
+ g.visualMode = VisualCharMode;
}
}
@@ -7672,7 +7769,7 @@ bool FakeVimHandler::Private::selectBlockTextObject(bool inner,
--p2;
setAnchorAndPosition(p1, p2);
- m_movetype = MoveExclusive;
+ g.movetype = MoveExclusive;
return true;
}
@@ -7774,7 +7871,7 @@ bool FakeVimHandler::Private::selectQuotedStringTextObject(bool inner,
--p2;
setAnchorAndPosition(p1, p2);
- m_movetype = MoveExclusive;
+ g.movetype = MoveExclusive;
return true;
}
@@ -7821,7 +7918,7 @@ bool FakeVimHandler::Private::jumpToMark(QChar mark, bool backTickMode)
setCursorPosition(m.position);
if (!backTickMode)
moveToFirstNonBlankOnLine();
- if (m_submode == NoSubMode)
+ if (g.submode == NoSubMode)
setAnchor();
setTargetColumn();
@@ -7975,7 +8072,7 @@ bool FakeVimHandler::eventFilter(QObject *ob, QEvent *ev)
if (ev->type() == QEvent::MouseButtonPress) {
QMouseEvent *mev = static_cast<QMouseEvent *>(ev);
if (mev->button() == Qt::LeftButton)
- d->m_visualMode = NoVisualMode;
+ Private::g.visualMode = NoVisualMode;
}
return QObject::eventFilter(ob, ev);
}
@@ -8001,11 +8098,12 @@ bool FakeVimHandler::eventFilter(QObject *ob, QEvent *ev)
}
if (ev->type() == QEvent::KeyPress &&
- (ob == d->editor() || (d->m_mode == ExMode || d->m_subsubmode == SearchSubSubMode))) {
+ (ob == d->editor()
+ || (Private::g.mode == ExMode || Private::g.subsubmode == SearchSubSubMode))) {
QKeyEvent *kev = static_cast<QKeyEvent *>(ev);
KEY_DEBUG("KEYPRESS" << kev->key() << kev->text() << QChar(kev->key()));
EventResult res = d->handleEvent(kev);
- //if (d->m_mode == InsertMode)
+ //if (Private::g.mode == InsertMode)
// emit completionRequested();
// returning false core the app see it
//KEY_DEBUG("HANDLED CODE:" << res);
@@ -8122,7 +8220,7 @@ void FakeVimHandler::setTextCursorPosition(int position)
d->m_fakeEnd = false;
d->setTargetColumn();
- if (!d->m_inFakeVim)
+ if (!Private::g.inFakeVim)
d->commitCursor();
}
diff --git a/src/plugins/fakevim/fakevimplugin.cpp b/src/plugins/fakevim/fakevimplugin.cpp
index 1ecf1934f6..f8e79162f2 100644
--- a/src/plugins/fakevim/fakevimplugin.cpp
+++ b/src/plugins/fakevim/fakevimplugin.cpp
@@ -41,7 +41,7 @@
#include <coreplugin/coreconstants.h>
#include <coreplugin/dialogs/ioptionspage.h>
#include <coreplugin/editormanager/editormanager.h>
-#include <coreplugin/editormanager/openeditorsmodel.h>
+#include <coreplugin/editormanager/documentmodel.h>
#include <coreplugin/documentmanager.h>
#include <coreplugin/icore.h>
#include <coreplugin/idocument.h>
@@ -122,7 +122,6 @@ class MiniBuffer : public QStackedWidget
public:
MiniBuffer() : m_label(new QLabel(this)), m_edit(new QLineEdit(this)), m_eventFilter(0)
{
- 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()));
@@ -206,18 +205,6 @@ private slots:
emit edited(m_edit->text(), cursorPos, anchorPos);
}
- bool eventFilter(QObject *ob, QEvent *ev)
- {
- // 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;
@@ -372,8 +359,8 @@ QWidget *FakeVimOptionPage::createPage(QWidget *parent)
void FakeVimOptionPage::copyTextEditorSettings()
{
- TabSettings ts = TextEditorSettings::instance()->codeStyle()->tabSettings();
- TypingSettings tps = TextEditorSettings::instance()->typingSettings();
+ TabSettings ts = TextEditorSettings::codeStyle()->tabSettings();
+ TypingSettings tps = TextEditorSettings::typingSettings();
m_ui.checkBoxExpandTab->setChecked(ts.m_tabPolicy != TabSettings::TabsOnlyTabPolicy);
m_ui.spinBoxTabStop->setValue(ts.m_tabSize);
m_ui.spinBoxShiftWidth->setValue(ts.m_indentSize);
@@ -1041,7 +1028,7 @@ FakeVimPluginPrivate::~FakeVimPluginPrivate()
void FakeVimPluginPrivate::onCoreAboutToClose()
{
// Don't attach to editors anymore.
- disconnect(ICore::editorManager(), SIGNAL(editorOpened(Core::IEditor*)),
+ disconnect(EditorManager::instance(), SIGNAL(editorOpened(Core::IEditor*)),
this, SLOT(editorOpened(Core::IEditor*)));
}
@@ -1051,8 +1038,6 @@ void FakeVimPluginPrivate::aboutToShutdown()
bool FakeVimPluginPrivate::initialize()
{
- EditorManager *editorManager = ICore::editorManager();
-
//m_wordCompletion = new WordCompletion;
//q->addAutoReleasedObject(m_wordCompletion);
m_wordProvider = new FakeVimCompletionAssistProvider;
@@ -1089,7 +1074,7 @@ bool FakeVimPluginPrivate::initialize()
ActionManager::actionContainer(Core::Constants::M_EDIT_ADVANCED);
advancedMenu->addAction(cmd, Core::Constants::G_EDIT_EDITOR);
- const Id base = Id("FakeVim.UserAction");
+ const Id base = "FakeVim.UserAction";
for (int i = 1; i < 10; ++i) {
QAction *act = new QAction(this);
act->setText(tr("Execute User Action #%1").arg(i));
@@ -1102,9 +1087,9 @@ bool FakeVimPluginPrivate::initialize()
connect(ICore::instance(), SIGNAL(coreAboutToClose()), this, SLOT(onCoreAboutToClose()));
// EditorManager
- connect(editorManager, SIGNAL(editorAboutToClose(Core::IEditor*)),
+ connect(EditorManager::instance(), SIGNAL(editorAboutToClose(Core::IEditor*)),
this, SLOT(editorAboutToClose(Core::IEditor*)));
- connect(editorManager, SIGNAL(editorOpened(Core::IEditor*)),
+ connect(EditorManager::instance(), SIGNAL(editorOpened(Core::IEditor*)),
this, SLOT(editorOpened(Core::IEditor*)));
connect(theFakeVimSetting(ConfigUseFakeVim), SIGNAL(valueChanged(QVariant)),
@@ -1326,6 +1311,8 @@ void FakeVimPluginPrivate::windowCommand(const QString &map, int count)
triggerAction(Core::Constants::GOTOPREV);
else if (key == _("S") || key == _("<C-S>"))
triggerAction(Core::Constants::SPLIT);
+ else if (key == _("V") || key == _("<C-V>"))
+ triggerAction(Core::Constants::SPLIT_SIDE_BY_SIDE);
else if (key == _("W") || key == _("<C-W>"))
triggerAction(Core::Constants::GOTO_NEXT_SPLIT);
else if (key.contains(_("RIGHT")) || key == _("L") || key == _("<S-L>"))
@@ -1354,7 +1341,7 @@ void FakeVimPluginPrivate::moveSomewhere(DistFunction f, int count)
IEditor *bestEditor = 0;
int repeat = count;
- QList<IEditor *> editors = EditorManager::instance()->visibleEditors();
+ QList<IEditor *> editors = EditorManager::visibleEditors();
while (repeat < 0 || repeat-- > 0) {
editors.removeOne(currentEditor);
int bestValue = -1;
@@ -1387,7 +1374,7 @@ void FakeVimPluginPrivate::moveSomewhere(DistFunction f, int count)
void FakeVimPluginPrivate::keepOnlyWindow()
{
IEditor *currentEditor = EditorManager::currentEditor();
- QList<IEditor *> editors = EditorManager::instance()->visibleEditors();
+ QList<IEditor *> editors = EditorManager::visibleEditors();
editors.removeOne(currentEditor);
foreach (IEditor *editor, editors) {
@@ -1401,8 +1388,8 @@ void FakeVimPluginPrivate::find(bool reverse)
if (Find::FindPlugin *plugin = Find::FindPlugin::instance()) {
plugin->setUseFakeVim(true);
plugin->openFindToolBar(reverse
- ? Find::FindPlugin::FindBackward
- : Find::FindPlugin::FindForward);
+ ? Find::FindPlugin::FindBackwardDirection
+ : Find::FindPlugin::FindForwardDirection);
}
}
@@ -1663,7 +1650,7 @@ void FakeVimPluginPrivate::editorOpened(IEditor *editor)
connect(ICore::instance(), SIGNAL(saveSettingsRequested()),
SLOT(writeSettings()));
- handler->setCurrentFileName(editor->document()->fileName());
+ handler->setCurrentFileName(editor->document()->filePath());
handler->installEventFilter();
// pop up the bar
@@ -1774,7 +1761,7 @@ void FakeVimPluginPrivate::handleExCommand(bool *handled, const ExCommand &cmd)
// :w[rite]
IEditor *editor = m_editorToHandler.key(handler);
const QString fileName = handler->currentFileName();
- if (editor && editor->document()->fileName() == fileName) {
+ if (editor && editor->document()->filePath() == fileName) {
// Handle that as a special case for nicer interaction with core
DocumentManager::saveDocument(editor->document());
// Check result by reading back.
@@ -1865,20 +1852,16 @@ void FakeVimPluginPrivate::handleDelayedQuit(bool forced, IEditor *editor)
{
// This tries to simulate vim behaviour. But the models of vim and
// Qt Creator core do not match well...
- EditorManager *editorManager = ICore::editorManager();
- if (editorManager->hasSplitter()) {
+ if (EditorManager::hasSplitter())
triggerAction(Core::Constants::REMOVE_CURRENT_SPLIT);
- } else {
- QList<IEditor *> editors;
- editors.append(editor);
- editorManager->closeEditors(editors, !forced);
- }
+ else
+ EditorManager::closeEditor(editor, !forced);
}
void FakeVimPluginPrivate::handleDelayedQuitAll(bool forced)
{
triggerAction(Core::Constants::REMOVE_ALL_SPLITS);
- ICore::editorManager()->closeAllEditors(!forced);
+ EditorManager::closeAllEditors(!forced);
}
void FakeVimPluginPrivate::moveToMatchingParenthesis(bool *moved, bool *forward,
@@ -1989,30 +1972,30 @@ void FakeVimPluginPrivate::changeSelection(const QList<QTextEdit::ExtraSelection
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);
+ foreach (IEditor *editor, EditorManager::visibleEditors()) {
+ 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();
IEditor *editor = EditorManager::currentEditor();
- return model->indexOf(editor).row();
+ if (!editor)
+ return -1;
+ return EditorManager::documentModel()->indexOfDocument(editor->document());
}
void FakeVimPluginPrivate::switchToFile(int n)
{
- EditorManager *editorManager = ICore::editorManager();
- OpenEditorsModel *model = editorManager->openedEditorsModel();
- int size = model->rowCount();
+ int size = EditorManager::documentModel()->documentCount();
QTC_ASSERT(size, return);
n = n % size;
if (n < 0)
n += size;
- editorManager->activateEditorForIndex(model->index(n, 0));
+ EditorManager::activateEditorForEntry(EditorManager::documentModel()->documents().at(n));
}
ExCommandMap &FakeVimExCommandsPage::exCommandMap()
diff --git a/src/plugins/find/Find.pluginspec.in b/src/plugins/find/Find.pluginspec.in
index ddce548787..d467971fd4 100644
--- a/src/plugins/find/Find.pluginspec.in
+++ b/src/plugins/find/Find.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"Find\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"Find\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/find/basetextfind.cpp b/src/plugins/find/basetextfind.cpp
index 1b2226dddc..14f19b8e57 100644
--- a/src/plugins/find/basetextfind.cpp
+++ b/src/plugins/find/basetextfind.cpp
@@ -121,11 +121,10 @@ bool BaseTextFind::supportsReplace() const
return !isReadOnly();
}
-Find::FindFlags BaseTextFind::supportedFindFlags() const
+FindFlags BaseTextFind::supportedFindFlags() const
{
- return Find::FindBackward | Find::FindCaseSensitively
- | Find::FindRegularExpression | Find::FindWholeWords
- | Find::FindPreserveCase;
+ return FindBackward | FindCaseSensitively | FindRegularExpression
+ | FindWholeWords | FindPreserveCase;
}
void BaseTextFind::resetIncrementalSearch()
@@ -172,7 +171,7 @@ QString BaseTextFind::completedFindString() const
return cursor.selectedText();
}
-IFindSupport::Result BaseTextFind::findIncremental(const QString &txt, Find::FindFlags findFlags)
+IFindSupport::Result BaseTextFind::findIncremental(const QString &txt, FindFlags findFlags)
{
QTextCursor cursor = textCursor();
if (d->m_incrementalStartPos < 0)
@@ -191,7 +190,7 @@ IFindSupport::Result BaseTextFind::findIncremental(const QString &txt, Find::Fin
return found ? Found : NotFound;
}
-IFindSupport::Result BaseTextFind::findStep(const QString &txt, Find::FindFlags findFlags)
+IFindSupport::Result BaseTextFind::findStep(const QString &txt, FindFlags findFlags)
{
bool wrapped = false;
bool found = find(txt, findFlags, textCursor(), &wrapped);
@@ -204,21 +203,20 @@ IFindSupport::Result BaseTextFind::findStep(const QString &txt, Find::FindFlags
return found ? Found : NotFound;
}
-void BaseTextFind::replace(const QString &before, const QString &after,
- Find::FindFlags findFlags)
+void BaseTextFind::replace(const QString &before, const QString &after, FindFlags findFlags)
{
QTextCursor cursor = replaceInternal(before, after, findFlags);
setTextCursor(cursor);
}
QTextCursor BaseTextFind::replaceInternal(const QString &before, const QString &after,
- Find::FindFlags findFlags)
+ FindFlags findFlags)
{
QTextCursor cursor = textCursor();
- bool usesRegExp = (findFlags & Find::FindRegularExpression);
- bool preserveCase = (findFlags & Find::FindPreserveCase);
+ bool usesRegExp = (findFlags & FindRegularExpression);
+ bool preserveCase = (findFlags & FindPreserveCase);
QRegExp regexp(before,
- (findFlags & Find::FindCaseSensitively) ? Qt::CaseSensitive : Qt::CaseInsensitive,
+ (findFlags & FindCaseSensitively) ? Qt::CaseSensitive : Qt::CaseInsensitive,
usesRegExp ? QRegExp::RegExp : QRegExp::FixedString);
if (regexp.exactMatch(cursor.selectedText())) {
@@ -231,14 +229,13 @@ QTextCursor BaseTextFind::replaceInternal(const QString &before, const QString &
realAfter = after;
int start = cursor.selectionStart();
cursor.insertText(realAfter);
- if ((findFlags&Find::FindBackward) != 0)
+ if ((findFlags & FindBackward) != 0)
cursor.setPosition(start);
}
return cursor;
}
-bool BaseTextFind::replaceStep(const QString &before, const QString &after,
- Find::FindFlags findFlags)
+bool BaseTextFind::replaceStep(const QString &before, const QString &after, FindFlags findFlags)
{
QTextCursor cursor = replaceInternal(before, after, findFlags);
bool wrapped = false;
@@ -248,8 +245,7 @@ bool BaseTextFind::replaceStep(const QString &before, const QString &after,
return found;
}
-int BaseTextFind::replaceAll(const QString &before, const QString &after,
- Find::FindFlags findFlags)
+int BaseTextFind::replaceAll(const QString &before, const QString &after, FindFlags findFlags)
{
QTextCursor editCursor = textCursor();
if (!d->m_findScopeStart.isNull())
@@ -258,12 +254,12 @@ int BaseTextFind::replaceAll(const QString &before, const QString &after,
editCursor.movePosition(QTextCursor::Start);
editCursor.beginEditBlock();
int count = 0;
- bool usesRegExp = (findFlags & Find::FindRegularExpression);
- bool preserveCase = (findFlags & Find::FindPreserveCase);
+ bool usesRegExp = (findFlags & FindRegularExpression);
+ bool preserveCase = (findFlags & 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));
+ regexp.setCaseSensitivity((findFlags & FindCaseSensitively) ? Qt::CaseSensitive : Qt::CaseInsensitive);
+ QTextCursor found = findOne(regexp, editCursor, textDocumentFlagsForFindFlags(findFlags));
bool first = true;
while (!found.isNull() && inScope(found.selectionStart(), found.selectionEnd())) {
if (found == editCursor && !first) {
@@ -273,10 +269,10 @@ int BaseTextFind::replaceAll(const QString &before, const QString &after,
// otherwise we would run into an endless loop for some regular expressions
// like ^ or \b.
QTextCursor newPosCursor = editCursor;
- newPosCursor.movePosition(findFlags & Find::FindBackward ?
+ newPosCursor.movePosition(findFlags & FindBackward ?
QTextCursor::PreviousCharacter :
QTextCursor::NextCharacter);
- found = findOne(regexp, newPosCursor, Find::textDocumentFlagsForFindFlags(findFlags));
+ found = findOne(regexp, newPosCursor, textDocumentFlagsForFindFlags(findFlags));
continue;
}
if (first)
@@ -294,13 +290,13 @@ int BaseTextFind::replaceAll(const QString &before, const QString &after,
else
realAfter = after;
editCursor.insertText(realAfter);
- found = findOne(regexp, editCursor, Find::textDocumentFlagsForFindFlags(findFlags));
+ found = findOne(regexp, editCursor, textDocumentFlagsForFindFlags(findFlags));
}
editCursor.endEditBlock();
return count;
}
-bool BaseTextFind::find(const QString &txt, Find::FindFlags findFlags,
+bool BaseTextFind::find(const QString &txt, FindFlags findFlags,
QTextCursor start, bool *wrapped)
{
if (txt.isEmpty()) {
@@ -308,9 +304,9 @@ bool BaseTextFind::find(const QString &txt, Find::FindFlags findFlags,
return true;
}
QRegExp regexp(txt);
- regexp.setPatternSyntax((findFlags&Find::FindRegularExpression) ? QRegExp::RegExp : QRegExp::FixedString);
- regexp.setCaseSensitivity((findFlags&Find::FindCaseSensitively) ? Qt::CaseSensitive : Qt::CaseInsensitive);
- QTextCursor found = findOne(regexp, start, Find::textDocumentFlagsForFindFlags(findFlags));
+ regexp.setPatternSyntax((findFlags & FindRegularExpression) ? QRegExp::RegExp : QRegExp::FixedString);
+ regexp.setCaseSensitivity((findFlags & FindCaseSensitively) ? Qt::CaseSensitive : Qt::CaseInsensitive);
+ QTextCursor found = findOne(regexp, start, textDocumentFlagsForFindFlags(findFlags));
if (wrapped)
*wrapped = false;
@@ -318,11 +314,11 @@ bool BaseTextFind::find(const QString &txt, Find::FindFlags findFlags,
// scoped
if (found.isNull() || !inScope(found.selectionStart(), found.selectionEnd())) {
- if ((findFlags&Find::FindBackward) == 0)
+ if ((findFlags & FindBackward) == 0)
start.setPosition(d->m_findScopeStart.position());
else
start.setPosition(d->m_findScopeEnd.position());
- found = findOne(regexp, start, Find::textDocumentFlagsForFindFlags(findFlags));
+ found = findOne(regexp, start, textDocumentFlagsForFindFlags(findFlags));
if (found.isNull() || !inScope(found.selectionStart(), found.selectionEnd()))
return false;
if (wrapped)
@@ -332,11 +328,11 @@ bool BaseTextFind::find(const QString &txt, Find::FindFlags findFlags,
// entire document
if (found.isNull()) {
- if ((findFlags&Find::FindBackward) == 0)
+ if ((findFlags & FindBackward) == 0)
start.movePosition(QTextCursor::Start);
else
start.movePosition(QTextCursor::End);
- found = findOne(regexp, start, Find::textDocumentFlagsForFindFlags(findFlags));
+ found = findOne(regexp, start, textDocumentFlagsForFindFlags(findFlags));
if (found.isNull())
return false;
if (wrapped)
diff --git a/src/plugins/find/basetextfind.h b/src/plugins/find/basetextfind.h
index 243722fffd..60f2ef06c9 100644
--- a/src/plugins/find/basetextfind.h
+++ b/src/plugins/find/basetextfind.h
@@ -42,7 +42,7 @@ QT_END_NAMESPACE
namespace Find {
struct BaseTextFindPrivate;
-class FIND_EXPORT BaseTextFind : public Find::IFindSupport
+class FIND_EXPORT BaseTextFind : public IFindSupport
{
Q_OBJECT
@@ -52,20 +52,17 @@ public:
virtual ~BaseTextFind();
bool supportsReplace() const;
- Find::FindFlags supportedFindFlags() const;
+ FindFlags supportedFindFlags() const;
void resetIncrementalSearch();
void clearResults();
QString currentFindString() const;
QString completedFindString() const;
- Result findIncremental(const QString &txt, Find::FindFlags findFlags);
- Result findStep(const QString &txt, Find::FindFlags findFlags);
- void replace(const QString &before, const QString &after,
- Find::FindFlags findFlags);
- bool replaceStep(const QString &before, const QString &after,
- Find::FindFlags findFlags);
- int replaceAll(const QString &before, const QString &after,
- Find::FindFlags findFlags);
+ Result findIncremental(const QString &txt, FindFlags findFlags);
+ Result findStep(const QString &txt, FindFlags findFlags);
+ void replace(const QString &before, const QString &after, FindFlags findFlags);
+ bool replaceStep(const QString &before, const QString &after, FindFlags findFlags);
+ int replaceAll(const QString &before, const QString &after, FindFlags findFlags);
void defineFindScope();
void clearFindScope();
@@ -77,12 +74,8 @@ signals:
int verticalBlockSelectionLastColumn);
private:
- bool find(const QString &txt,
- Find::FindFlags findFlags,
- QTextCursor start,
- bool *wrapped);
- QTextCursor replaceInternal(const QString &before, const QString &after,
- Find::FindFlags findFlags);
+ bool find(const QString &txt, FindFlags findFlags, QTextCursor start, bool *wrapped);
+ QTextCursor replaceInternal(const QString &before, const QString &after, FindFlags findFlags);
QTextCursor textCursor() const;
void setTextCursor(const QTextCursor&);
diff --git a/src/plugins/find/currentdocumentfind.cpp b/src/plugins/find/currentdocumentfind.cpp
index c6b7e2940e..b788433003 100644
--- a/src/plugins/find/currentdocumentfind.cpp
+++ b/src/plugins/find/currentdocumentfind.cpp
@@ -82,7 +82,7 @@ bool CurrentDocumentFind::supportsReplace() const
return m_currentFind->supportsReplace();
}
-Find::FindFlags CurrentDocumentFind::supportedFindFlags() const
+FindFlags CurrentDocumentFind::supportedFindFlags() const
{
QTC_ASSERT(m_currentFind, return 0);
return m_currentFind->supportedFindFlags();
@@ -100,40 +100,37 @@ QString CurrentDocumentFind::completedFindString() const
return m_currentFind->completedFindString();
}
-void CurrentDocumentFind::highlightAll(const QString &txt, Find::FindFlags findFlags)
+void CurrentDocumentFind::highlightAll(const QString &txt, FindFlags findFlags)
{
QTC_ASSERT(m_currentFind, return);
m_currentFind->highlightAll(txt, findFlags);
}
-IFindSupport::Result CurrentDocumentFind::findIncremental(const QString &txt, Find::FindFlags findFlags)
+IFindSupport::Result CurrentDocumentFind::findIncremental(const QString &txt, FindFlags findFlags)
{
QTC_ASSERT(m_currentFind, return IFindSupport::NotFound);
return m_currentFind->findIncremental(txt, findFlags);
}
-IFindSupport::Result CurrentDocumentFind::findStep(const QString &txt, Find::FindFlags findFlags)
+IFindSupport::Result CurrentDocumentFind::findStep(const QString &txt, FindFlags findFlags)
{
QTC_ASSERT(m_currentFind, return IFindSupport::NotFound);
return m_currentFind->findStep(txt, findFlags);
}
-void CurrentDocumentFind::replace(const QString &before, const QString &after,
- Find::FindFlags findFlags)
+void CurrentDocumentFind::replace(const QString &before, const QString &after, FindFlags findFlags)
{
QTC_ASSERT(m_currentFind, return);
m_currentFind->replace(before, after, findFlags);
}
-bool CurrentDocumentFind::replaceStep(const QString &before, const QString &after,
- Find::FindFlags findFlags)
+bool CurrentDocumentFind::replaceStep(const QString &before, const QString &after, FindFlags findFlags)
{
QTC_ASSERT(m_currentFind, return false);
return m_currentFind->replaceStep(before, after, findFlags);
}
-int CurrentDocumentFind::replaceAll(const QString &before, const QString &after,
- Find::FindFlags findFlags)
+int CurrentDocumentFind::replaceAll(const QString &before, const QString &after, FindFlags findFlags)
{
QTC_ASSERT(m_currentFind, return 0);
return m_currentFind->replaceAll(before, after, findFlags);
@@ -246,8 +243,7 @@ void CurrentDocumentFind::aggregationChanged()
m_candidateWidget = m_currentWidget;
m_candidateFind = currentFind;
acceptCandidate();
- }
- else {
+ } else {
clearFindSupport();
}
}
diff --git a/src/plugins/find/currentdocumentfind.h b/src/plugins/find/currentdocumentfind.h
index d030e2ce5b..d6a2cc1ef3 100644
--- a/src/plugins/find/currentdocumentfind.h
+++ b/src/plugins/find/currentdocumentfind.h
@@ -47,21 +47,18 @@ public:
void resetIncrementalSearch();
void clearResults();
bool supportsReplace() const;
- Find::FindFlags supportedFindFlags() const;
+ FindFlags supportedFindFlags() const;
QString currentFindString() const;
QString completedFindString() const;
bool isEnabled() const;
bool candidateIsEnabled() const;
- void highlightAll(const QString &txt, Find::FindFlags findFlags);
- IFindSupport::Result findIncremental(const QString &txt, Find::FindFlags findFlags);
- IFindSupport::Result findStep(const QString &txt, Find::FindFlags findFlags);
- void replace(const QString &before, const QString &after,
- Find::FindFlags findFlags);
- bool replaceStep(const QString &before, const QString &after,
- Find::FindFlags findFlags);
- int replaceAll(const QString &before, const QString &after,
- Find::FindFlags findFlags);
+ void highlightAll(const QString &txt, FindFlags findFlags);
+ IFindSupport::Result findIncremental(const QString &txt, FindFlags findFlags);
+ IFindSupport::Result findStep(const QString &txt, FindFlags findFlags);
+ void replace(const QString &before, const QString &after, FindFlags findFlags);
+ bool replaceStep(const QString &before, const QString &after, FindFlags findFlags);
+ int replaceAll(const QString &before, const QString &after, FindFlags findFlags);
void defineFindScope();
void clearFindScope();
void acceptCandidate();
diff --git a/src/plugins/find/find.qbs b/src/plugins/find/find.qbs
index bcc177d707..d9f653ae43 100644
--- a/src/plugins/find/find.qbs
+++ b/src/plugins/find/find.qbs
@@ -8,13 +8,6 @@ QtcPlugin {
Depends { name: "Qt"; submodules: ["widgets", "xml", "network", "script"] }
Depends { name: "Core" }
- cpp.includePaths: base.concat([
- "generichighlighter",
- "tooltip",
- "snippets",
- "codeassist"
- ])
-
files: [
"basetextfind.cpp",
"basetextfind.h",
diff --git a/src/plugins/find/findplugin.cpp b/src/plugins/find/findplugin.cpp
index 3ea17e75d0..6a819dbe17 100644
--- a/src/plugins/find/findplugin.cpp
+++ b/src/plugins/find/findplugin.cpp
@@ -74,7 +74,8 @@ namespace {
namespace Find {
-struct FindPluginPrivate {
+class FindPluginPrivate {
+public:
explicit FindPluginPrivate(FindPlugin *q);
//variables
@@ -85,7 +86,7 @@ struct FindPluginPrivate {
Internal::CurrentDocumentFind *m_currentDocumentFind;
Internal::FindToolBar *m_findToolBar;
Internal::FindToolWindow *m_findDialog;
- Find::FindFlags m_findFlags;
+ FindFlags m_findFlags;
QStringListModel *m_findCompletionModel;
QStringListModel *m_replaceCompletionModel;
QStringList m_findCompletions;
@@ -244,37 +245,37 @@ void FindPlugin::setupFilterMenuItems()
d->m_openFindDialog->setEnabled(haveEnabledFilters);
}
-Find::FindFlags FindPlugin::findFlags() const
+FindFlags FindPlugin::findFlags() const
{
return d->m_findFlags;
}
void FindPlugin::setCaseSensitive(bool sensitive)
{
- setFindFlag(Find::FindCaseSensitively, sensitive);
+ setFindFlag(FindCaseSensitively, sensitive);
}
void FindPlugin::setWholeWord(bool wholeOnly)
{
- setFindFlag(Find::FindWholeWords, wholeOnly);
+ setFindFlag(FindWholeWords, wholeOnly);
}
void FindPlugin::setBackward(bool backward)
{
- setFindFlag(Find::FindBackward, backward);
+ setFindFlag(FindBackward, backward);
}
void FindPlugin::setRegularExpression(bool regExp)
{
- setFindFlag(Find::FindRegularExpression, regExp);
+ setFindFlag(FindRegularExpression, regExp);
}
void FindPlugin::setPreserveCase(bool preserveCase)
{
- setFindFlag(Find::FindPreserveCase, preserveCase);
+ setFindFlag(FindPreserveCase, preserveCase);
}
-void FindPlugin::setFindFlag(Find::FindFlag flag, bool enabled)
+void FindPlugin::setFindFlag(FindFlag flag, bool enabled)
{
bool hasFlag = hasFindFlag(flag);
if ((hasFlag && enabled) || (!hasFlag && !enabled))
@@ -283,11 +284,11 @@ void FindPlugin::setFindFlag(Find::FindFlag flag, bool enabled)
d->m_findFlags |= flag;
else
d->m_findFlags &= ~flag;
- if (flag != Find::FindBackward)
+ if (flag != FindBackward)
emit findFlagsChanged();
}
-bool FindPlugin::hasFindFlag(Find::FindFlag flag)
+bool FindPlugin::hasFindFlag(FindFlag flag)
{
return d->m_findFlags & flag;
}
@@ -296,11 +297,11 @@ void FindPlugin::writeSettings()
{
QSettings *settings = Core::ICore::settings();
settings->beginGroup(QLatin1String("Find"));
- settings->setValue(QLatin1String("Backward"), hasFindFlag(Find::FindBackward));
- 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("Backward"), hasFindFlag(FindBackward));
+ settings->setValue(QLatin1String("CaseSensitively"), hasFindFlag(FindCaseSensitively));
+ settings->setValue(QLatin1String("WholeWords"), hasFindFlag(FindWholeWords));
+ settings->setValue(QLatin1String("RegularExpression"), hasFindFlag(FindRegularExpression));
+ settings->setValue(QLatin1String("PreserveCase"), hasFindFlag(FindPreserveCase));
settings->setValue(QLatin1String("FindStrings"), d->m_findCompletions);
settings->setValue(QLatin1String("ReplaceStrings"), d->m_replaceCompletions);
settings->endGroup();
@@ -359,7 +360,7 @@ void FindPlugin::setUseFakeVim(bool on)
void FindPlugin::openFindToolBar(FindDirection direction)
{
if (d->m_findToolBar) {
- d->m_findToolBar->setBackward(direction == FindBackward);
+ d->m_findToolBar->setBackward(direction == FindBackwardDirection);
d->m_findToolBar->openFindToolBar();
}
}
@@ -385,7 +386,7 @@ QKeySequence IFindFilter::defaultShortcut() const
QTextDocument::FindFlags Find::textDocumentFlagsForFindFlags(Find::FindFlags flags)
{
QTextDocument::FindFlags textDocFlags;
- if (flags & Find::FindBackward)
+ if (flags & FindBackward)
textDocFlags |= QTextDocument::FindBackward;
if (flags & Find::FindCaseSensitively)
textDocFlags |= QTextDocument::FindCaseSensitively;
diff --git a/src/plugins/find/findplugin.h b/src/plugins/find/findplugin.h
index 46e3953c76..b4fb190730 100644
--- a/src/plugins/find/findplugin.h
+++ b/src/plugins/find/findplugin.h
@@ -41,7 +41,7 @@ QT_END_NAMESPACE
namespace Find {
class IFindFilter;
-struct FindPluginPrivate;
+class FindPluginPrivate;
namespace Internal {
class FindToolBar;
@@ -59,8 +59,8 @@ public:
static FindPlugin *instance();
enum FindDirection {
- FindForward,
- FindBackward
+ FindForwardDirection,
+ FindBackwardDirection
};
// IPlugin
@@ -68,8 +68,8 @@ public:
void extensionsInitialized();
ShutdownFlag aboutToShutdown();
- Find::FindFlags findFlags() const;
- bool hasFindFlag(Find::FindFlag flag);
+ FindFlags findFlags() const;
+ bool hasFindFlag(FindFlag flag);
void updateFindCompletion(const QString &text);
void updateReplaceCompletion(const QString &text);
QStringListModel *findCompletionModel() const;
@@ -93,7 +93,7 @@ private slots:
void openFindFilter();
private:
- void setFindFlag(Find::FindFlag flag, bool enabled);
+ void setFindFlag(FindFlag flag, bool enabled);
void updateCompletion(const QString &text, QStringList &completions, QStringListModel *model);
void setupMenu();
void setupFilterMenuItems();
diff --git a/src/plugins/find/findtoolbar.cpp b/src/plugins/find/findtoolbar.cpp
index 227e319660..2b6c07d75a 100644
--- a/src/plugins/find/findtoolbar.cpp
+++ b/src/plugins/find/findtoolbar.cpp
@@ -369,7 +369,7 @@ void FindToolBar::updateToolBar()
m_caseSensitiveAction->setEnabled(enabled);
m_wholeWordAction->setEnabled(enabled);
m_regularExpressionAction->setEnabled(enabled);
- m_preserveCaseAction->setEnabled(replaceEnabled && !hasFindFlag(Find::FindRegularExpression));
+ m_preserveCaseAction->setEnabled(replaceEnabled && !hasFindFlag(FindRegularExpression));
if (QApplication::clipboard()->supportsFindBuffer())
m_enterFindStringAction->setEnabled(enabled);
bool replaceFocus = m_ui.replaceEdit->hasFocus();
@@ -415,13 +415,13 @@ void FindToolBar::invokeClearResults()
void FindToolBar::invokeFindNext()
{
- setFindFlag(Find::FindBackward, false);
+ setFindFlag(FindBackward, false);
invokeFindStep();
}
void FindToolBar::invokeFindPrevious()
{
- setFindFlag(Find::FindBackward, true);
+ setFindFlag(FindBackward, true);
invokeFindStep();
}
@@ -438,7 +438,7 @@ QString FindToolBar::getReplaceText()
void FindToolBar::setFindText(const QString &text)
{
disconnect(m_ui.findEdit, SIGNAL(textChanged(QString)), this, SLOT(invokeFindIncremental()));
- if (hasFindFlag(Find::FindRegularExpression))
+ if (hasFindFlag(FindRegularExpression))
m_ui.findEdit->setText(QRegExp::escape(text));
else
m_ui.findEdit->setText(text);
@@ -480,7 +480,7 @@ void FindToolBar::invokeFindIncremental()
void FindToolBar::invokeReplace()
{
- setFindFlag(Find::FindBackward, false);
+ setFindFlag(FindBackward, false);
if (m_currentDocumentFind->isEnabled() && m_currentDocumentFind->supportsReplace()) {
m_plugin->updateFindCompletion(getFindText());
m_plugin->updateReplaceCompletion(getReplaceText());
@@ -490,13 +490,13 @@ void FindToolBar::invokeReplace()
void FindToolBar::invokeReplaceNext()
{
- setFindFlag(Find::FindBackward, false);
+ setFindFlag(FindBackward, false);
invokeReplaceStep();
}
void FindToolBar::invokeReplacePrevious()
{
- setFindFlag(Find::FindBackward, true);
+ setFindFlag(FindBackward, true);
invokeReplaceStep();
}
@@ -554,11 +554,11 @@ void FindToolBar::findFlagsChanged()
void FindToolBar::updateIcons()
{
- Find::FindFlags effectiveFlags = effectiveFindFlags();
- bool casesensitive = effectiveFlags & Find::FindCaseSensitively;
- bool wholewords = effectiveFlags & Find::FindWholeWords;
- bool regexp = effectiveFlags & Find::FindRegularExpression;
- bool preserveCase = effectiveFlags & Find::FindPreserveCase;
+ FindFlags effectiveFlags = effectiveFindFlags();
+ bool casesensitive = effectiveFlags & FindCaseSensitively;
+ bool wholewords = effectiveFlags & FindWholeWords;
+ bool regexp = effectiveFlags & FindRegularExpression;
+ bool preserveCase = effectiveFlags & FindPreserveCase;
if (!casesensitive && !wholewords && !regexp && !preserveCase) {
QPixmap pixmap(17, 17);
pixmap.fill(Qt::transparent);
@@ -572,27 +572,27 @@ void FindToolBar::updateIcons()
}
}
-Find::FindFlags FindToolBar::effectiveFindFlags()
+FindFlags FindToolBar::effectiveFindFlags()
{
- Find::FindFlags supportedFlags;
+ FindFlags supportedFlags;
bool supportsReplace = true;
if (m_currentDocumentFind->isEnabled()) {
supportedFlags = m_currentDocumentFind->supportedFindFlags();
supportsReplace = m_currentDocumentFind->supportsReplace();
} else {
- supportedFlags = (Find::FindFlags)0xFFFFFF;
+ supportedFlags = (FindFlags)0xFFFFFF;
}
- if (!supportsReplace || m_findFlags & Find::FindRegularExpression)
- supportedFlags &= ~Find::FindPreserveCase;
+ if (!supportsReplace || m_findFlags & FindRegularExpression)
+ supportedFlags &= ~FindPreserveCase;
return supportedFlags & m_findFlags;
}
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));
+ bool wholeOnly = ((m_findFlags & FindWholeWords));
+ bool sensitive = ((m_findFlags & FindCaseSensitively));
+ bool regexp = ((m_findFlags & FindRegularExpression));
+ bool preserveCase = ((m_findFlags & FindPreserveCase));
if (m_wholeWordAction->isChecked() != wholeOnly)
m_wholeWordAction->setChecked(wholeOnly);
if (m_caseSensitiveAction->isChecked() != sensitive)
@@ -601,14 +601,14 @@ void FindToolBar::updateFlagMenus()
m_regularExpressionAction->setChecked(regexp);
if (m_preserveCaseAction->isChecked() != preserveCase)
m_preserveCaseAction->setChecked(preserveCase);
- Find::FindFlags supportedFlags;
+ 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);
+ m_wholeWordAction->setEnabled(supportedFlags & FindWholeWords);
+ m_caseSensitiveAction->setEnabled(supportedFlags & FindCaseSensitively);
+ m_regularExpressionAction->setEnabled(supportedFlags & FindRegularExpression);
bool replaceEnabled = m_currentDocumentFind->isEnabled() && m_currentDocumentFind->supportsReplace();
- m_preserveCaseAction->setEnabled((supportedFlags & Find::FindPreserveCase) && !regexp && replaceEnabled);
+ m_preserveCaseAction->setEnabled((supportedFlags & FindPreserveCase) && !regexp && replaceEnabled);
}
bool FindToolBar::setFocusToCurrentFindSupport()
@@ -698,11 +698,11 @@ void FindToolBar::writeSettings()
QSettings *settings = Core::ICore::settings();
settings->beginGroup(QLatin1String("Find"));
settings->beginGroup(QLatin1String("FindToolBar"));
- settings->setValue(QLatin1String("Backward"), QVariant((m_findFlags & Find::FindBackward) != 0));
- 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->setValue(QLatin1String("Backward"), QVariant((m_findFlags & FindBackward) != 0));
+ settings->setValue(QLatin1String("CaseSensitively"), QVariant((m_findFlags & FindCaseSensitively) != 0));
+ settings->setValue(QLatin1String("WholeWords"), QVariant((m_findFlags & FindWholeWords) != 0));
+ settings->setValue(QLatin1String("RegularExpression"), QVariant((m_findFlags & FindRegularExpression) != 0));
+ settings->setValue(QLatin1String("PreserveCase"), QVariant((m_findFlags & FindPreserveCase) != 0));
settings->endGroup();
settings->endGroup();
}
@@ -712,17 +712,17 @@ void FindToolBar::readSettings()
QSettings *settings = Core::ICore::settings();
settings->beginGroup(QLatin1String("Find"));
settings->beginGroup(QLatin1String("FindToolBar"));
- Find::FindFlags flags;
+ FindFlags flags;
if (settings->value(QLatin1String("Backward"), false).toBool())
- flags |= Find::FindBackward;
+ flags |= FindBackward;
if (settings->value(QLatin1String("CaseSensitively"), false).toBool())
- flags |= Find::FindCaseSensitively;
+ flags |= FindCaseSensitively;
if (settings->value(QLatin1String("WholeWords"), false).toBool())
- flags |= Find::FindWholeWords;
+ flags |= FindWholeWords;
if (settings->value(QLatin1String("RegularExpression"), false).toBool())
- flags |= Find::FindRegularExpression;
+ flags |= FindRegularExpression;
if (settings->value(QLatin1String("PreserveCase"), false).toBool())
- flags |= Find::FindPreserveCase;
+ flags |= FindPreserveCase;
settings->endGroup();
settings->endGroup();
m_findFlags = flags;
@@ -734,7 +734,7 @@ void FindToolBar::setUseFakeVim(bool on)
m_useFakeVim = on;
}
-void FindToolBar::setFindFlag(Find::FindFlag flag, bool enabled)
+void FindToolBar::setFindFlag(FindFlag flag, bool enabled)
{
bool hasFlag = hasFindFlag(flag);
if ((hasFlag && enabled) || (!hasFlag && !enabled))
@@ -743,36 +743,36 @@ void FindToolBar::setFindFlag(Find::FindFlag flag, bool enabled)
m_findFlags |= flag;
else
m_findFlags &= ~flag;
- if (flag != Find::FindBackward)
+ if (flag != FindBackward)
findFlagsChanged();
}
-bool FindToolBar::hasFindFlag(Find::FindFlag flag)
+bool FindToolBar::hasFindFlag(FindFlag flag)
{
return m_findFlags & flag;
}
void FindToolBar::setCaseSensitive(bool sensitive)
{
- setFindFlag(Find::FindCaseSensitively, sensitive);
+ setFindFlag(FindCaseSensitively, sensitive);
}
void FindToolBar::setWholeWord(bool wholeOnly)
{
- setFindFlag(Find::FindWholeWords, wholeOnly);
+ setFindFlag(FindWholeWords, wholeOnly);
}
void FindToolBar::setRegularExpressions(bool regexp)
{
- setFindFlag(Find::FindRegularExpression, regexp);
+ setFindFlag(FindRegularExpression, regexp);
}
void FindToolBar::setPreserveCase(bool preserveCase)
{
- setFindFlag(Find::FindPreserveCase, preserveCase);
+ setFindFlag(FindPreserveCase, preserveCase);
}
void FindToolBar::setBackward(bool backward)
{
- setFindFlag(Find::FindBackward, backward);
+ setFindFlag(FindBackward, backward);
}
diff --git a/src/plugins/find/findtoolbar.h b/src/plugins/find/findtoolbar.h
index f8f9b3b8ab..2928ac47e1 100644
--- a/src/plugins/find/findtoolbar.h
+++ b/src/plugins/find/findtoolbar.h
@@ -103,9 +103,9 @@ private:
void installEventFilters();
void invokeClearResults();
bool setFocusToCurrentFindSupport();
- void setFindFlag(Find::FindFlag flag, bool enabled);
- bool hasFindFlag(Find::FindFlag flag);
- Find::FindFlags effectiveFindFlags();
+ void setFindFlag(FindFlag flag, bool enabled);
+ bool hasFindFlag(FindFlag flag);
+ FindFlags effectiveFindFlags();
Core::FindToolBarPlaceHolder *findToolBarPlaceHolder() const;
bool eventFilter(QObject *obj, QEvent *event);
@@ -137,7 +137,7 @@ private:
QAction *m_wholeWordAction;
QAction *m_regularExpressionAction;
QAction *m_preserveCaseAction;
- Find::FindFlags m_findFlags;
+ FindFlags m_findFlags;
QTimer m_findIncrementalTimer;
QTimer m_findStepTimer;
diff --git a/src/plugins/find/findtoolwindow.cpp b/src/plugins/find/findtoolwindow.cpp
index 750de78865..5d22d114a9 100644
--- a/src/plugins/find/findtoolwindow.cpp
+++ b/src/plugins/find/findtoolwindow.cpp
@@ -124,19 +124,19 @@ void FindToolWindow::updateButtonStates()
m_configWidget->setEnabled(filterEnabled);
m_ui.matchCase->setEnabled(filterEnabled
- && (m_currentFilter->supportedFindFlags() & Find::FindCaseSensitively));
+ && (m_currentFilter->supportedFindFlags() & FindCaseSensitively));
m_ui.wholeWords->setEnabled(filterEnabled
- && (m_currentFilter->supportedFindFlags() & Find::FindWholeWords));
+ && (m_currentFilter->supportedFindFlags() & FindWholeWords));
m_ui.regExp->setEnabled(filterEnabled
- && (m_currentFilter->supportedFindFlags() & Find::FindRegularExpression));
+ && (m_currentFilter->supportedFindFlags() & FindRegularExpression));
m_ui.searchTerm->setEnabled(filterEnabled);
}
void FindToolWindow::updateFindFlags()
{
- m_ui.matchCase->setChecked(m_plugin->hasFindFlag(Find::FindCaseSensitively));
- m_ui.wholeWords->setChecked(m_plugin->hasFindFlag(Find::FindWholeWords));
- m_ui.regExp->setChecked(m_plugin->hasFindFlag(Find::FindRegularExpression));
+ m_ui.matchCase->setChecked(m_plugin->hasFindFlag(FindCaseSensitively));
+ m_ui.wholeWords->setChecked(m_plugin->hasFindFlag(FindWholeWords));
+ m_ui.regExp->setChecked(m_plugin->hasFindFlag(FindRegularExpression));
}
diff --git a/src/plugins/find/ifindfilter.cpp b/src/plugins/find/ifindfilter.cpp
index 77d1c5d0b0..06754f9ca0 100644
--- a/src/plugins/find/ifindfilter.cpp
+++ b/src/plugins/find/ifindfilter.cpp
@@ -216,22 +216,25 @@
The default is Find::FindCaseSensitively, Find::FindRegularExpression
and Find::FindWholeWords
*/
-Find::FindFlags Find::IFindFilter::supportedFindFlags() const
+
+namespace Find {
+
+FindFlags IFindFilter::supportedFindFlags() const
{
- return Find::FindCaseSensitively
- | Find::FindRegularExpression | Find::FindWholeWords;
+ return FindCaseSensitively
+ | FindRegularExpression | FindWholeWords;
}
-QPixmap Find::IFindFilter::pixmapForFindFlags(Find::FindFlags flags)
+QPixmap IFindFilter::pixmapForFindFlags(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;
+ bool casesensitive = flags & FindCaseSensitively;
+ bool wholewords = flags & FindWholeWords;
+ bool regexp = flags & FindRegularExpression;
+ bool preservecase = flags & FindPreserveCase;
int width = 0;
if (casesensitive) width += 6;
if (wholewords) width += 6;
@@ -260,16 +263,16 @@ QPixmap Find::IFindFilter::pixmapForFindFlags(Find::FindFlags flags)
return pixmap;
}
-QString Find::IFindFilter::descriptionForFindFlags(Find::FindFlags flags)
+QString IFindFilter::descriptionForFindFlags(FindFlags flags)
{
QStringList flagStrings;
- if (flags & Find::FindCaseSensitively)
+ if (flags & FindCaseSensitively)
flagStrings.append(tr("Case sensitive"));
- if (flags & Find::FindWholeWords)
+ if (flags & FindWholeWords)
flagStrings.append(tr("Whole words"));
- if (flags & Find::FindRegularExpression)
+ if (flags & FindRegularExpression)
flagStrings.append(tr("Regular expressions"));
- if (flags & Find::FindPreserveCase)
+ if (flags & FindPreserveCase)
flagStrings.append(tr("Preserve case"));
QString description = tr("Flags: %1");
if (flagStrings.isEmpty())
@@ -278,3 +281,5 @@ QString Find::IFindFilter::descriptionForFindFlags(Find::FindFlags flags)
description = description.arg(flagStrings.join(tr(", ")));
return description;
}
+
+} // namespace Find
diff --git a/src/plugins/find/ifindfilter.h b/src/plugins/find/ifindfilter.h
index ce58e58394..3be0336802 100644
--- a/src/plugins/find/ifindfilter.h
+++ b/src/plugins/find/ifindfilter.h
@@ -57,8 +57,8 @@ public:
virtual bool isReplaceSupported() const { return false; }
virtual FindFlags supportedFindFlags() const;
- virtual void findAll(const QString &txt, Find::FindFlags findFlags) = 0;
- virtual void replaceAll(const QString &txt, Find::FindFlags findFlags)
+ virtual void findAll(const QString &txt, FindFlags findFlags) = 0;
+ virtual void replaceAll(const QString &txt, FindFlags findFlags)
{ Q_UNUSED(txt) Q_UNUSED(findFlags) }
virtual QWidget *createConfigWidget() { return 0; }
diff --git a/src/plugins/find/searchresulttreeitems.cpp b/src/plugins/find/searchresulttreeitems.cpp
index b5e9ac8b5a..32ca311420 100644
--- a/src/plugins/find/searchresulttreeitems.cpp
+++ b/src/plugins/find/searchresulttreeitems.cpp
@@ -29,9 +29,10 @@
#include "searchresulttreeitems.h"
-using namespace Find::Internal;
+namespace Find {
+namespace Internal {
-SearchResultTreeItem::SearchResultTreeItem(const Find::SearchResultItem &item,
+SearchResultTreeItem::SearchResultTreeItem(const SearchResultItem &item,
SearchResultTreeItem *parent)
: item(item),
m_parent(parent),
@@ -115,7 +116,7 @@ int SearchResultTreeItem::insertionIndex(const QString &text, SearchResultTreeIt
return insertionPosition - m_children.begin();
}
-int SearchResultTreeItem::insertionIndex(const Find::SearchResultItem &item, SearchResultTreeItem **existingItem) const
+int SearchResultTreeItem::insertionIndex(const SearchResultItem &item, SearchResultTreeItem **existingItem) const
{
return insertionIndex(item.text, existingItem);
}
@@ -125,7 +126,7 @@ void SearchResultTreeItem::insertChild(int index, SearchResultTreeItem *child)
m_children.insert(index, child);
}
-void SearchResultTreeItem::insertChild(int index, const Find::SearchResultItem &item)
+void SearchResultTreeItem::insertChild(int index, const SearchResultItem &item)
{
SearchResultTreeItem *child = new SearchResultTreeItem(item, this);
if (isUserCheckable()) {
@@ -135,7 +136,10 @@ void SearchResultTreeItem::insertChild(int index, const Find::SearchResultItem &
insertChild(index, child);
}
-void SearchResultTreeItem::appendChild(const Find::SearchResultItem &item)
+void SearchResultTreeItem::appendChild(const SearchResultItem &item)
{
insertChild(m_children.count(), item);
}
+
+} // namespace Internal
+} // namespace Find
diff --git a/src/plugins/find/searchresulttreeview.cpp b/src/plugins/find/searchresulttreeview.cpp
index b8b233c67e..24559fc318 100644
--- a/src/plugins/find/searchresulttreeview.cpp
+++ b/src/plugins/find/searchresulttreeview.cpp
@@ -35,7 +35,8 @@
#include <QHeaderView>
#include <QKeyEvent>
-using namespace Find::Internal;
+namespace Find {
+namespace Internal {
SearchResultTreeView::SearchResultTreeView(QWidget *parent)
: QTreeView(parent)
@@ -71,7 +72,7 @@ void SearchResultTreeView::clear()
m_model->clear();
}
-void SearchResultTreeView::addResults(const QList<Find::SearchResultItem> &items, Find::SearchResult::AddMode mode)
+void SearchResultTreeView::addResults(const QList<SearchResultItem> &items, SearchResult::AddMode mode)
{
QList<QModelIndex> addedParents = m_model->addResults(items, mode);
if (m_autoExpandResults && !addedParents.isEmpty()) {
@@ -103,3 +104,6 @@ SearchResultTreeModel *SearchResultTreeView::model() const
{
return m_model;
}
+
+} // namespace Internal
+} // namespace Find
diff --git a/src/plugins/find/searchresulttreeview.h b/src/plugins/find/searchresulttreeview.h
index 4b4a3d205e..900329140c 100644
--- a/src/plugins/find/searchresulttreeview.h
+++ b/src/plugins/find/searchresulttreeview.h
@@ -51,7 +51,7 @@ public:
void setTextEditorFont(const QFont &font, const SearchResultColor color);
SearchResultTreeModel *model() const;
- void addResults(const QList<Find::SearchResultItem> &items, SearchResult::AddMode mode);
+ void addResults(const QList<SearchResultItem> &items, SearchResult::AddMode mode);
signals:
void jumpToSearchResult(const SearchResultItem &item);
diff --git a/src/plugins/find/searchresultwidget.cpp b/src/plugins/find/searchresultwidget.cpp
index e38aed622a..57c16afc61 100644
--- a/src/plugins/find/searchresultwidget.cpp
+++ b/src/plugins/find/searchresultwidget.cpp
@@ -167,7 +167,7 @@ SearchResultWidget::SearchResultWidget(QWidget *parent) :
m_preserveCaseCheck->setEnabled(false);
if (FindPlugin * plugin = FindPlugin::instance()) {
- m_preserveCaseCheck->setChecked(plugin->hasFindFlag(Find::FindPreserveCase));
+ m_preserveCaseCheck->setChecked(plugin->hasFindFlag(FindPreserveCase));
connect(m_preserveCaseCheck, SIGNAL(clicked(bool)), plugin, SLOT(setPreserveCase(bool)));
}
diff --git a/src/plugins/find/searchresultwindow.h b/src/plugins/find/searchresultwindow.h
index 24bc7db97e..49e371ce78 100644
--- a/src/plugins/find/searchresultwindow.h
+++ b/src/plugins/find/searchresultwindow.h
@@ -50,8 +50,9 @@ namespace Internal {
}
class SearchResultWindow;
-struct FIND_EXPORT SearchResultItem
+class FIND_EXPORT SearchResultItem
{
+public:
SearchResultItem()
: textMarkPos(-1),
textMarkLength(0),
diff --git a/src/plugins/find/textfindconstants.h b/src/plugins/find/textfindconstants.h
index 2383451a47..f2fe3f4d9c 100644
--- a/src/plugins/find/textfindconstants.h
+++ b/src/plugins/find/textfindconstants.h
@@ -74,7 +74,7 @@ enum FindFlag {
Q_DECLARE_FLAGS(FindFlags, FindFlag)
// defined in findplugin.cpp
-QTextDocument::FindFlags FIND_EXPORT textDocumentFlagsForFindFlags(Find::FindFlags flags);
+QTextDocument::FindFlags FIND_EXPORT textDocumentFlagsForFindFlags(FindFlags flags);
} // namespace Find
diff --git a/src/plugins/find/treeviewfind.cpp b/src/plugins/find/treeviewfind.cpp
index 414be05fe7..967f09fb51 100644
--- a/src/plugins/find/treeviewfind.cpp
+++ b/src/plugins/find/treeviewfind.cpp
@@ -66,10 +66,9 @@ bool TreeViewFind::supportsReplace() const
return false;
}
-Find::FindFlags TreeViewFind::supportedFindFlags() const
+FindFlags TreeViewFind::supportedFindFlags() const
{
- return Find::FindBackward | Find::FindCaseSensitively
- | Find::FindRegularExpression | Find::FindWholeWords;
+ return FindBackward | FindCaseSensitively | FindRegularExpression | FindWholeWords;
}
void TreeViewFind::resetIncrementalSearch()
@@ -96,8 +95,7 @@ void TreeViewFind::highlightAll(const QString &/*txt*/, FindFlags /*findFlags*/)
{
}
-IFindSupport::Result TreeViewFind::findIncremental(const QString &txt,
- Find::FindFlags findFlags)
+IFindSupport::Result TreeViewFind::findIncremental(const QString &txt, FindFlags findFlags)
{
if (!d->m_incrementalFindStart.isValid()) {
d->m_incrementalFindStart = d->m_view->currentIndex();
@@ -114,8 +112,7 @@ IFindSupport::Result TreeViewFind::findIncremental(const QString &txt,
return result;
}
-IFindSupport::Result TreeViewFind::findStep(const QString &txt,
- Find::FindFlags findFlags)
+IFindSupport::Result TreeViewFind::findStep(const QString &txt, FindFlags findFlags)
{
bool wrapped = false;
IFindSupport::Result result = find(txt, findFlags, false/*startFromNext*/,
@@ -130,7 +127,7 @@ IFindSupport::Result TreeViewFind::findStep(const QString &txt,
}
IFindSupport::Result TreeViewFind::find(const QString &searchTxt,
- Find::FindFlags findFlags,
+ FindFlags findFlags,
bool startFromCurrentIndex,
bool *wrapped)
{
@@ -139,8 +136,7 @@ IFindSupport::Result TreeViewFind::find(const QString &searchTxt,
if (searchTxt.isEmpty())
return IFindSupport::NotFound;
- QTextDocument::FindFlags flags =
- Find::textDocumentFlagsForFindFlags(findFlags);
+ QTextDocument::FindFlags flags = textDocumentFlagsForFindFlags(findFlags);
QModelIndex resultIndex;
QModelIndex currentIndex = d->m_view->currentIndex();
QModelIndex index = currentIndex;
@@ -160,8 +156,8 @@ IFindSupport::Result TreeViewFind::find(const QString &searchTxt,
if (index.isValid()) {
const QString &text = d->m_view->model()->data(
index, d->m_role).toString();
- if (findFlags & Find::FindRegularExpression) {
- bool sensitive = (findFlags & Find::FindCaseSensitively);
+ if (findFlags & FindRegularExpression) {
+ bool sensitive = (findFlags & FindCaseSensitively);
QRegExp searchExpr = QRegExp(searchTxt,
(sensitive ? Qt::CaseSensitive :
Qt::CaseInsensitive));
@@ -172,8 +168,7 @@ IFindSupport::Result TreeViewFind::find(const QString &searchTxt,
} else {
QTextDocument doc(text);
if (!doc.find(searchTxt, 0,
- flags & (Find::FindCaseSensitively |
- Find::FindWholeWords)).isNull()
+ flags & (FindCaseSensitively | FindWholeWords)).isNull()
&& d->m_view->model()->flags(index) & Qt::ItemIsSelectable
&& (index.row() != currentRow || index.parent() != currentIndex.parent()))
resultIndex = index;
diff --git a/src/plugins/find/treeviewfind.h b/src/plugins/find/treeviewfind.h
index aec6312f20..8d300978e7 100644
--- a/src/plugins/find/treeviewfind.h
+++ b/src/plugins/find/treeviewfind.h
@@ -40,7 +40,7 @@ QT_END_NAMESPACE
namespace Find {
class ItemModelFindPrivate;
-class FIND_EXPORT TreeViewFind : public Find::IFindSupport
+class FIND_EXPORT TreeViewFind : public IFindSupport
{
Q_OBJECT
public:
@@ -48,18 +48,18 @@ public:
virtual ~TreeViewFind();
bool supportsReplace() const;
- Find::FindFlags supportedFindFlags() const;
+ FindFlags supportedFindFlags() const;
void resetIncrementalSearch();
void clearResults();
QString currentFindString() const;
QString completedFindString() const;
virtual void highlightAll(const QString &txt, FindFlags findFlags);
- Result findIncremental(const QString &txt, Find::FindFlags findFlags);
- Result findStep(const QString &txt, Find::FindFlags findFlags);
+ Result findIncremental(const QString &txt, FindFlags findFlags);
+ Result findStep(const QString &txt, FindFlags findFlags);
private:
- Result find(const QString &txt, Find::FindFlags findFlags,
+ Result find(const QString &txt, FindFlags findFlags,
bool startFromCurrentIndex, bool *wrapped);
QModelIndex nextIndex(const QModelIndex &idx, bool *wrapped) const;
QModelIndex prevIndex(const QModelIndex &idx, bool *wrapped) const;
diff --git a/src/plugins/genericprojectmanager/GenericProjectManager.pluginspec.in b/src/plugins/genericprojectmanager/GenericProjectManager.pluginspec.in
index 19e72d595d..f4c8a5404d 100644
--- a/src/plugins/genericprojectmanager/GenericProjectManager.pluginspec.in
+++ b/src/plugins/genericprojectmanager/GenericProjectManager.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"GenericProjectManager\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"GenericProjectManager\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/genericprojectmanager/genericbuildconfiguration.cpp b/src/plugins/genericprojectmanager/genericbuildconfiguration.cpp
index 663552a635..f130f327b4 100644
--- a/src/plugins/genericprojectmanager/genericbuildconfiguration.cpp
+++ b/src/plugins/genericprojectmanager/genericbuildconfiguration.cpp
@@ -31,7 +31,11 @@
#include "genericmakestep.h"
#include "genericproject.h"
+#include "genericprojectconstants.h"
+#include <coreplugin/icore.h>
+#include <coreplugin/mimedatabase.h>
+#include <projectexplorer/buildinfo.h>
#include <projectexplorer/buildsteplist.h>
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/projectexplorerconstants.h>
@@ -48,7 +52,6 @@ namespace GenericProjectManager {
namespace Internal {
const char GENERIC_BC_ID[] = "GenericProjectManager.GenericBuildConfiguration";
-const char BUILD_DIRECTORY_KEY[] = "GenericProjectManager.GenericBuildConfiguration.BuildDirectory";
GenericBuildConfiguration::GenericBuildConfiguration(Target *parent)
: BuildConfiguration(parent, Core::Id(GENERIC_BC_ID))
@@ -61,50 +64,11 @@ GenericBuildConfiguration::GenericBuildConfiguration(Target *parent, const Core:
}
GenericBuildConfiguration::GenericBuildConfiguration(Target *parent, GenericBuildConfiguration *source) :
- BuildConfiguration(parent, source),
- m_buildDirectory(source->m_buildDirectory)
+ BuildConfiguration(parent, source)
{
cloneSteps(source);
}
-QVariantMap GenericBuildConfiguration::toMap() const
-{
- QVariantMap map(BuildConfiguration::toMap());
- map.insert(QLatin1String(BUILD_DIRECTORY_KEY), m_buildDirectory);
- return map;
-}
-
-bool GenericBuildConfiguration::fromMap(const QVariantMap &map)
-{
- m_buildDirectory = map.value(QLatin1String(BUILD_DIRECTORY_KEY), target()->project()->projectDirectory()).toString();
-
- return BuildConfiguration::fromMap(map);
-}
-
-QString GenericBuildConfiguration::buildDirectory() const
-{
- // Convert to absolute path when necessary
- const QDir projectDir(target()->project()->projectDirectory());
- return projectDir.absoluteFilePath(m_buildDirectory);
-}
-
-/**
- * Returns the build directory unmodified, instead of making it absolute like
- * buildDirectory() does.
- */
-QString GenericBuildConfiguration::rawBuildDirectory() const
-{
- return m_buildDirectory;
-}
-
-void GenericBuildConfiguration::setBuildDirectory(const QString &buildDirectory)
-{
- if (m_buildDirectory == buildDirectory)
- return;
- m_buildDirectory = buildDirectory;
- emit buildDirectoryChanged();
-}
-
NamedWidget *GenericBuildConfiguration::createConfigWidget()
{
return new GenericBuildSettingsWidget(this);
@@ -123,53 +87,52 @@ GenericBuildConfigurationFactory::~GenericBuildConfigurationFactory()
{
}
-QList<Core::Id> GenericBuildConfigurationFactory::availableCreationIds(const Target *parent) const
+bool GenericBuildConfigurationFactory::canCreate(const Target *parent) const
{
- if (!canHandle(parent))
- return QList<Core::Id>();
- return QList<Core::Id>() << Core::Id(GENERIC_BC_ID);
+ return canHandle(parent);
}
-QString GenericBuildConfigurationFactory::displayNameForId(const Core::Id id) const
+QList<BuildInfo *> GenericBuildConfigurationFactory::availableBuilds(const Target *parent) const
{
- if (id == GENERIC_BC_ID)
- return tr("Build");
- return QString();
+ QList<ProjectExplorer::BuildInfo *> result;
+ QTC_ASSERT(canCreate(parent), return result);
+
+ BuildInfo *info = createBuildInfo(parent->kit(), Utils::FileName::fromString(parent->project()->projectDirectory()));
+ result << info;
+ return result;
}
-bool GenericBuildConfigurationFactory::canCreate(const Target *parent, const Core::Id id) const
+bool GenericBuildConfigurationFactory::canSetup(const Kit *k, const QString &projectPath) const
{
- if (!canHandle(parent))
- return false;
- if (id == GENERIC_BC_ID)
- return true;
- return false;
+ return k && Core::MimeDatabase::findByFile(QFileInfo(projectPath))
+ .matchesType(QLatin1String(Constants::GENERICMIMETYPE));
}
-BuildConfiguration *GenericBuildConfigurationFactory::create(Target *parent, const Core::Id id, const QString &name)
+QList<BuildInfo *> GenericBuildConfigurationFactory::availableSetups(const Kit *k, const QString &projectPath) const
{
- if (!canCreate(parent, id))
- return 0;
+ QList<BuildInfo *> result;
+ QTC_ASSERT(canSetup(k, projectPath), return result);
+ BuildInfo *info = createBuildInfo(k, Utils::FileName::fromString(ProjectExplorer::Project::projectDirectory(projectPath)));
+ //: The name of the build configuration created by default for a generic project.
+ info->displayName = tr("Default");
+ result << info;
+ return result;
+}
- //TODO asking for name is duplicated everywhere, but maybe more
- // wizards will show up, that incorporate choosing the nam
- bool ok = true;
- QString buildConfigurationName = name;
- if (buildConfigurationName.isNull())
- buildConfigurationName = QInputDialog::getText(0,
- tr("New Configuration"),
- tr("New configuration name:"),
- QLineEdit::Normal,
- QString(), &ok);
- buildConfigurationName = buildConfigurationName.trimmed();
- if (!ok || buildConfigurationName.isEmpty())
- return 0;
+BuildConfiguration *GenericBuildConfigurationFactory::create(Target *parent, const BuildInfo *info) const
+{
+ QTC_ASSERT(canCreate(parent), return 0);
+ QTC_ASSERT(info->factory() == this, return 0);
+ QTC_ASSERT(info->kitId == parent->kit()->id(), return 0);
+ QTC_ASSERT(!info->displayName.isEmpty(), return 0);
GenericBuildConfiguration *bc = new GenericBuildConfiguration(parent);
- bc->setDisplayName(buildConfigurationName);
+ bc->setDisplayName(info->displayName);
+ bc->setDefaultDisplayName(info->displayName);
+ bc->setBuildDirectory(info->buildDirectory);
- BuildStepList *buildSteps = bc->stepList(Constants::BUILDSTEPS_BUILD);
- BuildStepList *cleanSteps = bc->stepList(Constants::BUILDSTEPS_CLEAN);
+ BuildStepList *buildSteps = bc->stepList(ProjectExplorer::Constants::BUILDSTEPS_BUILD);
+ BuildStepList *cleanSteps = bc->stepList(ProjectExplorer::Constants::BUILDSTEPS_CLEAN);
Q_ASSERT(buildSteps);
GenericMakeStep *makeStep = new GenericMakeStep(buildSteps);
@@ -187,7 +150,9 @@ BuildConfiguration *GenericBuildConfigurationFactory::create(Target *parent, con
bool GenericBuildConfigurationFactory::canClone(const Target *parent, BuildConfiguration *source) const
{
- return canCreate(parent, source->id());
+ if (!canHandle(parent))
+ return false;
+ return source->id() == GENERIC_BC_ID;
}
BuildConfiguration *GenericBuildConfigurationFactory::clone(Target *parent, BuildConfiguration *source)
@@ -199,7 +164,9 @@ BuildConfiguration *GenericBuildConfigurationFactory::clone(Target *parent, Buil
bool GenericBuildConfigurationFactory::canRestore(const Target *parent, const QVariantMap &map) const
{
- return canCreate(parent, ProjectExplorer::idFromMap(map));
+ if (!canHandle(parent))
+ return false;
+ return ProjectExplorer::idFromMap(map) == GENERIC_BC_ID;
}
BuildConfiguration *GenericBuildConfigurationFactory::restore(Target *parent, const QVariantMap &map)
@@ -220,6 +187,16 @@ bool GenericBuildConfigurationFactory::canHandle(const Target *t) const
return qobject_cast<GenericProject *>(t->project());
}
+BuildInfo *GenericBuildConfigurationFactory::createBuildInfo(const ProjectExplorer::Kit *k,
+ const Utils::FileName &buildDir) const
+{
+ BuildInfo *info = new BuildInfo(this);
+ info->typeName = tr("Build");
+ info->buildDirectory = buildDir;
+ info->kitId = k->id();
+ return info;
+}
+
BuildConfiguration::BuildType GenericBuildConfiguration::buildType() const
{
return Unknown;
@@ -244,13 +221,21 @@ GenericBuildSettingsWidget::GenericBuildSettingsWidget(GenericBuildConfiguration
m_buildConfiguration = bc;
m_pathChooser->setBaseDirectory(bc->target()->project()->projectDirectory());
- m_pathChooser->setPath(m_buildConfiguration->rawBuildDirectory());
+ m_pathChooser->setEnvironment(bc->environment());
+ m_pathChooser->setPath(m_buildConfiguration->rawBuildDirectory().toString());
setDisplayName(tr("Generic Manager"));
+
+ connect(bc, SIGNAL(environmentChanged()), this, SLOT(environmentHasChanged()));
}
void GenericBuildSettingsWidget::buildDirectoryChanged()
{
- m_buildConfiguration->setBuildDirectory(m_pathChooser->rawPath());
+ m_buildConfiguration->setBuildDirectory(Utils::FileName::fromString(m_pathChooser->rawPath()));
+}
+
+void GenericBuildSettingsWidget::environmentHasChanged()
+{
+ m_pathChooser->setEnvironment(m_buildConfiguration->environment());
}
} // namespace Internal
diff --git a/src/plugins/genericprojectmanager/genericbuildconfiguration.h b/src/plugins/genericprojectmanager/genericbuildconfiguration.h
index 996fa4ae42..aca2452d65 100644
--- a/src/plugins/genericprojectmanager/genericbuildconfiguration.h
+++ b/src/plugins/genericprojectmanager/genericbuildconfiguration.h
@@ -33,13 +33,17 @@
#include <projectexplorer/buildconfiguration.h>
#include <projectexplorer/namedwidget.h>
-namespace Utils { class PathChooser; }
+namespace Utils {
+class FileName;
+class PathChooser;
+} // namespace Utils
namespace GenericProjectManager {
namespace Internal {
class GenericTarget;
class GenericBuildConfigurationFactory;
+class GenericBuildSettingsWidget;
class GenericBuildConfiguration : public ProjectExplorer::BuildConfiguration
{
@@ -50,21 +54,14 @@ public:
explicit GenericBuildConfiguration(ProjectExplorer::Target *parent);
ProjectExplorer::NamedWidget *createConfigWidget();
- QString buildDirectory() const;
- QString rawBuildDirectory() const;
- void setBuildDirectory(const QString &buildDirectory);
-
- QVariantMap toMap() const;
BuildType buildType() const;
protected:
GenericBuildConfiguration(ProjectExplorer::Target *parent, GenericBuildConfiguration *source);
GenericBuildConfiguration(ProjectExplorer::Target *parent, const Core::Id id);
- virtual bool fromMap(const QVariantMap &map);
-private:
- QString m_buildDirectory;
+ friend class GenericBuildSettingsWidget;
};
class GenericBuildConfigurationFactory : public ProjectExplorer::IBuildConfigurationFactory
@@ -75,11 +72,14 @@ public:
explicit GenericBuildConfigurationFactory(QObject *parent = 0);
~GenericBuildConfigurationFactory();
- QList<Core::Id> availableCreationIds(const ProjectExplorer::Target *parent) const;
- QString displayNameForId(const Core::Id id) const;
+ bool canCreate(const ProjectExplorer::Target *parent) const;
+ QList<ProjectExplorer::BuildInfo *> availableBuilds(const ProjectExplorer::Target *parent) const;
+ bool canSetup(const ProjectExplorer::Kit *k, const QString &projectPath) const;
+ QList<ProjectExplorer::BuildInfo *> availableSetups(const ProjectExplorer::Kit *k,
+ const QString &projectPath) const;
+ ProjectExplorer::BuildConfiguration *create(ProjectExplorer::Target *parent,
+ const ProjectExplorer::BuildInfo *info) const;
- bool canCreate(const ProjectExplorer::Target *parent, const Core::Id id) const;
- ProjectExplorer::BuildConfiguration *create(ProjectExplorer::Target *parent, const Core::Id id, const QString &name = QString());
bool canClone(const ProjectExplorer::Target *parent, ProjectExplorer::BuildConfiguration *source) const;
ProjectExplorer::BuildConfiguration *clone(ProjectExplorer::Target *parent, ProjectExplorer::BuildConfiguration *source);
bool canRestore(const ProjectExplorer::Target *parent, const QVariantMap &map) const;
@@ -87,6 +87,7 @@ public:
private:
bool canHandle(const ProjectExplorer::Target *t) const;
+ ProjectExplorer::BuildInfo *createBuildInfo(const ProjectExplorer::Kit *k, const Utils::FileName &buildDir) const;
};
class GenericBuildSettingsWidget : public ProjectExplorer::NamedWidget
@@ -98,6 +99,7 @@ public:
private slots:
void buildDirectoryChanged();
+ void environmentHasChanged();
private:
Utils::PathChooser *m_pathChooser;
diff --git a/src/plugins/genericprojectmanager/genericmakestep.cpp b/src/plugins/genericprojectmanager/genericmakestep.cpp
index da24383a73..d2f0c58076 100644
--- a/src/plugins/genericprojectmanager/genericmakestep.cpp
+++ b/src/plugins/genericprojectmanager/genericmakestep.cpp
@@ -47,6 +47,8 @@
#include <utils/qtcassert.h>
#include <utils/qtcprocess.h>
+#include <QDir>
+
using namespace Core;
using namespace ProjectExplorer;
@@ -113,7 +115,7 @@ bool GenericMakeStep::init()
ProcessParameters *pp = processParameters();
pp->setMacroExpander(bc->macroExpander());
- pp->setWorkingDirectory(bc->buildDirectory());
+ pp->setWorkingDirectory(bc->buildDirectory().toString());
Utils::Environment env = bc->environment();
// Force output to english for the parsers. Do this here and not in the toolchain's
// addToEnvironment() to not screw up the users run environment.
@@ -290,7 +292,7 @@ void GenericMakeStepConfigWidget::updateMakeOverrrideLabel()
if (!bc)
bc = m_makeStep->target()->activeBuildConfiguration();
- m_ui->makeLabel->setText(tr("Override %1:").arg(m_makeStep->makeCommand(bc->environment())));
+ m_ui->makeLabel->setText(tr("Override %1:").arg(QDir::toNativeSeparators(m_makeStep->makeCommand(bc->environment()))));
}
void GenericMakeStepConfigWidget::updateDetails()
@@ -301,7 +303,7 @@ void GenericMakeStepConfigWidget::updateDetails()
ProcessParameters param;
param.setMacroExpander(bc->macroExpander());
- param.setWorkingDirectory(bc->buildDirectory());
+ param.setWorkingDirectory(bc->buildDirectory().toString());
param.setEnvironment(bc->environment());
param.setCommand(m_makeStep->makeCommand(bc->environment()));
param.setArguments(m_makeStep->allArguments());
diff --git a/src/plugins/genericprojectmanager/genericproject.cpp b/src/plugins/genericprojectmanager/genericproject.cpp
index 86019214a9..69c5209063 100644
--- a/src/plugins/genericprojectmanager/genericproject.cpp
+++ b/src/plugins/genericprojectmanager/genericproject.cpp
@@ -221,8 +221,11 @@ void GenericProject::parseProject(RefreshOptions options)
m_defines.clear();
QFile configFile(configFileName());
- if (configFile.open(QFile::ReadOnly))
- m_defines = configFile.readAll();
+ if (configFile.open(QFile::ReadOnly)) {
+ // convert from local/file encoding to UTF-8
+ QTextStream configStream(&configFile);
+ m_defines = configStream.readAll().toUtf8();
+ }
}
if (options & Files)
@@ -248,13 +251,14 @@ void GenericProject::refresh(RefreshOptions options)
pinfo.clearProjectParts();
CppTools::ProjectPart::Ptr part(new CppTools::ProjectPart);
- Kit *k = activeTarget() ? activeTarget()->kit() : KitManager::instance()->defaultKit();
+ Kit *k = activeTarget() ? activeTarget()->kit() : KitManager::defaultKit();
if (ToolChain *tc = ToolChainKitInformation::toolChain(k)) {
QStringList cxxflags; // FIXME: Can we do better?
part->evaluateToolchain(tc, cxxflags, cxxflags,
SysRootKitInformation::sysRoot(k));
}
+ part->cxxVersion = CppTools::ProjectPart::CXX11; // assume C++11
part->includePaths += allIncludePaths();
part->defines += m_defines;
@@ -265,22 +269,7 @@ void GenericProject::refresh(RefreshOptions options)
foreach (const QString &file, files())
adder.maybeAdd(file);
- QStringList filesToUpdate;
-
- if (options & Configuration) {
- foreach (const CppTools::ProjectFile &file, part->files)
- filesToUpdate << file.path;
- filesToUpdate.append(CppTools::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;
- foreach (const CppTools::ProjectFile &file, part->files)
- newFileList.insert(file.path);
- newFileList.subtract(oldFileList);
- filesToUpdate.append(newFileList.toList());
- }
+ m_codeModelFuture.cancel();
pinfo.appendProjectPart(part);
setProjectLanguage(ProjectExplorer::Constants::LANG_CXX, !part->files.isEmpty());
@@ -422,7 +411,7 @@ bool GenericProject::fromMap(const QVariantMap &map)
if (!Project::fromMap(map))
return false;
- Kit *defaultKit = KitManager::instance()->defaultKit();
+ Kit *defaultKit = KitManager::defaultKit();
if (!activeTarget() && defaultKit)
addTarget(createTarget(defaultKit));
@@ -452,18 +441,14 @@ bool GenericProject::fromMap(const QVariantMap &map)
GenericProjectFile::GenericProjectFile(GenericProject *parent, QString fileName, GenericProject::RefreshOptions options)
: IDocument(parent),
m_project(parent),
- m_fileName(fileName),
m_options(options)
-{ }
-
-bool GenericProjectFile::save(QString *, const QString &, bool)
{
- return false;
+ setFilePath(fileName);
}
-QString GenericProjectFile::fileName() const
+bool GenericProjectFile::save(QString *, const QString &, bool)
{
- return m_fileName;
+ return false;
}
QString GenericProjectFile::defaultPath() const
@@ -491,13 +476,6 @@ bool GenericProjectFile::isSaveAsAllowed() const
return false;
}
-void GenericProjectFile::rename(const QString &newName)
-{
- // Can't happen
- Q_UNUSED(newName);
- QTC_CHECK(false);
-}
-
IDocument::ReloadBehavior GenericProjectFile::reloadBehavior(ChangeTrigger state, ChangeType type) const
{
Q_UNUSED(state)
diff --git a/src/plugins/genericprojectmanager/genericproject.h b/src/plugins/genericprojectmanager/genericproject.h
index 917a69482f..f4f2fb5457 100644
--- a/src/plugins/genericprojectmanager/genericproject.h
+++ b/src/plugins/genericprojectmanager/genericproject.h
@@ -128,7 +128,6 @@ public:
GenericProjectFile(GenericProject *parent, QString fileName, GenericProject::RefreshOptions options);
bool save(QString *errorString, const QString &fileName, bool autoSave);
- QString fileName() const;
QString defaultPath() const;
QString suggestedFileName() const;
@@ -136,14 +135,12 @@ public:
bool isModified() const;
bool isSaveAsAllowed() const;
- void rename(const QString &newName);
ReloadBehavior reloadBehavior(ChangeTrigger state, ChangeType type) const;
bool reload(QString *errorString, ReloadFlag flag, ChangeType type);
private:
GenericProject *m_project;
- QString m_fileName;
GenericProject::RefreshOptions m_options;
};
diff --git a/src/plugins/genericprojectmanager/genericprojectconstants.h b/src/plugins/genericprojectmanager/genericprojectconstants.h
index 4587586d29..bba052ed5c 100644
--- a/src/plugins/genericprojectmanager/genericprojectconstants.h
+++ b/src/plugins/genericprojectmanager/genericprojectconstants.h
@@ -48,7 +48,7 @@ const char CONFIG_MIMETYPE[] = "application/vnd.qtcreator.generic.config";
const char GENERICPROJECT_ID[] = "GenericProjectManager.GenericProject";
const char HIDE_FILE_FILTER_SETTING[] = "GenericProject/FileFilter";
-const char HIDE_FILE_FILTER_DEFAULT[] = "Makefile*; *.o; *.obj; *~; *.files; *.config; *.creator; *.user; *.includes";
+const char HIDE_FILE_FILTER_DEFAULT[] = "Makefile*; *.o; *.obj; *~; *.files; *.config; *.creator; *.user; *.includes; *.autosave";
const char SHOW_FILE_FILTER_SETTING[] = "GenericProject/ShowFileFilter";
const char SHOW_FILE_FILTER_DEFAULT[] = "*.c; *.cc; *.cpp; *.cp; *.cxx; *.c++; *.h; *.hh; *.hpp; *.hxx;";
diff --git a/src/plugins/genericprojectmanager/genericprojectfileseditor.cpp b/src/plugins/genericprojectmanager/genericprojectfileseditor.cpp
index ef62b1e3b5..287ce30563 100644
--- a/src/plugins/genericprojectmanager/genericprojectfileseditor.cpp
+++ b/src/plugins/genericprojectmanager/genericprojectfileseditor.cpp
@@ -54,33 +54,20 @@ ProjectFilesFactory::ProjectFilesFactory(Manager *manager, TextEditorActionHandl
: Core::IEditorFactory(manager),
m_actionHandler(handler)
{
- m_mimeTypes.append(QLatin1String(Constants::FILES_MIMETYPE));
- m_mimeTypes.append(QLatin1String(Constants::INCLUDES_MIMETYPE));
- m_mimeTypes.append(QLatin1String(Constants::CONFIG_MIMETYPE));
+ setId(Constants::FILES_EDITOR_ID);
+ setDisplayName(QCoreApplication::translate("OpenWith::Editors", ".files Editor"));
+ addMimeType(Constants::FILES_MIMETYPE);
+ addMimeType(Constants::INCLUDES_MIMETYPE);
+ addMimeType(Constants::CONFIG_MIMETYPE);
}
Core::IEditor *ProjectFilesFactory::createEditor(QWidget *parent)
{
ProjectFilesEditorWidget *ed = new ProjectFilesEditorWidget(parent, this, m_actionHandler);
- TextEditorSettings::instance()->initializeEditor(ed);
+ TextEditorSettings::initializeEditor(ed);
return ed->editor();
}
-QStringList ProjectFilesFactory::mimeTypes() const
-{
- return m_mimeTypes;
-}
-
-Core::Id ProjectFilesFactory::id() const
-{
- return Core::Id(Constants::FILES_EDITOR_ID);
-}
-
-QString ProjectFilesFactory::displayName() const
-{
- return QCoreApplication::translate("OpenWith::Editors", ".files Editor");
-}
-
////////////////////////////////////////////////////////////////////////////////////////
//
// ProjectFilesEditable
@@ -109,7 +96,7 @@ Core::IEditor *ProjectFilesEditor::duplicate(QWidget *parent)
ProjectFilesEditorWidget *editor = new ProjectFilesEditorWidget(parent,
parentEditor->factory(),
parentEditor->actionHandler());
- TextEditorSettings::instance()->initializeEditor(editor);
+ TextEditorSettings::initializeEditor(editor);
return editor->editor();
}
diff --git a/src/plugins/genericprojectmanager/genericprojectfileseditor.h b/src/plugins/genericprojectmanager/genericprojectfileseditor.h
index a2fa73a4d7..75014f8060 100644
--- a/src/plugins/genericprojectmanager/genericprojectfileseditor.h
+++ b/src/plugins/genericprojectmanager/genericprojectfileseditor.h
@@ -56,13 +56,8 @@ public:
Core::IEditor *createEditor(QWidget *parent);
- QStringList mimeTypes() const;
- Core::Id id() const;
- QString displayName() const;
-
private:
TextEditor::TextEditorActionHandler *m_actionHandler;
- QStringList m_mimeTypes;
};
class ProjectFilesEditor : public TextEditor::BaseTextEditor
@@ -75,7 +70,6 @@ public:
Core::Id id() const;
bool duplicateSupported() const;
Core::IEditor *duplicate(QWidget *parent);
- bool isTemporary() const { return false; }
};
class ProjectFilesEditorWidget : public TextEditor::BaseTextEditorWidget
diff --git a/src/plugins/genericprojectmanager/genericprojectnodes.cpp b/src/plugins/genericprojectmanager/genericprojectnodes.cpp
index 192e1c9f45..7bd6773f53 100644
--- a/src/plugins/genericprojectmanager/genericprojectnodes.cpp
+++ b/src/plugins/genericprojectmanager/genericprojectnodes.cpp
@@ -42,9 +42,9 @@ namespace GenericProjectManager {
namespace Internal {
GenericProjectNode::GenericProjectNode(GenericProject *project, Core::IDocument *projectFile)
- : ProjectNode(projectFile->fileName()), m_project(project), m_projectFile(projectFile)
+ : ProjectNode(projectFile->filePath()), m_project(project), m_projectFile(projectFile)
{
- setDisplayName(QFileInfo(projectFile->fileName()).completeBaseName());
+ setDisplayName(QFileInfo(projectFile->filePath()).completeBaseName());
}
Core::IDocument *GenericProjectNode::projectFile() const
@@ -54,7 +54,7 @@ Core::IDocument *GenericProjectNode::projectFile() const
QString GenericProjectNode::projectFilePath() const
{
- return m_projectFile->fileName();
+ return m_projectFile->filePath();
}
QHash<QString, QStringList> sortFilesIntoPaths(const QString &base, const QSet<QString> files)
@@ -259,37 +259,28 @@ bool GenericProjectNode::removeSubProjects(const QStringList &proFilePaths)
return false;
}
-bool GenericProjectNode::addFiles(const FileType fileType,
- const QStringList &filePaths, QStringList *notAdded)
+bool GenericProjectNode::addFiles(const QStringList &filePaths, QStringList *notAdded)
{
- Q_UNUSED(fileType)
Q_UNUSED(notAdded)
return m_project->addFiles(filePaths);
}
-bool GenericProjectNode::removeFiles(const FileType fileType,
- const QStringList &filePaths, QStringList *notRemoved)
+bool GenericProjectNode::removeFiles(const QStringList &filePaths, QStringList *notRemoved)
{
- Q_UNUSED(fileType)
Q_UNUSED(notRemoved)
return m_project->removeFiles(filePaths);
}
-bool GenericProjectNode::deleteFiles(const FileType fileType,
- const QStringList &filePaths)
+bool GenericProjectNode::deleteFiles(const QStringList &filePaths)
{
- Q_UNUSED(fileType)
Q_UNUSED(filePaths)
return false;
}
-bool GenericProjectNode::renameFile(const FileType fileType,
- const QString &filePath, const QString &newFilePath)
+bool GenericProjectNode::renameFile(const QString &filePath, const QString &newFilePath)
{
- Q_UNUSED(fileType)
-
return m_project->renameFile(filePath, newFilePath);
}
diff --git a/src/plugins/genericprojectmanager/genericprojectnodes.h b/src/plugins/genericprojectmanager/genericprojectnodes.h
index 35d2465a5c..38ed7bdc17 100644
--- a/src/plugins/genericprojectmanager/genericprojectnodes.h
+++ b/src/plugins/genericprojectmanager/genericprojectnodes.h
@@ -62,19 +62,10 @@ public:
bool addSubProjects(const QStringList &proFilePaths);
bool removeSubProjects(const QStringList &proFilePaths);
- bool addFiles(const ProjectExplorer::FileType fileType,
- const QStringList &filePaths,
- QStringList *notAdded = 0);
-
- bool removeFiles(const ProjectExplorer::FileType fileType,
- const QStringList &filePaths,
- QStringList *notRemoved = 0);
- bool deleteFiles(const ProjectExplorer::FileType fileType,
- const QStringList &filePaths);
-
- bool renameFile(const ProjectExplorer::FileType fileType,
- const QString &filePath,
- const QString &newFilePath);
+ bool addFiles(const QStringList &filePaths, QStringList *notAdded = 0);
+ bool removeFiles(const QStringList &filePaths, QStringList *notRemoved = 0);
+ bool deleteFiles(const QStringList &filePaths);
+ bool renameFile(const QString &filePath, const QString &newFilePath);
QList<ProjectExplorer::RunConfiguration *> runConfigurationsFor(Node *node);
diff --git a/src/plugins/genericprojectmanager/genericprojectplugin.cpp b/src/plugins/genericprojectmanager/genericprojectplugin.cpp
index 837fffece3..08695a063b 100644
--- a/src/plugins/genericprojectmanager/genericprojectplugin.cpp
+++ b/src/plugins/genericprojectmanager/genericprojectplugin.cpp
@@ -69,11 +69,9 @@ bool GenericProjectPlugin::initialize(const QStringList &, QString *errorMessage
{
using namespace Core;
- Core::MimeDatabase *mimeDB = ICore::mimeDatabase();
-
const QLatin1String mimetypesXml(":genericproject/GenericProjectManager.mimetypes.xml");
- if (! mimeDB->addMimeTypes(mimetypesXml, errorMessage))
+ if (!MimeDatabase::addMimeTypes(mimetypesXml, errorMessage))
return false;
Manager *manager = new Manager;
@@ -89,13 +87,13 @@ bool GenericProjectPlugin::initialize(const QStringList &, QString *errorMessage
addAutoReleasedObject(new GenericProjectWizard);
addAutoReleasedObject(new GenericBuildConfigurationFactory);
- const Core::Context projectContext(Constants::PROJECTCONTEXT);
- Core::ActionContainer *mproject =
- Core::ActionManager::actionContainer(ProjectExplorer::Constants::M_PROJECTCONTEXT);
+ const Context projectContext(Constants::PROJECTCONTEXT);
+ ActionContainer *mproject =
+ ActionManager::actionContainer(ProjectExplorer::Constants::M_PROJECTCONTEXT);
m_editFilesAction = new QAction(tr("Edit Files..."), this);
- Core::Command *command = Core::ActionManager::registerAction(m_editFilesAction, "GenericProjectManager.EditFiles", projectContext);
- command->setAttribute(Core::Command::CA_Hide);
+ Command *command = ActionManager::registerAction(m_editFilesAction, "GenericProjectManager.EditFiles", projectContext);
+ command->setAttribute(Command::CA_Hide);
mproject->addAction(command, ProjectExplorer::Constants::G_PROJECT_FILES);
connect(m_editFilesAction, SIGNAL(triggered()), this, SLOT(editFiles()));
@@ -117,7 +115,7 @@ void GenericProjectPlugin::updateContextMenu(ProjectExplorer::Project *project,
void GenericProjectPlugin::editFiles()
{
GenericProject *genericProject = static_cast<GenericProject *>(m_contextMenuProject);
- SelectableFilesDialog sfd(QFileInfo(genericProject->document()->fileName()).path(), genericProject->files(),
+ SelectableFilesDialog sfd(QFileInfo(genericProject->projectFilePath()).path(), genericProject->files(),
Core::ICore::mainWindow());
if (sfd.exec() == QDialog::Accepted)
genericProject->setFiles(sfd.selectedFiles());
diff --git a/src/plugins/genericprojectmanager/genericprojectwizard.cpp b/src/plugins/genericprojectmanager/genericprojectwizard.cpp
index e2e2874e4e..60b118b01b 100644
--- a/src/plugins/genericprojectmanager/genericprojectwizard.cpp
+++ b/src/plugins/genericprojectmanager/genericprojectwizard.cpp
@@ -108,33 +108,23 @@ QString GenericProjectWizardDialog::projectName() const
//////////////////////////////////////////////////////////////////////////////
GenericProjectWizard::GenericProjectWizard()
- : Core::BaseFileWizard(parameters())
-{ }
-
-Core::FeatureSet GenericProjectWizard::requiredFeatures() const
{
- return Core::FeatureSet();
-}
-
-Core::BaseFileWizardParameters GenericProjectWizard::parameters()
-{
- Core::BaseFileWizardParameters parameters(ProjectWizard);
+ setWizardKind(ProjectWizard);
// TODO do something about the ugliness of standard icons in sizes different than 16, 32, 64, 128
{
QPixmap icon(22, 22);
icon.fill(Qt::transparent);
QPainter p(&icon);
p.drawPixmap(3, 3, 16, 16, qApp->style()->standardIcon(QStyle::SP_DirIcon).pixmap(16));
- parameters.setIcon(icon);
+ setIcon(icon);
}
- parameters.setDisplayName(tr("Import Existing Project"));
- parameters.setId(QLatin1String("Z.Makefile"));
- parameters.setDescription(tr("Imports existing projects that do not use qmake, CMake or Autotools. "
- "This allows you to use Qt Creator as a code editor."));
- parameters.setCategory(QLatin1String(ProjectExplorer::Constants::IMPORT_WIZARD_CATEGORY));
- parameters.setDisplayCategory(QLatin1String(ProjectExplorer::Constants::IMPORT_WIZARD_CATEGORY_DISPLAY));
- parameters.setFlags(Core::IWizard::PlatformIndependent);
- return parameters;
+ setDisplayName(tr("Import Existing Project"));
+ setId(QLatin1String("Z.Makefile"));
+ setDescription(tr("Imports existing projects that do not use qmake, CMake or Autotools. "
+ "This allows you to use Qt Creator as a code editor."));
+ setCategory(QLatin1String(ProjectExplorer::Constants::IMPORT_WIZARD_CATEGORY));
+ setDisplayCategory(QLatin1String(ProjectExplorer::Constants::IMPORT_WIZARD_CATEGORY_DISPLAY));
+ setFlags(Core::IWizard::PlatformIndependent);
}
QWizard *GenericProjectWizard::createWizardDialog(QWidget *parent,
@@ -166,9 +156,7 @@ Core::GeneratedFiles GenericProjectWizard::generateFiles(const QWizard *w,
const QString configFileName = QFileInfo(dir, projectName + QLatin1String(".config")).absoluteFilePath();
const QStringList paths = wizard->selectedPaths();
- Core::MimeDatabase *mimeDatabase = Core::ICore::mimeDatabase();
-
- Core::MimeType headerTy = mimeDatabase->findByType(QLatin1String("text/x-chdr"));
+ Core::MimeType headerTy = Core::MimeDatabase::findByType(QLatin1String("text/x-chdr"));
QStringList nameFilters;
foreach (const Core::MimeGlobPattern &gp, headerTy.globPatterns())
diff --git a/src/plugins/genericprojectmanager/genericprojectwizard.h b/src/plugins/genericprojectmanager/genericprojectwizard.h
index 3db2991b66..2a2aac9147 100644
--- a/src/plugins/genericprojectmanager/genericprojectwizard.h
+++ b/src/plugins/genericprojectmanager/genericprojectwizard.h
@@ -64,9 +64,6 @@ class GenericProjectWizard : public Core::BaseFileWizard
public:
GenericProjectWizard();
- Core::FeatureSet requiredFeatures() const;
-
- static Core::BaseFileWizardParameters parameters();
protected:
QWizard *createWizardDialog(QWidget *parent,
diff --git a/src/plugins/genericprojectmanager/pkgconfigtool.cpp b/src/plugins/genericprojectmanager/pkgconfigtool.cpp
index a2f8b3b924..127d82d473 100644
--- a/src/plugins/genericprojectmanager/pkgconfigtool.cpp
+++ b/src/plugins/genericprojectmanager/pkgconfigtool.cpp
@@ -90,9 +90,7 @@ void PkgConfigTool::packages_helper() const
if (ch.isSpace()) {
do { ++index; }
while (index < cflags.size() && cflags.at(index).isSpace());
- }
-
- else if (ch == QLatin1Char('-') && index + 1 < cflags.size()) {
+ } else if (ch == QLatin1Char('-') && index + 1 < cflags.size()) {
++index;
const QChar opt = cflags.at(index);
@@ -109,9 +107,7 @@ void PkgConfigTool::packages_helper() const
qDebug() << "*** add include path:" << cflags.mid(start, index - start);
package.includePaths.append(cflags.mid(start, index - start));
}
- }
-
- else {
+ } else {
for (; index < cflags.size(); ++index) {
if (cflags.at(index).isSpace())
break;
diff --git a/src/plugins/genericprojectmanager/selectablefilesmodel.cpp b/src/plugins/genericprojectmanager/selectablefilesmodel.cpp
index 6ce393d47a..60deb9da16 100644
--- a/src/plugins/genericprojectmanager/selectablefilesmodel.cpp
+++ b/src/plugins/genericprojectmanager/selectablefilesmodel.cpp
@@ -257,7 +257,7 @@ QVariant SelectableFilesModel::data(const QModelIndex &index, int role) const
return t->checked;
if (role == Qt::DecorationRole) {
if (t->icon.isNull())
- t->icon = Core::FileIconProvider::instance()->icon(QFileInfo(t->fullPath));
+ t->icon = Core::FileIconProvider::icon(t->fullPath);
return t->icon;
}
return QVariant();
diff --git a/src/plugins/git/Git.pluginspec.in b/src/plugins/git/Git.pluginspec.in
index b5a2c03495..b68684dd81 100644
--- a/src/plugins/git/Git.pluginspec.in
+++ b/src/plugins/git/Git.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"Git\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"Git\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/git/annotationhighlighter.cpp b/src/plugins/git/annotationhighlighter.cpp
index 9b19420eb4..4e91ca0882 100644
--- a/src/plugins/git/annotationhighlighter.cpp
+++ b/src/plugins/git/annotationhighlighter.cpp
@@ -35,9 +35,8 @@ namespace Git {
namespace Internal {
GitAnnotationHighlighter::GitAnnotationHighlighter(const ChangeNumbers &changeNumbers,
- const QColor &bg,
QTextDocument *document) :
- VcsBase::BaseAnnotationHighlighter(changeNumbers, bg, document),
+ VcsBase::BaseAnnotationHighlighter(changeNumbers, document),
m_blank(QLatin1Char(' '))
{
}
diff --git a/src/plugins/git/annotationhighlighter.h b/src/plugins/git/annotationhighlighter.h
index 6c2539b6fb..73f5985126 100644
--- a/src/plugins/git/annotationhighlighter.h
+++ b/src/plugins/git/annotationhighlighter.h
@@ -40,7 +40,7 @@ class GitAnnotationHighlighter : public VcsBase::BaseAnnotationHighlighter
{
Q_OBJECT
public:
- explicit GitAnnotationHighlighter(const ChangeNumbers &changeNumbers, const QColor &bg,
+ explicit GitAnnotationHighlighter(const ChangeNumbers &changeNumbers,
QTextDocument *document = 0);
private:
diff --git a/src/plugins/git/branchdialog.cpp b/src/plugins/git/branchdialog.cpp
index 2e299511e3..fa5321f479 100644
--- a/src/plugins/git/branchdialog.cpp
+++ b/src/plugins/git/branchdialog.cpp
@@ -69,6 +69,8 @@ BranchDialog::BranchDialog(QWidget *parent) :
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()));
+ connect(m_ui->cherryPickButton, SIGNAL(clicked()), this, SLOT(cherryPick()));
+ connect(m_ui->trackButton, SIGNAL(clicked()), this, SLOT(setRemoteTracking()));
m_ui->branchView->setModel(m_model);
@@ -106,18 +108,24 @@ void BranchDialog::refreshIfSame(const QString &repository)
void BranchDialog::enableButtons()
{
QModelIndex idx = selectedIndex();
+ QModelIndex currentBranch = m_model->currentBranch();
const bool hasSelection = idx.isValid();
- const bool currentSelected = hasSelection && idx == m_model->currentBranch();
+ const bool currentSelected = hasSelection && idx == currentBranch;
const bool isLocal = m_model->isLocal(idx);
const bool isLeaf = m_model->isLeaf(idx);
-
- m_ui->removeButton->setEnabled(hasSelection && !currentSelected && isLocal && isLeaf);
- m_ui->renameButton->setEnabled(hasSelection && 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);
- m_ui->mergeButton->setEnabled(hasSelection && !currentSelected && isLeaf);
+ const bool isTag = m_model->isTag(idx);
+ const bool hasActions = hasSelection && isLeaf;
+ const bool currentLocal = m_model->isLocal(currentBranch);
+
+ m_ui->removeButton->setEnabled(hasActions && !currentSelected && (isLocal || isTag));
+ m_ui->renameButton->setEnabled(hasActions && (isLocal || isTag));
+ m_ui->logButton->setEnabled(hasActions);
+ m_ui->diffButton->setEnabled(hasActions);
+ m_ui->checkoutButton->setEnabled(hasActions && !currentSelected);
+ m_ui->rebaseButton->setEnabled(hasActions && !currentSelected);
+ m_ui->mergeButton->setEnabled(hasActions && !currentSelected);
+ m_ui->cherryPickButton->setEnabled(hasActions && !currentSelected);
+ m_ui->trackButton->setEnabled(hasActions && currentLocal && !currentSelected && !isTag);
}
void BranchDialog::refresh()
@@ -128,10 +136,10 @@ void BranchDialog::refresh()
void BranchDialog::add()
{
QModelIndex trackedIndex = selectedIndex();
- QString trackedBranch = m_model->branchName(trackedIndex);
+ QString trackedBranch = m_model->fullName(trackedIndex);
if (trackedBranch.isEmpty()) {
trackedIndex = m_model->currentBranch();
- trackedBranch = m_model->branchName(trackedIndex);
+ trackedBranch = m_model->fullName(trackedIndex);
}
const bool isLocal = m_model->isLocal(trackedIndex);
const bool isTag = m_model->isTag(trackedIndex);
@@ -152,6 +160,8 @@ void BranchDialog::add()
if (branchAddDialog.exec() == QDialog::Accepted && m_model) {
QModelIndex idx = m_model->addBranch(branchAddDialog.branchName(), branchAddDialog.track(), trackedIndex);
+ if (!idx.isValid())
+ return;
m_ui->branchView->selectionModel()->select(idx, QItemSelectionModel::Clear
| QItemSelectionModel::Select
| QItemSelectionModel::Current);
@@ -166,8 +176,8 @@ void BranchDialog::checkout()
{
QModelIndex idx = selectedIndex();
- const QString currentBranch = m_model->branchName(m_model->currentBranch());
- const QString nextBranch = m_model->branchName(idx);
+ const QString currentBranch = m_model->fullName(m_model->currentBranch());
+ const QString nextBranch = m_model->fullName(idx);
const QString popMessageStart = QCoreApplication::applicationName() +
QLatin1String(" ") + nextBranch + QLatin1String("-AutoStash ");
@@ -230,37 +240,52 @@ void BranchDialog::remove()
QModelIndex selected = selectedIndex();
QTC_CHECK(selected != m_model->currentBranch()); // otherwise the button would not be enabled!
- QString branchName = m_model->branchName(selected);
+ QString branchName = m_model->fullName(selected);
if (branchName.isEmpty())
return;
- QString message = tr("Would you like to delete the branch '%1'?").arg(branchName);
- bool wasMerged = m_model->branchIsMerged(selected);
- if (!wasMerged)
+ const bool isTag = m_model->isTag(selected);
+ const bool wasMerged = isTag ? true : m_model->branchIsMerged(selected);
+ QString message;
+ if (isTag)
+ message = tr("Would you like to delete the tag '%1'?").arg(branchName);
+ else if (wasMerged)
+ message = tr("Would you like to delete the branch '%1'?").arg(branchName);
+ else
message = tr("Would you like to delete the <b>unmerged</b> branch '%1'?").arg(branchName);
- if (QMessageBox::question(this, tr("Delete Branch"), message, QMessageBox::Yes|QMessageBox::No,
- wasMerged ? QMessageBox::Yes : QMessageBox::No) == QMessageBox::Yes)
- m_model->removeBranch(selected);
+ if (QMessageBox::question(this, isTag ? tr("Delete Tag") : tr("Delete Branch"),
+ message, QMessageBox::Yes | QMessageBox::No,
+ wasMerged ? QMessageBox::Yes : QMessageBox::No) == QMessageBox::Yes) {
+ if (isTag)
+ m_model->removeTag(selected);
+ else
+ m_model->removeBranch(selected);
+ }
}
void BranchDialog::rename()
{
QModelIndex selected = selectedIndex();
QTC_CHECK(selected != m_model->currentBranch()); // otherwise the button would not be enabled!
- QTC_CHECK(m_model->isLocal(selected)); // otherwise the button would not be enabled!
+ const bool isTag = m_model->isTag(selected);
+ QTC_CHECK(m_model->isLocal(selected) || isTag);
- QString oldBranchName = m_model->branchName(selected);
- QStringList localNames = m_model->localBranchNames();
+ QString oldName = m_model->fullName(selected);
+ QStringList localNames;
+ if (!isTag)
+ localNames = m_model->localBranchNames();
BranchAddDialog branchAddDialog(false, this);
- branchAddDialog.setBranchName(oldBranchName);
+ if (isTag)
+ branchAddDialog.setWindowTitle(tr("Rename Tag"));
+ branchAddDialog.setBranchName(oldName);
branchAddDialog.setTrackedBranchName(QString(), false);
branchAddDialog.exec();
if (branchAddDialog.result() == QDialog::Accepted && m_model) {
- if (branchAddDialog.branchName() == oldBranchName)
+ if (branchAddDialog.branchName() == oldName)
return;
if (localNames.contains(branchAddDialog.branchName())) {
QMessageBox::critical(this, tr("Branch Exists"),
@@ -268,7 +293,10 @@ void BranchDialog::rename()
.arg(branchAddDialog.branchName()));
return;
}
- m_model->renameBranch(oldBranchName, branchAddDialog.branchName());
+ if (isTag)
+ m_model->renameTag(oldName, branchAddDialog.branchName());
+ else
+ m_model->renameBranch(oldName, branchAddDialog.branchName());
refresh();
}
enableButtons();
@@ -276,20 +304,20 @@ void BranchDialog::rename()
void BranchDialog::diff()
{
- QString branchName = m_model->branchName(selectedIndex());
- if (branchName.isEmpty())
+ QString fullName = m_model->fullName(selectedIndex(), true);
+ if (fullName.isEmpty())
return;
// Do not pass working dir by reference since it might change
- GitPlugin::instance()->gitClient()->diffBranch(QString(m_repository), QStringList(), branchName);
+ GitPlugin::instance()->gitClient()->diffBranch(QString(m_repository), QStringList(), fullName);
}
void BranchDialog::log()
{
- QString branchName = m_model->branchName(selectedIndex());
+ QString branchName = m_model->fullName(selectedIndex(), true);
if (branchName.isEmpty())
return;
// Do not pass working dir by reference since it might change
- GitPlugin::instance()->gitClient()->log(QString(m_repository), QStringList(), false, QStringList(branchName));
+ GitPlugin::instance()->gitClient()->log(QString(m_repository), QString(), false, QStringList(branchName));
}
void BranchDialog::merge()
@@ -297,7 +325,7 @@ void BranchDialog::merge()
QModelIndex idx = selectedIndex();
QTC_CHECK(idx != m_model->currentBranch()); // otherwise the button would not be enabled!
- const QString branch = m_model->branchName(idx);
+ const QString branch = m_model->fullName(idx, true);
GitClient *client = GitPlugin::instance()->gitClient();
if (client->beginStashScope(m_repository, QLatin1String("merge"), AllowUnstashed))
client->synchronousMerge(m_repository, branch);
@@ -308,12 +336,26 @@ void BranchDialog::rebase()
QModelIndex idx = selectedIndex();
QTC_CHECK(idx != m_model->currentBranch()); // otherwise the button would not be enabled!
- const QString baseBranch = m_model->branchName(idx);
+ const QString baseBranch = m_model->fullName(idx, true);
GitClient *client = GitPlugin::instance()->gitClient();
if (client->beginStashScope(m_repository, QLatin1String("rebase")))
client->rebase(m_repository, baseBranch);
}
+void BranchDialog::cherryPick()
+{
+ QModelIndex idx = selectedIndex();
+ QTC_CHECK(idx != m_model->currentBranch()); // otherwise the button would not be enabled!
+
+ const QString branch = m_model->fullName(idx, true);
+ GitPlugin::instance()->gitClient()->synchronousCherryPick(m_repository, branch);
+}
+
+void BranchDialog::setRemoteTracking()
+{
+ m_model->setRemoteTracking(selectedIndex());
+}
+
QModelIndex BranchDialog::selectedIndex()
{
QModelIndexList selected = m_ui->branchView->selectionModel()->selectedIndexes();
diff --git a/src/plugins/git/branchdialog.h b/src/plugins/git/branchdialog.h
index aac316d1c8..3343becfa9 100644
--- a/src/plugins/git/branchdialog.h
+++ b/src/plugins/git/branchdialog.h
@@ -74,6 +74,8 @@ private slots:
void log();
void merge();
void rebase();
+ void cherryPick();
+ void setRemoteTracking();
private:
QModelIndex selectedIndex();
diff --git a/src/plugins/git/branchdialog.ui b/src/plugins/git/branchdialog.ui
index e23889a342..11adc4cb4a 100644
--- a/src/plugins/git/branchdialog.ui
+++ b/src/plugins/git/branchdialog.ui
@@ -154,6 +154,26 @@
</layout>
</item>
<item>
+ <widget class="QPushButton" name="cherryPickButton">
+ <property name="toolTip">
+ <string>Cherry Pick top commit from selected branch</string>
+ </property>
+ <property name="text">
+ <string>Cherry Pick</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="trackButton">
+ <property name="toolTip">
+ <string>Sets current branch to track the selected one</string>
+ </property>
+ <property name="text">
+ <string>&amp;Track</string>
+ </property>
+ </widget>
+ </item>
+ <item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
diff --git a/src/plugins/git/branchmodel.cpp b/src/plugins/git/branchmodel.cpp
index 791b7b9606..ee961b6371 100644
--- a/src/plugins/git/branchmodel.cpp
+++ b/src/plugins/git/branchmodel.cpp
@@ -38,6 +38,12 @@
namespace Git {
namespace Internal {
+enum RootNodes {
+ LocalBranches = 0,
+ RemoteBranches = 1,
+ Tags = 2
+};
+
// --------------------------------------------------------------------------
// BranchNode:
// --------------------------------------------------------------------------
@@ -77,18 +83,6 @@ public:
return children.isEmpty() && parent && parent->parent;
}
- bool isTag() const
- {
- if (!parent)
- return false;
- for (const BranchNode *p = this; p->parent; p = p->parent) {
- // find root child with name "tags"
- if (!p->parent->parent && p->name == QLatin1String("tags"))
- return true;
- }
- return false;
- }
-
bool childOf(BranchNode *node) const
{
if (this == node)
@@ -96,12 +90,24 @@ public:
return parent ? parent->childOf(node) : false;
}
- bool isLocal() const
+ bool childOfRoot(RootNodes root) const
{
BranchNode *rn = rootNode();
if (rn->isLeaf())
return false;
- return childOf(rn->children.at(0));
+ if (root >= rn->children.count())
+ return false;
+ return childOf(rn->children.at(root));
+ }
+
+ bool isTag() const
+ {
+ return childOfRoot(Tags);
+ }
+
+ bool isLocal() const
+ {
+ return childOfRoot(LocalBranches);
}
BranchNode *childOfName(const QString &name) const
@@ -113,7 +119,7 @@ public:
return 0;
}
- QStringList fullName() const
+ QStringList fullName(bool includePrefix = false) const
{
QTC_ASSERT(isLeaf(), return QStringList());
@@ -125,8 +131,9 @@ public:
current = current->parent;
}
- if (current->children.at(0) == nodes.at(0))
- nodes.removeFirst(); // remove local branch designation
+ if (includePrefix)
+ fn.append(nodes.first()->sha);
+ nodes.removeFirst();
foreach (const BranchNode *n, nodes)
fn.append(n->name);
@@ -191,7 +198,10 @@ BranchModel::BranchModel(GitClient *client, QObject *parent) :
m_currentBranch(0)
{
QTC_CHECK(m_client);
- m_rootNode->append(new BranchNode(tr("Local Branches")));
+
+ // Abuse the sha field for ref prefix
+ m_rootNode->append(new BranchNode(tr("Local Branches"), QLatin1String("refs/heads")));
+ m_rootNode->append(new BranchNode(tr("Remote Branches"), QLatin1String("refs/remotes")));
}
BranchModel::~BranchModel()
@@ -320,11 +330,11 @@ Qt::ItemFlags BranchModel::flags(const QModelIndex &index) const
void BranchModel::clear()
{
- while (m_rootNode->count() > 1)
- delete m_rootNode->children.takeLast();
- BranchNode *locals = m_rootNode->children.at(0);
- while (locals->count())
- delete locals->children.takeLast();
+ foreach (BranchNode *root, m_rootNode->children)
+ while (root->count())
+ delete root->children.takeLast();
+ if (hasTags())
+ m_rootNode->children.takeLast();
m_currentBranch = 0;
}
@@ -351,7 +361,7 @@ bool BranchModel::refresh(const QString &workingDirectory, QString *errorMessage
parseOutputLine(l);
if (m_currentBranch) {
- if (m_currentBranch->parent == m_rootNode->children[0])
+ if (m_currentBranch->parent == m_rootNode->children.at(LocalBranches))
m_currentBranch = 0;
setCurrentBranch();
}
@@ -367,7 +377,7 @@ void BranchModel::setCurrentBranch()
if (currentBranch.isEmpty())
return;
- BranchNode *local = m_rootNode->children.at(0);
+ BranchNode *local = m_rootNode->children.at(LocalBranches);
int pos = 0;
for (pos = 0; pos < local->count(); ++pos) {
if (local->children.at(pos)->name == currentBranch) {
@@ -388,6 +398,21 @@ void BranchModel::renameBranch(const QString &oldName, const QString &newName)
refresh(m_workingDirectory, &errorMessage);
}
+void BranchModel::renameTag(const QString &oldName, const QString &newName)
+{
+ QString errorMessage;
+ QString output;
+ if (!m_client->synchronousTagCmd(m_workingDirectory, QStringList() << newName << oldName,
+ &output, &errorMessage)
+ || !m_client->synchronousTagCmd(m_workingDirectory,
+ QStringList() << QLatin1String("-d") << oldName,
+ &output, &errorMessage)) {
+ VcsBase::VcsBaseOutputWindow::instance()->appendError(errorMessage);
+ } else {
+ refresh(m_workingDirectory, &errorMessage);
+ }
+}
+
QString BranchModel::workingDirectory() const
{
return m_workingDirectory;
@@ -405,23 +430,23 @@ QModelIndex BranchModel::currentBranch() const
return nodeToIndex(m_currentBranch);
}
-QString BranchModel::branchName(const QModelIndex &idx) const
+QString BranchModel::fullName(const QModelIndex &idx, bool includePrefix) const
{
if (!idx.isValid())
return QString();
BranchNode *node = indexToNode(idx);
if (!node || !node->isLeaf())
return QString();
- QStringList path = node->fullName();
+ QStringList path = node->fullName(includePrefix);
return path.join(QString(QLatin1Char('/')));
}
QStringList BranchModel::localBranchNames() const
{
- if (!m_rootNode || m_rootNode->children.isEmpty())
+ if (!m_rootNode || !m_rootNode->count())
return QStringList();
- return m_rootNode->children.at(0)->childrenNames();
+ return m_rootNode->children.at(LocalBranches)->childrenNames();
}
QString BranchModel::sha(const QModelIndex &idx) const
@@ -432,6 +457,11 @@ QString BranchModel::sha(const QModelIndex &idx) const
return node->sha;
}
+bool BranchModel::hasTags() const
+{
+ return m_rootNode->children.count() > Tags;
+}
+
bool BranchModel::isLocal(const QModelIndex &idx) const
{
if (!idx.isValid())
@@ -450,14 +480,14 @@ bool BranchModel::isLeaf(const QModelIndex &idx) const
bool BranchModel::isTag(const QModelIndex &idx) const
{
- if (!idx.isValid())
+ if (!idx.isValid() || !hasTags())
return false;
return indexToNode(idx)->isTag();
}
void BranchModel::removeBranch(const QModelIndex &idx)
{
- QString branch = branchName(idx);
+ QString branch = fullName(idx);
if (branch.isEmpty())
return;
@@ -470,21 +500,30 @@ void BranchModel::removeBranch(const QModelIndex &idx)
VcsBase::VcsBaseOutputWindow::instance()->appendError(errorMessage);
return;
}
+ removeNode(idx);
+}
- 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::removeTag(const QModelIndex &idx)
+{
+ QString tag = fullName(idx);
+ if (tag.isEmpty())
+ return;
+
+ QString errorMessage;
+ QString output;
+ QStringList args;
+
+ args << QLatin1String("-d") << tag;
+ if (!m_client->synchronousTagCmd(m_workingDirectory, args, &output, &errorMessage)) {
+ VcsBase::VcsBaseOutputWindow::instance()->appendError(errorMessage);
+ return;
}
+ removeNode(idx);
}
void BranchModel::checkoutBranch(const QModelIndex &idx)
{
- QString branch = branchName(idx);
+ QString branch = fullName(idx, !isLocal(idx));
if (branch.isEmpty())
return;
@@ -495,7 +534,7 @@ void BranchModel::checkoutBranch(const QModelIndex &idx)
bool BranchModel::branchIsMerged(const QModelIndex &idx)
{
- QString branch = branchName(idx);
+ QString branch = fullName(idx);
if (branch.isEmpty())
return false;
@@ -533,22 +572,23 @@ QModelIndex BranchModel::addBranch(const QString &name, bool track, const QModel
if (!m_rootNode || !m_rootNode->count())
return QModelIndex();
- const QString trackedBranch = branchName(startPoint);
+ const QString trackedBranch = fullName(startPoint);
+ const QString fullTrackedBranch = fullName(startPoint, true);
QString output;
QString errorMessage;
QStringList args;
args << (track ? QLatin1String("--track") : QLatin1String("--no-track"));
args << name;
- if (!trackedBranch.isEmpty())
- args << trackedBranch;
+ if (!fullTrackedBranch.isEmpty())
+ args << fullTrackedBranch;
if (!m_client->synchronousBranchCmd(m_workingDirectory, args, &output, &errorMessage)) {
VcsBase::VcsBaseOutputWindow::instance()->appendError(errorMessage);
return QModelIndex();
}
- BranchNode *local = m_rootNode->children.at(0);
+ BranchNode *local = m_rootNode->children.at(LocalBranches);
const int slash = name.indexOf(QLatin1Char('/'));
const QString leafName = slash == -1 ? name : name.mid(slash + 1);
bool added = false;
@@ -575,6 +615,18 @@ QModelIndex BranchModel::addBranch(const QString &name, bool track, const QModel
return nodeToIndex(newNode);
}
+void BranchModel::setRemoteTracking(const QModelIndex &trackingIndex)
+{
+ QModelIndex current = currentBranch();
+ QTC_ASSERT(current.isValid(), return);
+ const QString currentName = fullName(current);
+ const QString shortTracking = fullName(trackingIndex);
+ const QString tracking = fullName(trackingIndex, true);
+ m_client->synchronousSetTrackingBranch(m_workingDirectory, currentName, tracking);
+ m_currentBranch->tracking = shortTracking;
+ emit dataChanged(current, current);
+}
+
void BranchModel::parseOutputLine(const QString &line)
{
if (line.size() < 3)
@@ -592,14 +644,20 @@ void BranchModel::parseOutputLine(const QString &line)
QStringList nameParts = fullName.split(QLatin1Char('/'));
nameParts.removeFirst(); // remove refs...
- if (nameParts.first() == QLatin1String("heads"))
- nameParts[0] = m_rootNode->children.at(0)->name; // Insert the local designator
- else if (nameParts.first() == QLatin1String("remotes"))
- nameParts.removeFirst(); // remove "remotes"
- else if (nameParts.first() == QLatin1String("stash"))
- return;
- else if (!showTags && (nameParts.first() == QLatin1String("tags")))
+ BranchNode *root = 0;
+ if (nameParts.first() == QLatin1String("heads")) {
+ root = m_rootNode->children.at(LocalBranches);
+ } else if (nameParts.first() == QLatin1String("remotes")) {
+ root = m_rootNode->children.at(RemoteBranches);
+ } else if (showTags && nameParts.first() == QLatin1String("tags")) {
+ if (!hasTags()) // Tags is missing, add it
+ m_rootNode->append(new BranchNode(tr("Tags"), QLatin1String("refs/tags")));
+ root = m_rootNode->children.at(Tags);
+ } else {
return;
+ }
+
+ nameParts.removeFirst();
// limit depth of list. Git basically only ever wants one / and considers the rest as part of
// the name.
@@ -612,7 +670,7 @@ void BranchModel::parseOutputLine(const QString &line)
nameParts.removeLast();
BranchNode *newNode = new BranchNode(name, sha, lineParts.at(2));
- m_rootNode->insert(nameParts, newNode);
+ root->insert(nameParts, newNode);
if (current)
m_currentBranch = newNode;
}
@@ -633,6 +691,19 @@ QModelIndex BranchModel::nodeToIndex(BranchNode *node) const
return createIndex(node->parent->rowOf(node), 0, static_cast<void *>(node));
}
+void BranchModel::removeNode(const QModelIndex &idx)
+{
+ 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;
+ }
+}
+
QString BranchModel::toolTip(const QString &sha) const
{
// Show the sha description excluding diff as toolTip
diff --git a/src/plugins/git/branchmodel.h b/src/plugins/git/branchmodel.h
index 1be003dab2..f110944105 100644
--- a/src/plugins/git/branchmodel.h
+++ b/src/plugins/git/branchmodel.h
@@ -64,28 +64,33 @@ public:
bool refresh(const QString &workingDirectory, QString *errorMessage);
void renameBranch(const QString &oldName, const QString &newName);
+ void renameTag(const QString &oldName, const QString &newName);
QString workingDirectory() const;
GitClient *client() const;
QModelIndex currentBranch() const;
- QString branchName(const QModelIndex &idx) const;
+ QString fullName(const QModelIndex &idx, bool includePrefix = false) const;
QStringList localBranchNames() const;
QString sha(const QModelIndex &idx) const;
+ bool hasTags() const;
bool isLocal(const QModelIndex &idx) const;
bool isLeaf(const QModelIndex &idx) const;
bool isTag(const QModelIndex &idx) const;
void removeBranch(const QModelIndex &idx);
+ void removeTag(const QModelIndex &idx);
void checkoutBranch(const QModelIndex &idx);
bool branchIsMerged(const QModelIndex &idx);
QModelIndex addBranch(const QString &name, bool track, const QModelIndex &trackedBranch);
+ void setRemoteTracking(const QModelIndex &trackingIndex);
private:
void parseOutputLine(const QString &line);
void setCurrentBranch();
BranchNode *indexToNode(const QModelIndex &index) const;
QModelIndex nodeToIndex(BranchNode *node) const;
+ void removeNode(const QModelIndex &idx);
QString toolTip(const QString &sha) const;
diff --git a/src/plugins/git/changeselectiondialog.cpp b/src/plugins/git/changeselectiondialog.cpp
index cc5dc40b22..8dc3dba6c6 100644
--- a/src/plugins/git/changeselectiondialog.cpp
+++ b/src/plugins/git/changeselectiondialog.cpp
@@ -45,7 +45,7 @@
namespace Git {
namespace Internal {
-ChangeSelectionDialog::ChangeSelectionDialog(const QString &workingDirectory, QWidget *parent)
+ChangeSelectionDialog::ChangeSelectionDialog(const QString &workingDirectory, Core::Id id, QWidget *parent)
: QDialog(parent)
, m_process(0)
, m_workingDirEdit(new QLineEdit(workingDirectory, this))
@@ -107,6 +107,15 @@ ChangeSelectionDialog::ChangeSelectionDialog(const QString &workingDirectory, QW
connect(m_checkoutButton, SIGNAL(clicked()), this, SLOT(acceptCheckout()));
connect(m_closeButton, SIGNAL(clicked()), this, SLOT(reject()));
+ QByteArray idName = id.name();
+ if (idName == "Git.Revert")
+ m_revertButton->setDefault(true);
+ else if (idName == "Git.CherryPick")
+ m_cherryPickButton->setDefault(true);
+ else if (idName == "Git.Checkout")
+ m_checkoutButton->setDefault(true);
+ else
+ m_showButton->setDefault(true);
recalculateDetails();
}
diff --git a/src/plugins/git/changeselectiondialog.h b/src/plugins/git/changeselectiondialog.h
index e850570369..9035ec7c19 100644
--- a/src/plugins/git/changeselectiondialog.h
+++ b/src/plugins/git/changeselectiondialog.h
@@ -30,6 +30,8 @@
#ifndef CHANGESELECTIONDIALOG_H
#define CHANGESELECTIONDIALOG_H
+#include <coreplugin/id.h>
+
#include <QDialog>
#include <QProcessEnvironment>
@@ -56,7 +58,7 @@ class ChangeSelectionDialog : public QDialog
{
Q_OBJECT
public:
- ChangeSelectionDialog(const QString &workingDirectory, QWidget *parent);
+ ChangeSelectionDialog(const QString &workingDirectory, Core::Id id, QWidget *parent);
~ChangeSelectionDialog();
QString change() const;
diff --git a/src/plugins/git/clonewizard.cpp b/src/plugins/git/clonewizard.cpp
index d3f99c68c2..a222ef48dc 100644
--- a/src/plugins/git/clonewizard.cpp
+++ b/src/plugins/git/clonewizard.cpp
@@ -33,35 +33,20 @@
#include "gitplugin.h"
#include "gitversioncontrol.h"
-#include <vcsbase/checkoutjobs.h>
#include <vcsbase/vcsbaseconstants.h>
#include <vcsbase/vcsconfigurationpage.h>
#include <utils/qtcassert.h>
-#include <QIcon>
-
namespace Git {
namespace Internal {
-CloneWizard::CloneWizard(QObject *parent) :
- VcsBase::BaseCheckoutWizard(parent)
+CloneWizard::CloneWizard()
{
setId(QLatin1String(VcsBase::Constants::VCS_ID_GIT));
-}
-
-QIcon CloneWizard::icon() const
-{
- return QIcon(QLatin1String(":/git/images/git.png"));
-}
-
-QString CloneWizard::description() const
-{
- return tr("Clones a Git repository and tries to load the contained project.");
-}
-
-QString CloneWizard::displayName() const
-{
- return tr("Git Repository Clone");
+ setCustomLabels(tr("Cloning"), tr("Cloning started..."));
+ setIcon(QIcon(QLatin1String(":/git/images/git.png")));
+ setDescription(tr("Clones a Git repository and tries to load the contained project."));
+ setDisplayName(tr("Git Repository Clone"));
}
QList<QWizardPage*> CloneWizard::createParameterPages(const QString &path)
@@ -76,8 +61,8 @@ QList<QWizardPage*> CloneWizard::createParameterPages(const QString &path)
return rc;
}
-QSharedPointer<VcsBase::AbstractCheckoutJob> CloneWizard::createJob(const QList<QWizardPage*> &parameterPages,
- QString *checkoutPath)
+VcsBase::Command *CloneWizard::createCommand(const QList<QWizardPage*> &parameterPages,
+ QString *checkoutPath)
{
// Collect parameters for the clone command.
const CloneWizardPage *cwp = 0;
@@ -87,7 +72,7 @@ QSharedPointer<VcsBase::AbstractCheckoutJob> CloneWizard::createJob(const QList<
break;
}
- QTC_ASSERT(cwp, return QSharedPointer<VcsBase::AbstractCheckoutJob>());
+ QTC_ASSERT(cwp, return 0);
return cwp->createCheckoutJob(checkoutPath);
}
diff --git a/src/plugins/git/clonewizard.h b/src/plugins/git/clonewizard.h
index f0c5af8adf..676a132a3e 100644
--- a/src/plugins/git/clonewizard.h
+++ b/src/plugins/git/clonewizard.h
@@ -38,19 +38,15 @@ namespace Internal {
class CloneWizard : public VcsBase::BaseCheckoutWizard
{
Q_OBJECT
-public:
- explicit CloneWizard(QObject *parent = 0);
- // IWizard
- QIcon icon() const;
- QString description() const;
- QString displayName() const;
+public:
+ CloneWizard();
-protected:
+private:
// BaseCheckoutWizard
QList<QWizardPage*> createParameterPages(const QString &path);
- QSharedPointer<VcsBase::AbstractCheckoutJob> createJob(const QList<QWizardPage*> &parameterPages,
- QString *checkoutPath);
+ VcsBase::Command *createCommand(const QList<QWizardPage*> &parameterPages,
+ QString *checkoutPath);
};
} // namespace Internal
diff --git a/src/plugins/git/clonewizardpage.cpp b/src/plugins/git/clonewizardpage.cpp
index 1ea045141e..adebffb75d 100644
--- a/src/plugins/git/clonewizardpage.cpp
+++ b/src/plugins/git/clonewizardpage.cpp
@@ -31,7 +31,9 @@
#include "gitplugin.h"
#include "gitclient.h"
-#include <vcsbase/checkoutjobs.h>
+#include <vcsbase/command.h>
+
+#include <QCheckBox>
namespace Git {
@@ -43,12 +45,14 @@ struct CloneWizardPagePrivate {
const QString mainLinePostfix;
const QString gitPostFix;
const QString protocolDelimiter;
+ QCheckBox *recursiveCheckBox;
};
CloneWizardPagePrivate::CloneWizardPagePrivate() :
mainLinePostfix(QLatin1String("/mainline.git")),
gitPostFix(QLatin1String(".git")),
- protocolDelimiter(QLatin1String("://"))
+ protocolDelimiter(QLatin1String("://")),
+ recursiveCheckBox(0)
{
}
@@ -68,6 +72,8 @@ CloneWizardPage::CloneWizardPage(QWidget *parent) :
setTitle(tr("Location"));
setSubTitle(tr("Specify repository URL, checkout directory and path."));
setRepositoryLabel(tr("Clone URL:"));
+ d->recursiveCheckBox = new QCheckBox(tr("Recursive"));
+ addLocalControl(d->recursiveCheckBox);
}
CloneWizardPage::~CloneWizardPage()
@@ -112,25 +118,26 @@ QString CloneWizardPage::directoryFromRepository(const QString &urlIn) const
return url;
}
-QSharedPointer<VcsBase::AbstractCheckoutJob> CloneWizardPage::createCheckoutJob(QString *checkoutPath) const
+VcsBase::Command *CloneWizardPage::createCheckoutJob(QString *checkoutPath) const
{
const Internal::GitClient *client = Internal::GitPlugin::instance()->gitClient();
const QString workingDirectory = path();
const QString checkoutDir = directory();
*checkoutPath = workingDirectory + QLatin1Char('/') + checkoutDir;
- const QString binary = client->gitBinaryPath();
-
- VcsBase::ProcessCheckoutJob *job = new VcsBase::ProcessCheckoutJob;
- const QProcessEnvironment env = client->processEnvironment();
const QString checkoutBranch = branch();
QStringList args(QLatin1String("clone"));
if (!checkoutBranch.isEmpty())
args << QLatin1String("--branch") << checkoutBranch;
- args << repository() << checkoutDir;
- job->addStep(binary, args, workingDirectory, env);
- return QSharedPointer<VcsBase::AbstractCheckoutJob>(job);
+ if (d->recursiveCheckBox->isChecked())
+ args << QLatin1String("--recursive");
+ args << QLatin1String("--progress") << repository() << checkoutDir;
+ VcsBase::Command *command = new VcsBase::Command(client->gitBinaryPath(), workingDirectory,
+ client->processEnvironment());
+ command->addFlags(VcsBase::VcsBasePlugin::MergeOutputChannels);
+ command->addJob(args, -1);
+ return command;
}
QStringList CloneWizardPage::branches(const QString &repository, int *current)
diff --git a/src/plugins/git/clonewizardpage.h b/src/plugins/git/clonewizardpage.h
index 1b7eb1ef2b..ab69df8090 100644
--- a/src/plugins/git/clonewizardpage.h
+++ b/src/plugins/git/clonewizardpage.h
@@ -35,7 +35,7 @@
#include <QSharedPointer>
namespace VcsBase {
- class AbstractCheckoutJob;
+ class Command;
}
namespace Git {
@@ -50,7 +50,7 @@ public:
explicit CloneWizardPage(QWidget *parent = 0);
~CloneWizardPage();
- QSharedPointer<VcsBase::AbstractCheckoutJob> createCheckoutJob(QString *checkoutPath) const;
+ VcsBase::Command *createCheckoutJob(QString *checkoutPath) const;
protected:
QString directoryFromRepository(const QString &r) const;
diff --git a/src/plugins/git/commitdata.cpp b/src/plugins/git/commitdata.cpp
index d17cf89d1c..129e256d9f 100644
--- a/src/plugins/git/commitdata.cpp
+++ b/src/plugins/git/commitdata.cpp
@@ -53,6 +53,8 @@ void GitSubmitEditorPanelData::clear()
author.clear();
email.clear();
bypassHooks = false;
+ pushAction = CommitOnly;
+ hasRemotes = false;
}
QString GitSubmitEditorPanelData::authorString() const
@@ -72,7 +74,8 @@ QString GitSubmitEditorPanelData::authorString() const
QDebug operator<<(QDebug d, const GitSubmitEditorPanelData &data)
{
d.nospace() << " author:" << data.author << " email: " << data.email
- << " bypass hooks: " << data.bypassHooks;
+ << " bypass hooks: " << data.bypassHooks
+ << " action after commit " << data.pushAction;
return d;
}
diff --git a/src/plugins/git/commitdata.h b/src/plugins/git/commitdata.h
index 6688843dd5..824f9dfe5d 100644
--- a/src/plugins/git/commitdata.h
+++ b/src/plugins/git/commitdata.h
@@ -52,6 +52,12 @@ struct GitSubmitEditorPanelInfo
QDebug operator<<(QDebug d, const GitSubmitEditorPanelInfo &);
+enum PushAction {
+ CommitOnly,
+ CommitAndPush,
+ CommitAndPushToGerrit
+};
+
struct GitSubmitEditorPanelData
{
void clear();
@@ -61,6 +67,8 @@ struct GitSubmitEditorPanelData
QString author;
QString email;
bool bypassHooks;
+ PushAction pushAction;
+ bool hasRemotes;
};
QDebug operator<<(QDebug d, const GitSubmitEditorPanelData &);
diff --git a/src/plugins/git/gerrit/gerrit.pri b/src/plugins/git/gerrit/gerrit.pri
index b06518ec5b..617cd941bf 100644
--- a/src/plugins/git/gerrit/gerrit.pri
+++ b/src/plugins/git/gerrit/gerrit.pri
@@ -1,5 +1,3 @@
-INCLUDEPATH += $$PWD
-
SOURCES += $$PWD/gerritdialog.cpp \
$$PWD/gerritmodel.cpp \
$$PWD/gerritparameters.cpp \
diff --git a/src/plugins/git/gerrit/gerritdialog.cpp b/src/plugins/git/gerrit/gerritdialog.cpp
index 2ec682dfa3..27f84d55be 100644
--- a/src/plugins/git/gerrit/gerritdialog.cpp
+++ b/src/plugins/git/gerrit/gerritdialog.cpp
@@ -233,7 +233,7 @@ void GerritDialog::updateCompletions(const QString &query)
queries.removeAll(query);
queries.prepend(query);
m_queryModel->setStringList(queries);
- m_parameters->saveQueries(Core::ICore::instance()->settings());
+ m_parameters->saveQueries(Core::ICore::settings());
}
GerritDialog::~GerritDialog()
diff --git a/src/plugins/git/gerrit/gerritmodel.cpp b/src/plugins/git/gerrit/gerritmodel.cpp
index b7cb210b97..4084cc8a04 100644
--- a/src/plugins/git/gerrit/gerritmodel.cpp
+++ b/src/plugins/git/gerrit/gerritmodel.cpp
@@ -32,7 +32,6 @@
#include "../gitplugin.h"
#include "../gitclient.h"
-#include <coreplugin/icore.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <coreplugin/progressmanager/futureprogress.h>
#include <vcsbase/vcsbaseoutputwindow.h>
@@ -323,9 +322,8 @@ QueryContext::~QueryContext()
void QueryContext::start()
{
- Core::ProgressManager *pm = Core::ICore::instance()->progressManager();
- Core::FutureProgress *fp = pm->addTask(m_progress.future(), tr("Gerrit"),
- QLatin1String("gerrit-query"));
+ Core::FutureProgress *fp = Core::ProgressManager::addTask(m_progress.future(), tr("Gerrit"),
+ "gerrit-query");
fp->setKeepOnFinish(Core::FutureProgress::HideOnFinish);
m_progress.reportStarted();
startQuery(m_queries.front()); // Order: synchronous call to error handling if something goes wrong.
@@ -664,11 +662,13 @@ static bool parseOutput(const QSharedPointer<GerritParameters> &parameters,
result.clear();
result.reserve(lines.size());
+ Utils::JsonMemoryPool pool;
+
foreach (const QByteArray &line, lines) {
if (line.isEmpty())
continue;
- QScopedPointer<Utils::JsonValue> objectValue(Utils::JsonValue::create(QString::fromUtf8(line)));
- if (objectValue.isNull()) {
+ Utils::JsonValue *objectValue = Utils::JsonValue::create(QString::fromUtf8(line), &pool);
+ if (!objectValue) {
QString errorMessage = GerritModel::tr("Parse error: '%1'")
.arg(QString::fromLocal8Bit(line));
qWarning() << errorMessage;
diff --git a/src/plugins/git/gerrit/gerritoptionspage.cpp b/src/plugins/git/gerrit/gerritoptionspage.cpp
index 70c6174335..456b1edf6d 100644
--- a/src/plugins/git/gerrit/gerritoptionspage.cpp
+++ b/src/plugins/git/gerrit/gerritoptionspage.cpp
@@ -73,7 +73,7 @@ void GerritOptionsPage::apply()
else
newParameters.setPortFlagBySshType();
*m_parameters = newParameters;
- m_parameters->toSettings(Core::ICore::instance()->settings());
+ m_parameters->toSettings(Core::ICore::settings());
}
}
}
diff --git a/src/plugins/git/gerrit/gerritplugin.cpp b/src/plugins/git/gerrit/gerritplugin.cpp
index f1deaa2a07..75eefd32b1 100644
--- a/src/plugins/git/gerrit/gerritplugin.cpp
+++ b/src/plugins/git/gerrit/gerritplugin.cpp
@@ -67,6 +67,8 @@
#include <QDir>
#include <QMap>
+using namespace Core;
+
enum { debug = 0 };
namespace Gerrit {
@@ -165,10 +167,9 @@ FetchContext::~FetchContext()
void FetchContext::start()
{
m_progress.setProgressRange(0, 2);
- Core::ProgressManager *pm = Core::ICore::instance()->progressManager();
- Core::FutureProgress *fp = pm->addTask(m_progress.future(), tr("Gerrit Fetch"),
- QLatin1String("gerrit-fetch"));
- fp->setKeepOnFinish(Core::FutureProgress::HideOnFinish);
+ FutureProgress *fp = ProgressManager::addTask(m_progress.future(), tr("Gerrit Fetch"),
+ "gerrit-fetch");
+ fp->setKeepOnFinish(FutureProgress::HideOnFinish);
m_progress.reportStarted();
// Order: initialize future before starting the process in case error handling is invoked.
const QStringList args = m_change->gitFetchArguments(m_parameters);
@@ -247,8 +248,8 @@ void FetchContext::show()
void FetchContext::cherryPick()
{
// Point user to errors.
- VcsBase::VcsBaseOutputWindow::instance()->popup(Core::IOutputPane::ModeSwitch
- | Core::IOutputPane::WithFocus);
+ VcsBase::VcsBaseOutputWindow::instance()->popup(IOutputPane::ModeSwitch
+ | IOutputPane::WithFocus);
Git::Internal::GitPlugin::instance()->gitClient()->synchronousCherryPick(
m_repository, QLatin1String("FETCH_HEAD"));
}
@@ -270,23 +271,23 @@ GerritPlugin::~GerritPlugin()
{
}
-bool GerritPlugin::initialize(Core::ActionContainer *ac)
+bool GerritPlugin::initialize(ActionContainer *ac)
{
- m_parameters->fromSettings(Core::ICore::instance()->settings());
+ m_parameters->fromSettings(ICore::settings());
QAction *openViewAction = new QAction(tr("Gerrit..."), this);
m_gerritCommand =
- Core::ActionManager::registerAction(openViewAction, Constants::GERRIT_OPEN_VIEW,
- Core::Context(Core::Constants::C_GLOBAL));
+ ActionManager::registerAction(openViewAction, Constants::GERRIT_OPEN_VIEW,
+ Context(Core::Constants::C_GLOBAL));
connect(openViewAction, SIGNAL(triggered()), this, SLOT(openView()));
ac->addAction(m_gerritCommand);
QAction *pushAction = new QAction(tr("Push to Gerrit..."), this);
- Core::Command *pushCommand =
- Core::ActionManager::registerAction(pushAction, Constants::GERRIT_PUSH,
- Core::Context(Core::Constants::C_GLOBAL));
+ Command *pushCommand =
+ ActionManager::registerAction(pushAction, Constants::GERRIT_PUSH,
+ Context(Core::Constants::C_GLOBAL));
connect(pushAction, SIGNAL(triggered()), this, SLOT(push()));
ac->addAction(pushCommand);
@@ -307,18 +308,16 @@ void GerritPlugin::addToLocator(Locator::CommandLocator *locator)
locator->appendCommand(m_pushToGerritPair.second);
}
-void GerritPlugin::push()
+void GerritPlugin::push(const QString &topLevel)
{
- const QString topLevel = Git::Internal::GitPlugin::instance()->currentState().topLevel();
-
// QScopedPointer is required to delete the dialog when leaving the function
- GerritPushDialog dialog(topLevel, m_reviewers, Core::ICore::mainWindow());
+ GerritPushDialog dialog(topLevel, m_reviewers, ICore::mainWindow());
if (!dialog.localChangesFound())
return;
if (!dialog.valid()) {
- QMessageBox::warning(Core::ICore::mainWindow(), tr("Initialization Failed"),
+ QMessageBox::warning(ICore::mainWindow(), tr("Initialization Failed"),
tr("Failed to initialize dialog. Aborting."));
return;
}
@@ -360,11 +359,13 @@ void GerritPlugin::openView()
{
if (m_dialog.isNull()) {
while (!m_parameters->isValid()) {
- const Core::Id group = VcsBase::Constants::VCS_SETTINGS_CATEGORY;
- if (!Core::ICore::instance()->showOptionsDialog(group, Core::Id("Gerrit")))
+ QMessageBox::warning(0, tr("Error"),
+ tr("Invalid Gerrit configuration. Host, user and ssh binary are mandatory."));
+ const Id group = VcsBase::Constants::VCS_SETTINGS_CATEGORY;
+ if (!ICore::showOptionsDialog(group, "Gerrit"))
return;
}
- GerritDialog *gd = new GerritDialog(m_parameters, Core::ICore::mainWindow());
+ GerritDialog *gd = new GerritDialog(m_parameters, ICore::mainWindow());
gd->setModal(false);
connect(gd, SIGNAL(fetchDisplay(QSharedPointer<Gerrit::Internal::GerritChange>)),
this, SLOT(fetchDisplay(QSharedPointer<Gerrit::Internal::GerritChange>)));
@@ -384,6 +385,11 @@ void GerritPlugin::openView()
m_dialog.data()->raise();
}
+void GerritPlugin::push()
+{
+ push(Git::Internal::GitPlugin::instance()->currentState().topLevel());
+}
+
QString GerritPlugin::gitBinary()
{
bool ok;
@@ -465,7 +471,7 @@ void GerritPlugin::fetch(const QSharedPointer<Gerrit::Internal::GerritChange> &c
if (!verifiedRepository) {
QMessageBox::StandardButton answer = QMessageBox::question(
- Core::ICore::mainWindow(), tr("Remote Not Verified"),
+ ICore::mainWindow(), tr("Remote Not Verified"),
tr("Change host %1\nand project %2\n\nwere not verified among remotes"
" in %3. Select different folder?")
.arg(m_parameters->host,
@@ -509,8 +515,7 @@ void GerritPlugin::fetch(const QSharedPointer<Gerrit::Internal::GerritChange> &c
// Try to find a matching repository for a project by asking the VcsManager.
QString GerritPlugin::findLocalRepository(QString project, const QString &branch) const
{
- const Core::VcsManager *vcsManager = Core::ICore::instance()->vcsManager();
- const QStringList gitRepositories = vcsManager->repositories(Git::Internal::GitPlugin::instance()->gitVersionControl());
+ const QStringList gitRepositories = VcsManager::repositories(Git::Internal::GitPlugin::instance()->gitVersionControl());
// Determine key (file name) to look for (qt/qtbase->'qtbase').
const int slashPos = project.lastIndexOf(QLatin1Char('/'));
if (slashPos != -1)
@@ -544,7 +549,7 @@ QString GerritPlugin::findLocalRepository(QString project, const QString &branch
} // for repositories
// No match, do we have a projects folder?
if (Core::DocumentManager::useProjectsDirectory())
- return Core::DocumentManager::projectsDirectory();
+ return DocumentManager::projectsDirectory();
return QDir::currentPath();
}
diff --git a/src/plugins/git/gerrit/gerritplugin.h b/src/plugins/git/gerrit/gerritplugin.h
index 4eda51bd98..b2a6ef737a 100644
--- a/src/plugins/git/gerrit/gerritplugin.h
+++ b/src/plugins/git/gerrit/gerritplugin.h
@@ -67,6 +67,7 @@ public:
static QString gitBinary();
static QString branch(const QString &repository);
void addToLocator(Locator::CommandLocator *locator);
+ void push(const QString &topLevel);
public slots:
void fetchDisplay(const QSharedPointer<Gerrit::Internal::GerritChange> &change);
diff --git a/src/plugins/git/gerrit/gerritpushdialog.cpp b/src/plugins/git/gerrit/gerritpushdialog.cpp
index 87bc2d235d..25bc5a10bc 100644
--- a/src/plugins/git/gerrit/gerritpushdialog.cpp
+++ b/src/plugins/git/gerrit/gerritpushdialog.cpp
@@ -33,6 +33,7 @@
#include "../gitplugin.h"
#include "../gitclient.h"
+#include <QDateTime>
#include <QDir>
namespace Gerrit {
@@ -94,20 +95,23 @@ GerritPushDialog::GerritPushDialog(const QString &workingDir, const QString &rev
error.clear();
args.clear();
- args << QLatin1String("-r");
-
- if (!gitClient->synchronousBranchCmd(m_workingDir, args, &output, &error))
+ QString remotesPrefix(QLatin1String("refs/remotes/"));
+ args << QLatin1String("--format=%(refname)\t%(committerdate:raw)")
+ << remotesPrefix;
+ if (!gitClient->synchronousForEachRefCmd(workingDir, args, &output))
return;
refs.clear();
refs = output.split(QLatin1String("\n"));
foreach (const QString &reference, refs) {
- if (reference.contains(head) || reference.isEmpty())
+ QStringList entries = reference.split(QLatin1Char('\t'));
+ if (entries.count() < 2 || entries.first().endsWith(head))
continue;
-
- int refBranchIndex = reference.indexOf(QLatin1Char('/'));
- m_remoteBranches.insertMulti(reference.left(refBranchIndex).trimmed(),
- reference.mid(refBranchIndex + 1).trimmed());
+ const QString ref = entries.at(0).mid(remotesPrefix.size());
+ int refBranchIndex = ref.indexOf(QLatin1Char('/'));
+ int timeT = entries.at(1).left(entries.at(1).indexOf(QLatin1Char(' '))).toInt();
+ BranchDate bd(ref.mid(refBranchIndex + 1), QDateTime::fromTime_t(timeT).date());
+ m_remoteBranches.insertMulti(ref.left(refBranchIndex), bd);
}
int currIndex = 0;
@@ -165,6 +169,10 @@ QString GerritPushDialog::calculateChangeRange()
void GerritPushDialog::setChangeRange()
{
+ if (m_ui->branchComboBox->itemData(m_ui->branchComboBox->currentIndex()) == 1) {
+ setRemoteBranches(true);
+ return;
+ }
QString remote = selectedRemoteName();
remote += QLatin1Char('/');
remote += selectedRemoteBranchName();
@@ -182,22 +190,31 @@ bool GerritPushDialog::valid() const
return m_valid;
}
-void GerritPushDialog::setRemoteBranches()
+void GerritPushDialog::setRemoteBranches(bool includeOld)
{
bool blocked = m_ui->branchComboBox->blockSignals(true);
m_ui->branchComboBox->clear();
int i = 0;
+ bool excluded = false;
for (RemoteBranchesMap::const_iterator it = m_remoteBranches.constBegin(),
end = m_remoteBranches.constEnd();
it != end; ++it) {
if (it.key() == selectedRemoteName()) {
- m_ui->branchComboBox->addItem(it.value());
- if (it.value() == m_suggestedRemoteBranch)
- m_ui->branchComboBox->setCurrentIndex(i);
- ++i;
+ const BranchDate &bd = it.value();
+ const bool isSuggested = bd.first == m_suggestedRemoteBranch;
+ if (includeOld || bd.second.daysTo(QDate::currentDate()) <= 60 || isSuggested) {
+ m_ui->branchComboBox->addItem(bd.first);
+ if (isSuggested)
+ m_ui->branchComboBox->setCurrentIndex(i);
+ ++i;
+ } else {
+ excluded = true;
+ }
}
}
+ if (excluded)
+ m_ui->branchComboBox->addItem(tr("... Include older branches ..."), 1);
setChangeRange();
m_ui->branchComboBox->blockSignals(blocked);
}
diff --git a/src/plugins/git/gerrit/gerritpushdialog.h b/src/plugins/git/gerrit/gerritpushdialog.h
index 08afdd8a9f..950cbacb29 100644
--- a/src/plugins/git/gerrit/gerritpushdialog.h
+++ b/src/plugins/git/gerrit/gerritpushdialog.h
@@ -32,6 +32,7 @@
#include <QDialog>
#include <QMultiMap>
+#include <QDate>
namespace Gerrit {
namespace Internal {
@@ -59,10 +60,11 @@ public:
private slots:
void setChangeRange();
- void setRemoteBranches();
+ void setRemoteBranches(bool includeOld = false);
private:
- typedef QMultiMap<QString, QString> RemoteBranchesMap;
+ typedef QPair<QString, QDate> BranchDate;
+ typedef QMultiMap<QString, BranchDate> RemoteBranchesMap;
QString calculateChangeRange();
QString m_workingDir;
diff --git a/src/plugins/git/gitclient.cpp b/src/plugins/git/gitclient.cpp
index 949705242c..124a0d63a4 100644
--- a/src/plugins/git/gitclient.cpp
+++ b/src/plugins/git/gitclient.cpp
@@ -44,6 +44,7 @@
#include <coreplugin/vcsmanager.h>
#include <coreplugin/id.h>
#include <coreplugin/iversioncontrol.h>
+#include <coreplugin/coreconstants.h>
#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
@@ -84,6 +85,100 @@ namespace Internal {
using VcsBase::VcsBasePlugin;
+class GitDiffSwitcher : public QObject
+{
+ Q_OBJECT
+
+public:
+ enum DiffType {
+ DiffRepository,
+ DiffFile,
+ DiffFileList,
+ DiffProjectList,
+ DiffBranch,
+ DiffShow
+ };
+
+ GitDiffSwitcher(Core::IEditor *parentEditor, GitClient *gitClient)
+ : QObject(parentEditor),
+ m_editor(parentEditor),
+ m_gitClient(gitClient)
+ {
+ m_usingDiffEditor = gitClient->settings()->boolValue(GitSettings::useDiffEditorKey);
+ QIcon actionIcon = m_usingDiffEditor
+ ? QIcon(QLatin1String(Core::Constants::ICON_TEXT_DIFF))
+ : QIcon(QLatin1String(Core::Constants::ICON_SIDE_BY_SIDE_DIFF));
+
+ const QString actionToolTip = m_usingDiffEditor
+ ? tr("Switch to Text Diff Editor")
+ : tr("Switch to Side By Side Diff Editor");
+
+ QAction *switchAction = new QAction(actionIcon, actionToolTip, parentEditor);
+ parentEditor->toolBar()->addAction(switchAction);
+ connect(switchAction, SIGNAL(triggered()), this, SLOT(execute()));
+ }
+
+ void setWorkingDirectory(const QString &workingDir) { m_workingDirectory = workingDir; }
+ void setDiffType(DiffType type) { m_diffType = type; }
+ void setFileName(const QString &fileName) { m_fileName = fileName; }
+ void setFileList(const QStringList &stagedFiles, const QStringList &unstagedFiles)
+ {
+ m_stagedFiles = stagedFiles;
+ m_unstagedFiles = unstagedFiles;
+ }
+ void setProjectList(const QStringList &projectFiles) { m_projectFiles = projectFiles; }
+ void setBranchName(const QString &branchName) { m_branchName = branchName; }
+ void setId(const QString &id) { m_id = id; }
+ void setDisplayName(const QString &displayName) { m_displayName = displayName; }
+ void setBaseArguments(const QStringList &args) { m_baseArguments = args; }
+
+public slots:
+ void execute();
+
+private:
+ Core::IEditor *m_editor;
+ GitClient *m_gitClient;
+ QString m_workingDirectory;
+ DiffType m_diffType;
+ bool m_usingDiffEditor;
+ QString m_fileName;
+ QStringList m_stagedFiles;
+ QStringList m_unstagedFiles;
+ QStringList m_projectFiles;
+ QString m_branchName;
+ QString m_id;
+ QString m_displayName;
+ QStringList m_baseArguments;
+};
+
+void GitDiffSwitcher::execute()
+{
+ m_gitClient->settings()->setValue(GitSettings::useDiffEditorKey, !m_usingDiffEditor);
+ switch (m_diffType) {
+ case DiffRepository:
+ m_gitClient->diff(m_workingDirectory, QStringList(), QStringList());
+ break;
+ case DiffFile:
+ m_gitClient->diff(m_workingDirectory, m_fileName);
+ break;
+ case DiffFileList:
+ m_gitClient->diff(m_workingDirectory, m_unstagedFiles, m_stagedFiles);
+ break;
+ case DiffProjectList:
+ m_gitClient->diff(m_workingDirectory, m_projectFiles, QStringList());
+ break;
+ case DiffBranch:
+ m_gitClient->diffBranch(m_workingDirectory, m_baseArguments, m_branchName);
+ break;
+ case DiffShow:
+ m_gitClient->show(m_fileName, m_id, m_baseArguments, m_displayName);
+ break;
+ default:
+ break;
+ }
+ Core::EditorManager::closeEditor(m_editor, false);
+}
+
class GitDiffHandler : public QObject
{
Q_OBJECT
@@ -132,9 +227,9 @@ public:
void show(const QString &id);
private slots:
- void slotShowDescriptionReceived(const QByteArray &data);
- void slotFileListReceived(const QByteArray &data);
- void slotFileContentsReceived(const QByteArray &data);
+ void slotShowDescriptionReceived(const QString &data);
+ void slotFileListReceived(const QString &fileList);
+ void slotFileContentsReceived(const QString &contents);
private:
void collectShowDescription(const QString &id);
@@ -259,23 +354,24 @@ void GitDiffHandler::collectShowDescription(const QString &id)
return;
m_editor->clear(m_waitMessage);
VcsBase::Command *command = new VcsBase::Command(m_gitPath, m_workingDirectory, m_processEnvironment);
- connect(command, SIGNAL(outputData(QByteArray)), this, SLOT(slotShowDescriptionReceived(QByteArray)));
+ command->setCodec(m_editor->editorWidget()->codec());
+ connect(command, SIGNAL(output(QString)), this, SLOT(slotShowDescriptionReceived(QString)));
QStringList arguments;
- arguments << QLatin1String("show") << QLatin1String("-s") << QLatin1String("--format=fuller")
+ arguments << QLatin1String("show") << QLatin1String("-s")
<< QLatin1String(noColorOption) << QLatin1String(decorateOption) << id;
command->addJob(arguments, m_timeout);
command->execute();
}
-void GitDiffHandler::slotShowDescriptionReceived(const QByteArray &data)
+void GitDiffHandler::slotShowDescriptionReceived(const QString &description)
{
if (m_editor.isNull())
return;
- const QString description = m_editor->editorWidget()->codec()->toUnicode(data).remove(QLatin1Char('\r'));
-
DiffEditor::DiffShowEditor *editor = qobject_cast<DiffEditor::DiffShowEditor *>(m_editor);
- if (editor)
- editor->setDescription(description);
+ if (editor) {
+ editor->setDescription(GitPlugin::instance()->gitClient()->
+ extendedShowDescription(m_workingDirectory, description));
+ }
collectFilesList(QStringList()
<< m_requestedRevisionRange.begin.id
@@ -288,19 +384,19 @@ void GitDiffHandler::collectFilesList(const QStringList &additionalArguments)
return;
m_editor->clear(m_waitMessage);
VcsBase::Command *command = new VcsBase::Command(m_gitPath, m_workingDirectory, m_processEnvironment);
- connect(command, SIGNAL(outputData(QByteArray)), this, SLOT(slotFileListReceived(QByteArray)));
+ command->setCodec(m_editor->editorWidget()->codec());
+ connect(command, SIGNAL(output(QString)), this, SLOT(slotFileListReceived(QString)));
QStringList arguments;
arguments << QLatin1String("diff") << QLatin1String("--name-only") << additionalArguments;
command->addJob(arguments, m_timeout);
command->execute();
}
-void GitDiffHandler::slotFileListReceived(const QByteArray &data)
+void GitDiffHandler::slotFileListReceived(const QString &fileList)
{
if (m_editor.isNull())
return;
- const QString fileList = m_editor->editorWidget()->codec()->toUnicode(data).remove(QLatin1Char('\r'));
QStringList fileNames = fileList.split(QLatin1Char('\n'), QString::SkipEmptyParts);
fileNames.removeDuplicates();
@@ -355,11 +451,13 @@ void GitDiffHandler::collectFilesContents()
// prepare job here
VcsBase::Command *command = new VcsBase::Command(m_gitPath, m_workingDirectory, m_processEnvironment);
- connect(command, SIGNAL(outputData(QByteArray)), this, SLOT(slotFileContentsReceived(QByteArray)));
+ if (m_editor)
+ command->setCodec(m_editor->editorWidget()->codec());
+ connect(command, SIGNAL(output(QString)), this, SLOT(slotFileContentsReceived(QString)));
QString revisionArgument = (revision.type == Other)
? revision.id : QString();
- revisionArgument += QLatin1String(":./");
+ revisionArgument += QLatin1Char(':');
QStringList arguments;
arguments << QLatin1String("show") << revisionArgument + fileName;
command->addJob(arguments, m_timeout);
@@ -375,7 +473,7 @@ void GitDiffHandler::collectFilesContents()
feedEditor();
}
-void GitDiffHandler::slotFileContentsReceived(const QByteArray &data)
+void GitDiffHandler::slotFileContentsReceived(const QString &contents)
{
if (m_editor.isNull())
return;
@@ -392,7 +490,6 @@ void GitDiffHandler::slotFileContentsReceived(const QByteArray &data)
QMap<Revision, bool>::iterator itRevEnd
= revisions.end();
if (itRev != itRevEnd) {
- const QString contents = m_editor->editorWidget()->codec()->toUnicode(data).remove(QLatin1Char('\r'));
m_collectedRevisions[fileName][itRev.key()] = contents;
itRev = revisions.erase(itRev);
@@ -484,21 +581,26 @@ class GitCommitDiffArgumentsWidget : public BaseGitDiffArgumentsWidget
public:
GitCommitDiffArgumentsWidget(Git::Internal::GitClient *client, const QString &directory,
- const QStringList &args, const QStringList &unstaged,
- const QStringList &staged) :
- BaseGitDiffArgumentsWidget(client, directory, args),
- m_unstagedFileNames(unstaged),
- m_stagedFileNames(staged)
- { }
+ const QStringList &unstaged, const QStringList &staged) :
+ BaseGitDiffArgumentsWidget(client, directory, QStringList())
+ {
+ setFileNames(unstaged, staged);
+ }
+
+ void setFileNames(const QStringList &unstaged, const QStringList &staged)
+ {
+ m_unstagedFileNames = unstaged;
+ m_stagedFileNames = staged;
+ }
void executeCommand()
{
- m_client->diff(m_workingDirectory, arguments(), m_unstagedFileNames, m_stagedFileNames);
+ m_client->diff(m_workingDirectory, m_unstagedFileNames, m_stagedFileNames);
}
private:
- const QStringList m_unstagedFileNames;
- const QStringList m_stagedFileNames;
+ QStringList m_unstagedFileNames;
+ QStringList m_stagedFileNames;
};
class GitFileDiffArgumentsWidget : public BaseGitDiffArgumentsWidget
@@ -506,14 +608,14 @@ class GitFileDiffArgumentsWidget : public BaseGitDiffArgumentsWidget
Q_OBJECT
public:
GitFileDiffArgumentsWidget(Git::Internal::GitClient *client, const QString &directory,
- const QStringList &args, const QString &file) :
- BaseGitDiffArgumentsWidget(client, directory, args),
+ const QString &file) :
+ BaseGitDiffArgumentsWidget(client, directory, QStringList()),
m_fileName(file)
{ }
void executeCommand()
{
- m_client->diff(m_workingDirectory, arguments(), m_fileName);
+ m_client->diff(m_workingDirectory, m_fileName);
}
private:
@@ -532,7 +634,7 @@ public:
void executeCommand()
{
- m_client->diffBranch(m_workingDirectory, arguments(), m_branchName);
+ m_client->diffBranch(m_workingDirectory, baseArguments(), m_branchName);
}
private:
@@ -567,7 +669,7 @@ public:
void executeCommand()
{
- m_client->show(m_workingDirectory, m_id, arguments());
+ m_client->show(m_workingDirectory, m_id, baseArguments());
}
private:
@@ -612,7 +714,7 @@ public:
int line = -1;
if (m_editor)
line = m_editor->lineNumberOfCurrentEditor();
- m_client->blame(m_workingDirectory, arguments(), m_fileName, m_revision, line);
+ m_client->blame(m_workingDirectory, baseArguments(), m_fileName, m_revision, line);
}
private:
@@ -632,12 +734,11 @@ public:
const QString &directory,
bool enableAnnotationContextMenu,
const QStringList &args,
- const QStringList &fileNames) :
+ const QString &fileName) :
BaseGitDiffArgumentsWidget(client, directory, args),
m_client(client),
m_workingDirectory(directory),
- m_enableAnnotationContextMenu(enableAnnotationContextMenu),
- m_fileNames(fileNames)
+ m_enableAnnotationContextMenu(enableAnnotationContextMenu)
{
QTC_ASSERT(!directory.isEmpty(), return);
QToolButton *diffButton = addToggleButton(QLatin1String("--patch"), tr("Show Diff"),
@@ -653,18 +754,24 @@ public:
QToolButton *graphButton = addToggleButton(graphArguments, tr("Graph"),
tr("Show textual graph log."));
mapSetting(graphButton, m_client->settings()->boolPointer(GitSettings::graphLogKey));
+ setFileName(fileName);
+ }
+
+ void setFileName(const QString &fileNames)
+ {
+ m_fileName = fileNames;
}
void executeCommand()
{
- m_client->log(m_workingDirectory, m_fileNames, m_enableAnnotationContextMenu, arguments());
+ m_client->log(m_workingDirectory, m_fileName, m_enableAnnotationContextMenu, baseArguments());
}
private:
GitClient *m_client;
QString m_workingDirectory;
bool m_enableAnnotationContextMenu;
- QStringList m_fileNames;
+ QString m_fileName;
};
class ConflictHandler : public QObject
@@ -679,8 +786,8 @@ public:
m_command(command)
{
if (parentCommand) {
- parentCommand->setExpectChanges(true);
- connect(parentCommand, SIGNAL(outputData(QByteArray)), this, SLOT(readStdOut(QByteArray)));
+ parentCommand->addFlags(VcsBasePlugin::ExpectRepoChanges);
+ connect(parentCommand, SIGNAL(output(QString)), this, SLOT(readStdOut(QString)));
connect(parentCommand, SIGNAL(errorText(QString)), this, SLOT(readStdErr(QString)));
}
}
@@ -700,7 +807,8 @@ public:
}
}
- void readStdOutString(const QString &data)
+public slots:
+ void readStdOut(const QString &data)
{
static QRegExp patchFailedRE(QLatin1String("Patch failed at ([^\\n]*)"));
static QRegExp conflictedFilesRE(QLatin1String("Merge conflict in ([^\\n]*)"));
@@ -711,11 +819,6 @@ public:
m_files.append(conflictedFilesRE.cap(1));
}
}
-public slots:
- void readStdOut(const QByteArray &data)
- {
- readStdOutString(QString::fromUtf8(data));
- }
void readStdErr(const QString &data)
{
@@ -730,21 +833,39 @@ private:
QStringList m_files;
};
+class ProgressParser : public VcsBase::ProgressParser
+{
+public:
+ ProgressParser() :
+ m_progressExp(QLatin1String("\\((\\d+)/(\\d+)\\)")) // e.g. Rebasing (7/42)
+ {
+ }
+
+protected:
+ void parseProgress(const QString &text)
+ {
+ if (m_progressExp.lastIndexIn(text) != -1)
+ setProgressAndMaximum(m_progressExp.cap(1).toInt(), m_progressExp.cap(2).toInt());
+ }
+
+private:
+ QRegExp m_progressExp;
+};
+
+
Core::IEditor *locateEditor(const char *property, const QString &entry)
{
- foreach (Core::IEditor *ed, Core::ICore::editorManager()->openedEditors())
- if (ed->document()->property(property).toString() == entry)
- return ed;
+ foreach (Core::IDocument *document, Core::EditorManager::documentModel()->openedDocuments())
+ if (document->property(property).toString() == entry)
+ return Core::EditorManager::documentModel()->editorsForDocument(document).first();
return 0;
}
// Return converted command output, remove '\r' read on Windows
static inline QString commandOutputFromLocal8Bit(const QByteArray &a)
{
- QString output = QString::fromLocal8Bit(a);
- output.remove(QLatin1Char('\r'));
- return output;
+ return Utils::SynchronousProcess::normalizeNewlines(QString::fromLocal8Bit(a));
}
// Return converted command output split into lines
@@ -774,13 +895,24 @@ static inline QString msgParseFilesFailed()
return GitClient::tr("Cannot parse the file output.");
}
+static inline QString msgCannotLaunch(const QString &binary)
+{
+ return GitClient::tr("Cannot launch \"%1\".").arg(QDir::toNativeSeparators(binary));
+}
+
static inline QString currentDocumentPath()
{
- if (Core::IEditor *editor = Core::EditorManager::currentEditor())
- return QFileInfo(editor->document()->fileName()).path();
+ if (Core::IDocument *document= Core::EditorManager::currentDocument())
+ return QFileInfo(document->filePath()).path();
return QString();
}
+static inline QStringList statusArguments()
+{
+ return QStringList() << QLatin1String("-c") << QLatin1String("color.status=false")
+ << QLatin1String("status");
+}
+
// ---------------- GitClient
const char *GitClient::stashNamePrefix = "stash@{";
@@ -850,53 +982,60 @@ VcsBase::VcsBaseEditorWidget *GitClient::findExistingVCSEditor(const char *regis
// Exists already
Core::EditorManager::activateEditor(outputEditor);
- outputEditor->createNew(m_msgWait);
+ outputEditor->document()->setContents(m_msgWait.toUtf8());
rc = VcsBase::VcsBaseEditorWidget::getVcsBaseEditor(outputEditor);
return rc;
}
-DiffEditor::DiffEditor *GitClient::findExistingOrOpenNewDiffEditor(const char *registerDynamicProperty,
- const QString &dynamicPropertyValue, const QString &titlePattern, const Core::Id editorId) const
+DiffEditor::DiffEditor *GitClient::findExistingDiffEditor(const char *registerDynamicProperty,
+ const QString &dynamicPropertyValue) const
{
- Core::IEditor *outputEditor = locateEditor(registerDynamicProperty, dynamicPropertyValue);
- if (outputEditor) {
- // Exists already
- Core::EditorManager::activateEditor(outputEditor);
- outputEditor->createNew(m_msgWait);
- }
-
- DiffEditor::DiffEditor *editor = qobject_cast<DiffEditor::DiffEditor *>(outputEditor);
- if (!editor) {
- QString title = titlePattern;
- editor = qobject_cast<DiffEditor::DiffEditor *>(
- Core::EditorManager::openEditorWithContents(editorId, &title, m_msgWait));
- editor->document()->setProperty(registerDynamicProperty, dynamicPropertyValue);
- Core::EditorManager::activateEditor(editor);
+ DiffEditor::DiffEditor *diffEditor = qobject_cast<DiffEditor::DiffEditor *>(
+ locateEditor(registerDynamicProperty, dynamicPropertyValue));
+ if (diffEditor) {
+ diffEditor->document()->setContents(m_msgWait.toUtf8());
+ Core::EditorManager::activateEditor(diffEditor);
}
- return editor;
+ return diffEditor;
}
+DiffEditor::DiffEditor *GitClient::createDiffEditor(const char *registerDynamicProperty,
+ const QString &dynamicPropertyValue,
+ const QString &source,
+ const QString &titlePattern,
+ const Core::Id editorId) const
+{
+ QString title = titlePattern;
+ DiffEditor::DiffEditor *diffEditor = qobject_cast<DiffEditor::DiffEditor *>(
+ Core::EditorManager::openEditorWithContents(editorId, &title, m_msgWait.toUtf8()));
+ QTC_ASSERT(diffEditor, return 0);
+ diffEditor->document()->setProperty(registerDynamicProperty, dynamicPropertyValue);
+ diffEditor->editorWidget()->setSource(source);
+
+ Core::EditorManager::activateEditor(diffEditor);
+ return diffEditor;
+}
/* Create an editor associated to VCS output of a source file/directory
* (using the file's codec). Makes use of a dynamic property to find an
* existing instance and to reuse it (in case, say, 'git diff foo' is
* already open). */
-VcsBase::VcsBaseEditorWidget *GitClient::createVcsEditor(const Core::Id &id,
- QString title,
- // Source file or directory
- const QString &source,
- CodecType codecType,
- // Dynamic property and value to identify that editor
- const char *registerDynamicProperty,
- const QString &dynamicPropertyValue,
- QWidget *configWidget) const
+VcsBase::VcsBaseEditorWidget *GitClient::createVcsEditor(
+ const Core::Id &id,
+ QString title,
+ const QString &source, // Source file or directory
+ CodecType codecType,
+ const char *registerDynamicProperty, // Dynamic property and value to identify that editor
+ const QString &dynamicPropertyValue,
+ VcsBase::VcsBaseEditorParameterWidget *configWidget) const
{
VcsBase::VcsBaseEditorWidget *rc = 0;
QTC_CHECK(!findExistingVCSEditor(registerDynamicProperty, dynamicPropertyValue));
// Create new, set wait message, set up with source and codec
- Core::IEditor *outputEditor = Core::EditorManager::openEditorWithContents(id, &title, m_msgWait);
+ Core::IEditor *outputEditor = Core::EditorManager::openEditorWithContents(id, &title,
+ m_msgWait.toUtf8());
outputEditor->document()->setProperty(registerDynamicProperty, dynamicPropertyValue);
rc = VcsBase::VcsBaseEditorWidget::getVcsBaseEditor(outputEditor);
connect(rc, SIGNAL(annotateRevisionRequested(QString,QString,int)),
@@ -922,21 +1061,28 @@ VcsBase::VcsBaseEditorWidget *GitClient::createVcsEditor(const Core::Id &id,
}
void GitClient::diff(const QString &workingDirectory,
- const QStringList &diffArgs,
const QStringList &unstagedFileNames,
const QStringList &stagedFileNames)
{
const QString title = tr("Git Diff");
const int timeout = settings()->intValue(GitSettings::timeoutKey);
-
+ Core::IEditor *newEditor = 0;
if (settings()->boolValue(GitSettings::useDiffEditorKey)) {
- DiffEditor::DiffEditor *editor = findExistingOrOpenNewDiffEditor(
- "originalFileName",
- workingDirectory,
- title,
- DiffEditor::Constants::DIFF_EDITOR_ID);
+ const char *propertyName = "sideBySideOriginalFileName";
+ DiffEditor::DiffEditor *diffEditor = findExistingDiffEditor(propertyName, workingDirectory);
+ if (!diffEditor) {
+ newEditor = diffEditor = createDiffEditor(propertyName,
+ workingDirectory,
+ workingDirectory,
+ title,
+ DiffEditor::Constants::DIFF_EDITOR_ID);
+ }
- GitDiffHandler *handler = new GitDiffHandler(editor, gitBinaryPath(), workingDirectory, processEnvironment(), timeout);
+ GitDiffHandler *handler = new GitDiffHandler(diffEditor,
+ gitBinaryPath(),
+ workingDirectory,
+ processEnvironment(),
+ timeout);
if (unstagedFileNames.empty() && stagedFileNames.empty()) {
// local repository diff
@@ -950,31 +1096,43 @@ void GitClient::diff(const QString &workingDirectory,
}
} else {
const QString binary = settings()->stringValue(GitSettings::binaryPathKey);
- const Core::Id editorId = Git::Constants::GIT_DIFF_EDITOR_ID;
-
- VcsBase::VcsBaseEditorWidget *editor = findExistingVCSEditor("originalFileName", workingDirectory);
- if (!editor) {
+ const char *propertyName = "originalFileName";
+ VcsBase::VcsBaseEditorWidget *vcsEditor = findExistingVCSEditor(propertyName, workingDirectory);
+ if (!vcsEditor) {
GitCommitDiffArgumentsWidget *argWidget =
- new GitCommitDiffArgumentsWidget(this, workingDirectory, diffArgs,
- unstagedFileNames, stagedFileNames);
-
- editor = createVcsEditor(editorId, title,
- workingDirectory, CodecSource, "originalFileName", workingDirectory, argWidget);
- connect(editor, SIGNAL(diffChunkReverted(VcsBase::DiffChunk)), argWidget, SLOT(executeCommand()));
+ new GitCommitDiffArgumentsWidget(this,
+ workingDirectory,
+ unstagedFileNames,
+ stagedFileNames);
+ vcsEditor = createVcsEditor(Git::Constants::GIT_DIFF_EDITOR_ID,
+ title,
+ workingDirectory,
+ CodecSource,
+ propertyName,
+ workingDirectory,
+ argWidget);
+ newEditor = vcsEditor->editor();
+ connect(vcsEditor, SIGNAL(diffChunkApplied(VcsBase::DiffChunk)),
+ argWidget, SLOT(executeCommand()));
+ connect(vcsEditor, SIGNAL(diffChunkReverted(VcsBase::DiffChunk)),
+ argWidget, SLOT(executeCommand()));
}
- GitCommitDiffArgumentsWidget *argWidget = qobject_cast<GitCommitDiffArgumentsWidget *>(editor->configurationWidget());
+ GitCommitDiffArgumentsWidget *argWidget = qobject_cast<GitCommitDiffArgumentsWidget *>(
+ vcsEditor->configurationWidget());
+ argWidget->setFileNames(unstagedFileNames, stagedFileNames);
QStringList userDiffArgs = argWidget->arguments();
- editor->setDiffBaseDirectory(workingDirectory);
+ vcsEditor->setDiffBaseDirectory(workingDirectory);
// Create a batch of 2 commands to be run after each other in case
// we have a mixture of staged/unstaged files as is the case
// when using the submit dialog.
- VcsBase::Command *command = createCommand(workingDirectory, editor);
+ VcsBase::Command *command = createCommand(workingDirectory, vcsEditor);
// Directory diff?
QStringList cmdArgs;
- cmdArgs << QLatin1String("diff") << QLatin1String(noColorOption);
+ cmdArgs << QLatin1String("diff")
+ << QLatin1String(noColorOption);
if (unstagedFileNames.empty() && stagedFileNames.empty()) {
QStringList arguments(cmdArgs);
@@ -985,65 +1143,99 @@ void GitClient::diff(const QString &workingDirectory,
// Files diff.
if (!unstagedFileNames.empty()) {
QStringList arguments(cmdArgs);
- arguments << userDiffArgs;
- arguments << QLatin1String("--") << unstagedFileNames;
+ arguments << userDiffArgs
+ << QLatin1String("--")
+ << unstagedFileNames;
outputWindow()->appendCommand(workingDirectory, binary, arguments);
command->addJob(arguments, timeout);
}
if (!stagedFileNames.empty()) {
QStringList arguments(cmdArgs);
- arguments << userDiffArgs;
- arguments << QLatin1String("--cached") << diffArgs << QLatin1String("--") << stagedFileNames;
+ arguments << userDiffArgs
+ << QLatin1String("--cached")
+ << QLatin1String("--")
+ << stagedFileNames;
outputWindow()->appendCommand(workingDirectory, binary, arguments);
command->addJob(arguments, timeout);
}
}
command->execute();
}
+ if (newEditor) {
+ GitDiffSwitcher *switcher = new GitDiffSwitcher(newEditor, this);
+ switcher->setWorkingDirectory(workingDirectory);
+ if (unstagedFileNames.empty() && stagedFileNames.empty()) {
+ // local repository diff
+ switcher->setDiffType(GitDiffSwitcher::DiffRepository);
+ } else if (!stagedFileNames.empty()) {
+ // diff of selected files only with --cached option, used in commit editor
+ switcher->setDiffType(GitDiffSwitcher::DiffFileList);
+ switcher->setFileList(stagedFileNames, unstagedFileNames);
+ } else {
+ // current project diff
+ switcher->setDiffType(GitDiffSwitcher::DiffProjectList);
+ switcher->setProjectList(unstagedFileNames);
+ }
+ }
}
-void GitClient::diff(const QString &workingDirectory,
- const QStringList &diffArgs,
- const QString &fileName)
+void GitClient::diff(const QString &workingDirectory, const QString &fileName)
{
const QString title = tr("Git Diff \"%1\"").arg(fileName);
+ const QString sourceFile = VcsBase::VcsBaseEditorWidget::getSource(workingDirectory, fileName);
+ Core::IEditor *newEditor = 0;
if (settings()->boolValue(GitSettings::useDiffEditorKey)) {
- const QString sourceFile = VcsBase::VcsBaseEditorWidget::getSource(workingDirectory, fileName);
- DiffEditor::DiffEditor *editor = findExistingOrOpenNewDiffEditor(
- "originalFileName",
- sourceFile,
- title,
- DiffEditor::Constants::DIFF_EDITOR_ID);
-
- if (!fileName.isEmpty()) {
- int timeout = settings()->intValue(GitSettings::timeoutKey);
- GitDiffHandler *handler = new GitDiffHandler(editor, gitBinaryPath(), workingDirectory, processEnvironment(), timeout);
- handler->diffFile(fileName);
+ const char *propertyName = "sideBySideOriginalFileName";
+ DiffEditor::DiffEditor *diffEditor = findExistingDiffEditor(propertyName, sourceFile);
+ if (!diffEditor) {
+ newEditor = diffEditor = createDiffEditor(propertyName,
+ sourceFile,
+ sourceFile,
+ title,
+ DiffEditor::Constants::DIFF_EDITOR_ID);
}
+ GitDiffHandler *handler = new GitDiffHandler(diffEditor,
+ gitBinaryPath(),
+ workingDirectory,
+ processEnvironment(),
+ settings()->intValue(GitSettings::timeoutKey));
+ handler->diffFile(fileName);
} else {
- const Core::Id editorId = Git::Constants::GIT_DIFF_EDITOR_ID;
- const QString sourceFile = VcsBase::VcsBaseEditorWidget::getSource(workingDirectory, fileName);
-
- VcsBase::VcsBaseEditorWidget *editor = findExistingVCSEditor("originalFileName", sourceFile);
- if (!editor) {
+ const char *propertyName = "originalFileName";
+ VcsBase::VcsBaseEditorWidget *vcsEditor = findExistingVCSEditor(propertyName, sourceFile);
+ if (!vcsEditor) {
GitFileDiffArgumentsWidget *argWidget =
- new GitFileDiffArgumentsWidget(this, workingDirectory, diffArgs, fileName);
-
- editor = createVcsEditor(editorId, title, sourceFile, CodecSource, "originalFileName", sourceFile, argWidget);
- connect(editor, SIGNAL(diffChunkReverted(VcsBase::DiffChunk)), argWidget, SLOT(executeCommand()));
+ new GitFileDiffArgumentsWidget(this, workingDirectory, fileName);
+
+ vcsEditor = createVcsEditor(Git::Constants::GIT_DIFF_EDITOR_ID,
+ title,
+ sourceFile,
+ CodecSource,
+ propertyName,
+ sourceFile,
+ argWidget);
+ newEditor = vcsEditor->editor();
+ connect(vcsEditor, SIGNAL(diffChunkApplied(VcsBase::DiffChunk)),
+ argWidget, SLOT(executeCommand()));
+ connect(vcsEditor, SIGNAL(diffChunkReverted(VcsBase::DiffChunk)),
+ argWidget, SLOT(executeCommand()));
}
- editor->setDiffBaseDirectory(workingDirectory);
-
- GitFileDiffArgumentsWidget *argWidget = qobject_cast<GitFileDiffArgumentsWidget *>(editor->configurationWidget());
- QStringList userDiffArgs = argWidget->arguments();
+ vcsEditor->setDiffBaseDirectory(workingDirectory);
QStringList cmdArgs;
- cmdArgs << QLatin1String("diff") << QLatin1String(noColorOption)
- << userDiffArgs;
+ cmdArgs << QLatin1String("diff")
+ << QLatin1String(noColorOption)
+ << vcsEditor->configurationWidget()->arguments();
if (!fileName.isEmpty())
cmdArgs << QLatin1String("--") << fileName;
- executeGit(workingDirectory, cmdArgs, editor);
+ executeGit(workingDirectory, cmdArgs, vcsEditor);
+ }
+ if (newEditor) {
+ GitDiffSwitcher *switcher = new GitDiffSwitcher(newEditor, this);
+ switcher->setWorkingDirectory(workingDirectory);
+ switcher->setDiffType(GitDiffSwitcher::DiffFile);
+ switcher->setFileName(fileName);
}
}
@@ -1052,35 +1244,58 @@ void GitClient::diffBranch(const QString &workingDirectory,
const QString &branchName)
{
const QString title = tr("Git Diff Branch \"%1\"").arg(branchName);
+ Core::IEditor *newEditor = 0;
if (settings()->boolValue(GitSettings::useDiffEditorKey)) {
- DiffEditor::DiffEditor *editor = findExistingOrOpenNewDiffEditor(
- "BranchName",
- branchName,
- title,
- DiffEditor::Constants::DIFF_EDITOR_ID);
-
- int timeout = settings()->intValue(GitSettings::timeoutKey);
- GitDiffHandler *handler = new GitDiffHandler(editor, gitBinaryPath(), workingDirectory, processEnvironment(), timeout);
+ const char *propertyName = "sideBySideBranchName";
+ DiffEditor::DiffEditor *diffEditor = findExistingDiffEditor(propertyName, branchName);
+ if (!diffEditor) {
+ newEditor = diffEditor = createDiffEditor(propertyName,
+ branchName,
+ workingDirectory,
+ title,
+ DiffEditor::Constants::DIFF_EDITOR_ID);
+ }
+
+ GitDiffHandler *handler = new GitDiffHandler(diffEditor,
+ gitBinaryPath(),
+ workingDirectory,
+ processEnvironment(),
+ settings()->intValue(GitSettings::timeoutKey));
handler->diffBranch(branchName);
} else {
- const Core::Id editorId = Git::Constants::GIT_DIFF_EDITOR_ID;
+ const char *propertyName = "BranchName";
const QString sourceFile = VcsBase::VcsBaseEditorWidget::getSource(workingDirectory, QStringList());
- VcsBase::VcsBaseEditorWidget *editor = findExistingVCSEditor("BranchName", branchName);
- if (!editor)
- editor = createVcsEditor(editorId, title, sourceFile, CodecSource, "BranchName", branchName,
- new GitBranchDiffArgumentsWidget(this, workingDirectory,
- diffArgs, branchName));
- editor->setDiffBaseDirectory(workingDirectory);
-
- GitBranchDiffArgumentsWidget *argWidget = qobject_cast<GitBranchDiffArgumentsWidget *>(editor->configurationWidget());
- QStringList userDiffArgs = argWidget->arguments();
+ VcsBase::VcsBaseEditorWidget *vcsEditor = findExistingVCSEditor(propertyName, branchName);
+ if (!vcsEditor) {
+ vcsEditor = createVcsEditor(Git::Constants::GIT_DIFF_EDITOR_ID,
+ title,
+ sourceFile,
+ CodecSource,
+ propertyName,
+ branchName,
+ new GitBranchDiffArgumentsWidget(this,
+ workingDirectory,
+ diffArgs,
+ branchName));
+ newEditor = vcsEditor->editor();
+ }
+ vcsEditor->setDiffBaseDirectory(workingDirectory);
QStringList cmdArgs;
- cmdArgs << QLatin1String("diff") << QLatin1String(noColorOption)
- << userDiffArgs << branchName;
+ cmdArgs << QLatin1String("diff")
+ << QLatin1String(noColorOption)
+ << vcsEditor->configurationWidget()->arguments()
+ << branchName;
- executeGit(workingDirectory, cmdArgs, editor);
+ executeGit(workingDirectory, cmdArgs, vcsEditor);
+ }
+ if (newEditor) {
+ GitDiffSwitcher *switcher = new GitDiffSwitcher(newEditor, this);
+ switcher->setWorkingDirectory(workingDirectory);
+ switcher->setDiffType(GitDiffSwitcher::DiffBranch);
+ switcher->setBaseArguments(diffArgs);
+ switcher->setBranchName(branchName);
}
}
@@ -1093,8 +1308,7 @@ void GitClient::merge(const QString &workingDirectory, const QStringList &unmerg
void GitClient::status(const QString &workingDirectory)
{
- // @TODO: Use "--no-color" once it is supported
- QStringList statusArgs(QLatin1String("status"));
+ QStringList statusArgs = statusArguments();
statusArgs << QLatin1String("-u");
VcsBase::VcsBaseOutputWindow *outwin = outputWindow();
outwin->setRepository(workingDirectory);
@@ -1103,20 +1317,19 @@ void GitClient::status(const QString &workingDirectory)
Qt::QueuedConnection);
}
-void GitClient::log(const QString &workingDirectory, const QStringList &fileNames,
+void GitClient::log(const QString &workingDirectory, const QString &fileName,
bool enableAnnotationContextMenu, const QStringList &args)
{
- const QString msgArg = fileNames.empty() ? workingDirectory :
- fileNames.join(QLatin1String(", "));
+ const QString msgArg = fileName.isEmpty() ? workingDirectory : fileName;
const QString title = tr("Git Log \"%1\"").arg(msgArg);
const Core::Id editorId = Git::Constants::GIT_LOG_EDITOR_ID;
- const QString sourceFile = VcsBase::VcsBaseEditorWidget::getSource(workingDirectory, fileNames);
+ const QString sourceFile = VcsBase::VcsBaseEditorWidget::getSource(workingDirectory, fileName);
VcsBase::VcsBaseEditorWidget *editor = findExistingVCSEditor("logFileName", sourceFile);
if (!editor)
editor = createVcsEditor(editorId, title, sourceFile, CodecLogOutput, "logFileName", sourceFile,
new GitLogArgumentsWidget(this, workingDirectory,
enableAnnotationContextMenu,
- args, fileNames));
+ args, fileName));
editor->setFileLogAnnotateEnabled(enableAnnotationContextMenu);
editor->setDiffBaseDirectory(workingDirectory);
@@ -1129,12 +1342,35 @@ void GitClient::log(const QString &workingDirectory, const QStringList &fileName
arguments << QLatin1String("-n") << QString::number(logCount);
GitLogArgumentsWidget *argWidget = qobject_cast<GitLogArgumentsWidget *>(editor->configurationWidget());
+ argWidget->setBaseArguments(args);
+ argWidget->setFileName(fileName);
QStringList userArgs = argWidget->arguments();
arguments.append(userArgs);
- if (!fileNames.isEmpty())
- arguments << QLatin1String("--") << fileNames;
+ if (!fileName.isEmpty())
+ arguments << QLatin1String("--follow") << QLatin1String("--") << fileName;
+
+ executeGit(workingDirectory, arguments, editor);
+}
+
+void GitClient::reflog(const QString &workingDirectory)
+{
+ const QString title = tr("Git Reflog \"%1\"").arg(workingDirectory);
+ const Core::Id editorId = Git::Constants::GIT_LOG_EDITOR_ID;
+ VcsBase::VcsBaseEditorWidget *editor = findExistingVCSEditor("reflogRepository", workingDirectory);
+ if (!editor) {
+ editor = createVcsEditor(editorId, title, workingDirectory, CodecLogOutput,
+ "reflogRepository", workingDirectory, 0);
+ }
+
+ QStringList arguments;
+ arguments << QLatin1String("reflog") << QLatin1String(noColorOption)
+ << QLatin1String(decorateOption);
+
+ int logCount = settings()->intValue(GitSettings::logCountKey);
+ if (logCount > 0)
+ arguments << QLatin1String("-n") << QString::number(logCount);
executeGit(workingDirectory, arguments, editor);
}
@@ -1158,43 +1394,65 @@ void GitClient::show(const QString &source, const QString &id,
const QStringList &args, const QString &name)
{
if (!canShow(id)) {
- outputWindow()->append(msgCannotShow(id));
+ outputWindow()->appendError(msgCannotShow(id));
return;
}
const QString title = tr("Git Show \"%1\"").arg(name.isEmpty() ? id : name);
const QFileInfo sourceFi(source);
- const QString workDir = sourceFi.isDir() ? sourceFi.absoluteFilePath() : sourceFi.absolutePath();
+ const QString workingDirectory = sourceFi.isDir() ? sourceFi.absoluteFilePath() : sourceFi.absolutePath();
+ Core::IEditor *newEditor = 0;
if (settings()->boolValue(GitSettings::useDiffEditorKey)) {
- DiffEditor::DiffEditor *editor = findExistingOrOpenNewDiffEditor(
- "show",
- id,
- title,
- DiffEditor::Constants::DIFF_SHOW_EDITOR_ID);
-
- int timeout = settings()->intValue(GitSettings::timeoutKey);
- GitDiffHandler *handler = new GitDiffHandler(editor, gitBinaryPath(),
- findRepositoryForDirectory(workDir),
- processEnvironment(), timeout);
+ const char *propertyName = "sideBySideShow";
+ DiffEditor::DiffEditor *diffEditor = findExistingDiffEditor(propertyName, id);
+ if (!diffEditor) {
+ newEditor = diffEditor = createDiffEditor(propertyName,
+ id,
+ source,
+ title,
+ DiffEditor::Constants::DIFF_SHOW_EDITOR_ID);
+ }
+
+ GitDiffHandler *handler = new GitDiffHandler(diffEditor,
+ gitBinaryPath(),
+ workingDirectory,
+ processEnvironment(),
+ settings()->intValue(GitSettings::timeoutKey));
handler->show(id);
} else {
+ const char *propertyName = "show";
const Core::Id editorId = Git::Constants::GIT_DIFF_EDITOR_ID;
- VcsBase::VcsBaseEditorWidget *editor = findExistingVCSEditor("show", id);
- if (!editor)
- editor = createVcsEditor(editorId, title, source, CodecSource, "show", id,
- new GitShowArgumentsWidget(this, source, args, id));
-
- GitShowArgumentsWidget *argWidget = qobject_cast<GitShowArgumentsWidget *>(editor->configurationWidget());
- QStringList userArgs = argWidget->arguments();
+ VcsBase::VcsBaseEditorWidget *vcsEditor = findExistingVCSEditor(propertyName, id);
+ if (!vcsEditor) {
+ vcsEditor = createVcsEditor(editorId,
+ title,
+ source,
+ CodecSource,
+ propertyName,
+ id,
+ new GitShowArgumentsWidget(this,
+ source,
+ args,
+ id));
+ newEditor = vcsEditor->editor();
+ }
QStringList arguments;
- arguments << QLatin1String("show") << QLatin1String(noColorOption);
- arguments << QLatin1String(decorateOption);
- arguments.append(userArgs);
- arguments << id;
+ arguments << QLatin1String("show")
+ << QLatin1String(noColorOption)
+ << QLatin1String(decorateOption)
+ << vcsEditor->configurationWidget()->arguments()
+ << id;
- editor->setDiffBaseDirectory(workDir);
- executeGit(workDir, arguments, editor);
+ vcsEditor->setDiffBaseDirectory(workingDirectory);
+ executeGit(workingDirectory, arguments, vcsEditor);
+ }
+ if (newEditor) {
+ GitDiffSwitcher *switcher = new GitDiffSwitcher(newEditor, this);
+ switcher->setDiffType(GitDiffSwitcher::DiffShow);
+ switcher->setFileName(source);
+ switcher->setBaseArguments(args);
+ switcher->setId(id);
}
}
@@ -1214,18 +1472,6 @@ void GitClient::slotBlameRevisionRequested(const QString &source, QString change
blame(fi.absolutePath(), QStringList(), fi.fileName(), change, lineNumber);
}
-void GitClient::appendOutputData(const QByteArray &data) const
-{
- const QTextCodec *codec = getSourceCodec(currentDocumentPath());
- outputWindow()->appendData(codec->toUnicode(data).toLocal8Bit());
-}
-
-void GitClient::appendOutputDataSilently(const QByteArray &data) const
-{
- const QTextCodec *codec = getSourceCodec(currentDocumentPath());
- outputWindow()->appendDataSilently(codec->toUnicode(data).toLocal8Bit());
-}
-
QTextCodec *GitClient::getSourceCodec(const QString &file) const
{
if (QFileInfo(file).isFile())
@@ -1256,12 +1502,9 @@ void GitClient::blame(const QString &workingDirectory,
argWidget->setEditor(editor);
}
- GitBlameArgumentsWidget *argWidget = qobject_cast<GitBlameArgumentsWidget *>(editor->configurationWidget());
- QStringList userBlameArgs = argWidget->arguments();
-
QStringList arguments(QLatin1String("blame"));
arguments << QLatin1String("--root");
- arguments.append(userBlameArgs);
+ arguments.append(editor->configurationWidget()->arguments());
arguments << QLatin1String("--") << fileName;
if (!revision.isEmpty())
arguments << revision;
@@ -1446,11 +1689,11 @@ bool GitClient::synchronousInit(const QString &workingDirectory)
const bool rc = fullySynchronousGit(workingDirectory, arguments, &outputText, &errorText);
// '[Re]Initialized...'
outputWindow()->append(commandOutputFromLocal8Bit(outputText));
- if (!rc)
+ if (!rc) {
outputWindow()->appendError(commandOutputFromLocal8Bit(errorText));
- else {
+ } else {
// TODO: Turn this into a VcsBaseClient and use resetCachedVcsInfo(...)
- Core::ICore::vcsManager()->resetVersionControlForDirectory(workingDirectory);
+ Core::VcsManager::resetVersionControlForDirectory(workingDirectory);
}
return rc;
}
@@ -1540,9 +1783,9 @@ bool GitClient::synchronousRevListCmd(const QString &workingDirectory, const QSt
if (errorMessage)
*errorMessage = commandOutputFromLocal8Bit(errorText);
else
- outputWindow()->append(tr("Cannot execute \"git %1\" in \"%2\": %3").arg(
- args.join(QLatin1String(" ")), workingDirectory,
- commandOutputFromLocal8Bit(errorText)));
+ outputWindow()->appendError(tr("Cannot execute \"git %1\" in \"%2\": %3").arg(
+ args.join(QLatin1String(" ")), workingDirectory,
+ commandOutputFromLocal8Bit(errorText)));
return false;
}
*output = commandOutputFromLocal8Bit(outputTextData);
@@ -1620,11 +1863,6 @@ QString GitClient::synchronousCurrentLocalBranch(const QString &workingDirectory
return QString();
}
-static inline QString msgCannotDetermineBranch(const QString &workingDirectory, const QString &why)
-{
- return GitClient::tr("Cannot retrieve branch of \"%1\": %2").arg(QDir::toNativeSeparators(workingDirectory), why);
-}
-
static inline QString msgCannotRun(const QString &command, const QString &workingDirectory, const QString &why)
{
return GitClient::tr("Cannot run \"%1\" in \"%2\": %3")
@@ -1646,7 +1884,7 @@ bool GitClient::synchronousHeadRefs(const QString &workingDirectory, QStringList
if (errorMessage)
*errorMessage = message;
else
- outputWindow()->append(message);
+ outputWindow()->appendError(message);
return false;
}
@@ -1690,20 +1928,6 @@ QString GitClient::synchronousTopic(const QString &workingDirectory)
if (!branch.isEmpty())
return data.topic = branch;
- switch (checkCommandInProgressInGitDir(gitDir)) {
- case Rebase:
- case RebaseMerge:
- return data.topic = tr("REBASING");
- case Revert:
- return data.topic = tr("REVERTING");
- case CherryPick:
- return data.topic = tr("CHERRY-PICKING");
- case Merge:
- return data.topic = tr("MERGING");
- default:
- break;
- }
-
// Detached HEAD, try a tag or remote branch
QStringList references;
if (!synchronousHeadRefs(workingDirectory, &references))
@@ -1757,17 +1981,19 @@ QString GitClient::synchronousTopRevision(const QString &workingDirectory, QStri
}
void GitClient::synchronousTagsForCommit(const QString &workingDirectory, const QString &revision,
- QByteArray &precedes, QByteArray &follows)
+ QString &precedes, QString &follows)
{
+ QByteArray pr;
QStringList arguments;
arguments << QLatin1String("describe") << QLatin1String("--contains") << revision;
- fullySynchronousGit(workingDirectory, arguments, &precedes, 0,
+ fullySynchronousGit(workingDirectory, arguments, &pr, 0,
VcsBasePlugin::SuppressCommandLogging);
- int tilde = precedes.indexOf('~');
+ int tilde = pr.indexOf('~');
if (tilde != -1)
- precedes.truncate(tilde);
+ pr.truncate(tilde);
else
- precedes = precedes.trimmed();
+ pr = pr.trimmed();
+ precedes = QString::fromLocal8Bit(pr);
QStringList parents;
QString errorMessage;
@@ -1782,12 +2008,42 @@ void GitClient::synchronousTagsForCommit(const QString &workingDirectory, const
pf.truncate(pf.lastIndexOf('\n'));
if (!pf.isEmpty()) {
if (!follows.isEmpty())
- follows += ", ";
- follows += pf;
+ follows += QLatin1String(", ");
+ follows += QString::fromLocal8Bit(pf);
}
}
}
+QStringList GitClient::synchronousBranchesForCommit(const QString &workingDirectory, const QString &revision)
+{
+ QByteArray outputData;
+ QString output;
+ QStringList arguments;
+ arguments << QLatin1String("branch") << QLatin1String(noColorOption)
+ << QLatin1String("-a") << QLatin1String("--contains") << revision;
+ fullySynchronousGit(workingDirectory, arguments, &outputData, 0,
+ VcsBasePlugin::SuppressCommandLogging);
+ output = commandOutputFromLocal8Bit(outputData);
+ QStringList res;
+ foreach (const QString &branch, output.split(QLatin1Char('\n'))) {
+ const QString b = branch.mid(2).trimmed();
+ if (!b.isEmpty())
+ res << b;
+ }
+ return res;
+}
+
+bool GitClient::isRemoteCommit(const QString &workingDirectory, const QString &commit)
+{
+ QStringList arguments;
+ QByteArray outputText;
+ arguments << QLatin1String("branch") << QLatin1String("-r")
+ << QLatin1String("--contains") << commit;
+ fullySynchronousGit(workingDirectory, arguments, &outputText, 0,
+ VcsBasePlugin::SuppressCommandLogging);
+ return !outputText.isEmpty();
+}
+
// Format an entry in a one-liner for selection list using git log.
QString GitClient::synchronousShortDescription(const QString &workingDirectory, const QString &revision,
const QString &format)
@@ -1862,10 +2118,10 @@ QString GitClient::synchronousStash(const QString &workingDirectory, const QStri
if (unchanged)
*unchanged = true;
if (!(flags & StashIgnoreUnchanged))
- outputWindow()->append(msgNoChangedFiles());
+ outputWindow()->appendWarning(msgNoChangedFiles());
break;
case StatusFailed:
- outputWindow()->append(errorMessage);
+ outputWindow()->appendError(errorMessage);
break;
}
if (!success)
@@ -1923,7 +2179,7 @@ bool GitClient::stashNameFromMessage(const QString &workingDirectory,
if (errorMessage)
*errorMessage = msg;
else
- outputWindow()->append(msg);
+ outputWindow()->appendError(msg);
return false;
}
@@ -1935,8 +2191,23 @@ bool GitClient::synchronousBranchCmd(const QString &workingDirectory, QStringLis
QByteArray errorText;
const bool rc = fullySynchronousGit(workingDirectory, branchArgs, &outputText, &errorText);
*output = commandOutputFromLocal8Bit(outputText);
+ if (!rc && errorMessage) {
+ *errorMessage = msgCannotRun(QLatin1String("git branch"), workingDirectory,
+ commandOutputFromLocal8Bit(errorText));
+ }
+ return rc;
+}
+
+bool GitClient::synchronousTagCmd(const QString &workingDirectory, QStringList tagArgs, QString *output, QString *errorMessage)
+{
+ tagArgs.push_front(QLatin1String("tag"));
+ QByteArray outputText;
+ QByteArray errorText;
+ const bool rc = fullySynchronousGit(workingDirectory, tagArgs, &outputText, &errorText);
+ *output = commandOutputFromLocal8Bit(outputText);
if (!rc) {
- *errorMessage = msgCannotRun(QLatin1String("git branch"), workingDirectory, commandOutputFromLocal8Bit(errorText));
+ *errorMessage = msgCannotRun(QLatin1String("git tag"), workingDirectory,
+ commandOutputFromLocal8Bit(errorText));
return false;
}
return true;
@@ -1951,8 +2222,12 @@ bool GitClient::synchronousForEachRefCmd(const QString &workingDirectory, QStrin
const bool rc = fullySynchronousGit(workingDirectory, args, &outputText, &errorText);
*output = commandOutputFromLocal8Bit(outputText);
if (!rc) {
- *errorMessage = msgCannotRun(QLatin1String("git for-each-ref"), workingDirectory,
+ QString error = msgCannotRun(QLatin1String("git for-each-ref"), workingDirectory,
commandOutputFromLocal8Bit(errorText));
+ if (errorMessage)
+ *errorMessage = error;
+ else
+ outputWindow()->appendError(error);
return false;
}
@@ -1985,7 +2260,7 @@ QMap<QString,QString> GitClient::synchronousRemotesList(const QString &workingDi
if (errorMessage)
*errorMessage = error;
else
- outputWindow()->append(error);
+ outputWindow()->appendError(error);
return result;
}
QStringList remotes = output.split(QLatin1String("\n"));
@@ -1994,12 +2269,11 @@ QMap<QString,QString> GitClient::synchronousRemotesList(const QString &workingDi
if (!remote.endsWith(QLatin1String(" (push)")))
continue;
- QStringList tokens = remote.split(QRegExp(QLatin1String("\\s")),
- QString::SkipEmptyParts);
- if (tokens.count() != 3)
+ int tabIndex = remote.indexOf(QLatin1Char('\t'));
+ if (tabIndex == -1)
continue;
-
- result.insert(tokens.at(0), tokens.at(1));
+ QString url = remote.mid(tabIndex + 1, remote.length() - tabIndex - 8);
+ result.insert(remote.left(tabIndex), url);
}
return result;
}
@@ -2021,7 +2295,7 @@ QStringList GitClient::synchronousSubmoduleStatus(const QString &workingDirector
if (errorMessage)
*errorMessage = error;
else
- outputWindow()->append(error);
+ outputWindow()->appendError(error);
return QStringList();
}
@@ -2143,10 +2417,11 @@ bool GitClient::synchronousCleanList(const QString &workingDirectory, QStringLis
}
bool GitClient::synchronousApplyPatch(const QString &workingDirectory,
- const QString &file, QString *errorMessage)
+ const QString &file, QString *errorMessage,
+ const QStringList &arguments)
{
QStringList args;
- args << QLatin1String("apply") << QLatin1String("--whitespace=fix") << file;
+ args << QLatin1String("apply") << QLatin1String("--whitespace=fix") << arguments << file;
QByteArray outputText;
QByteArray errorText;
const bool rc = fullySynchronousGit(workingDirectory, args, &outputText, &errorText);
@@ -2167,20 +2442,22 @@ VcsBase::Command *GitClient::createCommand(const QString &workingDirectory,
int editorLineNumber)
{
VcsBase::Command *command = new VcsBase::Command(gitBinaryPath(), workingDirectory, processEnvironment());
+ command->setCodec(getSourceCodec(currentDocumentPath()));
command->setCookie(QVariant(editorLineNumber));
- if (editor)
- connect(command, SIGNAL(finished(bool,int,QVariant)), editor, SLOT(commandFinishedGotoLine(bool,int,QVariant)));
+ if (editor) {
+ editor->setCommand(command);
+ connect(command, SIGNAL(finished(bool,int,QVariant)),
+ editor, SLOT(commandFinishedGotoLine(bool,int,QVariant)));
+ }
if (useOutputToWindow) {
+ command->addFlags(VcsBasePlugin::ShowStdOutInLogWindow);
+ command->addFlags(VcsBasePlugin::ShowSuccessMessage);
if (editor) // assume that the commands output is the important thing
- connect(command, SIGNAL(outputData(QByteArray)), this, SLOT(appendOutputDataSilently(QByteArray)));
- else
- connect(command, SIGNAL(outputData(QByteArray)), this, SLOT(appendOutputData(QByteArray)));
- } else {
- if (editor)
- connect(command, SIGNAL(outputData(QByteArray)), editor, SLOT(setPlainTextDataFiltered(QByteArray)));
+ command->addFlags(VcsBasePlugin::SilentOutput);
+ } else if (editor) {
+ connect(command, SIGNAL(output(QString)), editor, SLOT(setPlainTextFiltered(QString)));
}
- connect(command, SIGNAL(errorText(QString)), outputWindow(), SLOT(appendError(QString)));
return command;
}
@@ -2195,9 +2472,8 @@ VcsBase::Command *GitClient::executeGit(const QString &workingDirectory,
outputWindow()->appendCommand(workingDirectory, settings()->stringValue(GitSettings::binaryPathKey), arguments);
VcsBase::Command *command = createCommand(workingDirectory, editor, useOutputToWindow, editorLineNumber);
command->addJob(arguments, settings()->intValue(GitSettings::timeoutKey));
- command->setTerminationReportMode(VcsBase::Command::NoReport);
- command->setUnixTerminalDisabled(false);
- command->setExpectChanges(expectChanges);
+ if (expectChanges)
+ command->addFlags(VcsBasePlugin::ExpectRepoChanges);
command->execute();
return command;
}
@@ -2221,12 +2497,12 @@ QProcessEnvironment GitClient::processEnvironment() const
return environment;
}
-bool GitClient::beginStashScope(const QString &workingDirectory, const QString &keyword, StashFlag flag)
+bool GitClient::beginStashScope(const QString &workingDirectory, const QString &command, StashFlag flag)
{
const QString repoDirectory = findRepositoryForDirectory(workingDirectory);
QTC_ASSERT(!repoDirectory.isEmpty(), return false);
StashInfo &stashInfo = m_stashInfo[repoDirectory];
- return stashInfo.init(repoDirectory, keyword, flag);
+ return stashInfo.init(repoDirectory, command, flag);
}
GitClient::StashInfo &GitClient::stashInfo(const QString &workingDirectory)
@@ -2258,12 +2534,11 @@ bool GitClient::isValidRevision(const QString &revision) const
Utils::SynchronousProcessResponse GitClient::synchronousGit(const QString &workingDirectory,
const QStringList &gitArguments,
unsigned flags,
- QTextCodec *stdOutCodec)
+ QTextCodec *outputCodec)
{
return VcsBasePlugin::runVcs(workingDirectory, gitBinaryPath(), gitArguments,
settings()->intValue(GitSettings::timeoutKey) * 1000,
- processEnvironment(),
- flags, stdOutCodec);
+ flags, outputCodec, processEnvironment());
}
bool GitClient::fullySynchronousGit(const QString &workingDirectory,
@@ -2272,10 +2547,11 @@ bool GitClient::fullySynchronousGit(const QString &workingDirectory,
QByteArray* errorText,
unsigned flags) const
{
- return VcsBasePlugin::runFullySynchronous(workingDirectory, gitBinaryPath(), gitArguments,
- processEnvironment(), outputText, errorText,
- settings()->intValue(GitSettings::timeoutKey) * 1000,
- flags);
+ VcsBase::Command command(gitBinaryPath(), workingDirectory, processEnvironment());
+ command.addFlags(flags);
+ return command.runFullySynchronous(gitArguments,
+ settings()->intValue(GitSettings::timeoutKey) * 1000,
+ outputText, errorText);
}
void GitClient::updateSubmodulesIfNeeded(const QString &workingDirectory, bool prompt)
@@ -2342,21 +2618,6 @@ void GitClient::fetchFinished(const QVariant &cookie)
GitPlugin::instance()->updateBranches(cookie.toString());
}
-// Trim a git status file spec: "modified: foo .cpp" -> "modified: foo .cpp"
-static inline QString trimFileSpecification(QString fileSpec)
-{
- const int colonIndex = fileSpec.indexOf(QLatin1Char(':'));
- if (colonIndex != -1) {
- // Collapse the sequence of spaces
- const int filePos = colonIndex + 2;
- int nonBlankPos = filePos;
- for ( ; fileSpec.at(nonBlankPos).isSpace(); nonBlankPos++) ;
- if (nonBlankPos > filePos)
- fileSpec.remove(filePos, nonBlankPos - filePos);
- }
- return fileSpec;
-}
-
GitClient::StatusResult GitClient::gitStatus(const QString &workingDirectory, StatusMode mode,
QString *output, QString *errorMessage)
{
@@ -2364,7 +2625,7 @@ GitClient::StatusResult GitClient::gitStatus(const QString &workingDirectory, St
QByteArray outputText;
QByteArray errorText;
- QStringList statusArgs(QLatin1String("status"));
+ QStringList statusArgs = statusArguments();
if (mode & NoUntracked)
statusArgs << QLatin1String("--untracked-files=no");
else
@@ -2397,8 +2658,27 @@ GitClient::StatusResult GitClient::gitStatus(const QString &workingDirectory, St
return StatusUnchanged;
}
-GitClient::CommandInProgress GitClient::checkCommandInProgressInGitDir(const QString &gitDir)
+QString GitClient::commandInProgressDescription(const QString &workingDirectory)
+{
+ switch (checkCommandInProgress(workingDirectory)) {
+ case NoCommand:
+ break;
+ case Rebase:
+ case RebaseMerge:
+ return tr("REBASING");
+ case Revert:
+ return tr("REVERTING");
+ case CherryPick:
+ return tr("CHERRY-PICKING");
+ case Merge:
+ return tr("MERGING");
+ }
+ return QString();
+}
+
+GitClient::CommandInProgress GitClient::checkCommandInProgress(const QString &workingDirectory)
{
+ const QString gitDir = findGitDirForRepository(workingDirectory);
if (QFile::exists(gitDir + QLatin1String("/MERGE_HEAD")))
return Merge;
else if (QFile::exists(gitDir + QLatin1String("/rebase-apply/rebasing")))
@@ -2413,15 +2693,15 @@ GitClient::CommandInProgress GitClient::checkCommandInProgressInGitDir(const QSt
return NoCommand;
}
-GitClient::CommandInProgress GitClient::checkCommandInProgress(const QString &workingDirectory)
-{
- return checkCommandInProgressInGitDir(findGitDirForRepository(workingDirectory));
-}
-
void GitClient::continueCommandIfNeeded(const QString &workingDirectory)
{
CommandInProgress command = checkCommandInProgress(workingDirectory);
switch (command) {
+ case Merge:
+ continuePreviousGitCommand(workingDirectory, tr("Continue Merge"),
+ tr("Merge is in progress. What do you want to do?"),
+ tr("Continue"), QLatin1String("merge"));
+ break;
case Rebase:
case RebaseMerge:
continuePreviousGitCommand(workingDirectory, tr("Continue Rebase"),
@@ -2479,6 +2759,37 @@ void GitClient::continuePreviousGitCommand(const QString &workingDirectory,
}
}
+QString GitClient::extendedShowDescription(const QString &workingDirectory, const QString &text)
+{
+ if (!text.startsWith(QLatin1String("commit ")))
+ return text;
+ QString modText = text;
+ QString precedes, follows;
+ int lastHeaderLine = modText.indexOf(QLatin1String("\n\n")) + 1;
+ const QString commit = modText.mid(7, 8);
+ synchronousTagsForCommit(workingDirectory, commit, precedes, follows);
+ if (!precedes.isEmpty())
+ modText.insert(lastHeaderLine, QLatin1String("Precedes: ") + precedes + QLatin1Char('\n'));
+ if (!follows.isEmpty())
+ modText.insert(lastHeaderLine, QLatin1String("Follows: ") + follows + QLatin1Char('\n'));
+ QString moreBranches;
+ QStringList branches = synchronousBranchesForCommit(workingDirectory, commit);
+ const int branchCount = branches.count();
+ // If there are more than 20 branches, list first 10 followed by a hint
+ if (branchCount > 20) {
+ const int leave = 10;
+ //: Displayed after the untranslated message "Branches: branch1, branch2 'and %n more'" in git show.
+ moreBranches = tr(" and %n more", 0, branchCount - leave);
+ branches.erase(branches.begin() + leave, branches.end());
+ }
+ if (!branches.isEmpty()) {
+ modText.insert(lastHeaderLine, QLatin1String("Branches: ")
+ + branches.join(QLatin1String(", ")) + moreBranches
+ + QLatin1Char('\n'));
+ }
+ return modText;
+}
+
// Quietly retrieve branch list of remote repository URL
//
// The branch HEAD is pointing to is always returned first.
@@ -2578,15 +2889,27 @@ bool GitClient::tryLauchingGitK(const QProcessEnvironment &env,
success = QProcess::startDetached(binary, arguments, workingDirectory);
}
if (!success) {
- const QString error = tr("Cannot launch \"%1\".").arg(binary);
if (silent)
- outwin->appendSilently(error);
+ outwin->appendSilently(msgCannotLaunch(binary));
else
- outwin->appendError(error);
+ outwin->appendError(msgCannotLaunch(binary));
}
return success;
}
+bool GitClient::launchGitGui(const QString &workingDirectory) {
+ bool success;
+ QString gitBinary = gitBinaryPath(&success);
+ if (success)
+ success = QProcess::startDetached(gitBinary, QStringList(QLatin1String("gui")),
+ workingDirectory);
+
+ if (!success)
+ outputWindow()->appendError(msgCannotLaunch(QLatin1String("git gui")));
+
+ return success;
+}
+
QString GitClient::gitBinaryPath(bool *ok, QString *errorMessage) const
{
return settings()->gitBinaryPath(ok, errorMessage);
@@ -2721,6 +3044,8 @@ bool GitClient::getCommitData(const QString &workingDirectory,
case FixupCommit:
break;
}
+
+ commitData.panelData.hasRemotes = !synchronousRemotesList(repoDirectory).isEmpty();
return true;
}
@@ -2819,7 +3144,7 @@ bool GitClient::addAndCommit(const QString &repositoryDirectory,
const bool rc = fullySynchronousGit(repositoryDirectory, args, &outputText, &errorText);
const QString stdErr = commandOutputFromLocal8Bit(errorText);
if (rc) {
- outputWindow()->append(msgCommitted(amendSHA1, commitCount));
+ outputWindow()->appendMessage(msgCommitted(amendSHA1, commitCount));
outputWindow()->appendError(stdErr);
} else {
outputWindow()->appendError(tr("Cannot commit %n file(s): %1\n", 0, commitCount).arg(stdErr));
@@ -2928,11 +3253,11 @@ void GitClient::revert(const QStringList &files, bool revertStaging)
break;
case RevertUnchanged: {
const QString msg = (isDirectory || files.size() > 1) ? msgNoChangedFiles() : tr("The file is not modified.");
- outputWindow()->append(msg);
+ outputWindow()->appendWarning(msg);
}
break;
case RevertFailed:
- outputWindow()->append(errorMessage);
+ outputWindow()->appendError(errorMessage);
break;
}
}
@@ -2959,7 +3284,7 @@ bool GitClient::executeAndHandleConflicts(const QString &workingDirectory,
// Notify about changed files or abort the rebase.
const bool ok = resp.result == Utils::SynchronousProcessResponse::Finished;
if (!ok) {
- conflictHandler.readStdOutString(resp.stdOut);
+ conflictHandler.readStdOut(resp.stdOut);
conflictHandler.readStdErr(resp.stdErr);
}
return ok;
@@ -3021,13 +3346,36 @@ QString GitClient::synchronousTrackingBranch(const QString &workingDirectory, co
return remote + QLatin1Char('/') + rBranch;
}
+bool GitClient::synchronousSetTrackingBranch(const QString &workingDirectory,
+ const QString &branch, const QString &tracking)
+{
+ QByteArray outputText;
+ QByteArray errorText;
+ QStringList arguments;
+ arguments << QLatin1String("branch");
+ if (gitVersion() >= 0x010800)
+ arguments << (QLatin1String("--set-upstream-to=") + tracking) << branch;
+ else
+ arguments << QLatin1String("--set-upstream") << branch << tracking;
+ const bool rc = fullySynchronousGit(workingDirectory, arguments, &outputText, &errorText);
+ if (!rc) {
+ const QString errorMessage = tr("Cannot set tracking branch: %1")
+ .arg(commandOutputFromLocal8Bit(errorText));
+ outputWindow()->appendError(errorMessage);
+ }
+ return rc;
+}
+
void GitClient::handleMergeConflicts(const QString &workingDir, const QString &commit,
const QStringList &files, const QString &abortCommand)
{
- Q_UNUSED(files);
-
- QString message = commit.isEmpty() ? tr("Conflicts detected")
- : tr("Conflicts detected with commit %1").arg(commit);
+ QString message;
+ if (!commit.isEmpty())
+ message = tr("Conflicts detected with commit %1.").arg(commit);
+ else if (!files.isEmpty())
+ message = tr("Conflicts detected with files:\n%1").arg(files.join(QLatin1String("\n")));
+ else
+ message = tr("Conflicts detected.");
QMessageBox mergeOrAbort(QMessageBox::Question, tr("Conflicts Detected"), message,
QMessageBox::NoButton, Core::ICore::mainWindow());
QPushButton *mergeToolButton = mergeOrAbort.addButton(tr("Run &Merge Tool"),
@@ -3125,6 +3473,7 @@ void GitClient::rebase(const QString &workingDirectory, const QString &baseBranc
arguments);
VcsBase::Command *command = createCommand(workingDirectory, 0, true);
new ConflictHandler(command, workingDirectory, gitCommand);
+ command->setProgressParser(new ProgressParser);
command->addJob(arguments, -1);
command->execute();
}
@@ -3132,7 +3481,11 @@ void GitClient::rebase(const QString &workingDirectory, const QString &baseBranc
bool GitClient::synchronousRevert(const QString &workingDirectory, const QString &commit)
{
QStringList arguments;
- QString command = QLatin1String("revert");
+ const QString command = QLatin1String("revert");
+ // Do not stash if --continue or --abort is given as the commit
+ if (!commit.startsWith(QLatin1Char('-')) && !beginStashScope(workingDirectory, command))
+ return false;
+
arguments << command << QLatin1String("--no-edit") << commit;
return executeAndHandleConflicts(workingDirectory, arguments, command);
@@ -3140,9 +3493,16 @@ bool GitClient::synchronousRevert(const QString &workingDirectory, const QString
bool GitClient::synchronousCherryPick(const QString &workingDirectory, const QString &commit)
{
- QStringList arguments;
- QString command = QLatin1String("cherry-pick");
- arguments << command << commit;
+ const QString command = QLatin1String("cherry-pick");
+ // "commit" might be --continue or --abort
+ const bool isRealCommit = !commit.startsWith(QLatin1Char('-'));
+ if (isRealCommit && !beginStashScope(workingDirectory, command))
+ return false;
+
+ QStringList arguments(command);
+ if (isRealCommit && isRemoteCommit(workingDirectory, commit))
+ arguments << QLatin1String("-x");
+ arguments << commit;
return executeAndHandleConflicts(workingDirectory, arguments, command);
}
@@ -3159,6 +3519,7 @@ void GitClient::interactiveRebase(const QString &workingDirectory, const QString
m_disableEditor = true;
VcsBase::Command *command = createCommand(workingDirectory, 0, true);
new ConflictHandler(command, workingDirectory, QLatin1String("rebase"));
+ command->setProgressParser(new ProgressParser);
command->addJob(arguments, -1);
command->execute();
command->setCookie(workingDirectory);
@@ -3217,7 +3578,7 @@ bool GitClient::synchronousStashRestore(const QString &workingDirectory,
if (errorMessage)
*errorMessage = msg;
else
- outputWindow()->append(msg);
+ outputWindow()->appendError(msg);
return false;
}
QString output = commandOutputFromLocal8Bit(outputText);
@@ -3249,7 +3610,7 @@ bool GitClient::synchronousStashRemove(const QString &workingDirectory,
if (errorMessage)
*errorMessage = msg;
else
- outputWindow()->append(msg);
+ outputWindow()->appendError(msg);
return false;
}
QString output = commandOutputFromLocal8Bit(outputText);
@@ -3289,7 +3650,7 @@ bool GitClient::synchronousStashList(const QString &workingDirectory,
if (errorMessage)
*errorMessage = msg;
else
- outputWindow()->append(msg);
+ outputWindow()->appendError(msg);
return false;
}
Stash stash;
@@ -3310,7 +3671,7 @@ QString GitClient::readConfig(const QString &workingDirectory, const QStringList
VcsBasePlugin::SuppressCommandLogging))
return QString();
if (Utils::HostOsInfo::isWindowsHost())
- return QString::fromUtf8(outputText).remove(QLatin1Char('\r'));
+ return Utils::SynchronousProcess::normalizeNewlines(QString::fromUtf8(outputText));
return commandOutputFromLocal8Bit(outputText);
}
@@ -3365,7 +3726,7 @@ bool GitClient::cloneRepository(const QString &directory,const QByteArray &url)
const Utils::SynchronousProcessResponse resp =
synchronousGit(workingDirectory.path(), arguments, flags);
// TODO: Turn this into a VcsBaseClient and use resetCachedVcsInfo(...)
- Core::ICore::vcsManager()->resetVersionControlForDirectory(workingDirectory.absolutePath());
+ Core::VcsManager::resetVersionControlForDirectory(workingDirectory.absolutePath());
return (resp.result == Utils::SynchronousProcessResponse::Finished);
}
}
@@ -3419,7 +3780,7 @@ unsigned GitClient::synchronousGitVersion(QString *errorMessage) const
if (errorMessage)
*errorMessage = msg;
else
- outputWindow()->append(msg);
+ outputWindow()->appendError(msg);
return 0;
}
// cut 'git version 1.6.5.1.sha'
@@ -3438,7 +3799,7 @@ GitClient::StashInfo::StashInfo() :
{
}
-bool GitClient::StashInfo::init(const QString &workingDirectory, const QString &keyword,
+bool GitClient::StashInfo::init(const QString &workingDirectory, const QString &command,
StashFlag flag)
{
m_workingDir = workingDirectory;
@@ -3449,9 +3810,9 @@ bool GitClient::StashInfo::init(const QString &workingDirectory, const QString &
&statusOutput, &errorMessage)) {
case GitClient::StatusChanged:
if (m_flags & NoPrompt)
- executeStash(keyword, &errorMessage);
+ executeStash(command, &errorMessage);
else
- stashPrompt(keyword, statusOutput, &errorMessage);
+ stashPrompt(command, statusOutput, &errorMessage);
break;
case GitClient::StatusUnchanged:
m_stashResult = StashUnchanged;
@@ -3466,7 +3827,7 @@ bool GitClient::StashInfo::init(const QString &workingDirectory, const QString &
return !stashingFailed();
}
-void GitClient::StashInfo::stashPrompt(const QString &keyword, const QString &statusOutput,
+void GitClient::StashInfo::stashPrompt(const QString &command, const QString &statusOutput,
QString *errorMessage)
{
QMessageBox msgBox(QMessageBox::Question, tr("Uncommitted Changes Found"),
@@ -3476,40 +3837,45 @@ void GitClient::StashInfo::stashPrompt(const QString &keyword, const QString &st
msgBox.setDetailedText(statusOutput);
+ QPushButton *stashAndPopButton = msgBox.addButton(tr("Stash && Pop"), QMessageBox::AcceptRole);
+ stashAndPopButton->setToolTip(tr("Stash local changes and pop when %1 finishes.").arg(command));
+
QPushButton *stashButton = msgBox.addButton(tr("Stash"), QMessageBox::AcceptRole);
- stashButton->setToolTip(tr("Stash local changes and continue."));
+ stashButton->setToolTip(tr("Stash local changes and execute %1.").arg(command));
QPushButton *discardButton = msgBox.addButton(tr("Discard"), QMessageBox::AcceptRole);
- discardButton->setToolTip(tr("Discard (reset) local changes and continue."));
+ discardButton->setToolTip(tr("Discard (reset) local changes and execute %1.").arg(command));
QPushButton *ignoreButton = 0;
if (m_flags & AllowUnstashed) {
ignoreButton = msgBox.addButton(QMessageBox::Ignore);
- ignoreButton->setToolTip(tr("Continue with local changes in working directory."));
+ ignoreButton->setToolTip(tr("Execute %1 with local changes in working directory.")
+ .arg(command));
}
QPushButton *cancelButton = msgBox.addButton(QMessageBox::Cancel);
- cancelButton->setToolTip(tr("Cancel current command."));
+ cancelButton->setToolTip(tr("Cancel %1.").arg(command));
msgBox.exec();
if (msgBox.clickedButton() == discardButton) {
- if (!m_client->synchronousReset(m_workingDir, QStringList(), errorMessage))
- m_stashResult = StashFailed;
- else
- m_stashResult = StashUnchanged;
+ m_stashResult = m_client->synchronousReset(m_workingDir, QStringList(), errorMessage) ?
+ StashUnchanged : StashFailed;
} else if (msgBox.clickedButton() == ignoreButton) { // At your own risk, so.
m_stashResult = NotStashed;
} else if (msgBox.clickedButton() == cancelButton) {
m_stashResult = StashCanceled;
} else if (msgBox.clickedButton() == stashButton) {
- executeStash(keyword, errorMessage);
+ m_stashResult = m_client->executeSynchronousStash(m_workingDir,
+ creatorStashMessage(command), errorMessage) ? StashUnchanged : StashFailed;
+ } else if (msgBox.clickedButton() == stashAndPopButton) {
+ executeStash(command, errorMessage);
}
}
-void GitClient::StashInfo::executeStash(const QString &keyword, QString *errorMessage)
+void GitClient::StashInfo::executeStash(const QString &command, QString *errorMessage)
{
- m_message = creatorStashMessage(keyword);
+ m_message = creatorStashMessage(command);
if (!m_client->executeSynchronousStash(m_workingDir, m_message, errorMessage))
m_stashResult = StashFailed;
else
diff --git a/src/plugins/git/gitclient.h b/src/plugins/git/gitclient.h
index 22e552d7da..610a08498e 100644
--- a/src/plugins/git/gitclient.h
+++ b/src/plugins/git/gitclient.h
@@ -33,7 +33,6 @@
#include "gitsettings.h"
#include <coreplugin/editormanager/ieditor.h>
-#include <vcsbase/command.h>
#include <QObject>
#include <QString>
@@ -52,8 +51,10 @@ namespace Core {
}
namespace VcsBase {
- class VcsBaseEditorWidget;
+ class Command;
class SubmitFileModel;
+ class VcsBaseEditorWidget;
+ class VcsBaseEditorParameterWidget;
}
namespace Utils {
@@ -109,15 +110,15 @@ public:
enum StashResult { StashUnchanged, StashCanceled, StashFailed,
Stashed, NotStashed /* User did not want it */ };
- bool init(const QString &workingDirectory, const QString &keyword, StashFlag flag = Default);
+ bool init(const QString &workingDirectory, const QString &command, StashFlag flag = Default);
bool stashingFailed() const;
void end();
StashResult result() const { return m_stashResult; }
QString stashMessage() const { return m_message; }
private:
- void stashPrompt(const QString &keyword, const QString &statusOutput, QString *errorMessage);
- void executeStash(const QString &keyword, QString *errorMessage);
+ void stashPrompt(const QString &command, const QString &statusOutput, QString *errorMessage);
+ void executeStash(const QString &command, QString *errorMessage);
StashResult m_stashResult;
QString m_message;
@@ -137,17 +138,19 @@ public:
QString findRepositoryForDirectory(const QString &dir);
QString findGitDirForRepository(const QString &repositoryDir) const;
- void diff(const QString &workingDirectory, const QStringList &diffArgs, const QString &fileName);
- void diff(const QString &workingDirectory, const QStringList &diffArgs,
- const QStringList &unstagedFileNames, const QStringList &stagedFileNames= QStringList());
+ void diff(const QString &workingDirectory, const QString &fileName);
+ void diff(const QString &workingDirectory,
+ const QStringList &unstagedFileNames,
+ const QStringList &stagedFileNames = QStringList());
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 log(const QString &workingDirectory, const QStringList &fileNames = QStringList(),
+ void log(const QString &workingDirectory, const QString &fileName = QString(),
bool enableAnnotationContextMenu = false, const QStringList &args = QStringList());
+ void reflog(const QString &workingDirectory);
void blame(const QString &workingDirectory, const QStringList &args, const QString &fileName,
const QString &revision = QString(), int lineNumber = -1);
void reset(const QString &workingDirectory, const QString &argument, const QString &commit = QString());
@@ -169,7 +172,7 @@ public:
const QStringList &files = QStringList(),
QString *errorMessage = 0);
bool synchronousCleanList(const QString &workingDirectory, QStringList *files, QStringList *ignoredFiles, QString *errorMessage);
- bool synchronousApplyPatch(const QString &workingDirectory, const QString &file, QString *errorMessage);
+ bool synchronousApplyPatch(const QString &workingDirectory, const QString &file, QString *errorMessage, const QStringList &arguments = QStringList());
bool synchronousInit(const QString &workingDirectory);
bool synchronousCheckoutFiles(const QString &workingDirectory,
QStringList files = QStringList(),
@@ -200,8 +203,10 @@ public:
QString *errorMessage = 0);
bool synchronousBranchCmd(const QString &workingDirectory, QStringList branchArgs,
QString *output, QString *errorMessage);
+ bool synchronousTagCmd(const QString &workingDirectory, QStringList tagArgs,
+ QString *output, QString *errorMessage);
bool synchronousForEachRefCmd(const QString &workingDirectory, QStringList args,
- QString *output, QString *errorMessage);
+ QString *output, QString *errorMessage = 0);
bool synchronousRemoteCmd(const QString &workingDirectory, QStringList remoteArgs,
QString *output, QString *errorMessage);
@@ -232,7 +237,10 @@ public:
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);
+ QString &precedes, QString &follows);
+ QStringList synchronousBranchesForCommit(const QString &workingDirectory,
+ const QString &revision);
+ bool isRemoteCommit(const QString &workingDirectory, const QString &commit);
bool cloneRepository(const QString &directory, const QByteArray &url);
QString vcsGetRepositoryURL(const QString &directory);
@@ -248,6 +256,9 @@ public:
void synchronousAbortCommand(const QString &workingDir, const QString &abortCommand);
QString synchronousTrackingBranch(const QString &workingDirectory,
const QString &branch = QString());
+ bool synchronousSetTrackingBranch(const QString &workingDirectory,
+ const QString &branch,
+ const QString &tracking);
// git svn support (asynchronous).
void synchronousSubversionFetch(const QString &workingDirectory);
@@ -287,14 +298,17 @@ public:
QString *errorMessage = 0);
CommandInProgress checkCommandInProgress(const QString &workingDirectory);
- CommandInProgress checkCommandInProgressInGitDir(const QString &gitDir);
+ QString commandInProgressDescription(const QString &workingDirectory);
void continueCommandIfNeeded(const QString &workingDirectory);
void continuePreviousGitCommand(const QString &workingDirectory, const QString &msgBoxTitle, QString msgBoxText,
const QString &buttonName, const QString &gitCommand, bool requireChanges = true);
+ QString extendedShowDescription(const QString &workingDirectory, const QString &text);
+
void launchGitK(const QString &workingDirectory, const QString &fileName);
void launchGitK(const QString &workingDirectory) { launchGitK(workingDirectory, QString()); }
+ bool launchGitGui(const QString &workingDirectory);
void launchRepositoryBrowser(const QString &workingDirectory);
@@ -304,7 +318,7 @@ public:
QProcessEnvironment processEnvironment() const;
- bool beginStashScope(const QString &workingDirectory, const QString &keyword, StashFlag flag = Default);
+ bool beginStashScope(const QString &workingDirectory, const QString &command, StashFlag flag = Default);
StashInfo &stashInfo(const QString &workingDirectory);
void endStashScope(const QString &workingDirectory);
bool isValidRevision(const QString &revision) const;
@@ -314,25 +328,23 @@ public:
static QString msgNoCommits(bool includeRemote);
public slots:
- void show(const QString &source, const QString &id,
- const QStringList &args = QStringList(), const QString &name = QString());
+ void show(const QString &source,
+ const QString &id,
+ const QStringList &args = QStringList(),
+ const QString &name = QString());
void saveSettings();
private slots:
void slotBlameRevisionRequested(const QString &source, QString change, int lineNumber);
- void appendOutputData(const QByteArray &data) const;
- void appendOutputDataSilently(const QByteArray &data) const;
void finishSubmoduleUpdate();
void fetchFinished(const QVariant &cookie);
private:
QTextCodec *getSourceCodec(const QString &file) const;
VcsBase::VcsBaseEditorWidget *findExistingVCSEditor(const char *registerDynamicProperty,
- const QString &dynamicPropertyValue) const;
- DiffEditor::DiffEditor *findExistingOrOpenNewDiffEditor(const char *registerDynamicProperty,
- const QString &dynamicPropertyValue,
- const QString &titlePattern,
- const Core::Id editorId) const;
+ const QString &dynamicPropertyValue) const;
+ DiffEditor::DiffEditor *findExistingDiffEditor(const char *registerDynamicProperty,
+ const QString &dynamicPropertyValue) const;
enum CodecType { CodecSource, CodecLogOutput, CodecNone };
VcsBase::VcsBaseEditorWidget *createVcsEditor(const Core::Id &kind,
@@ -341,7 +353,12 @@ private:
CodecType codecType,
const char *registerDynamicProperty,
const QString &dynamicPropertyValue,
- QWidget *configWidget) const;
+ VcsBase::VcsBaseEditorParameterWidget *configWidget) const;
+ DiffEditor::DiffEditor *createDiffEditor(const char *registerDynamicProperty,
+ const QString &dynamicPropertyValue,
+ const QString &source,
+ const QString &titlePattern,
+ const Core::Id editorId) const;
VcsBase::Command *createCommand(const QString &workingDirectory,
VcsBase::VcsBaseEditorWidget* editor = 0,
diff --git a/src/plugins/git/giteditor.cpp b/src/plugins/git/giteditor.cpp
index d8f6de88e4..7aa36ec7fe 100644
--- a/src/plugins/git/giteditor.cpp
+++ b/src/plugins/git/giteditor.cpp
@@ -44,9 +44,12 @@
#include <QFileInfo>
#include <QRegExp>
#include <QSet>
+#include <QTemporaryFile>
+#include <QDir>
#include <QTextCursor>
#include <QTextBlock>
+#include <QMessageBox>
#define CHANGE_PATTERN "[a-f0-9]{7,40}"
@@ -107,10 +110,9 @@ QString GitEditor::changeUnderCursor(const QTextCursor &c) const
return QString();
}
-VcsBase::BaseAnnotationHighlighter *GitEditor::createAnnotationHighlighter(const QSet<QString> &changes,
- const QColor &bg) const
+VcsBase::BaseAnnotationHighlighter *GitEditor::createAnnotationHighlighter(const QSet<QString> &changes) const
{
- return new GitAnnotationHighlighter(changes, bg);
+ return new GitAnnotationHighlighter(changes);
}
/* Remove the date specification from annotation, which is tabular:
@@ -118,25 +120,26 @@ VcsBase::BaseAnnotationHighlighter *GitEditor::createAnnotationHighlighter(const
8ca887aa (author YYYY-MM-DD HH:MM:SS <offset> <line>)<content>
\endcode */
-static QByteArray removeAnnotationDate(const QByteArray &b)
+static QString removeAnnotationDate(const QString &b)
{
if (b.isEmpty())
- return QByteArray();
+ return b;
- const int parenPos = b.indexOf(')');
+ const QChar space(QLatin1Char(' '));
+ const int parenPos = b.indexOf(QLatin1Char(')'));
if (parenPos == -1)
- return QByteArray(b);
+ return b;
int datePos = parenPos;
int i = parenPos;
- while (i >= 0 && b.at(i) != ' ')
+ while (i >= 0 && b.at(i) != space)
--i;
- while (i >= 0 && b.at(i) == ' ')
+ while (i >= 0 && b.at(i) == space)
--i;
int spaceCount = 0;
// i is now on timezone. Go back 3 spaces: That is where the date starts.
while (i >= 0) {
- if (b.at(i) == ' ')
+ if (b.at(i) == space)
++spaceCount;
if (spaceCount == 3) {
datePos = i;
@@ -145,33 +148,33 @@ static QByteArray removeAnnotationDate(const QByteArray &b)
--i;
}
if (datePos == 0)
- return QByteArray(b);
+ return b;
// Copy over the parts that have not changed into a new byte array
- QByteArray result;
+ QString result;
QTC_ASSERT(b.size() >= parenPos, return result);
int prevPos = 0;
- int pos = b.indexOf('\n', 0) + 1;
+ int pos = b.indexOf(QLatin1Char('\n'), 0) + 1;
forever {
QTC_CHECK(prevPos < pos);
int afterParen = prevPos + parenPos;
- result.append(b.constData() + prevPos, datePos);
- result.append(b.constData() + afterParen, pos - afterParen);
+ result.append(b.mid(prevPos, datePos));
+ result.append(b.mid(afterParen, pos - afterParen));
prevPos = pos;
QTC_CHECK(prevPos != 0);
if (pos == b.size())
break;
- pos = b.indexOf('\n', pos) + 1;
+ pos = b.indexOf(QLatin1Char('\n'), pos) + 1;
if (pos == 0) // indexOf returned -1
pos = b.size();
}
return result;
}
-void GitEditor::setPlainTextDataFiltered(const QByteArray &a)
+void GitEditor::setPlainTextFiltered(const QString &text)
{
- QByteArray array = a;
+ QString modText = text;
GitPlugin *plugin = GitPlugin::instance();
// If desired, filter out the date from annotation
switch (contentType())
@@ -179,22 +182,16 @@ void GitEditor::setPlainTextDataFiltered(const QByteArray &a)
case VcsBase::AnnotateOutput: {
const bool omitAnnotationDate = plugin->settings().boolValue(GitSettings::omitAnnotationDateKey);
if (omitAnnotationDate)
- array = removeAnnotationDate(a);
+ modText = removeAnnotationDate(text);
break;
}
case VcsBase::DiffOutput: {
- if (array.isEmpty())
- array = QByteArray("No difference to HEAD");
- const QFileInfo fi(source());
- const QString workingDirectory = fi.isDir() ? fi.absoluteFilePath() : 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');
+ if (modText.isEmpty()) {
+ modText = QLatin1String("No difference to HEAD");
+ } else {
+ const QFileInfo fi(source());
+ const QString workingDirectory = fi.isDir() ? fi.absoluteFilePath() : fi.absolutePath();
+ modText = plugin->gitClient()->extendedShowDescription(workingDirectory, modText);
}
break;
}
@@ -202,7 +199,7 @@ void GitEditor::setPlainTextDataFiltered(const QByteArray &a)
break;
}
- setPlainTextData(array);
+ setPlainText(modText);
}
void GitEditor::commandFinishedGotoLine(bool ok, int exitCode, const QVariant &v)
@@ -229,6 +226,53 @@ void GitEditor::revertChange()
GitPlugin::instance()->gitClient()->synchronousRevert(workingDirectory, m_currentChange);
}
+void GitEditor::stageDiffChunk()
+{
+ const QAction *a = qobject_cast<QAction *>(sender());
+ QTC_ASSERT(a, return);
+ const VcsBase::DiffChunk chunk = qvariant_cast<VcsBase::DiffChunk>(a->data());
+ return applyDiffChunk(chunk, false);
+}
+
+void GitEditor::unstageDiffChunk()
+{
+ const QAction *a = qobject_cast<QAction *>(sender());
+ QTC_ASSERT(a, return);
+ const VcsBase::DiffChunk chunk = qvariant_cast<VcsBase::DiffChunk>(a->data());
+ return applyDiffChunk(chunk, true);
+}
+
+void GitEditor::applyDiffChunk(const VcsBase::DiffChunk& chunk, bool revert)
+{
+ VcsBase::VcsBaseOutputWindow *outwin = VcsBase::VcsBaseOutputWindow::instance();
+ QTemporaryFile patchFile;
+ if (!patchFile.open())
+ return;
+
+ const QString baseDir = diffBaseDirectory();
+ patchFile.write(chunk.header);
+ patchFile.write(chunk.chunk);
+ patchFile.close();
+
+ GitClient *client = GitPlugin::instance()->gitClient();
+ QStringList args = QStringList() << QLatin1String("--cached");
+ if (revert)
+ args << QLatin1String("--reverse");
+ QString errorMessage;
+ if (client->synchronousApplyPatch(baseDir, patchFile.fileName(), &errorMessage, args)) {
+ if (errorMessage.isEmpty())
+ outwin->append(tr("Chunk successfully staged"));
+ else
+ outwin->append(errorMessage);
+ if (revert)
+ emit diffChunkReverted(chunk);
+ else
+ emit diffChunkApplied(chunk);
+ } else {
+ outwin->appendError(errorMessage);
+ }
+}
+
void GitEditor::init()
{
VcsBase::VcsBaseEditorWidget::init();
@@ -239,6 +283,19 @@ void GitEditor::init()
new GitRebaseHighlighter(baseTextDocument().data());
}
+void GitEditor::addDiffActions(QMenu *menu, const VcsBase::DiffChunk &chunk)
+{
+ menu->addSeparator();
+
+ QAction *stageAction = menu->addAction(tr("Stage Chunk..."));
+ stageAction->setData(qVariantFromValue(chunk));
+ connect(stageAction, SIGNAL(triggered()), this, SLOT(stageDiffChunk()));
+
+ QAction *unstageAction = menu->addAction(tr("Unstage Chunk..."));
+ unstageAction->setData(qVariantFromValue(chunk));
+ connect(unstageAction, SIGNAL(triggered()), this, SLOT(unstageDiffChunk()));
+}
+
bool GitEditor::open(QString *errorString, const QString &fileName, const QString &realFileName)
{
bool res = VcsBaseEditorWidget::open(errorString, fileName, realFileName);
diff --git a/src/plugins/git/giteditor.h b/src/plugins/git/giteditor.h
index b5539892c9..1ed80c7ccf 100644
--- a/src/plugins/git/giteditor.h
+++ b/src/plugins/git/giteditor.h
@@ -50,20 +50,24 @@ public:
QWidget *parent);
public slots:
- void setPlainTextDataFiltered(const QByteArray &a);
+ void setPlainTextFiltered(const QString &text);
// Matches the signature of the finished signal of GitCommand
void commandFinishedGotoLine(bool ok, int exitCode, const QVariant &v);
private slots:
void cherryPickChange();
void revertChange();
+ void stageDiffChunk();
+ void unstageDiffChunk();
+ void applyDiffChunk(const VcsBase::DiffChunk& chunk, bool revert);
private:
void init();
+ void addDiffActions(QMenu *menu, const VcsBase::DiffChunk &chunk);
bool open(QString *errorString, const QString &fileName, const QString &realFileName);
QSet<QString> annotationChanges() const;
QString changeUnderCursor(const QTextCursor &) const;
- VcsBase::BaseAnnotationHighlighter *createAnnotationHighlighter(const QSet<QString> &changes, const QColor &bg) const;
+ VcsBase::BaseAnnotationHighlighter *createAnnotationHighlighter(const QSet<QString> &changes) const;
QString decorateVersion(const QString &revision) const;
QStringList annotationPreviousVersions(const QString &revision) const;
bool isValidRevision(const QString &revision) const;
diff --git a/src/plugins/git/githighlighters.cpp b/src/plugins/git/githighlighters.cpp
index 2f00c9f2db..835b0f556d 100644
--- a/src/plugins/git/githighlighters.cpp
+++ b/src/plugins/git/githighlighters.cpp
@@ -27,9 +27,7 @@
**
****************************************************************************/
-#include <texteditor/fontsettings.h>
#include <texteditor/texteditorconstants.h>
-#include <texteditor/texteditorsettings.h>
#include <utils/qtcassert.h>
@@ -40,13 +38,6 @@ namespace Internal {
static const char CHANGE_PATTERN[] = "\\b[a-f0-9]{7,40}\\b";
-// Retrieve the comment char format from the text editor.
-static QTextCharFormat commentFormat()
-{
- const TextEditor::FontSettings settings = TextEditor::TextEditorSettings::instance()->fontSettings();
- return settings.toTextCharFormat(TextEditor::C_COMMENT);
-}
-
GitSubmitHighlighter::GitSubmitHighlighter(QTextEdit * parent) :
TextEditor::SyntaxHighlighter(parent)
{
@@ -61,7 +52,11 @@ GitSubmitHighlighter::GitSubmitHighlighter(TextEditor::BaseTextDocument *parent)
void GitSubmitHighlighter::initialize()
{
- m_commentFormat = commentFormat();
+ static QVector<TextEditor::TextStyle> categories;
+ if (categories.isEmpty())
+ categories << TextEditor::C_COMMENT;
+
+ setTextFormatCategories(categories);
m_keywordPattern.setPattern(QLatin1String("^[\\w-]+:"));
m_hashChar = QLatin1Char('#');
QTC_CHECK(m_keywordPattern.isValid());
@@ -77,7 +72,7 @@ void GitSubmitHighlighter::highlightBlock(const QString &text)
setCurrentBlockState(state);
return;
} else if (text.startsWith(m_hashChar)) {
- setFormat(0, text.size(), m_commentFormat);
+ setFormat(0, text.size(), formatForCategory(Format_Comment));
setCurrentBlockState(state);
return;
} else if (state == None) {
@@ -107,11 +102,10 @@ void GitSubmitHighlighter::highlightBlock(const QString &text)
}
GitRebaseHighlighter::RebaseAction::RebaseAction(const QString &regexp,
- const TextEditor::FontSettings &settings,
- TextEditor::TextStyle category)
- : exp(regexp)
+ const Format formatCategory)
+ : exp(regexp),
+ formatCategory(formatCategory)
{
- format = settings.toTextCharFormat(category);
}
GitRebaseHighlighter::GitRebaseHighlighter(TextEditor::BaseTextDocument *parent) :
@@ -119,26 +113,36 @@ GitRebaseHighlighter::GitRebaseHighlighter(TextEditor::BaseTextDocument *parent)
m_hashChar(QLatin1Char('#')),
m_changeNumberPattern(QLatin1String(CHANGE_PATTERN))
{
- const TextEditor::FontSettings settings = TextEditor::TextEditorSettings::instance()->fontSettings();
- m_commentFormat = settings.toTextCharFormat(TextEditor::C_COMMENT);
- m_changeFormat = settings.toTextCharFormat(TextEditor::C_DOXYGEN_COMMENT);
- m_descFormat = settings.toTextCharFormat(TextEditor::C_STRING);
- m_actions << RebaseAction(QLatin1String("^(p|pick)\\b"), settings, TextEditor::C_KEYWORD);
- m_actions << RebaseAction(QLatin1String("^(r|reword)\\b"), settings, TextEditor::C_FIELD);
- m_actions << RebaseAction(QLatin1String("^(e|edit)\\b"), settings, TextEditor::C_TYPE);
- m_actions << RebaseAction(QLatin1String("^(s|squash)\\b"), settings, TextEditor::C_ENUMERATION);
- m_actions << RebaseAction(QLatin1String("^(f|fixup)\\b"), settings, TextEditor::C_NUMBER);
- m_actions << RebaseAction(QLatin1String("^(x|exec)\\b"), settings, TextEditor::C_LABEL);
+ static QVector<TextEditor::TextStyle> categories;
+ if (categories.isEmpty()) {
+ categories << TextEditor::C_COMMENT
+ << TextEditor::C_DOXYGEN_COMMENT
+ << TextEditor::C_STRING
+ << TextEditor::C_KEYWORD
+ << TextEditor::C_FIELD
+ << TextEditor::C_TYPE
+ << TextEditor::C_ENUMERATION
+ << TextEditor::C_NUMBER
+ << TextEditor::C_LABEL;
+ }
+ setTextFormatCategories(categories);
+
+ m_actions << RebaseAction(QLatin1String("^(p|pick)\\b"), Format_Pick);
+ m_actions << RebaseAction(QLatin1String("^(r|reword)\\b"), Format_Reword);
+ m_actions << RebaseAction(QLatin1String("^(e|edit)\\b"), Format_Edit);
+ m_actions << RebaseAction(QLatin1String("^(s|squash)\\b"), Format_Squash);
+ m_actions << RebaseAction(QLatin1String("^(f|fixup)\\b"), Format_Fixup);
+ m_actions << RebaseAction(QLatin1String("^(x|exec)\\b"), Format_Exec);
}
void GitRebaseHighlighter::highlightBlock(const QString &text)
{
if (text.startsWith(m_hashChar)) {
- setFormat(0, text.size(), m_commentFormat);
+ setFormat(0, text.size(), formatForCategory(Format_Comment));
int changeIndex = 0;
while ((changeIndex = m_changeNumberPattern.indexIn(text, changeIndex)) != -1) {
const int changeLen = m_changeNumberPattern.matchedLength();
- setFormat(changeIndex, changeLen, m_changeFormat);
+ setFormat(changeIndex, changeLen, formatForCategory(Format_Change));
changeIndex += changeLen;
}
return;
@@ -147,13 +151,13 @@ void GitRebaseHighlighter::highlightBlock(const QString &text)
foreach (const RebaseAction &action, m_actions) {
if (action.exp.indexIn(text) != -1) {
const int len = action.exp.matchedLength();
- setFormat(0, len, action.format);
+ setFormat(0, len, formatForCategory(action.formatCategory));
const int changeIndex = m_changeNumberPattern.indexIn(text, len);
if (changeIndex != -1) {
const int changeLen = m_changeNumberPattern.matchedLength();
const int descStart = changeIndex + changeLen + 1;
- setFormat(changeIndex, changeLen, m_changeFormat);
- setFormat(descStart, text.size() - descStart, m_descFormat);
+ setFormat(changeIndex, changeLen, formatForCategory(Format_Change));
+ setFormat(descStart, text.size() - descStart, formatForCategory(Format_Description));
}
break;
}
diff --git a/src/plugins/git/githighlighters.h b/src/plugins/git/githighlighters.h
index 3d7f6e0621..888b615c72 100644
--- a/src/plugins/git/githighlighters.h
+++ b/src/plugins/git/githighlighters.h
@@ -31,7 +31,6 @@
#define GITHIGHLIGHTERS_H
#include <texteditor/syntaxhighlighter.h>
-#include <texteditor/texteditorconstants.h>
namespace TextEditor {
class FontSettings;
@@ -40,6 +39,18 @@ class FontSettings;
namespace Git {
namespace Internal {
+enum Format {
+ Format_Comment,
+ Format_Change,
+ Format_Description,
+ Format_Pick,
+ Format_Reword,
+ Format_Edit,
+ Format_Squash,
+ Format_Fixup,
+ Format_Exec
+};
+
// Highlighter for git submit messages. Make the first line bold, indicates
// comments as such (retrieving the format from the text editor) and marks up
// keywords (words in front of a colon as in 'Task: <bla>').
@@ -50,10 +61,10 @@ public:
explicit GitSubmitHighlighter(TextEditor::BaseTextDocument *parent);
void highlightBlock(const QString &text);
- void initialize();
private:
+ void initialize();
+
enum State { None = -1, Header, Other };
- QTextCharFormat m_commentFormat;
QRegExp m_keywordPattern;
QChar m_hashChar;
};
@@ -71,13 +82,9 @@ private:
{
public:
mutable QRegExp exp;
- QTextCharFormat format;
- RebaseAction(const QString &regexp, const TextEditor::FontSettings &settings,
- TextEditor::TextStyle category);
+ Format formatCategory;
+ RebaseAction(const QString &regexp, const Format formatCategory);
};
- QTextCharFormat m_commentFormat;
- QTextCharFormat m_changeFormat;
- QTextCharFormat m_descFormat;
const QChar m_hashChar;
QRegExp m_changeNumberPattern;
QList<RebaseAction> m_actions;
diff --git a/src/plugins/git/gitorious/gitorious.pri b/src/plugins/git/gitorious/gitorious.pri
index 8678042a26..ec285ed15a 100644
--- a/src/plugins/git/gitorious/gitorious.pri
+++ b/src/plugins/git/gitorious/gitorious.pri
@@ -1,5 +1,4 @@
QT += network
-INCLUDEPATH+=$$PWD
HEADERS += $$PWD/gitoriousclonewizard.h \
$$PWD/gitorioushostwizardpage.h \
diff --git a/src/plugins/git/gitorious/gitoriousclonewizard.cpp b/src/plugins/git/gitorious/gitoriousclonewizard.cpp
index baa7cdb463..9628832696 100644
--- a/src/plugins/git/gitorious/gitoriousclonewizard.cpp
+++ b/src/plugins/git/gitorious/gitoriousclonewizard.cpp
@@ -36,13 +36,11 @@
#include "../gitplugin.h"
#include <coreplugin/iversioncontrol.h>
-#include <vcsbase/checkoutjobs.h>
#include <vcsbase/vcsbaseconstants.h>
#include <vcsbase/vcsconfigurationpage.h>
#include <utils/qtcassert.h>
#include <QUrl>
-#include <QIcon>
namespace Gitorious {
namespace Internal {
@@ -71,25 +69,12 @@ void GitoriousCloneWizardPage::initializePage()
}
// -------- GitoriousCloneWizard
-GitoriousCloneWizard::GitoriousCloneWizard(QObject *parent) :
- VcsBase::BaseCheckoutWizard(parent)
+GitoriousCloneWizard::GitoriousCloneWizard()
{
setId(QLatin1String(VcsBase::Constants::VCS_ID_GIT));
-}
-
-QIcon GitoriousCloneWizard::icon() const
-{
- return QIcon(QLatin1String(":/git/images/gitorious.png"));
-}
-
-QString GitoriousCloneWizard::description() const
-{
- return tr("Clones a Gitorious repository and tries to load the contained project.");
-}
-
-QString GitoriousCloneWizard::displayName() const
-{
- return tr("Gitorious Repository Clone");
+ setIcon(QIcon(QLatin1String(":/git/images/gitorious.png")));
+ setDescription(tr("Clones a Gitorious repository and tries to load the contained project."));
+ setDisplayName(tr("Gitorious Repository Clone"));
}
QList<QWizardPage*> GitoriousCloneWizard::createParameterPages(const QString &path)
@@ -109,11 +94,11 @@ QList<QWizardPage*> GitoriousCloneWizard::createParameterPages(const QString &pa
return rc;
}
-QSharedPointer<VcsBase::AbstractCheckoutJob> GitoriousCloneWizard::createJob(const QList<QWizardPage*> &parameterPages,
- QString *checkoutPath)
+VcsBase::Command *GitoriousCloneWizard::createCommand(const QList<QWizardPage*> &parameterPages,
+ QString *checkoutPath)
{
const Git::CloneWizardPage *cwp = qobject_cast<const Git::CloneWizardPage *>(parameterPages.back());
- QTC_ASSERT(cwp, return QSharedPointer<VcsBase::AbstractCheckoutJob>());
+ QTC_ASSERT(cwp, return 0);
return cwp->createCheckoutJob(checkoutPath);
}
diff --git a/src/plugins/git/gitorious/gitoriousclonewizard.h b/src/plugins/git/gitorious/gitoriousclonewizard.h
index 6f7b9418a4..81bc86ee98 100644
--- a/src/plugins/git/gitorious/gitoriousclonewizard.h
+++ b/src/plugins/git/gitorious/gitoriousclonewizard.h
@@ -40,19 +40,15 @@ namespace Internal {
class GitoriousCloneWizard : public VcsBase::BaseCheckoutWizard
{
Q_OBJECT
-public:
- explicit GitoriousCloneWizard(QObject *parent = 0);
- // IWizard
- QIcon icon() const;
- QString description() const;
- QString displayName() const;
+public:
+ GitoriousCloneWizard();
-protected:
+private:
// BaseCheckoutWizard
QList<QWizardPage*> createParameterPages(const QString &path);
- QSharedPointer<VcsBase::AbstractCheckoutJob> createJob(const QList<QWizardPage*> &parameterPages,
- QString *checkoutPath);
+ VcsBase::Command *createCommand(const QList<QWizardPage*> &parameterPages,
+ QString *checkoutPath);
};
} // namespace Internal
diff --git a/src/plugins/git/gitplugin.cpp b/src/plugins/git/gitplugin.cpp
index 9f8ba007db..72d9f4bb6d 100644
--- a/src/plugins/git/gitplugin.cpp
+++ b/src/plugins/git/gitplugin.cpp
@@ -249,6 +249,7 @@ ActionCommandPair
{
const ActionCommandPair rc = createRepositoryAction(ac, text, id, context, addToLocator);
connect(rc.first, SIGNAL(triggered()), this, pluginSlot);
+ rc.first->setData(id.uniqueIdentifier());
return rc;
}
@@ -309,27 +310,27 @@ bool GitPlugin::initialize(const QStringList &arguments, QString *errorMessage)
m_menuAction = gitContainer->menu()->menuAction();
/* "Current File" menu */
- Core::ActionContainer *currentFileMenu = Core::ActionManager::createMenu(Core::Id("Git.CurrentFileMenu"));
+ Core::ActionContainer *currentFileMenu = Core::ActionManager::createMenu("Git.CurrentFileMenu");
currentFileMenu->menu()->setTitle(tr("Current &File"));
gitContainer->addMenu(currentFileMenu);
ParameterActionCommandPair parameterActionCommand
= createFileAction(currentFileMenu,
tr("Diff Current File"), tr("Diff of \"%1\""),
- Core::Id("Git.Diff"), globalcontext, true,
+ "Git.Diff", globalcontext, true,
SLOT(diffCurrentFile()));
parameterActionCommand.second->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+G,Meta+D") : tr("Alt+G,Alt+D")));
parameterActionCommand
= createFileAction(currentFileMenu,
tr("Log Current File"), tr("Log of \"%1\""),
- Core::Id("Git.Log"), globalcontext, true, SLOT(logFile()));
+ "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"),
+ "Git.Blame",
globalcontext, true, SLOT(blameFile()));
parameterActionCommand.second->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+G,Meta+B") : tr("Alt+G,Alt+B")));
@@ -339,24 +340,24 @@ bool GitPlugin::initialize(const QStringList &arguments, QString *errorMessage)
parameterActionCommand
= createFileAction(currentFileMenu,
tr("Stage File for Commit"), tr("Stage \"%1\" for Commit"),
- Core::Id("Git.Stage"), globalcontext, true, SLOT(stageFile()));
+ "Git.Stage", globalcontext, true, SLOT(stageFile()));
parameterActionCommand.second->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+G,Meta+A") : tr("Alt+G,Alt+A")));
parameterActionCommand
= createFileAction(currentFileMenu,
tr("Unstage File from Commit"), tr("Unstage \"%1\" from Commit"),
- Core::Id("Git.Unstage"), globalcontext, true, SLOT(unstageFile()));
+ "Git.Unstage", globalcontext, true, SLOT(unstageFile()));
parameterActionCommand
= createFileAction(currentFileMenu,
tr("Undo Unstaged Changes"), tr("Undo Unstaged Changes for \"%1\""),
- Core::Id("Git.UndoUnstaged"), globalcontext,
+ "Git.UndoUnstaged", globalcontext,
true, SLOT(undoUnstagedFileChanges()));
parameterActionCommand
= createFileAction(currentFileMenu,
tr("Undo Uncommitted Changes"), tr("Undo Uncommitted Changes for \"%1\""),
- Core::Id("Git.Undo"), globalcontext,
+ "Git.Undo", globalcontext,
true, SLOT(undoFileChanges()));
parameterActionCommand.second->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+G,Meta+U") : tr("Alt+G,Alt+U")));
@@ -365,29 +366,28 @@ bool GitPlugin::initialize(const QStringList &arguments, QString *errorMessage)
// ------------
/* "Current Project" menu */
- Core::ActionContainer *currentProjectMenu = Core::ActionManager::createMenu(Core::Id("Git.CurrentProjectMenu"));
+ Core::ActionContainer *currentProjectMenu = Core::ActionManager::createMenu("Git.CurrentProjectMenu");
currentProjectMenu->menu()->setTitle(tr("Current &Project"));
gitContainer->addMenu(currentProjectMenu);
parameterActionCommand
= createProjectAction(currentProjectMenu,
tr("Diff Current Project"), tr("Diff Project \"%1\""),
- Core::Id("Git.DiffProject"),
- globalcontext, true,
+ "Git.DiffProject", globalcontext, true,
SLOT(diffCurrentProject()));
parameterActionCommand.second->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+G,Meta+Shift+D") : tr("Alt+G,Alt+Shift+D")));
parameterActionCommand
= createProjectAction(currentProjectMenu,
tr("Log Project"), tr("Log Project \"%1\""),
- Core::Id("Git.LogProject"), globalcontext, true,
+ "Git.LogProject", globalcontext, true,
SLOT(logProject()));
parameterActionCommand.second->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+G,Meta+K") : tr("Alt+G,Alt+K")));
parameterActionCommand
= createProjectAction(currentProjectMenu,
tr("Clean Project..."), tr("Clean Project \"%1\"..."),
- Core::Id("Git.CleanProject"), globalcontext,
+ "Git.CleanProject", globalcontext,
true, SLOT(cleanProject()));
/* \"Current Project" menu */
@@ -395,106 +395,111 @@ bool GitPlugin::initialize(const QStringList &arguments, QString *errorMessage)
// --------------
/* "Local Repository" menu */
- Core::ActionContainer *localRepositoryMenu = Core::ActionManager::createMenu(Core::Id("Git.LocalRepositoryMenu"));
+ Core::ActionContainer *localRepositoryMenu = Core::ActionManager::createMenu("Git.LocalRepositoryMenu");
localRepositoryMenu->menu()->setTitle(tr("&Local Repository"));
gitContainer->addMenu(localRepositoryMenu);
createRepositoryAction(localRepositoryMenu,
- tr("Diff"), Core::Id("Git.DiffRepository"),
+ tr("Diff"), "Git.DiffRepository",
globalcontext, true, SLOT(diffRepository()));
createRepositoryAction(localRepositoryMenu,
- tr("Log"), Core::Id("Git.LogRepository"),
+ tr("Log"), "Git.LogRepository",
globalcontext, true,
SLOT(logRepository()));
createRepositoryAction(localRepositoryMenu,
- tr("Clean..."), Core::Id("Git.CleanRepository"),
+ tr("Reflog"), "Git.ReflogRepository",
+ globalcontext, true,
+ SLOT(reflogRepository()));
+
+ createRepositoryAction(localRepositoryMenu,
+ tr("Clean..."), "Git.CleanRepository",
globalcontext, true, SLOT(cleanRepository()));
createRepositoryAction(localRepositoryMenu,
- tr("Status"), Core::Id("Git.StatusRepository"),
+ tr("Status"), "Git.StatusRepository",
globalcontext, true, &GitClient::status);
// --------------
localRepositoryMenu->addSeparator(globalcontext);
ActionCommandPair actionCommand = createRepositoryAction(localRepositoryMenu,
- tr("Commit..."), Core::Id("Git.Commit"),
+ tr("Commit..."), "Git.Commit",
globalcontext, true, SLOT(startCommit()));
actionCommand.second->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+G,Meta+C") : tr("Alt+G,Alt+C")));
createRepositoryAction(localRepositoryMenu,
- tr("Amend Last Commit..."), Core::Id("Git.AmendCommit"),
+ tr("Amend Last Commit..."), "Git.AmendCommit",
globalcontext, true, SLOT(startAmendCommit()));
m_fixupCommitAction =
createRepositoryAction(localRepositoryMenu,
- tr("Fixup Previous Commit..."), Core::Id("Git.FixupCommit"),
+ tr("Fixup Previous Commit..."), "Git.FixupCommit",
globalcontext, true, SLOT(startFixupCommit())).first;
// --------------
localRepositoryMenu->addSeparator(globalcontext);
createRepositoryAction(localRepositoryMenu,
- tr("Reset..."), Core::Id("Git.Reset"),
+ tr("Reset..."), "Git.Reset",
globalcontext, true, SLOT(resetRepository()));
m_interactiveRebaseAction =
createRepositoryAction(localRepositoryMenu,
- tr("Interactive Rebase..."), Core::Id("Git.InteractiveRebase"),
+ tr("Interactive Rebase..."), "Git.InteractiveRebase",
globalcontext, true, SLOT(startRebase())).first;
m_submoduleUpdateAction =
createRepositoryAction(localRepositoryMenu,
- tr("Update Submodules"), Core::Id("Git.SubmoduleUpdate"),
+ tr("Update Submodules"), "Git.SubmoduleUpdate",
globalcontext, true, SLOT(updateSubmodules())).first;
m_abortMergeAction =
createRepositoryAction(localRepositoryMenu,
- tr("Abort Merge"), Core::Id("Git.MergeAbort"),
+ tr("Abort Merge"), "Git.MergeAbort",
globalcontext, true, SLOT(continueOrAbortCommand())).first;
m_abortRebaseAction =
createRepositoryAction(localRepositoryMenu,
- tr("Abort Rebase"), Core::Id("Git.RebaseAbort"),
+ tr("Abort Rebase"), "Git.RebaseAbort",
globalcontext, true, SLOT(continueOrAbortCommand())).first;
m_abortCherryPickAction =
createRepositoryAction(localRepositoryMenu,
- tr("Abort Cherry Pick"), Core::Id("Git.CherryPickAbort"),
+ tr("Abort Cherry Pick"), "Git.CherryPickAbort",
globalcontext, true, SLOT(continueOrAbortCommand())).first;
m_abortRevertAction =
createRepositoryAction(localRepositoryMenu,
- tr("Abort Revert"), Core::Id("Git.RevertAbort"),
+ tr("Abort Revert"), "Git.RevertAbort",
globalcontext, true, SLOT(continueOrAbortCommand())).first;
m_continueRebaseAction =
createRepositoryAction(localRepositoryMenu,
- tr("Continue Rebase"), Core::Id("Git.RebaseContinue"),
+ tr("Continue Rebase"), "Git.RebaseContinue",
globalcontext, true, SLOT(continueOrAbortCommand())).first;
m_continueCherryPickAction =
createRepositoryAction(localRepositoryMenu,
- tr("Continue Cherry Pick"), Core::Id("Git.CherryPickContinue"),
+ tr("Continue Cherry Pick"), "Git.CherryPickContinue",
globalcontext, true, SLOT(continueOrAbortCommand())).first;
m_continueRevertAction =
createRepositoryAction(localRepositoryMenu,
- tr("Continue Revert"), Core::Id("Git.RevertContinue"),
+ tr("Continue Revert"), "Git.RevertContinue",
globalcontext, true, SLOT(continueOrAbortCommand())).first;
// --------------
localRepositoryMenu->addSeparator(globalcontext);
createRepositoryAction(localRepositoryMenu,
- tr("Branches..."), Core::Id("Git.BranchList"),
+ tr("Branches..."), "Git.BranchList",
globalcontext, true, SLOT(branchList()));
// --------------
localRepositoryMenu->addSeparator(globalcontext);
// "Patch" menu
- Core::ActionContainer *patchMenu = Core::ActionManager::createMenu(Core::Id("Git.PatchMenu"));
+ Core::ActionContainer *patchMenu = Core::ActionManager::createMenu("Git.PatchMenu");
patchMenu->menu()->setTitle(tr("&Patch"));
localRepositoryMenu->addMenu(patchMenu);
@@ -502,41 +507,41 @@ bool GitPlugin::initialize(const QStringList &arguments, QString *errorMessage)
parameterActionCommand =
createParameterAction(patchMenu,
tr("Apply from Editor"), tr("Apply \"%1\""),
- Core::Id("Git.ApplyCurrentFilePatch"),
+ "Git.ApplyCurrentFilePatch",
globalcontext, true);
m_applyCurrentFilePatchAction = parameterActionCommand.first;
connect(m_applyCurrentFilePatchAction, SIGNAL(triggered()), this,
SLOT(applyCurrentFilePatch()));
createRepositoryAction(patchMenu,
- tr("Apply from File..."), Core::Id("Git.ApplyPatch"),
+ tr("Apply from File..."), "Git.ApplyPatch",
globalcontext, true, SLOT(promptApplyPatch()));
// "Stash" menu
- Core::ActionContainer *stashMenu = Core::ActionManager::createMenu(Core::Id("Git.StashMenu"));
+ Core::ActionContainer *stashMenu = Core::ActionManager::createMenu("Git.StashMenu");
stashMenu->menu()->setTitle(tr("&Stash"));
localRepositoryMenu->addMenu(stashMenu);
createRepositoryAction(stashMenu,
- tr("Stashes..."), Core::Id("Git.StashList"),
+ tr("Stashes..."), "Git.StashList",
globalcontext, false, SLOT(stashList()));
stashMenu->addSeparator(globalcontext);
actionCommand = createRepositoryAction(stashMenu,
- tr("Stash"), Core::Id("Git.Stash"),
+ tr("Stash"), "Git.Stash",
globalcontext, true, SLOT(stash()));
actionCommand.first->setToolTip(tr("Saves the current state of your work and resets the repository."));
actionCommand = createRepositoryAction(stashMenu,
- tr("Take Snapshot..."), Core::Id("Git.StashSnapshot"),
+ tr("Take Snapshot..."), "Git.StashSnapshot",
globalcontext, true, SLOT(stashSnapshot()));
actionCommand.first->setToolTip(tr("Saves the current state of your work."));
stashMenu->addSeparator(globalcontext);
actionCommand = createRepositoryAction(stashMenu,
- tr("Stash Pop"), Core::Id("Git.StashPop"),
+ tr("Stash Pop"), "Git.StashPop",
globalcontext, true, &GitClient::stashPop);
actionCommand.first->setToolTip(tr("Restores changes saved to the stash list using \"Stash\"."));
@@ -546,43 +551,43 @@ bool GitPlugin::initialize(const QStringList &arguments, QString *errorMessage)
// --------------
/* "Remote Repository" menu */
- Core::ActionContainer *remoteRepositoryMenu = Core::ActionManager::createMenu(Core::Id("Git.RemoteRepositoryMenu"));
+ Core::ActionContainer *remoteRepositoryMenu = Core::ActionManager::createMenu("Git.RemoteRepositoryMenu");
remoteRepositoryMenu->menu()->setTitle(tr("&Remote Repository"));
gitContainer->addMenu(remoteRepositoryMenu);
createRepositoryAction(remoteRepositoryMenu,
- tr("Fetch"), Core::Id("Git.Fetch"),
+ tr("Fetch"), "Git.Fetch",
globalcontext, true, SLOT(fetch()));
createRepositoryAction(remoteRepositoryMenu,
- tr("Pull"), Core::Id("Git.Pull"),
+ tr("Pull"), "Git.Pull",
globalcontext, true, SLOT(pull()));
actionCommand = createRepositoryAction(remoteRepositoryMenu,
- tr("Push"), Core::Id("Git.Push"),
+ tr("Push"), "Git.Push",
globalcontext, true, SLOT(push()));
// --------------
remoteRepositoryMenu->addSeparator(globalcontext);
// "Subversion" menu
- Core::ActionContainer *subversionMenu = Core::ActionManager::createMenu(Core::Id("Git.Subversion"));
+ Core::ActionContainer *subversionMenu = Core::ActionManager::createMenu("Git.Subversion");
subversionMenu->menu()->setTitle(tr("&Subversion"));
remoteRepositoryMenu->addMenu(subversionMenu);
createRepositoryAction(subversionMenu,
- tr("Log"), Core::Id("Git.Subversion.Log"),
+ tr("Log"), "Git.Subversion.Log",
globalcontext, false, &GitClient::subversionLog);
createRepositoryAction(subversionMenu,
- tr("Fetch"), Core::Id("Git.Subversion.Fetch"),
+ tr("Fetch"), "Git.Subversion.Fetch",
globalcontext, false, &GitClient::synchronousSubversionFetch);
// --------------
remoteRepositoryMenu->addSeparator(globalcontext);
createRepositoryAction(remoteRepositoryMenu,
- tr("Manage Remotes..."), Core::Id("Git.RemoteList"),
+ tr("Manage Remotes..."), "Git.RemoteList",
globalcontext, false, SLOT(remoteList()));
/* \"Remote Repository" menu */
@@ -590,22 +595,22 @@ bool GitPlugin::initialize(const QStringList &arguments, QString *errorMessage)
// --------------
/* Actions only in locator */
- createRepositoryAction(0, tr("Show..."), Core::Id("Git.Show"),
+ createRepositoryAction(0, tr("Show..."), "Git.Show",
globalcontext, true, SLOT(startChangeRelatedAction()));
- createRepositoryAction(0, tr("Revert..."), Core::Id("Git.Revert"),
+ createRepositoryAction(0, tr("Revert..."), "Git.Revert",
globalcontext, true, SLOT(startChangeRelatedAction()));
- createRepositoryAction(0, tr("Cherry Pick..."), Core::Id("Git.CherryPick"),
+ createRepositoryAction(0, tr("Cherry Pick..."), "Git.CherryPick",
globalcontext, true, SLOT(startChangeRelatedAction()));
- createRepositoryAction(0, tr("Checkout..."), Core::Id("Git.Checkout"),
+ createRepositoryAction(0, tr("Checkout..."), "Git.Checkout",
globalcontext, true, SLOT(startChangeRelatedAction()));
- createRepositoryAction(0, tr("Rebase..."), Core::Id("Git.Rebase"),
+ createRepositoryAction(0, tr("Rebase..."), "Git.Rebase",
globalcontext, true, SLOT(branchList()));
- createRepositoryAction(0, tr("Merge..."), Core::Id("Git.Merge"),
+ createRepositoryAction(0, tr("Merge..."), "Git.Merge",
globalcontext, true, SLOT(branchList()));
/* \Actions only in locator */
@@ -613,35 +618,41 @@ bool GitPlugin::initialize(const QStringList &arguments, QString *errorMessage)
// --------------
/* "Git Tools" menu */
- Core::ActionContainer *gitToolsMenu = Core::ActionManager::createMenu(Core::Id("Git.GitToolsMenu"));
+ Core::ActionContainer *gitToolsMenu = Core::ActionManager::createMenu("Git.GitToolsMenu");
gitToolsMenu->menu()->setTitle(tr("Git &Tools"));
gitContainer->addMenu(gitToolsMenu);
createRepositoryAction(gitToolsMenu,
- tr("Gitk"), Core::Id("Git.LaunchGitK"),
+ tr("Gitk"), "Git.LaunchGitK",
globalcontext, true, &GitClient::launchGitK);
parameterActionCommand
= createFileAction(gitToolsMenu,
tr("Gitk Current File"), tr("Gitk of \"%1\""),
- Core::Id("Git.GitkFile"), globalcontext, true, SLOT(gitkForCurrentFile()));
+ "Git.GitkFile", globalcontext, true, SLOT(gitkForCurrentFile()));
parameterActionCommand
= createFileAction(gitToolsMenu,
tr("Gitk for folder of Current File"), tr("Gitk for folder of \"%1\""),
- Core::Id("Git.GitkFolder"), globalcontext, true, SLOT(gitkForCurrentFolder()));
+ "Git.GitkFolder", globalcontext, true, SLOT(gitkForCurrentFolder()));
+
+ // --------------
+ gitToolsMenu->addSeparator(globalcontext);
+
+ createRepositoryAction(gitToolsMenu, tr("Git Gui"), "Git.GitGui",
+ globalcontext, true, SLOT(gitGui()));
// --------------
gitToolsMenu->addSeparator(globalcontext);
m_repositoryBrowserAction
= createRepositoryAction(gitToolsMenu,
- tr("Repository Browser"), Core::Id("Git.LaunchRepositoryBrowser"),
+ tr("Repository Browser"), "Git.LaunchRepositoryBrowser",
globalcontext, true, &GitClient::launchRepositoryBrowser).first;
m_mergeToolAction =
createRepositoryAction(gitToolsMenu,
- tr("Merge Tool"), Core::Id("Git.MergeTool"),
+ tr("Merge Tool"), "Git.MergeTool",
globalcontext, true, SLOT(startMergeTool())).first;
/* \"Git Tools" menu */
@@ -687,12 +698,12 @@ bool GitPlugin::initialize(const QStringList &arguments, QString *errorMessage)
m_redoAction = new QAction(tr("&Redo"), this);
command = Core::ActionManager::registerAction(m_redoAction, Core::Constants::REDO, submitContext);
- connect(Core::ICore::vcsManager(), SIGNAL(repositoryChanged(QString)),
+ connect(Core::VcsManager::instance(), SIGNAL(repositoryChanged(QString)),
this, SLOT(updateContinueAndAbortCommands()));
- connect(Core::ICore::vcsManager(), SIGNAL(repositoryChanged(QString)),
+ connect(Core::VcsManager::instance(), SIGNAL(repositoryChanged(QString)),
this, SLOT(updateBranches(QString)), Qt::QueuedConnection);
- if (!Core::ICore::mimeDatabase()->addMimeTypes(QLatin1String(RC_GIT_MIME_XML), errorMessage))
+ if (!Core::MimeDatabase::addMimeTypes(QLatin1String(RC_GIT_MIME_XML), errorMessage))
return false;
/* "Gerrit" */
@@ -711,7 +722,7 @@ GitVersionControl *GitPlugin::gitVersionControl() const
void GitPlugin::submitEditorDiff(const QStringList &unstaged, const QStringList &staged)
{
- m_gitClient->diff(m_submitRepository, QStringList(), unstaged, staged);
+ m_gitClient->diff(m_submitRepository, unstaged, staged);
}
void GitPlugin::submitEditorMerge(const QStringList &unmerged)
@@ -731,28 +742,30 @@ void GitPlugin::diffCurrentFile()
{
const VcsBase::VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasFile(), return);
- m_gitClient->diff(state.currentFileTopLevel(), QStringList(), state.relativeCurrentFile());
+ m_gitClient->diff(state.currentFileTopLevel(), state.relativeCurrentFile());
}
void GitPlugin::diffCurrentProject()
{
const VcsBase::VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasProject(), return);
- m_gitClient->diff(state.currentProjectTopLevel(), QStringList(), state.relativeCurrentProject());
+ const QString relativeProject = state.relativeCurrentProject();
+ m_gitClient->diff(state.currentProjectTopLevel(),
+ relativeProject.isEmpty() ? QStringList() : QStringList(relativeProject));
}
void GitPlugin::diffRepository()
{
const VcsBase::VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasTopLevel(), return);
- m_gitClient->diff(state.topLevel(), QStringList(), QStringList());
+ m_gitClient->diff(state.topLevel(), QStringList());
}
void GitPlugin::logFile()
{
const VcsBase::VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasFile(), return);
- m_gitClient->log(state.currentFileTopLevel(), QStringList(state.relativeCurrentFile()), true);
+ m_gitClient->log(state.currentFileTopLevel(), state.relativeCurrentFile(), true);
}
void GitPlugin::blameFile()
@@ -777,6 +790,13 @@ void GitPlugin::logRepository()
m_gitClient->log(state.topLevel());
}
+void GitPlugin::reflogRepository()
+{
+ const VcsBase::VcsBasePluginState state = currentState();
+ QTC_ASSERT(state.hasTopLevel(), return);
+ m_gitClient->reflog(state.topLevel());
+}
+
void GitPlugin::undoFileChanges(bool revertStaging)
{
if (!ensureAllDocumentsSaved())
@@ -833,7 +853,9 @@ void GitPlugin::startChangeRelatedAction()
if (!state.hasTopLevel())
return;
- ChangeSelectionDialog dialog(state.topLevel(), Core::ICore::mainWindow());
+ QAction *action = qobject_cast<QAction *>(sender());
+ Core::Id id = action ? Core::Id::fromUniqueIdentifier(action->data().toInt()) : Core::Id();
+ ChangeSelectionDialog dialog(state.topLevel(), id, Core::ICore::mainWindow());
int result = dialog.exec();
@@ -853,28 +875,23 @@ void GitPlugin::startChangeRelatedAction()
if (!ensureAllDocumentsSaved())
return;
- QString command;
bool (GitClient::*commandFunction)(const QString&, const QString&);
switch (dialog.command()) {
case CherryPick:
- command = QLatin1String("Cherry-pick");
commandFunction = &GitClient::synchronousCherryPick;
break;
case Revert:
- command = QLatin1String("Revert");
commandFunction = &GitClient::synchronousRevert;
break;
case Checkout:
- command = QLatin1String("Checkout");
+ if (!m_gitClient->beginStashScope(workingDirectory, QLatin1String("Checkout")))
+ return;
commandFunction = &GitClient::synchronousCheckout;
break;
default:
return;
}
- if (!m_gitClient->beginStashScope(workingDirectory, command))
- return;
-
(m_gitClient->*commandFunction)(workingDirectory, change);
}
@@ -919,9 +936,9 @@ void GitPlugin::gitkForCurrentFolder()
*
*/
QDir dir(state.currentFileDirectory());
- if (QFileInfo(dir,QLatin1String(".git")).exists() || dir.cd(QLatin1String(".git")))
+ if (QFileInfo(dir,QLatin1String(".git")).exists() || dir.cd(QLatin1String(".git"))) {
m_gitClient->launchGitK(state.currentFileDirectory());
- else {
+ } else {
QString folderName = dir.absolutePath();
dir.cdUp();
folderName = folderName.remove(0, dir.absolutePath().length() + 1);
@@ -929,6 +946,13 @@ void GitPlugin::gitkForCurrentFolder()
}
}
+void GitPlugin::gitGui()
+{
+ const VcsBase::VcsBasePluginState state = currentState();
+ QTC_ASSERT(state.hasTopLevel(), return);
+ m_gitClient->launchGitGui(state.topLevel());
+}
+
void GitPlugin::startAmendCommit()
{
startCommit(AmendCommit);
@@ -959,7 +983,7 @@ void GitPlugin::startCommit(CommitType commitType)
QString errorMessage, commitTemplate;
CommitData data(commitType);
if (!m_gitClient->getCommitData(state.topLevel(), &commitTemplate, data, &errorMessage)) {
- VcsBase::VcsBaseOutputWindow::instance()->append(errorMessage);
+ VcsBase::VcsBaseOutputWindow::instance()->appendError(errorMessage);
return;
}
@@ -973,7 +997,7 @@ void GitPlugin::startCommit(CommitType commitType)
saver.setAutoRemove(false);
saver.write(commitTemplate.toLocal8Bit());
if (!saver.finalize()) {
- VcsBase::VcsBaseOutputWindow::instance()->append(saver.errorString());
+ VcsBase::VcsBaseOutputWindow::instance()->appendError(saver.errorString());
return;
}
m_commitMessageFileName = saver.fileName();
@@ -985,10 +1009,7 @@ void GitPlugin::updateVersionWarning()
unsigned version = m_gitClient->gitVersion();
if (!version || version >= minimumRequiredVersion)
return;
- Core::IEditor *curEditor = Core::EditorManager::currentEditor();
- if (!curEditor)
- return;
- Core::IDocument *curDocument = curEditor->document();
+ Core::IDocument *curDocument = Core::EditorManager::currentDocument();
if (!curDocument)
return;
Core::InfoBar *infoBar = curDocument->infoBar();
@@ -1023,7 +1044,7 @@ Core::IEditor *GitPlugin::openSubmitEditor(const QString &fileName, const Commit
default:
title = tr("Git Commit");
}
- submitEditor->setDisplayName(title);
+ submitEditor->document()->setDisplayName(title);
connect(submitEditor, SIGNAL(diff(QStringList,QStringList)), this, SLOT(submitEditorDiff(QStringList,QStringList)));
connect(submitEditor, SIGNAL(merge(QStringList)), this, SLOT(submitEditorMerge(QStringList)));
connect(submitEditor, SIGNAL(show(QString,QString)), m_gitClient, SLOT(show(QString,QString)));
@@ -1034,7 +1055,7 @@ void GitPlugin::submitCurrentLog()
{
// Close the submit editor
m_submitActionTriggered = true;
- Core::ICore::editorManager()->closeEditor();
+ Core::EditorManager::closeEditor();
}
bool GitPlugin::submitEditorAboutToClose()
@@ -1047,7 +1068,7 @@ bool GitPlugin::submitEditorAboutToClose()
QTC_ASSERT(editorDocument, return true);
// Submit editor closing. Make it write out the commit message
// and retrieve files
- const QFileInfo editorFile(editorDocument->fileName());
+ const QFileInfo editorFile(editorDocument->filePath());
const QFileInfo changeFile(m_commitMessageFileName);
// Paranoia!
if (editorFile.absoluteFilePath() != changeFile.absoluteFilePath())
@@ -1100,6 +1121,14 @@ bool GitPlugin::submitEditorAboutToClose()
m_gitClient->continueCommandIfNeeded(m_submitRepository);
}
}
+
+ if (m_gitClient->checkCommandInProgress(m_submitRepository) == GitClient::NoCommand) {
+ if (editor->panelData().pushAction == CommitAndPush)
+ m_gitClient->push(m_submitRepository);
+ else if (editor->panelData().pushAction == CommitAndPushToGerrit)
+ connect(editor, SIGNAL(destroyed()), this, SLOT(delayedPushToGerrit()));
+ }
+
return closeEditor;
}
@@ -1115,7 +1144,7 @@ void GitPlugin::pull()
const VcsBase::VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasTopLevel(), return);
QString topLevel = state.topLevel();
- bool rebase = m_gitClient->settings()->boolValue(GitSettings::pullRebaseKey);
+ bool rebase = m_settings.boolValue(GitSettings::pullRebaseKey);
if (!rebase) {
QString currentBranch = m_gitClient->synchronousCurrentLocalBranch(topLevel);
@@ -1245,16 +1274,11 @@ void GitPlugin::updateSubmodules()
// If the file is modified in an editor, make sure it is saved.
static bool ensureFileSaved(const QString &fileName)
{
- const QList<Core::IEditor*> editors = Core::EditorManager::instance()->editorsForFileName(fileName);
- if (editors.isEmpty())
- return true;
- Core::IDocument *document = editors.front()->document();
+ Core::IDocument *document = Core::EditorManager::documentModel()->documentForFilePath(fileName);
if (!document || !document->isModified())
return true;
bool canceled;
- QList<Core::IDocument *> documents;
- documents << document;
- Core::DocumentManager::saveModifiedDocuments(documents, &canceled);
+ Core::DocumentManager::saveModifiedDocuments(QList<Core::IDocument *>() << document, &canceled);
return !canceled;
}
@@ -1296,9 +1320,9 @@ void GitPlugin::applyPatch(const QString &workingDirectory, QString file)
QString errorMessage;
if (m_gitClient->synchronousApplyPatch(workingDirectory, file, &errorMessage)) {
if (errorMessage.isEmpty())
- outwin->append(tr("Patch %1 successfully applied to %2").arg(file, workingDirectory));
+ outwin->appendMessage(tr("Patch %1 successfully applied to %2").arg(file, workingDirectory));
else
- outwin->append(errorMessage);
+ outwin->appendError(errorMessage);
} else {
outwin->appendError(errorMessage);
}
@@ -1429,6 +1453,11 @@ void GitPlugin::updateContinueAndAbortCommands()
}
}
+void GitPlugin::delayedPushToGerrit()
+{
+ m_gerritPlugin->push(m_submitRepository);
+}
+
void GitPlugin::updateBranches(const QString &repository)
{
if (m_branchDialog && m_branchDialog->isVisible())
@@ -1438,7 +1467,7 @@ void GitPlugin::updateBranches(const QString &repository)
void GitPlugin::updateRepositoryBrowserAction()
{
const bool repositoryEnabled = currentState().hasTopLevel();
- const bool hasRepositoryBrowserCmd = !settings().stringValue(GitSettings::repositoryBrowserCmd).isEmpty();
+ const bool hasRepositoryBrowserCmd = !m_settings.stringValue(GitSettings::repositoryBrowserCmd).isEmpty();
m_repositoryBrowserAction->setEnabled(repositoryEnabled && hasRepositoryBrowserCmd);
}
diff --git a/src/plugins/git/gitplugin.h b/src/plugins/git/gitplugin.h
index 468d54dca3..f451834f30 100644
--- a/src/plugins/git/gitplugin.h
+++ b/src/plugins/git/gitplugin.h
@@ -32,7 +32,7 @@
#include "gitsettings.h"
-#include "vcsbase/vcsbaseplugin.h"
+#include <vcsbase/vcsbaseplugin.h>
#include <QStringList>
#include <QPointer>
@@ -115,6 +115,7 @@ private slots:
void blameFile();
void logProject();
void logRepository();
+ void reflogRepository();
void undoFileChanges(bool revertStaging = true);
void undoUnstagedFileChanges();
void resetRepository();
@@ -124,6 +125,7 @@ private slots:
void unstageFile();
void gitkForCurrentFile();
void gitkForCurrentFolder();
+ void gitGui();
void cleanProject();
void cleanRepository();
void updateSubmodules();
@@ -144,6 +146,7 @@ private slots:
void startMergeTool();
void continueOrAbortCommand();
void updateContinueAndAbortCommands();
+ void delayedPushToGerrit();
#ifdef WITH_TESTS
void testStatusParsing_data();
diff --git a/src/plugins/git/gitsettings.cpp b/src/plugins/git/gitsettings.cpp
index 64feea302e..197c13d724 100644
--- a/src/plugins/git/gitsettings.cpp
+++ b/src/plugins/git/gitsettings.cpp
@@ -48,6 +48,7 @@ const QLatin1String GitSettings::gitkOptionsKey("GitKOptions");
const QLatin1String GitSettings::logDiffKey("LogDiff");
const QLatin1String GitSettings::repositoryBrowserCmd("RepositoryBrowserCmd");
const QLatin1String GitSettings::graphLogKey("GraphLog");
+const QLatin1String GitSettings::lastResetIndexKey("LastResetIndex");
GitSettings::GitSettings()
{
@@ -68,6 +69,7 @@ GitSettings::GitSettings()
declareKey(logDiffKey, false);
declareKey(repositoryBrowserCmd, QString());
declareKey(graphLogKey, false);
+ declareKey(lastResetIndexKey, 0);
}
QString GitSettings::gitBinaryPath(bool *ok, QString *errorMessage) const
diff --git a/src/plugins/git/gitsettings.h b/src/plugins/git/gitsettings.h
index dcf5fd940e..33980173b7 100644
--- a/src/plugins/git/gitsettings.h
+++ b/src/plugins/git/gitsettings.h
@@ -61,6 +61,7 @@ public:
static const QLatin1String logDiffKey;
static const QLatin1String repositoryBrowserCmd;
static const QLatin1String graphLogKey;
+ static const QLatin1String lastResetIndexKey;
QString gitBinaryPath(bool *ok = 0, QString *errorMessage = 0) const;
diff --git a/src/plugins/git/gitsubmiteditor.cpp b/src/plugins/git/gitsubmiteditor.cpp
index d318580b51..7cd2ad9e93 100644
--- a/src/plugins/git/gitsubmiteditor.cpp
+++ b/src/plugins/git/gitsubmiteditor.cpp
@@ -111,9 +111,7 @@ void GitSubmitEditor::setCommitData(const CommitData &d)
m_amendSHA1 = d.amendSHA1;
GitSubmitEditorWidget *w = submitEditorWidget();
- w->initialize(m_commitType, m_workingDirectory);
- w->setPanelData(d.panelData);
- w->setPanelInfo(d.panelInfo);
+ w->initialize(m_commitType, m_workingDirectory, d.panelData, d.panelInfo);
w->setHasUnmerged(false);
setEmptyFileListEnabled(m_commitType == AmendCommit); // Allow for just correcting the message
@@ -179,9 +177,9 @@ void GitSubmitEditor::updateFileModel()
setCommitData(data);
submitEditorWidget()->refreshLog(m_workingDirectory);
} else {
- VcsBase::VcsBaseOutputWindow::instance()->append(errorMessage);
+ VcsBase::VcsBaseOutputWindow::instance()->appendError(errorMessage);
m_forceClose = true;
- Core::EditorManager::instance()->closeEditors(QList<IEditor*>() << this);
+ Core::EditorManager::closeEditor(this);
}
}
diff --git a/src/plugins/git/gitsubmiteditorwidget.cpp b/src/plugins/git/gitsubmiteditorwidget.cpp
index 9e94200674..133e5583f0 100644
--- a/src/plugins/git/gitsubmiteditorwidget.cpp
+++ b/src/plugins/git/gitsubmiteditorwidget.cpp
@@ -39,6 +39,7 @@
#include <QGroupBox>
#include <QRegExp>
#include <QVBoxLayout>
+#include <QMenu>
namespace Git {
namespace Internal {
@@ -46,6 +47,7 @@ namespace Internal {
// ------------------
GitSubmitEditorWidget::GitSubmitEditorWidget(QWidget *parent) :
VcsBase::SubmitEditorWidget(parent),
+ m_pushAction(CommitOnly),
m_gitSubmitPanel(new QWidget),
m_logChangeWidget(0),
m_hasUnmerged(false),
@@ -82,7 +84,10 @@ void GitSubmitEditorWidget::setHasUnmerged(bool e)
m_hasUnmerged = e;
}
-void GitSubmitEditorWidget::initialize(CommitType commitType, const QString &repository)
+void GitSubmitEditorWidget::initialize(CommitType commitType,
+ const QString &repository,
+ const GitSubmitEditorPanelData &data,
+ const GitSubmitEditorPanelInfo &info)
{
if (m_isInitialized)
return;
@@ -100,6 +105,16 @@ void GitSubmitEditorWidget::initialize(CommitType commitType, const QString &rep
hideDescription();
}
insertTopWidget(m_gitSubmitPanel);
+ setPanelData(data);
+ setPanelInfo(info);
+
+ if (data.hasRemotes && commitType != FixupCommit) {
+ QMenu *menu = new QMenu(this);
+ menu->addAction(tr("Commit only"), this, SLOT(commitOnlySlot()));
+ menu->addAction(tr("Commit and Push"), this, SLOT(commitAndPushSlot()));
+ menu->addAction(tr("Commit and Push to Gerrit"), this, SLOT(commitAndPushToGerritSlot()));
+ addSubmitButtonMenu(menu);
+ }
}
void GitSubmitEditorWidget::refreshLog(const QString &repository)
@@ -114,6 +129,7 @@ GitSubmitEditorPanelData GitSubmitEditorWidget::panelData() const
rc.author = m_gitSubmitPanelUi.authorLineEdit->text();
rc.email = m_gitSubmitPanelUi.emailLineEdit->text();
rc.bypassHooks = m_gitSubmitPanelUi.bypassHooksCheckBox->isChecked();
+ rc.pushAction = m_pushAction;
return rc;
}
@@ -153,6 +169,16 @@ QString GitSubmitEditorWidget::cleanupDescription(const QString &input) const
}
+QString GitSubmitEditorWidget::commitName() const
+{
+ if (m_pushAction == CommitAndPush)
+ return tr("Commit and Push");
+ else if (m_pushAction == CommitAndPushToGerrit)
+ return tr("Commit and Push to Gerrit");
+
+ return tr("Commit");
+}
+
void GitSubmitEditorWidget::authorInformationChanged()
{
bool bothEmpty = m_gitSubmitPanelUi.authorLineEdit->text().isEmpty() &&
@@ -166,6 +192,24 @@ void GitSubmitEditorWidget::authorInformationChanged()
updateSubmitAction();
}
+void GitSubmitEditorWidget::commitOnlySlot()
+{
+ m_pushAction = CommitOnly;
+ updateSubmitAction();
+}
+
+void GitSubmitEditorWidget::commitAndPushSlot()
+{
+ m_pushAction = CommitAndPush;
+ updateSubmitAction();
+}
+
+void GitSubmitEditorWidget::commitAndPushToGerritSlot()
+{
+ m_pushAction = CommitAndPushToGerrit;
+ updateSubmitAction();
+}
+
bool GitSubmitEditorWidget::emailIsValid() const
{
int pos = m_gitSubmitPanelUi.emailLineEdit->cursorPosition();
diff --git a/src/plugins/git/gitsubmiteditorwidget.h b/src/plugins/git/gitsubmiteditorwidget.h
index 36f80b5230..73043cdaf3 100644
--- a/src/plugins/git/gitsubmiteditorwidget.h
+++ b/src/plugins/git/gitsubmiteditorwidget.h
@@ -32,6 +32,7 @@
#include "ui_gitsubmitpanel.h"
#include "gitsettings.h"
+#include "commitdata.h"
#include <texteditor/syntaxhighlighter.h>
#include <vcsbase/submiteditorwidget.h>
@@ -66,26 +67,34 @@ public:
explicit GitSubmitEditorWidget(QWidget *parent = 0);
GitSubmitEditorPanelData panelData() const;
- void setPanelData(const GitSubmitEditorPanelData &data);
- void setPanelInfo(const GitSubmitEditorPanelInfo &info);
QString amendSHA1() const;
void setHasUnmerged(bool e);
- void initialize(CommitType commitType, const QString &repository);
+ void initialize(CommitType commitType,
+ const QString &repository,
+ const GitSubmitEditorPanelData &data,
+ const GitSubmitEditorPanelInfo &info);
void refreshLog(const QString &repository);
protected:
bool canSubmit() const;
QString cleanupDescription(const QString &) const;
+ QString commitName() const;
signals:
void show(const QString &commit);
private slots:
void authorInformationChanged();
+ void commitOnlySlot();
+ void commitAndPushSlot();
+ void commitAndPushToGerritSlot();
private:
bool emailIsValid() const;
+ void setPanelData(const GitSubmitEditorPanelData &data);
+ void setPanelInfo(const GitSubmitEditorPanelInfo &info);
+ PushAction m_pushAction;
QWidget *m_gitSubmitPanel;
LogChangeWidget *m_logChangeWidget;
Ui::GitSubmitPanel m_gitSubmitPanelUi;
diff --git a/src/plugins/git/gitversioncontrol.cpp b/src/plugins/git/gitversioncontrol.cpp
index 845050d0cc..b98e9ea350 100644
--- a/src/plugins/git/gitversioncontrol.cpp
+++ b/src/plugins/git/gitversioncontrol.cpp
@@ -124,7 +124,11 @@ QString GitVersionControl::vcsGetRepositoryURL(const QString &directory)
QString GitVersionControl::vcsTopic(const QString &directory)
{
- return m_client->synchronousTopic(directory);
+ QString topic = m_client->synchronousTopic(directory);
+ const QString commandInProgress = m_client->commandInProgressDescription(directory);
+ if (!commandInProgress.isEmpty())
+ topic += QLatin1String(" (") + commandInProgress + QLatin1Char(')');
+ return topic;
}
/* Snapshots are implemented using stashes, relying on stash messages for
diff --git a/src/plugins/git/logchangedialog.cpp b/src/plugins/git/logchangedialog.cpp
index 3dba3eb3a7..f96cb5b137 100644
--- a/src/plugins/git/logchangedialog.cpp
+++ b/src/plugins/git/logchangedialog.cpp
@@ -180,6 +180,9 @@ LogChangeDialog::LogChangeDialog(bool isReset, QWidget *parent) :
m_resetTypeComboBox->addItem(tr("Hard"), QLatin1String("--hard"));
m_resetTypeComboBox->addItem(tr("Mixed"), QLatin1String("--mixed"));
m_resetTypeComboBox->addItem(tr("Soft"), QLatin1String("--soft"));
+ GitClient *client = GitPlugin::instance()->gitClient();
+ m_resetTypeComboBox->setCurrentIndex(client->settings()->intValue(
+ GitSettings::lastResetIndexKey));
popUpLayout->addWidget(m_resetTypeComboBox);
popUpLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Ignored));
}
@@ -203,7 +206,15 @@ bool LogChangeDialog::runDialog(const QString &repository, const QString &commit
if (!widget->init(repository, commit, includeRemote))
return false;
- return QDialog::exec() == QDialog::Accepted;
+ if (QDialog::exec() == QDialog::Accepted) {
+ if (m_resetTypeComboBox) {
+ GitClient *client = GitPlugin::instance()->gitClient();
+ client->settings()->setValue(GitSettings::lastResetIndexKey,
+ m_resetTypeComboBox->currentIndex());
+ }
+ return true;
+ }
+ return false;
}
QString LogChangeDialog::commit() const
diff --git a/src/plugins/git/mergetool.cpp b/src/plugins/git/mergetool.cpp
index 1bf3a439fd..9e565b76f4 100644
--- a/src/plugins/git/mergetool.cpp
+++ b/src/plugins/git/mergetool.cpp
@@ -102,8 +102,7 @@ bool MergeTool::start(const QString &workingDirectory, const QStringList &files)
if (m_process->waitForStarted()) {
connect(m_process, SIGNAL(finished(int)), this, SLOT(done()));
connect(m_process, SIGNAL(readyRead()), this, SLOT(readData()));
- }
- else {
+ } else {
delete m_process;
m_process = 0;
return false;
@@ -263,10 +262,11 @@ void MergeTool::done()
const QString workingDirectory = m_process->workingDirectory();
int exitCode = m_process->exitCode();
if (!exitCode) {
- outputWindow->append(tr("Merge tool process finished successully."));
+ outputWindow->appendMessage(tr("Merge tool process finished successully."));
m_gitClient->continueCommandIfNeeded(workingDirectory);
} else {
- outputWindow->append(tr("Merge tool process terminated with exit code %1").arg(exitCode));
+ outputWindow->appendError(tr("Merge tool process terminated with exit code %1")
+ .arg(exitCode));
}
GitPlugin::instance()->gitVersionControl()->emitRepositoryChanged(workingDirectory);
deleteLater();
diff --git a/src/plugins/git/remotedialog.cpp b/src/plugins/git/remotedialog.cpp
index 9807816829..db4cb86759 100644
--- a/src/plugins/git/remotedialog.cpp
+++ b/src/plugins/git/remotedialog.cpp
@@ -118,16 +118,15 @@ RemoteDialog::~RemoteDialog()
void RemoteDialog::refresh(const QString &repository, bool force)
{
- if (m_repository == repository && !force)
+ if (m_remoteModel->workingDirectory() == repository && !force)
return;
// Refresh
- m_repository = repository;
- m_ui->repositoryLabel->setText(StashDialog::msgRepositoryLabel(m_repository));
- if (m_repository.isEmpty()) {
+ m_ui->repositoryLabel->setText(StashDialog::msgRepositoryLabel(repository));
+ if (repository.isEmpty()) {
m_remoteModel->clear();
} else {
QString errorMessage;
- if (!m_remoteModel->refresh(m_repository, &errorMessage))
+ if (!m_remoteModel->refresh(repository, &errorMessage))
VcsBase::VcsBaseOutputWindow::instance()->appendError(errorMessage);
}
}
diff --git a/src/plugins/git/remotedialog.h b/src/plugins/git/remotedialog.h
index 7a8d00900b..7ab485ef04 100644
--- a/src/plugins/git/remotedialog.h
+++ b/src/plugins/git/remotedialog.h
@@ -92,8 +92,6 @@ private:
RemoteModel *m_remoteModel;
RemoteAdditionDialog *m_addDialog;
-
- QString m_repository;
};
} // namespace Internal
diff --git a/src/plugins/git/remotemodel.cpp b/src/plugins/git/remotemodel.cpp
index d7ad7a3147..b6f0933e7c 100644
--- a/src/plugins/git/remotemodel.cpp
+++ b/src/plugins/git/remotemodel.cpp
@@ -177,6 +177,8 @@ void RemoteModel::clear()
bool RemoteModel::refresh(const QString &workingDirectory, QString *errorMessage)
{
+ m_workingDirectory = workingDirectory;
+
// get list of remotes.
QMap<QString,QString> remotesList =
m_client->synchronousRemotesList(workingDirectory, errorMessage);
@@ -184,7 +186,6 @@ bool RemoteModel::refresh(const QString &workingDirectory, QString *errorMessage
if (remotesList.isEmpty())
return false;
- m_workingDirectory = workingDirectory;
beginResetModel();
m_remotes.clear();
foreach (const QString &remoteName, remotesList.keys()) {
diff --git a/src/plugins/git/settingspage.cpp b/src/plugins/git/settingspage.cpp
index 08b4875e44..a76d07bc2c 100644
--- a/src/plugins/git/settingspage.cpp
+++ b/src/plugins/git/settingspage.cpp
@@ -70,7 +70,6 @@ GitSettings SettingsPageWidget::settings() const
rc.setValue(GitSettings::pathKey, m_ui.pathLineEdit->text());
rc.setValue(GitSettings::logCountKey, m_ui.logCountSpinBox->value());
rc.setValue(GitSettings::timeoutKey, m_ui.timeoutSpinBox->value());
- rc.setValue(GitSettings::useDiffEditorKey, m_ui.useDiffEditorCheckBox->isChecked());
rc.setValue(GitSettings::pullRebaseKey, m_ui.pullRebaseCheckBox->isChecked());
rc.setValue(GitSettings::showTagsKey, m_ui.showTagsCheckBox->isChecked());
rc.setValue(GitSettings::promptOnSubmitKey, m_ui.promptToSubmitCheckBox->isChecked());
@@ -85,7 +84,6 @@ void SettingsPageWidget::setSettings(const GitSettings &s)
m_ui.pathLineEdit->setText(s.stringValue(GitSettings::pathKey));
m_ui.logCountSpinBox->setValue(s.intValue(GitSettings::logCountKey));
m_ui.timeoutSpinBox->setValue(s.intValue(GitSettings::timeoutKey));
- m_ui.useDiffEditorCheckBox->setChecked(s.boolValue(GitSettings::useDiffEditorKey));
m_ui.pullRebaseCheckBox->setChecked(s.boolValue(GitSettings::pullRebaseKey));
m_ui.showTagsCheckBox->setChecked(s.boolValue(GitSettings::showTagsKey));
m_ui.promptToSubmitCheckBox->setChecked(s.boolValue(GitSettings::promptOnSubmitKey));
diff --git a/src/plugins/git/settingspage.ui b/src/plugins/git/settingspage.ui
index 26b51f527f..5e010df2a3 100644
--- a/src/plugins/git/settingspage.ui
+++ b/src/plugins/git/settingspage.ui
@@ -7,7 +7,7 @@
<x>0</x>
<y>0</y>
<width>705</width>
- <height>436</height>
+ <height>459</height>
</rect>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
@@ -60,32 +60,25 @@
<string>Miscellaneous</string>
</property>
<layout class="QGridLayout" name="gridLayout">
- <item row="0" column="0">
- <widget class="QLabel" name="logCountLabel">
+ <item row="2" column="0" colspan="2">
+ <widget class="QCheckBox" name="pullRebaseCheckBox">
<property name="text">
- <string>Log count:</string>
+ <string>Pull with rebase</string>
</property>
</widget>
</item>
- <item row="0" column="1">
- <widget class="QSpinBox" name="logCountSpinBox">
- <property name="toolTip">
- <string>Note that huge amount of commits might take some time.</string>
- </property>
- <property name="maximum">
- <number>1000</number>
- </property>
- <property name="value">
- <number>1000</number>
+ <item row="0" column="4">
+ <spacer name="horizontalSpacer">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
</property>
- </widget>
- </item>
- <item row="0" column="2">
- <widget class="QLabel" name="timeoutLabel">
- <property name="text">
- <string>Timeout:</string>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>211</width>
+ <height>20</height>
+ </size>
</property>
- </widget>
+ </spacer>
</item>
<item row="0" column="3">
<widget class="QSpinBox" name="timeoutSpinBox">
@@ -103,19 +96,6 @@
</property>
</widget>
</item>
- <item row="0" column="4">
- <spacer name="horizontalSpacer">
- <property name="orientation">
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>211</width>
- <height>20</height>
- </size>
- </property>
- </spacer>
- </item>
<item row="1" column="0" colspan="2">
<widget class="QCheckBox" name="promptToSubmitCheckBox">
<property name="text">
@@ -123,24 +103,37 @@
</property>
</widget>
</item>
- <item row="2" column="0" colspan="2">
- <widget class="QCheckBox" name="pullRebaseCheckBox">
+ <item row="0" column="0">
+ <widget class="QLabel" name="logCountLabel">
<property name="text">
- <string>Pull with rebase</string>
+ <string>Log count:</string>
</property>
</widget>
</item>
- <item row="1" column="3" colspan="2">
- <widget class="QCheckBox" name="showTagsCheckBox">
+ <item row="0" column="2">
+ <widget class="QLabel" name="timeoutLabel">
<property name="text">
- <string>Show tags in Branches dialog</string>
+ <string>Timeout:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="1">
+ <widget class="QSpinBox" name="logCountSpinBox">
+ <property name="toolTip">
+ <string>Note that huge amount of commits might take some time.</string>
+ </property>
+ <property name="maximum">
+ <number>1000</number>
+ </property>
+ <property name="value">
+ <number>1000</number>
</property>
</widget>
</item>
- <item row="2" column="3">
- <widget class="QCheckBox" name="useDiffEditorCheckBox">
+ <item row="3" column="0">
+ <widget class="QCheckBox" name="showTagsCheckBox">
<property name="text">
- <string>Show diff side-by-side</string>
+ <string>Show tags in Branches dialog</string>
</property>
</widget>
</item>
diff --git a/src/plugins/glsleditor/GLSLEditor.pluginspec.in b/src/plugins/glsleditor/GLSLEditor.pluginspec.in
index cb29e65f99..d584804ead 100644
--- a/src/plugins/glsleditor/GLSLEditor.pluginspec.in
+++ b/src/plugins/glsleditor/GLSLEditor.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"GLSLEditor\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"GLSLEditor\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/glsleditor/glslautocompleter.cpp b/src/plugins/glsleditor/glslautocompleter.cpp
index 22e2cb0cda..5f5747c469 100644
--- a/src/plugins/glsleditor/glslautocompleter.cpp
+++ b/src/plugins/glsleditor/glslautocompleter.cpp
@@ -85,8 +85,7 @@ bool GLSLCompleter::contextAllowsElectricCharacters(const QTextCursor &cursor) c
if (pos < tk.end())
return false;
- }
- else if (tk.isStringLiteral() || tk.isCharLiteral()) {
+ } else if (tk.isStringLiteral() || tk.isCharLiteral()) {
const unsigned pos = cursor.selectionEnd() - cursor.block().position();
if (pos <= tk.end())
return false;
diff --git a/src/plugins/glsleditor/glslcompletionassist.h b/src/plugins/glsleditor/glslcompletionassist.h
index 81d5c0a547..bf75cfe31f 100644
--- a/src/plugins/glsleditor/glslcompletionassist.h
+++ b/src/plugins/glsleditor/glslcompletionassist.h
@@ -55,6 +55,8 @@ class GLSLCompletionAssistInterface;
class GLSLCompletionAssistProvider : public TextEditor::CompletionAssistProvider
{
+ Q_OBJECT
+
public:
virtual bool supportsEditor(const Core::Id &editorId) const;
virtual TextEditor::IAssistProcessor *createProcessor() const;
diff --git a/src/plugins/glsleditor/glsleditor.cpp b/src/plugins/glsleditor/glsleditor.cpp
index 844e61b380..f7cdc00336 100644
--- a/src/plugins/glsleditor/glsleditor.cpp
+++ b/src/plugins/glsleditor/glsleditor.cpp
@@ -51,8 +51,6 @@
#include <coreplugin/mimedatabase.h>
#include <extensionsystem/pluginmanager.h>
#include <texteditor/basetextdocument.h>
-#include <texteditor/fontsettings.h>
-#include <texteditor/tabsettings.h>
#include <texteditor/texteditorconstants.h>
#include <texteditor/texteditorsettings.h>
#include <texteditor/syntaxhighlighter.h>
@@ -64,7 +62,7 @@
#include <QFileInfo>
#include <QSignalMapper>
#include <QTimer>
-#include <QDebug>
+#include <QTextBlock>
#include <QMenu>
#include <QComboBox>
@@ -193,56 +191,25 @@ Core::IEditor *GLSLEditorEditable::duplicate(QWidget *parent)
{
GLSLTextEditorWidget *newEditor = new GLSLTextEditorWidget(parent);
newEditor->duplicateFrom(editorWidget());
- GLSLEditorPlugin::instance()->initializeEditor(newEditor);
+ GLSLEditorPlugin::initializeEditor(newEditor);
return newEditor->editor();
}
Core::Id GLSLEditorEditable::id() const
{
- return Core::Id(GLSLEditor::Constants::C_GLSLEDITOR_ID);
+ return GLSLEditor::Constants::C_GLSLEDITOR_ID;
}
bool GLSLEditorEditable::open(QString *errorString, const QString &fileName, const QString &realFileName)
{
- editorWidget()->setMimeType(Core::ICore::mimeDatabase()->findByFile(QFileInfo(fileName)).type());
+ editorWidget()->setMimeType(Core::MimeDatabase::findByFile(QFileInfo(fileName)).type());
bool b = TextEditor::BaseTextEditor::open(errorString, fileName, realFileName);
return b;
}
-void GLSLTextEditorWidget::setFontSettings(const TextEditor::FontSettings &fs)
+TextEditor::CompletionAssistProvider *GLSLEditorEditable::completionAssistProvider()
{
- TextEditor::BaseTextEditorWidget::setFontSettings(fs);
- Highlighter *highlighter = qobject_cast<Highlighter*>(baseTextDocument()->syntaxHighlighter());
- if (!highlighter)
- return;
-
- /*
- NumberFormat,
- StringFormat,
- TypeFormat,
- KeywordFormat,
- LabelFormat,
- CommentFormat,
- VisualWhitespace,
- */
- static QVector<TextEditor::TextStyle> categories;
- if (categories.isEmpty()) {
- categories << TextEditor::C_NUMBER
- << TextEditor::C_STRING
- << TextEditor::C_TYPE
- << TextEditor::C_KEYWORD
- << TextEditor::C_OPERATOR
- << TextEditor::C_PREPROCESSOR
- << TextEditor::C_LABEL
- << TextEditor::C_COMMENT
- << TextEditor::C_DOXYGEN_COMMENT
- << TextEditor::C_DOXYGEN_TAG
- << TextEditor::C_VISUAL_WHITESPACE
- << TextEditor::C_REMOVED_LINE;
- }
-
- highlighter->setFormats(fs.toTextCharFormats(categories));
- highlighter->rehighlight();
+ return ExtensionSystem::PluginManager::getObject<GLSLCompletionAssistProvider>();
}
QString GLSLTextEditorWidget::wordUnderCursor() const
@@ -289,11 +256,6 @@ void GLSLTextEditorWidget::createToolBar(GLSLEditorEditable *editor)
editor->insertExtraToolBarWidget(TextEditor::BaseTextEditor::Left, m_outlineCombo);
}
-bool GLSLTextEditorWidget::event(QEvent *e)
-{
- return BaseTextEditorWidget::event(e);
-}
-
void GLSLTextEditorWidget::unCommentSelection()
{
Utils::unCommentSelection(this);
@@ -318,16 +280,19 @@ void GLSLTextEditorWidget::updateDocumentNow()
Parser parser(doc->_engine, preprocessedCode.constData(), preprocessedCode.size(), variant);
TranslationUnitAST *ast = parser.parse();
if (ast != 0 || extraSelections(CodeWarningsSelection).isEmpty()) {
- GLSLEditorPlugin *plugin = GLSLEditorPlugin::instance();
-
Semantic sem;
Scope *globalScope = engine->newNamespace();
doc->_globalScope = globalScope;
- sem.translationUnit(plugin->shaderInit(variant)->ast, globalScope, plugin->shaderInit(variant)->engine);
- if (variant & Lexer::Variant_VertexShader)
- sem.translationUnit(plugin->vertexShaderInit(variant)->ast, globalScope, plugin->vertexShaderInit(variant)->engine);
- if (variant & Lexer::Variant_FragmentShader)
- sem.translationUnit(plugin->fragmentShaderInit(variant)->ast, globalScope, plugin->fragmentShaderInit(variant)->engine);
+ const GLSLEditorPlugin::InitFile *file = GLSLEditorPlugin::shaderInit(variant);
+ sem.translationUnit(file->ast, globalScope, file->engine);
+ if (variant & Lexer::Variant_VertexShader) {
+ file = GLSLEditorPlugin::vertexShaderInit(variant);
+ sem.translationUnit(file->ast, globalScope, file->engine);
+ }
+ if (variant & Lexer::Variant_FragmentShader) {
+ file = GLSLEditorPlugin::fragmentShaderInit(variant);
+ sem.translationUnit(file->ast, globalScope, file->engine);
+ }
sem.translationUnit(ast, globalScope, engine);
CreateRanges createRanges(document(), doc);
@@ -404,11 +369,6 @@ int GLSLTextEditorWidget::languageVariant(const QString &type)
return variant;
}
-Document::Ptr GLSLTextEditorWidget::glslDocument() const
-{
- return m_glslDocument;
-}
-
TextEditor::IAssistInterface *GLSLTextEditorWidget::createAssistInterface(
TextEditor::AssistKind kind,
TextEditor::AssistReason reason) const
@@ -416,9 +376,9 @@ TextEditor::IAssistInterface *GLSLTextEditorWidget::createAssistInterface(
if (kind == TextEditor::Completion)
return new GLSLCompletionAssistInterface(document(),
position(),
- editor()->document()->fileName(),
+ editor()->document()->filePath(),
reason,
mimeType(),
- glslDocument());
+ m_glslDocument);
return BaseTextEditorWidget::createAssistInterface(kind, reason);
}
diff --git a/src/plugins/glsleditor/glsleditor.h b/src/plugins/glsleditor/glsleditor.h
index dbb8f0279b..1362a64e3d 100644
--- a/src/plugins/glsleditor/glsleditor.h
+++ b/src/plugins/glsleditor/glsleditor.h
@@ -30,8 +30,6 @@
#ifndef GLSLEDITOR_H
#define GLSLEDITOR_H
-#include "glsleditor_global.h"
-
#include <texteditor/basetexteditor.h>
#include <QSharedPointer>
@@ -46,19 +44,15 @@ namespace GLSL {
class Engine;
class TranslationUnitAST;
class Scope;
-}
-
-namespace Core {
-class ICore;
-}
+} // namespace GLSL
namespace GLSLEditor {
-class GLSLTextEditorWidget;
namespace Internal {
+
class GLSLEditorEditable;
-}
+class GLSLTextEditorWidget;
-class GLSLEDITOR_EXPORT Document
+class Document
{
public:
typedef QSharedPointer<Document> Ptr;
@@ -87,7 +81,7 @@ private:
friend class GLSLTextEditorWidget;
};
-class GLSLEDITOR_EXPORT GLSLTextEditorWidget : public TextEditor::BaseTextEditorWidget
+class GLSLTextEditorWidget : public TextEditor::BaseTextEditorWidget
{
Q_OBJECT
@@ -104,20 +98,14 @@ public:
static int languageVariant(const QString &mimeType);
- Document::Ptr glslDocument() const;
-
TextEditor::IAssistInterface *createAssistInterface(TextEditor::AssistKind assistKind,
TextEditor::AssistReason reason) const;
-public slots:
- virtual void setFontSettings(const TextEditor::FontSettings &);
-
private slots:
void updateDocument();
void updateDocumentNow();
protected:
- bool event(QEvent *e);
TextEditor::BaseTextEditor *createEditor();
void createToolBar(Internal::GLSLEditorEditable *editable);
@@ -130,6 +118,7 @@ private:
Document::Ptr m_glslDocument;
};
+} // namespace Internal
} // namespace GLSLEditor
#endif // GLSLEDITOR_H
diff --git a/src/plugins/glsleditor/glsleditor.pro b/src/plugins/glsleditor/glsleditor.pro
index aef8a138a1..e7f5375a74 100644
--- a/src/plugins/glsleditor/glsleditor.pro
+++ b/src/plugins/glsleditor/glsleditor.pro
@@ -5,13 +5,13 @@ DEFINES += \
HEADERS += \
glsleditor.h \
-glsleditor_global.h \
glsleditorconstants.h \
glsleditoreditable.h \
glsleditorfactory.h \
glsleditorplugin.h \
glslfilewizard.h \
glslhighlighter.h \
+glslhighlighterfactory.h \
glslautocompleter.h \
glslindenter.h \
glslhoverhandler.h \
@@ -25,6 +25,7 @@ glsleditorfactory.cpp \
glsleditorplugin.cpp \
glslfilewizard.cpp \
glslhighlighter.cpp \
+glslhighlighterfactory.cpp \
glslautocompleter.cpp \
glslindenter.cpp \
glslhoverhandler.cpp \
diff --git a/src/plugins/glsleditor/glsleditor.qbs b/src/plugins/glsleditor/glsleditor.qbs
index c34c479c31..d99571f1b5 100644
--- a/src/plugins/glsleditor/glsleditor.qbs
+++ b/src/plugins/glsleditor/glsleditor.qbs
@@ -21,7 +21,6 @@ QtcPlugin {
"glsleditor.cpp",
"glsleditor.h",
"glsleditor.qrc",
- "glsleditor_global.h",
"glsleditorconstants.h",
"glsleditoreditable.cpp",
"glsleditoreditable.h",
@@ -33,6 +32,8 @@ QtcPlugin {
"glslfilewizard.h",
"glslhighlighter.cpp",
"glslhighlighter.h",
+ "glslhighlighterfactory.cpp",
+ "glslhighlighterfactory.h",
"glslhoverhandler.cpp",
"glslhoverhandler.h",
"glslindenter.cpp",
diff --git a/src/plugins/glsleditor/glsleditoreditable.h b/src/plugins/glsleditor/glsleditoreditable.h
index 3e6ce0a529..d358af3d73 100644
--- a/src/plugins/glsleditor/glsleditoreditable.h
+++ b/src/plugins/glsleditor/glsleditoreditable.h
@@ -33,10 +33,10 @@
#include <texteditor/basetexteditor.h>
namespace GLSLEditor {
-class GLSLTextEditorWidget;
-
namespace Internal {
+class GLSLTextEditorWidget;
+
class GLSLEditorEditable : public TextEditor::BaseTextEditor
{
Q_OBJECT
@@ -47,8 +47,8 @@ public:
bool duplicateSupported() const { return true; }
Core::IEditor *duplicate(QWidget *parent);
Core::Id id() const;
- bool isTemporary() const { return false; }
bool open(QString *errorString, const QString &fileName, const QString &realFileName);
+ TextEditor::CompletionAssistProvider *completionAssistProvider();
};
} // namespace Internal
diff --git a/src/plugins/glsleditor/glsleditorfactory.cpp b/src/plugins/glsleditor/glsleditorfactory.cpp
index 09db817a9d..5afdfe65cb 100644
--- a/src/plugins/glsleditor/glsleditorfactory.cpp
+++ b/src/plugins/glsleditor/glsleditorfactory.cpp
@@ -37,14 +37,9 @@
#include <extensionsystem/pluginspec.h>
#include <coreplugin/icore.h>
-#include <coreplugin/editormanager/editormanager.h>
#include <QCoreApplication>
-#include <QFileInfo>
-#include <QDebug>
#include <QSettings>
-#include <QMessageBox>
-#include <QPushButton>
using namespace GLSLEditor::Internal;
using namespace GLSLEditor::Constants;
@@ -52,37 +47,22 @@ using namespace GLSLEditor::Constants;
GLSLEditorFactory::GLSLEditorFactory(QObject *parent)
: Core::IEditorFactory(parent)
{
- m_mimeTypes
- << QLatin1String(GLSLEditor::Constants::GLSL_MIMETYPE)
- << QLatin1String(GLSLEditor::Constants::GLSL_MIMETYPE_VERT)
- << QLatin1String(GLSLEditor::Constants::GLSL_MIMETYPE_FRAG)
- << QLatin1String(GLSLEditor::Constants::GLSL_MIMETYPE_VERT_ES)
- << QLatin1String(GLSLEditor::Constants::GLSL_MIMETYPE_FRAG_ES)
- ;
-}
-
-Core::Id GLSLEditorFactory::id() const
-{
- return Core::Id(C_GLSLEDITOR_ID);
-}
-
-QString GLSLEditorFactory::displayName() const
-{
- return qApp->translate("OpenWith::Editors", C_GLSLEDITOR_DISPLAY_NAME);
+ setId(C_GLSLEDITOR_ID);
+ setDisplayName(qApp->translate("OpenWith::Editors", C_GLSLEDITOR_DISPLAY_NAME));
+ addMimeType(GLSLEditor::Constants::GLSL_MIMETYPE);
+ addMimeType(GLSLEditor::Constants::GLSL_MIMETYPE_VERT);
+ addMimeType(GLSLEditor::Constants::GLSL_MIMETYPE_FRAG);
+ addMimeType(GLSLEditor::Constants::GLSL_MIMETYPE_VERT_ES);
+ addMimeType(GLSLEditor::Constants::GLSL_MIMETYPE_FRAG_ES);
}
Core::IEditor *GLSLEditorFactory::createEditor(QWidget *parent)
{
- GLSLEditor::GLSLTextEditorWidget *rc = new GLSLEditor::GLSLTextEditorWidget(parent);
- GLSLEditorPlugin::instance()->initializeEditor(rc);
+ GLSLTextEditorWidget *rc = new GLSLTextEditorWidget(parent);
+ GLSLEditorPlugin::initializeEditor(rc);
return rc->editor();
}
-QStringList GLSLEditorFactory::mimeTypes() const
-{
- return m_mimeTypes;
-}
-
void GLSLEditorFactory::updateEditorInfoBar(Core::IEditor *)
{
}
diff --git a/src/plugins/glsleditor/glsleditorfactory.h b/src/plugins/glsleditor/glsleditorfactory.h
index 34b68a3c9e..0932b3f556 100644
--- a/src/plugins/glsleditor/glsleditorfactory.h
+++ b/src/plugins/glsleditor/glsleditorfactory.h
@@ -32,8 +32,6 @@
#include <coreplugin/editormanager/ieditorfactory.h>
-#include <QStringList>
-
namespace GLSLEditor {
namespace Internal {
@@ -44,17 +42,10 @@ class GLSLEditorFactory : public Core::IEditorFactory
public:
GLSLEditorFactory(QObject *parent);
- // IEditorFactory
- QStringList mimeTypes() const;
- Core::Id id() const;
- QString displayName() const;
Core::IEditor *createEditor(QWidget *parent);
private slots:
void updateEditorInfoBar(Core::IEditor *editor);
-
-private:
- QStringList m_mimeTypes;
};
} // namespace Internal
diff --git a/src/plugins/glsleditor/glsleditorplugin.cpp b/src/plugins/glsleditor/glsleditorplugin.cpp
index 08d44956d5..43b30df305 100644
--- a/src/plugins/glsleditor/glsleditorplugin.cpp
+++ b/src/plugins/glsleditor/glsleditorplugin.cpp
@@ -34,6 +34,7 @@
#include "glslfilewizard.h"
#include "glslhoverhandler.h"
#include "glslcompletionassist.h"
+#include "glslhighlighterfactory.h"
#include <coreplugin/icore.h>
#include <coreplugin/coreconstants.h>
@@ -71,42 +72,67 @@ using namespace TextEditor;
namespace GLSLEditor {
namespace Internal {
-GLSLEditorPlugin *GLSLEditorPlugin::m_instance = 0;
+class GLSLEditorPluginPrivate
+{
+public:
+ GLSLEditorPluginPrivate() :
+ m_editor(0),
+ m_actionHandler(0),
+ m_glsl_120_frag(0),
+ m_glsl_120_vert(0),
+ m_glsl_120_common(0),
+ m_glsl_es_100_frag(0),
+ m_glsl_es_100_vert(0),
+ m_glsl_es_100_common(0)
+ {}
+
+ ~GLSLEditorPluginPrivate()
+ {
+ delete m_actionHandler;
+ delete m_glsl_120_frag;
+ delete m_glsl_120_vert;
+ delete m_glsl_120_common;
+ delete m_glsl_es_100_frag;
+ delete m_glsl_es_100_vert;
+ delete m_glsl_es_100_common;
+ }
+
+ GLSLEditorFactory *m_editor;
+ TextEditor::TextEditorActionHandler *m_actionHandler;
+ QPointer<TextEditor::ITextEditor> m_currentTextEditable;
+
+ GLSLEditorPlugin::InitFile *m_glsl_120_frag;
+ GLSLEditorPlugin::InitFile *m_glsl_120_vert;
+ GLSLEditorPlugin::InitFile *m_glsl_120_common;
+ GLSLEditorPlugin::InitFile *m_glsl_es_100_frag;
+ GLSLEditorPlugin::InitFile *m_glsl_es_100_vert;
+ GLSLEditorPlugin::InitFile *m_glsl_es_100_common;
+};
+
+static GLSLEditorPluginPrivate *dd = 0;
+static GLSLEditorPlugin *m_instance = 0;
GLSLEditorPlugin::InitFile::~InitFile()
{
delete engine;
}
-GLSLEditorPlugin::GLSLEditorPlugin() :
- m_editor(0),
- m_actionHandler(0),
- m_glsl_120_frag(0),
- m_glsl_120_vert(0),
- m_glsl_120_common(0),
- m_glsl_es_100_frag(0),
- m_glsl_es_100_vert(0),
- m_glsl_es_100_common(0)
+GLSLEditorPlugin::GLSLEditorPlugin()
{
m_instance = this;
+ dd = new GLSLEditorPluginPrivate;
}
GLSLEditorPlugin::~GLSLEditorPlugin()
{
- removeObject(m_editor);
- delete m_actionHandler;
- delete m_glsl_120_frag;
- delete m_glsl_120_vert;
- delete m_glsl_120_common;
- delete m_glsl_es_100_frag;
- delete m_glsl_es_100_vert;
- delete m_glsl_es_100_common;
+ removeObject(dd->m_editor);
+ delete dd;
m_instance = 0;
}
bool GLSLEditorPlugin::initialize(const QStringList & /*arguments*/, QString *errorMessage)
{
- if (!ICore::mimeDatabase()->addMimeTypes(QLatin1String(":/glsleditor/GLSLEditor.mimetypes.xml"), errorMessage))
+ if (!MimeDatabase::addMimeTypes(QLatin1String(":/glsleditor/GLSLEditor.mimetypes.xml"), errorMessage))
return false;
// m_modelManager = new ModelManager(this);
@@ -114,16 +140,16 @@ bool GLSLEditorPlugin::initialize(const QStringList & /*arguments*/, QString *er
addAutoReleasedObject(new GLSLHoverHandler(this));
- m_editor = new GLSLEditorFactory(this);
- addObject(m_editor);
+ dd->m_editor = new GLSLEditorFactory(this);
+ addObject(dd->m_editor);
addAutoReleasedObject(new GLSLCompletionAssistProvider);
- m_actionHandler = new TextEditorActionHandler(Constants::C_GLSLEDITOR_ID,
+ dd->m_actionHandler = new TextEditorActionHandler(Constants::C_GLSLEDITOR_ID,
TextEditorActionHandler::Format
| TextEditorActionHandler::UnCommentSelection
| TextEditorActionHandler::UnCollapseAll);
- m_actionHandler->initializeActions();
+ dd->m_actionHandler->initializeActions();
ActionContainer *contextMenu = ActionManager::createMenu(GLSLEditor::Constants::M_CONTEXT);
ActionContainer *glslToolsMenu = ActionManager::createMenu(Id(Constants::M_TOOLS_GLSL));
@@ -146,61 +172,65 @@ bool GLSLEditorPlugin::initialize(const QStringList & /*arguments*/, QString *er
errorMessage->clear();
- 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")),
- mimeDatabase->findByType(QLatin1String(GLSLEditor::Constants::GLSL_MIMETYPE_VERT)));
- iconProvider->registerIconOverlayForMimeType(QIcon(QLatin1String(":/glsleditor/images/glslfile.png")),
- mimeDatabase->findByType(QLatin1String(GLSLEditor::Constants::GLSL_MIMETYPE_FRAG)));
- iconProvider->registerIconOverlayForMimeType(QIcon(QLatin1String(":/glsleditor/images/glslfile.png")),
- mimeDatabase->findByType(QLatin1String(GLSLEditor::Constants::GLSL_MIMETYPE_VERT_ES)));
- iconProvider->registerIconOverlayForMimeType(QIcon(QLatin1String(":/glsleditor/images/glslfile.png")),
- mimeDatabase->findByType(QLatin1String(GLSLEditor::Constants::GLSL_MIMETYPE_FRAG_ES)));
-
- 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
+ FileIconProvider::registerIconOverlayForMimeType(":/glsleditor/images/glslfile.png", Constants::GLSL_MIMETYPE);
+ FileIconProvider::registerIconOverlayForMimeType(":/glsleditor/images/glslfile.png", Constants::GLSL_MIMETYPE_VERT);
+ FileIconProvider::registerIconOverlayForMimeType(":/glsleditor/images/glslfile.png", Constants::GLSL_MIMETYPE_FRAG);
+ FileIconProvider::registerIconOverlayForMimeType(":/glsleditor/images/glslfile.png", Constants::GLSL_MIMETYPE_VERT_ES);
+ FileIconProvider::registerIconOverlayForMimeType(":/glsleditor/images/glslfile.png", Constants::GLSL_MIMETYPE_FRAG_ES);
+
+ IWizard *wizard = new GLSLFileWizard(GLSLFileWizard::FragmentShaderES);
+ wizard->setWizardKind(IWizard::FileWizard);
+ wizard->setCategory(QLatin1String(Constants::WIZARD_CATEGORY_GLSL));
+ wizard->setDisplayCategory(QCoreApplication::translate("GLSLEditor", Constants::WIZARD_TR_CATEGORY_GLSL));
+ wizard->setDescription
(tr("Creates a fragment shader in the OpenGL/ES 2.0 Shading "
"Language (GLSL/ES). Fragment shaders generate the final "
"pixel colors for triangles, points and lines rendered "
"with OpenGL."));
- fragWizardParameters.setDisplayName(tr("Fragment Shader (OpenGL/ES 2.0)"));
- fragWizardParameters.setId(QLatin1String("F.GLSL"));
- addAutoReleasedObject(new GLSLFileWizard(fragWizardParameters, GLSLFileWizard::FragmentShaderES, core));
-
- BaseFileWizardParameters vertWizardParameters(IWizard::FileWizard);
- vertWizardParameters.setCategory(QLatin1String(Constants::WIZARD_CATEGORY_GLSL));
- vertWizardParameters.setDisplayCategory(QCoreApplication::translate("GLSLEditor", Constants::WIZARD_TR_CATEGORY_GLSL));
- vertWizardParameters.setDescription
+ wizard->setDisplayName(tr("Fragment Shader (OpenGL/ES 2.0)"));
+ wizard->setId(QLatin1String("F.GLSL"));
+ addAutoReleasedObject(wizard);
+
+ wizard = new GLSLFileWizard(GLSLFileWizard::VertexShaderES);
+ wizard->setWizardKind(IWizard::FileWizard);
+ wizard->setCategory(QLatin1String(Constants::WIZARD_CATEGORY_GLSL));
+ wizard->setDisplayCategory(QCoreApplication::translate("GLSLEditor", Constants::WIZARD_TR_CATEGORY_GLSL));
+ wizard->setDescription
(tr("Creates a vertex shader in the OpenGL/ES 2.0 Shading "
"Language (GLSL/ES). Vertex shaders transform the "
"positions, normals and texture co-ordinates of "
"triangles, points and lines rendered with OpenGL."));
- vertWizardParameters.setDisplayName(tr("Vertex Shader (OpenGL/ES 2.0)"));
- vertWizardParameters.setId(QLatin1String("G.GLSL"));
- addAutoReleasedObject(new GLSLFileWizard(vertWizardParameters, GLSLFileWizard::VertexShaderES, core));
-
- fragWizardParameters.setDescription
+ wizard->setDisplayName(tr("Vertex Shader (OpenGL/ES 2.0)"));
+ wizard->setId(QLatin1String("G.GLSL"));
+ addAutoReleasedObject(wizard);
+
+ wizard = new GLSLFileWizard(GLSLFileWizard::FragmentShaderDesktop);
+ wizard->setWizardKind(IWizard::FileWizard);
+ wizard->setCategory(QLatin1String(Constants::WIZARD_CATEGORY_GLSL));
+ wizard->setDisplayCategory(QCoreApplication::translate("GLSLEditor", Constants::WIZARD_TR_CATEGORY_GLSL));
+ wizard->setDescription
(tr("Creates a fragment shader in the Desktop OpenGL Shading "
"Language (GLSL). Fragment shaders generate the final "
"pixel colors for triangles, points and lines rendered "
"with OpenGL."));
- fragWizardParameters.setDisplayName(tr("Fragment Shader (Desktop OpenGL)"));
- fragWizardParameters.setId(QLatin1String("J.GLSL"));
- addAutoReleasedObject(new GLSLFileWizard(fragWizardParameters, GLSLFileWizard::FragmentShaderDesktop, core));
-
- vertWizardParameters.setDescription
+ wizard->setDisplayName(tr("Fragment Shader (Desktop OpenGL)"));
+ wizard->setId(QLatin1String("J.GLSL"));
+ addAutoReleasedObject(wizard);
+
+ wizard = new GLSLFileWizard(GLSLFileWizard::VertexShaderDesktop);
+ wizard->setWizardKind(IWizard::FileWizard);
+ wizard->setCategory(QLatin1String(Constants::WIZARD_CATEGORY_GLSL));
+ wizard->setDisplayCategory(QCoreApplication::translate("GLSLEditor", Constants::WIZARD_TR_CATEGORY_GLSL));
+ wizard->setDescription
(tr("Creates a vertex shader in the Desktop OpenGL Shading "
"Language (GLSL). Vertex shaders transform the "
"positions, normals and texture co-ordinates of "
"triangles, points and lines rendered with OpenGL."));
- vertWizardParameters.setDisplayName(tr("Vertex Shader (Desktop OpenGL)"));
- vertWizardParameters.setId(QLatin1String("K.GLSL"));
- addAutoReleasedObject(new GLSLFileWizard(vertWizardParameters, GLSLFileWizard::VertexShaderDesktop, core));
+ wizard->setDisplayName(tr("Vertex Shader (Desktop OpenGL)"));
+ wizard->setId(QLatin1String("K.GLSL"));
+ addAutoReleasedObject(wizard);
+
+ addAutoReleasedObject(new GLSLHighlighterFactory);
return true;
}
@@ -215,23 +245,14 @@ ExtensionSystem::IPlugin::ShutdownFlag GLSLEditorPlugin::aboutToShutdown()
return IPlugin::aboutToShutdown();
}
-void GLSLEditorPlugin::initializeEditor(GLSLEditor::GLSLTextEditorWidget *editor)
+void GLSLEditorPlugin::initializeEditor(GLSLTextEditorWidget *editor)
{
QTC_CHECK(m_instance);
- m_actionHandler->setupActions(editor);
- TextEditorSettings::instance()->initializeEditor(editor);
-}
-
-GLSLEditorPlugin::InitFile *GLSLEditorPlugin::getInitFile(const QString &fileName, InitFile **initFile) const
-{
- if (*initFile)
- return *initFile;
- *initFile = new GLSLEditorPlugin::InitFile;
- parseGlslFile(fileName, *initFile);
- return *initFile;
+ dd->m_actionHandler->setupActions(editor);
+ TextEditorSettings::initializeEditor(editor);
}
-QByteArray GLSLEditorPlugin::glslFile(const QString &fileName) const
+static QByteArray glslFile(const QString &fileName)
{
QFile file(ICore::resourcePath() + QLatin1String("/glsl/") + fileName);
if (file.open(QFile::ReadOnly))
@@ -239,7 +260,7 @@ QByteArray GLSLEditorPlugin::glslFile(const QString &fileName) const
return QByteArray();
}
-void GLSLEditorPlugin::parseGlslFile(const QString &fileName, InitFile *initFile) const
+static void parseGlslFile(const QString &fileName, GLSLEditorPlugin::InitFile *initFile)
{
// Parse the builtins for any langugage variant so we can use all keywords.
const int variant = GLSL::Lexer::Variant_All;
@@ -250,28 +271,37 @@ void GLSLEditorPlugin::parseGlslFile(const QString &fileName, InitFile *initFile
initFile->ast = parser.parse();
}
-const GLSLEditorPlugin::InitFile *GLSLEditorPlugin::fragmentShaderInit(int variant) const
+static GLSLEditorPlugin::InitFile *getInitFile(const char *fileName, GLSLEditorPlugin::InitFile **initFile)
+{
+ if (*initFile)
+ return *initFile;
+ *initFile = new GLSLEditorPlugin::InitFile;
+ parseGlslFile(QLatin1String(fileName), *initFile);
+ return *initFile;
+}
+
+const GLSLEditorPlugin::InitFile *GLSLEditorPlugin::fragmentShaderInit(int variant)
{
if (variant & GLSL::Lexer::Variant_GLSL_120)
- return getInitFile(QLatin1String("glsl_120.frag"), &m_glsl_120_frag);
+ return getInitFile("glsl_120.frag", &dd->m_glsl_120_frag);
else
- return getInitFile(QLatin1String("glsl_es_100.frag"), &m_glsl_es_100_frag);
+ return getInitFile("glsl_es_100.frag", &dd->m_glsl_es_100_frag);
}
-const GLSLEditorPlugin::InitFile *GLSLEditorPlugin::vertexShaderInit(int variant) const
+const GLSLEditorPlugin::InitFile *GLSLEditorPlugin::vertexShaderInit(int variant)
{
if (variant & GLSL::Lexer::Variant_GLSL_120)
- return getInitFile(QLatin1String("glsl_120.vert"), &m_glsl_120_vert);
+ return getInitFile("glsl_120.vert", &dd->m_glsl_120_vert);
else
- return getInitFile(QLatin1String("glsl_es_100.vert"), &m_glsl_es_100_vert);
+ return getInitFile("glsl_es_100.vert", &dd->m_glsl_es_100_vert);
}
-const GLSLEditorPlugin::InitFile *GLSLEditorPlugin::shaderInit(int variant) const
+const GLSLEditorPlugin::InitFile *GLSLEditorPlugin::shaderInit(int variant)
{
if (variant & GLSL::Lexer::Variant_GLSL_120)
- return getInitFile(QLatin1String("glsl_120_common.glsl"), &m_glsl_120_common);
+ return getInitFile("glsl_120_common.glsl", &dd->m_glsl_120_common);
else
- return getInitFile(QLatin1String("glsl_es_100_common.glsl"), &m_glsl_es_100_common);
+ return getInitFile("glsl_es_100_common.glsl", &dd->m_glsl_es_100_common);
}
} // namespace Internal
diff --git a/src/plugins/glsleditor/glsleditorplugin.h b/src/plugins/glsleditor/glsleditorplugin.h
index b119cfc9c2..882f01800a 100644
--- a/src/plugins/glsleditor/glsleditorplugin.h
+++ b/src/plugins/glsleditor/glsleditorplugin.h
@@ -31,32 +31,12 @@
#define GLSLEDITORPLUGIN_H
#include <extensionsystem/iplugin.h>
-#include <coreplugin/icontext.h>
-#include <coreplugin/id.h>
#include <glsl/glsl.h>
-#include <QPointer>
-
-QT_FORWARD_DECLARE_CLASS(QAction)
-
-namespace TextEditor {
-class TextEditorActionHandler;
-class ITextEditor;
-} // namespace TextEditor
-
-namespace Core {
-class Command;
-class ActionContainer;
-class ActionManager;
-}
-
namespace GLSLEditor {
-
-class GLSLTextEditorWidget;
-
namespace Internal {
-class GLSLEditorFactory;
+class GLSLTextEditorWidget;
class GLSLEditorPlugin : public ExtensionSystem::IPlugin
{
@@ -72,9 +52,7 @@ public:
void extensionsInitialized();
ShutdownFlag aboutToShutdown();
- static GLSLEditorPlugin *instance() { return m_instance; }
-
- void initializeEditor(GLSLEditor::GLSLTextEditorWidget *editor);
+ static void initializeEditor(GLSLTextEditorWidget *editor);
struct InitFile
{
@@ -88,28 +66,9 @@ public:
GLSL::TranslationUnitAST *ast;
};
- const InitFile *fragmentShaderInit(int variant) const;
- const InitFile *vertexShaderInit(int variant) const;
- const InitFile *shaderInit(int variant) const;
-
-private:
- QByteArray glslFile(const QString &fileName) const;
- InitFile *getInitFile(const QString &fileName, InitFile **initFile) const;
- void parseGlslFile(const QString &fileName, InitFile *initFile) const;
-
- static GLSLEditorPlugin *m_instance;
-
- GLSLEditorFactory *m_editor;
- TextEditor::TextEditorActionHandler *m_actionHandler;
-
- QPointer<TextEditor::ITextEditor> m_currentTextEditable;
-
- mutable InitFile *m_glsl_120_frag;
- mutable InitFile *m_glsl_120_vert;
- mutable InitFile *m_glsl_120_common;
- mutable InitFile *m_glsl_es_100_frag;
- mutable InitFile *m_glsl_es_100_vert;
- mutable InitFile *m_glsl_es_100_common;
+ static const InitFile *fragmentShaderInit(int variant);
+ static const InitFile *vertexShaderInit(int variant);
+ static const InitFile *shaderInit(int variant);
};
} // namespace Internal
diff --git a/src/plugins/glsleditor/glslfilewizard.cpp b/src/plugins/glsleditor/glslfilewizard.cpp
index 4d1c42ba90..9d3809df19 100644
--- a/src/plugins/glsleditor/glslfilewizard.cpp
+++ b/src/plugins/glsleditor/glslfilewizard.cpp
@@ -52,21 +52,10 @@ public:
using namespace GLSLEditor;
-GLSLFileWizard::GLSLFileWizard(const BaseFileWizardParameters &parameters,
- ShaderType shaderType, QObject *parent):
- Core::BaseFileWizard(parameters, parent),
- m_shaderType(shaderType)
+GLSLFileWizard::GLSLFileWizard(ShaderType shaderType)
+ : m_shaderType(shaderType)
{
-}
-
-Core::FeatureSet GLSLFileWizard::requiredFeatures() const
-{
- return Core::FeatureSet();
-}
-
-Core::IWizard::WizardFlags GLSLFileWizard::flags() const
-{
- return Core::IWizard::PlatformIndependent;
+ setFlags(Core::IWizard::PlatformIndependent);
}
Core::GeneratedFiles GLSLFileWizard::generateFiles(const QWizard *w,
diff --git a/src/plugins/glsleditor/glslfilewizard.h b/src/plugins/glsleditor/glslfilewizard.h
index b3546c1812..4beeedb461 100644
--- a/src/plugins/glsleditor/glslfilewizard.h
+++ b/src/plugins/glsleditor/glslfilewizard.h
@@ -39,8 +39,6 @@ class GLSLFileWizard: public Core::BaseFileWizard
Q_OBJECT
public:
- typedef Core::BaseFileWizardParameters BaseFileWizardParameters;
-
enum ShaderType
{
VertexShaderES,
@@ -49,22 +47,18 @@ public:
FragmentShaderDesktop
};
- explicit GLSLFileWizard(const BaseFileWizardParameters &parameters,
- ShaderType shaderType, QObject *parent = 0);
-
- virtual Core::FeatureSet requiredFeatures() const;
- virtual WizardFlags flags() const;
+ explicit GLSLFileWizard(ShaderType shaderType);
-protected:
+private:
QString fileContents(const QString &baseName, ShaderType shaderType) const;
- virtual QWizard *createWizardDialog(QWidget *parent,
+ QWizard *createWizardDialog(QWidget *parent,
const Core::WizardDialogParameters &wizardDialogParameters) const;
- virtual Core::GeneratedFiles generateFiles(const QWizard *w,
+ Core::GeneratedFiles generateFiles(const QWizard *w,
QString *errorMessage) const;
- virtual QString preferredSuffix(ShaderType shaderType) const;
+ QString preferredSuffix(ShaderType shaderType) const;
private:
ShaderType m_shaderType;
diff --git a/src/plugins/glsleditor/glslhighlighter.cpp b/src/plugins/glsleditor/glslhighlighter.cpp
index 61b1e341d6..ae64cd24fa 100644
--- a/src/plugins/glsleditor/glslhighlighter.cpp
+++ b/src/plugins/glsleditor/glslhighlighter.cpp
@@ -39,19 +39,41 @@ using namespace GLSLEditor;
using namespace GLSLEditor::Internal;
using namespace TextEditor;
-Highlighter::Highlighter(BaseTextDocument *parent)
+Highlighter::Highlighter(QTextDocument *parent)
: TextEditor::SyntaxHighlighter(parent)
{
+ init();
}
-Highlighter::~Highlighter()
+Highlighter::Highlighter(BaseTextDocument *parent)
+ : TextEditor::SyntaxHighlighter(parent)
{
+ init();
+}
+void Highlighter::init()
+{
+ static QVector<TextEditor::TextStyle> categories;
+ if (categories.isEmpty()) {
+ categories << TextEditor::C_NUMBER
+ << TextEditor::C_STRING
+ << TextEditor::C_TYPE
+ << TextEditor::C_KEYWORD
+ << TextEditor::C_OPERATOR
+ << TextEditor::C_PREPROCESSOR
+ << TextEditor::C_LABEL
+ << TextEditor::C_COMMENT
+ << TextEditor::C_DOXYGEN_COMMENT
+ << TextEditor::C_DOXYGEN_TAG
+ << TextEditor::C_VISUAL_WHITESPACE
+ << TextEditor::C_REMOVED_LINE;
+ }
+ setTextFormatCategories(categories);
}
-void Highlighter::setFormats(const QVector<QTextCharFormat> &formats)
+Highlighter::~Highlighter()
{
- qCopy(formats.begin(), formats.end(), m_formats);
+
}
void Highlighter::highlightBlock(const QString &text)
@@ -96,7 +118,7 @@ void Highlighter::highlightBlock(const QString &text)
setCurrentBlockState(previousState);
BaseTextDocumentLayout::clearParentheses(currentBlock());
if (text.length()) // the empty line can still contain whitespace
- setFormat(0, text.length(), m_formats[GLSLVisualWhitespace]);
+ setFormat(0, text.length(), formatForCategory(GLSLVisualWhitespace));
BaseTextDocumentLayout::setFoldingIndent(currentBlock(), foldingIndent);
return;
}
@@ -120,7 +142,7 @@ void Highlighter::highlightBlock(const QString &text)
if (previousTokenEnd != tk.begin()) {
setFormat(previousTokenEnd, tk.begin() - previousTokenEnd,
- m_formats[GLSLVisualWhitespace]);
+ formatForCategory(GLSLVisualWhitespace));
}
if (tk.is(GLSL::Parser::T_LEFT_PAREN) || tk.is(GLSL::Parser::T_LEFT_BRACE) || tk.is(GLSL::Parser::T_LEFT_BRACKET)) {
@@ -157,17 +179,17 @@ void Highlighter::highlightBlock(const QString &text)
highlightAsPreprocessor = false;
if (false /* && i == 0 && tk.is(GLSL::Parser::T_POUND)*/) {
- highlightLine(text, tk.begin(), tk.length, m_formats[GLSLPreprocessorFormat]);
+ highlightLine(text, tk.begin(), tk.length, formatForCategory(GLSLPreprocessorFormat));
highlightAsPreprocessor = true;
- } else if (highlightCurrentWordAsPreprocessor && isPPKeyword(text.midRef(tk.begin(), tk.length)))
- setFormat(tk.begin(), tk.length, m_formats[GLSLPreprocessorFormat]);
+ } else if (highlightCurrentWordAsPreprocessor && isPPKeyword(text.midRef(tk.begin(), tk.length))) {
+ setFormat(tk.begin(), tk.length, formatForCategory(GLSLPreprocessorFormat));
- else if (tk.is(GLSL::Parser::T_NUMBER))
- setFormat(tk.begin(), tk.length, m_formats[GLSLNumberFormat]);
+ } else if (tk.is(GLSL::Parser::T_NUMBER)) {
+ setFormat(tk.begin(), tk.length, formatForCategory(GLSLNumberFormat));
- else if (tk.is(GLSL::Parser::T_COMMENT)) {
- highlightLine(text, tk.begin(), tk.length, m_formats[GLSLCommentFormat]);
+ } else if (tk.is(GLSL::Parser::T_COMMENT)) {
+ highlightLine(text, tk.begin(), tk.length, formatForCategory(GLSLCommentFormat));
// we need to insert a close comment parenthesis, if
// - the line starts in a C Comment (initalState != 0)
@@ -190,9 +212,9 @@ void Highlighter::highlightBlock(const QString &text)
} else if (tk.is(GLSL::Parser::T_IDENTIFIER)) {
int kind = lex.findKeyword(data.constData() + tk.position, tk.length);
if (kind == GLSL::Parser::T_RESERVED)
- setFormat(tk.position, tk.length, m_formats[GLSLReservedKeyword]);
+ setFormat(tk.position, tk.length, formatForCategory(GLSLReservedKeyword));
else if (kind != GLSL::Parser::T_IDENTIFIER)
- setFormat(tk.position, tk.length, m_formats[GLSLKeywordFormat]);
+ setFormat(tk.position, tk.length, formatForCategory(GLSLKeywordFormat));
}
}
@@ -245,7 +267,7 @@ void Highlighter::highlightBlock(const QString &text)
void Highlighter::highlightLine(const QString &text, int position, int length,
const QTextCharFormat &format)
{
- const QTextCharFormat visualSpaceFormat = m_formats[GLSLVisualWhitespace];
+ const QTextCharFormat visualSpaceFormat = formatForCategory(GLSLVisualWhitespace);
const int end = position + length;
int index = position;
@@ -362,16 +384,16 @@ void Highlighter::highlightBlock(const QString &text)
for (int i = 0; i < tokens.size(); ++i) {
const GLSL::Token &tk = tokens.at(i);
- if (tk.is(GLSL::Parser::T_NUMBER))
- setFormat(tk.position, tk.length, m_formats[GLSLNumberFormat]);
- else if (tk.is(GLSL::Parser::T_COMMENT))
- setFormat(tk.position, tk.length, Qt::darkGreen); // ### FIXME: m_formats[GLSLCommentFormat]);
- else if (tk.is(GLSL::Parser::T_IDENTIFIER)) {
+ if (tk.is(GLSL::Parser::T_NUMBER)) {
+ setFormat(tk.position, tk.length, formatForCategory(GLSLNumberFormat);
+ } else if (tk.is(GLSL::Parser::T_COMMENT)) {
+ setFormat(tk.position, tk.length, Qt::darkGreen); // ### FIXME: formatForCategory(GLSLCommentFormat);
+ } else if (tk.is(GLSL::Parser::T_IDENTIFIER)) {
int kind = lex.findKeyword(data.constData() + tk.position, tk.length);
if (kind == GLSL::Parser::T_RESERVED)
- setFormat(tk.position, tk.length, m_formats[GLSLReservedKeyword]);
+ setFormat(tk.position, tk.length, formatForCategory(GLSLReservedKeyword);
else if (kind != GLSL::Parser::T_IDENTIFIER)
- setFormat(tk.position, tk.length, m_formats[GLSLKeywordFormat]);
+ setFormat(tk.position, tk.length, formatForCategory(GLSLKeywordFormat);
} else if (tk.is(GLSL::Parser::T_LEFT_PAREN) || tk.is(GLSL::Parser::T_LEFT_BRACE) || tk.is(GLSL::Parser::T_LEFT_BRACKET)) {
const QChar c = text.at(tk.begin());
parentheses.append(Parenthesis(Parenthesis::Opened, c, tk.begin()));
diff --git a/src/plugins/glsleditor/glslhighlighter.h b/src/plugins/glsleditor/glslhighlighter.h
index 9038f636b3..0f5660092a 100644
--- a/src/plugins/glsleditor/glslhighlighter.h
+++ b/src/plugins/glsleditor/glslhighlighter.h
@@ -32,10 +32,10 @@
#include <texteditor/syntaxhighlighter.h>
namespace GLSLEditor {
-class GLSLTextEditorWidget;
-
namespace Internal {
+class GLSLTextEditorWidget;
+
class Highlighter : public TextEditor::SyntaxHighlighter
{
Q_OBJECT
@@ -57,18 +57,17 @@ public:
NumGLSLFormats
};
+ explicit Highlighter(QTextDocument *parent = 0);
explicit Highlighter(TextEditor::BaseTextDocument *parent);
virtual ~Highlighter();
- void setFormats(const QVector<QTextCharFormat> &formats);
-
protected:
void highlightBlock(const QString &text);
void highlightLine(const QString &text, int position, int length, const QTextCharFormat &format);
bool isPPKeyword(const QStringRef &text) const;
private:
- QTextCharFormat m_formats[NumGLSLFormats];
+ void init();
};
} // namespace Internal
diff --git a/src/plugins/glsleditor/glslhighlighterfactory.cpp b/src/plugins/glsleditor/glslhighlighterfactory.cpp
new file mode 100644
index 0000000000..db9faa86e0
--- /dev/null
+++ b/src/plugins/glsleditor/glslhighlighterfactory.cpp
@@ -0,0 +1,49 @@
+/****************************************************************************
+**
+** 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 "glslhighlighterfactory.h"
+#include "glsleditorconstants.h"
+#include "glslhighlighter.h"
+
+using namespace GLSLEditor::Internal;
+
+GLSLHighlighterFactory::GLSLHighlighterFactory()
+{
+ setId(GLSLEditor::Constants::C_GLSLEDITOR_ID);
+ addMimeType(GLSLEditor::Constants::GLSL_MIMETYPE);
+ addMimeType(GLSLEditor::Constants::GLSL_MIMETYPE_VERT);
+ addMimeType(GLSLEditor::Constants::GLSL_MIMETYPE_FRAG);
+ addMimeType(GLSLEditor::Constants::GLSL_MIMETYPE_VERT_ES);
+ addMimeType(GLSLEditor::Constants::GLSL_MIMETYPE_FRAG_ES);
+}
+
+TextEditor::SyntaxHighlighter *GLSLHighlighterFactory::createHighlighter() const
+{
+ return new Highlighter;
+}
diff --git a/src/plugins/glsleditor/glslhighlighterfactory.h b/src/plugins/glsleditor/glslhighlighterfactory.h
new file mode 100644
index 0000000000..e6dbbddedc
--- /dev/null
+++ b/src/plugins/glsleditor/glslhighlighterfactory.h
@@ -0,0 +1,51 @@
+/****************************************************************************
+**
+** 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 GLSLHIGHLIGHTERFACTORY_H
+#define GLSLHIGHLIGHTERFACTORY_H
+
+#include <texteditor/ihighlighterfactory.h>
+
+namespace GLSLEditor {
+namespace Internal {
+
+class GLSLHighlighterFactory : public TextEditor::IHighlighterFactory
+{
+ Q_OBJECT
+
+public:
+ GLSLHighlighterFactory();
+
+ virtual TextEditor::SyntaxHighlighter *createHighlighter() const;
+};
+
+} // namespace Internal
+} // namespace GLSLEditor
+
+#endif // GLSLHIGHLIGHTERFACTORY_H
diff --git a/src/plugins/helloworld/HelloWorld.pluginspec.in b/src/plugins/helloworld/HelloWorld.pluginspec.in
index 17e14e8481..4a951ed3ac 100644
--- a/src/plugins/helloworld/HelloWorld.pluginspec.in
+++ b/src/plugins/helloworld/HelloWorld.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"HelloWorld\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\" experimental=\"true\">
+<plugin name=\"HelloWorld\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\" experimental=\"true\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/helloworld/helloworldwindow.h b/src/plugins/helloworld/helloworldwindow.h
index ce1baf46c2..fa50f31e21 100644
--- a/src/plugins/helloworld/helloworldwindow.h
+++ b/src/plugins/helloworld/helloworldwindow.h
@@ -32,8 +32,6 @@
#include <QWidget>
-QT_FORWARD_DECLARE_CLASS(QLabel)
-
namespace HelloWorld {
namespace Internal {
diff --git a/src/plugins/help/Help.pluginspec.in b/src/plugins/help/Help.pluginspec.in
index 393f331341..e54c0d3422 100644
--- a/src/plugins/help/Help.pluginspec.in
+++ b/src/plugins/help/Help.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"Help\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"Help\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/help/centralwidget.cpp b/src/plugins/help/centralwidget.cpp
index 43dea44778..c5fbe52abf 100644
--- a/src/plugins/help/centralwidget.cpp
+++ b/src/plugins/help/centralwidget.cpp
@@ -31,7 +31,8 @@
#include "helpviewer.h"
#include "localhelpmanager.h"
-#include "topicchooser.h"
+
+#include <topicchooser.h>
#include <QEvent>
#include <QTimer>
diff --git a/src/plugins/help/docsettingspage.cpp b/src/plugins/help/docsettingspage.cpp
index 28421c2b39..627aaab13f 100644
--- a/src/plugins/help/docsettingspage.cpp
+++ b/src/plugins/help/docsettingspage.cpp
@@ -38,6 +38,7 @@
#include <QKeyEvent>
#include <QMessageBox>
+using namespace Core;
using namespace Help::Internal;
DocSettingsPage::DocSettingsPage()
@@ -59,11 +60,10 @@ QWidget *DocSettingsPage::createPage(QWidget *parent)
m_ui.docsListWidget->installEventFilter(this);
- Core::HelpManager *manager = Core::HelpManager::instance();
- const QStringList &nameSpaces = manager->registeredNamespaces();
+ const QStringList nameSpaces = HelpManager::registeredNamespaces();
foreach (const QString &nameSpace, nameSpaces) {
- addItem(nameSpace, manager->fileFromNamespace(nameSpace));
- m_filesToRegister.insert(nameSpace, manager->fileFromNamespace(nameSpace));
+ addItem(nameSpace, HelpManager::fileFromNamespace(nameSpace));
+ m_filesToRegister.insert(nameSpace, HelpManager::fileFromNamespace(nameSpace));
}
m_filesToUnregister.clear();
@@ -84,10 +84,9 @@ void DocSettingsPage::addDocumentation()
m_recentDialogPath = QFileInfo(files.first()).canonicalPath();
NameSpaceToPathHash docsUnableToRegister;
- Core::HelpManager *manager = Core::HelpManager::instance();
foreach (const QString &file, files) {
const QString filePath = QDir::cleanPath(file);
- const QString &nameSpace = manager->namespaceFromFile(filePath);
+ const QString &nameSpace = HelpManager::namespaceFromFile(filePath);
if (nameSpace.isEmpty()) {
docsUnableToRegister.insertMulti(QLatin1String("UnknownNamespace"),
QDir::toNativeSeparators(filePath));
@@ -150,10 +149,8 @@ void DocSettingsPage::removeDocumentation()
void DocSettingsPage::apply()
{
- Core::HelpManager *manager = Core::HelpManager::instance();
-
- manager->unregisterDocumentation(m_filesToUnregister.keys());
- manager->registerDocumentation(m_filesToRegister.values());
+ HelpManager::unregisterDocumentation(m_filesToUnregister.keys());
+ HelpManager::registerDocumentation(m_filesToRegister.values());
m_filesToUnregister.clear();
}
@@ -166,7 +163,7 @@ bool DocSettingsPage::matches(const QString &s) const
bool DocSettingsPage::eventFilter(QObject *object, QEvent *event)
{
if (object != m_ui.docsListWidget)
- return Core::IOptionsPage::eventFilter(object, event);
+ return IOptionsPage::eventFilter(object, event);
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent*>(event);
@@ -178,7 +175,7 @@ bool DocSettingsPage::eventFilter(QObject *object, QEvent *event)
}
}
- return Core::IOptionsPage::eventFilter(object, event);
+ return IOptionsPage::eventFilter(object, event);
}
void DocSettingsPage::removeDocumentation(const QList<QListWidgetItem*> items)
@@ -187,12 +184,11 @@ void DocSettingsPage::removeDocumentation(const QList<QListWidgetItem*> items)
return;
int row = 0;
- Core::HelpManager *manager = Core::HelpManager::instance();
foreach (QListWidgetItem* item, items) {
const QString nameSpace = item->text();
m_filesToRegister.remove(nameSpace);
- m_filesToUnregister.insertMulti(nameSpace, QDir::cleanPath(manager->fileFromNamespace(nameSpace)));
+ m_filesToUnregister.insertMulti(nameSpace, QDir::cleanPath(HelpManager::fileFromNamespace(nameSpace)));
row = m_ui.docsListWidget->row(item);
delete m_ui.docsListWidget->takeItem(row);
diff --git a/src/plugins/help/filtersettingspage.cpp b/src/plugins/help/filtersettingspage.cpp
index 023d7a99cd..f97cdfa879 100644
--- a/src/plugins/help/filtersettingspage.cpp
+++ b/src/plugins/help/filtersettingspage.cpp
@@ -29,17 +29,18 @@
#include "filtersettingspage.h"
-#include "filternamedialog.h"
#include "helpconstants.h"
+#include <filternamedialog.h>
+
#include <coreplugin/helpmanager.h>
#include <QCoreApplication>
-
#include <QFileDialog>
#include <QMessageBox>
using namespace Help::Internal;
+using namespace Core;
FilterSettingsPage::FilterSettingsPage()
{
@@ -65,7 +66,7 @@ QWidget *FilterSettingsPage::createPage(QWidget *parent)
connect(m_ui.filterAddButton, SIGNAL(clicked()), this, SLOT(addFilter()));
connect(m_ui.filterRemoveButton, SIGNAL(clicked()), this,
SLOT(removeFilter()));
- connect(Core::HelpManager::instance(), SIGNAL(documentationChanged()),
+ connect(HelpManager::instance(), SIGNAL(documentationChanged()),
this, SLOT(updateFilterPage()));
if (m_searchKeywords.isEmpty()) {
@@ -84,14 +85,13 @@ void FilterSettingsPage::updateFilterPage()
QString lastTrUnfiltered;
const QString trUnfiltered = tr("Unfiltered");
- Core::HelpManager *manager = Core::HelpManager::instance();
- if (manager->customValue(Help::Constants::WeAddedFilterKey).toInt() == 1) {
+ if (HelpManager::customValue(Help::Constants::WeAddedFilterKey).toInt() == 1) {
lastTrUnfiltered =
- manager->customValue(Help::Constants::PreviousFilterNameKey).toString();
+ HelpManager::customValue(Help::Constants::PreviousFilterNameKey).toString();
}
- Core::HelpManager::Filters filters = manager->userDefinedFilters();
- Core::HelpManager::Filters::const_iterator it;
+ HelpManager::Filters filters = HelpManager::userDefinedFilters();
+ HelpManager::Filters::const_iterator it;
for (it = filters.constBegin(); it != filters.constEnd(); ++it) {
const QString &filter = it.key();
if (filter == trUnfiltered || filter == lastTrUnfiltered)
@@ -104,7 +104,7 @@ void FilterSettingsPage::updateFilterPage()
m_ui.filterWidget->addItems(m_filterMap.keys());
QSet<QString> attributes;
- filters = manager->filters();
+ filters = HelpManager::filters();
for (it = filters.constBegin(); it != filters.constEnd(); ++it)
attributes += it.value().toSet();
@@ -213,13 +213,12 @@ void FilterSettingsPage::apply()
}
if (changed) {
- Core::HelpManager *manager = Core::HelpManager::instance();
foreach (const QString &filter, m_removedFilters)
- manager->removeUserDefinedFilter(filter);
+ HelpManager::removeUserDefinedFilter(filter);
FilterMap::const_iterator it;
for (it = m_filterMap.constBegin(); it != m_filterMap.constEnd(); ++it)
- manager->addUserDefinedFilter(it.key(), it.value());
+ HelpManager::addUserDefinedFilter(it.key(), it.value());
// emit this signal to the help plugin, since we don't want
// to force gui help engine setup if we are not in help mode
@@ -229,7 +228,7 @@ void FilterSettingsPage::apply()
void FilterSettingsPage::finish()
{
- disconnect(Core::HelpManager::instance(), SIGNAL(documentationChanged()),
+ disconnect(HelpManager::instance(), SIGNAL(documentationChanged()),
this, SLOT(updateFilterPage()));
}
diff --git a/src/plugins/help/generalsettingspage.cpp b/src/plugins/help/generalsettingspage.cpp
index 7d951747b0..43ac9b1aed 100644
--- a/src/plugins/help/generalsettingspage.cpp
+++ b/src/plugins/help/generalsettingspage.cpp
@@ -29,13 +29,14 @@
#include "generalsettingspage.h"
-#include "bookmarkmanager.h"
#include "centralwidget.h"
#include "helpconstants.h"
#include "helpviewer.h"
#include "localhelpmanager.h"
#include "xbelsupport.h"
+#include <bookmarkmanager.h>
+
#include <coreplugin/coreconstants.h>
#include <coreplugin/helpmanager.h>
#include <coreplugin/icore.h>
@@ -53,6 +54,7 @@
#include <QWebSettings>
#endif
+using namespace Core;
using namespace Help::Internal;
GeneralSettingsPage::GeneralSettingsPage()
@@ -78,27 +80,25 @@ QWidget *GeneralSettingsPage::createPage(QWidget *parent)
m_ui->sizeComboBox->setEditable(false);
m_ui->styleComboBox->setEditable(false);
- Core::HelpManager *manager = Core::HelpManager::instance();
- m_font = qvariant_cast<QFont>(manager->customValue(QLatin1String("font"),
- m_font));
+ m_font = qvariant_cast<QFont>(HelpManager::customValue(QLatin1String("font"), m_font));
updateFontSize();
updateFontStyle();
updateFontFamily();
- m_homePage = manager->customValue(QLatin1String("HomePage"), QString())
+ m_homePage = HelpManager::customValue(QLatin1String("HomePage"), QString())
.toString();
if (m_homePage.isEmpty()) {
- m_homePage = manager->customValue(QLatin1String("DefaultHomePage"),
+ m_homePage = HelpManager::customValue(QLatin1String("DefaultHomePage"),
Help::Constants::AboutBlank).toString();
}
m_ui->homePageLineEdit->setText(m_homePage);
- m_startOption = manager->customValue(QLatin1String("StartOption"),
+ m_startOption = HelpManager::customValue(QLatin1String("StartOption"),
Help::Constants::ShowLastPages).toInt();
m_ui->helpStartComboBox->setCurrentIndex(m_startOption);
- m_contextOption = manager->customValue(QLatin1String("ContextHelpOption"),
+ m_contextOption = HelpManager::customValue(QLatin1String("ContextHelpOption"),
Help::Constants::SideBySideIfPossible).toInt();
m_ui->contextHelpComboBox->setCurrentIndex(m_contextOption);
@@ -120,7 +120,7 @@ QWidget *GeneralSettingsPage::createPage(QWidget *parent)
m_searchKeywords.remove(QLatin1Char('&'));
}
- m_returnOnClose = manager->customValue(QLatin1String("ReturnOnClose"),
+ m_returnOnClose = HelpManager::customValue(QLatin1String("ReturnOnClose"),
false).toBool();
m_ui->m_returnOnClose->setChecked(m_returnOnClose);
@@ -157,10 +157,9 @@ void GeneralSettingsPage::apply()
if (weight >= 0) // Weight < 0 asserts...
newFont.setWeight(weight);
- Core::HelpManager *manager = Core::HelpManager::instance();
if (newFont != m_font) {
m_font = newFont;
- manager->setCustomValue(QLatin1String("font"), newFont);
+ HelpManager::setCustomValue(QLatin1String("font"), newFont);
emit fontChanged();
}
@@ -170,19 +169,19 @@ void GeneralSettingsPage::apply()
m_ui->homePageLineEdit->setText(homePage);
if (m_homePage != homePage) {
m_homePage = homePage;
- manager->setCustomValue(QLatin1String("HomePage"), homePage);
+ HelpManager::setCustomValue(QLatin1String("HomePage"), homePage);
}
const int startOption = m_ui->helpStartComboBox->currentIndex();
if (m_startOption != startOption) {
m_startOption = startOption;
- manager->setCustomValue(QLatin1String("StartOption"), startOption);
+ HelpManager::setCustomValue(QLatin1String("StartOption"), startOption);
}
const int helpOption = m_ui->contextHelpComboBox->currentIndex();
if (m_contextOption != helpOption) {
m_contextOption = helpOption;
- manager->setCustomValue(QLatin1String("ContextHelpOption"), helpOption);
+ HelpManager::setCustomValue(QLatin1String("ContextHelpOption"), helpOption);
QSettings *settings = Core::ICore::settings();
settings->beginGroup(QLatin1String(Help::Constants::ID_MODE_HELP));
@@ -195,7 +194,7 @@ void GeneralSettingsPage::apply()
const bool close = m_ui->m_returnOnClose->isChecked();
if (m_returnOnClose != close) {
m_returnOnClose = close;
- manager->setCustomValue(QLatin1String("ReturnOnClose"), close);
+ HelpManager::setCustomValue(QLatin1String("ReturnOnClose"), close);
emit returnOnCloseChanged();
}
}
@@ -214,9 +213,8 @@ void GeneralSettingsPage::setBlankPage()
void GeneralSettingsPage::setDefaultPage()
{
- const QString &defaultHomePage = Core::HelpManager::instance()
- ->customValue(QLatin1String("DefaultHomePage"), QString()).toString();
- m_ui->homePageLineEdit->setText(defaultHomePage);
+ m_ui->homePageLineEdit->setText(
+ HelpManager::customValue(QLatin1String("DefaultHomePage"), QString()).toString());
}
void GeneralSettingsPage::importBookmarks()
diff --git a/src/plugins/help/help.pro b/src/plugins/help/help.pro
index fa984b93c9..552818098d 100644
--- a/src/plugins/help/help.pro
+++ b/src/plugins/help/help.pro
@@ -21,7 +21,6 @@ HEADERS += \
docsettingspage.h \
filtersettingspage.h \
generalsettingspage.h \
- help_global.h \
helpconstants.h \
helpfindsupport.h \
helpindexfilter.h \
diff --git a/src/plugins/help/help.qbs b/src/plugins/help/help.qbs
index dec5fb2011..e408ac4765 100644
--- a/src/plugins/help/help.qbs
+++ b/src/plugins/help/help.qbs
@@ -5,14 +5,10 @@ import "../QtcPlugin.qbs" as QtcPlugin
QtcPlugin {
name: "Help"
- Depends { id: qtcore; name: "Qt.core" }
+ Depends { name: "Qt"; submodules: ["help", "network", "webkit"]; }
Depends {
- condition: qtcore.versionMajor == 4
- name: "Qt"; submodules: ["widgets", "help", "webkit", "network"]
- }
- Depends {
- condition: qtcore.versionMajor >= 5
- name: "Qt"; submodules: ["widgets", "help", "network", "printsupport"]
+ condition: Qt.core.versionMajor >= 5;
+ name: "Qt"; submodules: ["printsupport", "webkitwidgets"];
}
Depends { name: "Core" }
@@ -20,76 +16,50 @@ QtcPlugin {
Depends { name: "Locator" }
Depends { name: "app_version_header" }
+ cpp.defines: base.concat(["QT_CLUCENE_SUPPORT"])
- cpp.defines: {
- var list = base;
- if (qtcore.versionMajor >= 5)
- list.push("QT_NO_WEBKIT");
- list.push("QT_CLUCENE_SUPPORT");
- return list;
- }
+ // We include headers from src/shared/help, and their sources include headers from here...
+ cpp.includePaths: base.concat([sharedSources.prefix, path])
- cpp.includePaths: base.concat("../../shared/help")
+ Group {
+ name: "Sources"
+ 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",
+ "helpconstants.h",
+ "helpfindsupport.cpp", "helpfindsupport.h",
+ "helpindexfilter.cpp", "helpindexfilter.h",
+ "helpmode.cpp", "helpmode.h",
+ "helpplugin.cpp", "helpplugin.h",
+ "helpviewer.cpp", "helpviewer.h", "helpviewer_p.h",
+ "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", "xbelsupport.h",
+ ]
+ }
- 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",
- "helpmode.cpp",
- "helpmode.h",
- "helpplugin.cpp",
- "helpplugin.h",
- "helpviewer.cpp",
- "helpviewer.h",
- "helpviewer_p.h",
- "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",
- "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/topicchooser.h",
- "../../shared/help/topicchooser.ui",
- ]
+ Group {
+ id: sharedSources
+ name: "Shared Sources"
+ prefix: "../../shared/help/"
+ files: [
+ "bookmarkdialog.ui",
+ "bookmarkmanager.cpp", "bookmarkmanager.h",
+ "contentwindow.cpp", "contentwindow.h",
+ "filternamedialog.cpp", "filternamedialog.h", "filternamedialog.ui",
+ "indexwindow.cpp", "indexwindow.h",
+ "topicchooser.cpp", "topicchooser.h", "topicchooser.ui",
+ ]
+ }
}
diff --git a/src/plugins/help/helpindexfilter.cpp b/src/plugins/help/helpindexfilter.cpp
index 1016ed38eb..5e65e84e32 100644
--- a/src/plugins/help/helpindexfilter.cpp
+++ b/src/plugins/help/helpindexfilter.cpp
@@ -30,7 +30,8 @@
#include "helpindexfilter.h"
#include "centralwidget.h"
-#include "topicchooser.h"
+
+#include <topicchooser.h>
#include <extensionsystem/pluginmanager.h>
#include <coreplugin/icore.h>
@@ -62,9 +63,9 @@ QList<FilterEntry> HelpIndexFilter::matchesFor(QFutureInterface<Locator::FilterE
{
QStringList keywords;
if (entry.length() < 2)
- keywords = Core::HelpManager::instance()->findKeywords(entry, 200);
+ keywords = Core::HelpManager::findKeywords(entry, caseSensitivity(entry), 200);
else
- keywords = Core::HelpManager::instance()->findKeywords(entry);
+ keywords = Core::HelpManager::findKeywords(entry, caseSensitivity(entry));
QList<FilterEntry> entries;
foreach (const QString &keyword, keywords) {
@@ -79,7 +80,7 @@ QList<FilterEntry> HelpIndexFilter::matchesFor(QFutureInterface<Locator::FilterE
void HelpIndexFilter::accept(FilterEntry selection) const
{
const QString &key = selection.displayName;
- const QMap<QString, QUrl> &links = Core::HelpManager::instance()->linksForKeyword(key);
+ const QMap<QString, QUrl> &links = Core::HelpManager::linksForKeyword(key);
if (links.size() == 1) {
emit linkActivated(links.begin().value());
diff --git a/src/plugins/help/helpplugin.cpp b/src/plugins/help/helpplugin.cpp
index e77911d42d..33113f689e 100644
--- a/src/plugins/help/helpplugin.cpp
+++ b/src/plugins/help/helpplugin.cpp
@@ -29,9 +29,7 @@
#include "helpplugin.h"
-#include "bookmarkmanager.h"
#include "centralwidget.h"
-#include "contentwindow.h"
#include "docsettingspage.h"
#include "externalhelpwindow.h"
#include "filtersettingspage.h"
@@ -41,13 +39,16 @@
#include "helpindexfilter.h"
#include "helpmode.h"
#include "helpviewer.h"
-#include "indexwindow.h"
#include "localhelpmanager.h"
#include "openpagesmanager.h"
#include "openpagesmodel.h"
#include "remotehelpfilter.h"
#include "searchwidget.h"
+#include <bookmarkmanager.h>
+#include <contentwindow.h>
+#include <indexwindow.h>
+
#include <app/app_version.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/actioncontainer.h>
@@ -150,14 +151,14 @@ bool HelpPlugin::initialize(const QStringList &arguments, QString *error)
{
Q_UNUSED(arguments)
Q_UNUSED(error)
- Core::Context globalcontext(Core::Constants::C_GLOBAL);
- Core::Context modecontext(Constants::C_MODE_HELP);
+ Context globalcontext(Core::Constants::C_GLOBAL);
+ Context modecontext(Constants::C_MODE_HELP);
- const QString &locale = Core::ICore::userInterfaceLanguage();
+ const QString &locale = ICore::userInterfaceLanguage();
if (!locale.isEmpty()) {
QTranslator *qtr = new QTranslator(this);
QTranslator *qhelptr = new QTranslator(this);
- const QString &creatorTrPath = Core::ICore::resourcePath()
+ const QString &creatorTrPath = ICore::resourcePath()
+ QLatin1String("/translations");
const QString &qtTrPath = QLibraryInfo::location(QLibraryInfo::TranslationsPath);
const QString &trFile = QLatin1String("assistant_") + locale;
@@ -180,19 +181,19 @@ bool HelpPlugin::initialize(const QStringList &arguments, QString *error)
SLOT(contextHelpOptionChanged()));
connect(m_generalSettingsPage, SIGNAL(returnOnCloseChanged()), this,
SLOT(updateCloseButton()));
- connect(Core::HelpManager::instance(), SIGNAL(helpRequested(QUrl)), this,
+ connect(HelpManager::instance(), SIGNAL(helpRequested(QUrl)), this,
SLOT(handleHelpRequest(QUrl)));
connect(m_filterSettingsPage, SIGNAL(filtersChanged()), this,
SLOT(setupHelpEngineIfNeeded()));
- connect(Core::HelpManager::instance(), SIGNAL(documentationChanged()), this,
+ connect(HelpManager::instance(), SIGNAL(documentationChanged()), this,
SLOT(setupHelpEngineIfNeeded()));
- connect(Core::HelpManager::instance(), SIGNAL(collectionFileChanged()), this,
+ connect(HelpManager::instance(), SIGNAL(collectionFileChanged()), this,
SLOT(setupHelpEngineIfNeeded()));
- connect(Core::HelpManager::instance(), SIGNAL(setupFinished()), this,
+ connect(HelpManager::instance(), SIGNAL(setupFinished()), this,
SLOT(unregisterOldQtCreatorDocumentation()));
- m_splitter = new Core::MiniSplitter;
+ m_splitter = new MiniSplitter;
m_centralWidget = new Help::Internal::CentralWidget();
connect(m_centralWidget, SIGNAL(sourceChanged(QUrl)), this,
SLOT(updateSideBarSource(QUrl)));
@@ -202,21 +203,20 @@ bool HelpPlugin::initialize(const QStringList &arguments, QString *error)
// Add Home, Previous and Next actions (used in the toolbar)
QAction *action = new QAction(QIcon(QLatin1String(IMAGEPATH "home.png")),
tr("Home"), this);
- Core::ActionManager::registerAction(action, "Help.Home", globalcontext);
+ ActionManager::registerAction(action, "Help.Home", globalcontext);
connect(action, SIGNAL(triggered()), m_centralWidget, SLOT(home()));
action = new QAction(QIcon(QLatin1String(IMAGEPATH "previous.png")),
tr("Previous Page"), this);
- Core::Command *cmd = Core::ActionManager::registerAction(action, Core::Id("Help.Previous"), modecontext);
+ Command *cmd = ActionManager::registerAction(action, "Help.Previous", modecontext);
cmd->setDefaultKeySequence(QKeySequence::Back);
action->setEnabled(m_centralWidget->isBackwardAvailable());
connect(action, SIGNAL(triggered()), m_centralWidget, SLOT(backward()));
connect(m_centralWidget, SIGNAL(backwardAvailable(bool)), action,
SLOT(setEnabled(bool)));
- action = new QAction(QIcon(QLatin1String(IMAGEPATH "next.png")), tr("Next Page"),
- this);
- cmd = Core::ActionManager::registerAction(action, Core::Id("Help.Next"), modecontext);
+ action = new QAction(QIcon(QLatin1String(IMAGEPATH "next.png")), tr("Next Page"), this);
+ cmd = ActionManager::registerAction(action, "Help.Next", modecontext);
cmd->setDefaultKeySequence(QKeySequence::Forward);
action->setEnabled(m_centralWidget->isForwardAvailable());
connect(action, SIGNAL(triggered()), m_centralWidget, SLOT(forward()));
@@ -225,98 +225,96 @@ bool HelpPlugin::initialize(const QStringList &arguments, QString *error)
action = new QAction(QIcon(QLatin1String(IMAGEPATH "bookmark.png")),
tr("Add Bookmark"), this);
- cmd = Core::ActionManager::registerAction(action, Core::Id("Help.AddBookmark"),
- modecontext);
- cmd->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+M") : tr("Ctrl+M")));
+ cmd = ActionManager::registerAction(action, "Help.AddBookmark", modecontext);
+ cmd->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+M") : tr("Ctrl+M")));
connect(action, SIGNAL(triggered()), this, SLOT(addBookmark()));
// Add Contents, Index, and Context menu items and a separator to the Help menu
action = new QAction(QIcon::fromTheme(QLatin1String("help-contents")),
tr(SB_CONTENTS), this);
- cmd = Core::ActionManager::registerAction(action, Core::Id("Help.Contents"), globalcontext);
- Core::ActionManager::actionContainer(Core::Constants::M_HELP)->addAction(cmd, Core::Constants::G_HELP_HELP);
+ cmd = ActionManager::registerAction(action, "Help.Contents", globalcontext);
+ ActionManager::actionContainer(Core::Constants::M_HELP)->addAction(cmd, Core::Constants::G_HELP_HELP);
connect(action, SIGNAL(triggered()), this, SLOT(activateContents()));
action = new QAction(tr(SB_INDEX), this);
- cmd = Core::ActionManager::registerAction(action, Core::Id("Help.Index"), globalcontext);
- Core::ActionManager::actionContainer(Core::Constants::M_HELP)->addAction(cmd, Core::Constants::G_HELP_HELP);
+ cmd = ActionManager::registerAction(action, "Help.Index", globalcontext);
+ ActionManager::actionContainer(Core::Constants::M_HELP)->addAction(cmd, Core::Constants::G_HELP_HELP);
connect(action, SIGNAL(triggered()), this, SLOT(activateIndex()));
action = new QAction(tr("Context Help"), this);
- cmd = Core::ActionManager::registerAction(action, Core::Id("Help.Context"), globalcontext);
- Core::ActionManager::actionContainer(Core::Constants::M_HELP)->addAction(cmd, Core::Constants::G_HELP_HELP);
+ cmd = ActionManager::registerAction(action, "Help.Context", globalcontext);
+ ActionManager::actionContainer(Core::Constants::M_HELP)->addAction(cmd, Core::Constants::G_HELP_HELP);
cmd->setDefaultKeySequence(QKeySequence(Qt::Key_F1));
connect(action, SIGNAL(triggered()), this, SLOT(activateContext()));
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);
+ cmd = ActionManager::registerAction(action, "Help.Separator", globalcontext);
+ 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);
- Core::ActionManager::actionContainer(Core::Constants::M_HELP)->addAction(cmd, Core::Constants::G_HELP_HELP);
+ cmd = ActionManager::registerAction(action, "Help.TechSupport", globalcontext);
+ ActionManager::actionContainer(Core::Constants::M_HELP)->addAction(cmd, Core::Constants::G_HELP_HELP);
connect(action, SIGNAL(triggered()), this, SLOT(slotOpenSupportPage()));
action = new QAction(tr("Report Bug..."), this);
- cmd = Core::ActionManager::registerAction(action, Core::Id("Help.ReportBug"), globalcontext);
- Core::ActionManager::actionContainer(Core::Constants::M_HELP)->addAction(cmd, Core::Constants::G_HELP_HELP);
+ cmd = ActionManager::registerAction(action, "Help.ReportBug", globalcontext);
+ ActionManager::actionContainer(Core::Constants::M_HELP)->addAction(cmd, Core::Constants::G_HELP_HELP);
connect(action, SIGNAL(triggered()), this, SLOT(slotReportBug()));
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);
+ cmd = ActionManager::registerAction(action, "Help.Separator2", globalcontext);
+ 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);
+ ActionManager::registerAction(action, Core::Constants::PRINT, modecontext);
connect(action, SIGNAL(triggered()), m_centralWidget, SLOT(print()));
action = new QAction(this);
- cmd = Core::ActionManager::registerAction(action, Core::Constants::COPY, modecontext);
+ cmd = ActionManager::registerAction(action, Core::Constants::COPY, modecontext);
connect(action, SIGNAL(triggered()), m_centralWidget, SLOT(copy()));
action->setText(cmd->action()->text());
action->setIcon(cmd->action()->icon());
- if (Core::ActionContainer *advancedMenu = Core::ActionManager::actionContainer(Core::Constants::M_EDIT_ADVANCED)) {
+ if (ActionContainer *advancedMenu = ActionManager::actionContainer(Core::Constants::M_EDIT_ADVANCED)) {
// reuse TextEditor constants to avoid a second pair of menu actions
action = new QAction(tr("Increase Font Size"), this);
- cmd = Core::ActionManager::registerAction(action, TextEditor::Constants::INCREASE_FONT_SIZE,
- modecontext);
+ cmd = ActionManager::registerAction(action, TextEditor::Constants::INCREASE_FONT_SIZE, modecontext);
connect(action, SIGNAL(triggered()), m_centralWidget, SLOT(zoomIn()));
advancedMenu->addAction(cmd, Core::Constants::G_EDIT_FONT);
action = new QAction(tr("Decrease Font Size"), this);
- cmd = Core::ActionManager::registerAction(action, TextEditor::Constants::DECREASE_FONT_SIZE,
- modecontext);
+ cmd = ActionManager::registerAction(action, TextEditor::Constants::DECREASE_FONT_SIZE, modecontext);
connect(action, SIGNAL(triggered()), m_centralWidget, SLOT(zoomOut()));
advancedMenu->addAction(cmd, Core::Constants::G_EDIT_FONT);
action = new QAction(tr("Reset Font Size"), this);
- cmd = Core::ActionManager::registerAction(action, TextEditor::Constants::RESET_FONT_SIZE,
- modecontext);
+ cmd = ActionManager::registerAction(action, TextEditor::Constants::RESET_FONT_SIZE, modecontext);
connect(action, SIGNAL(triggered()), m_centralWidget, SLOT(resetZoom()));
advancedMenu->addAction(cmd, Core::Constants::G_EDIT_FONT);
}
- if (Core::ActionContainer *windowMenu = Core::ActionManager::actionContainer(Core::Constants::M_WINDOW)) {
+ if (ActionContainer *windowMenu = ActionManager::actionContainer(Core::Constants::M_WINDOW)) {
// reuse EditorManager constants to avoid a second pair of menu actions
+ // Goto Previous In History Action
action = new QAction(QApplication::translate("EditorManager",
"Next Open Document in History"), this);
- Core::Command *ctrlTab = Core::ActionManager::registerAction(action, Core::Constants::GOTOPREVINHISTORY,
- modecontext); // Goto Previous In History Action
+ Command *ctrlTab = ActionManager::registerAction(action, Core::Constants::GOTOPREVINHISTORY,
+ modecontext);
windowMenu->addAction(ctrlTab, Core::Constants::G_WINDOW_NAVIGATE);
connect(action, SIGNAL(triggered()), &OpenPagesManager::instance(),
SLOT(gotoPreviousPage()));
+ // Goto Next In History Action
action = new QAction(QApplication::translate("EditorManager",
"Previous Open Document in History"), this);
- Core::Command *ctrlShiftTab = Core::ActionManager::registerAction(action, Core::Constants::GOTONEXTINHISTORY,
- modecontext); // Goto Next In History Action
+ Command *ctrlShiftTab = ActionManager::registerAction(action, Core::Constants::GOTONEXTINHISTORY,
+ modecontext);
windowMenu->addAction(ctrlShiftTab, Core::Constants::G_WINDOW_NAVIGATE);
connect(action, SIGNAL(triggered()), &OpenPagesManager::instance(),
SLOT(gotoNextPage()));
@@ -344,7 +342,7 @@ bool HelpPlugin::initialize(const QStringList &arguments, QString *error)
if (QLayout *layout = m_centralWidget->layout()) {
layout->setSpacing(0);
- Core::FindToolBarPlaceHolder *fth = new Core::FindToolBarPlaceHolder(m_centralWidget);
+ FindToolBarPlaceHolder *fth = new FindToolBarPlaceHolder(m_centralWidget);
fth->setObjectName(QLatin1String("HelpFindToolBarPlaceHolder"));
layout->addWidget(fth);
}
@@ -360,8 +358,8 @@ bool HelpPlugin::initialize(const QStringList &arguments, QString *error)
SLOT(switchToHelpMode(QUrl)));
QDesktopServices::setUrlHandler(QLatin1String("qthelp"), this, "handleHelpRequest");
- connect(Core::ModeManager::instance(), SIGNAL(currentModeChanged(Core::IMode*,
- Core::IMode*)), this, SLOT(modeChanged(Core::IMode*,Core::IMode*)));
+ connect(ModeManager::instance(), SIGNAL(currentModeChanged(Core::IMode*,Core::IMode*)),
+ this, SLOT(modeChanged(Core::IMode*,Core::IMode*)));
m_externalWindow = new ExternalHelpWindow;
m_mode = new HelpMode;
@@ -385,13 +383,13 @@ void HelpPlugin::extensionsInitialized()
QStringList filesToRegister;
// we might need to register creators inbuild help
filesToRegister.append(ICore::documentationPath() + QLatin1String("/qtcreator.qch"));
- Core::HelpManager::instance()->registerDocumentation(filesToRegister);
+ HelpManager::registerDocumentation(filesToRegister);
}
ExtensionSystem::IPlugin::ShutdownFlag HelpPlugin::aboutToShutdown()
{
if (m_sideBar) {
- QSettings *settings = Core::ICore::settings();
+ QSettings *settings = ICore::settings();
m_sideBar->saveSettings(settings, QLatin1String("HelpSideBar"));
// keep a boolean value to avoid to modify the sidebar class, at least some qml stuff
// depends on the always visible property of the sidebar...
@@ -412,73 +410,69 @@ void HelpPlugin::unregisterOldQtCreatorDocumentation()
const QString &nsInternal = QString::fromLatin1("org.qt-project.qtcreator.%1%2%3")
.arg(IDE_VERSION_MAJOR).arg(IDE_VERSION_MINOR).arg(IDE_VERSION_RELEASE);
- Core::HelpManager *helpManager = Core::HelpManager::instance();
QStringList documentationToUnregister;
- foreach (const QString &ns, helpManager->registeredNamespaces()) {
+ foreach (const QString &ns, HelpManager::registeredNamespaces()) {
if (ns.startsWith(QLatin1String("org.qt-project.qtcreator."))
&& ns != nsInternal) {
documentationToUnregister << ns;
}
}
if (!documentationToUnregister.isEmpty())
- helpManager->unregisterDocumentation(documentationToUnregister);
+ HelpManager::unregisterDocumentation(documentationToUnregister);
}
void HelpPlugin::setupUi()
{
// side bar widgets and shortcuts
- Core::Context modecontext(Constants::C_MODE_HELP);
+ Context modecontext(Constants::C_MODE_HELP);
IndexWindow *indexWindow = new IndexWindow();
indexWindow->setWindowTitle(tr(SB_INDEX));
- m_indexItem = new Core::SideBarItem(indexWindow, QLatin1String(SB_INDEX));
+ m_indexItem = new SideBarItem(indexWindow, QLatin1String(SB_INDEX));
connect(indexWindow, SIGNAL(linkActivated(QUrl)), m_centralWidget,
SLOT(setSource(QUrl)));
connect(indexWindow, SIGNAL(linksActivated(QMap<QString,QUrl>,QString)),
m_centralWidget, SLOT(showTopicChooser(QMap<QString,QUrl>,QString)));
- QMap<QString, Core::Command*> shortcutMap;
+ QMap<QString, Command*> shortcutMap;
QShortcut *shortcut = new QShortcut(m_splitter);
shortcut->setWhatsThis(tr("Activate Index in Help mode"));
- Core::Command* cmd = Core::ActionManager::registerShortcut(shortcut,
- Core::Id("Help.IndexShortcut"), modecontext);
- cmd->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+I") : tr("Ctrl+Shift+I")));
+ Command *cmd = ActionManager::registerShortcut(shortcut, "Help.IndexShortcut", modecontext);
+ cmd->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+I") : tr("Ctrl+Shift+I")));
connect(shortcut, SIGNAL(activated()), this, SLOT(activateIndex()));
shortcutMap.insert(QLatin1String(SB_INDEX), cmd);
ContentWindow *contentWindow = new ContentWindow();
contentWindow->setWindowTitle(tr(SB_CONTENTS));
- m_contentItem = new Core::SideBarItem(contentWindow, QLatin1String(SB_CONTENTS));
+ m_contentItem = new SideBarItem(contentWindow, QLatin1String(SB_CONTENTS));
connect(contentWindow, SIGNAL(linkActivated(QUrl)), m_centralWidget,
SLOT(setSource(QUrl)));
shortcut = new QShortcut(m_splitter);
shortcut->setWhatsThis(tr("Activate Contents in Help mode"));
- cmd = Core::ActionManager::registerShortcut(shortcut, Core::Id("Help.ContentsShortcut"),
- modecontext);
- cmd->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+Shift+C") : tr("Ctrl+Shift+C")));
+ cmd = ActionManager::registerShortcut(shortcut, "Help.ContentsShortcut", modecontext);
+ cmd->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+Shift+C") : tr("Ctrl+Shift+C")));
connect(shortcut, SIGNAL(activated()), this, SLOT(activateContents()));
shortcutMap.insert(QLatin1String(SB_CONTENTS), cmd);
SearchWidget *searchWidget = new SearchWidget();
searchWidget->setWindowTitle(tr(SB_SEARCH));
- m_searchItem = new Core::SideBarItem(searchWidget, QLatin1String(SB_SEARCH));
+ m_searchItem = new SideBarItem(searchWidget, QLatin1String(SB_SEARCH));
connect(searchWidget, SIGNAL(linkActivated(QUrl)), m_centralWidget,
SLOT(setSourceFromSearch(QUrl)));
shortcut = new QShortcut(m_splitter);
shortcut->setWhatsThis(tr("Activate Search in Help mode"));
- cmd = Core::ActionManager::registerShortcut(shortcut, Core::Id("Help.SearchShortcut"),
- modecontext);
- cmd->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+/") : tr("Ctrl+Shift+/")));
+ cmd = ActionManager::registerShortcut(shortcut, "Help.SearchShortcut", modecontext);
+ cmd->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+/") : tr("Ctrl+Shift+/")));
connect(shortcut, SIGNAL(activated()), this, SLOT(activateSearch()));
shortcutMap.insert(QLatin1String(SB_SEARCH), cmd);
BookmarkManager *manager = &LocalHelpManager::bookmarkManager();
BookmarkWidget *bookmarkWidget = new BookmarkWidget(manager, 0, false);
bookmarkWidget->setWindowTitle(tr(SB_BOOKMARKS));
- m_bookmarkItem = new Core::SideBarItem(bookmarkWidget, QLatin1String(SB_BOOKMARKS));
+ m_bookmarkItem = new SideBarItem(bookmarkWidget, QLatin1String(SB_BOOKMARKS));
connect(bookmarkWidget, SIGNAL(linkActivated(QUrl)), m_centralWidget,
SLOT(setSource(QUrl)));
connect(bookmarkWidget, SIGNAL(createPage(QUrl,bool)), &OpenPagesManager::instance(),
@@ -486,28 +480,26 @@ void HelpPlugin::setupUi()
shortcut = new QShortcut(m_splitter);
shortcut->setWhatsThis(tr("Activate Bookmarks in Help mode"));
- cmd = Core::ActionManager::registerShortcut(shortcut, Core::Id("Help.BookmarkShortcut"),
- modecontext);
- cmd->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+B") : tr("Ctrl+Shift+B")));
+ cmd = ActionManager::registerShortcut(shortcut, "Help.BookmarkShortcut", modecontext);
+ cmd->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+B") : tr("Ctrl+Shift+B")));
connect(shortcut, SIGNAL(activated()), this, SLOT(activateBookmarks()));
shortcutMap.insert(QLatin1String(SB_BOOKMARKS), cmd);
QWidget *openPagesWidget = OpenPagesManager::instance().openPagesWidget();
openPagesWidget->setWindowTitle(tr("Open Pages"));
- m_openPagesItem = new Core::SideBarItem(openPagesWidget, QLatin1String(SB_OPENPAGES));
+ m_openPagesItem = new SideBarItem(openPagesWidget, QLatin1String(SB_OPENPAGES));
shortcut = new QShortcut(m_splitter);
shortcut->setWhatsThis(tr("Activate Open Pages in Help mode"));
- cmd = Core::ActionManager::registerShortcut(shortcut, Core::Id("Help.PagesShortcut"),
- modecontext);
- cmd->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+O") : tr("Ctrl+Shift+O")));
+ cmd = ActionManager::registerShortcut(shortcut, "Help.PagesShortcut", modecontext);
+ cmd->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+O") : tr("Ctrl+Shift+O")));
connect(shortcut, SIGNAL(activated()), this, SLOT(activateOpenPages()));
shortcutMap.insert(QLatin1String(SB_OPENPAGES), cmd);
- QList<Core::SideBarItem*> itemList;
+ QList<SideBarItem*> itemList;
itemList << m_contentItem << m_indexItem << m_searchItem << m_bookmarkItem
<< m_openPagesItem;
- m_sideBar = new Core::SideBar(itemList, QList<Core::SideBarItem*>()
+ m_sideBar = new SideBar(itemList, QList<SideBarItem*>()
<< m_contentItem << m_openPagesItem);
m_sideBar->setCloseWhenEmpty(true);
m_sideBar->setShortcutMap(shortcutMap);
@@ -517,14 +509,14 @@ void HelpPlugin::setupUi()
m_splitter->insertWidget(0, m_sideBar);
m_splitter->setStretchFactor(0, 0);
m_splitter->setStretchFactor(1, 1);
- m_sideBar->readSettings(Core::ICore::settings(), QLatin1String("HelpSideBar"));
+ m_sideBar->readSettings(ICore::settings(), QLatin1String("HelpSideBar"));
m_splitter->setSizes(QList<int>() << m_sideBar->size().width() << 300);
m_toggleSideBarAction = new QAction(QIcon(QLatin1String(Core::Constants::ICON_TOGGLE_SIDEBAR)),
tr("Show Sidebar"), this);
m_toggleSideBarAction->setCheckable(true);
connect(m_toggleSideBarAction, SIGNAL(triggered(bool)), this, SLOT(showHideSidebar()));
- cmd = Core::ActionManager::registerAction(m_toggleSideBarAction, Core::Constants::TOGGLE_SIDEBAR, modecontext);
+ cmd = ActionManager::registerAction(m_toggleSideBarAction, Core::Constants::TOGGLE_SIDEBAR, modecontext);
}
void HelpPlugin::resetFilter()
@@ -602,7 +594,7 @@ void HelpPlugin::createRightPaneContextViewer()
rightPaneLayout->setSpacing(0);
rightPaneLayout->addWidget(toolBar);
rightPaneLayout->addWidget(m_helpViewerForSideBar);
- Core::FindToolBarPlaceHolder *fth = new Core::FindToolBarPlaceHolder(m_rightPaneSideBarWidget);
+ FindToolBarPlaceHolder *fth = new FindToolBarPlaceHolder(m_rightPaneSideBarWidget);
fth->setObjectName(QLatin1String("HelpRightPaneFindToolBarPlaceHolder"));
rightPaneLayout->addWidget(fth);
m_rightPaneSideBarWidget->setFocusProxy(m_helpViewerForSideBar);
@@ -611,15 +603,14 @@ void HelpPlugin::createRightPaneContextViewer()
agg->add(m_helpViewerForSideBar);
agg->add(new HelpViewerFindSupport(m_helpViewerForSideBar));
- Core::Context context(Constants::C_HELP_SIDEBAR);
- Core::IContext *icontext = new Core::IContext(this);
+ Context context(Constants::C_HELP_SIDEBAR);
+ IContext *icontext = new IContext(this);
icontext->setContext(context);
icontext->setWidget(m_helpViewerForSideBar);
- Core::ICore::addContextObject(icontext);
+ ICore::addContextObject(icontext);
QAction *copy = new QAction(this);
- Core::Command *cmd = Core::ActionManager::registerAction(copy,
- Core::Constants::COPY, context);
+ Command *cmd = ActionManager::registerAction(copy, Core::Constants::COPY, context);
copy->setText(cmd->action()->text());
copy->setIcon(cmd->action()->icon());
connect(copy, SIGNAL(triggered()), m_helpViewerForSideBar, SLOT(copy()));
@@ -634,23 +625,20 @@ void HelpPlugin::createRightPaneContextViewer()
connect(m_helpViewerForSideBar, SIGNAL(backwardAvailable(bool)), back,
SLOT(setEnabled(bool)));
- if (Core::ActionContainer *advancedMenu = Core::ActionManager::actionContainer(Core::Constants::M_EDIT_ADVANCED)) {
+ if (ActionContainer *advancedMenu = ActionManager::actionContainer(Core::Constants::M_EDIT_ADVANCED)) {
// reuse TextEditor constants to avoid a second pair of menu actions
QAction *action = new QAction(tr("Increase Font Size"), this);
- cmd = Core::ActionManager::registerAction(action, TextEditor::Constants::INCREASE_FONT_SIZE,
- context);
+ cmd = ActionManager::registerAction(action, TextEditor::Constants::INCREASE_FONT_SIZE, context);
connect(action, SIGNAL(triggered()), this, SLOT(scaleRightPaneUp()));
advancedMenu->addAction(cmd, Core::Constants::G_EDIT_FONT);
action = new QAction(tr("Decrease Font Size"), this);
- cmd = Core::ActionManager::registerAction(action, TextEditor::Constants::DECREASE_FONT_SIZE,
- context);
+ cmd = ActionManager::registerAction(action, TextEditor::Constants::DECREASE_FONT_SIZE, context);
connect(action, SIGNAL(triggered()), this, SLOT(scaleRightPaneDown()));
advancedMenu->addAction(cmd, Core::Constants::G_EDIT_FONT);
action = new QAction(tr("Reset Font Size"), this);
- cmd = Core::ActionManager::registerAction(action, TextEditor::Constants::RESET_FONT_SIZE,
- context);
+ cmd = ActionManager::registerAction(action, TextEditor::Constants::RESET_FONT_SIZE, context);
connect(action, SIGNAL(triggered()), this, SLOT(resetRightPaneScale()));
advancedMenu->addAction(cmd, Core::Constants::G_EDIT_FONT);
}
@@ -681,7 +669,7 @@ void HelpPlugin::resetRightPaneScale()
void HelpPlugin::activateHelpMode()
{
if (contextHelpOption() != Help::Constants::ExternalHelpAlways)
- Core::ModeManager::activateMode(Id(Constants::ID_MODE_HELP));
+ ModeManager::activateMode(Id(Constants::ID_MODE_HELP));
else
showExternalWindow();
}
@@ -700,7 +688,7 @@ void HelpPlugin::switchToHelpMode(const QUrl &source)
void HelpPlugin::slotHideRightPane()
{
- Core::RightPaneWidget::instance()->setShown(false);
+ RightPaneWidget::instance()->setShown(false);
}
void HelpPlugin::showHideSidebar()
@@ -716,12 +704,12 @@ void HelpPlugin::showExternalWindow()
m_externalWindow->show();
connectExternalHelpWindow();
if (firstTime)
- Core::ICore::raiseWindow(Core::ICore::mainWindow());
+ ICore::raiseWindow(ICore::mainWindow());
else
- Core::ICore::raiseWindow(m_externalWindow);
+ ICore::raiseWindow(m_externalWindow);
}
-void HelpPlugin::modeChanged(Core::IMode *mode, Core::IMode *old)
+void HelpPlugin::modeChanged(IMode *mode, IMode *old)
{
if (mode == m_mode) {
m_oldMode = old;
@@ -748,8 +736,7 @@ void HelpPlugin::updateSideBarSource(const QUrl &newUrl)
void HelpPlugin::updateCloseButton()
{
- Core::HelpManager *manager = Core::HelpManager::instance();
- const bool closeOnReturn = manager->customValue(QLatin1String("ReturnOnClose"),
+ const bool closeOnReturn = HelpManager::customValue(QLatin1String("ReturnOnClose"),
false).toBool();
m_closeButton->setEnabled((OpenPagesManager::instance().pageCount() > 1)
| closeOnReturn);
@@ -835,7 +822,7 @@ void HelpPlugin::contextHelpOptionChanged()
void HelpPlugin::setupHelpEngineIfNeeded()
{
m_helpManager->setEngineNeedsUpdate();
- if (Core::ModeManager::currentMode() == m_mode
+ if (ModeManager::currentMode() == m_mode
|| contextHelpOption() == Help::Constants::ExternalHelpAlways)
m_helpManager->setupGuiHelpEngine();
}
@@ -900,7 +887,7 @@ void HelpPlugin::activateContext()
QMap<QString, QUrl> links;
if (IContext *context = Core::ICore::currentContextObject()) {
m_idFromContext = context->contextHelpId();
- links = Core::HelpManager::instance()->linksForIdentifier(m_idFromContext);
+ links = HelpManager::linksForIdentifier(m_idFromContext);
if (links.isEmpty()) {
// Maybe this is already an URL...
QUrl url(m_idFromContext);
@@ -1062,10 +1049,10 @@ Utils::StyledBar *HelpPlugin::createIconToolBar(bool external)
tr("Add Bookmark"), toolBar);
connect(bookmark, SIGNAL(triggered()), this, SLOT(addBookmark()));
} else {
- home = Core::ActionManager::command(Core::Id("Help.Home"))->action();
- back = Core::ActionManager::command(Core::Id("Help.Previous"))->action();
- next = Core::ActionManager::command(Core::Id("Help.Next"))->action();
- bookmark = Core::ActionManager::command(Core::Id("Help.AddBookmark"))->action();
+ home = Core::ActionManager::command("Help.Home")->action();
+ back = Core::ActionManager::command("Help.Previous")->action();
+ next = Core::ActionManager::command("Help.Next")->action();
+ bookmark = Core::ActionManager::command("Help.AddBookmark")->action();
}
setupNavigationMenus(back, next, toolBar);
@@ -1155,7 +1142,7 @@ void HelpPlugin::handleHelpRequest(const QUrl &url)
return;
QString address = url.toString();
- if (!Core::HelpManager::instance()->findFile(url).isValid()) {
+ if (!HelpManager::findFile(url).isValid()) {
if (address.startsWith(QLatin1String("qthelp://org.qt-project."))
|| address.startsWith(QLatin1String("qthelp://com.nokia."))
|| address.startsWith(QLatin1String("qthelp://com.trolltech."))) {
@@ -1243,7 +1230,7 @@ void HelpPlugin::slotReportBug()
void HelpPlugin::openFindToolBar()
{
if (Find::FindPlugin::instance())
- Find::FindPlugin::instance()->openFindToolBar(Find::FindPlugin::FindForward);
+ Find::FindPlugin::instance()->openFindToolBar(Find::FindPlugin::FindForwardDirection);
}
void HelpPlugin::onSideBarVisibilityChanged()
diff --git a/src/plugins/help/localhelpmanager.cpp b/src/plugins/help/localhelpmanager.cpp
index 4d909b8287..a225d77125 100644
--- a/src/plugins/help/localhelpmanager.cpp
+++ b/src/plugins/help/localhelpmanager.cpp
@@ -28,7 +28,8 @@
****************************************************************************/
#include "localhelpmanager.h"
-#include "bookmarkmanager.h"
+
+#include <bookmarkmanager.h>
#include <app/app_version.h>
#include <coreplugin/helpmanager.h>
diff --git a/src/plugins/help/openpagesmanager.cpp b/src/plugins/help/openpagesmanager.cpp
index f4cd9206bf..8bc3471d1e 100644
--- a/src/plugins/help/openpagesmanager.cpp
+++ b/src/plugins/help/openpagesmanager.cpp
@@ -49,6 +49,7 @@
#include <coreplugin/helpmanager.h>
#include <coreplugin/modemanager.h>
+using namespace Core;
using namespace Help::Internal;
OpenPagesManager *OpenPagesManager::m_instance = 0;
@@ -235,12 +236,11 @@ void OpenPagesManager::closeCurrentPage()
if (indexes.isEmpty())
return;
- Core::HelpManager *manager = Core::HelpManager::instance();
- const bool closeOnReturn = manager->customValue(QLatin1String("ReturnOnClose"),
+ const bool closeOnReturn = HelpManager::customValue(QLatin1String("ReturnOnClose"),
false).toBool();
if (m_model->rowCount() == 1 && closeOnReturn) {
- Core::ModeManager::activateMode(Core::Constants::MODE_EDIT);
+ ModeManager::activateMode(Core::Constants::MODE_EDIT);
} else {
Q_ASSERT(indexes.count() == 1);
removePage(indexes.first().row());
diff --git a/src/plugins/help/searchwidget.cpp b/src/plugins/help/searchwidget.cpp
index 25f5b8ade8..d616c054c5 100644
--- a/src/plugins/help/searchwidget.cpp
+++ b/src/plugins/help/searchwidget.cpp
@@ -194,8 +194,7 @@ void SearchWidget::indexingStarted()
{
Q_ASSERT(!m_progress);
m_progress = new QFutureInterface<void>();
- Core::ICore::progressManager() ->addTask(m_progress->future(),
- tr("Indexing"), QLatin1String("Help.Indexer"));
+ Core::ProgressManager::addTask(m_progress->future(), tr("Indexing"), "Help.Indexer");
m_progress->setProgressRange(0, 2);
m_progress->setProgressValueAndText(1, tr("Indexing Documentation..."));
m_progress->reportStarted();
diff --git a/src/plugins/help/xbelsupport.cpp b/src/plugins/help/xbelsupport.cpp
index 5913286d3c..1850629fb9 100644
--- a/src/plugins/help/xbelsupport.cpp
+++ b/src/plugins/help/xbelsupport.cpp
@@ -28,7 +28,8 @@
****************************************************************************/
#include "xbelsupport.h"
-#include "bookmarkmanager.h"
+
+#include <bookmarkmanager.h>
#include <QCoreApplication>
diff --git a/src/plugins/imageviewer/ImageViewer.pluginspec.in b/src/plugins/imageviewer/ImageViewer.pluginspec.in
index c22fe56a3f..6a1975fc12 100644
--- a/src/plugins/imageviewer/ImageViewer.pluginspec.in
+++ b/src/plugins/imageviewer/ImageViewer.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"ImageViewer\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"ImageViewer\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Denis Mingulov</copyright>
<license>
diff --git a/src/plugins/imageviewer/imageviewer.cpp b/src/plugins/imageviewer/imageviewer.cpp
index 25777c5e5e..e214eade6d 100644
--- a/src/plugins/imageviewer/imageviewer.cpp
+++ b/src/plugins/imageviewer/imageviewer.cpp
@@ -92,8 +92,6 @@ ImageViewer::ImageViewer(QWidget *parent)
d->ui_toolbar.toolButtonPlayPause->setCommandId(Constants::ACTION_TOGGLE_ANIMATION);
// connections
- connect(d->file, SIGNAL(changed()), this, SIGNAL(changed()));
-
connect(d->ui_toolbar.toolButtonZoomIn, SIGNAL(clicked()),
d->imageView, SLOT(zoomIn()));
connect(d->ui_toolbar.toolButtonZoomOut, SIGNAL(clicked()),
@@ -121,24 +119,16 @@ ImageViewer::~ImageViewer()
delete d;
}
-bool ImageViewer::createNew(const QString &contents)
-{
- Q_UNUSED(contents)
- return false;
-}
-
bool ImageViewer::open(QString *errorString, const QString &fileName, const QString &realFileName)
{
if (!d->imageView->openFile(realFileName)) {
*errorString = tr("Cannot open image file %1.").arg(QDir::toNativeSeparators(realFileName));
return false;
}
- setDisplayName(QFileInfo(fileName).fileName());
- d->file->setFileName(fileName);
+ d->file->setFilePath(fileName);
d->ui_toolbar.toolButtonPlayPause->setVisible(d->imageView->isAnimated());
setPaused(!d->imageView->isAnimated());
// d_ptr->file->setMimeType
- emit changed();
return true;
}
@@ -152,22 +142,6 @@ Core::Id ImageViewer::id() const
return Core::Id(Constants::IMAGEVIEWER_ID);
}
-QString ImageViewer::displayName() const
-{
- return d->displayName;
-}
-
-void ImageViewer::setDisplayName(const QString &title)
-{
- d->displayName = title;
- emit changed();
-}
-
-bool ImageViewer::isTemporary() const
-{
- return false;
-}
-
QWidget *ImageViewer::toolBar()
{
return d->toolbar;
diff --git a/src/plugins/imageviewer/imageviewer.h b/src/plugins/imageviewer/imageviewer.h
index 14a1774e0f..2890d45a32 100644
--- a/src/plugins/imageviewer/imageviewer.h
+++ b/src/plugins/imageviewer/imageviewer.h
@@ -54,13 +54,9 @@ public:
explicit ImageViewer(QWidget *parent = 0);
~ImageViewer();
- 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 isTemporary() const;
QWidget *toolBar();
public slots:
diff --git a/src/plugins/imageviewer/imagevieweractionhandler.h b/src/plugins/imageviewer/imagevieweractionhandler.h
index 375ebbfb95..505ab6d64e 100644
--- a/src/plugins/imageviewer/imagevieweractionhandler.h
+++ b/src/plugins/imageviewer/imagevieweractionhandler.h
@@ -31,7 +31,7 @@
#ifndef IMAGEVIEWERACTIONHANDLER_H
#define IMAGEVIEWERACTIONHANDLER_H
-#include "coreplugin/id.h"
+#include <coreplugin/id.h>
#include <QObject>
diff --git a/src/plugins/imageviewer/imageviewerfactory.cpp b/src/plugins/imageviewer/imageviewerfactory.cpp
index d925ea6cc9..b77c468c1a 100644
--- a/src/plugins/imageviewer/imageviewerfactory.cpp
+++ b/src/plugins/imageviewer/imageviewerfactory.cpp
@@ -43,7 +43,6 @@ namespace Internal {
struct ImageViewerFactoryPrivate
{
- QStringList mimeTypes;
QPointer<ImageViewerActionHandler> actionHandler;
};
@@ -51,30 +50,33 @@ ImageViewerFactory::ImageViewerFactory(QObject *parent) :
Core::IEditorFactory(parent),
d(new ImageViewerFactoryPrivate)
{
+ setId(Constants::IMAGEVIEWER_ID);
+ setDisplayName(qApp->translate("OpenWith::Editors", Constants::IMAGEVIEWER_DISPLAY_NAME));
+
d->actionHandler = new ImageViewerActionHandler(this);
- QMap<QByteArray, QString> possibleMimeTypes;
- possibleMimeTypes.insert("bmp", QLatin1String("image/bmp"));
- possibleMimeTypes.insert("gif", QLatin1String("image/gif"));
- possibleMimeTypes.insert("ico", QLatin1String("image/x-icon"));
- possibleMimeTypes.insert("jpeg", QLatin1String("image/jpeg"));
- possibleMimeTypes.insert("jpg", QLatin1String("image/jpeg"));
- possibleMimeTypes.insert("mng", QLatin1String("video/x-mng"));
- possibleMimeTypes.insert("pbm", QLatin1String("image/x-portable-bitmap"));
- possibleMimeTypes.insert("pgm", QLatin1String("image/x-portable-graymap"));
- possibleMimeTypes.insert("png", QLatin1String("image/png"));
- possibleMimeTypes.insert("ppm", QLatin1String("image/x-portable-pixmap"));
- possibleMimeTypes.insert("svg", QLatin1String("image/svg+xml"));
- possibleMimeTypes.insert("tif", QLatin1String("image/tiff"));
- possibleMimeTypes.insert("tiff", QLatin1String("image/tiff"));
- possibleMimeTypes.insert("xbm", QLatin1String("image/xbm"));
- possibleMimeTypes.insert("xpm", QLatin1String("image/xpm"));
+ QMap<QByteArray, const char *> possibleMimeTypes;
+ possibleMimeTypes.insert("bmp", "image/bmp");
+ possibleMimeTypes.insert("gif", "image/gif");
+ possibleMimeTypes.insert("ico", "image/x-icon");
+ possibleMimeTypes.insert("jpeg","image/jpeg");
+ possibleMimeTypes.insert("jpg", "image/jpeg");
+ possibleMimeTypes.insert("mng", "video/x-mng");
+ possibleMimeTypes.insert("pbm", "image/x-portable-bitmap");
+ possibleMimeTypes.insert("pgm", "image/x-portable-graymap");
+ possibleMimeTypes.insert("png", "image/png");
+ possibleMimeTypes.insert("ppm", "image/x-portable-pixmap");
+ possibleMimeTypes.insert("svg", "image/svg+xml");
+ possibleMimeTypes.insert("tif", "image/tiff");
+ possibleMimeTypes.insert("tiff","image/tiff");
+ possibleMimeTypes.insert("xbm", "image/xbm");
+ possibleMimeTypes.insert("xpm", "image/xpm");
QList<QByteArray> supportedFormats = QImageReader::supportedImageFormats();
foreach (const QByteArray &format, supportedFormats) {
- const QString &value = possibleMimeTypes.value(format);
- if (!value.isEmpty())
- d->mimeTypes.append(value);
+ const char *value = possibleMimeTypes.value(format);
+ if (value)
+ addMimeType(value);
}
}
@@ -88,21 +90,6 @@ Core::IEditor *ImageViewerFactory::createEditor(QWidget *parent)
return new ImageViewer(parent);
}
-QStringList ImageViewerFactory::mimeTypes() const
-{
- return d->mimeTypes;
-}
-
-Core::Id ImageViewerFactory::id() const
-{
- return Core::Id(Constants::IMAGEVIEWER_ID);
-}
-
-QString ImageViewerFactory::displayName() const
-{
- return qApp->translate("OpenWith::Editors", Constants::IMAGEVIEWER_DISPLAY_NAME);
-}
-
void ImageViewerFactory::extensionsInitialized()
{
d->actionHandler->createActions();
diff --git a/src/plugins/imageviewer/imageviewerfactory.h b/src/plugins/imageviewer/imageviewerfactory.h
index 77d372a265..a4200013ca 100644
--- a/src/plugins/imageviewer/imageviewerfactory.h
+++ b/src/plugins/imageviewer/imageviewerfactory.h
@@ -47,10 +47,6 @@ public:
Core::IEditor *createEditor(QWidget *parent);
- QStringList mimeTypes() const;
- Core::Id id() const;
- QString displayName() const;
-
void extensionsInitialized();
private:
diff --git a/src/plugins/imageviewer/imageviewerfile.cpp b/src/plugins/imageviewer/imageviewerfile.cpp
index 0f3850f896..a7c96e0ceb 100644
--- a/src/plugins/imageviewer/imageviewerfile.cpp
+++ b/src/plugins/imageviewer/imageviewerfile.cpp
@@ -61,7 +61,7 @@ bool ImageViewerFile::reload(QString *errorString,
emit changed();
return true;
}
- return m_editor->open(errorString, m_fileName, m_fileName);
+ return m_editor->open(errorString, filePath(), filePath());
}
bool ImageViewerFile::save(QString *errorString, const QString &fileName, bool autoSave)
@@ -72,18 +72,10 @@ bool ImageViewerFile::save(QString *errorString, const QString &fileName, bool a
return false;
}
-void ImageViewerFile::rename(const QString &newName)
+bool ImageViewerFile::setContents(const QByteArray &contents)
{
- const QString oldFilename = m_fileName;
- m_fileName = newName;
- m_editor->setDisplayName(QFileInfo(m_fileName).fileName());
- emit fileNameChanged(oldFilename, newName);
- emit changed();
-}
-
-QString ImageViewerFile::fileName() const
-{
- return m_fileName;
+ Q_UNUSED(contents);
+ return false;
}
QString ImageViewerFile::defaultPath() const
@@ -117,11 +109,5 @@ void ImageViewerFile::setMimetype(const QString &mimetype)
emit changed();
}
-void ImageViewerFile::setFileName(const QString &filename)
-{
- m_fileName = filename;
- emit changed();
-}
-
} // namespace Internal
} // namespace ImageViewer
diff --git a/src/plugins/imageviewer/imageviewerfile.h b/src/plugins/imageviewer/imageviewerfile.h
index ab913de68a..d042e8ab1f 100644
--- a/src/plugins/imageviewer/imageviewerfile.h
+++ b/src/plugins/imageviewer/imageviewerfile.h
@@ -46,8 +46,7 @@ public:
explicit ImageViewerFile(ImageViewer *parent = 0);
bool save(QString *errorString, const QString &fileName, bool autoSave);
- void rename(const QString &newName);
- QString fileName() const;
+ bool setContents(const QByteArray &contents);
QString defaultPath() const;
QString suggestedFileName() const;
@@ -60,10 +59,8 @@ public:
bool reload(QString *errorString, ReloadFlag flag, ChangeType type);
void setMimetype(const QString &mimetype);
- void setFileName(const QString &filename);
private:
- QString m_fileName;
QString m_mimeType;
ImageViewer *m_editor;
};
diff --git a/src/plugins/imageviewer/imageviewerplugin.cpp b/src/plugins/imageviewer/imageviewerplugin.cpp
index 81f22d7650..a0a6839411 100644
--- a/src/plugins/imageviewer/imageviewerplugin.cpp
+++ b/src/plugins/imageviewer/imageviewerplugin.cpp
@@ -64,7 +64,7 @@ bool ImageViewerPlugin::initialize(const QStringList &arguments, QString *errorM
{
Q_UNUSED(arguments)
- if (!Core::ICore::mimeDatabase()->addMimeTypes(QLatin1String(":/imageviewer/ImageViewer.mimetypes.xml"), errorMessage))
+ if (!Core::MimeDatabase::addMimeTypes(QLatin1String(":/imageviewer/ImageViewer.mimetypes.xml"), errorMessage))
return false;
d->factory = new ImageViewerFactory(this);
diff --git a/src/plugins/locator/Locator.pluginspec.in b/src/plugins/locator/Locator.pluginspec.in
index c9af5b827e..8144fdaa8d 100644
--- a/src/plugins/locator/Locator.pluginspec.in
+++ b/src/plugins/locator/Locator.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"Locator\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"Locator\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/locator/basefilefilter.cpp b/src/plugins/locator/basefilefilter.cpp
index 8cd2a96e40..bfe10a8cd6 100644
--- a/src/plugins/locator/basefilefilter.cpp
+++ b/src/plugins/locator/basefilefilter.cpp
@@ -47,19 +47,25 @@ BaseFileFilter::BaseFileFilter()
QList<FilterEntry> BaseFileFilter::matchesFor(QFutureInterface<Locator::FilterEntry> &future, const QString &origEntry)
{
updateFiles();
- QList<FilterEntry> matches;
- QList<FilterEntry> badMatches;
+ QList<FilterEntry> betterEntries;
+ QList<FilterEntry> goodEntries;
QString needle = trimWildcards(origEntry);
const QString lineNoSuffix = EditorManager::splitLineNumber(&needle);
QStringMatcher matcher(needle, Qt::CaseInsensitive);
const QChar asterisk = QLatin1Char('*');
QRegExp regexp(asterisk + needle+ asterisk, Qt::CaseInsensitive, QRegExp::Wildcard);
if (!regexp.isValid())
- return matches;
+ return betterEntries;
+ const QChar pathSeparator = QDir::separator();
+ const bool hasPathSeparator = needle.contains(pathSeparator);
const bool hasWildcard = needle.contains(asterisk) || needle.contains(QLatin1Char('?'));
QStringList searchListPaths;
QStringList searchListNames;
- if (!m_previousEntry.isEmpty() && !m_forceNewSearchList && needle.contains(m_previousEntry)) {
+ const bool containsPreviousEntry = !m_previousEntry.isEmpty()
+ && needle.contains(m_previousEntry);
+ const bool pathSeparatorAdded = !m_previousEntry.contains(pathSeparator)
+ && needle.contains(pathSeparator);
+ if (!m_forceNewSearchList && containsPreviousEntry && !pathSeparatorAdded) {
searchListPaths = m_previousResultPaths;
searchListNames = m_previousResultNames;
} else {
@@ -70,6 +76,7 @@ QList<FilterEntry> BaseFileFilter::matchesFor(QFutureInterface<Locator::FilterEn
m_previousResultNames.clear();
m_forceNewSearchList = false;
m_previousEntry = needle;
+ const Qt::CaseSensitivity caseSensitivityForPrefix = caseSensitivity(needle);
QStringListIterator paths(searchListPaths);
QStringListIterator names(searchListNames);
while (paths.hasNext() && names.hasNext()) {
@@ -78,23 +85,24 @@ QList<FilterEntry> BaseFileFilter::matchesFor(QFutureInterface<Locator::FilterEn
QString path = paths.next();
QString name = names.next();
- if ((hasWildcard && regexp.exactMatch(name))
- || (!hasWildcard && matcher.indexIn(name) != -1)) {
+ QString matchText = hasPathSeparator ? path : name;
+ if ((hasWildcard && regexp.exactMatch(matchText))
+ || (!hasWildcard && matcher.indexIn(matchText) != -1)) {
QFileInfo fi(path);
FilterEntry entry(this, fi.fileName(), QString(path + lineNoSuffix));
entry.extraInfo = FileUtils::shortNativePath(FileName(fi));
entry.fileName = path;
- if (name.startsWith(needle))
- matches.append(entry);
+ if (matchText.startsWith(needle, caseSensitivityForPrefix))
+ betterEntries.append(entry);
else
- badMatches.append(entry);
+ goodEntries.append(entry);
m_previousResultPaths.append(path);
m_previousResultNames.append(name);
}
}
- matches.append(badMatches);
- return matches;
+ betterEntries.append(goodEntries);
+ return betterEntries;
}
void BaseFileFilter::accept(Locator::FilterEntry selection) const
diff --git a/src/plugins/locator/commandlocator.cpp b/src/plugins/locator/commandlocator.cpp
index bdbdf80f1c..022ae3a7a3 100644
--- a/src/plugins/locator/commandlocator.cpp
+++ b/src/plugins/locator/commandlocator.cpp
@@ -66,12 +66,14 @@ void CommandLocator::appendCommand(Core::Command *cmd)
QList<Locator::FilterEntry> CommandLocator::matchesFor(QFutureInterface<Locator::FilterEntry> &future, const QString &entry)
{
- QList<FilterEntry> filters;
+ QList<FilterEntry> goodEntries;
+ QList<FilterEntry> betterEntries;
// Get active, enabled actions matching text, store in list.
// Reference via index in extraInfo.
const QChar ampersand = QLatin1Char('&');
+ const Qt::CaseSensitivity caseSensitivity_ = caseSensitivity(entry);
const int count = d->commands.size();
- for (int i = 0; i < count; i++) {
+ for (int i = 0; i < count; i++) {
if (future.isCanceled())
break;
if (d->commands.at(i)->isActive()) {
@@ -79,12 +81,15 @@ QList<Locator::FilterEntry> CommandLocator::matchesFor(QFutureInterface<Locator:
if (action->isEnabled()) {
QString text = action->text();
text.remove(ampersand);
- if (text.contains(entry, Qt::CaseInsensitive))
- filters.append(FilterEntry(this, text, QVariant(i)));
+ if (text.startsWith(entry, caseSensitivity_))
+ betterEntries.append(FilterEntry(this, text, QVariant(i)));
+ else if (text.contains(entry, caseSensitivity_))
+ goodEntries.append(FilterEntry(this, text, QVariant(i)));
}
}
}
- return filters;
+ betterEntries.append(goodEntries);
+ return betterEntries;
}
void CommandLocator::accept(Locator::FilterEntry entry) const
diff --git a/src/plugins/locator/executefilter.cpp b/src/plugins/locator/executefilter.cpp
index c34f7f5f27..cce2efd3ca 100644
--- a/src/plugins/locator/executefilter.cpp
+++ b/src/plugins/locator/executefilter.cpp
@@ -64,12 +64,13 @@ QList<FilterEntry> ExecuteFilter::matchesFor(QFutureInterface<Locator::FilterEnt
if (!entry.isEmpty()) // avoid empty entry
value.append(FilterEntry(this, entry, QVariant()));
QList<FilterEntry> others;
- foreach (const QString& i, m_commandHistory) {
+ const Qt::CaseSensitivity caseSensitivityForPrefix = caseSensitivity(entry);
+ foreach (const QString &i, m_commandHistory) {
if (future.isCanceled())
break;
if (i == entry) // avoid repeated entry
continue;
- if (i.startsWith(entry))
+ if (i.startsWith(entry, caseSensitivityForPrefix))
value.append(FilterEntry(this, i, QVariant()));
else
others.append(FilterEntry(this, i, QVariant()));
@@ -125,9 +126,9 @@ void ExecuteFilter::finished(int exitCode, QProcess::ExitStatus status)
{
QString log = QLatin1Char('\'') + headCommand() + QLatin1String("' ");
if (status == QProcess::NormalExit && exitCode == 0)
- ICore::messageManager()->printToOutputPane(log + tr("finished"), MessageManager::NoModeSwitch);
+ MessageManager::write(log + tr("finished"));
else
- ICore::messageManager()->printToOutputPane(log + tr("failed"), MessageManager::NoModeSwitch);
+ MessageManager::write(log + tr("failed"));
m_taskQueue.dequeue();
if (!m_taskQueue.isEmpty())
@@ -137,13 +138,13 @@ void ExecuteFilter::finished(int exitCode, QProcess::ExitStatus status)
void ExecuteFilter::readStandardOutput()
{
QByteArray data = m_process->readAllStandardOutput();
- ICore::messageManager()->printToOutputPane(QString::fromLocal8Bit(data), MessageManager::NoModeSwitch);
+ MessageManager::write(QString::fromLocal8Bit(data));
}
void ExecuteFilter::readStandardError()
{
QByteArray data = m_process->readAllStandardError();
- ICore::messageManager()->printToOutputPane(QString::fromLocal8Bit(data), MessageManager::NoModeSwitch);
+ MessageManager::write(QString::fromLocal8Bit(data));
}
void ExecuteFilter::runHeadCommand()
@@ -152,14 +153,12 @@ void ExecuteFilter::runHeadCommand()
const ExecuteData &d = m_taskQueue.head();
const QString fullPath = Utils::Environment::systemEnvironment().searchInPath(d.executable);
if (fullPath.isEmpty()) {
- const QString log = tr("Could not find executable for '%1'").arg(d.executable);
- ICore::messageManager()->printToOutputPane(log, MessageManager::NoModeSwitch);
+ MessageManager::write(tr("Could not find executable for '%1'").arg(d.executable));
m_taskQueue.dequeue();
runHeadCommand();
return;
}
- QString log(tr("Starting command '%1'").arg(headCommand()));
- ICore::messageManager()->printToOutputPane(log, MessageManager::NoModeSwitch);
+ MessageManager::write(tr("Starting command '%1'").arg(headCommand()));
m_process->setWorkingDirectory(d.workingDirectory);
m_process->setCommand(fullPath, d.arguments);
m_process->start();
diff --git a/src/plugins/locator/filesystemfilter.cpp b/src/plugins/locator/filesystemfilter.cpp
index 4e7af5c91b..d7c978a1e4 100644
--- a/src/plugins/locator/filesystemfilter.cpp
+++ b/src/plugins/locator/filesystemfilter.cpp
@@ -38,8 +38,23 @@ using namespace Core;
using namespace Locator;
using namespace Locator::Internal;
-FileSystemFilter::FileSystemFilter(EditorManager *editorManager, LocatorWidget *locatorWidget)
- : m_editorManager(editorManager), m_locatorWidget(locatorWidget), m_includeHidden(true)
+namespace {
+
+QList<FilterEntry> *categorize(const QString &entry, const QString &candidate,
+ Qt::CaseSensitivity caseSensitivity,
+ QList<FilterEntry> *betterEntries, QList<FilterEntry> *goodEntries)
+{
+ if (entry.isEmpty() || candidate.startsWith(entry, caseSensitivity))
+ return betterEntries;
+ else if (candidate.contains(entry, caseSensitivity))
+ return goodEntries;
+ return 0;
+}
+
+} // anynoumous namespace
+
+FileSystemFilter::FileSystemFilter(LocatorWidget *locatorWidget)
+ : m_locatorWidget(locatorWidget), m_includeHidden(true)
{
setId("Files in file system");
setDisplayName(tr("Files in File System"));
@@ -49,7 +64,8 @@ FileSystemFilter::FileSystemFilter(EditorManager *editorManager, LocatorWidget *
QList<FilterEntry> FileSystemFilter::matchesFor(QFutureInterface<Locator::FilterEntry> &future, const QString &entry)
{
- QList<FilterEntry> value;
+ QList<FilterEntry> goodEntries;
+ QList<FilterEntry> betterEntries;
QFileInfo entryInfo(entry);
QString name = entryInfo.fileName();
QString directory = entryInfo.path();
@@ -58,9 +74,9 @@ QList<FilterEntry> FileSystemFilter::matchesFor(QFutureInterface<Locator::Filter
if (filePath.startsWith(QLatin1String("~/"))) {
directory.replace(0, 1, QDir::homePath());
} else {
- IEditor *editor = EditorManager::currentEditor();
- if (editor && !editor->document()->fileName().isEmpty()) {
- QFileInfo info(editor->document()->fileName());
+ IDocument *document= EditorManager::currentDocument();
+ if (document && !document->filePath().isEmpty()) {
+ QFileInfo info(document->filePath());
directory.prepend(info.absolutePath() + QLatin1Char('/'));
}
}
@@ -72,6 +88,7 @@ QList<FilterEntry> FileSystemFilter::matchesFor(QFutureInterface<Locator::Filter
dirFilter |= QDir::Hidden;
fileFilter |= QDir::Hidden;
}
+ const Qt::CaseSensitivity caseSensitivity_ = caseSensitivity(entry);
QStringList dirs = dirInfo.entryList(dirFilter,
QDir::Name|QDir::IgnoreCase|QDir::LocaleAware);
QStringList files = dirInfo.entryList(fileFilter,
@@ -79,11 +96,12 @@ QList<FilterEntry> FileSystemFilter::matchesFor(QFutureInterface<Locator::Filter
foreach (const QString &dir, dirs) {
if (future.isCanceled())
break;
- if (name.isEmpty() || dir.startsWith(name, Qt::CaseInsensitive)) {
+ if (QList<FilterEntry> *category = categorize(name, dir, caseSensitivity_, &betterEntries,
+ &goodEntries)) {
const QString fullPath = dirInfo.filePath(dir);
FilterEntry filterEntry(this, dir, QVariant());
filterEntry.fileName = fullPath;
- value.append(filterEntry);
+ category->append(filterEntry);
}
}
// file names can match with +linenumber or :linenumber
@@ -93,14 +111,16 @@ QList<FilterEntry> FileSystemFilter::matchesFor(QFutureInterface<Locator::Filter
foreach (const QString &file, files) {
if (future.isCanceled())
break;
- if (name.isEmpty() || file.startsWith(name, Qt::CaseInsensitive)) {
+ if (QList<FilterEntry> *category = categorize(name, file, caseSensitivity_, &betterEntries,
+ &goodEntries)) {
const QString fullPath = dirInfo.filePath(file);
FilterEntry filterEntry(this, file, QString(fullPath + lineNoSuffix));
filterEntry.fileName = fullPath;
- value.append(filterEntry);
+ category->append(filterEntry);
}
}
- return value;
+ betterEntries.append(goodEntries);
+ return betterEntries;
}
void FileSystemFilter::accept(FilterEntry selection) const
diff --git a/src/plugins/locator/filesystemfilter.h b/src/plugins/locator/filesystemfilter.h
index 6a4f9db7b3..0ee126bd0d 100644
--- a/src/plugins/locator/filesystemfilter.h
+++ b/src/plugins/locator/filesystemfilter.h
@@ -38,8 +38,6 @@
#include <QByteArray>
#include <QFutureInterface>
-namespace Core { class EditorManager; }
-
namespace Locator {
namespace Internal {
@@ -50,7 +48,7 @@ class FileSystemFilter : public Locator::ILocatorFilter
Q_OBJECT
public:
- FileSystemFilter(Core::EditorManager *editorManager, LocatorWidget *locatorWidget);
+ explicit FileSystemFilter(LocatorWidget *locatorWidget);
QList<Locator::FilterEntry> matchesFor(QFutureInterface<Locator::FilterEntry> &future, const QString &entry);
void accept(Locator::FilterEntry selection) const;
QByteArray saveState() const;
@@ -59,7 +57,6 @@ public:
void refresh(QFutureInterface<void> &) {}
private:
- Core::EditorManager *m_editorManager;
LocatorWidget *m_locatorWidget;
bool m_includeHidden;
};
diff --git a/src/plugins/locator/ilocatorfilter.cpp b/src/plugins/locator/ilocatorfilter.cpp
index 16521dc5f1..8df4518100 100644
--- a/src/plugins/locator/ilocatorfilter.cpp
+++ b/src/plugins/locator/ilocatorfilter.cpp
@@ -120,7 +120,7 @@ QString ILocatorFilter::trimWildcards(const QString &str)
{
if (str.isEmpty())
return str;
- int first = 0, last = str.size()-1;
+ 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))
@@ -129,7 +129,12 @@ QString ILocatorFilter::trimWildcards(const QString &str)
--last;
if (first > last)
return QString();
- return str.mid(first, last-first+1);
+ return str.mid(first, last - first + 1);
+}
+
+Qt::CaseSensitivity ILocatorFilter::caseSensitivity(const QString &str)
+{
+ return str == str.toLower() ? Qt::CaseInsensitive : Qt::CaseSensitive;
}
bool ILocatorFilter::isConfigurable() const
diff --git a/src/plugins/locator/ilocatorfilter.h b/src/plugins/locator/ilocatorfilter.h
index 331b17e847..6ea20a64a9 100644
--- a/src/plugins/locator/ilocatorfilter.h
+++ b/src/plugins/locator/ilocatorfilter.h
@@ -138,6 +138,7 @@ public:
bool isEnabled() const;
static QString trimWildcards(const QString &str);
+ static Qt::CaseSensitivity caseSensitivity(const QString &str);
public slots:
/* Enable or disable the filter. */
diff --git a/src/plugins/locator/locator.pro b/src/plugins/locator/locator.pro
index 80cef75467..69c237599b 100644
--- a/src/plugins/locator/locator.pro
+++ b/src/plugins/locator/locator.pro
@@ -13,7 +13,8 @@ HEADERS += locatorplugin.h \
locatormanager.h \
basefilefilter.h \
locator_global.h \
- executefilter.h
+ executefilter.h \
+ locatorsearchutils.h
SOURCES += locatorplugin.cpp \
commandlocator.cpp \
locatorwidget.cpp \
@@ -25,9 +26,18 @@ SOURCES += locatorplugin.cpp \
locatormanager.cpp \
basefilefilter.cpp \
ilocatorfilter.cpp \
- executefilter.cpp
+ executefilter.cpp \
+ locatorsearchutils.cpp
FORMS += settingspage.ui \
filesystemfilter.ui \
directoryfilter.ui
RESOURCES += locator.qrc
+
+equals(TEST, 1) {
+ HEADERS += locatorfiltertest.h
+ SOURCES += \
+ locatorfiltertest.cpp \
+ locator_test.cpp
+ DEFINES += SRCDIR=\\\"$$PWD\\\"
+}
diff --git a/src/plugins/locator/locator.qbs b/src/plugins/locator/locator.qbs
index c5c99a328a..b4ff3f5923 100644
--- a/src/plugins/locator/locator.qbs
+++ b/src/plugins/locator/locator.qbs
@@ -1,4 +1,5 @@
import qbs.base 1.0
+import qbs.FileInfo
import "../QtcPlugin.qbs" as QtcPlugin
@@ -8,13 +9,6 @@ QtcPlugin {
Depends { name: "Qt"; submodules: ["widgets", "xml", "network", "script"] }
Depends { name: "Core" }
- cpp.includePaths: base.concat([
- "generichighlighter",
- "tooltip",
- "snippets",
- "codeassist"
- ])
-
files: [
"basefilefilter.cpp",
"basefilefilter.h",
@@ -39,6 +33,8 @@ QtcPlugin {
"locatormanager.h",
"locatorplugin.cpp",
"locatorplugin.h",
+ "locatorsearchutils.cpp",
+ "locatorsearchutils.h",
"locatorwidget.cpp",
"locatorwidget.h",
"opendocumentsfilter.cpp",
@@ -49,4 +45,16 @@ QtcPlugin {
"images/locator.png",
"images/reload.png",
]
+
+ Group {
+ name: "Tests"
+ condition: project.testsEnabled
+ files: [
+ "locatorfiltertest.cpp",
+ "locatorfiltertest.h",
+ "locator_test.cpp"
+ ]
+
+ cpp.defines: outer.concat(['SRCDIR="' + FileInfo.path(filePath) + '"'])
+ }
}
diff --git a/src/plugins/locator/locator_test.cpp b/src/plugins/locator/locator_test.cpp
new file mode 100644
index 0000000000..38b1287b82
--- /dev/null
+++ b/src/plugins/locator/locator_test.cpp
@@ -0,0 +1,178 @@
+/****************************************************************************
+**
+** 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 "locatorplugin.h"
+
+#include "basefilefilter.h"
+#include "locatorfiltertest.h"
+
+#include <coreplugin/testdatadir.h>
+#include <utils/fileutils.h>
+
+#include <QDir>
+#include <QTextStream>
+#include <QtTest>
+
+using namespace Locator::Internal::Tests;
+
+namespace {
+
+class MyTestDataDir : public Core::Internal::Tests::TestDataDir
+{
+public:
+ MyTestDataDir(const QString &testDataDirectory)
+ : TestDataDir(QLatin1String(SRCDIR "/../../../tests/locators/") + testDataDirectory) {}
+};
+
+class MyBaseFileFilter : public Locator::BaseFileFilter
+{
+public:
+ MyBaseFileFilter(const QStringList &theFiles)
+ {
+ files().clear();
+ files().append(theFiles);
+ BaseFileFilter::generateFileNames();
+ }
+
+ void refresh(QFutureInterface<void> &) {}
+
+protected:
+ void updateFiles() {}
+};
+
+inline QString _(const QByteArray &ba) { return QString::fromLatin1(ba, ba.size()); }
+
+class ReferenceData
+{
+public:
+ ReferenceData() {}
+ ReferenceData(const QString &searchText, const ResultDataList &results)
+ : searchText(searchText), results(results) {}
+
+ QString searchText;
+ ResultDataList results;
+};
+
+} // anonymous namespace
+
+Q_DECLARE_METATYPE(ReferenceData)
+Q_DECLARE_METATYPE(QList<ReferenceData>)
+
+void Locator::Internal::LocatorPlugin::test_basefilefilter()
+{
+ QFETCH(QStringList, testFiles);
+ QFETCH(QList<ReferenceData>, referenceDataList);
+
+ MyBaseFileFilter filter(testFiles);
+ BasicLocatorFilterTest test(&filter);
+
+ foreach (const ReferenceData &reference, referenceDataList) {
+ const QList<FilterEntry> filterEntries = test.matchesFor(reference.searchText);
+ const ResultDataList results = ResultData::fromFilterEntryList(filterEntries);
+// QTextStream(stdout) << "----" << endl;
+// ResultData::printFilterEntries(results);
+ QCOMPARE(results, reference.results);
+ }
+}
+
+void Locator::Internal::LocatorPlugin::test_basefilefilter_data()
+{
+ QTest::addColumn<QStringList>("testFiles");
+ QTest::addColumn<QList<ReferenceData> >("referenceDataList");
+
+ const QChar pathSeparator = QDir::separator();
+ const MyTestDataDir testDir(QLatin1String("testdata_basic"));
+ const QStringList testFiles = QStringList()
+ << testDir.file(QLatin1String("file.cpp"))
+ << testDir.file(QLatin1String("main.cpp"))
+ << testDir.file(QLatin1String("subdir/main.cpp"));
+ QStringList testFilesShort;
+ foreach (const QString &file, testFiles)
+ testFilesShort << Utils::FileUtils::shortNativePath(Utils::FileName::fromString(file));
+
+ QTest::newRow("BaseFileFilter-EmptyInput")
+ << testFiles
+ << (QList<ReferenceData>()
+ << ReferenceData(
+ QString(),
+ (QList<ResultData>()
+ << ResultData(_("file.cpp"), testFilesShort.at(0))
+ << ResultData(_("main.cpp"), testFilesShort.at(1))
+ << ResultData(_("main.cpp"), testFilesShort.at(2))))
+ );
+
+ QTest::newRow("BaseFileFilter-InputIsFileName")
+ << testFiles
+ << (QList<ReferenceData>()
+ << ReferenceData(
+ _("main.cpp"),
+ (QList<ResultData>()
+ << ResultData(_("main.cpp"), testFilesShort.at(1))
+ << ResultData(_("main.cpp"), testFilesShort.at(2))))
+ );
+
+ QTest::newRow("BaseFileFilter-InputIsFilePath")
+ << testFiles
+ << (QList<ReferenceData>()
+ << ReferenceData(
+ QString(_("subdir") + pathSeparator + _("main.cpp")),
+ (QList<ResultData>()
+ << ResultData(_("main.cpp"), testFilesShort.at(2))))
+ );
+
+ QTest::newRow("BaseFileFilter-InputIsDirIsPath")
+ << testFiles
+ << (QList<ReferenceData>()
+ << ReferenceData( _("subdir"), QList<ResultData>())
+ << ReferenceData(
+ QString(_("subdir") + pathSeparator + _("main.cpp")),
+ (QList<ResultData>()
+ << ResultData(_("main.cpp"), testFilesShort.at(2))))
+ );
+
+ QTest::newRow("BaseFileFilter-InputIsFileNameFilePathFileName")
+ << testFiles
+ << (QList<ReferenceData>()
+ << ReferenceData(
+ _("main.cpp"),
+ (QList<ResultData>()
+ << ResultData(_("main.cpp"), testFilesShort.at(1))
+ << ResultData(_("main.cpp"), testFilesShort.at(2))))
+ << ReferenceData(
+ QString(_("subdir") + pathSeparator + _("main.cpp")),
+ (QList<ResultData>()
+ << ResultData(_("main.cpp"), testFilesShort.at(2))))
+ << ReferenceData(
+ _("main.cpp"),
+ (QList<ResultData>()
+ << ResultData(_("main.cpp"), testFilesShort.at(1))
+ << ResultData(_("main.cpp"), testFilesShort.at(2))))
+ );
+}
diff --git a/src/plugins/locator/locatorfiltersfilter.cpp b/src/plugins/locator/locatorfiltersfilter.cpp
index 18300038aa..240a2581b4 100644
--- a/src/plugins/locator/locatorfiltersfilter.cpp
+++ b/src/plugins/locator/locatorfiltersfilter.cpp
@@ -58,7 +58,7 @@ QList<FilterEntry> LocatorFiltersFilter::matchesFor(QFutureInterface<Locator::Fi
if (!entry.isEmpty())
return entries;
- QMap<QString, ILocatorFilter*> uniqueFilters;
+ QMap<QString, ILocatorFilter *> uniqueFilters;
foreach (ILocatorFilter *filter, m_plugin->filters()) {
const QString filterId = filter->shortcutString() + QLatin1Char(',') + filter->displayName();
uniqueFilters.insert(filterId, filter);
@@ -82,7 +82,7 @@ QList<FilterEntry> LocatorFiltersFilter::matchesFor(QFutureInterface<Locator::Fi
void LocatorFiltersFilter::accept(FilterEntry selection) const
{
- ILocatorFilter *filter = selection.internalData.value<ILocatorFilter*>();
+ ILocatorFilter *filter = selection.internalData.value<ILocatorFilter *>();
if (filter)
m_locatorWidget->show(filter->shortcutString() + QLatin1Char(' '),
filter->shortcutString().length() + 1);
diff --git a/src/plugins/locator/locatorfiltertest.cpp b/src/plugins/locator/locatorfiltertest.cpp
new file mode 100644
index 0000000000..692d213ef9
--- /dev/null
+++ b/src/plugins/locator/locatorfiltertest.cpp
@@ -0,0 +1,89 @@
+/****************************************************************************
+**
+** 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 "locatorfiltertest.h"
+#include "locatorsearchutils.h"
+
+#include <utils/runextensions.h>
+
+#include <QFuture>
+#include <QList>
+#include <QString>
+#include <QTextStream>
+
+using namespace Locator;
+using namespace Locator::Internal;
+using namespace Locator::Internal::Tests;
+
+BasicLocatorFilterTest::BasicLocatorFilterTest(ILocatorFilter *filter) : m_filter(filter)
+{
+}
+
+QList<FilterEntry> BasicLocatorFilterTest::matchesFor(const QString &searchText)
+{
+ doBeforeLocatorRun();
+ const QList<ILocatorFilter *> filters = QList<ILocatorFilter *>() << m_filter;
+ QFuture<FilterEntry> locatorSearch = QtConcurrent::run(Locator::Internal::runSearch,
+ filters, searchText);
+ locatorSearch.waitForFinished();
+ doAfterLocatorRun();
+ return locatorSearch.results();
+}
+
+ResultData::ResultData()
+{
+}
+
+ResultData::ResultData(const QString &textColumn1, const QString &textColumn2)
+ : textColumn1(textColumn1), textColumn2(textColumn2)
+{
+}
+
+bool ResultData::operator==(const ResultData &other) const
+{
+ return textColumn1 == other.textColumn1 && textColumn2 == other.textColumn2;
+}
+
+ResultData::ResultDataList ResultData::fromFilterEntryList(const QList<FilterEntry> &entries)
+{
+ ResultDataList result;
+ foreach (const FilterEntry &entry, entries)
+ result << ResultData(entry.displayName, entry.extraInfo);
+ return result;
+}
+
+void ResultData::printFilterEntries(const ResultData::ResultDataList &entries)
+{
+ QTextStream out(stdout);
+ foreach (const ResultData entry, entries) {
+ out << "<< ResultData(_(\"" << entry.textColumn1 << "\"), _(\"" << entry.textColumn2
+ << "\"))" << endl;
+ }
+}
diff --git a/src/plugins/locator/locatorfiltertest.h b/src/plugins/locator/locatorfiltertest.h
new file mode 100644
index 0000000000..df520adfdf
--- /dev/null
+++ b/src/plugins/locator/locatorfiltertest.h
@@ -0,0 +1,98 @@
+/****************************************************************************
+**
+** 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 LOCATORFILTERTEST_H
+#define LOCATORFILTERTEST_H
+
+#include "locator_global.h"
+#include "ilocatorfilter.h"
+
+#include <QTest>
+
+namespace Locator {
+namespace Internal {
+namespace Tests {
+
+/// Runs a locator filter for a search text and returns the results.
+class LOCATOR_EXPORT BasicLocatorFilterTest
+{
+public:
+ BasicLocatorFilterTest(Locator::ILocatorFilter *filter);
+
+ QList<Locator::FilterEntry> matchesFor(const QString &searchText = QString());
+
+private:
+ virtual void doBeforeLocatorRun() {}
+ virtual void doAfterLocatorRun() {}
+
+ Locator::ILocatorFilter *m_filter;
+};
+
+class LOCATOR_EXPORT ResultData
+{
+public:
+ typedef QList<ResultData> ResultDataList;
+
+ ResultData();
+ ResultData(const QString &textColumn1, const QString &textColumn2);
+
+ bool operator==(const ResultData &other) const;
+
+ static ResultDataList fromFilterEntryList(const QList<FilterEntry> &entries);
+
+ /// For debugging and creating reference data
+ static void printFilterEntries(const ResultDataList &entries);
+
+ QString textColumn1;
+ QString textColumn2;
+};
+
+typedef ResultData::ResultDataList ResultDataList;
+
+} // namespace Tests
+} // namespace Internal
+} // namespace Locator
+
+Q_DECLARE_METATYPE(Locator::Internal::Tests::ResultData)
+Q_DECLARE_METATYPE(Locator::Internal::Tests::ResultDataList)
+
+QT_BEGIN_NAMESPACE
+namespace QTest {
+
+template<> inline char *toString(const Locator::Internal::Tests::ResultData &data)
+{
+ QByteArray ba = "\"" + data.textColumn1.toUtf8() + "\", \"" + data.textColumn2.toUtf8() + "\"";
+ return qstrdup(ba.data());
+}
+
+} // namespace QTest
+QT_END_NAMESPACE
+
+#endif // LOCATORFILTERTEST_H
diff --git a/src/plugins/locator/locatormanager.cpp b/src/plugins/locator/locatormanager.cpp
index dc051b5796..38a17dc270 100644
--- a/src/plugins/locator/locatormanager.cpp
+++ b/src/plugins/locator/locatormanager.cpp
@@ -33,27 +33,26 @@
#include <extensionsystem/pluginmanager.h>
#include <utils/qtcassert.h>
-using namespace Locator;
-using namespace Locator::Internal;
+namespace Locator {
-LocatorManager *LocatorManager::m_instance = 0;
+static Internal::LocatorWidget *m_locatorWidget = 0;
-LocatorManager::LocatorManager(LocatorWidget *locatorWidget)
- : QObject(locatorWidget),
- m_locatorWidget(locatorWidget)
+LocatorManager::LocatorManager(Internal::LocatorWidget *locatorWidget)
+ : QObject(locatorWidget)
{
- m_instance = this;
+ m_locatorWidget = locatorWidget;
}
LocatorManager::~LocatorManager()
{
ExtensionSystem::PluginManager::removeObject(this);
- m_instance = 0;
}
void LocatorManager::show(const QString &text,
- int selectionStart, int selectionLength)
+ int selectionStart, int selectionLength)
{
QTC_ASSERT(m_locatorWidget, return);
m_locatorWidget->show(text, selectionStart, selectionLength);
}
+
+} // namespace Internal
diff --git a/src/plugins/locator/locatormanager.h b/src/plugins/locator/locatormanager.h
index f18ddb1002..53b1b8a392 100644
--- a/src/plugins/locator/locatormanager.h
+++ b/src/plugins/locator/locatormanager.h
@@ -36,9 +36,7 @@
namespace Locator {
-namespace Internal {
-class LocatorWidget;
-}
+namespace Internal { class LocatorWidget; }
class LOCATOR_EXPORT LocatorManager : public QObject
{
@@ -48,13 +46,7 @@ public:
LocatorManager(Internal::LocatorWidget *locatorWidget);
~LocatorManager();
- static LocatorManager* instance() { return m_instance; }
-
- void show(const QString &text, int selectionStart = -1, int selectionLength = 0);
-
-private:
- Internal::LocatorWidget *m_locatorWidget;
- static LocatorManager *m_instance;
+ static void show(const QString &text, int selectionStart = -1, int selectionLength = 0);
};
} // namespace Locator
diff --git a/src/plugins/locator/locatorplugin.cpp b/src/plugins/locator/locatorplugin.cpp
index e7758facbe..9513b31779 100644
--- a/src/plugins/locator/locatorplugin.cpp
+++ b/src/plugins/locator/locatorplugin.cpp
@@ -62,6 +62,7 @@
\internal
*/
+using namespace Core;
using namespace Locator;
using namespace Locator::Internal;
@@ -103,29 +104,29 @@ bool LocatorPlugin::initialize(const QStringList &, QString *)
m_locatorWidget = new LocatorWidget(this);
m_locatorWidget->setEnabled(false);
- Core::StatusBarWidget *view = new Core::StatusBarWidget;
+ StatusBarWidget *view = new StatusBarWidget;
view->setWidget(m_locatorWidget);
- view->setContext(Core::Context("LocatorWidget"));
- view->setPosition(Core::StatusBarWidget::First);
+ view->setContext(Context("LocatorWidget"));
+ view->setPosition(StatusBarWidget::First);
addAutoReleasedObject(view);
QAction *action = new QAction(m_locatorWidget->windowIcon(), m_locatorWidget->windowTitle(), this);
- Core::Command *cmd = Core::ActionManager::registerAction(action, "QtCreator.Locate",
- Core::Context(Core::Constants::C_GLOBAL));
+ Command *cmd = ActionManager::registerAction(action, "QtCreator.Locate",
+ Context(Core::Constants::C_GLOBAL));
cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+K")));
connect(action, SIGNAL(triggered()), this, SLOT(openLocator()));
connect(cmd, SIGNAL(keySequenceChanged()), this, SLOT(updatePlaceholderText()));
updatePlaceholderText(cmd);
- Core::ActionContainer *mtools = Core::ActionManager::actionContainer(Core::Constants::M_TOOLS);
+ ActionContainer *mtools = ActionManager::actionContainer(Core::Constants::M_TOOLS);
mtools->addAction(cmd);
addObject(new LocatorManager(m_locatorWidget));
- m_openDocumentsFilter = new OpenDocumentsFilter(Core::ICore::editorManager());
+ m_openDocumentsFilter = new OpenDocumentsFilter;
addObject(m_openDocumentsFilter);
- m_fileSystemFilter = new FileSystemFilter(Core::ICore::editorManager(), m_locatorWidget);
+ m_fileSystemFilter = new FileSystemFilter(m_locatorWidget);
addObject(m_fileSystemFilter);
m_executeFilter = new ExecuteFilter();
@@ -136,10 +137,10 @@ bool LocatorPlugin::initialize(const QStringList &, QString *)
return true;
}
-void LocatorPlugin::updatePlaceholderText(Core::Command *command)
+void LocatorPlugin::updatePlaceholderText(Command *command)
{
if (!command)
- command = qobject_cast<Core::Command *>(sender());
+ command = qobject_cast<Command *>(sender());
QTC_ASSERT(command, return);
if (command->keySequence().isEmpty())
m_locatorWidget->setPlaceholderText(tr("Type to locate"));
@@ -168,13 +169,13 @@ bool LocatorPlugin::delayedInitialize()
void LocatorPlugin::loadSettings()
{
- QSettings *qs = Core::ICore::settings();
+ QSettings *qs = ICore::settings();
// Backwards compatibility to old settings location
if (qs->contains(QLatin1String("QuickOpen/FiltersFilter"))) {
loadSettingsHelper(qs);
} else {
- Core::SettingsDatabase *settings = Core::ICore::settingsDatabase();
+ SettingsDatabase *settings = ICore::settingsDatabase();
loadSettingsHelper(settings);
}
@@ -190,7 +191,7 @@ void LocatorPlugin::loadSettings()
void LocatorPlugin::saveSettings()
{
if (m_settingsInitialized) {
- Core::SettingsDatabase *s = Core::ICore::settingsDatabase();
+ SettingsDatabase *s = ICore::settingsDatabase();
s->beginGroup(QLatin1String("QuickOpen"));
s->remove(QString());
s->setValue(QLatin1String("RefreshInterval"), refreshInterval());
@@ -213,7 +214,7 @@ void LocatorPlugin::saveSettings()
/*!
Return all filters, including the ones created by the user.
*/
-QList<ILocatorFilter*> LocatorPlugin::filters()
+QList<ILocatorFilter *> LocatorPlugin::filters()
{
return m_filters;
}
@@ -222,12 +223,12 @@ QList<ILocatorFilter*> LocatorPlugin::filters()
This returns a subset of all the filters, that contains only the filters that
have been created by the user at some point (maybe in a previous session).
*/
-QList<ILocatorFilter*> LocatorPlugin::customFilters()
+QList<ILocatorFilter *> LocatorPlugin::customFilters()
{
return m_customFilters;
}
-void LocatorPlugin::setFilters(QList<ILocatorFilter*> f)
+void LocatorPlugin::setFilters(QList<ILocatorFilter *> f)
{
m_filters = f;
m_locatorWidget->updateFilterList();
@@ -254,13 +255,13 @@ void LocatorPlugin::setRefreshInterval(int interval)
m_refreshTimer.start();
}
-void LocatorPlugin::refresh(QList<ILocatorFilter*> filters)
+void LocatorPlugin::refresh(QList<ILocatorFilter *> filters)
{
if (filters.isEmpty())
filters = m_filters;
QFuture<void> task = QtConcurrent::run(&ILocatorFilter::refresh, filters);
- Core::FutureProgress *progress = Core::ICore::progressManager()
- ->addTask(task, tr("Indexing"), QLatin1String(Locator::Constants::TASK_INDEX));
+ FutureProgress *progress =
+ ProgressManager::addTask(task, tr("Indexing"), Locator::Constants::TASK_INDEX);
connect(progress, SIGNAL(finished()), this, SLOT(saveSettings()));
}
diff --git a/src/plugins/locator/locatorplugin.h b/src/plugins/locator/locatorplugin.h
index a16f10b574..b30e224b08 100644
--- a/src/plugins/locator/locatorplugin.h
+++ b/src/plugins/locator/locatorplugin.h
@@ -66,21 +66,26 @@ public:
void extensionsInitialized();
bool delayedInitialize();
- QList<ILocatorFilter*> filters();
- QList<ILocatorFilter*> customFilters();
- void setFilters(QList<ILocatorFilter*> f);
- void setCustomFilters(QList<ILocatorFilter*> f);
+ QList<ILocatorFilter *> filters();
+ QList<ILocatorFilter *> customFilters();
+ void setFilters(QList<ILocatorFilter *> f);
+ void setCustomFilters(QList<ILocatorFilter *> f);
int refreshInterval();
void setRefreshInterval(int interval);
public slots:
- void refresh(QList<ILocatorFilter*> filters = QList<ILocatorFilter*>());
+ void refresh(QList<ILocatorFilter *> filters = QList<ILocatorFilter *>());
void saveSettings();
void openLocator();
private slots:
void updatePlaceholderText(Core::Command *command = 0);
+#ifdef WITH_TESTS
+ void test_basefilefilter();
+ void test_basefilefilter_data();
+#endif
+
private:
void loadSettings();
@@ -91,8 +96,8 @@ private:
SettingsPage *m_settingsPage;
bool m_settingsInitialized;
- QList<ILocatorFilter*> m_filters;
- QList<ILocatorFilter*> m_customFilters;
+ QList<ILocatorFilter *> m_filters;
+ QList<ILocatorFilter *> m_customFilters;
int m_refreshInterval;
QTimer m_refreshTimer;
OpenDocumentsFilter *m_openDocumentsFilter;
diff --git a/src/plugins/locator/locatorsearchutils.cpp b/src/plugins/locator/locatorsearchutils.cpp
new file mode 100644
index 0000000000..eb3eed749e
--- /dev/null
+++ b/src/plugins/locator/locatorsearchutils.cpp
@@ -0,0 +1,65 @@
+/****************************************************************************
+**
+** 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 "locatorsearchutils.h"
+
+#include <QSet>
+#include <QString>
+#include <QVariant>
+
+namespace Locator {
+
+uint qHash(const Locator::FilterEntry &entry)
+{
+ if (entry.internalData.canConvert(QVariant::String))
+ return QT_PREPEND_NAMESPACE(qHash)(entry.internalData.toString());
+ return QT_PREPEND_NAMESPACE(qHash)(entry.internalData.constData());
+}
+
+} // namespace Locator
+
+void Locator::Internal::runSearch(QFutureInterface<Locator::FilterEntry> &entries,
+ QList<ILocatorFilter *> filters, QString searchText)
+{
+ QSet<FilterEntry> alreadyAdded;
+ const bool checkDuplicates = (filters.size() > 1);
+ foreach (ILocatorFilter *filter, filters) {
+ if (entries.isCanceled())
+ break;
+
+ foreach (const FilterEntry &entry, filter->matchesFor(entries, searchText)) {
+ if (checkDuplicates && alreadyAdded.contains(entry))
+ continue;
+ entries.reportResult(entry);
+ if (checkDuplicates)
+ alreadyAdded.insert(entry);
+ }
+ }
+}
diff --git a/src/plugins/locator/locatorsearchutils.h b/src/plugins/locator/locatorsearchutils.h
new file mode 100644
index 0000000000..0b0d382689
--- /dev/null
+++ b/src/plugins/locator/locatorsearchutils.h
@@ -0,0 +1,47 @@
+/****************************************************************************
+**
+** 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 LOCATORSEARCHUTILS_H
+#define LOCATORSEARCHUTILS_H
+
+#include "locator_global.h"
+#include "ilocatorfilter.h"
+
+namespace Locator {
+namespace Internal {
+
+void LOCATOR_EXPORT runSearch(QFutureInterface<Locator::FilterEntry> &entries,
+ QList<ILocatorFilter *> filters,
+ QString searchText);
+
+} // namespace Internal
+} // namespace Locator
+
+#endif // LOCATORSEARCHUTILS_H
+
diff --git a/src/plugins/locator/locatorwidget.cpp b/src/plugins/locator/locatorwidget.cpp
index 1497b5e60f..f432c6d8dd 100644
--- a/src/plugins/locator/locatorwidget.cpp
+++ b/src/plugins/locator/locatorwidget.cpp
@@ -30,6 +30,7 @@
#include "locatorwidget.h"
#include "locatorplugin.h"
#include "locatorconstants.h"
+#include "locatorsearchutils.h"
#include "ilocatorfilter.h"
#include <coreplugin/coreconstants.h>
@@ -95,13 +96,10 @@ public:
void updatePreferredSize();
QSize preferredSize() const { return m_preferredSize; }
- void focusOutEvent (QFocusEvent * event) {
- if (Utils::HostOsInfo::isWindowsHost()) {
- if (event->reason() == Qt::ActiveWindowFocusReason)
- hide();
- } else {
- QTreeView::focusOutEvent(event);
- }
+ void focusOutEvent (QFocusEvent *event) {
+ if (event->reason() == Qt::ActiveWindowFocusReason)
+ hide();
+ QTreeView::focusOutEvent(event);
}
void next() {
@@ -130,12 +128,7 @@ private:
} // namespace Internal
-uint qHash(const FilterEntry &entry)
-{
- if (entry.internalData.canConvert(QVariant::String))
- return QT_PREPEND_NAMESPACE(qHash)(entry.internalData.toString());
- return QT_PREPEND_NAMESPACE(qHash)(entry.internalData.constData());
-}
+
} // namespace Locator
@@ -180,7 +173,7 @@ QVariant LocatorModel::data(const QModelIndex &index, int role) const
FilterEntry &entry = mEntries[index.row()];
if (!entry.fileIconResolved && !entry.fileName.isEmpty() && entry.displayIcon.isNull()) {
entry.fileIconResolved = true;
- entry.displayIcon = Core::FileIconProvider::instance()->icon(QFileInfo(entry.fileName));
+ entry.displayIcon = FileIconProvider::icon(entry.fileName);
}
return entry.displayIcon;
} else if (role == Qt::ForegroundRole && index.column() == 1) {
@@ -404,15 +397,11 @@ bool LocatorWidget::eventFilter(QObject *obj, QEvent *event)
}
}
} else if (obj == m_fileLineEdit && event->type() == QEvent::FocusOut) {
- 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)
+ QFocusEvent *fev = static_cast<QFocusEvent *>(event);
+ if (fev->reason() != Qt::ActiveWindowFocusReason || !m_completionList->isActiveWindow()) {
m_completionList->hide();
+ m_fileLineEdit->clearFocus();
+ }
} else if (obj == m_fileLineEdit && event->type() == QEvent::FocusIn) {
showPopupNow();
} else if (obj == this && event->type() == QEvent::ShortcutOverride) {
@@ -464,9 +453,9 @@ void LocatorWidget::showPopupNow()
showCompletionList();
}
-QList<ILocatorFilter*> LocatorWidget::filtersFor(const QString &text, QString &searchText)
+QList<ILocatorFilter *> LocatorWidget::filtersFor(const QString &text, QString &searchText)
{
- QList<ILocatorFilter*> filters = m_locatorPlugin->filters();
+ QList<ILocatorFilter *> filters = m_locatorPlugin->filters();
const int whiteSpace = text.indexOf(QLatin1Char(' '));
QString prefix;
if (whiteSpace >= 0)
@@ -484,42 +473,24 @@ QList<ILocatorFilter*> LocatorWidget::filtersFor(const QString &text, QString &s
return prefixFilters;
}
searchText = text;
- QList<ILocatorFilter*> activeFilters;
+ QList<ILocatorFilter *> activeFilters;
foreach (ILocatorFilter *filter, filters)
if (filter->isIncludedByDefault())
activeFilters << filter;
return activeFilters;
}
-static void filter_helper(QFutureInterface<Locator::FilterEntry> &entries, QList<ILocatorFilter *> filters, QString searchText)
-{
- QSet<FilterEntry> alreadyAdded;
- const bool checkDuplicates = (filters.size() > 1);
- foreach (ILocatorFilter *filter, filters) {
- if (entries.isCanceled())
- break;
-
- foreach (const FilterEntry &entry, filter->matchesFor(entries, searchText)) {
- if (checkDuplicates && alreadyAdded.contains(entry))
- continue;
- entries.reportResult(entry);
- if (checkDuplicates)
- alreadyAdded.insert(entry);
- }
- }
-}
-
void LocatorWidget::updateCompletionList(const QString &text)
{
m_updateRequested = true;
QString searchText;
- const QList<ILocatorFilter*> filters = filtersFor(text, searchText);
+ const QList<ILocatorFilter *> filters = filtersFor(text, searchText);
// cancel the old future
m_entriesWatcher->future().cancel();
m_entriesWatcher->future().waitForFinished();
- QFuture<FilterEntry> future = QtConcurrent::run(filter_helper, filters, searchText);
+ QFuture<FilterEntry> future = QtConcurrent::run(runSearch, filters, searchText);
m_entriesWatcher->setFuture(future);
}
@@ -564,6 +535,7 @@ void LocatorWidget::acceptCurrentEntry()
return;
const FilterEntry entry = m_locatorModel->data(index, Qt::UserRole).value<FilterEntry>();
m_completionList->hide();
+ m_fileLineEdit->clearFocus();
entry.filter->accept(entry);
}
@@ -589,9 +561,9 @@ void LocatorWidget::show(const QString &text, int selectionStart, int selectionL
void LocatorWidget::filterSelected()
{
QString searchText = tr("<type here>");
- QAction *action = qobject_cast<QAction*>(sender());
+ QAction *action = qobject_cast<QAction *>(sender());
QTC_ASSERT(action, return);
- ILocatorFilter *filter = action->data().value<ILocatorFilter*>();
+ ILocatorFilter *filter = action->data().value<ILocatorFilter *>();
QTC_ASSERT(filter, return);
QString currentText = m_fileLineEdit->text().trimmed();
// add shortcut string at front or replace existing shortcut string
@@ -599,7 +571,7 @@ void LocatorWidget::filterSelected()
searchText = currentText;
foreach (ILocatorFilter *otherfilter, m_locatorPlugin->filters()) {
if (currentText.startsWith(otherfilter->shortcutString() + QLatin1Char(' '))) {
- searchText = currentText.mid(otherfilter->shortcutString().length()+1);
+ searchText = currentText.mid(otherfilter->shortcutString().length() + 1);
break;
}
}
diff --git a/src/plugins/locator/opendocumentsfilter.cpp b/src/plugins/locator/opendocumentsfilter.cpp
index c626b2de94..85ead6f064 100644
--- a/src/plugins/locator/opendocumentsfilter.cpp
+++ b/src/plugins/locator/opendocumentsfilter.cpp
@@ -40,23 +40,23 @@ using namespace Locator;
using namespace Locator::Internal;
using namespace Utils;
-OpenDocumentsFilter::OpenDocumentsFilter(EditorManager *editorManager) :
- m_editorManager(editorManager)
+OpenDocumentsFilter::OpenDocumentsFilter()
{
setId("Open documents");
setDisplayName(tr("Open Documents"));
setShortcutString(QString(QLatin1Char('o')));
setIncludedByDefault(true);
- connect(m_editorManager, SIGNAL(editorOpened(Core::IEditor*)),
+ connect(EditorManager::instance(), SIGNAL(editorOpened(Core::IEditor*)),
this, SLOT(refreshInternally()));
- connect(m_editorManager, SIGNAL(editorsClosed(QList<Core::IEditor*>)),
+ connect(EditorManager::instance(), SIGNAL(editorsClosed(QList<Core::IEditor*>)),
this, SLOT(refreshInternally()));
}
QList<FilterEntry> OpenDocumentsFilter::matchesFor(QFutureInterface<Locator::FilterEntry> &future, const QString &entry_)
{
- QList<FilterEntry> value;
+ QList<FilterEntry> goodEntries;
+ QList<FilterEntry> betterEntries;
QString entry = entry_;
const QString lineNoSuffix = EditorManager::splitLineNumber(&entry);
const QChar asterisk = QLatin1Char('*');
@@ -65,36 +65,40 @@ QList<FilterEntry> OpenDocumentsFilter::matchesFor(QFutureInterface<Locator::Fil
pattern += asterisk;
QRegExp regexp(pattern, Qt::CaseInsensitive, QRegExp::Wildcard);
if (!regexp.isValid())
- return value;
- foreach (const OpenEditorsModel::Entry &editorEntry, m_editors) {
+ return goodEntries;
+ const Qt::CaseSensitivity caseSensitivityForPrefix = caseSensitivity(entry);
+ foreach (const DocumentModel::Entry &editorEntry, m_editors) {
if (future.isCanceled())
break;
QString fileName = editorEntry.fileName();
+ if (fileName.isEmpty())
+ continue;
QString displayName = editorEntry.displayName();
if (regexp.exactMatch(displayName)) {
- if (!fileName.isEmpty()) {
- QFileInfo fi(fileName);
- FilterEntry fiEntry(this, fi.fileName(), QString(fileName + lineNoSuffix));
- fiEntry.extraInfo = FileUtils::shortNativePath(FileName(fi));
- fiEntry.fileName = fileName;
- value.append(fiEntry);
- }
+ QFileInfo fi(fileName);
+ FilterEntry fiEntry(this, fi.fileName(), QString(fileName + lineNoSuffix));
+ fiEntry.extraInfo = FileUtils::shortNativePath(FileName(fi));
+ fiEntry.fileName = fileName;
+ QList<FilterEntry> &category = displayName.startsWith(entry, caseSensitivityForPrefix)
+ ? betterEntries : goodEntries;
+ category.append(fiEntry);
}
}
- return value;
+ betterEntries.append(goodEntries);
+ return betterEntries;
}
void OpenDocumentsFilter::refreshInternally()
{
m_editors.clear();
- foreach (IEditor *editor, m_editorManager->openedEditors()) {
- OpenEditorsModel::Entry entry;
- // don't work on IEditor directly, since that will be useless with split windows
- entry.m_displayName = editor->displayName();
- entry.m_fileName = editor->document()->fileName();
+ foreach (DocumentModel::Entry *e, EditorManager::documentModel()->documents()) {
+ DocumentModel::Entry entry;
+ // create copy with only the information relevant to use
+ // to avoid model deleting entries behind our back
+ entry.m_displayName = e->displayName();
+ entry.m_fileName = e->fileName();
m_editors.append(entry);
}
- m_editors += m_editorManager->openedEditorsModel()->restoredEditors();
}
void OpenDocumentsFilter::refresh(QFutureInterface<void> &future)
diff --git a/src/plugins/locator/opendocumentsfilter.h b/src/plugins/locator/opendocumentsfilter.h
index 52e9ce208a..a42f8fca50 100644
--- a/src/plugins/locator/opendocumentsfilter.h
+++ b/src/plugins/locator/opendocumentsfilter.h
@@ -32,16 +32,12 @@
#include "ilocatorfilter.h"
-#include <coreplugin/editormanager/openeditorsmodel.h>
+#include <coreplugin/editormanager/documentmodel.h>
#include <QString>
#include <QList>
#include <QFutureInterface>
-namespace Core {
- class EditorManager;
-}
-
namespace Locator {
namespace Internal {
@@ -50,7 +46,7 @@ class OpenDocumentsFilter : public Locator::ILocatorFilter
Q_OBJECT
public:
- explicit OpenDocumentsFilter(Core::EditorManager *editorManager);
+ OpenDocumentsFilter();
QList<Locator::FilterEntry> matchesFor(QFutureInterface<Locator::FilterEntry> &future, const QString &entry);
void accept(Locator::FilterEntry selection) const;
void refresh(QFutureInterface<void> &future);
@@ -59,9 +55,7 @@ public slots:
void refreshInternally();
private:
- Core::EditorManager *m_editorManager;
-
- QList<Core::OpenEditorsModel::Entry> m_editors;
+ QList<Core::DocumentModel::Entry> m_editors;
};
} // namespace Internal
diff --git a/src/plugins/locator/settingspage.h b/src/plugins/locator/settingspage.h
index 941fa8da70..7cd2ec71ee 100644
--- a/src/plugins/locator/settingspage.h
+++ b/src/plugins/locator/settingspage.h
@@ -74,7 +74,7 @@ private:
Ui::SettingsWidget m_ui;
LocatorPlugin *m_plugin;
- QWidget* m_page;
+ QWidget *m_page;
QList<ILocatorFilter *> m_filters;
QList<ILocatorFilter *> m_addedFilters;
QList<ILocatorFilter *> m_removedFilters;
diff --git a/src/plugins/macros/Macros.pluginspec.in b/src/plugins/macros/Macros.pluginspec.in
index 7ed581c5d7..5796bbbb7c 100644
--- a/src/plugins/macros/Macros.pluginspec.in
+++ b/src/plugins/macros/Macros.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"Macros\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"Macros\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Nicolas Arnaud-Cormos</copyright>
<license>
diff --git a/src/plugins/macros/findmacrohandler.cpp b/src/plugins/macros/findmacrohandler.cpp
index 403fc966e1..829475cb17 100644
--- a/src/plugins/macros/findmacrohandler.cpp
+++ b/src/plugins/macros/findmacrohandler.cpp
@@ -60,8 +60,7 @@ static const quint8 RESET = 5;
FindMacroHandler::FindMacroHandler():
IMacroHandler()
{
- const Core::EditorManager *editorManager = Core::EditorManager::instance();
- connect(editorManager, SIGNAL(currentEditorChanged(Core::IEditor*)),
+ connect(Core::EditorManager::instance(), SIGNAL(currentEditorChanged(Core::IEditor*)),
this, SLOT(changeEditor(Core::IEditor*)));
}
@@ -222,7 +221,7 @@ void FindMacroHandler::changeEditor(Core::IEditor *editor)
}
}
-void FindMacroHandler::startRecording(Macros::Macro* macro)
+void FindMacroHandler::startRecording(Macro* macro)
{
IMacroHandler::startRecording(macro);
Core::IEditor *current = Core::EditorManager::currentEditor();
diff --git a/src/plugins/macros/findmacrohandler.h b/src/plugins/macros/findmacrohandler.h
index 07f5a5f6ef..a1bfb8eebf 100644
--- a/src/plugins/macros/findmacrohandler.h
+++ b/src/plugins/macros/findmacrohandler.h
@@ -48,10 +48,10 @@ class FindMacroHandler : public IMacroHandler
public:
FindMacroHandler();
- void startRecording(Macros::Macro* macro);
+ void startRecording(Macro* macro);
- bool canExecuteEvent(const Macros::MacroEvent &macroEvent);
- bool executeEvent(const Macros::MacroEvent &macroEvent);
+ bool canExecuteEvent(const MacroEvent &macroEvent);
+ bool executeEvent(const MacroEvent &macroEvent);
public slots:
void findIncremental(const QString &txt, Find::FindFlags findFlags);
diff --git a/src/plugins/macros/imacrohandler.cpp b/src/plugins/macros/imacrohandler.cpp
index 5b5a9850c1..25630a24ae 100644
--- a/src/plugins/macros/imacrohandler.cpp
+++ b/src/plugins/macros/imacrohandler.cpp
@@ -31,7 +31,7 @@
#include "macro.h"
-using namespace Macros;
+using namespace Macros::Internal;
/*!
\class Macro::IEventHandler
diff --git a/src/plugins/macros/imacrohandler.h b/src/plugins/macros/imacrohandler.h
index 3b2e665b96..defa7d041c 100644
--- a/src/plugins/macros/imacrohandler.h
+++ b/src/plugins/macros/imacrohandler.h
@@ -30,20 +30,22 @@
#ifndef MACROSPLUGIN_IMACROHANDLER_H
#define MACROSPLUGIN_IMACROHANDLER_H
-#include "macros_global.h"
#include <QObject>
namespace Macros {
+namespace Internal {
class Macro;
class MacroEvent;
class MacroManager;
-class MACROS_EXPORT IMacroHandler: public QObject
+class IMacroHandler: public QObject
{
+ Q_OBJECT
+
public:
IMacroHandler();
- virtual ~IMacroHandler();
+ ~IMacroHandler();
virtual void startRecording(Macro* macro);
virtual void endRecordingMacro(Macro* macro);
@@ -65,6 +67,7 @@ private:
IMacroHandlerPrivate *d;
};
+} // namespace Internal
} // namespace Macros
#endif // MACROSPLUGIN_IMACROHANDLER_H
diff --git a/src/plugins/macros/macro.cpp b/src/plugins/macros/macro.cpp
index 0443e850e6..4f7e174626 100644
--- a/src/plugins/macros/macro.cpp
+++ b/src/plugins/macros/macro.cpp
@@ -36,7 +36,7 @@
#include <QFileInfo>
#include <QDataStream>
-using namespace Macros;
+using namespace Macros::Internal;
/*!
\class Macros::Macro
diff --git a/src/plugins/macros/macro.h b/src/plugins/macros/macro.h
index e1947f1b09..6a06beb015 100644
--- a/src/plugins/macros/macro.h
+++ b/src/plugins/macros/macro.h
@@ -30,8 +30,6 @@
#ifndef MACROSPLUGIN_MACRO_H
#define MACROSPLUGIN_MACRO_H
-#include "macros_global.h"
-
#include <QList>
#include <QString>
@@ -40,10 +38,11 @@ class QWidget;
QT_END_NAMESPACE
namespace Macros {
+namespace Internal {
class MacroEvent;
-class MACROS_EXPORT Macro
+class Macro
{
public:
Macro();
@@ -72,6 +71,7 @@ private:
MacroPrivate* d;
};
+} // namespace Internal
} // namespace Macros
#endif // MACROSPLUGIN_MACRO_H
diff --git a/src/plugins/macros/macroevent.cpp b/src/plugins/macros/macroevent.cpp
index 9c7aae96da..6c2e925a2d 100644
--- a/src/plugins/macros/macroevent.cpp
+++ b/src/plugins/macros/macroevent.cpp
@@ -33,7 +33,7 @@
#include <QVariant>
#include <QDataStream>
-using namespace Macros;
+using namespace Macros::Internal;
/*!
\class Macros::MacroEvent
diff --git a/src/plugins/macros/macroevent.h b/src/plugins/macros/macroevent.h
index 9345f89dbe..2e12f37704 100644
--- a/src/plugins/macros/macroevent.h
+++ b/src/plugins/macros/macroevent.h
@@ -30,8 +30,6 @@
#ifndef MACROSPLUGIN_MACROEVENT_H
#define MACROSPLUGIN_MACROEVENT_H
-#include "macros_global.h"
-
#include <coreplugin/id.h>
#include <QMap>
@@ -43,8 +41,9 @@ class QDataStream;
QT_END_NAMESPACE
namespace Macros {
+namespace Internal {
-class MACROS_EXPORT MacroEvent
+class MacroEvent
{
public:
MacroEvent();
@@ -66,6 +65,7 @@ private:
MacroEventPrivate* d;
};
+} // namespace Internal
} // namespace Macros
#endif // MACROSPLUGIN_MACROEVENT_H
diff --git a/src/plugins/macros/macrolocatorfilter.cpp b/src/plugins/macros/macrolocatorfilter.cpp
index 2d4d72386f..2bb81904c5 100644
--- a/src/plugins/macros/macrolocatorfilter.cpp
+++ b/src/plugins/macros/macrolocatorfilter.cpp
@@ -55,23 +55,33 @@ MacroLocatorFilter::~MacroLocatorFilter()
QList<Locator::FilterEntry> MacroLocatorFilter::matchesFor(QFutureInterface<Locator::FilterEntry> &future, const QString &entry)
{
Q_UNUSED(future)
- QList<Locator::FilterEntry> result;
+ QList<Locator::FilterEntry> goodEntries;
+ QList<Locator::FilterEntry> betterEntries;
- const QMap<QString, Macro*> &macros = MacroManager::instance()->macros();
+ const Qt::CaseSensitivity caseSensitivity_ = caseSensitivity(entry);
+
+ const QMap<QString, Macro*> &macros = MacroManager::macros();
QMapIterator<QString, Macro*> it(macros);
while (it.hasNext()) {
it.next();
QString name = it.key();
- if (name.contains(entry)) {
+ QList<Locator::FilterEntry> *category = 0;
+ if (name.startsWith(entry, caseSensitivity_))
+ category = &betterEntries;
+ else if (name.contains(entry, caseSensitivity_))
+ category = &goodEntries;
+
+ if (category) {
QVariant id;
Locator::FilterEntry entry(this, it.key(), id, m_icon);
entry.extraInfo = it.value()->description();
- result.append(entry);
+ category->append(entry);
}
}
- return result;
+ betterEntries.append(goodEntries);
+ return betterEntries;
}
void MacroLocatorFilter::accept(Locator::FilterEntry selection) const
diff --git a/src/plugins/macros/macromanager.cpp b/src/plugins/macros/macromanager.cpp
index bb93e12fab..8e57644486 100644
--- a/src/plugins/macros/macromanager.cpp
+++ b/src/plugins/macros/macromanager.cpp
@@ -62,7 +62,6 @@
#include <QFileDialog>
#include <QMessageBox>
-using namespace Macros;
using namespace Macros::Internal;
/*!
@@ -94,7 +93,7 @@ using namespace Macros::Internal;
the action id passed to the ActionManager.
*/
-class Macros::MacroManager::MacroManagerPrivate
+class MacroManager::MacroManagerPrivate
{
public:
MacroManagerPrivate(MacroManager *qq);
@@ -157,7 +156,7 @@ void MacroManager::MacroManagerPrivate::initialize()
static Core::Id makeId(const QString &name)
{
- return Core::Id(Constants::PREFIX_MACRO).withSuffix(name);
+ return Core::Id(Macros::Constants::PREFIX_MACRO).withSuffix(name);
}
void MacroManager::MacroManagerPrivate::addMacro(Macro *macro)
@@ -253,10 +252,10 @@ MacroManager::MacroManager(QObject *parent) :
QObject(parent),
d(new MacroManagerPrivate(this))
{
+ m_instance = this;
registerMacroHandler(d->actionHandler);
registerMacroHandler(d->findHandler);
registerMacroHandler(d->textEditorHandler);
- m_instance = this;
}
MacroManager::~MacroManager()
@@ -291,7 +290,7 @@ void MacroManager::startMacro()
QString executeShortcut = Core::ActionManager::command(Constants::EXECUTE_LAST_MACRO)->defaultKeySequence().toString();
QString help = tr("Macro mode. Type \"%1\" to stop recording and \"%2\" to play it")
.arg(endShortcut).arg(executeShortcut);
- Core::EditorManager::instance()->showEditorStatusBar(
+ Core::EditorManager::showEditorStatusBar(
QLatin1String(Constants::M_STATUS_BUFFER),
help,
tr("Stop Recording Macro"), this, SLOT(endMacro()));
@@ -299,7 +298,7 @@ void MacroManager::startMacro()
void MacroManager::endMacro()
{
- Core::EditorManager::instance()->hideEditorStatusBar(QLatin1String(Constants::M_STATUS_BUFFER));
+ Core::EditorManager::hideEditorStatusBar(QLatin1String(Constants::M_STATUS_BUFFER));
Core::ActionManager::command(Constants::START_MACRO)->action()->setEnabled(true);
Core::ActionManager::command(Constants::END_MACRO)->action()->setEnabled(false);
@@ -360,14 +359,14 @@ void MacroManager::deleteMacro(const QString &name)
}
}
-const QMap<QString,Macro*> &MacroManager::macros() const
+const QMap<QString,Macro*> &MacroManager::macros()
{
- return d->macros;
+ return m_instance->d->macros;
}
void MacroManager::registerMacroHandler(IMacroHandler *handler)
{
- d->handlers.prepend(handler);
+ m_instance->d->handlers.prepend(handler);
}
MacroManager *MacroManager::instance()
@@ -386,13 +385,13 @@ void MacroManager::changeMacro(const QString &name, const QString &description)
d->changeMacroDescription(macro, description);
}
-void Macros::MacroManager::saveLastMacro()
+void MacroManager::saveLastMacro()
{
if (d->currentMacro->events().count())
d->showSaveDialog();
}
-QString Macros::MacroManager::macrosDirectory() const
+QString MacroManager::macrosDirectory()
{
const QString &path =
Core::ICore::userResourcePath() + QLatin1String("/macros");
diff --git a/src/plugins/macros/macromanager.h b/src/plugins/macros/macromanager.h
index 045d140bc5..843c087fa7 100644
--- a/src/plugins/macros/macromanager.h
+++ b/src/plugins/macros/macromanager.h
@@ -30,8 +30,6 @@
#ifndef MACROSPLUGIN_MACROMANAGER_H
#define MACROSPLUGIN_MACROMANAGER_H
-#include "macros_global.h"
-
#include <QObject>
#include <QMap>
@@ -40,28 +38,24 @@ class QAction;
QT_END_NAMESPACE
namespace Macros {
+namespace Internal {
-class Macro;
class IMacroHandler;
+class Macro;
+class MacroOptionsWidget;
+class MacrosPlugin;
-namespace Internal {
- class MacroOptionsWidget;
-}
-
-class MACROS_EXPORT MacroManager : public QObject
+class MacroManager : public QObject
{
Q_OBJECT
public:
- explicit MacroManager(QObject *parent = 0);
- ~MacroManager();
-
static MacroManager *instance();
- const QMap<QString, Macro *> &macros() const;
+ static const QMap<QString, Macro *> &macros();
- void registerMacroHandler(IMacroHandler *handler);
+ static void registerMacroHandler(IMacroHandler *handler);
- QString macrosDirectory() const;
+ static QString macrosDirectory();
public slots:
void startMacro();
@@ -77,12 +71,18 @@ protected:
void changeMacro(const QString &name, const QString &description);
private:
+ explicit MacroManager(QObject *parent = 0);
+ ~MacroManager();
+
static MacroManager *m_instance;
class MacroManagerPrivate;
MacroManagerPrivate* d;
+
+ friend class Internal::MacrosPlugin;
};
+} // namespace Internal
} // namespace Macros
#endif // MACROSPLUGIN_MACROMANAGER_H
diff --git a/src/plugins/macros/macrooptionspage.h b/src/plugins/macros/macrooptionspage.h
index 6e9f8ea1bf..a1b3575744 100644
--- a/src/plugins/macros/macrooptionspage.h
+++ b/src/plugins/macros/macrooptionspage.h
@@ -30,8 +30,6 @@
#ifndef MACROSPLUGIN_MACROOPTIONSPAGE_H
#define MACROSPLUGIN_MACROOPTIONSPAGE_H
-#include "macros_global.h"
-
#include <coreplugin/dialogs/ioptionspage.h>
namespace Macros {
@@ -39,7 +37,7 @@ namespace Internal {
class MacroOptionsWidget;
-class MACROS_EXPORT MacroOptionsPage : public Core::IOptionsPage
+class MacroOptionsPage : public Core::IOptionsPage
{
Q_OBJECT
diff --git a/src/plugins/macros/macrooptionswidget.cpp b/src/plugins/macros/macrooptionswidget.cpp
index fede998dfa..dfe386d306 100644
--- a/src/plugins/macros/macrooptionswidget.cpp
+++ b/src/plugins/macros/macrooptionswidget.cpp
@@ -97,9 +97,9 @@ void MacroOptionsWidget::initialize()
void MacroOptionsWidget::createTable()
{
- QDir dir(MacroManager::instance()->macrosDirectory());
+ QDir dir(MacroManager::macrosDirectory());
const Core::Id base = Core::Id(Constants::PREFIX_MACRO);
- QMapIterator<QString, Macro *> it(MacroManager::instance()->macros());
+ QMapIterator<QString, Macro *> it(MacroManager::macros());
while (it.hasNext()) {
it.next();
QFileInfo fileInfo(it.value()->fileName());
diff --git a/src/plugins/macros/macros.pro b/src/plugins/macros/macros.pro
index e328cd59a3..2f43549dba 100644
--- a/src/plugins/macros/macros.pro
+++ b/src/plugins/macros/macros.pro
@@ -3,7 +3,6 @@ DEFINES += MACROS_LIBRARY
include(../../qtcreatorplugin.pri)
HEADERS += macrosplugin.h \
- macros_global.h \
macrosconstants.h \
macro.h \
macroevent.h \
diff --git a/src/plugins/macros/macros.qbs b/src/plugins/macros/macros.qbs
index c30877a7cc..6dcc377abe 100644
--- a/src/plugins/macros/macros.qbs
+++ b/src/plugins/macros/macros.qbs
@@ -33,7 +33,6 @@ QtcPlugin {
"macrooptionswidget.h",
"macrooptionswidget.ui",
"macros.qrc",
- "macros_global.h",
"macrosconstants.h",
"macrosplugin.cpp",
"macrosplugin.h",
diff --git a/src/plugins/macros/macros_global.h b/src/plugins/macros/macros_global.h
deleted file mode 100644
index 397a070fca..0000000000
--- a/src/plugins/macros/macros_global.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/**************************************************************************
-**
-** Copyright (c) 2013 Nicolas Arnaud-Cormos
-** 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 MACROSPLUGIN_MACROS_GLOBAL_H
-#define MACROSPLUGIN_MACROS_GLOBAL_H
-
-#include <qglobal.h>
-
-#if defined(MACROS_LIBRARY)
-# define MACROS_EXPORT Q_DECL_EXPORT
-#else
-# define MACROS_EXPORT Q_DECL_IMPORT
-#endif
-
-#endif // MACROSPLUGIN_MACROS_GLOBAL_H
diff --git a/src/plugins/macros/macrosplugin.cpp b/src/plugins/macros/macrosplugin.cpp
index b31aa2f559..e3d445aada 100644
--- a/src/plugins/macros/macrosplugin.cpp
+++ b/src/plugins/macros/macrosplugin.cpp
@@ -50,7 +50,6 @@
#include <QKeySequence>
#include <QMenu>
-using namespace Macros;
using namespace Macros::Internal;
MacrosPlugin::MacrosPlugin()
@@ -59,6 +58,7 @@ MacrosPlugin::MacrosPlugin()
MacrosPlugin::~MacrosPlugin()
{
+ delete m_macroManager;
}
bool MacrosPlugin::initialize(const QStringList &arguments, QString *errorMessage)
diff --git a/src/plugins/macros/macrosplugin.h b/src/plugins/macros/macrosplugin.h
index 4617dfdb90..9eb196dcc0 100644
--- a/src/plugins/macros/macrosplugin.h
+++ b/src/plugins/macros/macrosplugin.h
@@ -33,11 +33,10 @@
#include <extensionsystem/iplugin.h>
namespace Macros {
+namespace Internal {
class MacroManager;
-namespace Internal {
-
class MacrosPlugin : public ExtensionSystem::IPlugin
{
Q_OBJECT
diff --git a/src/plugins/macros/texteditormacrohandler.cpp b/src/plugins/macros/texteditormacrohandler.cpp
index 7e6e4f0eec..8d156eac9e 100644
--- a/src/plugins/macros/texteditormacrohandler.cpp
+++ b/src/plugins/macros/texteditormacrohandler.cpp
@@ -61,14 +61,14 @@ static quint8 COUNT = 5;
TextEditorMacroHandler::TextEditorMacroHandler():
IMacroHandler()
{
- const Core::EditorManager *editorManager = Core::EditorManager::instance();
+ const QObject *editorManager = Core::EditorManager::instance();
connect(editorManager, SIGNAL(currentEditorChanged(Core::IEditor*)),
this, SLOT(changeEditor(Core::IEditor*)));
connect(editorManager, SIGNAL(editorAboutToClose(Core::IEditor*)),
this, SLOT(closeEditor(Core::IEditor*)));
}
-void TextEditorMacroHandler::startRecording(Macros::Macro *macro)
+void TextEditorMacroHandler::startRecording(Macro *macro)
{
IMacroHandler::startRecording(macro);
if (isRecording() && m_currentEditor && m_currentEditor->widget())
@@ -78,7 +78,7 @@ void TextEditorMacroHandler::startRecording(Macros::Macro *macro)
Core::ActionManager::command(TextEditor::Constants::COMPLETE_THIS)->shortcut()->blockSignals(true);
}
-void TextEditorMacroHandler::endRecordingMacro(Macros::Macro *macro)
+void TextEditorMacroHandler::endRecordingMacro(Macro *macro)
{
if (m_currentEditor && m_currentEditor->widget())
m_currentEditor->widget()->removeEventFilter(this);
diff --git a/src/plugins/macros/texteditormacrohandler.h b/src/plugins/macros/texteditormacrohandler.h
index b14065f854..c04710a0da 100644
--- a/src/plugins/macros/texteditormacrohandler.h
+++ b/src/plugins/macros/texteditormacrohandler.h
@@ -43,18 +43,18 @@ class ITextEditor;
namespace Macros {
namespace Internal {
-class TextEditorMacroHandler : public Macros::IMacroHandler
+class TextEditorMacroHandler : public IMacroHandler
{
Q_OBJECT
public:
TextEditorMacroHandler();
- void startRecording(Macros::Macro *macro);
- void endRecordingMacro(Macros::Macro *macro);
+ void startRecording(Macro *macro);
+ void endRecordingMacro(Macro *macro);
- bool canExecuteEvent(const Macros::MacroEvent &macroEvent);
- bool executeEvent(const Macros::MacroEvent &macroEvent);
+ bool canExecuteEvent(const MacroEvent &macroEvent);
+ bool executeEvent(const MacroEvent &macroEvent);
bool eventFilter(QObject *watched, QEvent *event);
diff --git a/src/plugins/madde/Madde.pluginspec.in b/src/plugins/madde/Madde.pluginspec.in
index 53485f089f..295a7d7e5c 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\" disabledByDefault=\"true\">
+<plugin name=\"Madde\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\" disabledByDefault=\"true\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/madde/debianmanager.cpp b/src/plugins/madde/debianmanager.cpp
index e629f9ae53..c0573c925d 100644
--- a/src/plugins/madde/debianmanager.cpp
+++ b/src/plugins/madde/debianmanager.cpp
@@ -696,7 +696,7 @@ void DebianManager::controlWasChanged()
WatchableFile *file = qobject_cast<WatchableFile *>(sender());
if (!file)
return;
- emit controlChanged(Utils::FileName::fromString(file->fileName()).parentDir());
+ emit controlChanged(Utils::FileName::fromString(file->filePath()).parentDir());
}
void DebianManager::changelogWasChanged()
@@ -704,7 +704,7 @@ void DebianManager::changelogWasChanged()
WatchableFile *file = qobject_cast<WatchableFile *>(sender());
if (!file)
return;
- emit changelogChanged(Utils::FileName::fromString(file->fileName()).parentDir());
+ emit changelogChanged(Utils::FileName::fromString(file->filePath()).parentDir());
}
Utils::FileName DebianManager::changelogFilePath(const Utils::FileName &debianDir)
diff --git a/src/plugins/madde/madde.pro b/src/plugins/madde/madde.pro
index 2ab51455d1..0212ac0da3 100644
--- a/src/plugins/madde/madde.pro
+++ b/src/plugins/madde/madde.pro
@@ -3,7 +3,6 @@ QT += network
include(../../qtcreatorplugin.pri)
HEADERS += \
- madde_exports.h \
maddeplugin.h \
debianmanager.h \
maemoconstants.h \
diff --git a/src/plugins/madde/madde.qbs b/src/plugins/madde/madde.qbs
index 368f96b055..8cbfefaa8d 100644
--- a/src/plugins/madde/madde.qbs
+++ b/src/plugins/madde/madde.qbs
@@ -16,7 +16,6 @@ QtcPlugin {
files: [
"debianmanager.cpp",
"debianmanager.h",
- "madde_exports.h",
"maddedevice.cpp",
"maddedevice.h",
"maddedeviceconfigurationfactory.cpp",
diff --git a/src/plugins/madde/maddedevice.cpp b/src/plugins/madde/maddedevice.cpp
index e8f3c5546f..b055872adb 100644
--- a/src/plugins/madde/maddedevice.cpp
+++ b/src/plugins/madde/maddedevice.cpp
@@ -31,11 +31,13 @@
#include "maddedevicetester.h"
#include "maemoconstants.h"
-#include <remotelinux/linuxdevicetestdialog.h>
+#include <remotelinux/linuxdeviceprocess.h>
#include <remotelinux/publickeydeploymentdialog.h>
#include <remotelinux/remotelinux_constants.h>
#include <utils/qtcassert.h>
+#include <QStringList>
+
using namespace ProjectExplorer;
using namespace RemoteLinux;
@@ -111,10 +113,19 @@ QSize MaddeDevice::packageManagerIconSize(Core::Id type)
return QSize();
}
-AbstractLinuxDeviceTester *MaddeDevice::createDeviceTester() const
+DeviceTester *MaddeDevice::createDeviceTester() const
{
return new MaddeDeviceTester;
}
+DeviceProcess *MaddeDevice::createProcess(QObject *parent) const
+{
+ LinuxDeviceProcess * const proc
+ = static_cast<LinuxDeviceProcess *>(LinuxDevice::createProcess(parent));
+ proc->setRcFilesToSource(QStringList() << QLatin1String("/etc/profile")
+ << QLatin1String("/home/user/.profile") << QLatin1String("~/.profile"));
+ return proc;
+}
+
} // namespace Internal
} // namespace Madde
diff --git a/src/plugins/madde/maddedevice.h b/src/plugins/madde/maddedevice.h
index 463c225231..a0bb80ca6d 100644
--- a/src/plugins/madde/maddedevice.h
+++ b/src/plugins/madde/maddedevice.h
@@ -58,7 +58,8 @@ public:
static QSize packageManagerIconSize(Core::Id type);
- RemoteLinux::AbstractLinuxDeviceTester *createDeviceTester() const;
+ ProjectExplorer::DeviceTester *createDeviceTester() const;
+ ProjectExplorer::DeviceProcess *createProcess(QObject *parent) const;
private:
MaddeDevice();
diff --git a/src/plugins/madde/maddedevicetester.cpp b/src/plugins/madde/maddedevicetester.cpp
index 8a68d98565..29b7d888f8 100644
--- a/src/plugins/madde/maddedevicetester.cpp
+++ b/src/plugins/madde/maddedevicetester.cpp
@@ -47,7 +47,7 @@ const char QmlToolingDirectory[] = "/usr/lib/qt4/plugins/qmltooling";
} // anonymous namespace
MaddeDeviceTester::MaddeDeviceTester(QObject *parent)
- : AbstractLinuxDeviceTester(parent),
+ : ProjectExplorer::DeviceTester(parent),
m_genericTester(new GenericLinuxDeviceTester(this)),
m_state(Inactive),
m_processRunner(0)
@@ -68,8 +68,8 @@ void MaddeDeviceTester::testDevice(const ProjectExplorer::IDevice::ConstPtr &dev
m_state = GenericTest;
connect(m_genericTester, SIGNAL(progressMessage(QString)), SIGNAL(progressMessage(QString)));
connect(m_genericTester, SIGNAL(errorMessage(QString)), SIGNAL(errorMessage(QString)));
- connect(m_genericTester, SIGNAL(finished(RemoteLinux::AbstractLinuxDeviceTester::TestResult)),
- SLOT(handleGenericTestFinished(RemoteLinux::AbstractLinuxDeviceTester::TestResult)));
+ connect(m_genericTester, SIGNAL(finished(ProjectExplorer::DeviceTester::TestResult)),
+ SLOT(handleGenericTestFinished(ProjectExplorer::DeviceTester::TestResult)));
m_genericTester->testDevice(deviceConfiguration);
}
diff --git a/src/plugins/madde/maddedevicetester.h b/src/plugins/madde/maddedevicetester.h
index cf63d41311..98461f0beb 100644
--- a/src/plugins/madde/maddedevicetester.h
+++ b/src/plugins/madde/maddedevicetester.h
@@ -38,7 +38,7 @@ class SshRemoteProcessRunner;
namespace Madde {
namespace Internal {
-class MaddeDeviceTester : public RemoteLinux::AbstractLinuxDeviceTester
+class MaddeDeviceTester : public ProjectExplorer::DeviceTester
{
Q_OBJECT
@@ -50,7 +50,7 @@ public:
void stopTest();
private slots:
- void handleGenericTestFinished(RemoteLinux::AbstractLinuxDeviceTester::TestResult result);
+ void handleGenericTestFinished(ProjectExplorer::DeviceTester::TestResult result);
void handleConnectionError();
void handleProcessFinished(int exitStatus);
@@ -66,7 +66,7 @@ private:
RemoteLinux::GenericLinuxDeviceTester * const m_genericTester;
State m_state;
- TestResult m_result;
+ ProjectExplorer::DeviceTester::TestResult m_result;
QSsh::SshRemoteProcessRunner *m_processRunner;
ProjectExplorer::IDevice::ConstPtr m_deviceConfiguration;
};
diff --git a/src/plugins/madde/maddeqemustartstep.cpp b/src/plugins/madde/maddeqemustartstep.cpp
index 5d0ee6df12..1226fbc560 100644
--- a/src/plugins/madde/maddeqemustartstep.cpp
+++ b/src/plugins/madde/maddeqemustartstep.cpp
@@ -113,7 +113,7 @@ void MaddeQemuStartStep::ctor()
Core::Id MaddeQemuStartStep::stepId()
{
- return Core::Id("Madde.MaddeQemuCheckStep");
+ return "Madde.MaddeQemuCheckStep";
}
QString MaddeQemuStartStep::stepDisplayName()
diff --git a/src/plugins/madde/maddeuploadandinstallpackagesteps.cpp b/src/plugins/madde/maddeuploadandinstallpackagesteps.cpp
index 5d7c2edd89..6d3f5d29dc 100644
--- a/src/plugins/madde/maddeuploadandinstallpackagesteps.cpp
+++ b/src/plugins/madde/maddeuploadandinstallpackagesteps.cpp
@@ -143,7 +143,7 @@ bool MaemoUploadAndInstallPackageStep::initInternal(QString *error)
Core::Id MaemoUploadAndInstallPackageStep::stepId()
{
- return Core::Id("MaemoUploadAndInstallDpkgPackageStep");
+ return "MaemoUploadAndInstallDpkgPackageStep";
}
QString MaemoUploadAndInstallPackageStep::displayName()
diff --git a/src/plugins/madde/maemodeploybymountsteps.cpp b/src/plugins/madde/maemodeploybymountsteps.cpp
index 9ff045826e..b0089ff746 100644
--- a/src/plugins/madde/maemodeploybymountsteps.cpp
+++ b/src/plugins/madde/maemodeploybymountsteps.cpp
@@ -410,7 +410,7 @@ bool MaemoInstallPackageViaMountStep::initInternal(QString *error)
Core::Id MaemoInstallPackageViaMountStep::stepId()
{
- return Core::Id("MaemoMountAndInstallDeployStep");
+ return "MaemoMountAndInstallDeployStep";
}
QString MaemoInstallPackageViaMountStep::displayName()
@@ -451,7 +451,7 @@ bool MaemoCopyFilesViaMountStep::initInternal(QString *error)
Core::Id MaemoCopyFilesViaMountStep::stepId()
{
- return Core::Id("MaemoMountAndCopyDeployStep");
+ return "MaemoMountAndCopyDeployStep";
}
QString MaemoCopyFilesViaMountStep::displayName()
diff --git a/src/plugins/madde/maemodeviceconfigwizard.cpp b/src/plugins/madde/maemodeviceconfigwizard.cpp
index f80b3b4169..f3f8c311d9 100644
--- a/src/plugins/madde/maemodeviceconfigwizard.cpp
+++ b/src/plugins/madde/maemodeviceconfigwizard.cpp
@@ -40,7 +40,6 @@
#include "maemoglobal.h"
#include <remotelinux/genericlinuxdeviceconfigurationwizardpages.h>
-#include <remotelinux/linuxdevicetestdialog.h>
#include <remotelinux/sshkeydeployer.h>
#include <utils/fileutils.h>
#include <ssh/sshkeygenerator.h>
@@ -441,7 +440,7 @@ private:
m_ui->passwordLineEdit->setEnabled(false);
m_ui->deployButton->setEnabled(false);
SshConnectionParameters sshParams;
- sshParams.authenticationType = SshConnectionParameters::AuthenticationByPassword;
+ sshParams.authenticationType = SshConnectionParameters::AuthenticationTypePassword;
sshParams.host = hostAddress();
sshParams.port = m_wizardData.sshPort;
sshParams.password = password();
@@ -553,35 +552,26 @@ MaemoDeviceConfigWizard::~MaemoDeviceConfigWizard()
IDevice::Ptr MaemoDeviceConfigWizard::device()
{
- bool doTest;
QString freePortsSpec;
QSsh::SshConnectionParameters sshParams;
sshParams.userName = defaultUser();
sshParams.host = d->wizardData.hostName;
sshParams.port = d->wizardData.sshPort;
if (d->wizardData.machineType == IDevice::Emulator) {
- sshParams.authenticationType = QSsh::SshConnectionParameters::AuthenticationByPassword;
+ sshParams.authenticationType = QSsh::SshConnectionParameters::AuthenticationTypePassword;
sshParams.password.clear();
sshParams.timeout = 30;
freePortsSpec = QLatin1String("13219,14168");
- doTest = false;
} else {
- sshParams.authenticationType = QSsh::SshConnectionParameters::AuthenticationByKey;
+ sshParams.authenticationType = QSsh::SshConnectionParameters::AuthenticationTypePublicKey;
sshParams.privateKeyFile = d->wizardData.privateKeyFilePath;
sshParams.timeout = 10;
freePortsSpec = QLatin1String("10000-10100");
- doTest = true;
}
const MaddeDevice::Ptr device = MaddeDevice::create(d->wizardData.configName,
d->wizardData.deviceType, d->wizardData.machineType);
device->setFreePorts(PortList::fromString(freePortsSpec));
device->setSshParameters(sshParams);
- if (doTest) {
- // Might be called after accept.
- QWidget *parent = isVisible() ? this : static_cast<QWidget *>(0);
- LinuxDeviceTestDialog dlg(device, new MaddeDeviceTester(this), parent);
- dlg.exec();
- }
return device;
}
diff --git a/src/plugins/madde/maemoglobal.h b/src/plugins/madde/maemoglobal.h
index 61a2fed058..feaeb4b6a1 100644
--- a/src/plugins/madde/maemoglobal.h
+++ b/src/plugins/madde/maemoglobal.h
@@ -56,10 +56,12 @@ class WatchableFile : public Core::IDocument
Q_OBJECT
public:
WatchableFile(const QString &fileName, QObject *parent = 0)
- : Core::IDocument(parent), m_fileName(fileName) {}
+ : Core::IDocument(parent)
+ {
+ setFilePath(fileName);
+ }
bool save(QString *, const QString &, bool) { return false; }
- QString fileName() const { return m_fileName; }
QString defaultPath() const { return QString(); }
QString suggestedFileName() const { return QString(); }
QString mimeType() const { return QLatin1String("text/plain"); }
@@ -67,13 +69,9 @@ public:
bool isSaveAsAllowed() const { return false; }
ReloadBehavior reloadBehavior(ChangeTrigger, ChangeType) const { return BehaviorSilent; }
bool reload(QString *, ReloadFlag, ChangeType) { emit modified(); return true; }
- void rename(const QString &) {}
signals:
void modified();
-
-private:
- QString m_fileName;
};
class MaemoGlobal
diff --git a/src/plugins/madde/maemoinstalltosysrootstep.cpp b/src/plugins/madde/maemoinstalltosysrootstep.cpp
index 00c918b712..85daa541e7 100644
--- a/src/plugins/madde/maemoinstalltosysrootstep.cpp
+++ b/src/plugins/madde/maemoinstalltosysrootstep.cpp
@@ -242,7 +242,7 @@ QStringList MaemoInstallDebianPackageToSysrootStep::madArguments() const
}
const Core::Id MaemoInstallDebianPackageToSysrootStep::Id
- = Core::Id("MaemoInstallDebianPackageToSysrootStep");
+ = "MaemoInstallDebianPackageToSysrootStep";
QString MaemoInstallDebianPackageToSysrootStep::displayName()
{
@@ -317,7 +317,7 @@ BuildStepConfigWidget *MaemoCopyToSysrootStep::createConfigWidget()
}
const Core::Id MaemoCopyToSysrootStep::Id
- = Core::Id("MaemoCopyToSysrootStep");
+ = "MaemoCopyToSysrootStep";
QString MaemoCopyToSysrootStep::displayName()
{
return tr("Copy files to sysroot");
@@ -366,7 +366,7 @@ bool MaemoMakeInstallToSysrootStep::init()
processParameters()->setCommand(command);
processParameters()->setArguments(args.join(QLatin1String(" ")));
processParameters()->setEnvironment(env);
- processParameters()->setWorkingDirectory(bc->buildDirectory());
+ processParameters()->setWorkingDirectory(bc->buildDirectory().toString());
return true;
}
@@ -376,7 +376,7 @@ BuildStepConfigWidget *MaemoMakeInstallToSysrootStep::createConfigWidget()
}
const Core::Id MaemoMakeInstallToSysrootStep::Id
- = Core::Id("MaemoMakeInstallToSysrootStep");
+ = "MaemoMakeInstallToSysrootStep";
QString MaemoMakeInstallToSysrootStep::displayName()
{
return tr("Copy files to sysroot");
diff --git a/src/plugins/madde/maemopackagecreationstep.cpp b/src/plugins/madde/maemopackagecreationstep.cpp
index d87f1aede2..254d0ea6be 100644
--- a/src/plugins/madde/maemopackagecreationstep.cpp
+++ b/src/plugins/madde/maemopackagecreationstep.cpp
@@ -257,7 +257,7 @@ MaemoDebianPackageCreationStep::MaemoDebianPackageCreationStep(BuildStepList *bs
}
const Core::Id MaemoDebianPackageCreationStep::CreatePackageId
- = Core::Id("MaemoDebianPackageCreationStep");
+ = "MaemoDebianPackageCreationStep";
MaemoDebianPackageCreationStep::MaemoDebianPackageCreationStep(BuildStepList *buildConfig,
MaemoDebianPackageCreationStep *other)
@@ -352,7 +352,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."),
- FileName(), -1, Core::Id(TASK_CATEGORY_BUILDSYSTEM)));
+ FileName(), -1, Core::Id(TASK_CATEGORY_DEPLOYMENT)));
}
}
diff --git a/src/plugins/madde/maemopublisherfremantlefree.cpp b/src/plugins/madde/maemopublisherfremantlefree.cpp
index d5dd05fade..7f3f7c0ef6 100644
--- a/src/plugins/madde/maemopublisherfremantlefree.cpp
+++ b/src/plugins/madde/maemopublisherfremantlefree.cpp
@@ -70,7 +70,7 @@ MaemoPublisherFremantleFree::MaemoPublisherFremantleFree(const ProjectExplorer::
m_state(Inactive),
m_uploader(0)
{
- m_sshParams.authenticationType = SshConnectionParameters::AuthenticationByKey;
+ m_sshParams.authenticationType = SshConnectionParameters::AuthenticationTypePublicKey;
m_sshParams.timeout = 30;
m_sshParams.port = 22;
m_process = new QProcess(this);
@@ -210,7 +210,7 @@ bool MaemoPublisherFremantleFree::copyRecursively(const QString &srcFilePath,
QByteArray rulesContents = reader.data();
rulesContents.replace("$(MAKE) clean", "# $(MAKE) clean");
rulesContents.replace("# Add here commands to configure the package.",
- "qmake " + QFileInfo(m_project->document()->fileName()).fileName().toLocal8Bit());
+ "qmake " + QFileInfo(m_project->projectFilePath()).fileName().toLocal8Bit());
MaemoDebianPackageCreationStep::ensureShlibdeps(rulesContents);
FileSaver saver(tgtFilePath);
saver.write(rulesContents);
diff --git a/src/plugins/madde/maemoqemumanager.cpp b/src/plugins/madde/maemoqemumanager.cpp
index 12c875981f..9a5ff3d6f3 100644
--- a/src/plugins/madde/maemoqemumanager.cpp
+++ b/src/plugins/madde/maemoqemumanager.cpp
@@ -65,6 +65,7 @@
#include <limits.h>
using namespace ProjectExplorer;
+using namespace QtSupport;
using namespace RemoteLinux;
namespace Madde {
@@ -102,16 +103,16 @@ MaemoQemuManager::MaemoQemuManager(QObject *parent)
m_qemuAction->setVisible(false);
// listen to Qt version changes to update the start button
- connect(QtSupport::QtVersionManager::instance(), SIGNAL(qtVersionsChanged(QList<int>,QList<int>,QList<int>)),
+ connect(QtVersionManager::instance(), SIGNAL(qtVersionsChanged(QList<int>,QList<int>,QList<int>)),
this, SLOT(qtVersionsChanged(QList<int>,QList<int>,QList<int>)));
// listen to project add, remove and startup changes to udate start button
- SessionManager *session = ProjectExplorerPlugin::instance()->session();
- connect(session, SIGNAL(projectAdded(ProjectExplorer::Project*)), this,
+ QObject *sessionManager = SessionManager::instance();
+ connect(sessionManager, SIGNAL(projectAdded(ProjectExplorer::Project*)), this,
SLOT(projectAdded(ProjectExplorer::Project*)));
- connect(session, SIGNAL(projectRemoved(ProjectExplorer::Project*)), this,
+ connect(sessionManager, SIGNAL(projectRemoved(ProjectExplorer::Project*)), this,
SLOT(projectRemoved(ProjectExplorer::Project*)));
- connect(session, SIGNAL(startupProjectChanged(ProjectExplorer::Project*)),
+ connect(sessionManager, SIGNAL(startupProjectChanged(ProjectExplorer::Project*)),
this, SLOT(projectChanged(ProjectExplorer::Project*)));
connect(m_qemuProcess, SIGNAL(error(QProcess::ProcessError)), this,
@@ -176,10 +177,9 @@ void MaemoQemuManager::qtVersionsChanged(const QList<int> &added, const QList<in
{
QList<int> uniqueIds;
uniqueIds << added << removed << changed;
- QtSupport::QtVersionManager *manager = QtSupport::QtVersionManager::instance();
foreach (int uniqueId, uniqueIds) {
- if (manager->isValidId(uniqueId)) {
- MaemoQtVersion *version = dynamic_cast<MaemoQtVersion *>(manager->version(uniqueId));
+ if (QtVersionManager::isValidId(uniqueId)) {
+ MaemoQtVersion *version = dynamic_cast<MaemoQtVersion *>(QtVersionManager::version(uniqueId));
if (version) {
MaemoQemuRuntime runtime
@@ -283,10 +283,8 @@ void MaemoQemuManager::systemChanged()
void MaemoQemuManager::environmentChanged()
{
// likely to happen when the Qt version changes the build config is using
- if (ProjectExplorerPlugin *explorer = ProjectExplorerPlugin::instance()) {
- if (Project *project = explorer->session()->startupProject())
- toggleStarterButton(project->activeTarget());
- }
+ if (Project *project = SessionManager::startupProject())
+ toggleStarterButton(project->activeTarget());
}
void MaemoQemuManager::deviceConfigurationChanged(ProjectExplorer::Target *target)
@@ -297,10 +295,10 @@ void MaemoQemuManager::deviceConfigurationChanged(ProjectExplorer::Target *targe
void MaemoQemuManager::startRuntime()
{
m_userTerminated = false;
- Project *p = ProjectExplorerPlugin::instance()->session()->startupProject();
+ Project *p = SessionManager::startupProject();
if (!p)
return;
- QtSupport::BaseQtVersion *version;
+ BaseQtVersion *version;
if (!targetUsesMatchingRuntimeConfig(p->activeTarget(), &version)) {
qWarning("Strange: Qemu button was enabled, but target does not match.");
return;
@@ -458,7 +456,7 @@ void MaemoQemuManager::toggleStarterButton(Target *target)
{
int uniqueId = -1;
if (target) {
- QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(target->kit());
+ BaseQtVersion *version = QtKitInformation::qtVersion(target->kit());
if (version)
uniqueId = version->uniqueId();
}
@@ -470,8 +468,7 @@ void MaemoQemuManager::toggleStarterButton(Target *target)
if (m_runningQtId == uniqueId)
isRunning = false;
- const Project * const p
- = ProjectExplorerPlugin::instance()->session()->startupProject();
+ const Project * const p = SessionManager::startupProject();
const bool qemuButtonEnabled
= p && p->activeTarget() && MaemoGlobal::hasMaemoDevice(target->kit())
&& m_runtimes.value(uniqueId, MaemoQemuRuntime()).isValid()
@@ -482,9 +479,7 @@ void MaemoQemuManager::toggleStarterButton(Target *target)
bool MaemoQemuManager::sessionHasMaemoTarget() const
{
- ProjectExplorerPlugin *explorer = ProjectExplorerPlugin::instance();
- const QList<Project*> &projects = explorer->session()->projects();
- foreach (const Project *p, projects) {
+ foreach (const Project *p, SessionManager::projects()) {
foreach (const Target * const target, p->targets()) {
if (MaemoGlobal::hasMaemoDevice(target->kit()))
return true;
@@ -494,7 +489,7 @@ bool MaemoQemuManager::sessionHasMaemoTarget() const
}
bool MaemoQemuManager::targetUsesMatchingRuntimeConfig(Target *target,
- QtSupport::BaseQtVersion **qtVersion)
+ BaseQtVersion **qtVersion)
{
if (!target)
return false;
@@ -506,7 +501,7 @@ bool MaemoQemuManager::targetUsesMatchingRuntimeConfig(Target *target,
if (!mrc)
return false;
- QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(target->kit());
+ BaseQtVersion *version = QtKitInformation::qtVersion(target->kit());
if (!version || !m_runtimes.value(version->uniqueId(), MaemoQemuRuntime()).isValid())
return false;
diff --git a/src/plugins/madde/maemoqemuruntimeparser.cpp b/src/plugins/madde/maemoqemuruntimeparser.cpp
index e013711fe5..1a88c73037 100644
--- a/src/plugins/madde/maemoqemuruntimeparser.cpp
+++ b/src/plugins/madde/maemoqemuruntimeparser.cpp
@@ -139,9 +139,9 @@ MaemoQemuRuntime MaemoQemuRuntimeParserV1::parseRuntime()
&& m_madInfoReader.name() == QLatin1String("installed")) {
if (m_madInfoReader.readNext() == QXmlStreamReader::Characters
&& m_madInfoReader.text() == QLatin1String("true")) {
- if (attrs.hasAttribute(QLatin1String("runtime_id")))
+ if (attrs.hasAttribute(QLatin1String("runtime_id"))) {
installedRuntimes << attrs.value(QLatin1String("runtime_id")).toString();
- else if (attrs.hasAttribute(QLatin1String("id"))) {
+ } else if (attrs.hasAttribute(QLatin1String("id"))) {
// older MADDE seems to use only id
installedRuntimes << attrs.value(QLatin1String("id")).toString();
}
diff --git a/src/plugins/madde/maemorunconfiguration.cpp b/src/plugins/madde/maemorunconfiguration.cpp
index b046428523..55c17c8393 100644
--- a/src/plugins/madde/maemorunconfiguration.cpp
+++ b/src/plugins/madde/maemorunconfiguration.cpp
@@ -112,24 +112,6 @@ bool MaemoRunConfiguration::fromMap(const QVariantMap &map)
return true;
}
-QString MaemoRunConfiguration::environmentPreparationCommand() const
-{
- return MaemoGlobal::remoteSourceProfilesCommand();
-}
-
-QString MaemoRunConfiguration::commandPrefix() const
-{
- IDevice::ConstPtr dev = DeviceKitInformation::device(target()->kit());
- if (!dev)
- return QString();
-
- const QString prefix = environmentPreparationCommand() + QLatin1Char(';');
-
- RemoteLinuxEnvironmentAspect *aspect = extraAspect<RemoteLinuxEnvironmentAspect>();
- QTC_ASSERT(aspect, return QString());
- return QString::fromLatin1("%1 %2").arg(prefix, aspect->userEnvironmentChangesAsString());
-}
-
Utils::PortList MaemoRunConfiguration::freePorts() const
{
return MaemoGlobal::freePorts(target()->kit());
diff --git a/src/plugins/madde/maemorunconfiguration.h b/src/plugins/madde/maemorunconfiguration.h
index d7083322d9..edfebb8fe7 100644
--- a/src/plugins/madde/maemorunconfiguration.h
+++ b/src/plugins/madde/maemorunconfiguration.h
@@ -48,8 +48,6 @@ public:
bool fromMap(const QVariantMap &map);
bool isEnabled() const;
QWidget *createConfigurationWidget();
- QString environmentPreparationCommand() const;
- QString commandPrefix() const;
Utils::PortList freePorts() const;
Internal::MaemoRemoteMountsModel *remoteMounts() const { return m_remoteMounts; }
diff --git a/src/plugins/madde/qt4maemodeployconfiguration.cpp b/src/plugins/madde/qt4maemodeployconfiguration.cpp
index adec54f79b..d423c206cd 100644
--- a/src/plugins/madde/qt4maemodeployconfiguration.cpp
+++ b/src/plugins/madde/qt4maemodeployconfiguration.cpp
@@ -87,17 +87,17 @@ Qt4MaemoDeployConfiguration::~Qt4MaemoDeployConfiguration() {}
Core::Id Qt4MaemoDeployConfiguration::fremantleWithPackagingId()
{
- return Core::Id("DeployToFremantleWithPackaging");
+ return "DeployToFremantleWithPackaging";
}
Core::Id Qt4MaemoDeployConfiguration::fremantleWithoutPackagingId()
{
- return Core::Id("DeployToFremantleWithoutPackaging");
+ return "DeployToFremantleWithoutPackaging";
}
Core::Id Qt4MaemoDeployConfiguration::harmattanId()
{
- return Core::Id("DeployToHarmattan");
+ return "DeployToHarmattan";
}
void Qt4MaemoDeployConfiguration::debianDirChanged(const Utils::FileName &dir)
diff --git a/src/plugins/mercurial/Mercurial.pluginspec.in b/src/plugins/mercurial/Mercurial.pluginspec.in
index 3a034c05f1..c771782d81 100644
--- a/src/plugins/mercurial/Mercurial.pluginspec.in
+++ b/src/plugins/mercurial/Mercurial.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"Mercurial\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"Mercurial\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Brian McGillion</vendor>
<copyright>(C) 2013 Brian McGillion</copyright>
<license>
diff --git a/src/plugins/mercurial/annotationhighlighter.cpp b/src/plugins/mercurial/annotationhighlighter.cpp
index 22656bed55..6a0a0be01e 100644
--- a/src/plugins/mercurial/annotationhighlighter.cpp
+++ b/src/plugins/mercurial/annotationhighlighter.cpp
@@ -34,9 +34,8 @@ using namespace Mercurial::Internal;
using namespace Mercurial;
MercurialAnnotationHighlighter::MercurialAnnotationHighlighter(const ChangeNumbers &changeNumbers,
- const QColor &bg,
QTextDocument *document)
- : VcsBase::BaseAnnotationHighlighter(changeNumbers, bg, document),
+ : VcsBase::BaseAnnotationHighlighter(changeNumbers, document),
changeset(QLatin1String(Constants::CHANGESETID12))
{
}
diff --git a/src/plugins/mercurial/annotationhighlighter.h b/src/plugins/mercurial/annotationhighlighter.h
index 310596554d..931a745c6e 100644
--- a/src/plugins/mercurial/annotationhighlighter.h
+++ b/src/plugins/mercurial/annotationhighlighter.h
@@ -39,7 +39,7 @@ namespace Internal {
class MercurialAnnotationHighlighter : public VcsBase::BaseAnnotationHighlighter
{
public:
- explicit MercurialAnnotationHighlighter(const ChangeNumbers &changeNumbers, const QColor &bg,
+ explicit MercurialAnnotationHighlighter(const ChangeNumbers &changeNumbers,
QTextDocument *document = 0);
private:
diff --git a/src/plugins/mercurial/clonewizard.cpp b/src/plugins/mercurial/clonewizard.cpp
index 9e2fd3424d..9da9266392 100644
--- a/src/plugins/mercurial/clonewizard.cpp
+++ b/src/plugins/mercurial/clonewizard.cpp
@@ -33,33 +33,20 @@
#include "mercurialsettings.h"
#include <coreplugin/iversioncontrol.h>
-#include <vcsbase/checkoutjobs.h>
+#include <vcsbase/command.h>
#include <vcsbase/vcsbaseconstants.h>
#include <vcsbase/vcsconfigurationpage.h>
using namespace Mercurial::Internal;
using namespace VcsBase;
-CloneWizard::CloneWizard(QObject *parent)
- : BaseCheckoutWizard(parent),
- m_icon(QIcon(QLatin1String(":/mercurial/images/hg.png")))
+CloneWizard::CloneWizard()
{
setId(QLatin1String(Constants::VCS_ID_MERCURIAL));
-}
-
-QIcon CloneWizard::icon() const
-{
- return m_icon;
-}
-
-QString CloneWizard::description() const
-{
- return tr("Clones a Mercurial repository and tries to load the contained project.");
-}
-
-QString CloneWizard::displayName() const
-{
- return tr("Mercurial Clone");
+ setCustomLabels(tr("Cloning"), tr("Cloning started..."));
+ setIcon(QIcon(QLatin1String(":/mercurial/images/hg.png")));
+ setDescription(tr("Clones a Mercurial repository and tries to load the contained project."));
+ setDisplayName(tr("Mercurial Clone"));
}
QList<QWizardPage *> CloneWizard::createParameterPages(const QString &path)
@@ -74,15 +61,15 @@ QList<QWizardPage *> CloneWizard::createParameterPages(const QString &path)
return wizardPageList;
}
-QSharedPointer<AbstractCheckoutJob> CloneWizard::createJob(const QList<QWizardPage *> &parameterPages,
- QString *checkoutPath)
+Command *CloneWizard::createCommand(const QList<QWizardPage *> &parameterPages,
+ QString *checkoutPath)
{
const CloneWizardPage *page = qobject_cast<const CloneWizardPage *>(parameterPages.front());
if (!page)
- return QSharedPointer<AbstractCheckoutJob>();
+ return 0;
- const MercurialSettings &settings = MercurialPlugin::instance()->settings();
+ const MercurialSettings &settings = MercurialPlugin::settings();
QString path = page->path();
QString directory = page->directory();
@@ -90,7 +77,8 @@ QSharedPointer<AbstractCheckoutJob> CloneWizard::createJob(const QList<QWizardPa
QStringList args;
args << QLatin1String("clone") << page->repository() << directory;
*checkoutPath = path + QLatin1Char('/') + directory;
- ProcessCheckoutJob *job = new ProcessCheckoutJob;
- job->addStep(settings.binaryPath(), args, path);
- return QSharedPointer<AbstractCheckoutJob>(job);
+ VcsBase::Command *command = new VcsBase::Command(settings.binaryPath(), path,
+ QProcessEnvironment::systemEnvironment());
+ command->addJob(args, -1);
+ return command;
}
diff --git a/src/plugins/mercurial/clonewizard.h b/src/plugins/mercurial/clonewizard.h
index a0e1f77d05..155058c01f 100644
--- a/src/plugins/mercurial/clonewizard.h
+++ b/src/plugins/mercurial/clonewizard.h
@@ -40,17 +40,14 @@ namespace Internal {
class CloneWizard : public VcsBase::BaseCheckoutWizard
{
Q_OBJECT
-public:
- CloneWizard(QObject *parent = 0);
- QIcon icon() const;
- QString description() const;
- QString displayName() const;
+public:
+ CloneWizard();
protected:
QList<QWizardPage *> createParameterPages(const QString &path);
- QSharedPointer<VcsBase::AbstractCheckoutJob> createJob(const QList<QWizardPage *> &parameterPages,
- QString *checkoutPath);
+ VcsBase::Command *createCommand(const QList<QWizardPage *> &parameterPages,
+ QString *checkoutPath);
private:
const QIcon m_icon;
diff --git a/src/plugins/mercurial/commiteditor.cpp b/src/plugins/mercurial/commiteditor.cpp
index 189afd4c43..175a8df224 100644
--- a/src/plugins/mercurial/commiteditor.cpp
+++ b/src/plugins/mercurial/commiteditor.cpp
@@ -30,6 +30,7 @@
#include "commiteditor.h"
#include "mercurialcommitwidget.h"
+#include <coreplugin/idocument.h>
#include <vcsbase/submitfilemodel.h>
#include <QDebug>
@@ -42,7 +43,7 @@ CommitEditor::CommitEditor(const VcsBaseSubmitEditorParameters *parameters, QWid
: VcsBaseSubmitEditor(parameters, new MercurialCommitWidget(parent)),
fileModel(0)
{
- setDisplayName(tr("Commit Editor"));
+ document()->setDisplayName(tr("Commit Editor"));
}
MercurialCommitWidget *CommitEditor::commitWidget()
diff --git a/src/plugins/mercurial/mercurialclient.cpp b/src/plugins/mercurial/mercurialclient.cpp
index d27b5e9b68..eef368c1d8 100644
--- a/src/plugins/mercurial/mercurialclient.cpp
+++ b/src/plugins/mercurial/mercurialclient.cpp
@@ -130,6 +130,29 @@ bool MercurialClient::synchronousClone(const QString &workingDir,
}
}
+bool MercurialClient::synchronousPull(const QString &workingDir, const QString &srcLocation, const QStringList &extraOptions)
+{
+ QStringList args;
+ args << vcsCommandString(PullCommand) << extraOptions << srcLocation;
+ // Disable UNIX terminals to suppress SSH prompting
+ const unsigned flags =
+ VcsBase::VcsBasePlugin::SshPasswordPrompt
+ | VcsBase::VcsBasePlugin::ShowStdOutInLogWindow
+ | VcsBase::VcsBasePlugin::ShowSuccessMessage;
+ const QString binary = settings()->binaryPath();
+ const int timeoutSec = settings()->value(settings()->timeoutKey).toInt();
+
+ // cause mercurial doesn`t understand LANG
+ QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
+ env.insert(QLatin1String("LANGUAGE"), QLatin1String("C"));
+ const Utils::SynchronousProcessResponse resp = VcsBase::VcsBasePlugin::runVcs(
+ workingDir, binary, args, timeoutSec * 1000, flags, 0, env);
+ const bool ok = resp.result == Utils::SynchronousProcessResponse::Finished;
+
+ parsePullOutput(resp.stdOut.trimmed());
+ return ok;
+}
+
QString MercurialClient::branchQuerySync(const QString &repositoryRoot)
{
QByteArray output;
@@ -164,8 +187,8 @@ QStringList MercurialClient::parentRevisionsSync(const QString &workingDirectory
QByteArray outputData;
if (!vcsFullySynchronousExec(workingDirectory, args, &outputData))
return QStringList();
- QString output = QString::fromLocal8Bit(outputData);
- output.remove(QLatin1Char('\r'));
+ const QString output = Utils::SynchronousProcess::normalizeNewlines(
+ QString::fromLocal8Bit(outputData));
/* Looks like: \code
changeset: 0:031a48610fba
user: ...
@@ -207,8 +230,7 @@ QString MercurialClient::shortDescriptionSync(const QString &workingDirectory,
QByteArray outputData;
if (!vcsFullySynchronousExec(workingDirectory, args, &outputData))
return revision;
- description = QString::fromLocal8Bit(outputData);
- description.remove(QLatin1Char('\r'));
+ description = Utils::SynchronousProcess::normalizeNewlines(QString::fromLocal8Bit(outputData));
if (description.endsWith(QLatin1Char('\n')))
description.truncate(description.size() - 1);
return description;
@@ -253,8 +275,6 @@ void MercurialClient::incoming(const QString &repositoryRoot, const QString &rep
VcsBase::VcsBaseEditorWidget *editor = createVcsEditor(Constants::DIFFLOG, title, repositoryRoot,
true, "incoming", id);
VcsBase::Command *cmd = createCommand(repository, editor);
- if (!repository.isEmpty() && VcsBase::VcsBasePlugin::isSshPromptConfigured())
- cmd->setUnixTerminalDisabled(true);
enqueueJob(cmd, args);
}
@@ -270,7 +290,6 @@ void MercurialClient::outgoing(const QString &repositoryRoot)
"outgoing", repositoryRoot);
VcsBase::Command *cmd = createCommand(repositoryRoot, editor);
- cmd->setUnixTerminalDisabled(VcsBase::VcsBasePlugin::isSshPromptConfigured());
enqueueJob(cmd, args);
}
@@ -377,6 +396,20 @@ MercurialClient::StatusItem MercurialClient::parseStatusLine(const QString &line
return item;
}
+void MercurialClient::parsePullOutput(const QString &output)
+{
+ if (output.endsWith(QLatin1String("no changes found")))
+ return;
+
+ if (output.endsWith(QLatin1String("(run 'hg update' to get a working copy)"))) {
+ emit needUpdate();
+ return;
+ }
+
+ if (output.endsWith(QLatin1String("'hg merge' to merge)")))
+ emit needMerge();
+}
+
// Collect all parameters required for a diff to be able to associate them
// with a diff editor and re-run the diff with parameters.
struct MercurialDiffParameters
diff --git a/src/plugins/mercurial/mercurialclient.h b/src/plugins/mercurial/mercurialclient.h
index f2c2e6f01d..7f12b8470f 100644
--- a/src/plugins/mercurial/mercurialclient.h
+++ b/src/plugins/mercurial/mercurialclient.h
@@ -49,6 +49,9 @@ public:
const QString &srcLocation,
const QString &dstLocation,
const QStringList &extraOptions = QStringList());
+ bool synchronousPull(const QString &workingDir,
+ const QString &srcLocation,
+ const QStringList &extraOptions = QStringList());
bool manifestSync(const QString &repository, const QString &filename);
QString branchQuerySync(const QString &repositoryRoot);
QStringList parentRevisionsSync(const QString &workingDirectory,
@@ -86,6 +89,13 @@ protected:
const QStringList &files,
const QStringList &extraOptions);
StatusItem parseStatusLine(const QString &line) const;
+
+signals:
+ void needUpdate();
+ void needMerge();
+
+private:
+ void parsePullOutput(const QString &output);
};
} //namespace Internal
diff --git a/src/plugins/mercurial/mercurialcommitwidget.cpp b/src/plugins/mercurial/mercurialcommitwidget.cpp
index 4f2d17f508..262994bf56 100644
--- a/src/plugins/mercurial/mercurialcommitwidget.cpp
+++ b/src/plugins/mercurial/mercurialcommitwidget.cpp
@@ -50,8 +50,7 @@ namespace Internal {
// Retrieve the comment char format from the text editor.
static QTextCharFormat commentFormat()
{
- const TextEditor::FontSettings settings = TextEditor::TextEditorSettings::instance()->fontSettings();
- return settings.toTextCharFormat(TextEditor::C_COMMENT);
+ return TextEditor::TextEditorSettings::fontSettings().toTextCharFormat(TextEditor::C_COMMENT);
}
// Highlighter for Mercurial submit messages. Make the first line bold, indicates
diff --git a/src/plugins/mercurial/mercurialeditor.cpp b/src/plugins/mercurial/mercurialeditor.cpp
index 59865be2ee..ca6a62b9fb 100644
--- a/src/plugins/mercurial/mercurialeditor.cpp
+++ b/src/plugins/mercurial/mercurialeditor.cpp
@@ -89,10 +89,9 @@ QString MercurialEditor::changeUnderCursor(const QTextCursor &cursorIn) const
return QString();
}
-VcsBase::BaseAnnotationHighlighter *MercurialEditor::createAnnotationHighlighter(const QSet<QString> &changes,
- const QColor &bg) const
+VcsBase::BaseAnnotationHighlighter *MercurialEditor::createAnnotationHighlighter(const QSet<QString> &changes) const
{
- return new MercurialAnnotationHighlighter(changes, bg);
+ return new MercurialAnnotationHighlighter(changes);
}
QString MercurialEditor::decorateVersion(const QString &revision) const
@@ -100,7 +99,7 @@ QString MercurialEditor::decorateVersion(const QString &revision) const
const QFileInfo fi(source());
const QString workingDirectory = fi.absolutePath();
// Format with short summary
- return MercurialPlugin::instance()->client()->shortDescriptionSync(workingDirectory, revision);
+ return MercurialPlugin::client()->shortDescriptionSync(workingDirectory, revision);
}
QStringList MercurialEditor::annotationPreviousVersions(const QString &revision) const
@@ -108,5 +107,5 @@ QStringList MercurialEditor::annotationPreviousVersions(const QString &revision)
const QFileInfo fi(source());
const QString workingDirectory = fi.absolutePath();
// Retrieve parent revisions
- return MercurialPlugin::instance()->client()->parentRevisionsSync(workingDirectory, fi.fileName(), revision);
+ return MercurialPlugin::client()->parentRevisionsSync(workingDirectory, fi.fileName(), revision);
}
diff --git a/src/plugins/mercurial/mercurialeditor.h b/src/plugins/mercurial/mercurialeditor.h
index a2ca6dce8b..ddbefdcce8 100644
--- a/src/plugins/mercurial/mercurialeditor.h
+++ b/src/plugins/mercurial/mercurialeditor.h
@@ -46,7 +46,7 @@ public:
private:
QSet<QString> annotationChanges() const;
QString changeUnderCursor(const QTextCursor &cursor) const;
- VcsBase::BaseAnnotationHighlighter *createAnnotationHighlighter(const QSet<QString> &changes, const QColor &bg) const;
+ VcsBase::BaseAnnotationHighlighter *createAnnotationHighlighter(const QSet<QString> &changes) const;
QString decorateVersion(const QString &revision) const;
QStringList annotationPreviousVersions(const QString &revision) const;
diff --git a/src/plugins/mercurial/mercurialplugin.cpp b/src/plugins/mercurial/mercurialplugin.cpp
index 74e5338088..abd529c2ad 100644
--- a/src/plugins/mercurial/mercurialplugin.cpp
+++ b/src/plugins/mercurial/mercurialplugin.cpp
@@ -140,6 +140,7 @@ bool MercurialPlugin::initialize(const QStringList & /* arguments */, QString *
mercurialSettings.readSettings(core->settings());
connect(m_client, SIGNAL(changed(QVariant)), versionControl(), SLOT(changed(QVariant)));
+ connect(m_client, SIGNAL(needUpdate()), this, SLOT(update()));
static const char *describeSlot = SLOT(view(QString,QString));
const int editorCount = sizeof(editorParameters)/sizeof(editorParameters[0]);
@@ -161,16 +162,16 @@ bool MercurialPlugin::initialize(const QStringList & /* arguments */, QString *
return true;
}
-const MercurialSettings &MercurialPlugin::settings() const
+const MercurialSettings &MercurialPlugin::settings()
{
- return mercurialSettings;
+ return m_instance->mercurialSettings;
}
void MercurialPlugin::setSettings(const MercurialSettings &settings)
{
- if (settings != mercurialSettings) {
- mercurialSettings = settings;
- static_cast<MercurialControl *>(versionControl())->emitConfigurationChanged();
+ if (settings != m_instance->mercurialSettings) {
+ m_instance->mercurialSettings = settings;
+ static_cast<MercurialControl *>(m_instance->versionControl())->emitConfigurationChanged();
}
}
@@ -179,7 +180,7 @@ void MercurialPlugin::createMenu()
Core::Context context(Core::Constants::C_GLOBAL);
// Create menu item for Mercurial
- mercurialContainer = Core::ActionManager::createMenu(Core::Id("Mercurial.MercurialMenu"));
+ mercurialContainer = Core::ActionManager::createMenu("Mercurial.MercurialMenu");
QMenu *menu = mercurialContainer->menu();
menu->setTitle(tr("Me&rcurial"));
@@ -556,7 +557,7 @@ void MercurialPlugin::showCommitWidget(const QList<VcsBaseClient::StatusItem> &s
// Keep the file alive, else it removes self and forgets its name
saver.setAutoRemove(false);
if (!saver.finalize()) {
- VcsBase::VcsBaseOutputWindow::instance()->append(saver.errorString());
+ VcsBase::VcsBaseOutputWindow::instance()->appendError(saver.errorString());
return;
}
@@ -578,7 +579,7 @@ void MercurialPlugin::showCommitWidget(const QList<VcsBaseClient::StatusItem> &s
const QString msg = tr("Commit changes for \"%1\".").
arg(QDir::toNativeSeparators(m_submitRepository));
- commitEditor->setDisplayName(msg);
+ commitEditor->document()->setDisplayName(msg);
QString branch = m_client->branchQuerySync(m_submitRepository);
commitEditor->setFields(m_submitRepository, branch,
@@ -595,7 +596,7 @@ void MercurialPlugin::commitFromEditor()
{
// Close the submit editor
m_submitActionTriggered = true;
- Core::ICore::editorManager()->closeEditor();
+ Core::EditorManager::closeEditor();
}
bool MercurialPlugin::submitEditorAboutToClose()
@@ -630,7 +631,7 @@ bool MercurialPlugin::submitEditorAboutToClose()
QStringList extraOptions;
if (!commitEditor->committerInfo().isEmpty())
extraOptions << QLatin1String("-u") << commitEditor->committerInfo();
- m_client->commit(m_submitRepository, files, editorFile->fileName(),
+ m_client->commit(m_submitRepository, files, editorFile->filePath(),
extraOptions);
}
return true;
diff --git a/src/plugins/mercurial/mercurialplugin.h b/src/plugins/mercurial/mercurialplugin.h
index 824bc04eb1..d34c1b8e95 100644
--- a/src/plugins/mercurial/mercurialplugin.h
+++ b/src/plugins/mercurial/mercurialplugin.h
@@ -72,10 +72,10 @@ public:
bool initialize(const QStringList &arguments, QString *errorMessage);
static MercurialPlugin *instance() { return m_instance; }
- MercurialClient *client() const { return m_client; }
+ static MercurialClient *client() { return m_instance->m_client; }
- const MercurialSettings &settings() const;
- void setSettings(const MercurialSettings &settings);
+ static const MercurialSettings &settings();
+ static void setSettings(const MercurialSettings &settings);
private slots:
// File menu action slots
diff --git a/src/plugins/mercurial/optionspage.cpp b/src/plugins/mercurial/optionspage.cpp
index 8f6087ab94..fa51834145 100644
--- a/src/plugins/mercurial/optionspage.cpp
+++ b/src/plugins/mercurial/optionspage.cpp
@@ -50,7 +50,7 @@ OptionsPageWidget::OptionsPageWidget(QWidget *parent) :
MercurialSettings OptionsPageWidget::settings() const
{
- MercurialSettings s = MercurialPlugin::instance()->settings();
+ MercurialSettings s = MercurialPlugin::settings();
s.setValue(MercurialSettings::binaryPathKey, m_ui.commandChooser->rawPath());
s.setValue(MercurialSettings::userNameKey, m_ui.defaultUsernameLineEdit->text().trimmed());
s.setValue(MercurialSettings::userEmailKey, m_ui.defaultEmailLineEdit->text().trimmed());
@@ -99,7 +99,7 @@ QWidget *OptionsPage::createPage(QWidget *parent)
{
if (!optionsPageWidget)
optionsPageWidget = new OptionsPageWidget(parent);
- optionsPageWidget->setSettings(MercurialPlugin::instance()->settings());
+ optionsPageWidget->setSettings(MercurialPlugin::settings());
if (m_searchKeywords.isEmpty())
m_searchKeywords = optionsPageWidget->searchKeywords();
return optionsPageWidget;
@@ -109,11 +109,10 @@ void OptionsPage::apply()
{
if (!optionsPageWidget)
return;
- MercurialPlugin *plugin = MercurialPlugin::instance();
const MercurialSettings newSettings = optionsPageWidget->settings();
- if (newSettings != plugin->settings()) {
+ if (newSettings != MercurialPlugin::settings()) {
//assume success and emit signal that settings are changed;
- plugin->setSettings(newSettings);
+ MercurialPlugin::setSettings(newSettings);
newSettings.writeSettings(Core::ICore::settings());
emit settingsChanged();
}
diff --git a/src/plugins/perforce/Perforce.pluginspec.in b/src/plugins/perforce/Perforce.pluginspec.in
index 415b1b068d..2b69c6368d 100644
--- a/src/plugins/perforce/Perforce.pluginspec.in
+++ b/src/plugins/perforce/Perforce.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"Perforce\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"Perforce\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/perforce/annotationhighlighter.cpp b/src/plugins/perforce/annotationhighlighter.cpp
index d3d8760958..93ee74918c 100644
--- a/src/plugins/perforce/annotationhighlighter.cpp
+++ b/src/plugins/perforce/annotationhighlighter.cpp
@@ -33,9 +33,8 @@ namespace Perforce {
namespace Internal {
PerforceAnnotationHighlighter::PerforceAnnotationHighlighter(const ChangeNumbers &changeNumbers,
- const QColor &bg,
QTextDocument *document) :
- VcsBase::BaseAnnotationHighlighter(changeNumbers, bg, document),
+ VcsBase::BaseAnnotationHighlighter(changeNumbers, document),
m_colon(QLatin1Char(':'))
{
}
diff --git a/src/plugins/perforce/annotationhighlighter.h b/src/plugins/perforce/annotationhighlighter.h
index 4c47fd48b3..2d35c04c6e 100644
--- a/src/plugins/perforce/annotationhighlighter.h
+++ b/src/plugins/perforce/annotationhighlighter.h
@@ -41,7 +41,6 @@ class PerforceAnnotationHighlighter : public VcsBase::BaseAnnotationHighlighter
Q_OBJECT
public:
explicit PerforceAnnotationHighlighter(const ChangeNumbers &changeNumbers,
- const QColor &bg,
QTextDocument *document = 0);
private:
diff --git a/src/plugins/perforce/perforceeditor.cpp b/src/plugins/perforce/perforceeditor.cpp
index d9885e1242..a859a77fe6 100644
--- a/src/plugins/perforce/perforceeditor.cpp
+++ b/src/plugins/perforce/perforceeditor.cpp
@@ -59,8 +59,7 @@ namespace Internal {
PerforceEditor::PerforceEditor(const VcsBase::VcsBaseEditorParameters *type,
QWidget *parent) :
VcsBase::VcsBaseEditorWidget(type, parent),
- m_changeNumberPattern(QLatin1String("^\\d+$")),
- m_plugin(PerforcePlugin::perforcePluginInstance())
+ m_changeNumberPattern(QLatin1String("^\\d+$"))
{
QTC_CHECK(m_changeNumberPattern.isValid());
// Diff format:
@@ -110,16 +109,15 @@ QString PerforceEditor::changeUnderCursor(const QTextCursor &c) const
return m_changeNumberPattern.exactMatch(change) ? change : QString();
}
-VcsBase::BaseAnnotationHighlighter *PerforceEditor::createAnnotationHighlighter(const QSet<QString> &changes,
- const QColor &bg) const
+VcsBase::BaseAnnotationHighlighter *PerforceEditor::createAnnotationHighlighter(const QSet<QString> &changes) const
{
- return new PerforceAnnotationHighlighter(changes, bg);
+ return new PerforceAnnotationHighlighter(changes);
}
QString PerforceEditor::findDiffFile(const QString &f) const
{
QString errorMessage;
- const QString fileName = m_plugin->fileNameFromPerforceName(f.trimmed(), false, &errorMessage);
+ const QString fileName = PerforcePlugin::fileNameFromPerforceName(f.trimmed(), false, &errorMessage);
if (fileName.isEmpty())
qWarning("%s", qPrintable(errorMessage));
return fileName;
diff --git a/src/plugins/perforce/perforceeditor.h b/src/plugins/perforce/perforceeditor.h
index 915d6ee4cd..6f8163d23c 100644
--- a/src/plugins/perforce/perforceeditor.h
+++ b/src/plugins/perforce/perforceeditor.h
@@ -50,12 +50,11 @@ public:
private:
QSet<QString> annotationChanges() const;
QString changeUnderCursor(const QTextCursor &) const;
- VcsBase::BaseAnnotationHighlighter *createAnnotationHighlighter(const QSet<QString> &changes, const QColor &bg) const;
+ VcsBase::BaseAnnotationHighlighter *createAnnotationHighlighter(const QSet<QString> &changes) const;
QString findDiffFile(const QString &f) const;
QStringList annotationPreviousVersions(const QString &v) const;
mutable QRegExp m_changeNumberPattern;
- PerforcePlugin *m_plugin;
};
} // namespace Perforce
diff --git a/src/plugins/perforce/perforceplugin.cpp b/src/plugins/perforce/perforceplugin.cpp
index 8fd5957c80..eae49651a8 100644
--- a/src/plugins/perforce/perforceplugin.cpp
+++ b/src/plugins/perforce/perforceplugin.cpp
@@ -105,19 +105,16 @@ static inline QString debugCodec(const QTextCodec *c)
// Ensure adding "..." to relative paths which is p4's convention
// for the current directory
-static inline QStringList perforceRelativeFileArguments(const QStringList &args)
+static inline QString perforceRelativeFileArguments(const QString &args)
{
if (args.isEmpty())
- return QStringList(QLatin1String("..."));
- QTC_ASSERT(args.size() == 1, return QStringList());
- QStringList p4Args = args;
- p4Args.front() += QLatin1String("/...");
- return p4Args;
+ return QLatin1String("...");
+ return args + QLatin1String("/...");
}
static inline QStringList perforceRelativeProjectDirectory(const VcsBase::VcsBasePluginState &s)
{
- return perforceRelativeFileArguments(s.relativeCurrentProject());
+ return QStringList(perforceRelativeFileArguments(s.relativeCurrentProject()));
}
// Clean user setting off diff-binary for 'p4 resolve' and 'p4 diff'.
@@ -142,7 +139,6 @@ static const char CMD_ID_UPDATE_PROJECT[] = "Perforce.UpdateProject";
static const char CMD_ID_REVERT_PROJECT[] = "Perforce.RevertProject";
static const char CMD_ID_REVERT_UNCHANGED_PROJECT[] = "Perforce.RevertUnchangedProject";
static const char CMD_ID_DIFF_ALL[] = "Perforce.DiffAll";
-static const char CMD_ID_RESOLVE[] = "Perforce.Resolve";
static const char CMD_ID_SUBMIT[] = "Perforce.Submit";
static const char CMD_ID_PENDING_CHANGES[] = "Perforce.PendingChanges";
static const char CMD_ID_DESCRIBE[] = "Perforce.Describe";
@@ -165,7 +161,7 @@ PerforceResponse::PerforceResponse() :
{
}
-PerforcePlugin *PerforcePlugin::m_perforcePluginInstance = NULL;
+PerforcePlugin *PerforcePlugin::m_instance = NULL;
PerforcePlugin::PerforcePlugin() :
m_commandLocator(0),
@@ -213,9 +209,9 @@ bool PerforcePlugin::initialize(const QStringList & /* arguments */, QString *er
initializeVcs(new PerforceVersionControl(this));
- if (!Core::ICore::mimeDatabase()->addMimeTypes(QLatin1String(":/trolltech.perforce/Perforce.mimetypes.xml"), errorMessage))
+ if (!Core::MimeDatabase::addMimeTypes(QLatin1String(":/trolltech.perforce/Perforce.mimetypes.xml"), errorMessage))
return false;
- m_perforcePluginInstance = this;
+ m_instance = this;
m_settings.fromSettings(Core::ICore::settings());
@@ -735,7 +731,7 @@ void PerforcePlugin::filelogCurrentFile()
{
const VcsBase::VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasFile(), return);
- filelog(state.currentFileTopLevel(), QStringList(state.relativeCurrentFile()), true);
+ filelog(state.currentFileTopLevel(), state.relativeCurrentFile(), true);
}
void PerforcePlugin::filelog()
@@ -743,7 +739,7 @@ void PerforcePlugin::filelog()
const QString file = QFileDialog::getOpenFileName(0, tr("p4 filelog"));
if (!file.isEmpty()) {
const QFileInfo fi(file);
- filelog(fi.absolutePath(), QStringList(fi.fileName()));
+ filelog(fi.absolutePath(), fi.fileName());
}
}
@@ -758,24 +754,25 @@ void PerforcePlugin::logRepository()
{
const VcsBase::VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasTopLevel(), return);
- filelog(state.topLevel(), perforceRelativeFileArguments(QStringList()));
+ filelog(state.topLevel(), perforceRelativeFileArguments(QString()));
}
-void PerforcePlugin::filelog(const QString &workingDir, const QStringList &fileNames,
+void PerforcePlugin::filelog(const QString &workingDir, const QString &fileName,
bool enableAnnotationContextMenu)
{
- const QString id = VcsBase::VcsBaseEditorWidget::getTitleId(workingDir, fileNames);
- QTextCodec *codec = VcsBase::VcsBaseEditorWidget::getCodec(workingDir, fileNames);
+ const QString id = VcsBase::VcsBaseEditorWidget::getTitleId(workingDir, QStringList(fileName));
+ QTextCodec *codec = VcsBase::VcsBaseEditorWidget::getCodec(workingDir, QStringList(fileName));
QStringList args;
args << QLatin1String("filelog") << QLatin1String("-li");
if (m_settings.logCount() > 0)
args << QLatin1String("-m") << QString::number(m_settings.logCount());
- args.append(fileNames);
+ if (!fileName.isEmpty())
+ args.append(fileName);
const PerforceResponse result = runP4Cmd(workingDir, args,
CommandToWindow|StdErrToWindow|ErrorToWindow,
QStringList(), QByteArray(), codec);
if (!result.error) {
- const QString source = VcsBase::VcsBaseEditorWidget::getSource(workingDir, fileNames);
+ const QString source = VcsBase::VcsBaseEditorWidget::getSource(workingDir, fileName);
Core::IEditor *editor = showOutputInEditor(tr("p4 filelog %1").arg(id), result.stdOut,
VcsBase::LogOutput, source, codec);
if (enableAnnotationContextMenu)
@@ -843,8 +840,8 @@ bool PerforcePlugin::managesDirectoryFstat(const QString &directory)
bool managed = false;
do {
// Quick check: Must be at or below top level and not "../../other_path"
- const QStringList relativeDirArgs = m_settings.relativeToTopLevelArguments(directory);
- if (!relativeDirArgs.empty() && relativeDirArgs.front().startsWith(QLatin1String("..")))
+ const QString relativeDirArgs = m_settings.relativeToTopLevelArguments(directory);
+ if (!relativeDirArgs.isEmpty() && relativeDirArgs.startsWith(QLatin1String("..")))
break;
// Is it actually managed by perforce?
QStringList args;
@@ -920,19 +917,21 @@ bool PerforcePlugin::vcsMove(const QString &workingDir, const QString &from, con
// Write extra args to temporary file
QSharedPointer<Utils::TempFileSaver>
- PerforcePlugin::createTemporaryArgumentFile(const QStringList &extraArgs,
- QString *errorString) const
+PerforcePlugin::createTemporaryArgumentFile(const QStringList &extraArgs,
+ QString *errorString)
{
if (extraArgs.isEmpty())
return QSharedPointer<Utils::TempFileSaver>();
// create pattern
- if (m_tempFilePattern.isEmpty()) {
- m_tempFilePattern = QDir::tempPath();
- if (!m_tempFilePattern.endsWith(QDir::separator()))
- m_tempFilePattern += QDir::separator();
- m_tempFilePattern += QLatin1String("qtc_p4_XXXXXX.args");
+ QString pattern = m_instance->m_tempFilePattern;
+ if (pattern.isEmpty()) {
+ pattern = QDir::tempPath();
+ if (!pattern.endsWith(QDir::separator()))
+ pattern += QDir::separator();
+ pattern += QLatin1String("qtc_p4_XXXXXX.args");
+ m_instance->m_tempFilePattern = pattern;
}
- QSharedPointer<Utils::TempFileSaver> rc(new Utils::TempFileSaver(m_tempFilePattern));
+ QSharedPointer<Utils::TempFileSaver> rc(new Utils::TempFileSaver(pattern));
rc->setAutoRemove(true);
const int last = extraArgs.size() - 1;
for (int i = 0; i <= last; i++) {
@@ -972,16 +971,16 @@ PerforceResponse PerforcePlugin::synchronousProcess(const QString &workingDir,
const QStringList &args,
unsigned flags,
const QByteArray &stdInput,
- QTextCodec *outputCodec) const
+ QTextCodec *outputCodec)
{
QTC_ASSERT(stdInput.isEmpty(), return PerforceResponse()); // Not supported here
VcsBase::VcsBaseOutputWindow *outputWindow = VcsBase::VcsBaseOutputWindow::instance();
// Run, connect stderr to the output window
Utils::SynchronousProcess process;
- const int timeOut = (flags & LongTimeOut) ? m_settings.longTimeOutMS() : m_settings.timeOutMS();
+ const int timeOut = (flags & LongTimeOut) ? settings().longTimeOutMS() : settings().timeOutMS();
process.setTimeout(timeOut);
- process.setStdOutCodec(outputCodec);
+ process.setCodec(outputCodec);
if (flags & OverrideDiffEnvironment)
process.setProcessEnvironment(overrideDiffEnvironmentVariable());
if (!workingDir.isEmpty())
@@ -1001,7 +1000,7 @@ PerforceResponse PerforcePlugin::synchronousProcess(const QString &workingDir,
if (Perforce::Constants::debug)
qDebug() << "PerforcePlugin::run syncp actual args [" << process.workingDirectory() << ']' << args;
process.setTimeOutMessageBoxEnabled(true);
- const Utils::SynchronousProcessResponse sp_resp = process.run(m_settings.p4BinaryPath(), args);
+ const Utils::SynchronousProcessResponse sp_resp = process.run(settings().p4BinaryPath(), args);
if (Perforce::Constants::debug)
qDebug() << sp_resp;
@@ -1022,7 +1021,7 @@ PerforceResponse PerforcePlugin::synchronousProcess(const QString &workingDir,
response.message = msgCrash();
break;
case Utils::SynchronousProcessResponse::StartFailed:
- response.message = msgNotStarted(m_settings.p4BinaryPath());
+ response.message = msgNotStarted(settings().p4BinaryPath());
break;
case Utils::SynchronousProcessResponse::Hang:
response.message = msgCrash();
@@ -1036,7 +1035,7 @@ PerforceResponse PerforcePlugin::fullySynchronousProcess(const QString &workingD
const QStringList &args,
unsigned flags,
const QByteArray &stdInput,
- QTextCodec *outputCodec) const
+ QTextCodec *outputCodec)
{
QProcess process;
@@ -1049,13 +1048,13 @@ PerforceResponse PerforcePlugin::fullySynchronousProcess(const QString &workingD
qDebug() << "PerforcePlugin::run fully syncp actual args [" << process.workingDirectory() << ']' << args;
PerforceResponse response;
- process.start(m_settings.p4BinaryPath(), args);
+ process.start(settings().p4BinaryPath(), args);
if (stdInput.isEmpty())
process.closeWriteChannel();
if (!process.waitForStarted(3000)) {
response.error = true;
- response.message = msgNotStarted(m_settings.p4BinaryPath());
+ response.message = msgNotStarted(settings().p4BinaryPath());
return response;
}
if (!stdInput.isEmpty()) {
@@ -1063,7 +1062,7 @@ PerforceResponse PerforcePlugin::fullySynchronousProcess(const QString &workingD
Utils::SynchronousProcess::stopProcess(process);
response.error = true;
response.message = tr("Unable to write input data to process %1: %2").
- arg(QDir::toNativeSeparators(m_settings.p4BinaryPath()),
+ arg(QDir::toNativeSeparators(settings().p4BinaryPath()),
process.errorString());
return response;
}
@@ -1072,7 +1071,7 @@ PerforceResponse PerforcePlugin::fullySynchronousProcess(const QString &workingD
QByteArray stdOut;
QByteArray stdErr;
- const int timeOut = (flags & LongTimeOut) ? m_settings.longTimeOutMS() : m_settings.timeOutMS();
+ const int timeOut = (flags & LongTimeOut) ? settings().longTimeOutMS() : settings().timeOutMS();
if (!Utils::SynchronousProcess::readDataFromProcess(process, timeOut, &stdOut, &stdErr, true)) {
Utils::SynchronousProcess::stopProcess(process);
response.error = true;
@@ -1095,7 +1094,7 @@ PerforceResponse PerforcePlugin::fullySynchronousProcess(const QString &workingD
// Logging
VcsBase::VcsBaseOutputWindow *outputWindow = VcsBase::VcsBaseOutputWindow::instance();
if ((flags & StdErrToWindow) && !response.stdErr.isEmpty())
- outputWindow->append(response.stdErr);
+ outputWindow->appendError(response.stdErr);
if ((flags & StdOutToWindow) && !response.stdOut.isEmpty())
outputWindow->append(response.stdOut);
return response;
@@ -1106,20 +1105,20 @@ PerforceResponse PerforcePlugin::runP4Cmd(const QString &workingDir,
unsigned flags,
const QStringList &extraArgs,
const QByteArray &stdInput,
- QTextCodec *outputCodec) const
+ QTextCodec *outputCodec)
{
if (Perforce::Constants::debug)
qDebug() << "PerforcePlugin::runP4Cmd [" << workingDir << ']' << args << extraArgs << stdInput << debugCodec(outputCodec);
VcsBase::VcsBaseOutputWindow *outputWindow = VcsBase::VcsBaseOutputWindow::instance();
- if (!m_settings.isValid()) {
+ if (!settings().isValid()) {
PerforceResponse invalidConfigResponse;
invalidConfigResponse.error = true;
invalidConfigResponse.message = tr("Perforce is not correctly configured.");
outputWindow->appendError(invalidConfigResponse.message);
return invalidConfigResponse;
}
- QStringList actualArgs = m_settings.commonP4Arguments(workingDir);
+ QStringList actualArgs = settings().commonP4Arguments(workingDir);
QString errorMessage;
QSharedPointer<Utils::TempFileSaver> tempFile = createTemporaryArgumentFile(extraArgs, &errorMessage);
if (!tempFile.isNull()) {
@@ -1133,7 +1132,7 @@ PerforceResponse PerforcePlugin::runP4Cmd(const QString &workingDir,
actualArgs.append(args);
if (flags & CommandToWindow)
- outputWindow->appendCommand(workingDir, m_settings.p4BinaryPath(), actualArgs);
+ outputWindow->appendCommand(workingDir, settings().p4BinaryPath(), actualArgs);
if (flags & ShowBusyCursor)
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
@@ -1166,7 +1165,7 @@ Core::IEditor *PerforcePlugin::showOutputInEditor(const QString &title, const QS
qDebug() << "PerforcePlugin::showOutputInEditor" << title << id.name()
<< "Size= " << output.size() << " Type=" << editorType << debugCodec(codec);
QString s = title;
- Core::IEditor *editor = Core::EditorManager::openEditorWithContents(id, &s, output);
+ Core::IEditor *editor = Core::EditorManager::openEditorWithContents(id, &s, output.toUtf8());
connect(editor, SIGNAL(annotateRevisionRequested(QString,QString,int)),
this, SLOT(vcsAnnotate(QString,QString,int)));
PerforceEditor *e = qobject_cast<PerforceEditor*>(editor->widget());
@@ -1260,7 +1259,7 @@ void PerforcePlugin::p4Diff(const PerforceDiffParameters &p)
return;
if (existingEditor) {
- existingEditor->createNew(result.stdOut);
+ existingEditor->document()->setContents(result.stdOut.toUtf8());
Core::EditorManager::activateEditor(existingEditor);
return;
}
@@ -1294,8 +1293,7 @@ void PerforcePlugin::describe(const QString & source, const QString &n)
void PerforcePlugin::submitCurrentLog()
{
m_submitActionTriggered = true;
- Core::EditorManager *em = Core::EditorManager::instance();
- em->closeEditors(QList<Core::IEditor*>() << Core::EditorManager::currentEditor());
+ Core::EditorManager::closeEditor(Core::EditorManager::currentEditor());
}
void PerforcePlugin::cleanCommitMessageFile()
@@ -1414,17 +1412,17 @@ PerforcePlugin::~PerforcePlugin()
{
}
-const PerforceSettings& PerforcePlugin::settings() const
+const PerforceSettings& PerforcePlugin::settings()
{
- return m_settings;
+ return m_instance->m_settings;
}
void PerforcePlugin::setSettings(const Settings &newSettings)
{
- if (newSettings != m_settings.settings()) {
- m_settings.setSettings(newSettings);
- m_managedDirectoryCache.clear();
- m_settings.toSettings(Core::ICore::settings());
+ if (newSettings != m_instance->m_settings.settings()) {
+ m_instance->m_settings.setSettings(newSettings);
+ m_instance->m_managedDirectoryCache.clear();
+ m_instance->m_settings.toSettings(Core::ICore::settings());
getTopLevel();
perforceVersionControl()->emitConfigurationChanged();
}
@@ -1441,7 +1439,7 @@ static inline QString msgWhereFailed(const QString & file, const QString &why)
// Map a perforce name "//xx" to its real name in the file system
QString PerforcePlugin::fileNameFromPerforceName(const QString& perforceName,
bool quiet,
- QString *errorMessage) const
+ QString *errorMessage)
{
// All happy, already mapped
if (!perforceName.startsWith(QLatin1String("//")))
@@ -1452,7 +1450,7 @@ QString PerforcePlugin::fileNameFromPerforceName(const QString& perforceName,
unsigned flags = RunFullySynchronous;
if (!quiet)
flags |= CommandToWindow|StdErrToWindow|ErrorToWindow;
- const PerforceResponse response = runP4Cmd(m_settings.topLevelSymLinkTarget(), args, flags);
+ const PerforceResponse response = runP4Cmd(settings().topLevelSymLinkTarget(), args, flags);
if (response.error) {
*errorMessage = msgWhereFailed(perforceName, response.message);
return QString();
@@ -1470,21 +1468,15 @@ QString PerforcePlugin::fileNameFromPerforceName(const QString& perforceName,
return QString();
}
const QString p4fileSpec = output.mid(output.lastIndexOf(QLatin1Char(' ')) + 1);
- const QString rc = m_settings.mapToFileSystem(p4fileSpec);
+ const QString rc = m_instance->m_settings.mapToFileSystem(p4fileSpec);
if (Perforce::Constants::debug)
qDebug() << "fileNameFromPerforceName" << perforceName << p4fileSpec << rc;
return rc;
}
-PerforcePlugin *PerforcePlugin::perforcePluginInstance()
-{
- QTC_ASSERT(m_perforcePluginInstance, return 0);
- return m_perforcePluginInstance;
-}
-
-PerforceVersionControl *PerforcePlugin::perforceVersionControl() const
+PerforceVersionControl *PerforcePlugin::perforceVersionControl()
{
- return static_cast<PerforceVersionControl *>(versionControl());
+ return static_cast<PerforceVersionControl *>(m_instance->versionControl());
}
void PerforcePlugin::slotTopLevelFound(const QString &t)
@@ -1507,14 +1499,14 @@ void PerforcePlugin::slotTopLevelFailed(const QString &errorMessage)
void PerforcePlugin::getTopLevel()
{
// Run a new checker
- if (m_settings.p4BinaryPath().isEmpty())
+ if (m_instance->m_settings.p4BinaryPath().isEmpty())
return;
- PerforceChecker *checker = new PerforceChecker(this);
- connect(checker, SIGNAL(failed(QString)), this, SLOT(slotTopLevelFailed(QString)));
+ PerforceChecker *checker = new PerforceChecker(m_instance);
+ connect(checker, SIGNAL(failed(QString)), m_instance, SLOT(slotTopLevelFailed(QString)));
connect(checker, SIGNAL(failed(QString)), checker, SLOT(deleteLater()));
- connect(checker, SIGNAL(succeeded(QString)), this, SLOT(slotTopLevelFound(QString)));
+ connect(checker, SIGNAL(succeeded(QString)), m_instance, SLOT(slotTopLevelFound(QString)));
connect(checker, SIGNAL(succeeded(QString)),checker, SLOT(deleteLater()));
- checker->start(m_settings.p4BinaryPath(), m_settings.commonP4Arguments(QString()), 30000);
+ checker->start(settings().p4BinaryPath(), settings().commonP4Arguments(QString()), 30000);
}
#ifdef WITH_TESTS
diff --git a/src/plugins/perforce/perforceplugin.h b/src/plugins/perforce/perforceplugin.h
index 8eeb1e232e..33d8f4737b 100644
--- a/src/plugins/perforce/perforceplugin.h
+++ b/src/plugins/perforce/perforceplugin.h
@@ -95,15 +95,13 @@ public:
Core::IEditor *openPerforceSubmitEditor(const QString &fileName, const QStringList &depotFileNames);
- static PerforcePlugin *perforcePluginInstance();
-
- const PerforceSettings& settings() const;
- void setSettings(const Settings &s);
+ static const PerforceSettings& settings();
+ static void setSettings(const Settings &s);
// Map a perforce name "//xx" to its real name in the file system
- QString fileNameFromPerforceName(const QString& perforceName,
- bool quiet,
- QString *errorMessage) const;
+ static QString fileNameFromPerforceName(const QString& perforceName,
+ bool quiet,
+ QString *errorMessage);
public slots:
void describe(const QString &source, const QString &n);
@@ -165,35 +163,35 @@ private:
// args are passed as command line arguments
// extra args via a tempfile and the option -x "temp-filename"
- PerforceResponse runP4Cmd(const QString &workingDir,
- const QStringList &args,
- unsigned flags = CommandToWindow|StdErrToWindow|ErrorToWindow,
- const QStringList &extraArgs = QStringList(),
- const QByteArray &stdInput = QByteArray(),
- QTextCodec *outputCodec = 0) const;
-
- inline PerforceResponse synchronousProcess(const QString &workingDir,
+ static PerforceResponse runP4Cmd(const QString &workingDir,
+ const QStringList &args,
+ unsigned flags = CommandToWindow|StdErrToWindow|ErrorToWindow,
+ const QStringList &extraArgs = QStringList(),
+ const QByteArray &stdInput = QByteArray(),
+ QTextCodec *outputCodec = 0);
+
+ static PerforceResponse synchronousProcess(const QString &workingDir,
const QStringList &args,
unsigned flags,
const QByteArray &stdInput,
- QTextCodec *outputCodec) const;
+ QTextCodec *outputCodec);
- inline PerforceResponse fullySynchronousProcess(const QString &workingDir,
+ static PerforceResponse fullySynchronousProcess(const QString &workingDir,
const QStringList &args,
unsigned flags,
const QByteArray &stdInput,
- QTextCodec *outputCodec) const;
+ QTextCodec *outputCodec);
QString clientFilePath(const QString &serverFilePath);
void annotate(const QString &workingDir, const QString &fileName,
const QString &changeList = QString(), int lineNumber = -1);
- void filelog(const QString &workingDir, const QStringList &fileNames = QStringList(),
+ void filelog(const QString &workingDir, const QString &fileName = QString(),
bool enableAnnotationContextMenu = false);
void cleanCommitMessageFile();
bool isCommitEditorOpen() const;
- QSharedPointer<Utils::TempFileSaver> createTemporaryArgumentFile(const QStringList &extraArgs,
- QString *errorString) const;
- void getTopLevel();
+ static QSharedPointer<Utils::TempFileSaver> createTemporaryArgumentFile(const QStringList &extraArgs,
+ QString *errorString);
+ static void getTopLevel();
QString pendingChangesData();
void updateCheckout(const QString &workingDir = QString(),
@@ -201,7 +199,7 @@ private:
bool revertProject(const QString &workingDir, const QStringList &args, bool unchangedOnly);
bool managesDirectoryFstat(const QString &directory);
- inline PerforceVersionControl *perforceVersionControl() const;
+ static PerforceVersionControl *perforceVersionControl();
Locator::CommandLocator *m_commandLocator;
Utils::ParameterAction *m_editAction;
@@ -235,7 +233,7 @@ private:
QAction *m_redoAction;
QAction *m_menuAction;
- static PerforcePlugin *m_perforcePluginInstance;
+ static PerforcePlugin *m_instance;
PerforceSettings m_settings;
ManagedDirectoryCache m_managedDirectoryCache;
diff --git a/src/plugins/perforce/perforcesettings.cpp b/src/plugins/perforce/perforcesettings.cpp
index 8579fa2f80..822f4f90bb 100644
--- a/src/plugins/perforce/perforcesettings.cpp
+++ b/src/plugins/perforce/perforcesettings.cpp
@@ -241,10 +241,9 @@ QString PerforceSettings::relativeToTopLevel(const QString &dir) const
return m_topLevelDir->relativeFilePath(dir);
}
-QStringList PerforceSettings::relativeToTopLevelArguments(const QString &dir) const
+QString PerforceSettings::relativeToTopLevelArguments(const QString &dir) const
{
- const QString relative = relativeToTopLevel(dir);
- return relative.isEmpty() ? QStringList() : QStringList(relative);
+ return relativeToTopLevel(dir);
}
// Map the root part of a path:
diff --git a/src/plugins/perforce/perforcesettings.h b/src/plugins/perforce/perforcesettings.h
index a84d81fc16..17a7fdca3b 100644
--- a/src/plugins/perforce/perforcesettings.h
+++ b/src/plugins/perforce/perforcesettings.h
@@ -117,7 +117,7 @@ public:
QString relativeToTopLevel(const QString &dir) const;
// Return argument list relative to top level (empty meaning,
// it is the same directory).
- QStringList relativeToTopLevelArguments(const QString &dir) const;
+ QString relativeToTopLevelArguments(const QString &dir) const;
// Map p4 path back to file system in case of a symlinked top-level
QString mapToFileSystem(const QString &perforceFilePath) const;
diff --git a/src/plugins/perforce/perforcesubmiteditor.cpp b/src/plugins/perforce/perforcesubmiteditor.cpp
index c72bac449c..ef910427ba 100644
--- a/src/plugins/perforce/perforcesubmiteditor.cpp
+++ b/src/plugins/perforce/perforcesubmiteditor.cpp
@@ -32,6 +32,7 @@
#include "perforceplugin.h"
#include "perforceconstants.h"
+#include <coreplugin/idocument.h>
#include <vcsbase/submitfilemodel.h>
#include <utils/qtcassert.h>
@@ -46,7 +47,7 @@ PerforceSubmitEditor::PerforceSubmitEditor(const VcsBase::VcsBaseSubmitEditorPar
VcsBaseSubmitEditor(parameters, new PerforceSubmitEditorWidget(parent)),
m_fileModel(new VcsBase::SubmitFileModel(this))
{
- setDisplayName(tr("Perforce Submit"));
+ document()->setDisplayName(tr("Perforce Submit"));
setFileModel(m_fileModel);
}
@@ -70,11 +71,11 @@ QByteArray PerforceSubmitEditor::fileContents() const
return text.toLocal8Bit();
}
-bool PerforceSubmitEditor::setFileContents(const QString &contents)
+bool PerforceSubmitEditor::setFileContents(const QByteArray &contents)
{
if (Perforce::Constants::debug)
qDebug() << Q_FUNC_INFO << contents;
- if (!parseText(contents))
+ if (!parseText(QString::fromUtf8(contents)))
return false;
updateFields();
return true;
diff --git a/src/plugins/perforce/perforcesubmiteditor.h b/src/plugins/perforce/perforcesubmiteditor.h
index dc3447712a..9baf78ac88 100644
--- a/src/plugins/perforce/perforcesubmiteditor.h
+++ b/src/plugins/perforce/perforcesubmiteditor.h
@@ -67,7 +67,7 @@ public:
protected:
QByteArray fileContents() const;
- bool setFileContents(const QString &contents);
+ bool setFileContents(const QByteArray &contents);
private:
inline PerforceSubmitEditorWidget *submitEditorWidget();
diff --git a/src/plugins/perforce/settingspage.cpp b/src/plugins/perforce/settingspage.cpp
index b065e9a83b..7c159d4791 100644
--- a/src/plugins/perforce/settingspage.cpp
+++ b/src/plugins/perforce/settingspage.cpp
@@ -145,7 +145,7 @@ SettingsPage::SettingsPage()
QWidget *SettingsPage::createPage(QWidget *parent)
{
m_widget = new SettingsPageWidget(parent);
- m_widget->setSettings(PerforcePlugin::perforcePluginInstance()->settings());
+ m_widget->setSettings(PerforcePlugin::settings());
if (m_searchKeywords.isEmpty())
m_searchKeywords = m_widget->searchKeywords();
return m_widget;
@@ -153,7 +153,7 @@ QWidget *SettingsPage::createPage(QWidget *parent)
void SettingsPage::apply()
{
- PerforcePlugin::perforcePluginInstance()->setSettings(m_widget->settings());
+ PerforcePlugin::setSettings(m_widget->settings());
}
bool SettingsPage::matches(const QString &s) const
diff --git a/src/plugins/plugins.pro b/src/plugins/plugins.pro
index 52855dd790..430e135b40 100644
--- a/src/plugins/plugins.pro
+++ b/src/plugins/plugins.pro
@@ -4,7 +4,6 @@ TEMPLATE = subdirs
SUBDIRS = \
coreplugin \
- welcome \
find \
texteditor \
cppeditor \
@@ -32,6 +31,7 @@ SUBDIRS = \
resourceeditor \
genericprojectmanager \
qmljseditor \
+ qmlprojectmanager \
glsleditor \
pythoneditor \
mercurial \
@@ -46,9 +46,12 @@ SUBDIRS = \
madde \
valgrind \
todo \
- qnx
+ qnx \
+ clearcase \
+ baremetal
-exists(../shared/qbs/qbs.pro): \
+isEmpty(QBS_INSTALL_DIR): QBS_INSTALL_DIR = $$(QBS_INSTALL_DIR)
+exists(../shared/qbs/qbs.pro)|!isEmpty(QBS_INSTALL_DIR): \
SUBDIRS += \
qbsprojectmanager
@@ -61,31 +64,16 @@ isEmpty(IDE_PACKAGE_MODE) {
updateinfo
}
-!macx: \
+minQtVersion(5, 1, 0) {
SUBDIRS += \
- clearcase
-
-contains(QT_CONFIG, declarative)|!isEmpty(QT.declarative.name) {
- SUBDIRS += \
- qmlprojectmanager \
- qmlprofiler
-
- greaterThan(QT_MAJOR_VERSION, 4) {
- SUBDIRS += \
- qmldesigner
- } else {
- include(../private_headers.pri)
- exists($${QT_PRIVATE_HEADERS}/QtDeclarative/private/qdeclarativecontext_p.h) {
- SUBDIRS += \
- qmldesigner
- } else {
- warning("QmlDesigner plugin has been disabled.")
- warning("The plugin depends on private headers from QtDeclarative module.")
- warning("To enable it, pass 'QT_PRIVATE_HEADERS=$QTDIR/include' to qmake, where $QTDIR is the source directory of qt.")
- }
- }
+ qmldesigner \
+ qmlprofiler \
+ welcome
} else {
- warning("QmlProjectManager, QmlProfiler and QmlDesigner plugins have been disabled: The plugins require QtDeclarative")
+ warning("QmlDesigner plugin has been disabled.")
+ warning("QmlProfiler plugin has been disabled.")
+ warning("Welcome plugin has been disabled.")
+ warning("These plugins need at least Qt 5.1.")
}
for(p, SUBDIRS) {
diff --git a/src/plugins/plugins.qbs b/src/plugins/plugins.qbs
index 0f0d044122..3981b5be54 100644
--- a/src/plugins/plugins.qbs
+++ b/src/plugins/plugins.qbs
@@ -2,10 +2,12 @@ import qbs
Project {
name: "Plugins"
+
references: [
"analyzerbase/analyzerbase.qbs",
"android/android.qbs",
"autotoolsprojectmanager/autotoolsprojectmanager.qbs",
+ "baremetal/baremetal.qbs",
"bazaar/bazaar.qbs",
"bineditor/bineditor.qbs",
"bookmarks/bookmarks.qbs",
diff --git a/src/plugins/projectexplorer/ProjectExplorer.pluginspec.in b/src/plugins/projectexplorer/ProjectExplorer.pluginspec.in
index 588fe9865d..bf58664ad0 100644
--- a/src/plugins/projectexplorer/ProjectExplorer.pluginspec.in
+++ b/src/plugins/projectexplorer/ProjectExplorer.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"ProjectExplorer\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"ProjectExplorer\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/projectexplorer/abi.cpp b/src/plugins/projectexplorer/abi.cpp
index fe5b0558f2..83705825cc 100644
--- a/src/plugins/projectexplorer/abi.cpp
+++ b/src/plugins/projectexplorer/abi.cpp
@@ -244,7 +244,7 @@ static QList<Abi> abiOf(const QByteArray &data)
result.append(Abi(Abi::ItaniumArchitecture, os, flavor, Abi::ElfFormat, 64));
break;
default:
- ;;
+ ;
}
} else if (((getUint8(data, 0) == 0xce || getUint8(data, 0) == 0xcf)
&& getUint8(data, 1) == 0xfa && getUint8(data, 2) == 0xed && getUint8(data, 3) == 0xfe
@@ -440,6 +440,78 @@ Abi::Abi(const QString &abiString) :
}
}
+Abi Abi::abiFromTargetTriplet(const QString &triple)
+{
+ QString machine = triple.toLower();
+ if (machine.isEmpty())
+ return Abi();
+
+ QStringList parts = machine.split(QRegExp(QLatin1String("[ /-]")));
+
+ Abi::Architecture arch = Abi::UnknownArchitecture;
+ Abi::OS os = Abi::UnknownOS;
+ Abi::OSFlavor flavor = Abi::UnknownFlavor;
+ Abi::BinaryFormat format = Abi::UnknownFormat;
+ int width = 0;
+ int unknownCount = 0;
+
+ foreach (const QString &p, parts) {
+ if (p == QLatin1String("unknown") || p == QLatin1String("pc") || p == QLatin1String("none")
+ || p == QLatin1String("gnu") || p == QLatin1String("uclibc")
+ || p == QLatin1String("86_64") || p == QLatin1String("redhat")
+ || p == QLatin1String("gnueabi") || p == QLatin1String("w64")) {
+ continue;
+ } else if (p == QLatin1String("i386") || p == QLatin1String("i486") || p == QLatin1String("i586")
+ || p == QLatin1String("i686") || p == QLatin1String("x86")) {
+ arch = Abi::X86Architecture;
+ } else if (p.startsWith(QLatin1String("arm"))) {
+ arch = Abi::ArmArchitecture;
+ width = 32;
+ } else if (p == QLatin1String("mipsel")) {
+ arch = Abi::MipsArchitecture;
+ width = 32;
+ } else if (p == QLatin1String("x86_64") || p == QLatin1String("amd64")) {
+ arch = Abi::X86Architecture;
+ width = 64;
+ } else if (p == QLatin1String("powerpc64")) {
+ arch = Abi::PowerPCArchitecture;
+ width = 64;
+ } else if (p == QLatin1String("powerpc")) {
+ arch = Abi::PowerPCArchitecture;
+ width = 32;
+ } else if (p == QLatin1String("linux") || p == QLatin1String("linux6e")) {
+ os = Abi::LinuxOS;
+ if (flavor == Abi::UnknownFlavor)
+ flavor = Abi::GenericLinuxFlavor;
+ format = Abi::ElfFormat;
+ } else if (p.startsWith(QLatin1String("freebsd"))) {
+ os = Abi::BsdOS;
+ if (flavor == Abi::UnknownFlavor)
+ flavor = Abi::FreeBsdFlavor;
+ format = Abi::ElfFormat;
+ } else if (p == QLatin1String("mingw32") || p == QLatin1String("win32") || p == QLatin1String("mingw32msvc")) {
+ arch = Abi::X86Architecture;
+ os = Abi::WindowsOS;
+ flavor = Abi::WindowsMSysFlavor;
+ format = Abi::PEFormat;
+ } else if (p == QLatin1String("apple")) {
+ os = Abi::MacOS;
+ flavor = Abi::GenericMacFlavor;
+ format = Abi::MachOFormat;
+ } else if (p == QLatin1String("darwin10")) {
+ width = 64;
+ } else if (p == QLatin1String("darwin9")) {
+ width = 32;
+ } else if (p == QLatin1String("gnueabi")) {
+ format = Abi::ElfFormat;
+ } else {
+ ++unknownCount;
+ }
+ }
+
+ return Abi(arch, os, flavor, format, width);
+}
+
QString Abi::toString() const
{
QStringList dn;
diff --git a/src/plugins/projectexplorer/abi.h b/src/plugins/projectexplorer/abi.h
index 6b7b56bab8..a805a1be04 100644
--- a/src/plugins/projectexplorer/abi.h
+++ b/src/plugins/projectexplorer/abi.h
@@ -117,6 +117,8 @@ public:
const OSFlavor &so, const BinaryFormat &f, unsigned char w);
Abi(const QString &abiString);
+ static Abi abiFromTargetTriplet(const QString &machineTriple);
+
bool operator != (const Abi &other) const;
bool operator == (const Abi &other) const;
bool isCompatibleWith(const Abi &other) const;
diff --git a/src/plugins/projectexplorer/abstractmsvctoolchain.cpp b/src/plugins/projectexplorer/abstractmsvctoolchain.cpp
index 9ebc21b409..cf20d23f1b 100644
--- a/src/plugins/projectexplorer/abstractmsvctoolchain.cpp
+++ b/src/plugins/projectexplorer/abstractmsvctoolchain.cpp
@@ -47,10 +47,10 @@ namespace Internal {
AbstractMsvcToolChain::AbstractMsvcToolChain(const QString &id,
- bool autodetect,
+ Detection d,
const Abi &abi,
const QString& vcvarsBat) :
- ToolChain(id, autodetect),
+ ToolChain(id, d),
m_lastEnvironment(Utils::Environment::systemEnvironment()),
m_abi(abi),
m_vcvarsBat(vcvarsBat)
@@ -61,8 +61,8 @@ AbstractMsvcToolChain::AbstractMsvcToolChain(const QString &id,
Q_ASSERT(!m_vcvarsBat.isEmpty());
}
-AbstractMsvcToolChain::AbstractMsvcToolChain(const QString &id, bool autodetect) :
- ToolChain(id, autodetect),
+AbstractMsvcToolChain::AbstractMsvcToolChain(const QString &id, Detection d) :
+ ToolChain(id, d),
m_lastEnvironment(Utils::Environment::systemEnvironment())
{
@@ -181,7 +181,7 @@ void AbstractMsvcToolChain::addToEnvironment(Utils::Environment &env) const
QString AbstractMsvcToolChain::makeCommand(const Utils::Environment &environment) const
{
- bool useJom = ProjectExplorerPlugin::instance()->projectExplorerSettings().useJom;
+ bool useJom = ProjectExplorerPlugin::projectExplorerSettings().useJom;
const QString jom = QLatin1String("jom.exe");
const QString nmake = QLatin1String("nmake.exe");
QString tmp;
@@ -223,14 +223,15 @@ QByteArray AbstractMsvcToolChain::msvcPredefinedMacros(const QStringList cxxflag
Q_UNUSED(cxxflags);
Q_UNUSED(env);
- QByteArray predefinedMacros = "#define __MSVCRT__\n"
+ static const QByteArray predefinedMacros(
+ "#define __MSVCRT__\n"
"#define __w64\n"
"#define __int64 long long\n"
"#define __int32 long\n"
"#define __int16 short\n"
"#define __int8 char\n"
"#define __ptr32\n"
- "#define __ptr64\n";
+ "#define __ptr64\n");
return predefinedMacros;
}
diff --git a/src/plugins/projectexplorer/abstractmsvctoolchain.h b/src/plugins/projectexplorer/abstractmsvctoolchain.h
index bcf405e417..13ec2dbb78 100644
--- a/src/plugins/projectexplorer/abstractmsvctoolchain.h
+++ b/src/plugins/projectexplorer/abstractmsvctoolchain.h
@@ -43,8 +43,8 @@ namespace Internal {
class PROJECTEXPLORER_EXPORT AbstractMsvcToolChain : public ToolChain
{
public:
- AbstractMsvcToolChain(const QString &id, bool autodetect, const Abi &abi, const QString& vcvarsBat);
- AbstractMsvcToolChain(const QString &id, bool autodetect);
+ explicit AbstractMsvcToolChain(const QString &id, Detection d, const Abi &abi, const QString& vcvarsBat);
+ explicit AbstractMsvcToolChain(const QString &id, Detection d);
Abi targetAbi() const;
diff --git a/src/plugins/projectexplorer/abstractprocessstep.cpp b/src/plugins/projectexplorer/abstractprocessstep.cpp
index e7402169fa..768cd9556a 100644
--- a/src/plugins/projectexplorer/abstractprocessstep.cpp
+++ b/src/plugins/projectexplorer/abstractprocessstep.cpp
@@ -300,6 +300,9 @@ void AbstractProcessStep::processStartupFailed()
bool AbstractProcessStep::processSucceeded(int exitCode, QProcess::ExitStatus status)
{
+ if (outputParser() && outputParser()->hasFatalErrors())
+ return false;
+
return exitCode == 0 && status == QProcess::NormalExit;
}
diff --git a/src/plugins/projectexplorer/allprojectsfilter.cpp b/src/plugins/projectexplorer/allprojectsfilter.cpp
index 4c85892865..32a0aeb751 100644
--- a/src/plugins/projectexplorer/allprojectsfilter.cpp
+++ b/src/plugins/projectexplorer/allprojectsfilter.cpp
@@ -37,8 +37,7 @@ using namespace Locator;
using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;
-AllProjectsFilter::AllProjectsFilter(ProjectExplorerPlugin *pe)
- : m_projectExplorer(pe), m_filesUpToDate(false)
+AllProjectsFilter::AllProjectsFilter() : m_filesUpToDate(false)
{
setId("Files in any project");
setDisplayName(tr("Files in Any Project"));
@@ -46,7 +45,7 @@ AllProjectsFilter::AllProjectsFilter(ProjectExplorerPlugin *pe)
setPriority(Low);
setIncludedByDefault(true);
- connect(m_projectExplorer, SIGNAL(fileListChanged()),
+ connect(ProjectExplorerPlugin::instance(), SIGNAL(fileListChanged()),
this, SLOT(markFilesAsOutOfDate()));
}
@@ -61,7 +60,7 @@ void AllProjectsFilter::updateFiles()
return;
m_filesUpToDate = true;
files().clear();
- foreach (Project *project, m_projectExplorer->session()->projects())
+ foreach (Project *project, SessionManager::projects())
files().append(project->files(Project::AllFiles));
qSort(files());
generateFileNames();
diff --git a/src/plugins/projectexplorer/allprojectsfilter.h b/src/plugins/projectexplorer/allprojectsfilter.h
index fcab19fafc..dbdbebe7f2 100644
--- a/src/plugins/projectexplorer/allprojectsfilter.h
+++ b/src/plugins/projectexplorer/allprojectsfilter.h
@@ -35,9 +35,6 @@
#include <QFutureInterface>
namespace ProjectExplorer {
-
-class ProjectExplorerPlugin;
-
namespace Internal {
class AllProjectsFilter : public Locator::BaseFileFilter
@@ -45,7 +42,7 @@ class AllProjectsFilter : public Locator::BaseFileFilter
Q_OBJECT
public:
- explicit AllProjectsFilter(ProjectExplorerPlugin *pe);
+ AllProjectsFilter();
void refresh(QFutureInterface<void> &future);
protected:
@@ -53,8 +50,8 @@ protected:
private slots:
void markFilesAsOutOfDate();
+
private:
- ProjectExplorerPlugin *m_projectExplorer;
bool m_filesUpToDate;
};
diff --git a/src/plugins/projectexplorer/allprojectsfind.cpp b/src/plugins/projectexplorer/allprojectsfind.cpp
index 2e7a7c5788..27a9e14060 100644
--- a/src/plugins/projectexplorer/allprojectsfind.cpp
+++ b/src/plugins/projectexplorer/allprojectsfind.cpp
@@ -48,11 +48,10 @@ using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;
using namespace TextEditor;
-AllProjectsFind::AllProjectsFind(ProjectExplorerPlugin *plugin)
- : m_plugin(plugin),
- m_configWidget(0)
+AllProjectsFind::AllProjectsFind()
+ : m_configWidget(0)
{
- connect(m_plugin, SIGNAL(fileListChanged()), this, SLOT(handleFileListChanged()));
+ connect(ProjectExplorerPlugin::instance(), SIGNAL(fileListChanged()), this, SLOT(handleFileListChanged()));
}
QString AllProjectsFind::id() const
@@ -67,15 +66,14 @@ QString AllProjectsFind::displayName() const
bool AllProjectsFind::isEnabled() const
{
- return BaseFileFind::isEnabled()
- && m_plugin->session()->projects().count() > 0;
+ return BaseFileFind::isEnabled() && SessionManager::hasProjects();
}
Utils::FileIterator *AllProjectsFind::files(const QStringList &nameFilters,
const QVariant &additionalParameters) const
{
Q_UNUSED(additionalParameters)
- return filesForProjects(nameFilters, m_plugin->session()->projects());
+ return filesForProjects(nameFilters, SessionManager::projects());
}
Utils::FileIterator *AllProjectsFind::filesForProjects(const QStringList &nameFilters,
@@ -85,7 +83,7 @@ Utils::FileIterator *AllProjectsFind::filesForProjects(const QStringList &nameFi
foreach (const QString &filter, nameFilters) {
filterRegs << QRegExp(filter, Qt::CaseInsensitive, QRegExp::Wildcard);
}
- QMap<QString, QTextCodec *> openEditorEncodings = TextEditor::ITextEditor::openedTextEditorsEncodings();
+ QMap<QString, QTextCodec *> openEditorEncodings = TextEditor::ITextEditor::openedTextDocumentEncodings();
QMap<QString, QTextCodec *> encodings;
foreach (const Project *project, projects) {
QStringList projectFiles = project->files(Project::AllFiles);
diff --git a/src/plugins/projectexplorer/allprojectsfind.h b/src/plugins/projectexplorer/allprojectsfind.h
index e8f619231e..7781e2fdef 100644
--- a/src/plugins/projectexplorer/allprojectsfind.h
+++ b/src/plugins/projectexplorer/allprojectsfind.h
@@ -36,7 +36,6 @@
namespace ProjectExplorer {
-class ProjectExplorerPlugin;
class Project;
namespace Internal {
@@ -46,7 +45,7 @@ class AllProjectsFind : public TextEditor::BaseFileFind
Q_OBJECT
public:
- AllProjectsFind(ProjectExplorerPlugin *plugin);
+ AllProjectsFind();
QString id() const;
QString displayName() const;
@@ -71,7 +70,6 @@ private slots:
void handleFileListChanged();
private:
- ProjectExplorerPlugin *m_plugin;
QPointer<QWidget> m_configWidget;
};
diff --git a/src/plugins/projectexplorer/applicationlauncher.cpp b/src/plugins/projectexplorer/applicationlauncher.cpp
index 3404b6c226..dbfef44220 100644
--- a/src/plugins/projectexplorer/applicationlauncher.cpp
+++ b/src/plugins/projectexplorer/applicationlauncher.cpp
@@ -90,7 +90,7 @@ ApplicationLauncherPrivate::ApplicationLauncherPrivate() :
ApplicationLauncher::ApplicationLauncher(QObject *parent)
: QObject(parent), d(new ApplicationLauncherPrivate)
{
- if (ProjectExplorerPlugin::instance()->projectExplorerSettings().mergeStdErrAndStdOut){
+ if (ProjectExplorerPlugin::projectExplorerSettings().mergeStdErrAndStdOut){
d->m_guiProcess.setReadChannelMode(QProcess::MergedChannels);
} else {
d->m_guiProcess.setReadChannelMode(QProcess::SeparateChannels);
@@ -113,8 +113,8 @@ ApplicationLauncher::ApplicationLauncher(QObject *parent)
this, SIGNAL(processStarted()));
connect(&d->m_consoleProcess, SIGNAL(processError(QString)),
this, SLOT(consoleProcessError(QString)));
- connect(&d->m_consoleProcess, SIGNAL(processStopped()),
- this, SLOT(processStopped()));
+ connect(&d->m_consoleProcess, SIGNAL(processStopped(int,QProcess::ExitStatus)),
+ this, SLOT(processDone(int,QProcess::ExitStatus)));
#ifdef Q_OS_WIN
connect(WinDebugInterface::instance(), SIGNAL(cannotRetrieveDebugOutput()),
@@ -181,7 +181,7 @@ void ApplicationLauncher::stop()
}
} else {
d->m_consoleProcess.stop();
- processStopped();
+ processDone(0, QProcess::CrashExit);
}
}
@@ -214,12 +214,14 @@ qint64 ApplicationLauncher::applicationPID() const
void ApplicationLauncher::guiProcessError()
{
QString error;
+ QProcess::ExitStatus status = QProcess::NormalExit;
switch (d->m_guiProcess.error()) {
case QProcess::FailedToStart:
error = tr("Failed to start program. Path or permissions wrong?");
break;
case QProcess::Crashed:
error = tr("The program has unexpectedly finished.");
+ status = QProcess::CrashExit;
break;
default:
error = tr("Some error has occurred while running the program.");
@@ -227,7 +229,7 @@ void ApplicationLauncher::guiProcessError()
emit appendMessage(error + QLatin1Char('\n'), Utils::ErrorMessageFormat);
if (d->m_processRunning && !isRunning()) {
d->m_processRunning = false;
- emit processExited(-1);
+ emit processExited(-1, status);
}
}
@@ -236,7 +238,7 @@ void ApplicationLauncher::consoleProcessError(const QString &error)
emit appendMessage(error + QLatin1Char('\n'), Utils::ErrorMessageFormat);
if (d->m_processRunning && d->m_consoleProcess.applicationPID() == 0) {
d->m_processRunning = false;
- emit processExited(-1);
+ emit processExited(-1, QProcess::NormalExit);
}
}
@@ -270,14 +272,9 @@ void ApplicationLauncher::checkDebugOutput(qint64 pid, const QString &message)
}
#endif
-void ApplicationLauncher::processStopped()
-{
- emit processExited(0);
-}
-
-void ApplicationLauncher::processDone(int exitCode, QProcess::ExitStatus)
+void ApplicationLauncher::processDone(int exitCode, QProcess::ExitStatus status)
{
- emit processExited(exitCode);
+ emit processExited(exitCode, status);
}
void ApplicationLauncher::bringToForeground()
diff --git a/src/plugins/projectexplorer/applicationlauncher.h b/src/plugins/projectexplorer/applicationlauncher.h
index f3c3c176d5..3744bab624 100644
--- a/src/plugins/projectexplorer/applicationlauncher.h
+++ b/src/plugins/projectexplorer/applicationlauncher.h
@@ -71,11 +71,10 @@ public:
signals:
void appendMessage(const QString &message, Utils::OutputFormat format);
void processStarted();
- void processExited(int exitCode);
+ void processExited(int exitCode, QProcess::ExitStatus);
void bringToForegroundRequested(qint64 pid);
private slots:
- void processStopped();
void guiProcessError();
void consoleProcessError(const QString &error);
void readStandardOutput();
diff --git a/src/plugins/projectexplorer/appoutputpane.cpp b/src/plugins/projectexplorer/appoutputpane.cpp
index e0969dc8df..74917d06d7 100644
--- a/src/plugins/projectexplorer/appoutputpane.cpp
+++ b/src/plugins/projectexplorer/appoutputpane.cpp
@@ -167,7 +167,7 @@ AppOutputPane::AppOutputPane() :
m_mainWidget->setLayout(layout);
- connect(ProjectExplorerPlugin::instance()->session(), SIGNAL(aboutToUnloadSession(QString)),
+ connect(SessionManager::instance(), SIGNAL(aboutToUnloadSession(QString)),
this, SLOT(aboutToUnloadSession()));
connect(ProjectExplorerPlugin::instance(), SIGNAL(settingsChanged()),
this, SLOT(updateFromSettings()));
@@ -301,7 +301,7 @@ void AppOutputPane::createNewOutputWindow(RunControl *rc)
this, SLOT(appendMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat)));
Utils::OutputFormatter *formatter = rc->outputFormatter();
- formatter->setFont(TextEditor::TextEditorSettings::instance()->fontSettings().font());
+ formatter->setFont(TextEditor::TextEditorSettings::fontSettings().font());
// First look if we can reuse a tab
const int size = m_runControlTabs.size();
@@ -327,8 +327,8 @@ void AppOutputPane::createNewOutputWindow(RunControl *rc)
ow->setWindowTitle(tr("Application Output Window"));
ow->setWindowIcon(QIcon(QLatin1String(Constants::ICON_WINDOW)));
ow->setFormatter(formatter);
- ow->setWordWrapEnabled(ProjectExplorerPlugin::instance()->projectExplorerSettings().wrapAppOutput);
- ow->setMaxLineCount(ProjectExplorerPlugin::instance()->projectExplorerSettings().maxAppOutputLines);
+ ow->setWordWrapEnabled(ProjectExplorerPlugin::projectExplorerSettings().wrapAppOutput);
+ ow->setMaxLineCount(ProjectExplorerPlugin::projectExplorerSettings().maxAppOutputLines);
Aggregation::Aggregate *agg = new Aggregation::Aggregate;
agg->add(ow);
agg->add(new Find::BaseTextFind(ow));
@@ -341,7 +341,7 @@ void AppOutputPane::createNewOutputWindow(RunControl *rc)
void AppOutputPane::handleOldOutput(Core::OutputWindow *window) const
{
- if (ProjectExplorerPlugin::instance()->projectExplorerSettings().cleanOldAppOutput)
+ if (ProjectExplorerPlugin::projectExplorerSettings().cleanOldAppOutput)
window->clear();
else
window->grayOutOldContent();
@@ -352,8 +352,8 @@ void AppOutputPane::updateFromSettings()
const int size = m_runControlTabs.size();
for (int i = 0; i < size; i++) {
RunControlTab &tab =m_runControlTabs[i];
- tab.window->setWordWrapEnabled(ProjectExplorerPlugin::instance()->projectExplorerSettings().wrapAppOutput);
- tab.window->setMaxLineCount(ProjectExplorerPlugin::instance()->projectExplorerSettings().maxAppOutputLines);
+ tab.window->setWordWrapEnabled(ProjectExplorerPlugin::projectExplorerSettings().wrapAppOutput);
+ tab.window->setMaxLineCount(ProjectExplorerPlugin::projectExplorerSettings().maxAppOutputLines);
}
}
@@ -486,11 +486,10 @@ bool AppOutputPane::closeTab(int tabIndex, CloseTabMode closeTabMode)
bool AppOutputPane::optionallyPromptToStop(RunControl *runControl)
{
- ProjectExplorerPlugin *pe = ProjectExplorerPlugin::instance();
- ProjectExplorerSettings settings = pe->projectExplorerSettings();
+ ProjectExplorerSettings settings = ProjectExplorerPlugin::projectExplorerSettings();
if (!runControl->promptToStop(&settings.prompToStopRunControl))
return false;
- pe->setProjectExplorerSettings(settings);
+ ProjectExplorerPlugin::setProjectExplorerSettings(settings);
return true;
}
@@ -569,6 +568,7 @@ void AppOutputPane::slotRunControlFinished()
ProjectExplorer::RunControl *rc = qobject_cast<RunControl *>(sender());
QMetaObject::invokeMethod(this, "slotRunControlFinished2", Qt::QueuedConnection,
Q_ARG(ProjectExplorer::RunControl *, rc));
+ rc->outputFormatter()->flush();
}
void AppOutputPane::slotRunControlFinished2(RunControl *sender)
diff --git a/src/plugins/projectexplorer/buildconfiguration.cpp b/src/plugins/projectexplorer/buildconfiguration.cpp
index 65a82aa565..8366ff00f0 100644
--- a/src/plugins/projectexplorer/buildconfiguration.cpp
+++ b/src/plugins/projectexplorer/buildconfiguration.cpp
@@ -43,10 +43,13 @@
#include <utils/qtcassert.h>
#include <utils/stringutils.h>
+#include <QDebug>
+
static const char BUILD_STEP_LIST_COUNT[] = "ProjectExplorer.BuildConfiguration.BuildStepListCount";
static const char BUILD_STEP_LIST_PREFIX[] = "ProjectExplorer.BuildConfiguration.BuildStepList.";
static const char CLEAR_SYSTEM_ENVIRONMENT_KEY[] = "ProjectExplorer.BuildConfiguration.ClearSystemEnvironment";
static const char USER_ENVIRONMENT_CHANGES_KEY[] = "ProjectExplorer.BuildConfiguration.UserEnvironmentChanges";
+static const char BUILDDIRECTORY_KEY[] = "ProjectExplorer.BuildConfiguration.BuildDirectory";
namespace ProjectExplorer {
namespace Internal {
@@ -66,7 +69,7 @@ bool BuildConfigMacroExpander::resolveMacro(const QString &name, QString *ret)
return true;
}
if (name == QLatin1String("buildDir")) {
- *ret = QDir::toNativeSeparators(m_bc->buildDirectory());
+ *ret = m_bc->buildDirectory().toUserOutput();
return true;
}
*ret = Core::VariableManager::value(name.toUtf8());
@@ -93,13 +96,15 @@ BuildConfiguration::BuildConfiguration(Target *target, const Core::Id id) :
connect(target, SIGNAL(kitChanged()),
this, SLOT(handleKitUpdate()));
+ connect(this, SIGNAL(environmentChanged()), this, SLOT(emitBuildDirectoryChanged()));
}
BuildConfiguration::BuildConfiguration(Target *target, BuildConfiguration *source) :
ProjectConfiguration(target, source),
m_clearSystemEnvironment(source->m_clearSystemEnvironment),
m_userEnvironmentChanges(source->m_userEnvironmentChanges),
- m_macroExpander(0)
+ m_macroExpander(0),
+ m_buildDirectory(source->m_buildDirectory)
{
Q_ASSERT(target);
// Do not clone stepLists here, do that in the derived constructor instead
@@ -117,6 +122,23 @@ BuildConfiguration::~BuildConfiguration()
delete m_macroExpander;
}
+Utils::FileName BuildConfiguration::buildDirectory() const
+{
+ QString path = QDir::cleanPath(environment().expandVariables(m_buildDirectory.toString()));
+ return Utils::FileName::fromString(QDir::cleanPath(QDir(target()->project()->projectDirectory()).absoluteFilePath(path)));
+}
+
+Utils::FileName BuildConfiguration::rawBuildDirectory() const
+{
+ return m_buildDirectory;
+}
+
+void BuildConfiguration::setBuildDirectory(const Utils::FileName &dir)
+{
+ m_buildDirectory = dir;
+ emitBuildDirectoryChanged();
+}
+
QList<NamedWidget *> BuildConfiguration::createSubConfigWidgets()
{
return QList<NamedWidget *>() << new ProjectExplorer::BuildEnvironmentWidget(this);
@@ -150,6 +172,7 @@ QVariantMap BuildConfiguration::toMap() const
QVariantMap map(ProjectConfiguration::toMap());
map.insert(QLatin1String(CLEAR_SYSTEM_ENVIRONMENT_KEY), m_clearSystemEnvironment);
map.insert(QLatin1String(USER_ENVIRONMENT_CHANGES_KEY), Utils::EnvironmentItem::toStringList(m_userEnvironmentChanges));
+ map.insert(QLatin1String(BUILDDIRECTORY_KEY), m_buildDirectory.toString());
map.insert(QLatin1String(BUILD_STEP_LIST_COUNT), m_stepLists.count());
for (int i = 0; i < m_stepLists.count(); ++i)
@@ -162,6 +185,7 @@ 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_buildDirectory = Utils::FileName::fromString(map.value(QLatin1String(BUILDDIRECTORY_KEY)).toString());
emitEnvironmentChanged();
@@ -202,7 +226,7 @@ void BuildConfiguration::emitEnvironmentChanged()
if (env == m_cachedEnvironment)
return;
m_cachedEnvironment = env;
- emit environmentChanged();
+ emit environmentChanged(); // might trigger buildDirectoryChanged signal!
}
void BuildConfiguration::handleKitUpdate()
@@ -210,6 +234,14 @@ void BuildConfiguration::handleKitUpdate()
emitEnvironmentChanged();
}
+void BuildConfiguration::emitBuildDirectoryChanged()
+{
+ if (buildDirectory() != m_lastEmmitedBuildDirectory) {
+ m_lastEmmitedBuildDirectory = buildDirectory();
+ emit buildDirectoryChanged();
+ }
+}
+
Target *BuildConfiguration::target() const
{
return static_cast<Target *>(parent());
@@ -301,7 +333,7 @@ IBuildConfigurationFactory::~IBuildConfigurationFactory()
IBuildConfigurationFactory *IBuildConfigurationFactory::find(Target *parent, const QVariantMap &map)
{
QList<IBuildConfigurationFactory *> factories
- = ExtensionSystem::PluginManager::instance()->getObjects<IBuildConfigurationFactory>();
+ = ExtensionSystem::PluginManager::getObjects<IBuildConfigurationFactory>();
foreach (IBuildConfigurationFactory *factory, factories) {
if (factory->canRestore(parent, map))
return factory;
@@ -309,13 +341,25 @@ IBuildConfigurationFactory *IBuildConfigurationFactory::find(Target *parent, con
return 0;
}
+// setup
+IBuildConfigurationFactory *IBuildConfigurationFactory::find(Kit *k, const QString &projectPath)
+{
+ QList<IBuildConfigurationFactory *> factories
+ = ExtensionSystem::PluginManager::instance()->getObjects<IBuildConfigurationFactory>();
+ foreach (IBuildConfigurationFactory *factory, factories) {
+ if (factory->canSetup(k, projectPath))
+ return factory;
+ }
+ return 0;
+}
+
// create
IBuildConfigurationFactory * IBuildConfigurationFactory::find(Target *parent)
{
QList<IBuildConfigurationFactory *> factories
- = ExtensionSystem::PluginManager::instance()->getObjects<IBuildConfigurationFactory>();
+ = ExtensionSystem::PluginManager::getObjects<IBuildConfigurationFactory>();
foreach (IBuildConfigurationFactory *factory, factories) {
- if (!factory->availableCreationIds(parent).isEmpty())
+ if (factory->canCreate(parent))
return factory;
}
return 0;
@@ -325,7 +369,7 @@ IBuildConfigurationFactory * IBuildConfigurationFactory::find(Target *parent)
IBuildConfigurationFactory *IBuildConfigurationFactory::find(Target *parent, BuildConfiguration *bc)
{
QList<IBuildConfigurationFactory *> factories
- = ExtensionSystem::PluginManager::instance()->getObjects<IBuildConfigurationFactory>();
+ = ExtensionSystem::PluginManager::getObjects<IBuildConfigurationFactory>();
foreach (IBuildConfigurationFactory *factory, factories) {
if (factory->canClone(parent, bc))
return factory;
diff --git a/src/plugins/projectexplorer/buildconfiguration.h b/src/plugins/projectexplorer/buildconfiguration.h
index 975c23c04c..52bca21090 100644
--- a/src/plugins/projectexplorer/buildconfiguration.h
+++ b/src/plugins/projectexplorer/buildconfiguration.h
@@ -34,14 +34,14 @@
#include "projectconfiguration.h"
#include <utils/environment.h>
+#include <utils/fileutils.h>
-namespace Utils {
-class AbstractMacroExpander;
-}
+namespace Utils { class AbstractMacroExpander; }
namespace ProjectExplorer {
class BuildConfiguration;
+class BuildInfo;
class NamedWidget;
class BuildStepList;
class Kit;
@@ -56,7 +56,8 @@ public:
// ctors are protected
virtual ~BuildConfiguration();
- virtual QString buildDirectory() const = 0;
+ Utils::FileName buildDirectory() const;
+ Utils::FileName rawBuildDirectory() const;
virtual ProjectExplorer::NamedWidget *createConfigWidget() = 0;
virtual QList<NamedWidget *> createSubConfigWidgets();
@@ -99,10 +100,12 @@ protected:
BuildConfiguration(Target *target, const Core::Id id);
BuildConfiguration(Target *target, BuildConfiguration *source);
+ virtual void setBuildDirectory(const Utils::FileName &dir);
void cloneSteps(BuildConfiguration *source);
private slots:
void handleKitUpdate();
+ void emitBuildDirectoryChanged();
private:
void emitEnvironmentChanged();
@@ -111,6 +114,8 @@ private:
QList<Utils::EnvironmentItem> m_userEnvironmentChanges;
QList<BuildStepList *> m_stepLists;
Utils::AbstractMacroExpander *m_macroExpander;
+ Utils::FileName m_buildDirectory;
+ Utils::FileName m_lastEmmitedBuildDirectory;
mutable Utils::Environment m_cachedEnvironment;
};
@@ -123,13 +128,20 @@ public:
explicit IBuildConfigurationFactory(QObject *parent = 0);
virtual ~IBuildConfigurationFactory();
- // used to show the list of possible additons to a target, returns a list of types
- virtual QList<Core::Id> availableCreationIds(const Target *parent) const = 0;
- // used to translate the types to names to display to the user
- virtual QString displayNameForId(const Core::Id id) const = 0;
+ // Used to see whether any BuildInfo is available on this factory for a given target.
+ virtual bool canCreate(const Target *parent) const = 0;
+ // List of build information that can be used to create a new build configuration via
+ // "Add Build Configuration" button.
+ virtual QList<BuildInfo *> availableBuilds(const Target *parent) const = 0;
+
+ // Used to see whether this factory can produce any BuildConfigurations for a kit when
+ // setting up the given project.
+ virtual bool canSetup(const Kit *k, const QString &projectPath) const = 0;
+ // List of build information that can be used to initially set up a new build configuration.
+ virtual QList<BuildInfo *> availableSetups(const Kit *k, const QString &projectPath) const = 0;
+
+ virtual BuildConfiguration *create(Target *parent, const BuildInfo *info) const = 0;
- virtual bool canCreate(const Target *parent, const Core::Id id) const = 0;
- virtual BuildConfiguration *create(Target *parent, const Core::Id id, const QString &name = QString()) = 0;
// used to recreate the runConfigurations when restoring settings
virtual bool canRestore(const Target *parent, const QVariantMap &map) const = 0;
virtual BuildConfiguration *restore(Target *parent, const QVariantMap &map) = 0;
@@ -137,6 +149,7 @@ public:
virtual BuildConfiguration *clone(Target *parent, BuildConfiguration *product) = 0;
static IBuildConfigurationFactory *find(Target *parent, const QVariantMap &map);
+ static IBuildConfigurationFactory *find(Kit *k, const QString &projectPath);
static IBuildConfigurationFactory *find(Target *parent);
static IBuildConfigurationFactory *find(Target *parent, BuildConfiguration *bc);
diff --git a/src/plugins/projectexplorer/buildenvironmentwidget.h b/src/plugins/projectexplorer/buildenvironmentwidget.h
index 8c49c69d3a..3d34f48320 100644
--- a/src/plugins/projectexplorer/buildenvironmentwidget.h
+++ b/src/plugins/projectexplorer/buildenvironmentwidget.h
@@ -59,6 +59,6 @@ private:
BuildConfiguration *m_buildConfiguration;
};
-} // namespace Qt4ProjectManager
+} // namespace ProjectExplorer
#endif // BUILDENVIRONMENTWIDGET_H
diff --git a/src/plugins/projectexplorer/buildinfo.h b/src/plugins/projectexplorer/buildinfo.h
new file mode 100644
index 0000000000..43fe6bc52b
--- /dev/null
+++ b/src/plugins/projectexplorer/buildinfo.h
@@ -0,0 +1,74 @@
+/****************************************************************************
+**
+** 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 BUILDINFO_H
+#define BUILDINFO_H
+
+#include "projectexplorer_export.h"
+
+#include "task.h"
+
+#include <coreplugin/id.h>
+#include <utils/fileutils.h>
+
+namespace ProjectExplorer {
+
+class IBuildConfigurationFactory;
+
+class PROJECTEXPLORER_EXPORT BuildInfo
+{
+public:
+ BuildInfo(const IBuildConfigurationFactory *f) : supportsShadowBuild(false), m_factory(f) { }
+ virtual ~BuildInfo() { }
+
+ const IBuildConfigurationFactory *factory() const { return m_factory; }
+
+ QString displayName;
+ QString typeName;
+ Utils::FileName buildDirectory;
+ Core::Id kitId;
+ bool supportsShadowBuild;
+
+ virtual QList<Task> reportIssues(const QString &projectPath,
+ const QString &buildDir) const
+ {
+ Q_UNUSED(projectPath);
+ Q_UNUSED(buildDir);
+ return QList<Task>();
+ }
+
+private:
+ const IBuildConfigurationFactory *m_factory;
+
+ friend class IBuildConfigurationFactory;
+};
+
+} // namespace ProjectExplorer
+
+#endif // BUILDINFO_H
diff --git a/src/plugins/projectexplorer/buildmanager.cpp b/src/plugins/projectexplorer/buildmanager.cpp
index 32e7455d85..12492447aa 100644
--- a/src/plugins/projectexplorer/buildmanager.cpp
+++ b/src/plugins/projectexplorer/buildmanager.cpp
@@ -32,8 +32,8 @@
#include "buildprogress.h"
#include "buildsteplist.h"
#include "compileoutputwindow.h"
-#include "projectexplorer.h"
#include "project.h"
+#include "projectexplorer.h"
#include "projectexplorersettings.h"
#include "target.h"
#include "taskwindow.h"
@@ -57,13 +57,17 @@
#include <QApplication>
-static inline QString msgProgress(int progress, int total)
+using namespace Core;
+
+namespace ProjectExplorer {
+
+static QString msgProgress(int progress, int total)
{
- return ProjectExplorer::BuildManager::tr("Finished %1 of %n steps", 0, total).arg(progress);
+ return BuildManager::tr("Finished %1 of %n steps", 0, total).arg(progress);
}
-namespace ProjectExplorer {
-struct BuildManagerPrivate {
+struct BuildManagerPrivate
+{
BuildManagerPrivate();
Internal::CompileOutputWindow *m_outputWindow;
@@ -92,7 +96,7 @@ struct BuildManagerPrivate {
int m_maxProgress;
QFutureInterface<void> *m_progressFutureInterface;
QFutureWatcher<void> m_progressWatcher;
- QPointer<Core::FutureProgress> m_futureProgress;
+ QPointer<FutureProgress> m_futureProgress;
QElapsedTimer m_elapsed;
};
@@ -107,9 +111,15 @@ BuildManagerPrivate::BuildManagerPrivate() :
{
}
-BuildManager::BuildManager(ProjectExplorerPlugin *parent, QAction *cancelBuildAction)
- : QObject(parent), d(new BuildManagerPrivate)
+static BuildManagerPrivate *d = 0;
+static BuildManager *m_instance = 0;
+
+BuildManager::BuildManager(QObject *parent, QAction *cancelBuildAction)
+ : QObject(parent)
{
+ m_instance = this;
+ d = new BuildManagerPrivate;
+
connect(&d->m_watcher, SIGNAL(finished()),
this, SLOT(nextBuildQueue()));
@@ -120,14 +130,13 @@ BuildManager::BuildManager(ProjectExplorerPlugin *parent, QAction *cancelBuildAc
connect(&d->m_watcher, SIGNAL(progressRangeChanged(int,int)),
this, SLOT(progressChanged()));
- connect(parent->session(), SIGNAL(aboutToRemoveProject(ProjectExplorer::Project*)),
+ connect(SessionManager::instance(), SIGNAL(aboutToRemoveProject(ProjectExplorer::Project*)),
this, SLOT(aboutToRemoveProject(ProjectExplorer::Project*)));
d->m_outputWindow = new Internal::CompileOutputWindow(this, cancelBuildAction);
ExtensionSystem::PluginManager::addObject(d->m_outputWindow);
- d->m_taskHub = ProjectExplorerPlugin::instance()->taskHub();
- d->m_taskWindow = new Internal::TaskWindow(d->m_taskHub);
+ d->m_taskWindow = new Internal::TaskWindow;
ExtensionSystem::PluginManager::addObject(d->m_taskWindow);
qRegisterMetaType<ProjectExplorer::BuildStep::OutputFormat>();
@@ -145,17 +154,25 @@ BuildManager::BuildManager(ProjectExplorerPlugin *parent, QAction *cancelBuildAc
this, SLOT(finish()));
}
+QObject *BuildManager::instance()
+{
+ return m_instance;
+}
+
void BuildManager::extensionsInitialized()
{
- d->m_taskHub->addCategory(Core::Id(Constants::TASK_CATEGORY_COMPILE),
- tr("Compile", "Category for compiler issues listed under 'Issues'"));
- d->m_taskHub->addCategory(Core::Id(Constants::TASK_CATEGORY_BUILDSYSTEM),
- tr("Build System", "Category for build system issues listed under 'Issues'"));
+ TaskHub::addCategory(Constants::TASK_CATEGORY_COMPILE,
+ tr("Compile", "Category for compiler issues listed under 'Issues'"));
+ TaskHub::addCategory(Constants::TASK_CATEGORY_BUILDSYSTEM,
+ tr("Build System", "Category for build system issues listed under 'Issues'"));
+ TaskHub::addCategory(Constants::TASK_CATEGORY_DEPLOYMENT,
+ tr("Deployment", "Category for deployment issues listed under 'Issues'"));
}
BuildManager::~BuildManager()
{
cancel();
+ m_instance = 0;
ExtensionSystem::PluginManager::removeObject(d->m_taskWindow);
delete d->m_taskWindow;
@@ -165,7 +182,7 @@ BuildManager::~BuildManager()
delete d;
}
-void BuildManager::aboutToRemoveProject(ProjectExplorer::Project *p)
+void BuildManager::aboutToRemoveProject(Project *p)
{
QHash<Project *, int>::iterator it = d->m_activeBuildSteps.find(p);
QHash<Project *, int>::iterator end = d->m_activeBuildSteps.end();
@@ -177,17 +194,18 @@ void BuildManager::aboutToRemoveProject(ProjectExplorer::Project *p)
}
}
-bool BuildManager::isBuilding() const
+bool BuildManager::isBuilding()
{
// we are building even if we are not running yet
return !d->m_buildQueue.isEmpty() || d->m_running;
}
-int BuildManager::getErrorTaskCount() const
+int BuildManager::getErrorTaskCount()
{
const int errors =
- d->m_taskWindow->errorTaskCount(Core::Id(Constants::TASK_CATEGORY_BUILDSYSTEM))
- + d->m_taskWindow->errorTaskCount(Core::Id(Constants::TASK_CATEGORY_COMPILE));
+ d->m_taskWindow->errorTaskCount(Constants::TASK_CATEGORY_BUILDSYSTEM)
+ + d->m_taskWindow->errorTaskCount(Constants::TASK_CATEGORY_COMPILE)
+ + d->m_taskWindow->errorTaskCount(Constants::TASK_CATEGORY_DEPLOYMENT);
return errors;
}
@@ -205,13 +223,9 @@ void BuildManager::cancel()
void BuildManager::updateTaskCount()
{
- Core::ProgressManager *progressManager = Core::ICore::progressManager();
const int errors = getErrorTaskCount();
- if (errors > 0)
- progressManager->setApplicationLabel(QString::number(errors));
- else
- progressManager->setApplicationLabel(QString());
- emit tasksChanged();
+ ProgressManager::setApplicationLabel(errors > 0 ? QString::number(errors) : QString());
+ emit m_instance->tasksChanged();
}
void BuildManager::finish()
@@ -222,7 +236,7 @@ void BuildManager::finish()
time.remove(0, 2); // Don't display zero hours
addToOutputWindow(tr("Elapsed time: %1.") .arg(time), BuildStep::MessageOutput);
- QApplication::alert(Core::ICore::mainWindow(), 3000);
+ QApplication::alert(ICore::mainWindow(), 3000);
}
void BuildManager::emitCancelMessage()
@@ -252,56 +266,55 @@ void BuildManager::clearBuildQueue()
d->m_futureProgress = 0;
d->m_maxProgress = 0;
- emit buildQueueFinished(false);
+ emit m_instance->buildQueueFinished(false);
}
void BuildManager::toggleOutputWindow()
{
- d->m_outputWindow->toggle(Core::IOutputPane::ModeSwitch);
+ d->m_outputWindow->toggle(IOutputPane::ModeSwitch);
}
void BuildManager::showTaskWindow()
{
- d->m_taskWindow->popup(Core::IOutputPane::NoModeSwitch);
+ d->m_taskWindow->popup(IOutputPane::NoModeSwitch);
}
void BuildManager::toggleTaskWindow()
{
- d->m_taskWindow->toggle(Core::IOutputPane::ModeSwitch);
+ d->m_taskWindow->toggle(IOutputPane::ModeSwitch);
}
-bool BuildManager::tasksAvailable() const
+bool BuildManager::tasksAvailable()
{
const int count =
- d->m_taskWindow->taskCount(Core::Id(Constants::TASK_CATEGORY_BUILDSYSTEM))
- + d->m_taskWindow->taskCount(Core::Id(Constants::TASK_CATEGORY_COMPILE));
+ d->m_taskWindow->taskCount(Constants::TASK_CATEGORY_BUILDSYSTEM)
+ + d->m_taskWindow->taskCount(Constants::TASK_CATEGORY_COMPILE)
+ + d->m_taskWindow->taskCount(Constants::TASK_CATEGORY_DEPLOYMENT);
return count > 0;
}
void BuildManager::startBuildQueue(const QStringList &preambleMessage)
{
if (d->m_buildQueue.isEmpty()) {
- emit buildQueueFinished(true);
+ emit m_instance->buildQueueFinished(true);
return;
}
if (!d->m_running) {
d->m_elapsed.start();
// Progress Reporting
- Core::ProgressManager *progressManager = Core::ICore::progressManager();
d->m_progressFutureInterface = new QFutureInterface<void>;
d->m_progressWatcher.setFuture(d->m_progressFutureInterface->future());
- d->m_outputWindow->clearContents();
foreach (const QString &str, preambleMessage)
addToOutputWindow(str, BuildStep::MessageOutput, BuildStep::DontAppendNewline);
- 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 = progressManager->addTask(d->m_progressFutureInterface->future(),
- QString(),
- QLatin1String(Constants::TASK_BUILD),
- Core::ProgressManager::KeepOnFinish | Core::ProgressManager::ShowInApplicationIcon);
- connect(d->m_futureProgress.data(), SIGNAL(clicked()), this, SLOT(showBuildResults()));
+ TaskHub::clearTasks(Constants::TASK_CATEGORY_COMPILE);
+ TaskHub::clearTasks(Constants::TASK_CATEGORY_BUILDSYSTEM);
+ TaskHub::clearTasks(Constants::TASK_CATEGORY_DEPLOYMENT);
+ ProgressManager::setApplicationLabel(QString());
+ d->m_futureProgress = ProgressManager::addTask(d->m_progressFutureInterface->future(),
+ QString(), "ProjectExplorer.Task.Build",
+ ProgressManager::KeepOnFinish | ProgressManager::ShowInApplicationIcon);
+ connect(d->m_futureProgress.data(), SIGNAL(clicked()), m_instance, SLOT(showBuildResults()));
d->m_futureProgress.data()->setWidget(new Internal::BuildProgress(d->m_taskWindow));
d->m_futureProgress.data()->setStatusBarWidget(new Internal::BuildProgress(d->m_taskWindow,
Qt::Horizontal));
@@ -331,7 +344,7 @@ void BuildManager::addToTaskWindow(const ProjectExplorer::Task &task)
{
d->m_outputWindow->registerPositionOf(task);
// Distribute to all others
- d->m_taskHub->addTask(task);
+ TaskHub::addTask(task);
}
void BuildManager::addToOutputWindow(const QString &string, BuildStep::OutputFormat format,
@@ -351,16 +364,17 @@ void BuildManager::addToOutputWindow(const QString &string, BuildStep::OutputFor
void BuildManager::buildStepFinishedAsync()
{
disconnect(d->m_currentBuildStep, SIGNAL(finished()),
- this, SLOT(buildStepFinishedAsync()));
+ m_instance, SLOT(buildStepFinishedAsync()));
d->m_futureInterfaceForAysnc = QFutureInterface<bool>();
nextBuildQueue();
}
void BuildManager::nextBuildQueue()
{
+ d->m_outputWindow->flush();
if (d->m_canceling) {
d->m_canceling = false;
- QTimer::singleShot(0, this, SLOT(emitCancelMessage()));
+ QTimer::singleShot(0, m_instance, SLOT(emitCancelMessage()));
disconnectOutput(d->m_currentBuildStep);
decrementActiveBuildSteps(d->m_currentBuildStep);
@@ -442,7 +456,7 @@ void BuildManager::nextStep()
if (d->m_currentBuildStep->runInGuiThread()) {
connect (d->m_currentBuildStep, SIGNAL(finished()),
- this, SLOT(buildStepFinishedAsync()));
+ m_instance, SLOT(buildStepFinishedAsync()));
d->m_watcher.setFuture(d->m_futureInterfaceForAysnc.future());
d->m_currentBuildStep->run(d->m_futureInterfaceForAysnc);
} else {
@@ -457,21 +471,22 @@ void BuildManager::nextStep()
delete d->m_progressFutureInterface;
d->m_progressFutureInterface = 0;
d->m_maxProgress = 0;
- emit buildQueueFinished(true);
+ emit m_instance->buildQueueFinished(true);
}
}
bool BuildManager::buildQueueAppend(QList<BuildStep *> steps, QStringList names)
{
+ d->m_outputWindow->clearContents();
int count = steps.size();
bool init = true;
int i = 0;
for (; i < count; ++i) {
BuildStep *bs = steps.at(i);
connect(bs, SIGNAL(addTask(ProjectExplorer::Task)),
- this, SLOT(addToTaskWindow(ProjectExplorer::Task)));
+ m_instance, SLOT(addToTaskWindow(ProjectExplorer::Task)));
connect(bs, SIGNAL(addOutput(QString,ProjectExplorer::BuildStep::OutputFormat,ProjectExplorer::BuildStep::OutputNewlineSetting)),
- this, SLOT(addToOutputWindow(QString,ProjectExplorer::BuildStep::OutputFormat,ProjectExplorer::BuildStep::OutputNewlineSetting)));
+ m_instance, SLOT(addToOutputWindow(QString,ProjectExplorer::BuildStep::OutputFormat,ProjectExplorer::BuildStep::OutputNewlineSetting)));
if (bs->enabled()) {
init = bs->init();
if (!init)
@@ -526,12 +541,12 @@ bool BuildManager::buildLists(QList<BuildStepList *> bsls, const QStringList &st
bool success = buildQueueAppend(steps, names);
if (!success) {
- d->m_outputWindow->popup(Core::IOutputPane::NoModeSwitch);
+ d->m_outputWindow->popup(IOutputPane::NoModeSwitch);
return false;
}
- if (ProjectExplorerPlugin::instance()->projectExplorerSettings().showCompilerOutput)
- d->m_outputWindow->popup(Core::IOutputPane::NoModeSwitch);
+ if (ProjectExplorerPlugin::projectExplorerSettings().showCompilerOutput)
+ d->m_outputWindow->popup(IOutputPane::NoModeSwitch);
startBuildQueue(preambelMessage);
return true;
}
@@ -540,11 +555,11 @@ void BuildManager::appendStep(BuildStep *step, const QString &name)
{
bool success = buildQueueAppend(QList<BuildStep *>() << step, QStringList() << name);
if (!success) {
- d->m_outputWindow->popup(Core::IOutputPane::NoModeSwitch);
+ d->m_outputWindow->popup(IOutputPane::NoModeSwitch);
return;
}
- if (ProjectExplorerPlugin::instance()->projectExplorerSettings().showCompilerOutput)
- d->m_outputWindow->popup(Core::IOutputPane::NoModeSwitch);
+ if (ProjectExplorerPlugin::projectExplorerSettings().showCompilerOutput)
+ d->m_outputWindow->popup(IOutputPane::NoModeSwitch);
startBuildQueue();
}
@@ -614,7 +629,7 @@ void BuildManager::incrementActiveBuildSteps(BuildStep *bs)
increment<ProjectConfiguration>(d->m_activeBuildStepsPerProjectConfiguration, bs->projectConfiguration());
increment<Target>(d->m_activeBuildStepsPerTarget, bs->target());
if (increment<Project>(d->m_activeBuildSteps, bs->project()))
- emit buildStateChanged(bs->project());
+ emit m_instance->buildStateChanged(bs->project());
}
void BuildManager::decrementActiveBuildSteps(BuildStep *bs)
@@ -622,16 +637,16 @@ void BuildManager::decrementActiveBuildSteps(BuildStep *bs)
decrement<ProjectConfiguration>(d->m_activeBuildStepsPerProjectConfiguration, bs->projectConfiguration());
decrement<Target>(d->m_activeBuildStepsPerTarget, bs->target());
if (decrement<Project>(d->m_activeBuildSteps, bs->project()))
- emit buildStateChanged(bs->project());
+ emit m_instance->buildStateChanged(bs->project());
}
void BuildManager::disconnectOutput(BuildStep *bs)
{
disconnect(bs, SIGNAL(addTask(ProjectExplorer::Task)),
- this, SLOT(addToTaskWindow(ProjectExplorer::Task)));
+ m_instance, SLOT(addToTaskWindow(ProjectExplorer::Task)));
disconnect(bs, SIGNAL(addOutput(QString, ProjectExplorer::BuildStep::OutputFormat,
ProjectExplorer::BuildStep::OutputNewlineSetting)),
- this, SLOT(addToOutputWindow(QString, ProjectExplorer::BuildStep::OutputFormat,
+ m_instance, SLOT(addToOutputWindow(QString, ProjectExplorer::BuildStep::OutputFormat,
ProjectExplorer::BuildStep::OutputNewlineSetting)));
}
diff --git a/src/plugins/projectexplorer/buildmanager.h b/src/plugins/projectexplorer/buildmanager.h
index 804e32fc22..0e093b60ef 100644
--- a/src/plugins/projectexplorer/buildmanager.h
+++ b/src/plugins/projectexplorer/buildmanager.h
@@ -37,47 +37,45 @@
#include <QStringList>
namespace ProjectExplorer {
+
class Task;
-class ProjectExplorerPlugin;
class Project;
-struct BuildManagerPrivate;
-
class PROJECTEXPLORER_EXPORT BuildManager : public QObject
{
Q_OBJECT
public:
- explicit BuildManager(ProjectExplorerPlugin *parent, QAction *cancelBuildAction);
- virtual ~BuildManager();
+ explicit BuildManager(QObject *parent, QAction *cancelBuildAction);
+ ~BuildManager();
+ static QObject *instance();
- void extensionsInitialized();
+ static void extensionsInitialized();
- bool isBuilding() const;
+ static bool isBuilding();
+ static bool tasksAvailable();
- bool tasksAvailable() const;
-
- bool buildLists(QList<BuildStepList *> bsls, const QStringList &stepListNames,
+ static bool buildLists(QList<BuildStepList *> bsls, const QStringList &stepListNames,
const QStringList &preambelMessage = QStringList());
- bool buildList(BuildStepList *bsl, const QString &stepListName);
+ static bool buildList(BuildStepList *bsl, const QString &stepListName);
- bool isBuilding(Project *p);
- bool isBuilding(Target *t);
- bool isBuilding(ProjectConfiguration *p);
- bool isBuilding(BuildStep *step);
+ static bool isBuilding(Project *p);
+ static bool isBuilding(Target *t);
+ static bool isBuilding(ProjectConfiguration *p);
+ static bool isBuilding(BuildStep *step);
// Append any build step to the list of build steps (currently only used to add the QMakeStep)
- void appendStep(BuildStep *step, const QString &name);
+ static void appendStep(BuildStep *step, const QString &name);
- int getErrorTaskCount() const;
+ static int getErrorTaskCount();
public slots:
- void cancel();
+ static void cancel();
// Shows without focus
- void showTaskWindow();
- void toggleTaskWindow();
- void toggleOutputWindow();
- void aboutToRemoveProject(ProjectExplorer::Project *p);
+ static void showTaskWindow();
+ static void toggleTaskWindow();
+ static void toggleOutputWindow();
+ static void aboutToRemoveProject(ProjectExplorer::Project *p);
signals:
void buildStateChanged(ProjectExplorer::Project *pro);
@@ -87,30 +85,29 @@ signals:
void tasksCleared();
private slots:
- void addToTaskWindow(const ProjectExplorer::Task &task);
- void addToOutputWindow(const QString &string, ProjectExplorer::BuildStep::OutputFormat,
+ static void addToTaskWindow(const ProjectExplorer::Task &task);
+ static void addToOutputWindow(const QString &string, ProjectExplorer::BuildStep::OutputFormat,
ProjectExplorer::BuildStep::OutputNewlineSetting = BuildStep::DoAppendNewline);
- void buildStepFinishedAsync();
- void nextBuildQueue();
- void progressChanged();
- void progressTextChanged();
- void emitCancelMessage();
- void showBuildResults();
- void updateTaskCount();
- void finish();
+ static void buildStepFinishedAsync();
+ static void nextBuildQueue();
+ static void progressChanged();
+ static void progressTextChanged();
+ static void emitCancelMessage();
+ static void showBuildResults();
+ static void updateTaskCount();
+ static void finish();
private:
- void startBuildQueue(const QStringList &preambleMessage = QStringList());
- void nextStep();
- void clearBuildQueue();
- bool buildQueueAppend(QList<BuildStep *> steps, QStringList names);
- void incrementActiveBuildSteps(BuildStep *bs);
- void decrementActiveBuildSteps(BuildStep *bs);
- void disconnectOutput(BuildStep *bs);
-
- BuildManagerPrivate *d;
+ static void startBuildQueue(const QStringList &preambleMessage = QStringList());
+ static void nextStep();
+ static void clearBuildQueue();
+ static bool buildQueueAppend(QList<BuildStep *> steps, QStringList names);
+ static void incrementActiveBuildSteps(BuildStep *bs);
+ static void decrementActiveBuildSteps(BuildStep *bs);
+ static void disconnectOutput(BuildStep *bs);
};
+
} // namespace ProjectExplorer
#endif // BUILDMANAGER_H
diff --git a/src/plugins/projectexplorer/buildprogress.cpp b/src/plugins/projectexplorer/buildprogress.cpp
index 9a6a673a0f..a2845bfed4 100644
--- a/src/plugins/projectexplorer/buildprogress.cpp
+++ b/src/plugins/projectexplorer/buildprogress.cpp
@@ -97,14 +97,16 @@ void BuildProgress::updateState()
{
if (!m_taskWindow)
return;
- int errors = m_taskWindow->errorTaskCount(Core::Id(Constants::TASK_CATEGORY_BUILDSYSTEM))
- + m_taskWindow->errorTaskCount(Core::Id(Constants::TASK_CATEGORY_COMPILE));
+ int errors = m_taskWindow->errorTaskCount(Constants::TASK_CATEGORY_BUILDSYSTEM)
+ + m_taskWindow->errorTaskCount(Constants::TASK_CATEGORY_COMPILE)
+ + m_taskWindow->errorTaskCount(Constants::TASK_CATEGORY_DEPLOYMENT);
bool haveErrors = (errors > 0);
m_errorIcon->setEnabled(haveErrors);
m_errorLabel->setEnabled(haveErrors);
m_errorLabel->setText(QString::number(errors));
- int warnings = m_taskWindow->warningTaskCount(Core::Id(Constants::TASK_CATEGORY_BUILDSYSTEM))
- + m_taskWindow->warningTaskCount(Core::Id(Constants::TASK_CATEGORY_COMPILE));
+ int warnings = m_taskWindow->warningTaskCount(Constants::TASK_CATEGORY_BUILDSYSTEM)
+ + m_taskWindow->warningTaskCount(Constants::TASK_CATEGORY_COMPILE)
+ + m_taskWindow->warningTaskCount(Constants::TASK_CATEGORY_DEPLOYMENT);
bool haveWarnings = (warnings > 0);
m_warningIcon->setEnabled(haveWarnings);
m_warningLabel->setEnabled(haveWarnings);
diff --git a/src/plugins/projectexplorer/buildsettingspropertiespage.cpp b/src/plugins/projectexplorer/buildsettingspropertiespage.cpp
index 2469430da4..ced35e0b85 100644
--- a/src/plugins/projectexplorer/buildsettingspropertiespage.cpp
+++ b/src/plugins/projectexplorer/buildsettingspropertiespage.cpp
@@ -28,6 +28,7 @@
****************************************************************************/
#include "buildsettingspropertiespage.h"
+#include "buildinfo.h"
#include "buildstepspage.h"
#include "project.h"
#include "target.h"
@@ -35,6 +36,7 @@
#include "buildconfigurationmodel.h"
#include <utils/qtcassert.h>
+#include <coreplugin/icore.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/buildmanager.h>
@@ -96,7 +98,8 @@ PropertiesPanel *BuildSettingsPanelFactory::createPanel(Target *target)
BuildSettingsWidget::~BuildSettingsWidget()
{
- clear();
+ clearWidgets();
+ qDeleteAll(m_buildInfoList);
}
BuildSettingsWidget::BuildSettingsWidget(Target *target) :
@@ -192,7 +195,7 @@ void BuildSettingsWidget::addSubWidget(NamedWidget *widget)
m_subWidgets.append(widget);
}
-void BuildSettingsWidget::clear()
+void BuildSettingsWidget::clearWidgets()
{
qDeleteAll(m_subWidgets);
m_subWidgets.clear();
@@ -208,24 +211,28 @@ QList<NamedWidget *> BuildSettingsWidget::subWidgets() const
void BuildSettingsWidget::updateAddButtonMenu()
{
m_addButtonMenu->clear();
+ qDeleteAll(m_buildInfoList);
+ m_buildInfoList.clear();
+
if (m_target) {
if (m_target->activeBuildConfiguration()) {
m_addButtonMenu->addAction(tr("&Clone Selected"),
this, SLOT(cloneConfiguration()));
}
- IBuildConfigurationFactory * factory = IBuildConfigurationFactory::find(m_target);
+ IBuildConfigurationFactory *factory = IBuildConfigurationFactory::find(m_target);
if (!factory)
return;
- foreach (Core::Id id, factory->availableCreationIds(m_target)) {
- QAction *action = m_addButtonMenu->addAction(factory->displayNameForId(id), this, SLOT(createConfiguration()));
- action->setData(QVariant::fromValue(id));
+ m_buildInfoList = factory->availableBuilds(m_target);
+ foreach (BuildInfo *info, m_buildInfoList) {
+ QAction *action = m_addButtonMenu->addAction(info->typeName, this, SLOT(createConfiguration()));
+ action->setData(QVariant::fromValue(static_cast<void *>(info)));
}
}
}
void BuildSettingsWidget::updateBuildSettings()
{
- clear();
+ clearWidgets();
// update buttons
m_removeButton->setEnabled(m_target->buildConfigurations().size() > 1);
@@ -269,19 +276,24 @@ void BuildSettingsWidget::updateActiveConfiguration()
void BuildSettingsWidget::createConfiguration()
{
QAction *action = qobject_cast<QAction *>(sender());
- Core::Id id = action->data().value<Core::Id>();
-
- IBuildConfigurationFactory *factory = IBuildConfigurationFactory::find(m_target);
- if (!factory)
- return;
+ BuildInfo *info = static_cast<BuildInfo *>(action->data().value<void*>());
+
+ if (info->displayName.isEmpty()) {
+ bool ok = false;
+ info->displayName = QInputDialog::getText(Core::ICore::mainWindow(),
+ tr("New Configuration"),
+ tr("New configuration name:"),
+ QLineEdit::Normal,
+ QString(), &ok).trimmed();
+ if (!ok || info->displayName.isEmpty())
+ return;
+ }
- BuildConfiguration *bc = factory->create(m_target, id);
+ BuildConfiguration *bc = info->factory()->create(m_target, info);
if (!bc)
return;
m_target->addBuildConfiguration(bc);
-
- QTC_CHECK(bc->id() == id);
m_target->setActiveBuildConfiguration(bc);
}
@@ -357,8 +369,7 @@ void BuildSettingsWidget::deleteConfiguration(BuildConfiguration *deleteConfigur
m_target->buildConfigurations().size() <= 1)
return;
- ProjectExplorer::BuildManager *bm = ProjectExplorerPlugin::instance()->buildManager();
- if (bm->isBuilding(deleteConfiguration)) {
+ if (BuildManager::isBuilding(deleteConfiguration)) {
QMessageBox box;
QPushButton *closeAnyway = box.addButton(tr("Cancel Build && Remove Build Configuration"), QMessageBox::AcceptRole);
QPushButton *cancelClose = box.addButton(tr("Do Not Remove"), QMessageBox::RejectRole);
@@ -369,7 +380,7 @@ void BuildSettingsWidget::deleteConfiguration(BuildConfiguration *deleteConfigur
box.exec();
if (box.clickedButton() != closeAnyway)
return;
- bm->cancel();
+ BuildManager::cancel();
} else {
QMessageBox msgBox(QMessageBox::Question, tr("Remove Build Configuration?"),
tr("Do you really want to delete build configuration <b>%1</b>?").arg(deleteConfiguration->displayName()),
diff --git a/src/plugins/projectexplorer/buildsettingspropertiespage.h b/src/plugins/projectexplorer/buildsettingspropertiespage.h
index 42fd178bc3..67e84a67a7 100644
--- a/src/plugins/projectexplorer/buildsettingspropertiespage.h
+++ b/src/plugins/projectexplorer/buildsettingspropertiespage.h
@@ -44,6 +44,7 @@ QT_END_NAMESPACE
namespace ProjectExplorer {
class BuildConfiguration;
+class BuildInfo;
class IBuildStepFactory;
class NamedWidget;
@@ -71,7 +72,7 @@ public:
BuildSettingsWidget(Target *target);
~BuildSettingsWidget();
- void clear();
+ void clearWidgets();
void addSubWidget(ProjectExplorer::NamedWidget *widget);
QList<ProjectExplorer::NamedWidget *> subWidgets() const;
@@ -104,6 +105,7 @@ private:
QList<NamedWidget *> m_subWidgets;
QList<QLabel *> m_labels;
+ QList<BuildInfo *> m_buildInfoList;
};
} // namespace Internal
diff --git a/src/plugins/projectexplorer/buildstep.cpp b/src/plugins/projectexplorer/buildstep.cpp
index 25cd1115a9..22fe07b4e0 100644
--- a/src/plugins/projectexplorer/buildstep.cpp
+++ b/src/plugins/projectexplorer/buildstep.cpp
@@ -97,14 +97,13 @@
*/
/*!
- \fn void addOutput(const QString &string, ProjectExplorer::BuildStep::OutputFormat format,
- ProjectExplorer::BuildStep::OutputNewlineSetting newlineSetting)
+ \fn void ProjectExplorer::BuildStep::addOutput(const QString &string, ProjectExplorer::BuildStep::OutputFormat format,
+ ProjectExplorer::BuildStep::OutputNewlineSetting newlineSetting = DoAppendNewline) const
The \a string is added to the generated output, usually in the output pane.
It should be in plain text, with the format in the parameter.
*/
-
/*!
\fn void ProjectExplorer::BuildStep::finished()
This signal needs to be emitted if the build step runs in the GUI thread.
diff --git a/src/plugins/projectexplorer/buildsteplist.cpp b/src/plugins/projectexplorer/buildsteplist.cpp
index 44a9f312b9..07ada0e465 100644
--- a/src/plugins/projectexplorer/buildsteplist.cpp
+++ b/src/plugins/projectexplorer/buildsteplist.cpp
@@ -60,8 +60,8 @@ IBuildStepFactory *findRestoreFactory(BuildStepList *parent, const QVariantMap &
return 0;
}
-const char * const STEPS_COUNT_KEY("ProjectExplorer.BuildStepList.StepsCount");
-const char * const STEPS_PREFIX("ProjectExplorer.BuildStepList.Step.");
+const char STEPS_COUNT_KEY[] = "ProjectExplorer.BuildStepList.StepsCount";
+const char STEPS_PREFIX[] = "ProjectExplorer.BuildStepList.Step.";
} // namespace
@@ -184,10 +184,8 @@ void BuildStepList::insertStep(int position, BuildStep *step)
bool BuildStepList::removeStep(int position)
{
- ProjectExplorer::BuildManager *bm =
- ProjectExplorer::ProjectExplorerPlugin::instance()->buildManager();
BuildStep *bs = at(position);
- if (bm->isBuilding(bs))
+ if (BuildManager::isBuilding(bs))
return false;
emit aboutToRemoveStep(position);
diff --git a/src/plugins/projectexplorer/buildsteplist.h b/src/plugins/projectexplorer/buildsteplist.h
index 1f0151ed86..bf3d697ed4 100644
--- a/src/plugins/projectexplorer/buildsteplist.h
+++ b/src/plugins/projectexplorer/buildsteplist.h
@@ -58,6 +58,7 @@ public:
bool contains(const Core::Id id) const;
void insertStep(int position, BuildStep *step);
+ void appendStep(BuildStep *step) { insertStep(count(), step); }
bool removeStep(int position);
void moveStepUp(int position);
BuildStep *at(int position);
diff --git a/src/plugins/projectexplorer/cesdkhandler.cpp b/src/plugins/projectexplorer/cesdkhandler.cpp
index b6b245cfd3..261506ed76 100644
--- a/src/plugins/projectexplorer/cesdkhandler.cpp
+++ b/src/plugins/projectexplorer/cesdkhandler.cpp
@@ -79,9 +79,9 @@ bool CeSdkHandler::parse(const QString &vsdir)
xml.readNext();
if (xml.isStartElement()) {
currentElement = xml.name().toString();
- if (currentElement == QLatin1String("Platform"))
+ if (currentElement == QLatin1String("Platform")) {
currentItem = CeSdkInfo();
- else if (currentElement == QLatin1String("Directories")) {
+ } else if (currentElement == QLatin1String("Directories")) {
QXmlStreamAttributes attr = xml.attributes();
currentItem.m_include = fixPaths(attr.value(QLatin1String("Include")).toString());
currentItem.m_lib = fixPaths(attr.value(QLatin1String("Library")).toString());
diff --git a/src/plugins/projectexplorer/cesdkhandler.h b/src/plugins/projectexplorer/cesdkhandler.h
index dd0ac33201..f6056dcfa9 100644
--- a/src/plugins/projectexplorer/cesdkhandler.h
+++ b/src/plugins/projectexplorer/cesdkhandler.h
@@ -103,6 +103,6 @@ inline QString CeSdkHandler::fixPaths(QString path) const
return QDir::toNativeSeparators(path);
}
-} // namespace Qt4ProjectManager
+} // namespace ProjectExplorer
#endif // CE_SDK_HANDLER_H
diff --git a/src/plugins/projectexplorer/clangparser.cpp b/src/plugins/projectexplorer/clangparser.cpp
index cc55157358..51604d812c 100644
--- a/src/plugins/projectexplorer/clangparser.cpp
+++ b/src/plugins/projectexplorer/clangparser.cpp
@@ -63,7 +63,7 @@ void ClangParser::stdError(const QString &line)
m_commandRegExp.cap(4),
Utils::FileName(), /* filename */
-1, /* line */
- Core::Id(Constants::TASK_CATEGORY_COMPILE));
+ Constants::TASK_CATEGORY_COMPILE);
if (m_commandRegExp.cap(3) == QLatin1String("warning"))
task.type = Task::Warning;
else if (m_commandRegExp.cap(3) == QLatin1String("note"))
@@ -78,7 +78,7 @@ void ClangParser::stdError(const QString &line)
lne.trimmed(),
Utils::FileName::fromUserInput(m_inLineRegExp.cap(2)), /* filename */
m_inLineRegExp.cap(3).toInt(), /* line */
- Core::Id(Constants::TASK_CATEGORY_COMPILE)));
+ Constants::TASK_CATEGORY_COMPILE));
return;
}
@@ -127,7 +127,7 @@ void ProjectExplorerPlugin::testClangOutputParser_data()
QTest::addColumn<QList<ProjectExplorer::Task> >("tasks");
QTest::addColumn<QString>("outputLines");
- const Core::Id categoryCompile = Core::Id(Constants::TASK_CATEGORY_COMPILE);
+ const Core::Id categoryCompile = Constants::TASK_CATEGORY_COMPILE;
QTest::newRow("pass-through stdout")
<< QString::fromLatin1("Sometext") << OutputParserTester::STDOUT
diff --git a/src/plugins/projectexplorer/codestylesettingspropertiespage.cpp b/src/plugins/projectexplorer/codestylesettingspropertiespage.cpp
index 839feef5ac..8cb5ebe29c 100644
--- a/src/plugins/projectexplorer/codestylesettingspropertiespage.cpp
+++ b/src/plugins/projectexplorer/codestylesettingspropertiespage.cpp
@@ -75,7 +75,7 @@ CodeStyleSettingsWidget::CodeStyleSettingsWidget(Project *project) : QWidget(),
const EditorConfiguration *config = m_project->editorConfiguration();
QMap<Core::Id, ICodeStylePreferencesFactory *> factories
- = TextEditor::TextEditorSettings::instance()->codeStyleFactories();
+ = TextEditor::TextEditorSettings::codeStyleFactories();
QMapIterator<Core::Id, ICodeStylePreferencesFactory *> it(factories);
while (it.hasNext()) {
it.next();
diff --git a/src/plugins/projectexplorer/compileoutputwindow.cpp b/src/plugins/projectexplorer/compileoutputwindow.cpp
index cc3073b7f7..b2babe8a99 100644
--- a/src/plugins/projectexplorer/compileoutputwindow.cpp
+++ b/src/plugins/projectexplorer/compileoutputwindow.cpp
@@ -40,6 +40,7 @@
#include <extensionsystem/pluginmanager.h>
#include <texteditor/texteditorsettings.h>
#include <texteditor/fontsettings.h>
+#include <utils/ansiescapecodehandler.h>
#include <QIcon>
#include <QTextCharFormat>
@@ -81,7 +82,7 @@ public:
private slots:
void fontSettingsChanged()
{
- setFont(TextEditor::TextEditorSettings::instance()->fontSettings().font());
+ setFont(TextEditor::TextEditorSettings::fontSettings().font());
}
protected:
@@ -89,8 +90,7 @@ protected:
{
int line = cursorForPosition(ev->pos()).block().blockNumber();
if (unsigned taskid = m_taskids.value(line, 0)) {
- TaskHub *hub = ExtensionSystem::PluginManager::getObject<TaskHub>();
- hub->showTaskInEditor(taskid);
+ TaskHub::showTaskInEditor(taskid);
} else {
QPlainTextEdit::mouseDoubleClickEvent(ev);
}
@@ -104,7 +104,8 @@ private:
} // namespace ProjectExplorer
CompileOutputWindow::CompileOutputWindow(BuildManager * /*bm*/, QAction *cancelBuildAction) :
- m_cancelBuildButton(new QToolButton)
+ m_cancelBuildButton(new QToolButton),
+ m_escapeCodeHandler(new Utils::AnsiEscapeCodeHandler)
{
Core::Context context(Constants::C_COMPILE_OUTPUT);
m_outputWindow = new CompileOutputTextEdit(context);
@@ -143,11 +144,12 @@ CompileOutputWindow::~CompileOutputWindow()
ExtensionSystem::PluginManager::removeObject(m_handler);
delete m_handler;
delete m_cancelBuildButton;
+ delete m_escapeCodeHandler;
}
void CompileOutputWindow::updateWordWrapMode()
{
- m_outputWindow->setWordWrapEnabled(ProjectExplorerPlugin::instance()->projectExplorerSettings().wrapAppOutput);
+ m_outputWindow->setWordWrapEnabled(ProjectExplorerPlugin::projectExplorerSettings().wrapAppOutput);
}
bool CompileOutputWindow::hasFocus() const
@@ -204,7 +206,8 @@ void CompileOutputWindow::appendText(const QString &text, ProjectExplorer::Build
}
- m_outputWindow->appendText(text, textFormat);
+ foreach (const Utils::StringFormatPair &pair, m_escapeCodeHandler->parseText(text, textFormat))
+ m_outputWindow->appendText(pair.first, pair.second);
}
void CompileOutputWindow::clearContents()
@@ -272,4 +275,10 @@ void CompileOutputWindow::showPositionOf(const Task &task)
m_outputWindow->setTextCursor(newCursor);
}
+void CompileOutputWindow::flush()
+{
+ if (m_escapeCodeHandler)
+ m_escapeCodeHandler->endFormatScope();
+}
+
#include "compileoutputwindow.moc"
diff --git a/src/plugins/projectexplorer/compileoutputwindow.h b/src/plugins/projectexplorer/compileoutputwindow.h
index 920b80986c..5afd43fd05 100644
--- a/src/plugins/projectexplorer/compileoutputwindow.h
+++ b/src/plugins/projectexplorer/compileoutputwindow.h
@@ -41,6 +41,8 @@ class QTextCharFormat;
class QToolButton;
QT_END_NAMESPACE
+namespace Utils { class AnsiEscapeCodeHandler; }
+
namespace ProjectExplorer {
class BuildManager;
@@ -80,6 +82,8 @@ public:
bool knowsPositionOf(const Task &task);
void showPositionOf(const Task &task);
+ void flush();
+
private slots:
void updateWordWrapMode();
@@ -88,6 +92,7 @@ private:
QHash<unsigned int, int> m_taskPositions;
ShowOutputTaskHandler * m_handler;
QToolButton *m_cancelBuildButton;
+ Utils::AnsiEscapeCodeHandler *m_escapeCodeHandler;
};
} // namespace Internal
diff --git a/src/plugins/projectexplorer/currentprojectfilter.cpp b/src/plugins/projectexplorer/currentprojectfilter.cpp
index b86559ec94..2ffe109d7a 100644
--- a/src/plugins/projectexplorer/currentprojectfilter.cpp
+++ b/src/plugins/projectexplorer/currentprojectfilter.cpp
@@ -38,8 +38,8 @@ using namespace Locator;
using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;
-CurrentProjectFilter::CurrentProjectFilter(ProjectExplorerPlugin *pe)
- : BaseFileFilter(), m_projectExplorer(pe), m_project(0), m_filesUpToDate(false)
+CurrentProjectFilter::CurrentProjectFilter()
+ : BaseFileFilter(), m_project(0), m_filesUpToDate(false)
{
setId("Files in current project");
setDisplayName(tr("Files in Current Project"));
@@ -47,7 +47,7 @@ CurrentProjectFilter::CurrentProjectFilter(ProjectExplorerPlugin *pe)
setShortcutString(QString(QLatin1Char('p')));
setIncludedByDefault(false);
- connect(m_projectExplorer, SIGNAL(currentProjectChanged(ProjectExplorer::Project*)),
+ connect(ProjectExplorerPlugin::instance(), SIGNAL(currentProjectChanged(ProjectExplorer::Project*)),
this, SLOT(currentProjectChanged(ProjectExplorer::Project*)));
}
diff --git a/src/plugins/projectexplorer/currentprojectfilter.h b/src/plugins/projectexplorer/currentprojectfilter.h
index 3738750fdd..f47581e825 100644
--- a/src/plugins/projectexplorer/currentprojectfilter.h
+++ b/src/plugins/projectexplorer/currentprojectfilter.h
@@ -36,7 +36,6 @@
namespace ProjectExplorer {
-class ProjectExplorerPlugin;
class Project;
namespace Internal {
@@ -46,7 +45,7 @@ class CurrentProjectFilter : public Locator::BaseFileFilter
Q_OBJECT
public:
- CurrentProjectFilter(ProjectExplorerPlugin *pe);
+ CurrentProjectFilter();
void refresh(QFutureInterface<void> &future);
protected:
@@ -57,7 +56,6 @@ private slots:
void markFilesAsOutOfDate();
private:
- ProjectExplorerPlugin *m_projectExplorer;
Project *m_project;
bool m_filesUpToDate;
};
diff --git a/src/plugins/projectexplorer/currentprojectfind.cpp b/src/plugins/projectexplorer/currentprojectfind.cpp
index 193e41ec0e..1cd81c0794 100644
--- a/src/plugins/projectexplorer/currentprojectfind.cpp
+++ b/src/plugins/projectexplorer/currentprojectfind.cpp
@@ -33,7 +33,6 @@
#include "project.h"
#include "session.h"
-#include <coreplugin/idocument.h>
#include <utils/qtcassert.h>
#include <utils/filesearch.h>
@@ -45,15 +44,13 @@ using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;
using namespace TextEditor;
-CurrentProjectFind::CurrentProjectFind(ProjectExplorerPlugin *plugin)
- : AllProjectsFind(plugin),
- m_plugin(plugin)
+CurrentProjectFind::CurrentProjectFind()
{
- connect(m_plugin, SIGNAL(currentProjectChanged(ProjectExplorer::Project*)),
+ connect(ProjectExplorerPlugin::instance(), SIGNAL(currentProjectChanged(ProjectExplorer::Project*)),
this, SLOT(handleProjectChanged()));
- connect(m_plugin->session(), SIGNAL(projectRemoved(ProjectExplorer::Project*)),
+ connect(SessionManager::instance(), SIGNAL(projectRemoved(ProjectExplorer::Project*)),
this, SLOT(handleProjectChanged()));
- connect(m_plugin->session(), SIGNAL(projectAdded(ProjectExplorer::Project*)),
+ connect(SessionManager::instance(), SIGNAL(projectAdded(ProjectExplorer::Project*)),
this, SLOT(handleProjectChanged()));
}
@@ -76,7 +73,7 @@ QVariant CurrentProjectFind::additionalParameters() const
{
Project *project = ProjectExplorerPlugin::currentProject();
if (project && project->document())
- return qVariantFromValue(project->document()->fileName());
+ return qVariantFromValue(project->projectFilePath());
return QVariant();
}
@@ -84,10 +81,9 @@ Utils::FileIterator *CurrentProjectFind::files(const QStringList &nameFilters,
const QVariant &additionalParameters) const
{
QTC_ASSERT(additionalParameters.isValid(), return new Utils::FileIterator());
- QList<Project *> allProjects = m_plugin->session()->projects();
QString projectFile = additionalParameters.toString();
- foreach (Project *project, allProjects) {
- if (project->document() && projectFile == project->document()->fileName())
+ foreach (Project *project, SessionManager::projects()) {
+ if (project->document() && projectFile == project->projectFilePath())
return filesForProjects(nameFilters, QList<Project *>() << project);
}
return new Utils::FileIterator();
@@ -110,9 +106,8 @@ void CurrentProjectFind::recheckEnabled()
if (!search)
return;
QString projectFile = getAdditionalParameters(search).toString();
- QList<Project *> allProjects = m_plugin->session()->projects();
- foreach (Project *project, allProjects) {
- if (project->document() && projectFile == project->document()->fileName()) {
+ foreach (Project *project, SessionManager::projects()) {
+ if (projectFile == project->projectFilePath()) {
search->setSearchAgainEnabled(true);
return;
}
diff --git a/src/plugins/projectexplorer/currentprojectfind.h b/src/plugins/projectexplorer/currentprojectfind.h
index 28c006018b..a3e23f77c7 100644
--- a/src/plugins/projectexplorer/currentprojectfind.h
+++ b/src/plugins/projectexplorer/currentprojectfind.h
@@ -32,13 +32,8 @@
#include "allprojectsfind.h"
-QT_BEGIN_NAMESPACE
-class QWidget;
-QT_END_NAMESPACE
-
namespace ProjectExplorer {
-class ProjectExplorerPlugin;
class Project;
namespace Internal {
@@ -48,7 +43,7 @@ class CurrentProjectFind : public AllProjectsFind
Q_OBJECT
public:
- CurrentProjectFind(ProjectExplorerPlugin *plugin);
+ CurrentProjectFind();
QString id() const;
QString displayName() const;
@@ -67,9 +62,6 @@ protected:
private slots:
void handleProjectChanged();
void recheckEnabled();
-
-private:
- ProjectExplorerPlugin *m_plugin;
};
} // namespace Internal
diff --git a/src/plugins/projectexplorer/customparser.cpp b/src/plugins/projectexplorer/customparser.cpp
new file mode 100644
index 0000000000..4df78c2e5d
--- /dev/null
+++ b/src/plugins/projectexplorer/customparser.cpp
@@ -0,0 +1,287 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Andre Hartmann.
+** Contact: aha_1980@gmx.de
+**
+** 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 "customparser.h"
+#include "task.h"
+#include "projectexplorerconstants.h"
+
+#include <utils/qtcassert.h>
+
+#include <QString>
+
+using namespace ProjectExplorer;
+
+CustomParserSettings::CustomParserSettings() :
+ fileNameCap(1),
+ lineNumberCap(2),
+ messageCap(3)
+{ }
+
+bool CustomParserSettings::operator ==(const CustomParserSettings &other) const
+{
+ return errorPattern == other.errorPattern && fileNameCap == other.fileNameCap
+ && lineNumberCap == other.lineNumberCap && messageCap == other.messageCap;
+}
+
+CustomParser::CustomParser(const CustomParserSettings &settings) :
+ m_parserChannels(ParseBothChannels)
+{
+ setObjectName(QLatin1String("CustomParser"));
+
+ setSettings(settings);
+}
+
+CustomParser::~CustomParser()
+{
+}
+
+void CustomParser::setErrorPattern(const QString &errorPattern)
+{
+ m_errorRegExp.setPattern(errorPattern);
+ m_errorRegExp.setMinimal(true);
+ QTC_CHECK(m_errorRegExp.isValid());
+}
+
+QString CustomParser::errorPattern() const
+{
+ return m_errorRegExp.pattern();
+}
+
+int CustomParser::lineNumberCap() const
+{
+ return m_lineNumberCap;
+}
+
+void CustomParser::setLineNumberCap(int lineNumberCap)
+{
+ m_lineNumberCap = lineNumberCap;
+}
+
+int CustomParser::fileNameCap() const
+{
+ return m_fileNameCap;
+}
+
+void CustomParser::setFileNameCap(int fileNameCap)
+{
+ m_fileNameCap = fileNameCap;
+}
+
+int CustomParser::messageCap() const
+{
+ return m_messageCap;
+}
+
+void CustomParser::setMessageCap(int messageCap)
+{
+ m_messageCap = messageCap;
+}
+
+void CustomParser::stdError(const QString &line)
+{
+ if (m_parserChannels & ParseStdErrChannel)
+ if (parseLine(line))
+ return;
+
+ IOutputParser::stdError(line);
+}
+
+void CustomParser::stdOutput(const QString &line)
+{
+ if (m_parserChannels & ParseStdOutChannel)
+ if (parseLine(line))
+ return;
+
+ IOutputParser::stdOutput(line);
+}
+
+void CustomParser::setSettings(const CustomParserSettings &settings)
+{
+ setErrorPattern(settings.errorPattern);
+ setFileNameCap(settings.fileNameCap);
+ setLineNumberCap(settings.lineNumberCap);
+ setMessageCap(settings.messageCap);
+}
+
+bool CustomParser::parseLine(const QString &rawLine)
+{
+ if (m_errorRegExp.isEmpty())
+ return false;
+
+ if (m_errorRegExp.indexIn(rawLine.trimmed()) == -1)
+ return false;
+
+ const Utils::FileName fileName =
+ Utils::FileName::fromUserInput(m_errorRegExp.cap(m_fileNameCap));
+ const int lineNumber = m_errorRegExp.cap(m_lineNumberCap).toInt();
+ const QString message = m_errorRegExp.cap(m_messageCap);
+
+ emit addTask(Task(Task::Error, message, fileName, lineNumber, Constants::TASK_CATEGORY_COMPILE));
+ return true;
+}
+
+// Unit tests:
+
+#ifdef WITH_TESTS
+# include <QTest>
+
+# include "projectexplorer.h"
+# include "metatypedeclarations.h"
+# include "outputparser_test.h"
+
+using namespace Utils;
+
+void ProjectExplorerPlugin::testCustomOutputParsers_data()
+{
+ QTest::addColumn<QString>("input");
+ QTest::addColumn<OutputParserTester::Channel>("inputChannel");
+ QTest::addColumn<QString>("pattern");
+ QTest::addColumn<int>("fileNameCap");
+ QTest::addColumn<int>("lineNumberCap");
+ QTest::addColumn<int>("messageCap");
+ QTest::addColumn<QString>("childStdOutLines");
+ QTest::addColumn<QString>("childStdErrLines");
+ QTest::addColumn<QList<ProjectExplorer::Task> >("tasks");
+ QTest::addColumn<QString>("outputLines");
+
+ const Core::Id categoryCompile = Constants::TASK_CATEGORY_COMPILE;
+ const QString simplePattern = QLatin1String("^([a-z]+\\.[a-z]+):(\\d+): error: ([^\\s].+)$");
+ const Utils::FileName fileName = Utils::FileName::fromUserInput(QLatin1String("main.c"));
+
+ QTest::newRow("empty pattern")
+ << QString::fromLatin1("Sometext")
+ << OutputParserTester::STDOUT
+ << QString::fromLatin1("")
+ << 1 << 2 << 3
+ << QString::fromLatin1("Sometext\n") << QString()
+ << QList<ProjectExplorer::Task>()
+ << QString();
+
+ QTest::newRow("pass-through stdout")
+ << QString::fromLatin1("Sometext")
+ << OutputParserTester::STDOUT
+ << simplePattern
+ << 1 << 2 << 3
+ << QString::fromLatin1("Sometext\n") << QString()
+ << QList<ProjectExplorer::Task>()
+ << QString();
+
+ QTest::newRow("pass-through stderr")
+ << QString::fromLatin1("Sometext")
+ << OutputParserTester::STDERR
+ << simplePattern
+ << 1 << 2 << 3
+ << QString() << QString::fromLatin1("Sometext\n")
+ << QList<ProjectExplorer::Task>()
+ << QString();
+
+ const QString simpleError = QLatin1String("main.c:9: error: `sfasdf' undeclared (first use this function)");
+ const QString message = QLatin1String("`sfasdf' undeclared (first use this function)");
+
+ QTest::newRow("simple error")
+ << simpleError
+ << OutputParserTester::STDERR
+ << simplePattern
+ << 1 << 2 << 3
+ << QString() << QString()
+ << (QList<ProjectExplorer::Task>()
+ << Task(Task::Error, message, fileName, 9, categoryCompile)
+ )
+ << QString();
+
+ const QString simpleError2 = QLatin1String("Error: main.c:19: `sfasdf' undeclared (first use this function)");
+ const QString simplePattern2 = QLatin1String("^Error: ([a-z]+\\.[a-z]+):(\\d+): ([^\\s].+)$");
+ const int lineNumber2 = 19;
+
+ QTest::newRow("another simple error on stderr")
+ << simpleError2
+ << OutputParserTester::STDERR
+ << simplePattern2
+ << 1 << 2 << 3
+ << QString() << QString()
+ << (QList<ProjectExplorer::Task>()
+ << Task(Task::Error, message, fileName, lineNumber2, categoryCompile)
+ )
+ << QString();
+
+ QTest::newRow("another simple error on stdout")
+ << simpleError2
+ << OutputParserTester::STDOUT
+ << simplePattern2
+ << 1 << 2 << 3
+ << QString() << QString()
+ << (QList<ProjectExplorer::Task>()
+ << Task(Task::Error, message, fileName, lineNumber2, categoryCompile)
+ )
+ << QString();
+
+ const QString unitTestError = QLatin1String("../LedDriver/LedDriverTest.c:63: FAIL: Expected 0x0080 Was 0xffff");
+ const FileName unitTestFileName = FileName::fromUserInput(QLatin1String("../LedDriver/LedDriverTest.c"));
+ const QString unitTestMessage = QLatin1String("Expected 0x0080 Was 0xffff");
+ const QString unitTestPattern = QLatin1String("^([^:]+):(\\d+): FAIL: ([^\\s].+)$");
+ const int unitTestLineNumber = 63;
+
+ QTest::newRow("unit test error")
+ << unitTestError
+ << OutputParserTester::STDOUT
+ << unitTestPattern
+ << 1 << 2 << 3
+ << QString() << QString()
+ << (QList<ProjectExplorer::Task>()
+ << Task(Task::Error, unitTestMessage, unitTestFileName, unitTestLineNumber, categoryCompile)
+ )
+ << QString();
+}
+
+void ProjectExplorerPlugin::testCustomOutputParsers()
+{
+ QFETCH(QString, input);
+ QFETCH(OutputParserTester::Channel, inputChannel);
+ QFETCH(QString, pattern);
+ QFETCH(int, fileNameCap);
+ QFETCH(int, lineNumberCap);
+ QFETCH(int, messageCap);
+ QFETCH(QString, childStdOutLines);
+ QFETCH(QString, childStdErrLines);
+ QFETCH(QList<Task>, tasks);
+ QFETCH(QString, outputLines);
+
+ CustomParser *parser = new CustomParser;
+ parser->setErrorPattern(pattern);
+ parser->setFileNameCap(fileNameCap);
+ parser->setLineNumberCap(lineNumberCap);
+ parser->setMessageCap(messageCap);
+
+ OutputParserTester testbench;
+ testbench.appendOutputParser(parser);
+ testbench.testParsing(input, inputChannel,
+ tasks, childStdOutLines, childStdErrLines,
+ outputLines);
+}
+#endif
diff --git a/src/plugins/projectexplorer/customparser.h b/src/plugins/projectexplorer/customparser.h
new file mode 100644
index 0000000000..933826a023
--- /dev/null
+++ b/src/plugins/projectexplorer/customparser.h
@@ -0,0 +1,94 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Andre Hartmann.
+** Contact: aha_1980@gmx.de
+**
+** 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 CUSTOMPARSER_H
+#define CUSTOMPARSER_H
+
+#include "ioutputparser.h"
+
+#include <projectexplorer/task.h>
+
+#include <QRegExp>
+
+namespace ProjectExplorer {
+
+class CustomParserSettings
+{
+public:
+ CustomParserSettings();
+
+ bool operator ==(const CustomParserSettings &other) const;
+ bool operator !=(const CustomParserSettings &other) const { return !operator==(other); }
+
+ QString errorPattern;
+ int fileNameCap;
+ int lineNumberCap;
+ int messageCap;
+};
+
+class CustomParser : public ProjectExplorer::IOutputParser
+{
+public:
+ enum CustomParserChannels {
+ ParseNoChannel = 0,
+ ParseStdErrChannel = 1,
+ ParseStdOutChannel = 2,
+ ParseBothChannels = 3
+ };
+
+ CustomParser(const CustomParserSettings &settings = CustomParserSettings());
+ ~CustomParser();
+ void stdError(const QString &line);
+ void stdOutput(const QString &line);
+
+ void setSettings(const CustomParserSettings &settings);
+
+ void setErrorPattern(const QString &errorPattern);
+ QString errorPattern() const;
+ int fileNameCap() const;
+ void setFileNameCap(int fileNameCap);
+ int lineNumberCap() const;
+ void setLineNumberCap(int lineNumberCap);
+ int messageCap() const;
+ void setMessageCap(int messageCap);
+
+private:
+ bool parseLine(const QString &rawLine);
+
+ QRegExp m_errorRegExp;
+ int m_fileNameCap;
+ int m_lineNumberCap;
+ int m_messageCap;
+
+ CustomParserChannels m_parserChannels;
+};
+
+} // namespace ProjectExplorer
+
+#endif // CUSTOMPARSER_H
diff --git a/src/plugins/projectexplorer/customparserconfigdialog.cpp b/src/plugins/projectexplorer/customparserconfigdialog.cpp
new file mode 100644
index 0000000000..b45c745c8f
--- /dev/null
+++ b/src/plugins/projectexplorer/customparserconfigdialog.cpp
@@ -0,0 +1,173 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Andre Hartmann.
+** Contact: aha_1980@gmx.de
+**
+** 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 "customparserconfigdialog.h"
+#include "ui_customparserconfigdialog.h"
+
+#include <QPushButton>
+#include <QRegExp>
+
+namespace ProjectExplorer {
+namespace Internal {
+
+CustomParserConfigDialog::CustomParserConfigDialog(QDialog *parent) :
+ QDialog(parent),
+ ui(new Ui::CustomParserConfigDialog)
+{
+ ui->setupUi(this);
+
+ connect(ui->errorPattern, SIGNAL(textChanged(QString)), this, SLOT(changed()));
+ connect(ui->errorMessage, SIGNAL(textChanged(QString)), this, SLOT(changed()));
+ connect(ui->fileNameCap, SIGNAL(valueChanged(int)), this, SLOT(changed()));
+ connect(ui->lineNumberCap, SIGNAL(valueChanged(int)), this, SLOT(changed()));
+ connect(ui->messageCap, SIGNAL(valueChanged(int)), this, SLOT(changed()));
+
+ changed();
+ m_dirty = false;
+}
+
+CustomParserConfigDialog::~CustomParserConfigDialog()
+{
+ delete ui;
+}
+
+void CustomParserConfigDialog::setExampleSettings()
+{
+ setErrorPattern(QLatin1String("#error (.*):(\\d+): (.*)$"));
+ setFileNameCap(1);
+ setLineNumberCap(2);
+ setMessageCap(3);
+ ui->errorMessage->setText(QLatin1String("#error /home/user/src/test.c:891: Unknown identifier `test`"));
+}
+
+void CustomParserConfigDialog::setSettings(const ProjectExplorer::CustomParserSettings &settings)
+{
+ if (settings.errorPattern.isEmpty()) {
+ setExampleSettings();
+ return;
+ }
+
+ setErrorPattern(settings.errorPattern);
+ setFileNameCap(settings.fileNameCap);
+ setLineNumberCap(settings.lineNumberCap);
+ setMessageCap(settings.messageCap);
+}
+
+ProjectExplorer::CustomParserSettings CustomParserConfigDialog::settings() const
+{
+ ProjectExplorer::CustomParserSettings result;
+ result.errorPattern = errorPattern();
+ result.fileNameCap = fileNameCap();
+ result.lineNumberCap = lineNumberCap();
+ result.messageCap = messageCap();
+ return result;
+}
+
+void CustomParserConfigDialog::setErrorPattern(const QString &errorPattern)
+{
+ ui->errorPattern->setText(errorPattern);
+}
+
+QString CustomParserConfigDialog::errorPattern() const
+{
+ return ui->errorPattern->text();
+}
+
+void CustomParserConfigDialog::setFileNameCap(int fileNameCap)
+{
+ ui->fileNameCap->setValue(fileNameCap);
+}
+
+int CustomParserConfigDialog::fileNameCap() const
+{
+ return ui->fileNameCap->value();
+}
+
+void CustomParserConfigDialog::setLineNumberCap(int lineNumberCap)
+{
+ ui->lineNumberCap->setValue(lineNumberCap);
+}
+
+int CustomParserConfigDialog::lineNumberCap() const
+{
+ return ui->lineNumberCap->value();
+}
+
+void CustomParserConfigDialog::setMessageCap(int messageCap)
+{
+ ui->messageCap->setValue(messageCap);
+}
+
+int CustomParserConfigDialog::messageCap() const
+{
+ return ui->messageCap->value();
+}
+
+bool CustomParserConfigDialog::isDirty() const
+{
+ return m_dirty;
+}
+
+void CustomParserConfigDialog::changed()
+{
+ QRegExp rx;
+ rx.setPattern(ui->errorPattern->text());
+ rx.setMinimal(true);
+
+ QPalette palette;
+ palette.setColor(QPalette::Text, rx.isValid() ? Qt::black : Qt::red);
+ ui->errorPattern->setPalette(palette);
+ ui->errorPattern->setToolTip(rx.isValid() ? QString() : rx.errorString());
+
+ int pos = rx.indexIn(ui->errorMessage->text());
+ if (rx.isEmpty() || !rx.isValid() || pos < 0) {
+ QString error = QLatin1String("<font color=\"red\">") + tr("Not applicable: ");
+ if (rx.isEmpty())
+ error += tr("Pattern is empty.");
+ else if (!rx.isValid())
+ error += rx.errorString();
+ else
+ error += tr("Pattern does not match the error message.");
+
+ ui->fileNameTest->setText(error);
+ ui->lineNumberTest->setText(error);
+ ui->messageTest->setText(error);
+ ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
+ return;
+ }
+
+ ui->fileNameTest->setText(rx.cap(ui->fileNameCap->value()));
+ ui->lineNumberTest->setText(rx.cap(ui->lineNumberCap->value()));
+ ui->messageTest->setText(rx.cap(ui->messageCap->value()));
+ ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(true);
+ m_dirty = true;
+}
+
+} // namespace Internal
+} // namespace ProjectExplorer
diff --git a/src/plugins/projectexplorer/customparserconfigdialog.h b/src/plugins/projectexplorer/customparserconfigdialog.h
new file mode 100644
index 0000000000..1f0e43be83
--- /dev/null
+++ b/src/plugins/projectexplorer/customparserconfigdialog.h
@@ -0,0 +1,74 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Andre Hartmann.
+** Contact: aha_1980@gmx.de
+**
+** 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 CUSTOMPARSERCONFIGDIALOG_H
+#define CUSTOMPARSERCONFIGDIALOG_H
+
+#include "customparser.h"
+
+#include <QDialog>
+
+namespace ProjectExplorer {
+namespace Internal {
+
+namespace Ui { class CustomParserConfigDialog; }
+
+class CustomParserConfigDialog : public QDialog
+{
+ Q_OBJECT
+
+public:
+ explicit CustomParserConfigDialog(QDialog *parent = 0);
+ ~CustomParserConfigDialog();
+
+ void setExampleSettings();
+ void setSettings(const ProjectExplorer::CustomParserSettings &settings);
+ ProjectExplorer::CustomParserSettings settings() const;
+ void setErrorPattern(const QString &errorPattern);
+ QString errorPattern() const;
+ void setFileNameCap(int fileNameCap);
+ int fileNameCap() const;
+ void setLineNumberCap(int lineNumberCap);
+ int lineNumberCap() const;
+ void setMessageCap(int messageCap);
+ int messageCap() const;
+ bool isDirty() const;
+
+private slots:
+ void changed();
+
+private:
+ Ui::CustomParserConfigDialog *ui;
+ bool m_dirty;
+};
+
+} // namespace Internal
+} // namespace ProjectExplorer
+
+#endif // CUSTOMPARSERCONFIGDIALOG_H
diff --git a/src/plugins/projectexplorer/customparserconfigdialog.ui b/src/plugins/projectexplorer/customparserconfigdialog.ui
new file mode 100644
index 0000000000..86f8bde762
--- /dev/null
+++ b/src/plugins/projectexplorer/customparserconfigdialog.ui
@@ -0,0 +1,244 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>ProjectExplorer::Internal::CustomParserConfigDialog</class>
+ <widget class="QDialog" name="ProjectExplorer::Internal::CustomParserConfigDialog">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>470</width>
+ <height>368</height>
+ </rect>
+ </property>
+ <property name="windowTitle">
+ <string>Custom Parser</string>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout_3">
+ <item>
+ <layout class="QVBoxLayout" name="verticalLayout">
+ <item>
+ <widget class="QLabel" name="label_4">
+ <property name="text">
+ <string>&amp;Error message capture pattern:</string>
+ </property>
+ <property name="buddy">
+ <cstring>errorPattern</cstring>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLineEdit" name="errorPattern">
+ <property name="text">
+ <string>#error (.*):(\d+): (.*)$</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QGroupBox" name="capturePositionsGroup">
+ <property name="title">
+ <string>Capture Positions</string>
+ </property>
+ <layout class="QGridLayout" name="gridLayout">
+ <item row="0" column="0">
+ <widget class="QLabel" name="label">
+ <property name="text">
+ <string>&amp;File name:</string>
+ </property>
+ <property name="buddy">
+ <cstring>fileNameCap</cstring>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="1">
+ <widget class="QLabel" name="label_2">
+ <property name="text">
+ <string>&amp;Line number:</string>
+ </property>
+ <property name="buddy">
+ <cstring>lineNumberCap</cstring>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="2">
+ <widget class="QLabel" name="label_3">
+ <property name="text">
+ <string>&amp;Message:</string>
+ </property>
+ <property name="buddy">
+ <cstring>messageCap</cstring>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="0">
+ <widget class="QSpinBox" name="fileNameCap">
+ <property name="maximum">
+ <number>9</number>
+ </property>
+ <property name="value">
+ <number>1</number>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="1">
+ <widget class="QSpinBox" name="lineNumberCap">
+ <property name="maximum">
+ <number>9</number>
+ </property>
+ <property name="value">
+ <number>2</number>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="2">
+ <widget class="QSpinBox" name="messageCap">
+ <property name="maximum">
+ <number>9</number>
+ </property>
+ <property name="value">
+ <number>3</number>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item>
+ <widget class="QGroupBox" name="testGroup">
+ <property name="title">
+ <string>Test</string>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout_2">
+ <item>
+ <widget class="QLabel" name="label_5">
+ <property name="text">
+ <string>E&amp;rror message:</string>
+ </property>
+ <property name="buddy">
+ <cstring>errorMessage</cstring>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLineEdit" name="errorMessage">
+ <property name="text">
+ <string>#error /home/user/src/test.c:891: Unknown identifier `test`</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <layout class="QFormLayout" name="formLayout">
+ <item row="0" column="0">
+ <widget class="QLabel" name="label_6">
+ <property name="text">
+ <string>File name:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="1">
+ <widget class="QLabel" name="fileNameTest">
+ <property name="text">
+ <string>TextLabel</string>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="0">
+ <widget class="QLabel" name="label_7">
+ <property name="text">
+ <string>Line number:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="1">
+ <widget class="QLabel" name="lineNumberTest">
+ <property name="text">
+ <string>TextLabel</string>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="0">
+ <widget class="QLabel" name="label_8">
+ <property name="text">
+ <string>Message:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="1">
+ <widget class="QLabel" name="messageTest">
+ <property name="text">
+ <string>TextLabel</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>
+ </widget>
+ </item>
+ <item>
+ <widget class="QDialogButtonBox" name="buttonBox">
+ <property name="standardButtons">
+ <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ <tabstops>
+ <tabstop>errorPattern</tabstop>
+ <tabstop>fileNameCap</tabstop>
+ <tabstop>lineNumberCap</tabstop>
+ <tabstop>messageCap</tabstop>
+ <tabstop>errorMessage</tabstop>
+ <tabstop>buttonBox</tabstop>
+ </tabstops>
+ <resources/>
+ <connections>
+ <connection>
+ <sender>buttonBox</sender>
+ <signal>accepted()</signal>
+ <receiver>ProjectExplorer::Internal::CustomParserConfigDialog</receiver>
+ <slot>accept()</slot>
+ <hints>
+ <hint type="sourcelabel">
+ <x>320</x>
+ <y>341</y>
+ </hint>
+ <hint type="destinationlabel">
+ <x>386</x>
+ <y>289</y>
+ </hint>
+ </hints>
+ </connection>
+ <connection>
+ <sender>buttonBox</sender>
+ <signal>rejected()</signal>
+ <receiver>ProjectExplorer::Internal::CustomParserConfigDialog</receiver>
+ <slot>reject()</slot>
+ <hints>
+ <hint type="sourcelabel">
+ <x>277</x>
+ <y>350</y>
+ </hint>
+ <hint type="destinationlabel">
+ <x>421</x>
+ <y>255</y>
+ </hint>
+ </hints>
+ </connection>
+ </connections>
+</ui>
diff --git a/src/plugins/projectexplorer/customtoolchain.cpp b/src/plugins/projectexplorer/customtoolchain.cpp
index 4676578584..98b881d74a 100644
--- a/src/plugins/projectexplorer/customtoolchain.cpp
+++ b/src/plugins/projectexplorer/customtoolchain.cpp
@@ -30,16 +30,25 @@
#include "customtoolchain.h"
#include "abiwidget.h"
#include "gccparser.h"
+#include "clangparser.h"
+#include "linuxiccparser.h"
+#include "msvcparser.h"
+#include "customparser.h"
+#include "customparserconfigdialog.h"
#include "projectexplorerconstants.h"
#include "toolchainmanager.h"
#include <utils/detailswidget.h>
#include <utils/environment.h>
#include <utils/pathchooser.h>
+#include <utils/qtcassert.h>
#include <QFormLayout>
#include <QPlainTextEdit>
#include <QLineEdit>
+#include <QHBoxLayout>
+#include <QComboBox>
+#include <QPushButton>
using namespace Utils;
@@ -52,22 +61,27 @@ namespace ProjectExplorer {
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";
+static const char outputParserKeyC[] = "ProjectExplorer.CustomToolChain.OutputParser";
+static const char errorPatternKeyC[] = "ProjectExplorer.CustomToolChain.ErrorPattern";
+static const char lineNumberCapKeyC[] = "ProjectExplorer.CustomToolChain.LineNumberCap";
+static const char fileNameCapKeyC[] = "ProjectExplorer.CustomToolChain.FileNameCap";
+static const char messageCapKeyC[] = "ProjectExplorer.CustomToolChain.MessageCap";
// --------------------------------------------------------------------------
// CustomToolChain
// --------------------------------------------------------------------------
-CustomToolChain::CustomToolChain(bool autodetect) :
- ToolChain(QLatin1String(Constants::CUSTOM_TOOLCHAIN_ID), autodetect)
+CustomToolChain::CustomToolChain(Detection d) :
+ ToolChain(QLatin1String(Constants::CUSTOM_TOOLCHAIN_ID), d),
+ m_outputParser(Gcc)
{ }
-CustomToolChain::CustomToolChain(const QString &id, bool autodetect) :
- ToolChain(id, autodetect)
+CustomToolChain::CustomToolChain(const QString &id, Detection d) :
+ ToolChain(id, d)
{ }
CustomToolChain::CustomToolChain(const CustomToolChain &tc) :
@@ -188,10 +202,18 @@ QList<FileName> CustomToolChain::suggestedMkspecList() const
return m_mkspecs;
}
-// TODO: Customize
IOutputParser *CustomToolChain::outputParser() const
{
- return new GccParser;
+ switch (m_outputParser) {
+ case Gcc: return new GccParser;
+ case Clang: return new ClangParser;
+ case LinuxIcc: return new LinuxIccParser;
+#if defined(Q_OS_WIN)
+ case Msvc: return new MsvcParser;
+#endif
+ case Custom: return new CustomParser(m_customParserSettings);
+ default: return 0;
+ }
}
QStringList CustomToolChain::headerPathsList() const
@@ -279,6 +301,11 @@ QVariantMap CustomToolChain::toMap() const
data.insert(QLatin1String(headerPathsKeyC), headerPathsList());
data.insert(QLatin1String(cxx11FlagsKeyC), m_cxx11Flags);
data.insert(QLatin1String(mkspecsKeyC), mkspecs());
+ data.insert(QLatin1String(outputParserKeyC), m_outputParser);
+ data.insert(QLatin1String(errorPatternKeyC), m_customParserSettings.errorPattern);
+ data.insert(QLatin1String(fileNameCapKeyC), m_customParserSettings.fileNameCap);
+ data.insert(QLatin1String(lineNumberCapKeyC), m_customParserSettings.lineNumberCap);
+ data.insert(QLatin1String(messageCapKeyC), m_customParserSettings.messageCap);
return data;
}
@@ -295,6 +322,12 @@ bool CustomToolChain::fromMap(const QVariantMap &data)
setHeaderPaths(data.value(QLatin1String(headerPathsKeyC)).toStringList());
m_cxx11Flags = data.value(QLatin1String(cxx11FlagsKeyC)).toStringList();
setMkspecs(data.value(QLatin1String(mkspecsKeyC)).toString());
+ m_outputParser = (OutputParser)data.value(QLatin1String(outputParserKeyC)).toInt();
+ m_customParserSettings.errorPattern = data.value(QLatin1String(errorPatternKeyC)).toString();
+ m_customParserSettings.fileNameCap = data.value(QLatin1String(fileNameCapKeyC)).toInt();
+ m_customParserSettings.lineNumberCap = data.value(QLatin1String(lineNumberCapKeyC)).toInt();
+ m_customParserSettings.messageCap = data.value(QLatin1String(messageCapKeyC)).toInt();
+ QTC_ASSERT(m_outputParser >= Gcc && m_outputParser < OutputParserCount, return false);
return true;
}
@@ -312,6 +345,40 @@ bool CustomToolChain::operator ==(const ToolChain &other) const
&& m_systemHeaderPaths == customTc->m_systemHeaderPaths;
}
+CustomToolChain::OutputParser CustomToolChain::outputParserType() const
+{
+ return m_outputParser;
+}
+
+void CustomToolChain::setOutputParserType(CustomToolChain::OutputParser parser)
+{
+ m_outputParser = parser;
+}
+
+CustomParserSettings CustomToolChain::customParserSettings() const
+{
+ return m_customParserSettings;
+}
+
+void CustomToolChain::setCustomParserSettings(const CustomParserSettings &settings)
+{
+ m_customParserSettings = settings;
+}
+
+QString CustomToolChain::parserName(CustomToolChain::OutputParser parser)
+{
+ switch (parser) {
+ case Gcc: return tr("GCC");
+ case Clang: return tr("Clang");
+ case LinuxIcc: return tr("ICC");
+#if defined(Q_OS_WIN)
+ case Msvc: return tr("MSVC");
+#endif
+ case Custom: return tr("Custom");
+ default: return QString();
+ }
+}
+
ToolChainConfigWidget *CustomToolChain::configurationWidget()
{
return new Internal::CustomToolChainConfigWidget(this);
@@ -323,14 +390,10 @@ namespace Internal {
// CustomToolChainFactory
// --------------------------------------------------------------------------
-QString CustomToolChainFactory::displayName() const
-{
- return tr("Custom");
-}
-
-QString CustomToolChainFactory::id() const
+CustomToolChainFactory::CustomToolChainFactory()
{
- return QLatin1String(Constants::CUSTOM_TOOLCHAIN_ID);
+ setId(Constants::CUSTOM_TOOLCHAIN_ID);
+ setDisplayName(tr("Custom"));
}
bool CustomToolChainFactory::canCreate()
@@ -352,7 +415,7 @@ bool CustomToolChainFactory::canRestore(const QVariantMap &data)
ToolChain *CustomToolChainFactory::restore(const QVariantMap &data)
{
- CustomToolChain *tc = new CustomToolChain(false);
+ CustomToolChain *tc = new CustomToolChain(ToolChain::ManualDetection);
if (tc->fromMap(data))
return tc;
@@ -362,7 +425,7 @@ ToolChain *CustomToolChainFactory::restore(const QVariantMap &data)
CustomToolChain *CustomToolChainFactory::createToolChain(bool autoDetect)
{
- return new CustomToolChain(autoDetect);
+ return new CustomToolChain(autoDetect ? ToolChain::AutoDetection : ToolChain::ManualDetection);
}
// --------------------------------------------------------------------------
@@ -419,10 +482,18 @@ CustomToolChainConfigWidget::CustomToolChainConfigWidget(CustomToolChain *tc) :
m_predefinedDetails(new TextEditDetailsWidget(m_predefinedMacros)),
m_headerDetails(new TextEditDetailsWidget(m_headerPaths)),
m_cxx11Flags(new QLineEdit),
- m_mkspecs(new QLineEdit)
+ m_mkspecs(new QLineEdit),
+ m_errorParserComboBox(new QComboBox),
+ m_customParserSettingsButton(new QPushButton(tr("Custom Parser Settings...")))
{
Q_ASSERT(tc);
+ for (int i = 0; i < CustomToolChain::OutputParserCount; ++i)
+ m_errorParserComboBox->addItem(CustomToolChain::parserName((CustomToolChain::OutputParser)i));
+
+ QWidget *parserLayoutWidget = new QWidget;
+ QHBoxLayout *parserLayout = new QHBoxLayout(parserLayoutWidget);
+ parserLayout->setContentsMargins(0, 0, 0, 0);
m_predefinedMacros->setTabChangesFocus(true);
m_predefinedMacros->setToolTip(tr("Each line defines a macro. Format is MACRO[=VALUE]"));
m_headerPaths->setTabChangesFocus(true);
@@ -438,6 +509,9 @@ CustomToolChainConfigWidget::CustomToolChainConfigWidget(CustomToolChain *tc) :
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);
+ parserLayout->addWidget(m_errorParserComboBox);
+ parserLayout->addWidget(m_customParserSettingsButton);
+ m_mainLayout->addRow(tr("&Error parser:"), parserLayoutWidget);
addErrorLabel();
setFromToolchain();
@@ -451,6 +525,11 @@ CustomToolChainConfigWidget::CustomToolChainConfigWidget(CustomToolChain *tc) :
connect(m_headerPaths, SIGNAL(textChanged()), this, SLOT(updateSummaries()));
connect(m_cxx11Flags, SIGNAL(textChanged(QString)), this, SIGNAL(dirty()));
connect(m_mkspecs, SIGNAL(textChanged(QString)), this, SIGNAL(dirty()));
+ connect(m_errorParserComboBox, SIGNAL(currentIndexChanged(int)),
+ this, SLOT(errorParserChanged(int)));
+ connect(m_customParserSettingsButton, SIGNAL(clicked()),
+ this, SLOT(openCustomParserSettingsDialog()));
+ errorParserChanged(m_errorParserComboBox->currentIndex());
}
void CustomToolChainConfigWidget::updateSummaries()
@@ -462,6 +541,24 @@ void CustomToolChainConfigWidget::updateSummaries()
emit dirty();
}
+void CustomToolChainConfigWidget::errorParserChanged(int index)
+{
+ m_customParserSettingsButton->setEnabled(index == m_errorParserComboBox->count() - 1);
+ emit dirty();
+}
+
+void CustomToolChainConfigWidget::openCustomParserSettingsDialog()
+{
+ CustomParserConfigDialog dialog;
+ dialog.setSettings(m_customParserSettings);
+
+ if (dialog.exec() == QDialog::Accepted) {
+ m_customParserSettings = dialog.settings();
+ if (dialog.isDirty())
+ emit dirty();
+ }
+}
+
void CustomToolChainConfigWidget::applyImpl()
{
if (toolChain()->isAutoDetected())
@@ -478,6 +575,8 @@ void CustomToolChainConfigWidget::applyImpl()
tc->setCxx11Flags(m_cxx11Flags->text().split(QLatin1Char(',')));
tc->setMkspecs(m_mkspecs->text());
tc->setDisplayName(displayName); // reset display name
+ tc->setOutputParserType((CustomToolChain::OutputParser)m_errorParserComboBox->currentIndex());
+ tc->setCustomParserSettings(m_customParserSettings);
}
void CustomToolChainConfigWidget::setFromToolchain()
@@ -492,6 +591,8 @@ void CustomToolChainConfigWidget::setFromToolchain()
m_headerPaths->setPlainText(tc->headerPathsList().join(QLatin1String("\n")));
m_cxx11Flags->setText(tc->cxx11Flags().join(QLatin1String(",")));
m_mkspecs->setText(tc->mkspecs());
+ m_errorParserComboBox->setCurrentIndex(tc->outputParserType());
+ m_customParserSettings = tc->customParserSettings();
blockSignals(blocked);
}
@@ -505,7 +606,9 @@ bool CustomToolChainConfigWidget::isDirtyImpl() const
|| m_predefinedDetails->entries() != tc->rawPredefinedMacros()
|| m_headerDetails->entries() != tc->headerPathsList()
|| m_cxx11Flags->text().split(QLatin1Char(',')) != tc->cxx11Flags()
- || m_mkspecs->text() != tc->mkspecs();
+ || m_mkspecs->text() != tc->mkspecs()
+ || m_errorParserComboBox->currentIndex() == tc->outputParserType()
+ || m_customParserSettings != tc->customParserSettings();
}
void CustomToolChainConfigWidget::makeReadOnlyImpl()
diff --git a/src/plugins/projectexplorer/customtoolchain.h b/src/plugins/projectexplorer/customtoolchain.h
index 97489bd54f..a344f605a9 100644
--- a/src/plugins/projectexplorer/customtoolchain.h
+++ b/src/plugins/projectexplorer/customtoolchain.h
@@ -33,6 +33,7 @@
#include "projectexplorer_export.h"
#include "abi.h"
+#include "customparser.h"
#include "headerpath.h"
#include "toolchain.h"
#include "toolchainconfigwidget.h"
@@ -42,6 +43,8 @@
QT_BEGIN_NAMESPACE
class QPlainTextEdit;
class QTextEdit;
+class QComboBox;
+class QPushButton;
QT_END_NAMESPACE
namespace Utils { class PathChooser; }
@@ -57,7 +60,21 @@ namespace Internal { class CustomToolChainFactory; }
class PROJECTEXPLORER_EXPORT CustomToolChain : public ToolChain
{
+ Q_DECLARE_TR_FUNCTIONS(CustomToolChain)
+
public:
+ enum OutputParser
+ {
+ Gcc = 0,
+ Clang = 1,
+ LinuxIcc = 2,
+#if defined(Q_OS_WIN)
+ Msvc = 3,
+#endif
+ Custom,
+ OutputParserCount
+ };
+
QString type() const;
QString typeDisplayName() const;
Abi targetAbi() const;
@@ -98,12 +115,18 @@ public:
ToolChain *clone() const;
+ OutputParser outputParserType() const;
+ void setOutputParserType(OutputParser parser);
+ CustomParserSettings customParserSettings() const;
+ void setCustomParserSettings(const CustomParserSettings &settings);
+ static QString parserName(OutputParser parser);
+
protected:
- CustomToolChain(const QString &id, bool autodetect);
+ explicit CustomToolChain(const QString &id, Detection d);
CustomToolChain(const CustomToolChain &);
private:
- CustomToolChain(bool autodetect);
+ explicit CustomToolChain(Detection d);
Utils::FileName m_compilerCommand;
Utils::FileName m_makeCommand;
@@ -114,6 +137,9 @@ private:
QStringList m_cxx11Flags;
QList<Utils::FileName> m_mkspecs;
+ OutputParser m_outputParser;
+ CustomParserSettings m_customParserSettings;
+
friend class Internal::CustomToolChainFactory;
friend class ToolChainFactory;
};
@@ -125,9 +151,7 @@ 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;
+ CustomToolChainFactory();
bool canCreate();
ToolChain *create();
@@ -157,6 +181,8 @@ public:
private slots:
void updateSummaries();
+ void errorParserChanged(int index);
+ void openCustomParserSettingsDialog();
protected:
void applyImpl();
@@ -175,6 +201,10 @@ protected:
TextEditDetailsWidget *m_headerDetails;
QLineEdit *m_cxx11Flags;
QLineEdit *m_mkspecs;
+ QComboBox *m_errorParserComboBox;
+ QPushButton *m_customParserSettingsButton;
+
+ CustomParserSettings m_customParserSettings;
};
} // namespace Internal
diff --git a/src/plugins/projectexplorer/customwizard/customwizard.cpp b/src/plugins/projectexplorer/customwizard/customwizard.cpp
index 180d273646..e8c720f9e6 100644
--- a/src/plugins/projectexplorer/customwizard/customwizard.cpp
+++ b/src/plugins/projectexplorer/customwizard/customwizard.cpp
@@ -30,9 +30,9 @@
#include "customwizard.h"
#include "customwizardparameters.h"
#include "customwizardpage.h"
-#include "projectexplorer.h"
-#include "baseprojectwizarddialog.h"
#include "customwizardscriptgenerator.h"
+#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/baseprojectwizarddialog.h>
#include <coreplugin/icore.h>
#include <coreplugin/messagemanager.h>
@@ -88,10 +88,8 @@ int CustomWizardPrivate::verbose = 0;
of type "class" or "file". Serves as base class for project wizards.
*/
-CustomWizard::CustomWizard(const Core::BaseFileWizardParameters& baseFileParameters,
- QObject *parent) :
- Core::BaseFileWizard(baseFileParameters, parent),
- d(new CustomWizardPrivate)
+CustomWizard::CustomWizard()
+ : d(new CustomWizardPrivate)
{
}
@@ -249,11 +247,6 @@ Core::GeneratedFiles CustomWizard::generateFiles(const QWizard *dialog, QString
return generateWizardFiles(errorMessage);
}
-Core::FeatureSet CustomWizard::requiredFeatures() const
-{
- return baseFileWizardParameters().requiredFeatures();
-}
-
bool CustomWizard::writeFiles(const Core::GeneratedFiles &files, QString *errorMessage)
{
if (!Core::BaseFileWizard::writeFiles(files, errorMessage))
@@ -346,30 +339,31 @@ void CustomWizard::registerFactory(const QString &name, const ICustomWizardFacto
customWizardFactoryMap()->insert(name, f);
}
-CustomWizard *CustomWizard::createWizard(const CustomWizardParametersPtr &p, const Core::BaseFileWizardParameters &b)
+CustomWizard *CustomWizard::createWizard(const CustomProjectWizard::CustomWizardParametersPtr &p, const Core::IWizard::Data &b)
{
CustomWizard * rc = 0;
if (p->klass.isEmpty()) {
// Use defaults for empty class names
- switch (b.kind()) {
+ switch (b.kind) {
case Core::IWizard::ProjectWizard:
- rc = new CustomProjectWizard(b);
+ rc = new CustomProjectWizard;
break;
case Core::IWizard::FileWizard:
case Core::IWizard::ClassWizard:
- rc = new CustomWizard(b);
+ rc = new CustomWizard;
break;
}
} else {
// Look up class name in map
const CustomWizardFactoryMap::const_iterator it = customWizardFactoryMap()->constFind(p->klass);
if (it != customWizardFactoryMap()->constEnd())
- rc = it.value()->create(b);
+ rc = it.value()->create();
}
if (!rc) {
qWarning("Unable to create custom wizard for class %s.", qPrintable(p->klass));
return 0;
}
+ rc->setData(b);
rc->setParameters(p);
return rc;
}
@@ -450,26 +444,27 @@ QList<CustomWizard*> CustomWizard::createWizards()
const QString configFile = QLatin1String(configFileC);
// Check and parse config file in each directory.
- foreach (const QFileInfo &dirFi, dirs) {
+ while (!dirs.isEmpty()) {
+ const QFileInfo dirFi = dirs.takeFirst();
const QDir dir(dirFi.absoluteFilePath());
if (CustomWizardPrivate::verbose)
verboseLog += QString::fromLatin1("CustomWizard: Scanning %1\n").arg(dirFi.absoluteFilePath());
if (dir.exists(configFile)) {
CustomWizardParametersPtr parameters(new Internal::CustomWizardParameters);
- Core::BaseFileWizardParameters baseFileParameters;
- switch (parameters->parse(dir.absoluteFilePath(configFile), &baseFileParameters, &errorMessage)) {
+ IWizard::Data data;
+ switch (parameters->parse(dir.absoluteFilePath(configFile), &data, &errorMessage)) {
case Internal::CustomWizardParameters::ParseOk:
parameters->directory = dir.absolutePath();
if (CustomWizardPrivate::verbose)
QTextStream(&verboseLog)
- << "\n### Adding: " << baseFileParameters.id() << " / " << baseFileParameters.displayName() << '\n'
- << baseFileParameters.category() << " / " <<baseFileParameters.displayCategory() << '\n'
- << " (" << baseFileParameters.description() << ")\n"
+ << "\n### Adding: " << data.id << " / " << data.displayName << '\n'
+ << data.category << " / " << data.displayCategory << '\n'
+ << " (" << data.description << ")\n"
<< parameters->toString();
- if (CustomWizard *w = createWizard(parameters, baseFileParameters))
+ if (CustomWizard *w = createWizard(parameters, data))
rc.push_back(w);
else
- qWarning("Custom wizard factory function failed for %s", qPrintable(baseFileParameters.id()));
+ qWarning("Custom wizard factory function failed for %s", qPrintable(data.id));
break;
case Internal::CustomWizardParameters::ParseDisabled:
if (CustomWizardPrivate::verbose)
@@ -481,15 +476,20 @@ QList<CustomWizard*> CustomWizard::createWizards()
break;
}
} else {
- if (CustomWizardPrivate::verbose)
- if (CustomWizardPrivate::verbose)
- verboseLog += QString::fromLatin1("CustomWizard: '%1' not found\n").arg(configFile);
+ QList<QFileInfo> subDirs = dir.entryInfoList(filters, sortflags);
+ if (!subDirs.isEmpty()) {
+ // There is no QList::prepend(QList)...
+ dirs.swap(subDirs);
+ dirs.append(subDirs);
+ } else if (CustomWizardPrivate::verbose) {
+ verboseLog += QString::fromLatin1("CustomWizard: '%1' not found\n").arg(configFile);
+ }
}
}
if (CustomWizardPrivate::verbose) { // Print to output pane for Windows.
verboseLog += listWizards();
qWarning("%s", qPrintable(verboseLog));
- Core::ICore::messageManager()->printToOutputPane(verboseLog, Core::MessageManager::ModeSwitch);
+ Core::MessageManager::write(verboseLog, Core::MessageManager::ModeSwitch);
}
return rc;
}
@@ -506,9 +506,7 @@ QList<CustomWizard*> CustomWizard::createWizards()
for QLineEdit-type fields' default text.
*/
-CustomProjectWizard::CustomProjectWizard(const Core::BaseFileWizardParameters& baseFileParameters,
- QObject *parent) :
- CustomWizard(baseFileParameters, parent)
+CustomProjectWizard::CustomProjectWizard()
{
}
diff --git a/src/plugins/projectexplorer/customwizard/customwizard.h b/src/plugins/projectexplorer/customwizard/customwizard.h
index 17bb7db316..5aca2a6d39 100644
--- a/src/plugins/projectexplorer/customwizard/customwizard.h
+++ b/src/plugins/projectexplorer/customwizard/customwizard.h
@@ -57,30 +57,29 @@ namespace Internal {
}
// Documentation inside.
-class ICustomWizardFactory {
+class ICustomWizardFactory
+{
public:
- virtual CustomWizard *create(const Core::BaseFileWizardParameters& baseFileParameters,
- QObject *parent = 0) const = 0;
+ virtual CustomWizard *create(QObject *parent = 0) const = 0;
virtual ~ICustomWizardFactory() {}
};
// Convenience template to create wizard factory classes.
-template <class Wizard> class CustomWizardFactory : public ICustomWizardFactory {
- virtual CustomWizard *create(const Core::BaseFileWizardParameters& baseFileParameters,
- QObject *parent = 0) const
- { return new Wizard(baseFileParameters, parent); }
+template <class Wizard> class CustomWizardFactory : public ICustomWizardFactory
+{
+ CustomWizard *create(QObject * = 0) const { return new Wizard; }
};
// Documentation inside.
class PROJECTEXPLORER_EXPORT CustomWizard : public Core::BaseFileWizard
{
Q_OBJECT
+
public:
typedef QMap<QString, QString> FieldReplacementMap;
typedef QSharedPointer<ICustomWizardFactory> ICustomWizardFactoryPtr;
- explicit CustomWizard(const Core::BaseFileWizardParameters& baseFileParameters,
- QObject *parent = 0);
+ CustomWizard();
virtual ~CustomWizard();
// Can be reimplemented to create custom wizards. initWizardDialog() needs to be
@@ -90,9 +89,6 @@ public:
virtual Core::GeneratedFiles generateFiles(const QWizard *w, QString *errorMessage) const;
- virtual Core::FeatureSet requiredFeatures() const;
-
-
// Register a factory for a derived custom widget
static void registerFactory(const QString &name, const ICustomWizardFactoryPtr &f);
template <class Wizard> static void registerFactory(const QString &name)
@@ -121,11 +117,12 @@ protected:
CustomWizardParametersPtr parameters() const;
CustomWizardContextPtr context() const;
+ static CustomWizard *createWizard(const CustomWizardParametersPtr &p, const Core::IWizard::Data &b);
+
private:
void setParameters(const CustomWizardParametersPtr &p);
- static CustomWizard *createWizard(const CustomWizardParametersPtr &p,
- const Core::BaseFileWizardParameters &b);
+ static CustomWizard *createWizard(const CustomWizardParametersPtr &p);
CustomWizardPrivate *d;
};
@@ -133,16 +130,17 @@ private:
class PROJECTEXPLORER_EXPORT CustomProjectWizard : public CustomWizard
{
Q_OBJECT
+
public:
- explicit CustomProjectWizard(const Core::BaseFileWizardParameters& baseFileParameters,
- QObject *parent = 0);
+ CustomProjectWizard();
- virtual QWizard *createWizardDialog(QWidget *parent,
- const Core::WizardDialogParameters &wizardDialogParameters) const;
+ static bool postGenerateOpen(const Core::GeneratedFiles &l, QString *errorMessage = 0);
- virtual Core::GeneratedFiles generateFiles(const QWizard *w, QString *errorMessage) const;
+protected:
+ QWizard *createWizardDialog(QWidget *parent,
+ const Core::WizardDialogParameters &wizardDialogParameters) const;
- static bool postGenerateOpen(const Core::GeneratedFiles &l, QString *errorMessage = 0);
+ Core::GeneratedFiles generateFiles(const QWizard *w, QString *errorMessage) const;
signals:
void projectLocationChanged(const QString &path);
diff --git a/src/plugins/projectexplorer/customwizard/customwizard.pri b/src/plugins/projectexplorer/customwizard/customwizard.pri
index 6b0066cbc6..fa3cf931e2 100644
--- a/src/plugins/projectexplorer/customwizard/customwizard.pri
+++ b/src/plugins/projectexplorer/customwizard/customwizard.pri
@@ -1,4 +1,3 @@
-INCLUDEPATH *= $$PWD
HEADERS += $$PWD/customwizard.h \
$$PWD/customwizardparameters.h \
$$PWD/customwizardpage.h \
diff --git a/src/plugins/projectexplorer/customwizard/customwizardparameters.cpp b/src/plugins/projectexplorer/customwizard/customwizardparameters.cpp
index fdd3b19216..8cb99a3d93 100644
--- a/src/plugins/projectexplorer/customwizard/customwizardparameters.cpp
+++ b/src/plugins/projectexplorer/customwizard/customwizardparameters.cpp
@@ -88,7 +88,6 @@ static const char fieldMandatoryAttributeC[] = "mandatory";
static const char fieldControlElementC[] = "fieldcontrol";
static const char filesElementC[] = "files";
-static const char filesGeneratorScriptAttributeC[] = "generatorscript";
static const char fileElementC[] = "file";
static const char fileSourceAttributeC[] = "source";
static const char fileTargetAttributeC[] = "target";
@@ -268,36 +267,12 @@ static inline bool assignLanguageElementText(QXmlStreamReader &reader,
return false;
}
-// Copy&paste from above to call a setter of BaseFileParameters.
-// Implementation of a sophisticated mem_fun pattern is left
-// as an exercise to the reader.
-static inline bool assignLanguageElementText(QXmlStreamReader &reader,
- const QString &desiredLanguage,
- BaseFileWizardParameters *bp,
- void (BaseFileWizardParameters::*setter)(const QString &))
-{
- const QStringRef elementLanguage = reader.attributes().value(QLatin1String(langAttributeC));
- if (elementLanguage.isEmpty()) {
- // Try to find a translation for our built-in Wizards
- const QString translated = QCoreApplication::translate("ProjectExplorer::CustomWizard", reader.readElementText().toLatin1().constData());
- (bp->*setter)(translated);
- return true;
- }
- if (elementLanguage == desiredLanguage) {
- (bp->*setter)(reader.readElementText());
- return true;
- }
- // Language mismatch: forward to end element.
- skipOverElementText(reader);
- return false;
-}
-
// Read level sub-elements of "wizard"
static bool parseCustomProjectElement(QXmlStreamReader &reader,
const QString &configFileFullPath,
const QString &language,
CustomWizardParameters *p,
- BaseFileWizardParameters *bp)
+ IWizard::Data *bp)
{
const QStringRef elementName = reader.name();
if (elementName == QLatin1String(iconElementC)) {
@@ -307,23 +282,20 @@ static bool parseCustomProjectElement(QXmlStreamReader &reader,
qWarning("Invalid icon path '%s' encountered in custom project template %s.",
qPrintable(path), qPrintable(configFileFullPath));
} else {
- bp->setIcon(icon);
+ bp->icon = icon;
}
return true;
}
if (elementName == QLatin1String(descriptionElementC)) {
- assignLanguageElementText(reader, language, bp,
- &BaseFileWizardParameters::setDescription);
+ assignLanguageElementText(reader, language, &bp->description);
return true;
}
if (elementName == QLatin1String(displayNameElementC)) {
- assignLanguageElementText(reader, language, bp,
- &BaseFileWizardParameters::setDisplayName);
+ assignLanguageElementText(reader, language, &bp->displayName);
return true;
}
if (elementName == QLatin1String(displayCategoryElementC)) {
- assignLanguageElementText(reader, language, bp,
- &BaseFileWizardParameters::setDisplayCategory);
+ assignLanguageElementText(reader, language, &bp->displayCategory);
return true;
}
if (elementName == QLatin1String(fieldPageTitleElementC)) {
@@ -503,7 +475,7 @@ static inline FeatureSet requiredFeatures(const QXmlStreamReader &reader)
static inline IWizard::WizardFlags wizardFlags(const QXmlStreamReader &reader)
{
IWizard::WizardFlags flags;
- QString value = reader.attributes().value(QLatin1String(platformIndependentC)).toString();
+ const QStringRef value = reader.attributes().value(QLatin1String(platformIndependentC));
if (!value.isEmpty() && value == QLatin1String("true"))
flags |= IWizard::PlatformIndependent;
@@ -530,14 +502,14 @@ static inline bool booleanAttributeValue(const QXmlStreamReader &r, const char *
static inline int integerAttributeValue(const QXmlStreamReader &r, const char *name, int defaultValue)
{
- const QString sValue = r.attributes().value(QLatin1String(name)).toString();
+ const QStringRef sValue = r.attributes().value(QLatin1String(name));
if (sValue.isEmpty())
return defaultValue;
bool ok;
- const int value = sValue.toInt(&ok);
+ const int value = sValue.toString().toInt(&ok);
if (!ok) {
qWarning("Invalid integer value specification '%s' for attribute '%s'.",
- qPrintable(sValue), name);
+ qPrintable(sValue.toString()), name);
return defaultValue;
}
return value;
@@ -580,7 +552,7 @@ GeneratorScriptArgument::GeneratorScriptArgument(const QString &v) :
CustomWizardParameters::ParseResult
CustomWizardParameters::parse(QIODevice &device,
const QString &configFileFullPath,
- BaseFileWizardParameters *bp,
+ IWizard::Data *bp,
QString *errorMessage)
{
int comboEntryCount = 0;
@@ -588,8 +560,8 @@ CustomWizardParameters::ParseResult
QXmlStreamReader::TokenType token = QXmlStreamReader::EndDocument;
ParseState state = ParseBeginning;
clear();
- bp->clear();
- bp->setKind(IWizard::ProjectWizard);
+ *bp = IWizard::Data();
+ bp->kind = IWizard::ProjectWizard;
const QString language = languageSetting();
CustomWizardField field;
do {
@@ -614,11 +586,11 @@ CustomWizardParameters::ParseResult
case ParseWithinWizard:
if (!booleanAttributeValue(reader, wizardEnabledAttributeC, true))
return ParseDisabled;
- bp->setId(attributeValue(reader, idAttributeC));
- bp->setCategory(attributeValue(reader, categoryAttributeC));
- bp->setKind(kindAttribute(reader));
- bp->setRequiredFeatures(requiredFeatures(reader));
- bp->setFlags(wizardFlags(reader));
+ bp->id = attributeValue(reader, idAttributeC);
+ bp->category = attributeValue(reader, categoryAttributeC);
+ bp->kind = kindAttribute(reader);
+ bp->requiredFeatures = requiredFeatures(reader);
+ bp->flags = wizardFlags(reader);
klass = attributeValue(reader, klassAttributeC);
firstPageId = integerAttributeValue(reader, firstPageAttributeC, -1);
break;
@@ -732,7 +704,7 @@ CustomWizardParameters::ParseResult
CustomWizardParameters::ParseResult
CustomWizardParameters::parse(const QString &configFileFullPath,
- BaseFileWizardParameters *bp,
+ IWizard::Data *bp,
QString *errorMessage)
{
QFile configFile(configFileFullPath);
@@ -853,7 +825,9 @@ bool replaceFieldHelper(ValueStringTransformation transform,
if (nextPos == -1)
break;
if (nextPos == pos + 1) {
- pos = nextPos; // Skip '%%'
+ pos = nextPos; // Replace '%%' with '%'
+ s->remove(pos, 1);
+ pos = pos + 1;
continue;
}
// Evaluate field specification for modifiers
@@ -888,7 +862,7 @@ bool replaceFieldHelper(ValueStringTransformation transform,
case 'c': // Capitalize first letter.
replacement = it.value();
if (!replacement.isEmpty())
- replacement[0] = replacement.at(0).toUpper();
+ replacement[0] = replacement.at(0).toTitleCase();
break;
default:
break;
@@ -997,11 +971,10 @@ void CustomWizardContext::reset()
{
// Basic replacement fields: Suffixes.
baseReplacements.clear();
- const MimeDatabase *mdb = ICore::mimeDatabase();
baseReplacements.insert(QLatin1String("CppSourceSuffix"),
- mdb->preferredSuffixByType(QLatin1String(CppTools::Constants::CPP_SOURCE_MIMETYPE)));
+ MimeDatabase::preferredSuffixByType(QLatin1String(CppTools::Constants::CPP_SOURCE_MIMETYPE)));
baseReplacements.insert(QLatin1String("CppHeaderSuffix"),
- mdb->preferredSuffixByType(QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE)));
+ MimeDatabase::preferredSuffixByType(QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE)));
replacements.clear();
path.clear();
targetPath.clear();
diff --git a/src/plugins/projectexplorer/customwizard/customwizardparameters.h b/src/plugins/projectexplorer/customwizard/customwizardparameters.h
index 2dfdf62b5a..cd531d2b74 100644
--- a/src/plugins/projectexplorer/customwizard/customwizardparameters.h
+++ b/src/plugins/projectexplorer/customwizard/customwizardparameters.h
@@ -106,9 +106,9 @@ public:
CustomWizardParameters();
void clear();
ParseResult parse(QIODevice &device, const QString &configFileFullPath,
- Core::BaseFileWizardParameters *bp, QString *errorMessage);
+ Core::IWizard::Data *bp, QString *errorMessage);
ParseResult parse(const QString &configFileFullPath,
- Core::BaseFileWizardParameters *bp, QString *errorMessage);
+ Core::IWizard::Data *bp, QString *errorMessage);
QString toString() const;
QString directory;
diff --git a/src/plugins/projectexplorer/customwizard/customwizardpreprocessor.cpp b/src/plugins/projectexplorer/customwizard/customwizardpreprocessor.cpp
index ba0c007bbb..8884772263 100644
--- a/src/plugins/projectexplorer/customwizard/customwizardpreprocessor.cpp
+++ b/src/plugins/projectexplorer/customwizard/customwizardpreprocessor.cpp
@@ -29,7 +29,7 @@
#include "customwizardpreprocessor.h"
#ifdef WITH_TESTS
-# include "projectexplorer.h"
+# include "../projectexplorer.h"
# include <QTest>
#endif
diff --git a/src/plugins/projectexplorer/dependenciespanel.cpp b/src/plugins/projectexplorer/dependenciespanel.cpp
index 4e75ec1792..50a71b706e 100644
--- a/src/plugins/projectexplorer/dependenciespanel.cpp
+++ b/src/plugins/projectexplorer/dependenciespanel.cpp
@@ -32,7 +32,6 @@
#include "session.h"
#include <coreplugin/fileiconprovider.h>
-#include <coreplugin/idocument.h>
#include <utils/detailswidget.h>
#include <QDebug>
@@ -47,34 +46,28 @@
namespace ProjectExplorer {
namespace Internal {
-DependenciesModel::DependenciesModel(SessionManager *session,
- Project *project,
- QObject *parent)
+DependenciesModel::DependenciesModel(Project *project, QObject *parent)
: QAbstractListModel(parent)
- , m_session(session)
, m_project(project)
- , m_projects(session->projects())
+ , m_projects(SessionManager::projects())
{
// We can't select ourselves as a dependency
m_projects.removeAll(m_project);
- connect(session, SIGNAL(projectRemoved(ProjectExplorer::Project*)),
+
+ QObject *sessionManager = SessionManager::instance();
+ connect(sessionManager, SIGNAL(projectRemoved(ProjectExplorer::Project*)),
this, SLOT(resetModel()));
- connect(session, SIGNAL(projectAdded(ProjectExplorer::Project*)),
+ connect(sessionManager, SIGNAL(projectAdded(ProjectExplorer::Project*)),
this, SLOT(resetModel()));
- connect(session, SIGNAL(sessionLoaded(QString)),
+ connect(sessionManager, SIGNAL(sessionLoaded(QString)),
this, SLOT(resetModel()));
// qDebug()<<"Dependencies Model"<<this<<"for project"<<project<<"("<<project->file()->fileName()<<")";
}
-DependenciesModel::~DependenciesModel()
-{
-// qDebug()<<"~DependenciesModel"<<this;
-}
-
void DependenciesModel::resetModel()
{
beginResetModel();
- m_projects = m_session->projects();
+ m_projects = SessionManager::projects();
m_projects.removeAll(m_project);
endResetModel();
}
@@ -102,9 +95,9 @@ QVariant DependenciesModel::data(const QModelIndex &index, int role) const
case Qt::DisplayRole:
return p->displayName();
case Qt::CheckStateRole:
- return m_session->hasDependency(m_project, p) ? Qt::Checked : Qt::Unchecked;
+ return SessionManager::hasDependency(m_project, p) ? Qt::Checked : Qt::Unchecked;
case Qt::DecorationRole:
- return Core::FileIconProvider::instance()->icon(QFileInfo(p->document()->fileName()));
+ return Core::FileIconProvider::icon(p->projectFilePath());
default:
return QVariant();
}
@@ -117,7 +110,7 @@ bool DependenciesModel::setData(const QModelIndex &index, const QVariant &value,
const Qt::CheckState c = static_cast<Qt::CheckState>(value.toInt());
if (c == Qt::Checked) {
- if (m_session->addDependency(m_project, p)) {
+ if (SessionManager::addDependency(m_project, p)) {
emit dataChanged(index, index);
return true;
} else {
@@ -125,8 +118,8 @@ bool DependenciesModel::setData(const QModelIndex &index, const QVariant &value,
QCoreApplication::translate("DependenciesModel", "This would create a circular dependency."));
}
} else if (c == Qt::Unchecked) {
- if (m_session->hasDependency(m_project, p)) {
- m_session->removeDependency(m_project, p);
+ if (SessionManager::hasDependency(m_project, p)) {
+ SessionManager::removeDependency(m_project, p);
emit dataChanged(index, index);
return true;
}
@@ -158,11 +151,6 @@ DependenciesView::DependenciesView(QWidget *parent)
setRootIsDecorated(false);
}
-DependenciesView::~DependenciesView()
-{
-
-}
-
QSize DependenciesView::sizeHint() const
{
return m_sizeHint;
@@ -220,13 +208,10 @@ void DependenciesView::updateSizeHint()
// DependenciesWidget
//
-DependenciesWidget::DependenciesWidget(SessionManager *session,
- Project *project,
- QWidget *parent)
+DependenciesWidget::DependenciesWidget(Project *project, QWidget *parent)
: QWidget(parent)
- , m_session(session)
, m_project(project)
- , m_model(new DependenciesModel(session, project, this))
+ , m_model(new DependenciesModel(project, this))
{
QVBoxLayout *vbox = new QVBoxLayout(this);
vbox->setContentsMargins(0, 0, 0, 0);
@@ -249,14 +234,9 @@ DependenciesWidget::DependenciesWidget(SessionManager *session,
// DependenciesPanelFactory
//
-DependenciesPanelFactory::DependenciesPanelFactory(SessionManager *session)
- : m_session(session)
-{
-}
-
QString DependenciesPanelFactory::id() const
{
- return QLatin1String(DEPENDENCIES_PANEL_ID);
+ return QLatin1String("ProjectExplorer.DependenciesPanel");
}
QString DependenciesPanelFactory::displayName() const
@@ -278,7 +258,7 @@ bool DependenciesPanelFactory::supports(Project *project)
PropertiesPanel *DependenciesPanelFactory::createPanel(Project *project)
{
PropertiesPanel *panel = new PropertiesPanel;
- panel->setWidget(new DependenciesWidget(m_session, project));
+ panel->setWidget(new DependenciesWidget(project));
panel->setIcon(QIcon(QLatin1String(":/projectexplorer/images/ProjectDependencies.png")));
panel->setDisplayName(QCoreApplication::translate("DependenciesPanel", "Dependencies"));
return panel;
diff --git a/src/plugins/projectexplorer/dependenciespanel.h b/src/plugins/projectexplorer/dependenciespanel.h
index 9fc7e041e7..b7cada2237 100644
--- a/src/plugins/projectexplorer/dependenciespanel.h
+++ b/src/plugins/projectexplorer/dependenciespanel.h
@@ -36,33 +36,24 @@
#include <QTreeView>
-namespace Utils {
- class DetailsWidget;
-}
+namespace Utils { class DetailsWidget; }
namespace ProjectExplorer {
class Project;
-class SessionManager;
namespace Internal {
-const char DEPENDENCIES_PANEL_ID[] = "ProjectExplorer.DependenciesPanel";
-
-class DependenciesWidget;
-
class DependenciesPanelFactory : public IProjectPanelFactory
{
public:
- DependenciesPanelFactory(SessionManager *session);
+ DependenciesPanelFactory() {}
QString id() const;
QString displayName() const;
int priority() const;
bool supports(Project *project);
PropertiesPanel *createPanel(Project *project);
-private:
- SessionManager *m_session;
};
@@ -73,9 +64,9 @@ private:
class DependenciesModel : public QAbstractListModel
{
Q_OBJECT
+
public:
- DependenciesModel(SessionManager *session, Project *project, QObject *parent = 0);
- ~DependenciesModel();
+ explicit DependenciesModel(Project *project, QObject *parent = 0);
int rowCount(const QModelIndex &index) const;
int columnCount(const QModelIndex &index) const;
@@ -87,7 +78,6 @@ public slots:
void resetModel();
private:
- SessionManager *m_session;
Project *m_project;
QList<Project *> m_projects;
};
@@ -95,13 +85,16 @@ private:
class DependenciesView : public QTreeView
{
Q_OBJECT
+
public:
DependenciesView(QWidget *parent);
- ~DependenciesView();
- virtual QSize sizeHint() const;
- virtual void setModel(QAbstractItemModel *model);
+
+ QSize sizeHint() const;
+ void setModel(QAbstractItemModel *model);
+
private slots:
void updateSizeHint();
+
private:
QSize m_sizeHint;
};
@@ -109,11 +102,11 @@ private:
class DependenciesWidget : public QWidget
{
Q_OBJECT
+
public:
- DependenciesWidget(SessionManager *session, Project *project,
- QWidget *parent = 0);
+ explicit DependenciesWidget(Project *project, QWidget *parent = 0);
+
private:
- SessionManager *m_session;
Project *m_project;
DependenciesModel *m_model;
Utils::DetailsWidget *m_detailsContainer;
diff --git a/src/plugins/projectexplorer/deployconfiguration.cpp b/src/plugins/projectexplorer/deployconfiguration.cpp
index cdd7c32528..91c867ebdc 100644
--- a/src/plugins/projectexplorer/deployconfiguration.cpp
+++ b/src/plugins/projectexplorer/deployconfiguration.cpp
@@ -39,12 +39,8 @@
using namespace ProjectExplorer;
-namespace {
-
-const char * const BUILD_STEP_LIST_COUNT("ProjectExplorer.BuildConfiguration.BuildStepListCount");
-const char * const BUILD_STEP_LIST_PREFIX("ProjectExplorer.BuildConfiguration.BuildStepList.");
-
-} // namespace
+const char BUILD_STEP_LIST_COUNT[] = "ProjectExplorer.BuildConfiguration.BuildStepListCount";
+const char BUILD_STEP_LIST_PREFIX[] = "ProjectExplorer.BuildConfiguration.BuildStepList.";
DeployConfiguration::DeployConfiguration(Target *target, const Core::Id id) :
ProjectConfiguration(target, id),
@@ -232,7 +228,7 @@ DeployConfiguration *DeployConfigurationFactory::clone(Target *parent, DeployCon
DeployConfigurationFactory *DeployConfigurationFactory::find(Target *parent, const QVariantMap &map)
{
QList<DeployConfigurationFactory *> factories
- = ExtensionSystem::PluginManager::instance()->getObjects<DeployConfigurationFactory>();
+ = ExtensionSystem::PluginManager::getObjects<DeployConfigurationFactory>();
foreach (DeployConfigurationFactory *factory, factories) {
if (factory->canRestore(parent, map))
return factory;
@@ -244,7 +240,7 @@ QList<DeployConfigurationFactory *> DeployConfigurationFactory::find(Target *par
{
QList<DeployConfigurationFactory *> result;
QList<DeployConfigurationFactory *> factories
- = ExtensionSystem::PluginManager::instance()->getObjects<DeployConfigurationFactory>();
+ = ExtensionSystem::PluginManager::getObjects<DeployConfigurationFactory>();
foreach (DeployConfigurationFactory *factory, factories) {
if (!factory->availableCreationIds(parent).isEmpty())
result << factory;
@@ -255,7 +251,7 @@ QList<DeployConfigurationFactory *> DeployConfigurationFactory::find(Target *par
DeployConfigurationFactory *DeployConfigurationFactory::find(Target *parent, DeployConfiguration *dc)
{
QList<DeployConfigurationFactory *> factories
- = ExtensionSystem::PluginManager::instance()->getObjects<DeployConfigurationFactory>();
+ = ExtensionSystem::PluginManager::getObjects<DeployConfigurationFactory>();
foreach (DeployConfigurationFactory *factory, factories) {
if (factory->canClone(parent, dc))
return factory;
diff --git a/src/plugins/projectexplorer/devicesupport/desktopdevice.cpp b/src/plugins/projectexplorer/devicesupport/desktopdevice.cpp
index 68478164d7..343032ea1b 100644
--- a/src/plugins/projectexplorer/devicesupport/desktopdevice.cpp
+++ b/src/plugins/projectexplorer/devicesupport/desktopdevice.cpp
@@ -28,10 +28,12 @@
****************************************************************************/
#include "desktopdevice.h"
-#include "projectexplorerconstants.h"
+#include "desktopdeviceprocess.h"
#include "deviceprocesslist.h"
#include "localprocesslist.h"
#include "desktopdeviceconfigurationwidget.h"
+#include "desktopprocesssignaloperation.h"
+#include <projectexplorer/projectexplorerconstants.h>
#include <ssh/sshconnection.h>
#include <utils/portlist.h>
@@ -87,7 +89,7 @@ QString DesktopDevice::displayNameForActionId(Core::Id actionId) const
return QString();
}
-void DesktopDevice::executeAction(Core::Id actionId, QWidget *parent) const
+void DesktopDevice::executeAction(Core::Id actionId, QWidget *parent)
{
Q_UNUSED(actionId);
Q_UNUSED(parent);
@@ -108,6 +110,16 @@ DeviceProcessList *DesktopDevice::createProcessListModel(QObject *parent) const
return new Internal::LocalProcessList(sharedFromThis(), parent);
}
+DeviceProcess *DesktopDevice::createProcess(QObject *parent) const
+{
+ return new Internal::DesktopDeviceProcess(sharedFromThis(), parent);
+}
+
+DeviceProcessSignalOperation::Ptr DesktopDevice::signalOperation() const
+{
+ return DeviceProcessSignalOperation::Ptr(new DesktopProcessSignalOperation());
+}
+
IDevice::Ptr DesktopDevice::clone() const
{
return Ptr(new DesktopDevice(*this));
diff --git a/src/plugins/projectexplorer/devicesupport/desktopdevice.h b/src/plugins/projectexplorer/devicesupport/desktopdevice.h
index 58f86d191a..1b65f6c49b 100644
--- a/src/plugins/projectexplorer/devicesupport/desktopdevice.h
+++ b/src/plugins/projectexplorer/devicesupport/desktopdevice.h
@@ -49,10 +49,13 @@ public:
IDeviceWidget *createWidget();
QList<Core::Id> actionIds() const;
QString displayNameForActionId(Core::Id actionId) const;
- void executeAction(Core::Id actionId, QWidget *parent = 0) const;
+ void executeAction(Core::Id actionId, QWidget *parent = 0);
bool canAutoDetectPorts() const;
bool canCreateProcessModel() const;
DeviceProcessList *createProcessListModel(QObject *parent) const;
+ bool canCreateProcess() const { return true; }
+ DeviceProcess *createProcess(QObject *parent) const;
+ DeviceProcessSignalOperation::Ptr signalOperation() const;
IDevice::Ptr clone() const;
diff --git a/src/plugins/projectexplorer/devicesupport/desktopdeviceconfigurationwidget.cpp b/src/plugins/projectexplorer/devicesupport/desktopdeviceconfigurationwidget.cpp
index 19120a46ef..155f59e78d 100644
--- a/src/plugins/projectexplorer/devicesupport/desktopdeviceconfigurationwidget.cpp
+++ b/src/plugins/projectexplorer/devicesupport/desktopdeviceconfigurationwidget.cpp
@@ -29,7 +29,7 @@
#include "desktopdeviceconfigurationwidget.h"
#include "ui_desktopdeviceconfigurationwidget.h"
-#include "projectexplorerconstants.h"
+#include <projectexplorer/projectexplorerconstants.h>
#include <utils/portlist.h>
#include <utils/qtcassert.h>
diff --git a/src/plugins/projectexplorer/devicesupport/desktopdevicefactory.cpp b/src/plugins/projectexplorer/devicesupport/desktopdevicefactory.cpp
index 24e01d9336..ca2817dcb6 100644
--- a/src/plugins/projectexplorer/devicesupport/desktopdevicefactory.cpp
+++ b/src/plugins/projectexplorer/devicesupport/desktopdevicefactory.cpp
@@ -29,7 +29,7 @@
#include "desktopdevicefactory.h"
#include "desktopdevice.h"
-#include "projectexplorerconstants.h"
+#include <projectexplorer/projectexplorerconstants.h>
#include <utils/qtcassert.h>
diff --git a/src/plugins/projectexplorer/devicesupport/desktopdeviceprocess.cpp b/src/plugins/projectexplorer/devicesupport/desktopdeviceprocess.cpp
new file mode 100644
index 0000000000..eb7f3b4f65
--- /dev/null
+++ b/src/plugins/projectexplorer/devicesupport/desktopdeviceprocess.cpp
@@ -0,0 +1,124 @@
+/****************************************************************************
+**
+** 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 "desktopdeviceprocess.h"
+#include "idevice.h"
+
+#include <utils/environment.h>
+#include <utils/qtcassert.h>
+#include <utils/qtcprocess.h>
+
+namespace ProjectExplorer {
+namespace Internal {
+
+DesktopDeviceProcess::DesktopDeviceProcess(const QSharedPointer<const IDevice> &device,
+ QObject *parent)
+ : DeviceProcess(device, parent), m_process(new QProcess(this))
+{
+ connect(m_process, SIGNAL(error(QProcess::ProcessError)),
+ SIGNAL(error(QProcess::ProcessError)));
+ connect(m_process, SIGNAL(finished(int)), SIGNAL(finished()));
+ connect(m_process, SIGNAL(readyReadStandardOutput()), SIGNAL(readyReadStandardOutput()));
+ connect(m_process, SIGNAL(readyReadStandardError()), SIGNAL(readyReadStandardError()));
+ connect(m_process, SIGNAL(started()), SIGNAL(started()));
+}
+
+void DesktopDeviceProcess::start(const QString &executable, const QStringList &arguments)
+{
+ QTC_ASSERT(m_process->state() == QProcess::NotRunning, return);
+ m_process->start(executable, arguments);
+}
+
+void DesktopDeviceProcess::interrupt()
+{
+ device()->signalOperation()->interruptProcess(Utils::qPidToPid(m_process->pid()));
+}
+
+void DesktopDeviceProcess::terminate()
+{
+ m_process->terminate();
+}
+
+void DesktopDeviceProcess::kill()
+{
+ m_process->kill();
+}
+
+QProcess::ProcessState DesktopDeviceProcess::state() const
+{
+ return m_process->state();
+}
+
+QProcess::ExitStatus DesktopDeviceProcess::exitStatus() const
+{
+ return m_process->exitStatus();
+}
+
+int DesktopDeviceProcess::exitCode() const
+{
+ return m_process->exitCode();
+}
+
+QString DesktopDeviceProcess::errorString() const
+{
+ return m_process->errorString();
+}
+
+Utils::Environment DesktopDeviceProcess::environment() const
+{
+ return Utils::Environment(m_process->processEnvironment().toStringList());
+}
+
+void DesktopDeviceProcess::setEnvironment(const Utils::Environment &env)
+{
+ m_process->setProcessEnvironment(env.toProcessEnvironment());
+}
+
+void DesktopDeviceProcess::setWorkingDirectory(const QString &directory)
+{
+ m_process->setWorkingDirectory(directory);
+}
+
+QByteArray DesktopDeviceProcess::readAllStandardOutput()
+{
+ return m_process->readAllStandardOutput();
+}
+
+QByteArray DesktopDeviceProcess::readAllStandardError()
+{
+ return m_process->readAllStandardError();
+}
+
+qint64 DesktopDeviceProcess::write(const QByteArray &data)
+{
+ return m_process->write(data);
+}
+
+} // namespace Internal
+} // namespace ProjectExplorer
diff --git a/src/plugins/projectexplorer/devicesupport/desktopdeviceprocess.h b/src/plugins/projectexplorer/devicesupport/desktopdeviceprocess.h
new file mode 100644
index 0000000000..8d1f68db11
--- /dev/null
+++ b/src/plugins/projectexplorer/devicesupport/desktopdeviceprocess.h
@@ -0,0 +1,72 @@
+/****************************************************************************
+**
+** 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 QTC_DESKTOPDEVICEPROCESS_H
+#define QTC_DESKTOPDEVICEPROCESS_H
+
+#include "deviceprocess.h"
+
+namespace ProjectExplorer {
+namespace Internal {
+class ProcessHelper;
+
+class DesktopDeviceProcess : public DeviceProcess
+{
+ Q_OBJECT
+public:
+ DesktopDeviceProcess(const QSharedPointer<const IDevice> &device, QObject *parent = 0);
+
+ void start(const QString &executable, const QStringList &arguments);
+ void interrupt();
+ void terminate();
+ void kill();
+
+ QProcess::ProcessState state() const;
+ QProcess::ExitStatus exitStatus() const;
+ int exitCode() const;
+ QString errorString() const;
+
+ Utils::Environment environment() const;
+ void setEnvironment(const Utils::Environment &env);
+
+ void setWorkingDirectory(const QString &directory);
+
+ QByteArray readAllStandardOutput();
+ QByteArray readAllStandardError();
+
+ qint64 write(const QByteArray &data);
+
+private:
+ QProcess * const m_process;
+};
+
+} // namespace Internal
+} // namespace ProjectExplorer
+
+#endif // Include guard
diff --git a/src/plugins/projectexplorer/devicesupport/desktopprocesssignaloperation.cpp b/src/plugins/projectexplorer/devicesupport/desktopprocesssignaloperation.cpp
new file mode 100644
index 0000000000..861cb23b71
--- /dev/null
+++ b/src/plugins/projectexplorer/devicesupport/desktopprocesssignaloperation.cpp
@@ -0,0 +1,207 @@
+/****************************************************************************
+**
+** 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 "desktopprocesssignaloperation.h"
+
+#include "localprocesslist.h"
+
+#include <utils/winutils.h>
+
+#include <QCoreApplication>
+#include <QDir>
+
+#ifdef Q_OS_WIN
+#define _WIN32_WINNT 0x0502
+#include <windows.h>
+#ifndef PROCESS_SUSPEND_RESUME
+#define PROCESS_SUSPEND_RESUME 0x0800
+#endif // PROCESS_SUSPEND_RESUME
+#else // Q_OS_WIN
+#include <errno.h>
+#include <signal.h>
+#endif // else Q_OS_WIN
+
+namespace ProjectExplorer {
+
+void DesktopProcessSignalOperation::killProcess(int pid)
+{
+ killProcessSilently(pid);
+ emit finished(m_errorMessage);
+}
+
+void DesktopProcessSignalOperation::killProcess(const QString &filePath)
+{
+ m_errorMessage.clear();
+ foreach (const DeviceProcessItem &process, Internal::LocalProcessList::getLocalProcesses()) {
+ if (process.cmdLine == filePath)
+ killProcessSilently(process.pid);
+ }
+ emit finished(m_errorMessage);
+}
+
+void DesktopProcessSignalOperation::interruptProcess(int pid)
+{
+ m_errorMessage.clear();
+ interruptProcessSilently(pid);
+ emit finished(m_errorMessage);
+}
+
+void DesktopProcessSignalOperation::interruptProcess(const QString &filePath)
+{
+ m_errorMessage.clear();
+ foreach (const DeviceProcessItem &process, Internal::LocalProcessList::getLocalProcesses()) {
+ if (process.cmdLine == filePath)
+ interruptProcessSilently(process.pid);
+ }
+ emit finished(m_errorMessage);
+}
+
+void DesktopProcessSignalOperation::appendMsgCannotKill(int pid, const QString &why)
+{
+ if (!m_errorMessage.isEmpty())
+ m_errorMessage += QChar::fromLatin1('\n');
+ m_errorMessage += tr("Cannot kill process with pid %1: %3 ").arg(pid).arg(why);
+}
+
+void DesktopProcessSignalOperation::appendMsgCannotInterrupt(int pid, const QString &why)
+{
+ if (!m_errorMessage.isEmpty())
+ m_errorMessage += QChar::fromLatin1('\n');
+ m_errorMessage += tr("Cannot interrupt process with pid %1: %3 ").arg(pid).arg(why);
+}
+
+void DesktopProcessSignalOperation::killProcessSilently(int pid)
+{
+#ifdef Q_OS_WIN
+ const DWORD rights = PROCESS_QUERY_INFORMATION|PROCESS_SET_INFORMATION
+ |PROCESS_VM_OPERATION|PROCESS_VM_WRITE|PROCESS_VM_READ
+ |PROCESS_DUP_HANDLE|PROCESS_TERMINATE|PROCESS_CREATE_THREAD|PROCESS_SUSPEND_RESUME;
+ if (const HANDLE handle = OpenProcess(rights, FALSE, pid)) {
+ if (!TerminateProcess(handle, UINT(-1)))
+ appendMsgCannotKill(pid, Utils::winErrorMessage(GetLastError()));
+ CloseHandle(handle);
+ } else {
+ appendMsgCannotKill(pid, tr("Cannot open process."));
+ }
+#else
+ if (pid <= 0)
+ appendMsgCannotKill(pid, tr("Invalid process id."));
+ else if (kill(pid, SIGKILL))
+ appendMsgCannotKill(pid, QString::fromLocal8Bit(strerror(errno)));
+#endif // Q_OS_WIN
+}
+
+void DesktopProcessSignalOperation::interruptProcessSilently(int pid)
+{
+#ifdef Q_OS_WIN
+ /*
+ Windows 64 bit has a 32 bit subsystem (WOW64) which makes it possible to run a
+ 32 bit application inside a 64 bit environment.
+ When GDB is used DebugBreakProcess must be called from the same system (32/64 bit) running
+ the inferior. If CDB is used we could in theory break wow64 processes,
+ but the break is actually a wow64 breakpoint. CDB is configured to ignore these
+ breakpoints, because they also appear on module loading.
+ Therefore we need helper executables (win(32/64)interrupt.exe) on Windows 64 bit calling
+ DebugBreakProcess from the correct system.
+
+ DebugBreak matrix for windows
+
+ Api = UseDebugBreakApi
+ Win64 = UseWin64InterruptHelper
+ Win32 = UseWin32InterruptHelper
+ N/A = This configuration is not possible
+
+ | Windows 32bit | Windows 64bit
+ | QtCreator 32bit | QtCreator 32bit | QtCreator 64bit
+ | Inferior 32bit | Inferior 32bit | Inferior 64bit | Inferior 32bit | Inferior 64bit
+----------|-----------------|-----------------|-----------------|-----------------|----------------
+CDB 32bit | Api | Api | N/A | Win32 | N/A
+ 64bit | N/A | Win64 | Win64 | Api | Api
+----------|-----------------|-----------------|-----------------|-----------------|----------------
+GDB 32bit | Api | Api | N/A | Win32 | N/A
+ 64bit | N/A | N/A | Win64 | N/A | Api
+----------|-----------------|-----------------|-----------------|-----------------|----------------
+
+ */
+ HANDLE inferior = NULL;
+ do {
+ const DWORD rights = PROCESS_QUERY_INFORMATION|PROCESS_SET_INFORMATION
+ |PROCESS_VM_OPERATION|PROCESS_VM_WRITE|PROCESS_VM_READ
+ |PROCESS_DUP_HANDLE|PROCESS_TERMINATE|PROCESS_CREATE_THREAD|PROCESS_SUSPEND_RESUME;
+ inferior = OpenProcess(rights, FALSE, pid);
+ if (inferior == NULL) {
+ appendMsgCannotInterrupt(pid, tr("Cannot open process: %1")
+ + Utils::winErrorMessage(GetLastError()));
+ break;
+ }
+ bool creatorIs64Bit = Utils::winIs64BitBinary(qApp->applicationFilePath());
+ if (!Utils::winIs64BitSystem() ||
+ m_specialInterrupt == NoSpecialInterrupt ||
+ m_specialInterrupt == Win64Interrupt && creatorIs64Bit ||
+ m_specialInterrupt == Win32Interrupt && !creatorIs64Bit) {
+ if (!DebugBreakProcess(inferior)) {
+ appendMsgCannotInterrupt(pid, tr("DebugBreakProcess failed: ")
+ + Utils::winErrorMessage(GetLastError()));
+ }
+ } else if (m_specialInterrupt == Win32Interrupt || m_specialInterrupt == Win64Interrupt) {
+ QString executable = QCoreApplication::applicationDirPath();
+ executable += m_specialInterrupt == Win32Interrupt
+ ? QLatin1String("/win32interrupt.exe")
+ : QLatin1String("/win64interrupt.exe");
+ if (!QFile::exists(executable)) {
+ appendMsgCannotInterrupt(pid, tr( "%1 does not exist. If you have built QtCreator "
+ "on your own ,checkout http://qt.gitorious.org/"
+ "qt-creator/binary-artifacts.").
+ arg(QDir::toNativeSeparators(executable)));
+ }
+ switch (QProcess::execute(executable, QStringList(QString::number(pid)))) {
+ case -2:
+ appendMsgCannotInterrupt(pid, tr(
+ "Cannot start %1. Check src\\tools\\win64interrupt\\win64interrupt.c "
+ "for more information.").arg(QDir::toNativeSeparators(executable)));
+ break;
+ case 0:
+ break;
+ default:
+ appendMsgCannotInterrupt(pid, QDir::toNativeSeparators(executable)
+ + tr(" could not break the process."));
+ break;
+ }
+ }
+ } while (false);
+ if (inferior != NULL)
+ CloseHandle(inferior);
+#else
+ if (pid <= 0)
+ appendMsgCannotInterrupt(pid, tr("Invalid process id."));
+ else if (kill(pid, SIGINT))
+ appendMsgCannotInterrupt(pid, QString::fromLocal8Bit(strerror(errno)));
+#endif // Q_OS_WIN
+}
+
+} // namespace ProjectExplorer
diff --git a/src/plugins/projectexplorer/devicesupport/desktopprocesssignaloperation.h b/src/plugins/projectexplorer/devicesupport/desktopprocesssignaloperation.h
new file mode 100644
index 0000000000..cca2018442
--- /dev/null
+++ b/src/plugins/projectexplorer/devicesupport/desktopprocesssignaloperation.h
@@ -0,0 +1,62 @@
+/****************************************************************************
+**
+** 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 WINDOWSPROCESSSIGNALOPERATION_H
+#define WINDOWSPROCESSSIGNALOPERATION_H
+
+#include "idevice.h"
+
+#include <projectexplorer/projectexplorer_export.h>
+
+namespace ProjectExplorer {
+
+class PROJECTEXPLORER_EXPORT DesktopProcessSignalOperation : public DeviceProcessSignalOperation
+{
+ Q_OBJECT
+public:
+ ~DesktopProcessSignalOperation() {}
+ void killProcess(int pid);
+ void killProcess(const QString &filePath);
+ void interruptProcess(int pid);
+ void interruptProcess(const QString &filePath);
+
+private:
+ void killProcessSilently(int pid);
+ void interruptProcessSilently(int pid);
+
+ void appendMsgCannotKill(int pid, const QString &why);
+ void appendMsgCannotInterrupt(int pid, const QString &why);
+
+protected:
+ explicit DesktopProcessSignalOperation() {}
+
+ friend class DesktopDevice;
+};
+
+} // namespace ProjectExplorer
+#endif // WINDOWSPROCESSSIGNALOPERATION_H
diff --git a/src/plugins/projectexplorer/devicesupport/deviceapplicationrunner.cpp b/src/plugins/projectexplorer/devicesupport/deviceapplicationrunner.cpp
index b7fe7248c3..11ee968e46 100644
--- a/src/plugins/projectexplorer/devicesupport/deviceapplicationrunner.cpp
+++ b/src/plugins/projectexplorer/devicesupport/deviceapplicationrunner.cpp
@@ -28,11 +28,14 @@
****************************************************************************/
#include "deviceapplicationrunner.h"
+#include "sshdeviceprocess.h"
+
#include <ssh/sshconnection.h>
#include <ssh/sshconnectionmanager.h>
-#include <ssh/sshremoteprocess.h>
+#include <utils/environment.h>
#include <utils/qtcassert.h>
+#include <QStringList>
#include <QTimer>
using namespace QSsh;
@@ -49,10 +52,13 @@ public:
SshConnection *connection;
DeviceApplicationHelperAction *preRunAction;
DeviceApplicationHelperAction *postRunAction;
+ DeviceProcess *deviceProcess;
IDevice::ConstPtr device;
- SshRemoteProcess::Ptr remoteApp;
QTimer stopTimer;
- QByteArray commandLine;
+ QString command;
+ QStringList arguments;
+ Utils::Environment environment;
+ QString workingDir;
State state;
bool stopRequested;
bool success;
@@ -74,6 +80,7 @@ DeviceApplicationRunner::DeviceApplicationRunner(QObject *parent) :
d->preRunAction = 0;
d->postRunAction = 0;
d->connection = 0;
+ d->deviceProcess = 0;
d->state = Inactive;
d->stopTimer.setSingleShot(true);
@@ -86,23 +93,33 @@ DeviceApplicationRunner::~DeviceApplicationRunner()
delete d;
}
+void DeviceApplicationRunner::setEnvironment(const Utils::Environment &env)
+{
+ d->environment = env;
+}
+
+void DeviceApplicationRunner::setWorkingDirectory(const QString &workingDirectory)
+{
+ d->workingDir = workingDirectory;
+}
+
void DeviceApplicationRunner::start(const IDevice::ConstPtr &device,
- const QByteArray &commandLine)
+ const QString &command, const QStringList &arguments)
{
+ QTC_ASSERT(device->canCreateProcess(), return);
QTC_ASSERT(d->state == Inactive, return);
d->device = device;
- d->commandLine = commandLine;
+ d->command = command;
+ d->arguments = arguments;
d->stopRequested = false;
d->success = true;
connectToServer();
}
-void DeviceApplicationRunner::stop(const QByteArray &stopCommand)
+void DeviceApplicationRunner::stop()
{
- QTC_ASSERT(d->state != Inactive, return);
-
if (d->stopRequested)
return;
d->stopRequested = true;
@@ -117,7 +134,7 @@ void DeviceApplicationRunner::stop(const QByteArray &stopCommand)
break;
case Run:
d->stopTimer.start(10000);
- d->connection->createRemoteProcess(stopCommand)->start();
+ d->deviceProcess->terminate();
break;
case PostRun:
d->postRunAction->stop();
@@ -149,7 +166,7 @@ void DeviceApplicationRunner::connectToServer()
return;
}
- d->connection = SshConnectionManager::instance().acquireConnection(d->device->sshParameters());
+ d->connection = QSsh::acquireConnection(d->device->sshParameters());
connect(d->connection, SIGNAL(error(QSsh::SshError)), SLOT(handleConnectionFailure()));
if (d->connection->state() == SshConnection::Connected) {
handleConnected();
@@ -188,14 +205,14 @@ void DeviceApplicationRunner::setFinished()
if (d->state == Inactive)
return;
- if (d->remoteApp) {
- d->remoteApp->disconnect(this);
- d->remoteApp->close();
- d->remoteApp.clear();
+ if (d->deviceProcess) {
+ d->deviceProcess->disconnect(this);
+ d->deviceProcess->deleteLater();
+ d->deviceProcess = 0;
}
if (d->connection) {
d->connection->disconnect(this);
- SshConnectionManager::instance().releaseConnection(d->connection);
+ QSsh::releaseConnection(d->connection);
d->connection = 0;
}
@@ -232,7 +249,7 @@ void DeviceApplicationRunner::handleConnectionFailure()
break;
case Run:
d->stopTimer.stop();
- d->remoteApp->disconnect(this);
+ d->deviceProcess->disconnect(this);
executePostRunAction();
break;
case PostRun:
@@ -290,16 +307,16 @@ void DeviceApplicationRunner::handleStopTimeout()
setFinished();
}
-void DeviceApplicationRunner::handleApplicationFinished(int exitStatus)
+void DeviceApplicationRunner::handleApplicationFinished()
{
QTC_ASSERT(d->state == Run, return);
d->stopTimer.stop();
- if (exitStatus == SshRemoteProcess::CrashExit) {
- emit reportError(tr("Remote application crashed: %1").arg(d->remoteApp->errorString()));
+ if (d->deviceProcess->exitStatus() == QProcess::CrashExit) {
+ emit reportError(tr("Remote application crashed: %1").arg(d->deviceProcess->errorString()));
d->success = false;
} else {
- const int exitCode = d->remoteApp->exitCode();
+ const int exitCode = d->deviceProcess->exitCode();
if (exitCode != 0) {
emit reportError(tr("Remote application finished with exit code %1.").arg(exitCode));
d->success = false;
@@ -313,13 +330,13 @@ void DeviceApplicationRunner::handleApplicationFinished(int exitStatus)
void DeviceApplicationRunner::handleRemoteStdout()
{
QTC_ASSERT(d->state == Run, return);
- emit remoteStdout(d->remoteApp->readAllStandardOutput());
+ emit remoteStdout(d->deviceProcess->readAllStandardOutput());
}
void DeviceApplicationRunner::handleRemoteStderr()
{
QTC_ASSERT(d->state == Run, return);
- emit remoteStderr(d->remoteApp->readAllStandardError());
+ emit remoteStderr(d->deviceProcess->readAllStandardError());
}
void DeviceApplicationRunner::runApplication()
@@ -327,12 +344,14 @@ void DeviceApplicationRunner::runApplication()
QTC_ASSERT(d->state == PreRun, return);
d->state = Run;
- d->remoteApp = d->connection->createRemoteProcess(d->commandLine);
- connect(d->remoteApp.data(), SIGNAL(started()), SIGNAL(remoteProcessStarted()));
- connect(d->remoteApp.data(), SIGNAL(readyReadStandardOutput()), SLOT(handleRemoteStdout()));
- connect(d->remoteApp.data(), SIGNAL(readyReadStandardError()), SLOT(handleRemoteStderr()));
- connect(d->remoteApp.data(), SIGNAL(closed(int)), SLOT(handleApplicationFinished(int)));
- d->remoteApp->start();
+ d->deviceProcess = d->device->createProcess(this);
+ connect(d->deviceProcess, SIGNAL(started()), SIGNAL(remoteProcessStarted()));
+ connect(d->deviceProcess, SIGNAL(readyReadStandardOutput()), SLOT(handleRemoteStdout()));
+ connect(d->deviceProcess, SIGNAL(readyReadStandardError()), SLOT(handleRemoteStderr()));
+ connect(d->deviceProcess, SIGNAL(finished()), SLOT(handleApplicationFinished()));
+ d->deviceProcess->setEnvironment(d->environment);
+ d->deviceProcess->setWorkingDirectory(d->workingDir);
+ d->deviceProcess->start(d->command, d->arguments);
}
} // namespace ProjectExplorer
diff --git a/src/plugins/projectexplorer/devicesupport/deviceapplicationrunner.h b/src/plugins/projectexplorer/devicesupport/deviceapplicationrunner.h
index 483f125692..188d05be22 100644
--- a/src/plugins/projectexplorer/devicesupport/deviceapplicationrunner.h
+++ b/src/plugins/projectexplorer/devicesupport/deviceapplicationrunner.h
@@ -35,6 +35,12 @@
#include <QObject>
+QT_BEGIN_NAMESPACE
+class QStringList;
+QT_END_NAMESPACE
+
+namespace Utils { class Environment; }
+
namespace ProjectExplorer {
class PROJECTEXPLORER_EXPORT DeviceApplicationHelperAction : public QObject
@@ -60,8 +66,12 @@ public:
explicit DeviceApplicationRunner(QObject *parent = 0);
virtual ~DeviceApplicationRunner();
- void start(const IDevice::ConstPtr &device, const QByteArray &commandLine);
- void stop(const QByteArray &stopCommand);
+ void setEnvironment(const Utils::Environment &env);
+ void setWorkingDirectory(const QString &workingDirectory);
+
+ void start(const IDevice::ConstPtr &device, const QString &command,
+ const QStringList &arguments);
+ void stop();
// Use these if you need to do something before and after the application is run, respectively.
// Typically, the post-run action reverts the effects of the pre-run action.
@@ -82,7 +92,7 @@ private slots:
void handleConnectionFailure();
void handleHelperActionFinished(bool success);
void handleStopTimeout();
- void handleApplicationFinished(int exitStatus);
+ void handleApplicationFinished();
void handleRemoteStdout();
void handleRemoteStderr();
diff --git a/src/plugins/projectexplorer/devicesupport/devicecheckbuildstep.cpp b/src/plugins/projectexplorer/devicesupport/devicecheckbuildstep.cpp
index 1c9554755e..d50477dd23 100644
--- a/src/plugins/projectexplorer/devicesupport/devicecheckbuildstep.cpp
+++ b/src/plugins/projectexplorer/devicesupport/devicecheckbuildstep.cpp
@@ -100,7 +100,7 @@ BuildStepConfigWidget *DeviceCheckBuildStep::createConfigWidget()
Core::Id DeviceCheckBuildStep::stepId()
{
- return Core::Id("ProjectExplorer.DeviceCheckBuildStep");
+ return "ProjectExplorer.DeviceCheckBuildStep";
}
QString DeviceCheckBuildStep::stepDisplayName()
diff --git a/src/plugins/projectexplorer/devicesupport/devicemanager.cpp b/src/plugins/projectexplorer/devicesupport/devicemanager.cpp
index d06f46b999..81328e8f11 100644
--- a/src/plugins/projectexplorer/devicesupport/devicemanager.cpp
+++ b/src/plugins/projectexplorer/devicesupport/devicemanager.cpp
@@ -96,7 +96,7 @@ int DeviceManager::deviceCount() const
void DeviceManager::replaceInstance()
{
copy(DeviceManagerPrivate::clonedInstance, instance(), false);
- emit instance()->deviceListChanged();
+ emit instance()->deviceListReplaced();
emit instance()->updated();
}
@@ -413,7 +413,7 @@ IDevice::ConstPtr DeviceManager::fromRawPointer(const IDevice *device) const
#ifdef WITH_TESTS
-#include "projectexplorer.h"
+#include <projectexplorer/projectexplorer.h>
#include <QSignalSpy>
#include <QTest>
#include <QUuid>
@@ -426,15 +426,19 @@ public:
TestDevice()
: IDevice(testTypeId(), AutoDetected, Hardware, Core::Id::fromString(QUuid::createUuid().toString())) {}
- static Core::Id testTypeId() { return Core::Id("TestType"); }
+ static Core::Id testTypeId() { return "TestType"; }
private:
TestDevice(const TestDevice &other) : IDevice(other) {}
QString displayType() const { return QLatin1String("blubb"); }
IDeviceWidget *createWidget() { return 0; }
QList<Core::Id> actionIds() const { return QList<Core::Id>(); }
QString displayNameForActionId(Core::Id) const { return QString(); }
- void executeAction(Core::Id, QWidget *) const { }
+ void executeAction(Core::Id, QWidget *) { }
Ptr clone() const { return Ptr(new TestDevice(*this)); }
+ DeviceProcessSignalOperation::Ptr signalOperation() const
+ {
+ return DeviceProcessSignalOperation::Ptr();
+ }
};
void ProjectExplorerPlugin::testDeviceManager()
@@ -455,7 +459,7 @@ void ProjectExplorerPlugin::testDeviceManager()
QSignalSpy deviceAddedSpy(mgr, SIGNAL(deviceAdded(Core::Id)));
QSignalSpy deviceRemovedSpy(mgr, SIGNAL(deviceRemoved(Core::Id)));
QSignalSpy deviceUpdatedSpy(mgr, SIGNAL(deviceUpdated(Core::Id)));
- QSignalSpy deviceListChangedSpy(mgr, SIGNAL(deviceListChanged()));
+ QSignalSpy deviceListReplacedSpy(mgr, SIGNAL(deviceListReplaced()));
QSignalSpy updatedSpy(mgr, SIGNAL(updated()));
mgr->addDevice(dev);
@@ -465,7 +469,7 @@ void ProjectExplorerPlugin::testDeviceManager()
QCOMPARE(deviceAddedSpy.count(), 1);
QCOMPARE(deviceRemovedSpy.count(), 0);
QCOMPARE(deviceUpdatedSpy.count(), 0);
- QCOMPARE(deviceListChangedSpy.count(), 0);
+ QCOMPARE(deviceListReplacedSpy.count(), 0);
QCOMPARE(updatedSpy.count(), 1);
deviceAddedSpy.clear();
updatedSpy.clear();
@@ -474,7 +478,7 @@ void ProjectExplorerPlugin::testDeviceManager()
QCOMPARE(deviceAddedSpy.count(), 0);
QCOMPARE(deviceRemovedSpy.count(), 0);
QCOMPARE(deviceUpdatedSpy.count(), 0);
- QCOMPARE(deviceListChangedSpy.count(), 0);
+ QCOMPARE(deviceListReplacedSpy.count(), 0);
QCOMPARE(updatedSpy.count(), 0);
mgr->setDeviceState(dev->id(), IDevice::DeviceReadyToUse);
@@ -482,7 +486,7 @@ void ProjectExplorerPlugin::testDeviceManager()
QCOMPARE(deviceAddedSpy.count(), 0);
QCOMPARE(deviceRemovedSpy.count(), 0);
QCOMPARE(deviceUpdatedSpy.count(), 1);
- QCOMPARE(deviceListChangedSpy.count(), 0);
+ QCOMPARE(deviceListReplacedSpy.count(), 0);
QCOMPARE(updatedSpy.count(), 1);
deviceUpdatedSpy.clear();
updatedSpy.clear();
@@ -493,7 +497,7 @@ void ProjectExplorerPlugin::testDeviceManager()
QCOMPARE(deviceAddedSpy.count(), 0);
QCOMPARE(deviceRemovedSpy.count(), 0);
QCOMPARE(deviceUpdatedSpy.count(), 1);
- QCOMPARE(deviceListChangedSpy.count(), 0);
+ QCOMPARE(deviceListReplacedSpy.count(), 0);
QCOMPARE(updatedSpy.count(), 1);
deviceUpdatedSpy.clear();
updatedSpy.clear();
@@ -508,7 +512,7 @@ void ProjectExplorerPlugin::testDeviceManager()
QCOMPARE(deviceAddedSpy.count(), 1);
QCOMPARE(deviceRemovedSpy.count(), 0);
QCOMPARE(deviceUpdatedSpy.count(), 0);
- QCOMPARE(deviceListChangedSpy.count(), 0);
+ QCOMPARE(deviceListReplacedSpy.count(), 0);
QCOMPARE(updatedSpy.count(), 1);
deviceAddedSpy.clear();
updatedSpy.clear();
@@ -521,7 +525,7 @@ void ProjectExplorerPlugin::testDeviceManager()
QCOMPARE(deviceAddedSpy.count(), 0);
QCOMPARE(deviceRemovedSpy.count(), 2);
// QCOMPARE(deviceUpdatedSpy.count(), 0); Uncomment once the "default" stuff is gone.
- QCOMPARE(deviceListChangedSpy.count(), 0);
+ QCOMPARE(deviceListReplacedSpy.count(), 0);
QCOMPARE(updatedSpy.count(), 2);
}
diff --git a/src/plugins/projectexplorer/devicesupport/devicemanager.h b/src/plugins/projectexplorer/devicesupport/devicemanager.h
index 0255b9699d..a2a6656146 100644
--- a/src/plugins/projectexplorer/devicesupport/devicemanager.h
+++ b/src/plugins/projectexplorer/devicesupport/devicemanager.h
@@ -76,7 +76,7 @@ signals:
void deviceAdded(Core::Id id);
void deviceRemoved(Core::Id id);
void deviceUpdated(Core::Id id);
- void deviceListChanged();
+ void deviceListReplaced(); // For bulk changes via the settings dialog.
void updated(); // Emitted for all of the above.
void devicesLoaded(); // Emitted once load() is done
diff --git a/src/plugins/projectexplorer/devicesupport/devicemanagermodel.cpp b/src/plugins/projectexplorer/devicesupport/devicemanagermodel.cpp
index c935d41af8..67c173f13e 100644
--- a/src/plugins/projectexplorer/devicesupport/devicemanagermodel.cpp
+++ b/src/plugins/projectexplorer/devicesupport/devicemanagermodel.cpp
@@ -54,7 +54,7 @@ DeviceManagerModel::DeviceManagerModel(const DeviceManager *deviceManager, QObje
connect(deviceManager, SIGNAL(deviceAdded(Core::Id)), SLOT(handleDeviceAdded(Core::Id)));
connect(deviceManager, SIGNAL(deviceRemoved(Core::Id)), SLOT(handleDeviceRemoved(Core::Id)));
connect(deviceManager, SIGNAL(deviceUpdated(Core::Id)), SLOT(handleDeviceUpdated(Core::Id)));
- connect(deviceManager, SIGNAL(deviceListChanged()), SLOT(handleDeviceListChanged()));
+ connect(deviceManager, SIGNAL(deviceListReplaced()), SLOT(handleDeviceListChanged()));
}
DeviceManagerModel::~DeviceManagerModel()
diff --git a/src/plugins/projectexplorer/devicesupport/deviceprocess.cpp b/src/plugins/projectexplorer/devicesupport/deviceprocess.cpp
new file mode 100644
index 0000000000..aa2f8c748c
--- /dev/null
+++ b/src/plugins/projectexplorer/devicesupport/deviceprocess.cpp
@@ -0,0 +1,52 @@
+/****************************************************************************
+**
+** 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 "deviceprocess.h"
+
+#include "idevice.h"
+
+#include <utils/qtcassert.h>
+
+namespace ProjectExplorer {
+
+DeviceProcess::DeviceProcess(const IDevice::ConstPtr &device, QObject *parent)
+ : QObject(parent), m_device(device)
+{
+}
+
+DeviceProcess::~DeviceProcess()
+{
+}
+
+IDevice::ConstPtr DeviceProcess::device() const
+{
+ return m_device;
+}
+
+} // namespace ProjectExplorer
diff --git a/src/plugins/debugger/gdb/abstractgdbprocess.h b/src/plugins/projectexplorer/devicesupport/deviceprocess.h
index 22b3385601..ebaf2b6ef3 100644
--- a/src/plugins/debugger/gdb/abstractgdbprocess.h
+++ b/src/plugins/projectexplorer/devicesupport/deviceprocess.h
@@ -27,47 +27,63 @@
**
****************************************************************************/
-#ifndef ABSTRACTGDBPROCESS_H
-#define ABSTRACTGDBPROCESS_H
+#ifndef QTC_DEVICEPROCESS_H
+#define QTC_DEVICEPROCESS_H
+#include "../projectexplorer_export.h"
+
+#include <QObject>
#include <QProcess>
+#include <QSharedPointer>
+#include <QStringList>
+
+namespace Utils { class Environment; }
-namespace Debugger {
-namespace Internal {
+namespace ProjectExplorer {
+class IDevice;
-class AbstractGdbProcess : public QObject
+class PROJECTEXPLORER_EXPORT DeviceProcess : public QObject
{
Q_OBJECT
-
-protected:
- explicit AbstractGdbProcess(QObject *parent = 0) : QObject(parent) {}
-
public:
- virtual QByteArray readAllStandardOutput() = 0;
- virtual QByteArray readAllStandardError() = 0;
+ virtual ~DeviceProcess();
- virtual void start(const QString &cmd, const QStringList &args) = 0;
- virtual bool waitForStarted() = 0;
- virtual qint64 write(const QByteArray &data) = 0;
+ virtual void start(const QString &executable, const QStringList &arguments = QStringList()) = 0;
+ virtual void interrupt() = 0;
+ virtual void terminate() = 0;
virtual void kill() = 0;
- virtual bool interrupt() = 0;
virtual QProcess::ProcessState state() const = 0;
+ virtual QProcess::ExitStatus exitStatus() const = 0;
+ virtual int exitCode() const = 0;
virtual QString errorString() const = 0;
- virtual QProcessEnvironment processEnvironment() const = 0;
- virtual void setProcessEnvironment(const QProcessEnvironment &env) = 0;
- virtual void setEnvironment(const QStringList &env) = 0;
- virtual void setWorkingDirectory(const QString &dir) = 0;
+ virtual Utils::Environment environment() const = 0;
+ virtual void setEnvironment(const Utils::Environment &env) = 0;
+
+ virtual void setWorkingDirectory(const QString &workingDirectory) = 0;
+
+ virtual QByteArray readAllStandardOutput() = 0;
+ virtual QByteArray readAllStandardError() = 0;
+
+ virtual qint64 write(const QByteArray &data) = 0;
signals:
- void error(QProcess::ProcessError);
- void finished(int exitCode, QProcess::ExitStatus exitStatus);
- void readyReadStandardError();
+ void started();
+ void finished();
+ void error(QProcess::ProcessError error);
+
void readyReadStandardOutput();
+ void readyReadStandardError();
+
+protected:
+ DeviceProcess(const QSharedPointer<const IDevice> &device, QObject *parent = 0);
+ QSharedPointer<const IDevice> device() const;
+
+private:
+ const QSharedPointer<const IDevice> m_device;
};
-} // namespace Internal
-} // namespace Debugger
+} // namespace ProjectExplorer
-#endif // ABSTRACTGDBPROCESS_H
+#endif // Include guard.
diff --git a/src/plugins/projectexplorer/devicesupport/deviceprocessesdialog.cpp b/src/plugins/projectexplorer/devicesupport/deviceprocessesdialog.cpp
index 289d61b0a3..5f898465cd 100644
--- a/src/plugins/projectexplorer/devicesupport/deviceprocessesdialog.cpp
+++ b/src/plugins/projectexplorer/devicesupport/deviceprocessesdialog.cpp
@@ -27,10 +27,10 @@
**
****************************************************************************/
-#include "devicesupport/deviceprocessesdialog.h"
-#include "devicesupport/deviceprocesslist.h"
-#include "kitchooser.h"
-#include "kitinformation.h"
+#include "deviceprocessesdialog.h"
+#include "deviceprocesslist.h"
+#include <projectexplorer/kitchooser.h>
+#include <projectexplorer/kitinformation.h>
#include <utils/filterlineedit.h>
#include <utils/qtcassert.h>
@@ -104,7 +104,7 @@ public slots:
void handleProcessListUpdated();
void handleProcessKilled();
void updateButtons();
- DeviceProcess selectedProcess() const;
+ DeviceProcessItem selectedProcess() const;
public:
QWidget *q;
@@ -277,11 +277,11 @@ void DeviceProcessesDialogPrivate::updateButtons()
errorText->setVisible(!errorText->document()->isEmpty());
}
-DeviceProcess DeviceProcessesDialogPrivate::selectedProcess() const
+DeviceProcessItem DeviceProcessesDialogPrivate::selectedProcess() const
{
const QModelIndexList indexes = procView->selectionModel()->selectedIndexes();
if (indexes.empty() || !processList)
- return DeviceProcess();
+ return DeviceProcessItem();
return processList->at(proxyModel.mapToSource(indexes.first()).row());
}
@@ -355,7 +355,7 @@ void DeviceProcessesDialog::showAllDevices()
d->updateDevice();
}
-DeviceProcess DeviceProcessesDialog::currentProcess() const
+DeviceProcessItem DeviceProcessesDialog::currentProcess() const
{
return d->selectedProcess();
}
diff --git a/src/plugins/projectexplorer/devicesupport/deviceprocessesdialog.h b/src/plugins/projectexplorer/devicesupport/deviceprocessesdialog.h
index e67d2c1001..8ab99e9022 100644
--- a/src/plugins/projectexplorer/devicesupport/deviceprocessesdialog.h
+++ b/src/plugins/projectexplorer/devicesupport/deviceprocessesdialog.h
@@ -38,7 +38,7 @@
namespace ProjectExplorer {
-class DeviceProcess;
+class DeviceProcessItem;
class KitChooser;
namespace Internal { class DeviceProcessesDialogPrivate; }
@@ -55,7 +55,7 @@ public:
void setDevice(const IDevice::ConstPtr &device);
void showAllDevices();
- DeviceProcess currentProcess() const;
+ DeviceProcessItem currentProcess() const;
KitChooser *kitChooser() const;
void logMessage(const QString &line);
DeviceProcessesDialog(KitChooser *chooser, QWidget *parent);
diff --git a/src/plugins/projectexplorer/devicesupport/deviceprocesslist.cpp b/src/plugins/projectexplorer/devicesupport/deviceprocesslist.cpp
index cd1b54cb93..1eca3c7e1b 100644
--- a/src/plugins/projectexplorer/devicesupport/deviceprocesslist.cpp
+++ b/src/plugins/projectexplorer/devicesupport/deviceprocesslist.cpp
@@ -46,7 +46,7 @@ public:
{ }
const IDevice::ConstPtr device;
- QList<DeviceProcess> remoteProcesses;
+ QList<DeviceProcessItem> remoteProcesses;
State state;
};
@@ -96,7 +96,7 @@ void DeviceProcessList::update()
doUpdate();
}
-void DeviceProcessList::reportProcessListUpdated(const QList<DeviceProcess> &processes)
+void DeviceProcessList::reportProcessListUpdated(const QList<DeviceProcessItem> &processes)
{
QTC_ASSERT(d->state == Listing, return);
setFinished();
@@ -125,7 +125,7 @@ void DeviceProcessList::reportProcessKilled()
emit processKilled();
}
-DeviceProcess DeviceProcessList::at(int row) const
+DeviceProcessItem DeviceProcessList::at(int row) const
{
return d->remoteProcesses.at(row);
}
@@ -156,7 +156,7 @@ QVariant DeviceProcessList::data(const QModelIndex &index, int role) const
return QVariant();
if (role == Qt::DisplayRole || role == Qt::ToolTipRole) {
- const DeviceProcess &proc = d->remoteProcesses.at(index.row());
+ const DeviceProcessItem &proc = d->remoteProcesses.at(index.row());
if (index.column() == 0)
return proc.pid;
else
@@ -182,12 +182,12 @@ void DeviceProcessList::reportError(const QString &message)
emit error(message);
}
-QList<DeviceProcess> DeviceProcessList::localProcesses()
+QList<DeviceProcessItem> DeviceProcessList::localProcesses()
{
return LocalProcessList::getLocalProcesses();
}
-bool DeviceProcess::operator <(const DeviceProcess &other) const
+bool DeviceProcessItem::operator <(const DeviceProcessItem &other) const
{
if (pid != other.pid)
return pid < other.pid;
diff --git a/src/plugins/projectexplorer/devicesupport/deviceprocesslist.h b/src/plugins/projectexplorer/devicesupport/deviceprocesslist.h
index 9bb129bf04..915b0676aa 100644
--- a/src/plugins/projectexplorer/devicesupport/deviceprocesslist.h
+++ b/src/plugins/projectexplorer/devicesupport/deviceprocesslist.h
@@ -39,11 +39,11 @@ namespace ProjectExplorer {
namespace Internal { class DeviceProcessListPrivate; }
-class PROJECTEXPLORER_EXPORT DeviceProcess
+class PROJECTEXPLORER_EXPORT DeviceProcessItem
{
public:
- DeviceProcess() : pid(0) {}
- bool operator<(const DeviceProcess &other) const;
+ DeviceProcessItem() : pid(0) {}
+ bool operator<(const DeviceProcessItem &other) const;
int pid;
QString cmdLine;
@@ -60,9 +60,9 @@ public:
void update();
void killProcess(int row);
- DeviceProcess at(int row) const;
+ DeviceProcessItem at(int row) const;
- static QList<DeviceProcess> localProcesses();
+ static QList<DeviceProcessItem> localProcesses();
signals:
void processListUpdated();
@@ -72,7 +72,7 @@ signals:
protected:
void reportError(const QString &message);
void reportProcessKilled();
- void reportProcessListUpdated(const QList<DeviceProcess> &processes);
+ void reportProcessListUpdated(const QList<DeviceProcessItem> &processes);
IDevice::ConstPtr device() const;
@@ -87,7 +87,7 @@ private:
bool hasChildren(const QModelIndex &parent) const;
virtual void doUpdate() = 0;
- virtual void doKillProcess(const DeviceProcess &process) = 0;
+ virtual void doKillProcess(const DeviceProcessItem &process) = 0;
void setFinished();
diff --git a/src/plugins/projectexplorer/devicesupport/devicesettingswidget.cpp b/src/plugins/projectexplorer/devicesupport/devicesettingswidget.cpp
index fb3a428752..b7f62a22a9 100644
--- a/src/plugins/projectexplorer/devicesupport/devicesettingswidget.cpp
+++ b/src/plugins/projectexplorer/devicesupport/devicesettingswidget.cpp
@@ -29,14 +29,15 @@
#include "devicesettingswidget.h"
#include "ui_devicesettingswidget.h"
-#include "projectexplorerconstants.h"
#include "devicefactoryselectiondialog.h"
#include "devicemanager.h"
#include "devicemanagermodel.h"
#include "deviceprocessesdialog.h"
+#include "devicetestdialog.h"
#include "idevice.h"
#include "idevicefactory.h"
#include "idevicewidget.h"
+#include <projectexplorer/projectexplorerconstants.h>
#include <coreplugin/icore.h>
#include <extensionsystem/pluginmanager.h>
@@ -167,6 +168,8 @@ void DeviceSettingsWidget::addDevice()
m_deviceManager->addDevice(device);
m_ui->removeConfigButton->setEnabled(true);
m_ui->configurationComboBox->setCurrentIndex(m_deviceManagerModel->indexOf(device));
+ if (device->hasDeviceTester())
+ testDevice();
}
void DeviceSettingsWidget::removeDevice()
@@ -262,6 +265,14 @@ void DeviceSettingsWidget::setDefaultDevice()
m_ui->defaultDeviceButton->setEnabled(false);
}
+void DeviceSettingsWidget::testDevice()
+{
+ const IDevice::ConstPtr &device = currentDevice();
+ QTC_ASSERT(device && device->hasDeviceTester(), return);
+ DeviceTestDialog dlg(device, this);
+ dlg.exec();
+}
+
void DeviceSettingsWidget::handleDeviceUpdated(Id id)
{
const int index = m_deviceManagerModel->indexForId(id);
@@ -286,6 +297,13 @@ void DeviceSettingsWidget::currentDeviceChanged(int index)
setDeviceInfoWidgetsEnabled(true);
m_ui->removeConfigButton->setEnabled(true);
+ if (device->hasDeviceTester()) {
+ QPushButton * const button = new QPushButton(tr("Test"));
+ m_additionalActionButtons << button;
+ connect(button, SIGNAL(clicked()), SLOT(testDevice()));
+ m_ui->buttonsLayout->insertWidget(m_ui->buttonsLayout->count() - 1, button);
+ }
+
if (device->canCreateProcessModel()) {
QPushButton * const button = new QPushButton(tr("Show Running Processes"));
m_additionalActionButtons << button;
@@ -318,10 +336,13 @@ void DeviceSettingsWidget::clearDetails()
void DeviceSettingsWidget::handleAdditionalActionRequest(int actionId)
{
- const IDevice::ConstPtr device = m_deviceManager->find(currentDevice()->id());
+ const IDevice::Ptr device = m_deviceManager->mutableDevice(currentDevice()->id());
QTC_ASSERT(device, return);
updateDeviceFromUi();
device->executeAction(Core::Id::fromUniqueIdentifier(actionId), this);
+
+ // Widget must be set up from scratch, because the action could have changed random attributes.
+ currentDeviceChanged(currentIndex());
}
void DeviceSettingsWidget::handleProcessListRequested()
diff --git a/src/plugins/projectexplorer/devicesupport/devicesettingswidget.h b/src/plugins/projectexplorer/devicesupport/devicesettingswidget.h
index d589400a43..c953fb9a95 100644
--- a/src/plugins/projectexplorer/devicesupport/devicesettingswidget.h
+++ b/src/plugins/projectexplorer/devicesupport/devicesettingswidget.h
@@ -30,7 +30,7 @@
#ifndef DEVICESETTINGSWIDGET_H
#define DEVICESETTINGSWIDGET_H
-#include "devicesupport/idevice.h"
+#include "idevice.h"
#include <QList>
#include <QString>
@@ -68,6 +68,7 @@ private slots:
void removeDevice();
void deviceNameEditingFinished();
void setDefaultDevice();
+ void testDevice();
void handleAdditionalActionRequest(int actionId);
void handleProcessListRequested();
diff --git a/src/plugins/projectexplorer/devicesupport/devicesettingswidget.ui b/src/plugins/projectexplorer/devicesupport/devicesettingswidget.ui
index 8054fb570e..dfffa79cff 100644
--- a/src/plugins/projectexplorer/devicesupport/devicesettingswidget.ui
+++ b/src/plugins/projectexplorer/devicesupport/devicesettingswidget.ui
@@ -6,8 +6,8 @@
<rect>
<x>0</x>
<y>0</y>
- <width>829</width>
- <height>516</height>
+ <width>728</width>
+ <height>429</height>
</rect>
</property>
<property name="windowTitle">
@@ -47,129 +47,124 @@
</layout>
</item>
<item>
- <widget class="QGroupBox" name="generalGroupBox">
- <property name="title">
- <string>General</string>
+ <widget class="QScrollArea" name="scrollArea">
+ <property name="horizontalScrollBarPolicy">
+ <enum>Qt::ScrollBarAlwaysOff</enum>
</property>
- <layout class="QHBoxLayout" name="horizontalLayout_3">
- <item>
- <layout class="QFormLayout" name="formLayout_2">
- <item row="0" column="0">
- <widget class="QLabel" name="deviceNameLabel">
- <property name="text">
- <string>&amp;Name:</string>
- </property>
- <property name="buddy">
- <cstring>nameLineEdit</cstring>
- </property>
- </widget>
- </item>
- <item row="0" column="1">
- <widget class="QLineEdit" name="nameLineEdit"/>
- </item>
- <item row="1" column="0">
- <widget class="QLabel" name="oSTypeLabel">
- <property name="text">
- <string>Type:</string>
- </property>
- </widget>
- </item>
- <item row="1" column="1">
- <widget class="QLabel" name="osTypeValueLabel">
- <property name="text">
- <string/>
- </property>
- </widget>
- </item>
- <item row="2" column="0">
- <widget class="QLabel" name="autoDetectionKeyLabel">
- <property name="text">
- <string>Auto-detected:</string>
- </property>
- </widget>
- </item>
- <item row="2" column="1">
- <widget class="QLabel" name="autoDetectionValueLabel">
- <property name="text">
- <string/>
- </property>
- </widget>
- </item>
- <item row="3" column="0">
- <widget class="QLabel" name="deviceStateKeyLabel">
- <property name="text">
- <string>Current state:</string>
- </property>
- </widget>
- </item>
- <item row="3" column="1">
- <layout class="QHBoxLayout" name="horizontalLayout_2">
- <item>
- <widget class="QLabel" name="deviceStateValueIconLabel"/>
- </item>
- <item>
- <widget class="QLabel" name="deviceStateValueTextLabel"/>
- </item>
+ <property name="widgetResizable">
+ <bool>true</bool>
+ </property>
+ <widget class="QWidget" name="scrollAreaWidgetContents">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>564</width>
+ <height>360</height>
+ </rect>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout_2">
+ <item>
+ <widget class="QGroupBox" name="generalGroupBox">
+ <property name="title">
+ <string>General</string>
+ </property>
+ <layout class="QHBoxLayout" name="horizontalLayout_3">
<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>
+ <layout class="QFormLayout" name="formLayout_2">
+ <item row="0" column="0">
+ <widget class="QLabel" name="deviceNameLabel">
+ <property name="text">
+ <string>&amp;Name:</string>
+ </property>
+ <property name="buddy">
+ <cstring>nameLineEdit</cstring>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="1">
+ <widget class="QLineEdit" name="nameLineEdit"/>
+ </item>
+ <item row="1" column="0">
+ <widget class="QLabel" name="oSTypeLabel">
+ <property name="text">
+ <string>Type:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="1">
+ <widget class="QLabel" name="osTypeValueLabel">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="0">
+ <widget class="QLabel" name="autoDetectionKeyLabel">
+ <property name="text">
+ <string>Auto-detected:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="1">
+ <widget class="QLabel" name="autoDetectionValueLabel">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ <item row="3" column="0">
+ <widget class="QLabel" name="deviceStateKeyLabel">
+ <property name="text">
+ <string>Current state:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="3" column="1">
+ <layout class="QHBoxLayout" name="horizontalLayout_2">
+ <item>
+ <widget class="QLabel" name="deviceStateValueIconLabel"/>
+ </item>
+ <item>
+ <widget class="QLabel" name="deviceStateValueTextLabel"/>
+ </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>
</item>
</layout>
- </item>
- </layout>
- </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>
- </item>
- <item>
- <widget class="QGroupBox" name="osSpecificGroupBox">
- <property name="minimumSize">
- <size>
- <width>0</width>
- <height>25</height>
- </size>
- </property>
- <property name="title">
- <string>Type Specific</string>
- </property>
- <layout class="QVBoxLayout" name="verticalLayout"/>
+ </widget>
+ </item>
+ <item>
+ <widget class="QGroupBox" name="osSpecificGroupBox">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Preferred" vsizetype="Expanding">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="title">
+ <string>Type Specific</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
</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>
</item>
<item>
diff --git a/src/plugins/remotelinux/linuxdevicetestdialog.cpp b/src/plugins/projectexplorer/devicesupport/devicetestdialog.cpp
index 63605db74d..ef09413a2f 100644
--- a/src/plugins/remotelinux/linuxdevicetestdialog.cpp
+++ b/src/plugins/projectexplorer/devicesupport/devicetestdialog.cpp
@@ -26,8 +26,8 @@
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
-#include "linuxdevicetestdialog.h"
-#include "ui_linuxdevicetestdialog.h"
+#include "devicetestdialog.h"
+#include "ui_devicetestdialog.h"
#include <QBrush>
#include <QColor>
@@ -35,72 +35,70 @@
#include <QPushButton>
#include <QTextCharFormat>
-namespace RemoteLinux {
+namespace ProjectExplorer {
namespace Internal {
-class LinuxDeviceTestDialogPrivate {
+
+class DeviceTestDialog::DeviceTestDialogPrivate
+{
public:
- LinuxDeviceTestDialogPrivate(AbstractLinuxDeviceTester *tester)
+ DeviceTestDialogPrivate(DeviceTester *tester)
: deviceTester(tester), finished(false)
{
}
- Ui::LinuxDeviceTestDialog ui;
- AbstractLinuxDeviceTester * const deviceTester;
+ Ui::DeviceTestDialog ui;
+ DeviceTester * const deviceTester;
bool finished;
};
-} // namespace Internal
-
-using namespace Internal;
-
-LinuxDeviceTestDialog::LinuxDeviceTestDialog(const ProjectExplorer::IDevice::ConstPtr &deviceConfiguration,
- AbstractLinuxDeviceTester *deviceTester, QWidget *parent)
- : QDialog(parent), d(new LinuxDeviceTestDialogPrivate(deviceTester))
+DeviceTestDialog::DeviceTestDialog(const ProjectExplorer::IDevice::ConstPtr &deviceConfiguration,
+ QWidget *parent)
+ : QDialog(parent), d(new DeviceTestDialogPrivate(deviceConfiguration->createDeviceTester()))
{
d->ui.setupUi(this);
d->deviceTester->setParent(this);
connect(d->deviceTester, SIGNAL(progressMessage(QString)), SLOT(handleProgressMessage(QString)));
connect(d->deviceTester, SIGNAL(errorMessage(QString)), SLOT(handleErrorMessage(QString)));
- connect(d->deviceTester, SIGNAL(finished(RemoteLinux::AbstractLinuxDeviceTester::TestResult)),
- SLOT(handleTestFinished(RemoteLinux::AbstractLinuxDeviceTester::TestResult)));
+ connect(d->deviceTester, SIGNAL(finished(ProjectExplorer::DeviceTester::TestResult)),
+ SLOT(handleTestFinished(ProjectExplorer::DeviceTester::TestResult)));
d->deviceTester->testDevice(deviceConfiguration);
}
-LinuxDeviceTestDialog::~LinuxDeviceTestDialog()
+DeviceTestDialog::~DeviceTestDialog()
{
delete d;
}
-void LinuxDeviceTestDialog::reject()
+void DeviceTestDialog::reject()
{
if (!d->finished)
d->deviceTester->stopTest();
QDialog::reject();
}
-void LinuxDeviceTestDialog::handleProgressMessage(const QString &message)
+void DeviceTestDialog::handleProgressMessage(const QString &message)
{
addText(message, QLatin1String("black"), false);
}
-void LinuxDeviceTestDialog::handleErrorMessage(const QString &message)
+void DeviceTestDialog::handleErrorMessage(const QString &message)
{
addText(message, QLatin1String("red"), false);
}
-void LinuxDeviceTestDialog::handleTestFinished(AbstractLinuxDeviceTester::TestResult result)
+void DeviceTestDialog::handleTestFinished(ProjectExplorer::DeviceTester::TestResult result)
{
d->finished = true;
d->ui.buttonBox->button(QDialogButtonBox::Cancel)->setText(tr("Close"));
- if (result == AbstractLinuxDeviceTester::TestSuccess)
+ if (result == ProjectExplorer::DeviceTester::TestSuccess)
addText(tr("Device test finished successfully."), QLatin1String("blue"), true);
else
addText(tr("Device test failed."), QLatin1String("red"), true);
}
-void LinuxDeviceTestDialog::addText(const QString &text, const QString &color, bool bold)
+void DeviceTestDialog::addText(const QString &text, const QString &color, bool bold)
{
QTextCharFormat format = d->ui.textEdit->currentCharFormat();
format.setForeground(QBrush(QColor(color)));
@@ -111,4 +109,5 @@ void LinuxDeviceTestDialog::addText(const QString &text, const QString &color, b
d->ui.textEdit->appendPlainText(text);
}
-} // namespace RemoteLinux
+} // namespace Internal
+} // namespace ProjectExplorer
diff --git a/src/plugins/remotelinux/linuxdevicetestdialog.h b/src/plugins/projectexplorer/devicesupport/devicetestdialog.h
index 1ac3535735..e07493e398 100644
--- a/src/plugins/remotelinux/linuxdevicetestdialog.h
+++ b/src/plugins/projectexplorer/devicesupport/devicetestdialog.h
@@ -26,42 +26,39 @@
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
-#ifndef LINUXDEVICETESTDIALOG_H
-#define LINUXDEVICETESTDIALOG_H
+#ifndef DEVICETESTDIALOG_H
+#define DEVICETESTDIALOG_H
-#include "linuxdevicetester.h"
-#include "remotelinux_export.h"
+#include "idevice.h"
#include <QDialog>
-namespace RemoteLinux {
+namespace ProjectExplorer {
namespace Internal {
-class LinuxDeviceTestDialogPrivate;
-} // namespace Internal
-class REMOTELINUX_EXPORT LinuxDeviceTestDialog : public QDialog
+class DeviceTestDialog : public QDialog
{
Q_OBJECT
public:
- // Note: The dialog takes ownership of deviceTester
- LinuxDeviceTestDialog(const ProjectExplorer::IDevice::ConstPtr &deviceConfiguration,
- AbstractLinuxDeviceTester * deviceTester, QWidget *parent = 0);
- ~LinuxDeviceTestDialog();
+ DeviceTestDialog(const IDevice::ConstPtr &deviceConfiguration, QWidget *parent = 0);
+ ~DeviceTestDialog();
void reject();
private slots:
void handleProgressMessage(const QString &message);
void handleErrorMessage(const QString &message);
- void handleTestFinished(RemoteLinux::AbstractLinuxDeviceTester::TestResult result);
+ void handleTestFinished(ProjectExplorer::DeviceTester::TestResult result);
private:
void addText(const QString &text, const QString &color, bool bold);
- Internal::LinuxDeviceTestDialogPrivate * const d;
+ class DeviceTestDialogPrivate;
+ DeviceTestDialogPrivate * const d;
};
-} // namespace RemoteLinux
+} // namespace Internal
+} // namespace ProjectExplorer
-#endif // LINUXDEVICETESTDIALOG_H
+#endif // Include guard.
diff --git a/src/plugins/remotelinux/linuxdevicetestdialog.ui b/src/plugins/projectexplorer/devicesupport/devicetestdialog.ui
index 4160d13452..b640f722d4 100644
--- a/src/plugins/remotelinux/linuxdevicetestdialog.ui
+++ b/src/plugins/projectexplorer/devicesupport/devicetestdialog.ui
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
- <class>RemoteLinux::Internal::LinuxDeviceTestDialog</class>
- <widget class="QDialog" name="RemoteLinux::Internal::LinuxDeviceTestDialog">
+ <class>ProjectExplorer::Internal::DeviceTestDialog</class>
+ <widget class="QDialog" name="ProjectExplorer::Internal::DeviceTestDialog">
<property name="geometry">
<rect>
<x>0</x>
@@ -38,7 +38,7 @@
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
- <receiver>RemoteLinux::Internal::LinuxDeviceTestDialog</receiver>
+ <receiver>ProjectExplorer::Internal::DeviceTestDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
@@ -54,7 +54,7 @@
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
- <receiver>RemoteLinux::Internal::LinuxDeviceTestDialog</receiver>
+ <receiver>ProjectExplorer::Internal::DeviceTestDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
diff --git a/src/plugins/projectexplorer/devicesupport/deviceusedportsgatherer.cpp b/src/plugins/projectexplorer/devicesupport/deviceusedportsgatherer.cpp
index 73b4b83941..2e89492e5f 100644
--- a/src/plugins/projectexplorer/devicesupport/deviceusedportsgatherer.cpp
+++ b/src/plugins/projectexplorer/devicesupport/deviceusedportsgatherer.cpp
@@ -72,7 +72,7 @@ void DeviceUsedPortsGatherer::start(const IDevice::ConstPtr &device)
QTC_ASSERT(device && device->portsGatheringMethod(), return);
d->device = device;
- d->connection = SshConnectionManager::instance().acquireConnection(device->sshParameters());
+ d->connection = QSsh::acquireConnection(device->sshParameters());
connect(d->connection, SIGNAL(error(QSsh::SshError)), SLOT(handleConnectionError()));
if (d->connection->state() == SshConnection::Connected) {
handleConnectionEstablished();
@@ -108,7 +108,7 @@ void DeviceUsedPortsGatherer::stop()
disconnect(d->process.data(), 0, this, 0);
d->process.clear();
disconnect(d->connection, 0, this, 0);
- SshConnectionManager::instance().releaseConnection(d->connection);
+ QSsh::releaseConnection(d->connection);
d->connection = 0;
}
diff --git a/src/plugins/projectexplorer/devicesupport/idevice.cpp b/src/plugins/projectexplorer/devicesupport/idevice.cpp
index c252499213..304991c86d 100644
--- a/src/plugins/projectexplorer/devicesupport/idevice.cpp
+++ b/src/plugins/projectexplorer/devicesupport/idevice.cpp
@@ -120,8 +120,10 @@ const char KeyFileKey[] = "KeyFile";
const char PasswordKey[] = "Password";
const char TimeoutKey[] = "Timeout";
+const char DebugServerKey[] = "DebugServerKey";
+
typedef QSsh::SshConnectionParameters::AuthenticationType AuthType;
-const AuthType DefaultAuthType = QSsh::SshConnectionParameters::AuthenticationByKey;
+const AuthType DefaultAuthType = QSsh::SshConnectionParameters::AuthenticationTypePublicKey;
const IDevice::MachineType DefaultMachineType = IDevice::Hardware;
const int DefaultTimeout = 10;
@@ -147,11 +149,12 @@ public:
QSsh::SshConnectionParameters sshParameters;
Utils::PortList freePorts;
+ QString debugServerPath;
};
} // namespace Internal
PortsGatheringMethod::~PortsGatheringMethod() { }
-DeviceProcessSupport::~DeviceProcessSupport() { }
+DeviceTester::DeviceTester(QObject *parent) : QObject(parent) { }
IDevice::IDevice() : d(new Internal::IDevicePrivate)
{ }
@@ -236,11 +239,6 @@ Core::Id IDevice::id() const
return d->id;
}
-DeviceProcessSupport::Ptr IDevice::processSupport() const
-{
- return DeviceProcessSupport::Ptr();
-}
-
PortsGatheringMethod::Ptr IDevice::portsGatheringMethod() const
{
return PortsGatheringMethod::Ptr();
@@ -253,6 +251,18 @@ DeviceProcessList *IDevice::createProcessListModel(QObject *parent) const
return 0;
}
+DeviceTester *IDevice::createDeviceTester() const
+{
+ QTC_ASSERT(false, qDebug("This should not have been called..."));
+ return 0;
+}
+
+DeviceProcess *IDevice::createProcess(QObject * /* parent */) const
+{
+ QTC_CHECK(false);
+ return 0;
+}
+
IDevice::DeviceState IDevice::deviceState() const
{
return d->deviceState;
@@ -303,6 +313,8 @@ void IDevice::fromMap(const QVariantMap &map)
QLatin1String("10000-10100")).toString());
d->machineType = static_cast<MachineType>(map.value(QLatin1String(MachineTypeKey), DefaultMachineType).toInt());
d->version = map.value(QLatin1String(VersionKey), 0).toInt();
+
+ d->debugServerPath = map.value(QLatin1String(DebugServerKey)).toString();
}
/*!
@@ -331,6 +343,8 @@ QVariantMap IDevice::toMap() const
map.insert(QLatin1String(PortsSpecKey), d->freePorts.toString());
map.insert(QLatin1String(VersionKey), d->version);
+ map.insert(QLatin1String(DebugServerKey), d->debugServerPath);
+
return map;
}
@@ -381,6 +395,16 @@ IDevice::MachineType IDevice::machineType() const
return d->machineType;
}
+QString IDevice::debugServerPath() const
+{
+ return d->debugServerPath;
+}
+
+void IDevice::setDebugServerPath(const QString &path)
+{
+ d->debugServerPath = path;
+}
+
int IDevice::version() const
{
return d->version;
@@ -397,4 +421,9 @@ QString IDevice::defaultPublicKeyFilePath()
return defaultPrivateKeyFilePath() + QLatin1String(".pub");
}
+DeviceProcessSignalOperation::DeviceProcessSignalOperation()
+ : m_specialInterrupt(NoSpecialInterrupt)
+{
+}
+
} // namespace ProjectExplorer
diff --git a/src/plugins/projectexplorer/devicesupport/idevice.h b/src/plugins/projectexplorer/devicesupport/idevice.h
index 3d54eb48ca..9b0df7453c 100644
--- a/src/plugins/projectexplorer/devicesupport/idevice.h
+++ b/src/plugins/projectexplorer/devicesupport/idevice.h
@@ -35,11 +35,11 @@
#include <QAbstractSocket>
#include <QList>
+#include <QObject>
#include <QSharedPointer>
#include <QVariantMap>
QT_BEGIN_NAMESPACE
-class QObject;
class QWidget;
QT_END_NAMESPACE
@@ -47,20 +47,38 @@ namespace QSsh { class SshConnectionParameters; }
namespace Utils { class PortList; }
namespace ProjectExplorer {
+class DeviceProcess;
class DeviceProcessList;
namespace Internal { class IDevicePrivate; }
class IDeviceWidget;
+class DeviceTester;
-class PROJECTEXPLORER_EXPORT DeviceProcessSupport
+class PROJECTEXPLORER_EXPORT DeviceProcessSignalOperation : public QObject
{
+ Q_OBJECT
public:
- typedef QSharedPointer<const DeviceProcessSupport> Ptr;
+ enum SpecialInterrupt { NoSpecialInterrupt, Win32Interrupt, Win64Interrupt };
- virtual ~DeviceProcessSupport();
- virtual QString killProcessByPidCommandLine(int pid) const = 0;
- virtual QString killProcessByNameCommandLine(const QString &filePath) const = 0;
+ ~DeviceProcessSignalOperation() {}
+ typedef QSharedPointer<DeviceProcessSignalOperation> Ptr;
+
+ virtual void killProcess(int pid) = 0;
+ virtual void killProcess(const QString &filePath) = 0;
+ virtual void interruptProcess(int pid) = 0;
+ virtual void interruptProcess(const QString &filePath) = 0;
+
+ void setSpecialInterrupt(SpecialInterrupt si);
+
+signals:
+ // If the error message is empty the operation was successful
+ void finished(const QString &errorMessage);
+
+protected:
+ explicit DeviceProcessSignalOperation();
+ QString m_errorMessage;
+ SpecialInterrupt m_specialInterrupt;
};
class PROJECTEXPLORER_EXPORT PortsGatheringMethod
@@ -73,7 +91,6 @@ public:
virtual QList<int> usedPorts(const QByteArray &commandOutput) const = 0;
};
-
// See cpp file for documentation.
class PROJECTEXPLORER_EXPORT IDevice
{
@@ -109,15 +126,20 @@ public:
virtual IDeviceWidget *createWidget() = 0;
virtual QList<Core::Id> actionIds() const = 0;
virtual QString displayNameForActionId(Core::Id actionId) const = 0;
- virtual void executeAction(Core::Id actionId, QWidget *parent = 0) const = 0;
+ virtual void executeAction(Core::Id actionId, QWidget *parent = 0) = 0;
- virtual DeviceProcessSupport::Ptr processSupport() const;
// Devices that can auto detect ports need not return a ports gathering method. Such devices can
// obtain a free port on demand. eg: Desktop device.
virtual bool canAutoDetectPorts() const { return false; }
virtual PortsGatheringMethod::Ptr portsGatheringMethod() const;
virtual bool canCreateProcessModel() const { return false; }
virtual DeviceProcessList *createProcessListModel(QObject *parent = 0) const;
+ virtual bool hasDeviceTester() const { return false; }
+ virtual DeviceTester *createDeviceTester() const;
+
+ virtual bool canCreateProcess() const { return false; }
+ virtual DeviceProcess *createProcess(QObject *parent) const;
+ virtual DeviceProcessSignalOperation::Ptr signalOperation() const = 0;
enum DeviceState { DeviceReadyToUse, DeviceConnected, DeviceDisconnected, DeviceStateUnknown };
DeviceState deviceState() const;
@@ -142,6 +164,9 @@ public:
MachineType machineType() const;
+ QString debugServerPath() const;
+ void setDebugServerPath(const QString &path);
+
protected:
IDevice();
IDevice(Core::Id type, Origin origin, MachineType machineType, Core::Id id = Core::Id());
@@ -159,6 +184,26 @@ private:
friend class DeviceManager;
};
+
+class PROJECTEXPLORER_EXPORT DeviceTester : public QObject
+{
+ Q_OBJECT
+
+public:
+ enum TestResult { TestSuccess, TestFailure };
+
+ virtual void testDevice(const ProjectExplorer::IDevice::ConstPtr &deviceConfiguration) = 0;
+ virtual void stopTest() = 0;
+
+signals:
+ void progressMessage(const QString &message);
+ void errorMessage(const QString &message);
+ void finished(ProjectExplorer::DeviceTester::TestResult result);
+
+protected:
+ explicit DeviceTester(QObject *parent = 0);
+};
+
} // namespace ProjectExplorer
#endif // IDEVICE_H
diff --git a/src/plugins/projectexplorer/devicesupport/localprocesslist.cpp b/src/plugins/projectexplorer/devicesupport/localprocesslist.cpp
index 5670399a35..963895b4a7 100644
--- a/src/plugins/projectexplorer/devicesupport/localprocesslist.cpp
+++ b/src/plugins/projectexplorer/devicesupport/localprocesslist.cpp
@@ -51,9 +51,6 @@
#include <utils/winutils.h>
#include <tlhelp32.h>
#include <psapi.h>
-#ifndef PROCESS_SUSPEND_RESUME
-#define PROCESS_SUSPEND_RESUME 0x0800
-#endif
#endif
namespace ProjectExplorer {
@@ -101,9 +98,9 @@ LocalProcessList::LocalProcessList(const IDevice::ConstPtr &device, QObject *par
{
}
-QList<DeviceProcess> LocalProcessList::getLocalProcesses()
+QList<DeviceProcessItem> LocalProcessList::getLocalProcesses()
{
- QList<DeviceProcess> processes;
+ QList<DeviceProcessItem> processes;
PROCESSENTRY32 pe;
pe.dwSize = sizeof(PROCESSENTRY32);
@@ -112,7 +109,7 @@ QList<DeviceProcess> LocalProcessList::getLocalProcesses()
return processes;
for (bool hasNext = Process32First(snapshot, &pe); hasNext; hasNext = Process32Next(snapshot, &pe)) {
- DeviceProcess p;
+ DeviceProcessItem p;
p.pid = pe.th32ProcessID;
// Image has the absolute path, but can fail.
const QString image = imageName(pe.th32ProcessID);
@@ -125,28 +122,8 @@ QList<DeviceProcess> LocalProcessList::getLocalProcesses()
return processes;
}
-void LocalProcessList::doKillProcess(const DeviceProcess &process)
-{
- const DWORD rights = PROCESS_QUERY_INFORMATION|PROCESS_SET_INFORMATION
- |PROCESS_VM_OPERATION|PROCESS_VM_WRITE|PROCESS_VM_READ
- |PROCESS_DUP_HANDLE|PROCESS_TERMINATE|PROCESS_CREATE_THREAD|PROCESS_SUSPEND_RESUME;
- m_error.clear();
- if (const HANDLE handle = OpenProcess(rights, FALSE, process.pid)) {
- if (!TerminateProcess(handle, UINT(-1))) {
- m_error = tr("Cannot terminate process %1: %2").
- arg(process.pid).arg(Utils::winErrorMessage(GetLastError()));
- }
- CloseHandle(handle);
- } else {
- m_error = tr("Cannot open process %1: %2").
- arg(process.pid).arg(Utils::winErrorMessage(GetLastError()));
- }
- QTimer::singleShot(0, this, SLOT(reportDelayedKillStatus()));
-}
-
#endif //Q_OS_WIN
-
#ifdef Q_OS_UNIX
LocalProcessList::LocalProcessList(const IDevice::ConstPtr &device, QObject *parent)
: DeviceProcessList(device, parent)
@@ -166,15 +143,15 @@ static bool isUnixProcessId(const QString &procname)
static const char procDirC[] = "/proc/";
-static QList<DeviceProcess> getLocalProcessesUsingProc(const QDir &procDir)
+static QList<DeviceProcessItem> getLocalProcessesUsingProc(const QDir &procDir)
{
- QList<DeviceProcess> processes;
+ QList<DeviceProcessItem> processes;
const QString procDirPath = QLatin1String(procDirC);
const QStringList procIds = procDir.entryList();
foreach (const QString &procId, procIds) {
if (!isUnixProcessId(procId))
continue;
- DeviceProcess proc;
+ DeviceProcessItem proc;
proc.pid = procId.toInt();
const QString root = procDirPath + procId;
@@ -216,14 +193,14 @@ static QList<DeviceProcess> getLocalProcessesUsingProc(const QDir &procDir)
}
// Determine UNIX processes by running ps
-static QList<DeviceProcess> getLocalProcessesUsingPs()
+static QList<DeviceProcessItem> getLocalProcessesUsingPs()
{
#ifdef Q_OS_MAC
static const char formatC[] = "pid state command";
#else
static const char formatC[] = "pid,state,cmd";
#endif
- QList<DeviceProcess> processes;
+ QList<DeviceProcessItem> processes;
QProcess psProcess;
QStringList args;
args << QLatin1String("-e") << QLatin1String("-o") << QLatin1String(formatC);
@@ -240,7 +217,7 @@ static QList<DeviceProcess> getLocalProcessesUsingPs()
const int pidSep = line.indexOf(blank);
const int cmdSep = pidSep != -1 ? line.indexOf(blank, pidSep + 1) : -1;
if (cmdSep > 0) {
- DeviceProcess procData;
+ DeviceProcessItem procData;
procData.pid = line.left(pidSep).toInt();
procData.exe = line.mid(cmdSep + 1);
procData.cmdLine = line.mid(cmdSep + 1);
@@ -252,23 +229,22 @@ static QList<DeviceProcess> getLocalProcessesUsingPs()
return processes;
}
-QList<DeviceProcess> LocalProcessList::getLocalProcesses()
+QList<DeviceProcessItem> LocalProcessList::getLocalProcesses()
{
const QDir procDir = QDir(QLatin1String(procDirC));
return procDir.exists() ? getLocalProcessesUsingProc(procDir) : getLocalProcessesUsingPs();
}
-void LocalProcessList::doKillProcess(const DeviceProcess &process)
+#endif // QT_OS_UNIX
+
+void LocalProcessList::doKillProcess(const DeviceProcessItem &process)
{
- if (kill(process.pid, SIGKILL) == -1)
- m_error = QString::fromLocal8Bit(strerror(errno));
- else
- m_error.clear();
- QTimer::singleShot(0, this, SLOT(reportDelayedKillStatus()));
+ DeviceProcessSignalOperation::Ptr signalOperation = device()->signalOperation();
+ connect(signalOperation.data(), SIGNAL(finished(QString)),
+ SLOT(reportDelayedKillStatus(QString)));
+ signalOperation->killProcess(process.pid);
}
-#endif // QT_OS_UNIX
-
Qt::ItemFlags LocalProcessList::flags(const QModelIndex &index) const
{
Qt::ItemFlags flags = DeviceProcessList::flags(index);
@@ -287,12 +263,12 @@ void LocalProcessList::doUpdate()
QTimer::singleShot(0, this, SLOT(handleUpdate()));
}
-void LocalProcessList::reportDelayedKillStatus()
+void LocalProcessList::reportDelayedKillStatus(const QString &errorMessage)
{
- if (m_error.isEmpty())
+ if (errorMessage.isEmpty())
reportProcessKilled();
else
- reportError(m_error);
+ reportError(errorMessage);
}
} // namespace Internal
diff --git a/src/plugins/projectexplorer/devicesupport/localprocesslist.h b/src/plugins/projectexplorer/devicesupport/localprocesslist.h
index ff0ed4a229..8588065ca8 100644
--- a/src/plugins/projectexplorer/devicesupport/localprocesslist.h
+++ b/src/plugins/projectexplorer/devicesupport/localprocesslist.h
@@ -49,19 +49,19 @@ public:
LocalProcessList(const IDevice::ConstPtr &device, QObject *parent = 0);
virtual Qt::ItemFlags flags(const QModelIndex &index) const;
- static QList<DeviceProcess> getLocalProcesses();
+ static QList<DeviceProcessItem> getLocalProcesses();
private:
void doUpdate();
- void doKillProcess(const DeviceProcess &process);
+ void doKillProcess(const DeviceProcessItem &process);
private slots:
void handleUpdate();
- void reportDelayedKillStatus();
+ void reportDelayedKillStatus(const QString &errorMessage);
private:
const qint64 m_myPid;
- QString m_error;
+
};
} // namespace Internal
diff --git a/src/plugins/projectexplorer/devicesupport/sshdeviceprocess.cpp b/src/plugins/projectexplorer/devicesupport/sshdeviceprocess.cpp
new file mode 100644
index 0000000000..af738701d5
--- /dev/null
+++ b/src/plugins/projectexplorer/devicesupport/sshdeviceprocess.cpp
@@ -0,0 +1,331 @@
+/****************************************************************************
+**
+** 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 "sshdeviceprocess.h"
+
+#include "idevice.h"
+
+#include <ssh/sshconnection.h>
+#include <ssh/sshconnectionmanager.h>
+#include <ssh/sshremoteprocess.h>
+#include <utils/environment.h>
+#include <utils/qtcassert.h>
+
+#include <QString>
+
+namespace ProjectExplorer {
+
+class SshDeviceProcess::SshDeviceProcessPrivate
+{
+public:
+ SshDeviceProcessPrivate(SshDeviceProcess *q) : q(q) {}
+
+ SshDeviceProcess * const q;
+ bool serverSupportsSignals;
+ QSsh::SshConnection *connection;
+ QSsh::SshRemoteProcess::Ptr process;
+ QString executable;
+ QStringList arguments;
+ QString errorMessage;
+ QSsh::SshRemoteProcess::ExitStatus exitStatus;
+ QByteArray stdOut;
+ QByteArray stdErr;
+ int exitCode;
+ enum State { Inactive, Connecting, Connected, ProcessRunning } state;
+ Utils::Environment environment;
+
+ void setState(State newState);
+ void doSignal(QSsh::SshRemoteProcess::Signal signal);
+};
+
+SshDeviceProcess::SshDeviceProcess(const IDevice::ConstPtr &device, QObject *parent)
+ : DeviceProcess(device, parent), d(new SshDeviceProcessPrivate(this))
+{
+ d->connection = 0;
+ d->state = SshDeviceProcessPrivate::Inactive;
+ setSshServerSupportsSignals(false);
+}
+
+SshDeviceProcess::~SshDeviceProcess()
+{
+ d->setState(SshDeviceProcessPrivate::Inactive);
+ delete d;
+}
+
+void SshDeviceProcess::start(const QString &executable, const QStringList &arguments)
+{
+ QTC_ASSERT(d->state == SshDeviceProcessPrivate::Inactive, return);
+ d->setState(SshDeviceProcessPrivate::Connecting);
+
+ d->errorMessage.clear();
+ d->exitCode = -1;
+ d->executable = executable;
+ d->arguments = arguments;
+ d->connection = QSsh::acquireConnection(device()->sshParameters());
+ connect(d->connection, SIGNAL(error(QSsh::SshError)), SLOT(handleConnectionError()));
+ connect(d->connection, SIGNAL(disconnected()), SLOT(handleDisconnected()));
+ if (d->connection->state() == QSsh::SshConnection::Connected) {
+ handleConnected();
+ } else {
+ connect(d->connection, SIGNAL(connected()), SLOT(handleConnected()));
+ if (d->connection->state() == QSsh::SshConnection::Unconnected)
+ d->connection->connectToHost();
+ }
+}
+
+void SshDeviceProcess::interrupt()
+{
+ QTC_ASSERT(d->state == SshDeviceProcessPrivate::ProcessRunning, return);
+ d->doSignal(QSsh::SshRemoteProcess::IntSignal);
+}
+
+void SshDeviceProcess::terminate()
+{
+ d->doSignal(QSsh::SshRemoteProcess::TermSignal);
+}
+
+void SshDeviceProcess::kill()
+{
+ d->doSignal(QSsh::SshRemoteProcess::KillSignal);
+}
+
+QString SshDeviceProcess::executable() const
+{
+ return d->executable;
+}
+
+QStringList SshDeviceProcess::arguments() const
+{
+ return d->arguments;
+}
+
+QProcess::ProcessState SshDeviceProcess::state() const
+{
+ switch (d->state) {
+ case SshDeviceProcessPrivate::Inactive:
+ return QProcess::NotRunning;
+ case SshDeviceProcessPrivate::Connecting:
+ case SshDeviceProcessPrivate::Connected:
+ return QProcess::Starting;
+ case SshDeviceProcessPrivate::ProcessRunning:
+ return QProcess::Running;
+ default:
+ QTC_CHECK(false);
+ return QProcess::NotRunning;
+ }
+}
+
+QProcess::ExitStatus SshDeviceProcess::exitStatus() const
+{
+ return d->exitStatus == QSsh::SshRemoteProcess::NormalExit
+ ? QProcess::NormalExit : QProcess::CrashExit;
+}
+
+int SshDeviceProcess::exitCode() const
+{
+ return d->exitCode;
+}
+
+QString SshDeviceProcess::errorString() const
+{
+ return d->errorMessage;
+}
+
+Utils::Environment SshDeviceProcess::environment() const
+{
+ return d->environment;
+}
+
+void SshDeviceProcess::setEnvironment(const Utils::Environment &env)
+{
+ d->environment = env;
+}
+
+QByteArray SshDeviceProcess::readAllStandardOutput()
+{
+ const QByteArray data = d->stdOut;
+ d->stdOut.clear();
+ return data;
+}
+
+QByteArray SshDeviceProcess::readAllStandardError()
+{
+ const QByteArray data = d->stdErr;
+ d->stdErr.clear();
+ return data;
+}
+
+void SshDeviceProcess::setSshServerSupportsSignals(bool signalsSupported)
+{
+ d->serverSupportsSignals = signalsSupported;
+}
+
+void SshDeviceProcess::handleConnected()
+{
+ QTC_ASSERT(d->state == SshDeviceProcessPrivate::Connecting, return);
+ d->setState(SshDeviceProcessPrivate::Connected);
+
+ d->process = d->connection->createRemoteProcess(fullCommandLine().toUtf8());
+ connect(d->process.data(), SIGNAL(started()), SLOT(handleProcessStarted()));
+ connect(d->process.data(), SIGNAL(closed(int)), SLOT(handleProcessFinished(int)));
+ connect(d->process.data(), SIGNAL(readyReadStandardOutput()), SLOT(handleStdout()));
+ connect(d->process.data(), SIGNAL(readyReadStandardError()), SLOT(handleStderr()));
+
+ d->process->clearEnvironment();
+ const Utils::Environment env = environment();
+ for (Utils::Environment::const_iterator it = env.constBegin(); it != env.constEnd(); ++it)
+ d->process->addToEnvironment(env.key(it).toUtf8(), env.value(it).toUtf8());
+ d->process->start();
+}
+
+void SshDeviceProcess::handleConnectionError()
+{
+ QTC_ASSERT(d->state != SshDeviceProcessPrivate::Inactive, return);
+
+ d->errorMessage = d->connection->errorString();
+ handleDisconnected();
+}
+
+void SshDeviceProcess::handleDisconnected()
+{
+ QTC_ASSERT(d->state != SshDeviceProcessPrivate::Inactive, return);
+ const SshDeviceProcessPrivate::State oldState = d->state;
+ d->setState(SshDeviceProcessPrivate::Inactive);
+ switch (oldState) {
+ case SshDeviceProcessPrivate::Connecting:
+ case SshDeviceProcessPrivate::Connected:
+ emit error(QProcess::FailedToStart);
+ break;
+ case SshDeviceProcessPrivate::ProcessRunning:
+ emit finished();
+ default:
+ break;
+ }
+}
+
+void SshDeviceProcess::handleProcessStarted()
+{
+ QTC_ASSERT(d->state == SshDeviceProcessPrivate::Connected, return);
+
+ d->setState(SshDeviceProcessPrivate::ProcessRunning);
+ emit started();
+}
+
+void SshDeviceProcess::handleProcessFinished(int exitStatus)
+{
+ d->exitStatus = static_cast<QSsh::SshRemoteProcess::ExitStatus>(exitStatus);
+ switch (d->exitStatus) {
+ case QSsh::SshRemoteProcess::FailedToStart:
+ QTC_ASSERT(d->state == SshDeviceProcessPrivate::Connected, return);
+ break;
+ case QSsh::SshRemoteProcess::CrashExit:
+ QTC_ASSERT(d->state == SshDeviceProcessPrivate::ProcessRunning, return);
+ break;
+ case QSsh::SshRemoteProcess::NormalExit:
+ QTC_ASSERT(d->state == SshDeviceProcessPrivate::ProcessRunning, return);
+ d->exitCode = d->process->exitCode();
+ break;
+ default:
+ QTC_ASSERT(false, return);
+ }
+ d->errorMessage = d->process->errorString();
+ d->setState(SshDeviceProcessPrivate::Inactive);
+ emit finished();
+}
+
+void SshDeviceProcess::handleStdout()
+{
+ d->stdOut += d->process->readAllStandardOutput();
+ emit readyReadStandardOutput();
+}
+
+void SshDeviceProcess::handleStderr()
+{
+ d->stdErr += d->process->readAllStandardError();
+ emit readyReadStandardError();
+}
+
+QString SshDeviceProcess::fullCommandLine() const
+{
+ QString cmdLine = executable();
+ if (!arguments().isEmpty())
+ cmdLine.append(QLatin1Char(' ')).append(arguments().join(QLatin1String(" ")));
+ return cmdLine;
+}
+
+void SshDeviceProcess::SshDeviceProcessPrivate::doSignal(QSsh::SshRemoteProcess::Signal signal)
+{
+ switch (state) {
+ case SshDeviceProcessPrivate::Inactive:
+ QTC_ASSERT(false, return);
+ break;
+ case SshDeviceProcessPrivate::Connecting:
+ errorMessage = tr("Terminated by request.");
+ setState(SshDeviceProcessPrivate::Inactive);
+ emit q->error(QProcess::FailedToStart);
+ break;
+ case SshDeviceProcessPrivate::Connected:
+ case SshDeviceProcessPrivate::ProcessRunning:
+ if (serverSupportsSignals) {
+ process->sendSignal(signal);
+ } else {
+ DeviceProcessSignalOperation::Ptr signalOperation = q->device()->signalOperation();
+ if (signal == QSsh::SshRemoteProcess::IntSignal)
+ signalOperation->interruptProcess(executable);
+ else
+ signalOperation->killProcess(executable);
+ }
+ break;
+ }
+}
+
+void SshDeviceProcess::SshDeviceProcessPrivate::setState(SshDeviceProcess::SshDeviceProcessPrivate::State newState)
+{
+ if (state == newState)
+ return;
+
+ state = newState;
+ if (state != Inactive)
+ return;
+
+ if (process)
+ process->disconnect(q);
+ if (connection) {
+ connection->disconnect(q);
+ QSsh::releaseConnection(connection);
+ connection = 0;
+ }
+}
+
+qint64 SshDeviceProcess::write(const QByteArray &data)
+{
+ return d->process->write(data);
+}
+
+} // namespace ProjectExplorer
diff --git a/src/plugins/projectexplorer/devicesupport/sshdeviceprocess.h b/src/plugins/projectexplorer/devicesupport/sshdeviceprocess.h
new file mode 100644
index 0000000000..1b82398319
--- /dev/null
+++ b/src/plugins/projectexplorer/devicesupport/sshdeviceprocess.h
@@ -0,0 +1,88 @@
+/****************************************************************************
+**
+** 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 QTC_SSHDEVICEPROCESS_H
+#define QTC_SSHDEVICEPROCESS_H
+
+#include "deviceprocess.h"
+
+namespace ProjectExplorer {
+
+class PROJECTEXPLORER_EXPORT SshDeviceProcess : public DeviceProcess
+{
+ Q_OBJECT
+public:
+ SshDeviceProcess(const QSharedPointer<const IDevice> &device, QObject *parent = 0);
+ ~SshDeviceProcess();
+
+ void start(const QString &executable, const QStringList &arguments);
+ void interrupt();
+ void terminate();
+ void kill();
+
+ QString executable() const;
+ QStringList arguments() const;
+ QProcess::ProcessState state() const;
+ QProcess::ExitStatus exitStatus() const;
+ int exitCode() const;
+ QString errorString() const;
+
+ Utils::Environment environment() const;
+ void setEnvironment(const Utils::Environment &env);
+
+ void setWorkingDirectory(const QString & /* directory */) { } // No such thing in the RFC.
+
+ QByteArray readAllStandardOutput();
+ QByteArray readAllStandardError();
+
+ qint64 write(const QByteArray &data);
+
+ // Default is "false" due to OpenSSH not implementing this feature for some reason.
+ void setSshServerSupportsSignals(bool signalsSupported);
+
+private slots:
+ void handleConnected();
+ void handleConnectionError();
+ void handleDisconnected();
+ void handleProcessStarted();
+ void handleProcessFinished(int exitStatus);
+ void handleStdout();
+ void handleStderr();
+
+private:
+ virtual QString fullCommandLine() const;
+
+ class SshDeviceProcessPrivate;
+ friend class SshDeviceProcessPrivate;
+ SshDeviceProcessPrivate * const d;
+};
+
+} // namespace ProjectExplorer
+
+#endif // Include guard.
diff --git a/src/plugins/projectexplorer/devicesupport/sshdeviceprocesslist.cpp b/src/plugins/projectexplorer/devicesupport/sshdeviceprocesslist.cpp
index 0b98e191f0..1970c588c7 100644
--- a/src/plugins/projectexplorer/devicesupport/sshdeviceprocesslist.cpp
+++ b/src/plugins/projectexplorer/devicesupport/sshdeviceprocesslist.cpp
@@ -28,6 +28,8 @@
****************************************************************************/
#include "sshdeviceprocesslist.h"
+#include "idevice.h"
+
#include <ssh/sshremoteprocessrunner.h>
#include <utils/qtcassert.h>
@@ -39,6 +41,7 @@ class SshDeviceProcessList::SshDeviceProcessListPrivate
{
public:
SshRemoteProcessRunner process;
+ DeviceProcessSignalOperation::Ptr signalOperation;
};
SshDeviceProcessList::SshDeviceProcessList(const IDevice::ConstPtr &device, QObject *parent) :
@@ -53,19 +56,18 @@ SshDeviceProcessList::~SshDeviceProcessList()
void SshDeviceProcessList::doUpdate()
{
- QTC_ASSERT(device()->processSupport(), return);
connect(&d->process, SIGNAL(connectionError()), SLOT(handleConnectionError()));
connect(&d->process, SIGNAL(processClosed(int)), SLOT(handleListProcessFinished(int)));
d->process.run(listProcessesCommandLine().toUtf8(), device()->sshParameters());
}
-void SshDeviceProcessList::doKillProcess(const DeviceProcess &process)
+void SshDeviceProcessList::doKillProcess(const DeviceProcessItem &process)
{
- QTC_ASSERT(device()->processSupport(), return);
- connect(&d->process, SIGNAL(connectionError()), SLOT(handleConnectionError()));
- connect(&d->process, SIGNAL(processClosed(int)), SLOT(handleKillProcessFinished(int)));
- d->process.run(device()->processSupport()->killProcessByPidCommandLine(process.pid).toUtf8(),
- device()->sshParameters());
+ d->signalOperation = device()->signalOperation();
+ QTC_ASSERT(d->signalOperation, return);
+ connect(d->signalOperation.data(), SIGNAL(finished(QString)),
+ SLOT(handleKillProcessFinished(QString)));
+ d->signalOperation->killProcess(process.pid);
}
void SshDeviceProcessList::handleConnectionError()
@@ -102,29 +104,13 @@ void SshDeviceProcessList::handleListProcessFinished(int exitStatus)
}
}
-void SshDeviceProcessList::handleKillProcessFinished(int exitStatus)
+void SshDeviceProcessList::handleKillProcessFinished(const QString &errorString)
{
+ if (errorString.isEmpty())
+ reportProcessKilled();
+ else
+ reportError(tr("Error: Kill process failed: %1").arg(errorString));
setFinished();
- switch (exitStatus) {
- case SshRemoteProcess::FailedToStart:
- handleProcessError(tr("Error: Kill process failed to start: %1")
- .arg(d->process.processErrorString()));
- break;
- case SshRemoteProcess::CrashExit:
- handleProcessError(tr("Error: Kill process crashed: %1")
- .arg(d->process.processErrorString()));
- break;
- case SshRemoteProcess::NormalExit: {
- const int exitCode = d->process.processExitCode();
- if (exitCode == 0)
- reportProcessKilled();
- else
- handleProcessError(tr("Kill process failed with exit code %1.").arg(exitCode));
- break;
- }
- default:
- Q_ASSERT_X(false, Q_FUNC_INFO, "Invalid exit status");
- }
}
void SshDeviceProcessList::handleProcessError(const QString &errorMessage)
@@ -139,6 +125,10 @@ void SshDeviceProcessList::handleProcessError(const QString &errorMessage)
void SshDeviceProcessList::setFinished()
{
d->process.disconnect(this);
+ if (d->signalOperation) {
+ d->signalOperation->disconnect(this);
+ d->signalOperation.clear();
+ }
}
} // namespace ProjectExplorer
diff --git a/src/plugins/projectexplorer/devicesupport/sshdeviceprocesslist.h b/src/plugins/projectexplorer/devicesupport/sshdeviceprocesslist.h
index faaab98b35..62d5548f95 100644
--- a/src/plugins/projectexplorer/devicesupport/sshdeviceprocesslist.h
+++ b/src/plugins/projectexplorer/devicesupport/sshdeviceprocesslist.h
@@ -43,14 +43,14 @@ public:
private slots:
void handleConnectionError();
void handleListProcessFinished(int exitStatus);
- void handleKillProcessFinished(int exitStatus);
+ void handleKillProcessFinished(const QString &errorString);
private:
virtual QString listProcessesCommandLine() const = 0;
- virtual QList<DeviceProcess> buildProcessList(const QString &listProcessesReply) const = 0;
+ virtual QList<DeviceProcessItem> buildProcessList(const QString &listProcessesReply) const = 0;
void doUpdate();
- void doKillProcess(const DeviceProcess &process);
+ void doKillProcess(const DeviceProcessItem &process);
void handleProcessError(const QString &errorMessage);
void setFinished();
diff --git a/src/plugins/projectexplorer/editorconfiguration.cpp b/src/plugins/projectexplorer/editorconfiguration.cpp
index 6273d97149..6af46548a6 100644
--- a/src/plugins/projectexplorer/editorconfiguration.cpp
+++ b/src/plugins/projectexplorer/editorconfiguration.cpp
@@ -53,7 +53,6 @@ static const QLatin1String kUseGlobal("EditorConfiguration.UseGlobal");
static const QLatin1String kCodec("EditorConfiguration.Codec");
static const QLatin1String kCodeStylePrefix("EditorConfiguration.CodeStyle.");
static const QLatin1String kCodeStyleCount("EditorConfiguration.CodeStyle.Count");
-static const QLatin1String kId("Project");
using namespace TextEditor;
@@ -63,11 +62,11 @@ struct EditorConfigurationPrivate
{
EditorConfigurationPrivate()
: m_useGlobal(true)
- , m_typingSettings(TextEditorSettings::instance()->typingSettings())
- , m_storageSettings(TextEditorSettings::instance()->storageSettings())
- , m_behaviorSettings(TextEditorSettings::instance()->behaviorSettings())
- , m_extraEncodingSettings(TextEditorSettings::instance()->extraEncodingSettings())
- , m_textCodec(Core::EditorManager::instance()->defaultTextCodec())
+ , m_typingSettings(TextEditorSettings::typingSettings())
+ , m_storageSettings(TextEditorSettings::storageSettings())
+ , m_behaviorSettings(TextEditorSettings::behaviorSettings())
+ , m_extraEncodingSettings(TextEditorSettings::extraEncodingSettings())
+ , m_textCodec(Core::EditorManager::defaultTextCodec())
{
}
@@ -84,29 +83,26 @@ struct EditorConfigurationPrivate
EditorConfiguration::EditorConfiguration() : d(new EditorConfigurationPrivate)
{
- TextEditorSettings *textEditorSettings = TextEditorSettings::instance();
-
- const QMap<Core::Id, ICodeStylePreferences *> languageCodeStylePreferences = textEditorSettings->codeStyles();
+ const QMap<Core::Id, ICodeStylePreferences *> languageCodeStylePreferences = TextEditorSettings::codeStyles();
QMapIterator<Core::Id, ICodeStylePreferences *> itCodeStyle(languageCodeStylePreferences);
while (itCodeStyle.hasNext()) {
itCodeStyle.next();
Core::Id languageId = itCodeStyle.key();
ICodeStylePreferences *originalPreferences = itCodeStyle.value();
- ICodeStylePreferencesFactory *factory = textEditorSettings->codeStyleFactory(languageId);
+ ICodeStylePreferencesFactory *factory = TextEditorSettings::codeStyleFactory(languageId);
ICodeStylePreferences *preferences = factory->createCodeStyle();
- preferences->setDelegatingPool(textEditorSettings->codeStylePool(languageId));
- preferences->setId(languageId.toString() + QLatin1String("Project"));
+ preferences->setDelegatingPool(TextEditorSettings::codeStylePool(languageId));
+ preferences->setId(languageId.name() + "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);
}
d->m_defaultCodeStyle = new SimpleCodeStylePreferences(this);
- d->m_defaultCodeStyle->setDelegatingPool(textEditorSettings->codeStylePool());
+ d->m_defaultCodeStyle->setDelegatingPool(TextEditorSettings::codeStylePool());
d->m_defaultCodeStyle->setDisplayName(tr("Project", "Settings"));
- d->m_defaultCodeStyle->setId(kId);
- d->m_defaultCodeStyle->setCurrentDelegate(d->m_useGlobal
- ? TextEditorSettings::instance()->codeStyle() : 0);
+ d->m_defaultCodeStyle->setId("Project");
+ d->m_defaultCodeStyle->setCurrentDelegate(d->m_useGlobal ? TextEditorSettings::codeStyle() : 0);
}
EditorConfiguration::~EditorConfiguration()
@@ -122,14 +118,12 @@ bool EditorConfiguration::useGlobalSettings() const
void EditorConfiguration::cloneGlobalSettings()
{
- TextEditorSettings *textEditorSettings = TextEditorSettings::instance();
-
- d->m_defaultCodeStyle->setTabSettings(textEditorSettings->codeStyle()->tabSettings());
- setTypingSettings(textEditorSettings->typingSettings());
- setStorageSettings(textEditorSettings->storageSettings());
- setBehaviorSettings(textEditorSettings->behaviorSettings());
- setExtraEncodingSettings(textEditorSettings->extraEncodingSettings());
- d->m_textCodec = Core::EditorManager::instance()->defaultTextCodec();
+ d->m_defaultCodeStyle->setTabSettings(TextEditorSettings::codeStyle()->tabSettings());
+ setTypingSettings(TextEditorSettings::typingSettings());
+ setStorageSettings(TextEditorSettings::storageSettings());
+ setBehaviorSettings(TextEditorSettings::behaviorSettings());
+ setExtraEncodingSettings(TextEditorSettings::extraEncodingSettings());
+ d->m_textCodec = Core::EditorManager::defaultTextCodec();
}
QTextCodec *EditorConfiguration::textCodec() const
@@ -208,7 +202,7 @@ void EditorConfiguration::fromMap(const QVariantMap &map)
const QByteArray &codecName = map.value(kCodec, d->m_textCodec->name()).toByteArray();
d->m_textCodec = QTextCodec::codecForName(codecName);
if (!d->m_textCodec)
- d->m_textCodec = Core::EditorManager::instance()->defaultTextCodec();
+ d->m_textCodec = Core::EditorManager::defaultTextCodec();
const int codeStyleCount = map.value(kCodeStyleCount, 0).toInt();
for (int i = 0; i < codeStyleCount; ++i) {
@@ -237,7 +231,7 @@ void EditorConfiguration::configureEditor(ITextEditor *textEditor) const
if (baseTextEditor)
baseTextEditor->setCodeStyle(codeStyle(baseTextEditor->languageSettingsId()));
if (!d->m_useGlobal) {
- textEditor->setTextCodec(d->m_textCodec, ITextEditor::TextCodecFromProjectSetting);
+ textEditor->textDocument()->setCodec(d->m_textCodec);
if (baseTextEditor)
switchSettings(baseTextEditor);
}
@@ -247,55 +241,57 @@ void EditorConfiguration::setUseGlobalSettings(bool use)
{
d->m_useGlobal = use;
d->m_defaultCodeStyle->setCurrentDelegate(d->m_useGlobal
- ? TextEditorSettings::instance()->codeStyle() : 0);
- const SessionManager *session = ProjectExplorerPlugin::instance()->session();
- QList<Core::IEditor *> opened = Core::EditorManager::instance()->openedEditors();
+ ? TextEditorSettings::codeStyle() : 0);
+ QList<Core::IEditor *> opened = Core::EditorManager::documentModel()->editorsForDocuments(
+ Core::EditorManager::documentModel()->openedDocuments());
foreach (Core::IEditor *editor, opened) {
if (BaseTextEditorWidget *baseTextEditor = qobject_cast<BaseTextEditorWidget *>(editor->widget())) {
- Project *project = session->projectForFile(editor->document()->fileName());
+ Project *project = SessionManager::projectForFile(editor->document()->filePath());
if (project && project->editorConfiguration() == this)
switchSettings(baseTextEditor);
}
}
}
-void EditorConfiguration::switchSettings(BaseTextEditorWidget *baseTextEditor) const
-{
- if (d->m_useGlobal)
- switchSettings_helper(TextEditorSettings::instance(), this, baseTextEditor);
- else
- switchSettings_helper(this, TextEditorSettings::instance(), baseTextEditor);
-}
-
-template <class NewSenderT, class OldSenderT>
-void EditorConfiguration::switchSettings_helper(const NewSenderT *newSender,
- const OldSenderT *oldSender,
- BaseTextEditorWidget *baseTextEditor) const
+static void switchSettings_helper(const QObject *newSender, const QObject *oldSender,
+ BaseTextEditorWidget *baseTextEditor)
{
- baseTextEditor->setTypingSettings(newSender->typingSettings());
- baseTextEditor->setStorageSettings(newSender->storageSettings());
- baseTextEditor->setBehaviorSettings(newSender->behaviorSettings());
- baseTextEditor->setExtraEncodingSettings(newSender->extraEncodingSettings());
-
- disconnect(oldSender, SIGNAL(typingSettingsChanged(TextEditor::TypingSettings)),
+ QObject::disconnect(oldSender, SIGNAL(typingSettingsChanged(TextEditor::TypingSettings)),
baseTextEditor, SLOT(setTypingSettings(TextEditor::TypingSettings)));
- disconnect(oldSender, SIGNAL(storageSettingsChanged(TextEditor::StorageSettings)),
+ QObject::disconnect(oldSender, SIGNAL(storageSettingsChanged(TextEditor::StorageSettings)),
baseTextEditor, SLOT(setStorageSettings(TextEditor::StorageSettings)));
- disconnect(oldSender, SIGNAL(behaviorSettingsChanged(TextEditor::BehaviorSettings)),
+ QObject::disconnect(oldSender, SIGNAL(behaviorSettingsChanged(TextEditor::BehaviorSettings)),
baseTextEditor, SLOT(setBehaviorSettings(TextEditor::BehaviorSettings)));
- disconnect(oldSender, SIGNAL(extraEncodingSettingsChanged(TextEditor::ExtraEncodingSettings)),
+ QObject::disconnect(oldSender, SIGNAL(extraEncodingSettingsChanged(TextEditor::ExtraEncodingSettings)),
baseTextEditor, SLOT(setExtraEncodingSettings(TextEditor::ExtraEncodingSettings)));
- connect(newSender, SIGNAL(typingSettingsChanged(TextEditor::TypingSettings)),
+ QObject::connect(newSender, SIGNAL(typingSettingsChanged(TextEditor::TypingSettings)),
baseTextEditor, SLOT(setTypingSettings(TextEditor::TypingSettings)));
- connect(newSender, SIGNAL(storageSettingsChanged(TextEditor::StorageSettings)),
+ QObject::connect(newSender, SIGNAL(storageSettingsChanged(TextEditor::StorageSettings)),
baseTextEditor, SLOT(setStorageSettings(TextEditor::StorageSettings)));
- connect(newSender, SIGNAL(behaviorSettingsChanged(TextEditor::BehaviorSettings)),
+ QObject::connect(newSender, SIGNAL(behaviorSettingsChanged(TextEditor::BehaviorSettings)),
baseTextEditor, SLOT(setBehaviorSettings(TextEditor::BehaviorSettings)));
- connect(newSender, SIGNAL(extraEncodingSettingsChanged(TextEditor::ExtraEncodingSettings)),
+ QObject::connect(newSender, SIGNAL(extraEncodingSettingsChanged(TextEditor::ExtraEncodingSettings)),
baseTextEditor, SLOT(setExtraEncodingSettings(TextEditor::ExtraEncodingSettings)));
}
+void EditorConfiguration::switchSettings(BaseTextEditorWidget *baseTextEditor) const
+{
+ if (d->m_useGlobal) {
+ baseTextEditor->setTypingSettings(TextEditorSettings::typingSettings());
+ baseTextEditor->setStorageSettings(TextEditorSettings::storageSettings());
+ baseTextEditor->setBehaviorSettings(TextEditorSettings::behaviorSettings());
+ baseTextEditor->setExtraEncodingSettings(TextEditorSettings::extraEncodingSettings());
+ switchSettings_helper(TextEditorSettings::instance(), this, baseTextEditor);
+ } else {
+ baseTextEditor->setTypingSettings(typingSettings());
+ baseTextEditor->setStorageSettings(storageSettings());
+ baseTextEditor->setBehaviorSettings(behaviorSettings());
+ baseTextEditor->setExtraEncodingSettings(extraEncodingSettings());
+ switchSettings_helper(this, TextEditorSettings::instance(), baseTextEditor);
+ }
+}
+
void EditorConfiguration::setTypingSettings(const TextEditor::TypingSettings &settings)
{
d->m_typingSettings = settings;
@@ -325,18 +321,13 @@ void EditorConfiguration::setTextCodec(QTextCodec *textCodec)
d->m_textCodec = textCodec;
}
-TabSettings actualTabSettings(const QString &fileName,
- const BaseTextEditorWidget *baseTextEditor)
+TabSettings actualTabSettings(const QString &fileName, const BaseTextEditorWidget *baseTextEditor)
{
- if (baseTextEditor) {
+ if (baseTextEditor)
return baseTextEditor->tabSettings();
- } else {
- const SessionManager *session = ProjectExplorerPlugin::instance()->session();
- if (Project *project = session->projectForFile(fileName))
- return project->editorConfiguration()->codeStyle()->tabSettings();
- else
- return TextEditorSettings::instance()->codeStyle()->tabSettings();
- }
+ if (Project *project = SessionManager::projectForFile(fileName))
+ return project->editorConfiguration()->codeStyle()->tabSettings();
+ return TextEditorSettings::codeStyle()->tabSettings();
}
} // ProjectExplorer
diff --git a/src/plugins/projectexplorer/editorconfiguration.h b/src/plugins/projectexplorer/editorconfiguration.h
index 0caaf2f58c..af419c8c6c 100644
--- a/src/plugins/projectexplorer/editorconfiguration.h
+++ b/src/plugins/projectexplorer/editorconfiguration.h
@@ -98,10 +98,6 @@ private slots:
private:
void switchSettings(TextEditor::BaseTextEditorWidget *baseTextEditor) const;
- template <class NewSenderT, class OldSenderT>
- void switchSettings_helper(const NewSenderT *newSender,
- const OldSenderT *oldSender,
- TextEditor::BaseTextEditorWidget *baseTextEditor) const;
EditorConfigurationPrivate *d;
};
diff --git a/src/plugins/projectexplorer/environmentaspect.cpp b/src/plugins/projectexplorer/environmentaspect.cpp
index f8648c1b17..058967acdb 100644
--- a/src/plugins/projectexplorer/environmentaspect.cpp
+++ b/src/plugins/projectexplorer/environmentaspect.cpp
@@ -43,30 +43,11 @@ namespace ProjectExplorer {
// EnvironmentAspect:
// --------------------------------------------------------------------
-EnvironmentAspect::EnvironmentAspect(RunConfiguration *rc) :
- m_base(-1),
- m_runConfiguration(rc)
+EnvironmentAspect::EnvironmentAspect(RunConfiguration *runConfig)
+ : IRunConfigurationAspect(runConfig), m_base(-1)
{
- QTC_CHECK(m_runConfiguration);
-}
-
-EnvironmentAspect::EnvironmentAspect(const EnvironmentAspect *other, RunConfiguration *parent) :
- m_base(other->m_base),
- m_changes(other->m_changes),
- m_runConfiguration(parent)
-{ }
-
-QVariantMap EnvironmentAspect::toMap() const
-{
- QVariantMap data;
- data.insert(QLatin1String(BASE_KEY), m_base);
- data.insert(QLatin1String(CHANGES_KEY), Utils::EnvironmentItem::toStringList(m_changes));
- return data;
-}
-
-QString EnvironmentAspect::displayName() const
-{
- return tr("Run Environment");
+ setDisplayName(tr("Run Environment"));
+ setId("EnvironmentAspect");
}
RunConfigWidget *EnvironmentAspect::createConfigurationWidget()
@@ -119,4 +100,10 @@ void EnvironmentAspect::fromMap(const QVariantMap &map)
m_changes = Utils::EnvironmentItem::fromStringList(map.value(QLatin1String(CHANGES_KEY)).toStringList());
}
+void EnvironmentAspect::toMap(QVariantMap &data) const
+{
+ data.insert(QLatin1String(BASE_KEY), m_base);
+ data.insert(QLatin1String(CHANGES_KEY), Utils::EnvironmentItem::toStringList(m_changes));
+}
+
} // namespace ProjectExplorer
diff --git a/src/plugins/projectexplorer/environmentaspect.h b/src/plugins/projectexplorer/environmentaspect.h
index 604d253d1c..3200907ef9 100644
--- a/src/plugins/projectexplorer/environmentaspect.h
+++ b/src/plugins/projectexplorer/environmentaspect.h
@@ -41,19 +41,14 @@
namespace ProjectExplorer {
-class PROJECTEXPLORER_EXPORT EnvironmentAspect : public QObject, public IRunConfigurationAspect
+class PROJECTEXPLORER_EXPORT EnvironmentAspect : public IRunConfigurationAspect
{
Q_OBJECT
public:
- // from IRunConfigurationAspect:
- QVariantMap toMap() const;
- QString displayName() const;
-
+ // IRunConfigurationAspect:
RunConfigWidget *createConfigurationWidget();
- virtual RunConfiguration *runConfiguration() const { return m_runConfiguration; }
-
virtual QList<int> possibleBaseEnvironments() const = 0;
virtual QString baseEnvironmentDisplayName(int base) const = 0;
@@ -72,14 +67,13 @@ signals:
void environmentChanged();
protected:
- EnvironmentAspect(const EnvironmentAspect *other, RunConfiguration *parent);
- EnvironmentAspect(RunConfiguration *rc);
+ explicit EnvironmentAspect(RunConfiguration *rc);
void fromMap(const QVariantMap &map);
+ void toMap(QVariantMap &map) const;
private:
mutable int m_base;
QList<Utils::EnvironmentItem> m_changes;
- RunConfiguration *m_runConfiguration;
};
} // namespace ProjectExplorer
diff --git a/src/plugins/projectexplorer/environmentitemswidget.cpp b/src/plugins/projectexplorer/environmentitemswidget.cpp
index 3e3f30a03f..381abe0adc 100644
--- a/src/plugins/projectexplorer/environmentitemswidget.cpp
+++ b/src/plugins/projectexplorer/environmentitemswidget.cpp
@@ -71,8 +71,7 @@ EnvironmentItemsWidget::EnvironmentItemsWidget(QWidget *parent) :
QWidget(parent), d(new EnvironmentItemsWidgetPrivate)
{
d->m_editor = new TextEditor::SnippetEditorWidget(this);
- TextEditor::TextEditorSettings *settings = TextEditor::TextEditorSettings::instance();
- d->m_editor->setFontSettings(settings->fontSettings());
+ d->m_editor->setFontSettings(TextEditor::TextEditorSettings::fontSettings());
QVBoxLayout *layout = new QVBoxLayout(this);
layout->addWidget(d->m_editor);
}
diff --git a/src/plugins/projectexplorer/foldernavigationwidget.cpp b/src/plugins/projectexplorer/foldernavigationwidget.cpp
index 09a069eae4..6aad3a6b20 100644
--- a/src/plugins/projectexplorer/foldernavigationwidget.cpp
+++ b/src/plugins/projectexplorer/foldernavigationwidget.cpp
@@ -124,7 +124,7 @@ FolderNavigationWidget::FolderNavigationWidget(QWidget *parent)
m_toggleSync(new QToolButton(this))
{
m_fileSystemModel->setResolveSymlinks(false);
- m_fileSystemModel->setIconProvider(Core::FileIconProvider::instance());
+ m_fileSystemModel->setIconProvider(Core::FileIconProvider::iconProvider());
QDir::Filters filters = QDir::AllDirs | QDir::Files | QDir::Drives
| QDir::Readable| QDir::Writable
| QDir::Executable | QDir::Hidden;
@@ -307,7 +307,7 @@ void FolderNavigationWidget::contextMenuEvent(QContextMenuEvent *ev)
QAction *actionTerminal = menu.addAction(Core::FileUtils::msgTerminalAction());
actionTerminal->setEnabled(hasCurrentItem);
- QAction *actionFind = menu.addAction(msgFindOnFileSystem());
+ QAction *actionFind = menu.addAction(Core::FileUtils::msgFindInDirectory());
actionFind->setEnabled(hasCurrentItem);
// open with...
if (!m_fileSystemModel->isDir(current)) {
@@ -343,36 +343,12 @@ void FolderNavigationWidget::contextMenuEvent(QContextMenuEvent *ev)
return;
}
if (action == actionFind) {
- QFileInfo info = m_fileSystemModel->fileInfo(current);
- if (m_fileSystemModel->isDir(current))
- findOnFileSystem(info.absoluteFilePath());
- else
- findOnFileSystem(info.absolutePath());
+ TextEditor::FindInFiles::findOnFileSystem(m_fileSystemModel->filePath(current));
return;
}
Core::DocumentManager::executeOpenWithMenuAction(action);
}
-QString FolderNavigationWidget::msgFindOnFileSystem()
-{
- return tr("Find in this directory...");
-}
-
-void FolderNavigationWidget::findOnFileSystem(const QString &pathIn)
-{
- const QFileInfo fileInfo(pathIn);
- const QString folder = fileInfo.isDir() ? fileInfo.absoluteFilePath() : fileInfo.absolutePath();
-
- TextEditor::FindInFiles *fif = ExtensionSystem::PluginManager::getObject<TextEditor::FindInFiles>();
- if (!fif)
- return;
- Find::FindPlugin *plugin = Find::FindPlugin::instance();
- if (!plugin)
- return;
- fif->setDirectory(folder);
- Find::FindPlugin::instance()->openFindDialog(fif);
-}
-
void FolderNavigationWidget::setHiddenFilesFilter(bool filter)
{
QDir::Filters filters = m_fileSystemModel->filter();
@@ -410,7 +386,7 @@ int FolderNavigationWidgetFactory::priority() const
Core::Id FolderNavigationWidgetFactory::id() const
{
- return Core::Id("File System");
+ return "File System";
}
QKeySequence FolderNavigationWidgetFactory::activationSequence() const
diff --git a/src/plugins/projectexplorer/foldernavigationwidget.h b/src/plugins/projectexplorer/foldernavigationwidget.h
index fbc109a9df..6b6aaed266 100644
--- a/src/plugins/projectexplorer/foldernavigationwidget.h
+++ b/src/plugins/projectexplorer/foldernavigationwidget.h
@@ -60,9 +60,6 @@ public:
FolderNavigationWidget(QWidget *parent = 0);
bool autoSynchronization() const;
-
- static void findOnFileSystem(const QString &pathIn);
- static QString msgFindOnFileSystem();
bool hiddenFilesFilter() const;
public slots:
diff --git a/src/plugins/projectexplorer/gccparser.cpp b/src/plugins/projectexplorer/gccparser.cpp
index 1cd2b725c4..a4437385c4 100644
--- a/src/plugins/projectexplorer/gccparser.cpp
+++ b/src/plugins/projectexplorer/gccparser.cpp
@@ -32,6 +32,8 @@
#include "task.h"
#include "projectexplorerconstants.h"
+#include <utils/qtcassert.h>
+
using namespace ProjectExplorer;
// opt. drive letter + filename: (2 brackets)
@@ -44,10 +46,12 @@ GccParser::GccParser()
m_regExp.setPattern(QLatin1Char('^') + QLatin1String(FILE_PATTERN)
+ QLatin1String("(\\d+):(\\d+:)?\\s+((fatal |#)?(warning|error|note):?\\s)?([^\\s].+)$"));
m_regExp.setMinimal(true);
+ QTC_CHECK(m_regExp.isValid());
m_regExpIncluded.setPattern(QString::fromLatin1("\\bfrom\\s") + QLatin1String(FILE_PATTERN)
+ QLatin1String("(\\d+)(:\\d+)?[,:]?$"));
m_regExpIncluded.setMinimal(true);
+ QTC_CHECK(m_regExpIncluded.isValid());
// optional path with trailing slash
// optional arm-linux-none-thingy
@@ -56,6 +60,7 @@ GccParser::GccParser()
// optional .exe postfix
m_regExpGccNames.setPattern(QLatin1String(COMMAND_PATTERN));
m_regExpGccNames.setMinimal(true);
+ QTC_CHECK(m_regExpGccNames.isValid());
appendOutputParser(new LdParser);
}
@@ -78,7 +83,7 @@ void GccParser::stdError(const QString &line)
lne /* description */,
Utils::FileName() /* filename */,
-1 /* linenumber */,
- Core::Id(Constants::TASK_CATEGORY_COMPILE)));
+ Constants::TASK_CATEGORY_COMPILE));
return;
} else if (m_regExpGccNames.indexIn(lne) > -1) {
QString description = lne.mid(m_regExpGccNames.matchedLength());
@@ -86,7 +91,7 @@ void GccParser::stdError(const QString &line)
description,
Utils::FileName(), /* filename */
-1, /* line */
- Core::Id(Constants::TASK_CATEGORY_COMPILE));
+ Constants::TASK_CATEGORY_COMPILE);
if (description.startsWith(QLatin1String("warning: "))) {
task.type = Task::Warning;
task.description = description.mid(9);
@@ -101,11 +106,12 @@ void GccParser::stdError(const QString &line)
Task task(Task::Unknown,
m_regExp.cap(8) /* description */,
filename, lineno,
- Core::Id(Constants::TASK_CATEGORY_COMPILE));
+ Constants::TASK_CATEGORY_COMPILE);
if (m_regExp.cap(7) == QLatin1String("warning"))
task.type = Task::Warning;
else if (m_regExp.cap(7) == QLatin1String("error") ||
- task.description.startsWith(QLatin1String("undefined reference to")))
+ task.description.startsWith(QLatin1String("undefined reference to")) ||
+ task.description.startsWith(QLatin1String("multiple definition of")))
task.type = Task::Error;
// Prepend "#warning" or "#error" if that triggered the match on (warning|error)
@@ -120,7 +126,7 @@ void GccParser::stdError(const QString &line)
lne.trimmed() /* description */,
Utils::FileName::fromUserInput(m_regExpIncluded.cap(1)) /* filename */,
m_regExpIncluded.cap(3).toInt() /* linenumber */,
- Core::Id(Constants::TASK_CATEGORY_COMPILE)));
+ Constants::TASK_CATEGORY_COMPILE));
return;
} else if (lne.startsWith(QLatin1Char(' '))) {
amendDescription(lne, true);
@@ -188,7 +194,7 @@ void ProjectExplorerPlugin::testGccOutputParsers_data()
QTest::addColumn<QList<ProjectExplorer::Task> >("tasks");
QTest::addColumn<QString>("outputLines");
- const Core::Id categoryCompile = Core::Id(Constants::TASK_CATEGORY_COMPILE);
+ const Core::Id categoryCompile = Constants::TASK_CATEGORY_COMPILE;
QTest::newRow("pass-through stdout")
<< QString::fromLatin1("Sometext") << OutputParserTester::STDOUT
@@ -416,13 +422,13 @@ void ProjectExplorerPlugin::testGccOutputParsers_data()
<< QList<ProjectExplorer::Task>()
<< QString();
QTest::newRow("note")
- << QString::fromLatin1("/home/dev/creator/share/qtcreator/dumper/dumper.cpp:1079: note: initialized from here")
+ << QString::fromLatin1("/home/dev/creator/share/qtcreator/debugger/dumper.cpp:1079: note: initialized from here")
<< OutputParserTester::STDERR
<< QString() << QString()
<< ( QList<ProjectExplorer::Task>()
<< Task(Task::Unknown,
QLatin1String("initialized from here"),
- Utils::FileName::fromUserInput(QLatin1String("/home/dev/creator/share/qtcreator/dumper/dumper.cpp")), 1079,
+ Utils::FileName::fromUserInput(QLatin1String("/home/dev/creator/share/qtcreator/debugger/dumper.cpp")), 1079,
categoryCompile))
<< QString();
QTest::newRow("static member function")
@@ -806,6 +812,54 @@ void ProjectExplorerPlugin::testGccOutputParsers_data()
categoryCompile))
<< QString();
+ QTest::newRow("ld: Multiple definition error")
+ << QString::fromLatin1("foo.o: In function `foo()':\n"
+ "/home/user/test/foo.cpp:2: multiple definition of `foo()'\n"
+ "bar.o:/home/user/test/bar.cpp:4: first defined here\n"
+ "collect2: error: ld returned 1 exit status")
+ << OutputParserTester::STDERR
+ << QString() << QString()
+ << (QList<ProjectExplorer::Task>()
+ << Task(Task::Unknown,
+ QLatin1String("In function `foo()':"),
+ Utils::FileName::fromUserInput(QLatin1String("foo.o")), -1,
+ categoryCompile)
+ << Task(Task::Error,
+ QLatin1String("multiple definition of `foo()'"),
+ Utils::FileName::fromUserInput(QLatin1String("/home/user/test/foo.cpp")), 2,
+ categoryCompile)
+ << Task(Task::Unknown,
+ QLatin1String("first defined here"),
+ Utils::FileName::fromUserInput(QLatin1String("/home/user/test/bar.cpp")), 4,
+ categoryCompile)
+ << Task(Task::Error,
+ QLatin1String("collect2: error: ld returned 1 exit status"),
+ Utils::FileName(), -1,
+ categoryCompile)
+ )
+ << QString();
+
+ QTest::newRow("ld: .data section")
+ << QString::fromLatin1("foo.o:(.data+0x0): multiple definition of `foo'\n"
+ "bar.o:(.data+0x0): first defined here\n"
+ "collect2: error: ld returned 1 exit status")
+ << OutputParserTester::STDERR
+ << QString() << QString()
+ << (QList<ProjectExplorer::Task>()
+ << Task(Task::Error,
+ QLatin1String("multiple definition of `foo'"),
+ Utils::FileName::fromUserInput(QLatin1String("foo.o")), -1,
+ categoryCompile)
+ << Task(Task::Unknown,
+ QLatin1String("first defined here"),
+ Utils::FileName::fromUserInput(QLatin1String("bar.o")), -1,
+ categoryCompile)
+ << Task(Task::Error,
+ QLatin1String("collect2: error: ld returned 1 exit status"),
+ Utils::FileName(), -1,
+ categoryCompile)
+ )
+ << QString();
}
void ProjectExplorerPlugin::testGccOutputParsers()
diff --git a/src/plugins/projectexplorer/gcctoolchain.cpp b/src/plugins/projectexplorer/gcctoolchain.cpp
index fd841af663..ed0c2fca86 100644
--- a/src/plugins/projectexplorer/gcctoolchain.cpp
+++ b/src/plugins/projectexplorer/gcctoolchain.cpp
@@ -39,6 +39,7 @@
#include <utils/hostosinfo.h>
#include <utils/synchronousprocess.h>
#include <utils/pathchooser.h>
+#include <utils/qtcassert.h>
#include <utils/qtcprocess.h>
#include <QBuffer>
@@ -54,6 +55,8 @@ using namespace Utils;
namespace ProjectExplorer {
+using namespace Internal;
+
// --------------------------------------------------------------------------
// Helpers:
// --------------------------------------------------------------------------
@@ -84,7 +87,7 @@ static QByteArray runGcc(const FileName &gcc, const QStringList &arguments, cons
return QByteArray();
}
cpp.closeWriteChannel();
- if (!cpp.waitForFinished()) {
+ if (!cpp.waitForFinished(10000)) {
SynchronousProcess::stopProcess(cpp);
qWarning("%s: Timeout running '%s'.", Q_FUNC_INFO, qPrintable(gcc.toUserOutput()));
return QByteArray();
@@ -94,7 +97,20 @@ static QByteArray runGcc(const FileName &gcc, const QStringList &arguments, cons
return QByteArray();
}
- return cpp.readAllStandardOutput() + '\n' + cpp.readAllStandardError();
+ const QByteArray stdErr = cpp.readAllStandardError();
+ if (cpp.exitCode() != 0) {
+ qWarning().nospace()
+ << Q_FUNC_INFO << ": " << gcc.toUserOutput() << ' '
+ << arguments.join(QLatin1String(" ")) << " returned exit code "
+ << cpp.exitCode() << ": " << stdErr;
+ return QByteArray();
+ }
+
+ QByteArray data = cpp.readAllStandardOutput();
+ if (!data.isEmpty() && !data.endsWith('\n'))
+ data.append('\n');
+ data.append(stdErr);
+ return data;
}
static QByteArray gccPredefinedMacros(const FileName &gcc, const QStringList &args, const QStringList &env)
@@ -136,6 +152,8 @@ static QByteArray gccPredefinedMacros(const FileName &gcc, const QStringList &ar
arguments << QLatin1String("-");
QByteArray predefinedMacros = runGcc(gcc, arguments, env);
+ // Sanity check in case we get an error message instead of real output:
+ QTC_CHECK(predefinedMacros.startsWith("#define "));
if (Utils::HostOsInfo::isMacHost()) {
// Turn off flag indicating Apple's blocks support
const QByteArray blocksDefine("#define __BLOCKS__ 1");
@@ -212,75 +230,15 @@ static QList<Abi> guessGccAbi(const QString &m, const QByteArray &macros)
{
QList<Abi> abiList;
- QString machine = m.toLower();
- if (machine.isEmpty())
+ Abi guessed = Abi::abiFromTargetTriplet(m);
+ if (guessed.isNull())
return abiList;
- QStringList parts = machine.split(QRegExp(QLatin1String("[ /-]")));
-
- Abi::Architecture arch = Abi::UnknownArchitecture;
- Abi::OS os = Abi::UnknownOS;
- Abi::OSFlavor flavor = Abi::UnknownFlavor;
- Abi::BinaryFormat format = Abi::UnknownFormat;
- int width = 0;
- int unknownCount = 0;
-
- foreach (const QString &p, parts) {
- if (p == QLatin1String("unknown") || p == QLatin1String("pc") || p == QLatin1String("none")
- || p == QLatin1String("gnu") || p == QLatin1String("uclibc")
- || p == QLatin1String("86_64") || p == QLatin1String("redhat")
- || p == QLatin1String("gnueabi") || p == QLatin1String("w64")) {
- continue;
- } else if (p == QLatin1String("i386") || p == QLatin1String("i486") || p == QLatin1String("i586")
- || p == QLatin1String("i686") || p == QLatin1String("x86")) {
- arch = Abi::X86Architecture;
- } else if (p.startsWith(QLatin1String("arm"))) {
- arch = Abi::ArmArchitecture;
- width = 32;
- } else if (p == QLatin1String("mipsel")) {
- arch = Abi::MipsArchitecture;
- width = 32;
- } else if (p == QLatin1String("x86_64") || p == QLatin1String("amd64")) {
- arch = Abi::X86Architecture;
- width = 64;
- } else if (p == QLatin1String("powerpc64")) {
- arch = Abi::PowerPCArchitecture;
- width = 64;
- } else if (p == QLatin1String("powerpc")) {
- arch = Abi::PowerPCArchitecture;
- width = 32;
- } else if (p == QLatin1String("linux") || p == QLatin1String("linux6e")) {
- os = Abi::LinuxOS;
- if (flavor == Abi::UnknownFlavor)
- flavor = Abi::GenericLinuxFlavor;
- format = Abi::ElfFormat;
- } else if (p.startsWith(QLatin1String("freebsd"))) {
- os = Abi::BsdOS;
- if (flavor == Abi::UnknownFlavor)
- flavor = Abi::FreeBsdFlavor;
- format = Abi::ElfFormat;
- } else if (p == QLatin1String("mingw32") || p == QLatin1String("win32") || p == QLatin1String("mingw32msvc")) {
- arch = Abi::X86Architecture;
- os = Abi::WindowsOS;
- flavor = Abi::WindowsMSysFlavor;
- format = Abi::PEFormat;
- } else if (p == QLatin1String("apple")) {
- os = Abi::MacOS;
- flavor = Abi::GenericMacFlavor;
- format = Abi::MachOFormat;
- } else if (p == QLatin1String("darwin10")) {
- width = 64;
- } else if (p == QLatin1String("darwin9")) {
- width = 32;
- } else if (p == QLatin1String("gnueabi")) {
- format = Abi::ElfFormat;
- } else {
- ++unknownCount;
- }
- }
-
- if (unknownCount == parts.count())
- return abiList;
+ Abi::Architecture arch = guessed.architecture();
+ Abi::OS os = guessed.os();
+ Abi::OSFlavor flavor = guessed.osFlavor();
+ Abi::BinaryFormat format = guessed.binaryFormat();
+ int width = guessed.wordWidth();
if (os == Abi::MacOS && arch != Abi::ArmArchitecture) {
// Apple does PPC and x86!
@@ -307,6 +265,8 @@ static QList<Abi> guessGccAbi(const FileName &path, const QStringList &env,
QStringList arguments = extraArgs;
arguments << QLatin1String("-dumpmachine");
QString machine = QString::fromLocal8Bit(runGcc(path, arguments, env)).trimmed();
+ if (machine.isEmpty())
+ return QList<Abi>(); // no need to continue if running failed once...
QByteArray macros = gccPredefinedMacros(path, QStringList(), env);
return guessGccAbi(machine, macros);
}
@@ -321,12 +281,12 @@ static QString gccVersion(const FileName &path, const QStringList &env)
// GccToolChain
// --------------------------------------------------------------------------
-GccToolChain::GccToolChain(bool autodetect) :
- ToolChain(QLatin1String(Constants::GCC_TOOLCHAIN_ID), autodetect)
+GccToolChain::GccToolChain(Detection d) :
+ ToolChain(QLatin1String(Constants::GCC_TOOLCHAIN_ID), d)
{ }
-GccToolChain::GccToolChain(const QString &id, bool autodetect) :
- ToolChain(id, autodetect)
+GccToolChain::GccToolChain(const QString &id, Detection d) :
+ ToolChain(id, d)
{ }
GccToolChain::GccToolChain(const GccToolChain &tc) :
@@ -362,7 +322,7 @@ QString GccToolChain::type() const
QString GccToolChain::typeDisplayName() const
{
- return Internal::GccToolChainFactory::tr("GCC");
+ return GccToolChainFactory::tr("GCC");
}
Abi GccToolChain::targetAbi() const
@@ -549,12 +509,15 @@ QList<HeaderPath> GccToolChain::systemHeaderPaths(const QStringList &cxxflags, c
return m_headerPaths;
}
+void GccToolChain::addCommandPathToEnvironment(const FileName &command, Environment &env)
+{
+ if (!command.isEmpty())
+ env.prependOrSetPath(command.parentDir().toString());
+}
+
void GccToolChain::addToEnvironment(Environment &env) const
{
- if (!m_compilerCommand.isEmpty()) {
- FileName path = m_compilerCommand.parentDir();
- env.prependOrSetPath(path.toString());
- }
+ addCommandPathToEnvironment(m_compilerCommand, env);
}
QList<FileName> GccToolChain::suggestedMkspecList() const
@@ -725,7 +688,7 @@ bool GccToolChain::operator ==(const ToolChain &other) const
ToolChainConfigWidget *GccToolChain::configurationWidget()
{
- return new Internal::GccToolChainConfigWidget(this);
+ return new GccToolChainConfigWidget(this);
}
void GccToolChain::updateSupportedAbis() const
@@ -752,27 +715,23 @@ QString GccToolChain::detectVersion() const
// GccToolChainFactory
// --------------------------------------------------------------------------
-QString Internal::GccToolChainFactory::displayName() const
-{
- return tr("GCC");
-}
-
-QString Internal::GccToolChainFactory::id() const
+GccToolChainFactory::GccToolChainFactory()
{
- return QLatin1String(Constants::GCC_TOOLCHAIN_ID);
+ setId(Constants::GCC_TOOLCHAIN_ID);
+ setDisplayName(tr("GCC"));
}
-bool Internal::GccToolChainFactory::canCreate()
+bool GccToolChainFactory::canCreate()
{
return true;
}
-ToolChain *Internal::GccToolChainFactory::create()
+ToolChain *GccToolChainFactory::create()
{
return createToolChain(false);
}
-QList<ToolChain *> Internal::GccToolChainFactory::autoDetect()
+QList<ToolChain *> GccToolChainFactory::autoDetect()
{
QList<ToolChain *> tcs;
if (Utils::HostOsInfo::isMacHost()) {
@@ -786,16 +745,16 @@ QList<ToolChain *> Internal::GccToolChainFactory::autoDetect()
}
// Used by the ToolChainManager to restore user-generated tool chains
-bool Internal::GccToolChainFactory::canRestore(const QVariantMap &data)
+bool GccToolChainFactory::canRestore(const QVariantMap &data)
{
const QString id = idFromMap(data);
return id.startsWith(QLatin1String(Constants::GCC_TOOLCHAIN_ID) + QLatin1Char(':'))
|| id.startsWith(QLatin1String(LEGACY_MAEMO_ID));
}
-ToolChain *Internal::GccToolChainFactory::restore(const QVariantMap &data)
+ToolChain *GccToolChainFactory::restore(const QVariantMap &data)
{
- GccToolChain *tc = new GccToolChain(false);
+ GccToolChain *tc = new GccToolChain(ToolChain::ManualDetection);
// Updating from 2.5:
QVariantMap updated = data;
QString id = idFromMap(updated);
@@ -811,21 +770,22 @@ ToolChain *Internal::GccToolChainFactory::restore(const QVariantMap &data)
return 0;
}
-GccToolChain *Internal::GccToolChainFactory::createToolChain(bool autoDetect)
+GccToolChain *GccToolChainFactory::createToolChain(bool autoDetect)
{
- return new GccToolChain(autoDetect);
+ return new GccToolChain(autoDetect ? ToolChain::AutoDetection : ToolChain::ManualDetection);
}
-QList<ToolChain *> Internal::GccToolChainFactory::autoDetectToolchains(const QString &compiler,
+QList<ToolChain *> GccToolChainFactory::autoDetectToolchains(const QString &compiler,
const Abi &requiredAbi)
{
QList<ToolChain *> result;
- const Environment systemEnvironment = Environment::systemEnvironment();
+ Environment systemEnvironment = Environment::systemEnvironment();
const FileName compilerPath = FileName::fromString(systemEnvironment.searchInPath(compiler));
if (compilerPath.isEmpty())
return result;
+ GccToolChain::addCommandPathToEnvironment(compilerPath, systemEnvironment);
QList<Abi> abiList = guessGccAbi(compilerPath, systemEnvironment.toStringList());
if (!abiList.contains(requiredAbi)) {
if (requiredAbi.wordWidth() != 64
@@ -853,7 +813,7 @@ QList<ToolChain *> Internal::GccToolChainFactory::autoDetectToolchains(const QSt
// GccToolChainConfigWidget
// --------------------------------------------------------------------------
-Internal::GccToolChainConfigWidget::GccToolChainConfigWidget(GccToolChain *tc) :
+GccToolChainConfigWidget::GccToolChainConfigWidget(GccToolChain *tc) :
ToolChainConfigWidget(tc),
m_compilerCommand(new PathChooser),
m_abiWidget(new AbiWidget),
@@ -885,7 +845,7 @@ Internal::GccToolChainConfigWidget::GccToolChainConfigWidget(GccToolChain *tc) :
connect(m_abiWidget, SIGNAL(abiChanged()), this, SIGNAL(dirty()));
}
-void Internal::GccToolChainConfigWidget::applyImpl()
+void GccToolChainConfigWidget::applyImpl()
{
if (toolChain()->isAutoDetected())
return;
@@ -900,7 +860,7 @@ void Internal::GccToolChainConfigWidget::applyImpl()
tc->setPlatformLinkerFlags(splitString(m_platformLinkerFlagsLineEdit->text()));
}
-void Internal::GccToolChainConfigWidget::setFromToolchain()
+void GccToolChainConfigWidget::setFromToolchain()
{
// subwidgets are not yet connected!
bool blocked = blockSignals(true);
@@ -914,7 +874,7 @@ void Internal::GccToolChainConfigWidget::setFromToolchain()
blockSignals(blocked);
}
-bool Internal::GccToolChainConfigWidget::isDirtyImpl() const
+bool GccToolChainConfigWidget::isDirtyImpl() const
{
GccToolChain *tc = static_cast<GccToolChain *>(toolChain());
Q_ASSERT(tc);
@@ -924,7 +884,7 @@ bool Internal::GccToolChainConfigWidget::isDirtyImpl() const
|| m_abiWidget->currentAbi() != tc->targetAbi();
}
-void Internal::GccToolChainConfigWidget::makeReadOnlyImpl()
+void GccToolChainConfigWidget::makeReadOnlyImpl()
{
m_compilerCommand->setEnabled(false);
m_abiWidget->setEnabled(false);
@@ -933,7 +893,7 @@ void Internal::GccToolChainConfigWidget::makeReadOnlyImpl()
m_isReadOnly = true;
}
-QStringList Internal::GccToolChainConfigWidget::splitString(const QString &s)
+QStringList GccToolChainConfigWidget::splitString(const QString &s)
{
QtcProcess::SplitError splitError;
QStringList res = QtcProcess::splitArgs(s, false, &splitError);
@@ -948,7 +908,7 @@ QStringList Internal::GccToolChainConfigWidget::splitString(const QString &s)
return res;
}
-void Internal::GccToolChainConfigWidget::handleCompilerCommandChange()
+void GccToolChainConfigWidget::handleCompilerCommandChange()
{
FileName path = m_compilerCommand->fileName();
QList<Abi> abiList;
@@ -957,16 +917,19 @@ void Internal::GccToolChainConfigWidget::handleCompilerCommandChange()
QFileInfo fi(path.toFileInfo());
haveCompiler = fi.isExecutable() && fi.isFile();
}
- if (haveCompiler)
- abiList = guessGccAbi(path, Environment::systemEnvironment().toStringList(),
+ if (haveCompiler) {
+ Environment env = Environment::systemEnvironment();
+ GccToolChain::addCommandPathToEnvironment(path, env);
+ abiList = guessGccAbi(path, env.toStringList(),
splitString(m_platformCodeGenFlagsLineEdit->text()));
+ }
m_abiWidget->setEnabled(haveCompiler);
Abi currentAbi = m_abiWidget->currentAbi();
m_abiWidget->setAbis(abiList, abiList.contains(currentAbi) ? currentAbi : Abi());
emit dirty();
}
-void Internal::GccToolChainConfigWidget::handlePlatformCodeGenFlagsChange()
+void GccToolChainConfigWidget::handlePlatformCodeGenFlagsChange()
{
QString str1 = m_platformCodeGenFlagsLineEdit->text();
QString str2 = QtcProcess::joinArgs(splitString(str1));
@@ -976,7 +939,7 @@ void Internal::GccToolChainConfigWidget::handlePlatformCodeGenFlagsChange()
handleCompilerCommandChange();
}
-void Internal::GccToolChainConfigWidget::handlePlatformLinkerFlagsChange()
+void GccToolChainConfigWidget::handlePlatformLinkerFlagsChange()
{
QString str1 = m_platformLinkerFlagsLineEdit->text();
QString str2 = QtcProcess::joinArgs(splitString(str1));
@@ -990,8 +953,8 @@ void Internal::GccToolChainConfigWidget::handlePlatformLinkerFlagsChange()
// ClangToolChain
// --------------------------------------------------------------------------
-ClangToolChain::ClangToolChain(bool autodetect) :
- GccToolChain(QLatin1String(Constants::CLANG_TOOLCHAIN_ID), autodetect)
+ClangToolChain::ClangToolChain(Detection d) :
+ GccToolChain(QLatin1String(Constants::CLANG_TOOLCHAIN_ID), d)
{ }
QString ClangToolChain::type() const
@@ -1001,7 +964,7 @@ QString ClangToolChain::type() const
QString ClangToolChain::typeDisplayName() const
{
- return Internal::ClangToolChainFactory::tr("Clang");
+ return ClangToolChainFactory::tr("Clang");
}
QString ClangToolChain::makeCommand(const Utils::Environment &environment) const
@@ -1037,7 +1000,7 @@ ToolChain::CompilerFlags ClangToolChain::compilerFlags(const QStringList &cxxfla
ToolChain::WarningFlags ClangToolChain::warningFlags(const QStringList &cflags) const
{
- WarningFlags flags = GccToolChain::warningFlags(cflags);;
+ WarningFlags flags = GccToolChain::warningFlags(cflags);
foreach (const QString &flag, cflags) {
if (flag == QLatin1String("-Wdocumentation"))
flags |= WarnDocumentation;
@@ -1053,7 +1016,8 @@ QList<FileName> ClangToolChain::suggestedMkspecList() const
if (abi.os() == Abi::MacOS)
return QList<FileName>()
<< FileName::fromString(QLatin1String("macx-clang"))
- << FileName::fromString(QLatin1String("unsupported/macx-clang"));
+ << FileName::fromString(QLatin1String("unsupported/macx-clang"))
+ << FileName::fromString(QLatin1String("macx-ios-clang"));
else if (abi.os() == Abi::LinuxOS)
return QList<FileName>()
<< FileName::fromString(QLatin1String("linux-clang"))
@@ -1090,40 +1054,36 @@ ToolChain *ClangToolChain::clone() const
// ClangToolChainFactory
// --------------------------------------------------------------------------
-QString Internal::ClangToolChainFactory::displayName() const
-{
- return tr("Clang");
-}
-
-QString Internal::ClangToolChainFactory::id() const
+ClangToolChainFactory::ClangToolChainFactory()
{
- return QLatin1String(Constants::CLANG_TOOLCHAIN_ID);
+ setDisplayName(tr("Clang"));
+ setId(Constants::CLANG_TOOLCHAIN_ID);
}
-QList<ToolChain *> Internal::ClangToolChainFactory::autoDetect()
+QList<ToolChain *> ClangToolChainFactory::autoDetect()
{
Abi ha = Abi::hostAbi();
return autoDetectToolchains(QLatin1String("clang++"), ha);
}
-bool Internal::ClangToolChainFactory::canCreate()
+bool ClangToolChainFactory::canCreate()
{
return true;
}
-ToolChain *Internal::ClangToolChainFactory::create()
+ToolChain *ClangToolChainFactory::create()
{
return createToolChain(false);
}
-bool Internal::ClangToolChainFactory::canRestore(const QVariantMap &data)
+bool ClangToolChainFactory::canRestore(const QVariantMap &data)
{
return idFromMap(data).startsWith(QLatin1String(Constants::CLANG_TOOLCHAIN_ID) + QLatin1Char(':'));
}
-ToolChain *Internal::ClangToolChainFactory::restore(const QVariantMap &data)
+ToolChain *ClangToolChainFactory::restore(const QVariantMap &data)
{
- ClangToolChain *tc = new ClangToolChain(false);
+ ClangToolChain *tc = new ClangToolChain(ToolChain::ManualDetection);
if (tc->fromMap(data))
return tc;
@@ -1131,17 +1091,17 @@ ToolChain *Internal::ClangToolChainFactory::restore(const QVariantMap &data)
return 0;
}
-GccToolChain *Internal::ClangToolChainFactory::createToolChain(bool autoDetect)
+GccToolChain *ClangToolChainFactory::createToolChain(bool autoDetect)
{
- return new ClangToolChain(autoDetect);
+ return new ClangToolChain(autoDetect ? ToolChain::AutoDetection : ToolChain::ManualDetection);
}
// --------------------------------------------------------------------------
// MingwToolChain
// --------------------------------------------------------------------------
-MingwToolChain::MingwToolChain(bool autodetect) :
- GccToolChain(QLatin1String(Constants::MINGW_TOOLCHAIN_ID), autodetect)
+MingwToolChain::MingwToolChain(Detection d) :
+ GccToolChain(QLatin1String(Constants::MINGW_TOOLCHAIN_ID), d)
{ }
QString MingwToolChain::type() const
@@ -1151,7 +1111,7 @@ QString MingwToolChain::type() const
QString MingwToolChain::typeDisplayName() const
{
- return Internal::MingwToolChainFactory::tr("MinGW");
+ return MingwToolChainFactory::tr("MinGW");
}
QList<FileName> MingwToolChain::suggestedMkspecList() const
@@ -1199,41 +1159,37 @@ ToolChain *MingwToolChain::clone() const
// MingwToolChainFactory
// --------------------------------------------------------------------------
-QString Internal::MingwToolChainFactory::displayName() const
-{
- return tr("MinGW");
-}
-
-QString Internal::MingwToolChainFactory::id() const
+MingwToolChainFactory::MingwToolChainFactory()
{
- return QLatin1String(Constants::MINGW_TOOLCHAIN_ID);
+ setId(Constants::MINGW_TOOLCHAIN_ID);
+ setDisplayName(tr("MinGW"));
}
-QList<ToolChain *> Internal::MingwToolChainFactory::autoDetect()
+QList<ToolChain *> MingwToolChainFactory::autoDetect()
{
Abi ha = Abi::hostAbi();
return autoDetectToolchains(QLatin1String("g++"),
Abi(ha.architecture(), Abi::WindowsOS, Abi::WindowsMSysFlavor, Abi::PEFormat, ha.wordWidth()));
}
-bool Internal::MingwToolChainFactory::canCreate()
+bool MingwToolChainFactory::canCreate()
{
return true;
}
-ToolChain *Internal::MingwToolChainFactory::create()
+ToolChain *MingwToolChainFactory::create()
{
return createToolChain(false);
}
-bool Internal::MingwToolChainFactory::canRestore(const QVariantMap &data)
+bool MingwToolChainFactory::canRestore(const QVariantMap &data)
{
return idFromMap(data).startsWith(QLatin1String(Constants::MINGW_TOOLCHAIN_ID) + QLatin1Char(':'));
}
-ToolChain *Internal::MingwToolChainFactory::restore(const QVariantMap &data)
+ToolChain *MingwToolChainFactory::restore(const QVariantMap &data)
{
- MingwToolChain *tc = new MingwToolChain(false);
+ MingwToolChain *tc = new MingwToolChain(ToolChain::ManualDetection);
if (tc->fromMap(data))
return tc;
@@ -1241,17 +1197,17 @@ ToolChain *Internal::MingwToolChainFactory::restore(const QVariantMap &data)
return 0;
}
-GccToolChain *Internal::MingwToolChainFactory::createToolChain(bool autoDetect)
+GccToolChain *MingwToolChainFactory::createToolChain(bool autoDetect)
{
- return new MingwToolChain(autoDetect);
+ return new MingwToolChain(autoDetect ? ToolChain::AutoDetection : ToolChain::ManualDetection);
}
// --------------------------------------------------------------------------
// LinuxIccToolChain
// --------------------------------------------------------------------------
-LinuxIccToolChain::LinuxIccToolChain(bool autodetect) :
- GccToolChain(QLatin1String(Constants::LINUXICC_TOOLCHAIN_ID), autodetect)
+LinuxIccToolChain::LinuxIccToolChain(Detection d) :
+ GccToolChain(QLatin1String(Constants::LINUXICC_TOOLCHAIN_ID), d)
{ }
QString LinuxIccToolChain::type() const
@@ -1261,7 +1217,7 @@ QString LinuxIccToolChain::type() const
QString LinuxIccToolChain::typeDisplayName() const
{
- return Internal::LinuxIccToolChainFactory::tr("Linux ICC");
+ return LinuxIccToolChainFactory::tr("Linux ICC");
}
/**
@@ -1306,34 +1262,30 @@ ToolChain *LinuxIccToolChain::clone() const
// LinuxIccToolChainFactory
// --------------------------------------------------------------------------
-QString Internal::LinuxIccToolChainFactory::displayName() const
-{
- return tr("Linux ICC");
-}
-
-QString Internal::LinuxIccToolChainFactory::id() const
+LinuxIccToolChainFactory::LinuxIccToolChainFactory()
{
- return QLatin1String(Constants::LINUXICC_TOOLCHAIN_ID);
+ setDisplayName(tr("Linux ICC"));
+ setId(Constants::LINUXICC_TOOLCHAIN_ID);
}
-QList<ToolChain *> Internal::LinuxIccToolChainFactory::autoDetect()
+QList<ToolChain *> LinuxIccToolChainFactory::autoDetect()
{
return autoDetectToolchains(QLatin1String("icpc"), Abi::hostAbi());
}
-ToolChain *Internal::LinuxIccToolChainFactory::create()
+ToolChain *LinuxIccToolChainFactory::create()
{
return createToolChain(false);
}
-bool Internal::LinuxIccToolChainFactory::canRestore(const QVariantMap &data)
+bool LinuxIccToolChainFactory::canRestore(const QVariantMap &data)
{
return idFromMap(data).startsWith(QLatin1String(Constants::LINUXICC_TOOLCHAIN_ID) + QLatin1Char(':'));
}
-ToolChain *Internal::LinuxIccToolChainFactory::restore(const QVariantMap &data)
+ToolChain *LinuxIccToolChainFactory::restore(const QVariantMap &data)
{
- LinuxIccToolChain *tc = new LinuxIccToolChain(false);
+ LinuxIccToolChain *tc = new LinuxIccToolChain(ToolChain::ManualDetection);
if (tc->fromMap(data))
return tc;
@@ -1341,9 +1293,9 @@ ToolChain *Internal::LinuxIccToolChainFactory::restore(const QVariantMap &data)
return 0;
}
-GccToolChain *Internal::LinuxIccToolChainFactory::createToolChain(bool autoDetect)
+GccToolChain *LinuxIccToolChainFactory::createToolChain(bool autoDetect)
{
- return new LinuxIccToolChain(autoDetect);
+ return new LinuxIccToolChain(autoDetect ? ToolChain::AutoDetection : ToolChain::ManualDetection);
}
GccToolChain::WarningFlagAdder::WarningFlagAdder(const QString &flag, ToolChain::WarningFlags &flags) :
diff --git a/src/plugins/projectexplorer/gcctoolchain.h b/src/plugins/projectexplorer/gcctoolchain.h
index e445d74b7e..64dda77a30 100644
--- a/src/plugins/projectexplorer/gcctoolchain.h
+++ b/src/plugins/projectexplorer/gcctoolchain.h
@@ -55,7 +55,7 @@ class LinuxIccToolChainFactory;
class PROJECTEXPLORER_EXPORT GccToolChain : public ToolChain
{
public:
- GccToolChain(const QString &id, bool autodetect);
+ GccToolChain(const QString &id, Detection d);
QString type() const;
QString typeDisplayName() const;
Abi targetAbi() const;
@@ -91,6 +91,8 @@ public:
ToolChain *clone() const;
+ static void addCommandPathToEnvironment(const Utils::FileName &command, Utils::Environment &env);
+
protected:
typedef QList<QPair<QStringList, QByteArray> > GccCache;
@@ -122,7 +124,7 @@ protected:
};
private:
- GccToolChain(bool autodetect);
+ explicit GccToolChain(Detection d);
void updateSupportedAbis() const;
@@ -164,7 +166,7 @@ protected:
virtual CompilerFlags defaultCompilerFlags() const;
private:
- ClangToolChain(bool autodetect);
+ explicit ClangToolChain(Detection d);
friend class Internal::ClangToolChainFactory;
friend class ToolChainFactory;
@@ -186,7 +188,7 @@ public:
QList<Utils::FileName> suggestedMkspecList() const;
private:
- MingwToolChain(bool autodetect);
+ explicit MingwToolChain(Detection d);
friend class Internal::MingwToolChainFactory;
friend class ToolChainFactory;
@@ -210,7 +212,7 @@ public:
QList<Utils::FileName> suggestedMkspecList() const;
private:
- LinuxIccToolChain(bool autodetect);
+ explicit LinuxIccToolChain(Detection d);
friend class Internal::LinuxIccToolChainFactory;
friend class ToolChainFactory;
diff --git a/src/plugins/projectexplorer/gcctoolchainfactories.h b/src/plugins/projectexplorer/gcctoolchainfactories.h
index 7034b90215..7a2ef000de 100644
--- a/src/plugins/projectexplorer/gcctoolchainfactories.h
+++ b/src/plugins/projectexplorer/gcctoolchainfactories.h
@@ -55,16 +55,13 @@ class GccToolChainFactory : 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;
+ GccToolChainFactory();
QList<ToolChain *> autoDetect();
bool canCreate();
ToolChain *create();
- // Used by the ToolChainManager to restore user-generated tool chains
bool canRestore(const QVariantMap &data);
ToolChain *restore(const QVariantMap &data);
@@ -116,16 +113,13 @@ class ClangToolChainFactory : public GccToolChainFactory
Q_OBJECT
public:
- // Name used to display the name of the tool chain that will be created.
- QString displayName() const;
- QString id() const;
+ ClangToolChainFactory();
QList<ToolChain *> autoDetect();
bool canCreate();
ToolChain *create();
- // Used by the ToolChainManager to restore user-generated tool chains
bool canRestore(const QVariantMap &data);
ToolChain *restore(const QVariantMap &data);
@@ -142,16 +136,13 @@ class MingwToolChainFactory : public GccToolChainFactory
Q_OBJECT
public:
- // Name used to display the name of the tool chain that will be created.
- QString displayName() const;
- QString id() const;
+ MingwToolChainFactory();
QList<ToolChain *> autoDetect();
bool canCreate();
ToolChain *create();
- // Used by the ToolChainManager to restore user-generated tool chains
bool canRestore(const QVariantMap &data);
ToolChain *restore(const QVariantMap &data);
@@ -168,15 +159,12 @@ class LinuxIccToolChainFactory : public GccToolChainFactory
Q_OBJECT
public:
- // Name used to display the name of the tool chain that will be created.
- QString displayName() const;
- QString id() const;
+ LinuxIccToolChainFactory();
QList<ToolChain *> autoDetect();
ToolChain *create();
- // Used by the ToolChainManager to restore user-generated tool chains
bool canRestore(const QVariantMap &data);
ToolChain *restore(const QVariantMap &data);
diff --git a/src/plugins/projectexplorer/gnumakeparser.cpp b/src/plugins/projectexplorer/gnumakeparser.cpp
index e478255382..39be3acfb4 100644
--- a/src/plugins/projectexplorer/gnumakeparser.cpp
+++ b/src/plugins/projectexplorer/gnumakeparser.cpp
@@ -32,6 +32,8 @@
#include "projectexplorerconstants.h"
#include "task.h"
+#include <utils/qtcassert.h>
+
#include <QDir>
#include <QFile>
@@ -50,10 +52,13 @@ GnuMakeParser::GnuMakeParser() :
m_makeDir.setPattern(QLatin1String(MAKE_PATTERN) +
QLatin1String("(\\w+) directory .(.+).$"));
m_makeDir.setMinimal(true);
+ QTC_CHECK(m_makeDir.isValid());
m_makeLine.setPattern(QLatin1String(MAKE_PATTERN) + QLatin1String("(\\*\\*\\*\\s)?(.*)$"));
m_makeLine.setMinimal(true);
+ QTC_CHECK(m_makeLine.isValid());
m_makefileError.setPattern(QLatin1String("^(.*):(\\d+):\\s\\*\\*\\*\\s(.*)$"));
m_makefileError.setMinimal(true);
+ QTC_CHECK(m_makefileError.isValid());
}
void GnuMakeParser::setWorkingDirectory(const QString &workingDirectory)
@@ -333,9 +338,9 @@ void ProjectExplorerPlugin::testGnuMakeParserParsing_data()
<< QStringList();
QTest::newRow("pass-trough note")
<< QStringList()
- << QString::fromLatin1("/home/dev/creator/share/qtcreator/dumper/dumper.cpp:1079: note: initialized from here")
+ << QString::fromLatin1("/home/dev/creator/share/qtcreator/debugger/dumper.cpp:1079: note: initialized from here")
<< OutputParserTester::STDERR
- << QString() << QString::fromLatin1("/home/dev/creator/share/qtcreator/dumper/dumper.cpp:1079: note: initialized from here\n")
+ << QString() << QString::fromLatin1("/home/dev/creator/share/qtcreator/debugger/dumper.cpp:1079: note: initialized from here\n")
<< QList<ProjectExplorer::Task>()
<< QString()
<< QStringList();
@@ -424,12 +429,12 @@ void ProjectExplorerPlugin::testGnuMakeParserTaskMangling_data()
QLatin1String("no filename, no mangling"),
Utils::FileName(),
-1,
- Core::Id(Constants::TASK_CATEGORY_COMPILE))
+ Constants::TASK_CATEGORY_COMPILE)
<< Task(Task::Error,
QLatin1String("no filename, no mangling"),
Utils::FileName(),
-1,
- Core::Id(Constants::TASK_CATEGORY_COMPILE));
+ Constants::TASK_CATEGORY_COMPILE);
QTest::newRow("no mangling")
<< QStringList()
<< QStringList()
@@ -437,12 +442,12 @@ void ProjectExplorerPlugin::testGnuMakeParserTaskMangling_data()
QLatin1String("unknown filename, no mangling"),
Utils::FileName::fromUserInput(QLatin1String("some/path/unknown.cpp")),
-1,
- Core::Id(Constants::TASK_CATEGORY_COMPILE))
+ Constants::TASK_CATEGORY_COMPILE)
<< Task(Task::Error,
QLatin1String("unknown filename, no mangling"),
Utils::FileName::fromUserInput(QLatin1String("some/path/unknown.cpp")),
-1,
- Core::Id(Constants::TASK_CATEGORY_COMPILE));
+ Constants::TASK_CATEGORY_COMPILE);
QTest::newRow("find file")
<< (QStringList(QLatin1String("test/file.cpp")))
<< (QStringList(QLatin1String("test")))
@@ -450,12 +455,12 @@ void ProjectExplorerPlugin::testGnuMakeParserTaskMangling_data()
QLatin1String("mangling"),
Utils::FileName::fromUserInput(QLatin1String("file.cpp")),
10,
- Core::Id(Constants::TASK_CATEGORY_COMPILE))
+ Constants::TASK_CATEGORY_COMPILE)
<< Task(Task::Error,
QLatin1String("mangling"),
Utils::FileName::fromUserInput(QLatin1String("$TMPDIR/test/file.cpp")),
10,
- Core::Id(Constants::TASK_CATEGORY_COMPILE));
+ Constants::TASK_CATEGORY_COMPILE);
}
void ProjectExplorerPlugin::testGnuMakeParserTaskMangling()
diff --git a/src/plugins/qt4projectmanager/wizards/importwidget.cpp b/src/plugins/projectexplorer/importwidget.cpp
index d3e5d99395..01d0cb3880 100644
--- a/src/plugins/qt4projectmanager/wizards/importwidget.cpp
+++ b/src/plugins/projectexplorer/importwidget.cpp
@@ -35,7 +35,7 @@
#include <QPushButton>
#include <QVBoxLayout>
-namespace Qt4ProjectManager {
+namespace ProjectExplorer {
namespace Internal {
ImportWidget::ImportWidget(QWidget *parent) :
@@ -85,4 +85,4 @@ void ImportWidget::handleImportRequest()
}
} // namespace Internal
-} // namespace Qt4ProjectManager
+} // namespace ProjectExplorer
diff --git a/src/plugins/qt4projectmanager/wizards/importwidget.h b/src/plugins/projectexplorer/importwidget.h
index 9cb1d728ca..5eb88350da 100644
--- a/src/plugins/qt4projectmanager/wizards/importwidget.h
+++ b/src/plugins/projectexplorer/importwidget.h
@@ -37,7 +37,7 @@ class PathChooser;
class FileName;
} // namespace Utils
-namespace Qt4ProjectManager {
+namespace ProjectExplorer {
namespace Internal {
class ImportWidget : public QWidget
@@ -61,6 +61,6 @@ private:
};
} // namespace Internal
-} // namespace Qt4ProjectManager
+} // namespace ProjectExplorer
#endif // IMPORTWIDGET_H
diff --git a/src/plugins/projectexplorer/ioutputparser.cpp b/src/plugins/projectexplorer/ioutputparser.cpp
index 3a0e46e38a..ea073d0824 100644
--- a/src/plugins/projectexplorer/ioutputparser.cpp
+++ b/src/plugins/projectexplorer/ioutputparser.cpp
@@ -202,7 +202,7 @@ void IOutputParser::doFlush()
bool IOutputParser::hasFatalErrors() const
{
- return false || (m_parser && m_parser->hasFatalErrors());
+ return m_parser && m_parser->hasFatalErrors();
}
void IOutputParser::setWorkingDirectory(const QString &workingDirectory)
diff --git a/src/plugins/projectexplorer/iprojectmanager.h b/src/plugins/projectexplorer/iprojectmanager.h
index 3b7cd301b9..88be1a4509 100644
--- a/src/plugins/projectexplorer/iprojectmanager.h
+++ b/src/plugins/projectexplorer/iprojectmanager.h
@@ -34,9 +34,6 @@
#include <QObject>
-namespace Core {
-class Context;
-}
namespace ProjectExplorer {
class Project;
diff --git a/src/plugins/projectexplorer/kit.cpp b/src/plugins/projectexplorer/kit.cpp
index a25add3994..23bdd24292 100644
--- a/src/plugins/projectexplorer/kit.cpp
+++ b/src/plugins/projectexplorer/kit.cpp
@@ -31,8 +31,12 @@
#include "kitmanager.h"
#include "ioutputparser.h"
+#include "osparser.h"
+
+#include <utils/fileutils.h>
#include <QApplication>
+#include <QFileInfo>
#include <QIcon>
#include <QStyle>
#include <QTextStream>
@@ -48,27 +52,12 @@ const char AUTODETECTED_KEY[] = "PE.Profile.AutoDetected";
const char SDK_PROVIDED_KEY[] = "PE.Profile.SDK";
const char DATA_KEY[] = "PE.Profile.Data";
const char ICON_KEY[] = "PE.Profile.Icon";
+const char MUTABLE_INFO_KEY[] = "PE.Profile.MutableInfo";
} // namespace
namespace ProjectExplorer {
-// --------------------------------------------------------------------
-// Helper:
-// --------------------------------------------------------------------
-
-static QString cleanName(const QString &name)
-{
- QString result = name;
- 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;
-}
-
// -------------------------------------------------------------------------
// KitPrivate
// -------------------------------------------------------------------------
@@ -99,13 +88,14 @@ public:
bool m_isValid;
bool m_hasWarning;
QIcon m_icon;
- QString m_iconPath;
+ Utils::FileName m_iconPath;
int m_nestedBlockingLevel;
bool m_mustNotify;
bool m_mustNotifyAboutDisplayName;
QHash<Core::Id, QVariant> m_data;
QSet<Core::Id> m_sticky;
+ QSet<Core::Id> m_mutable;
};
} // namespace Internal
@@ -117,13 +107,12 @@ public:
Kit::Kit(Core::Id id) :
d(new Internal::KitPrivate(id))
{
- KitManager *stm = KitManager::instance();
KitGuard g(this);
- foreach (KitInformation *sti, stm->kitInformation())
- setValue(sti->dataId(), sti->defaultValue(this));
+ foreach (KitInformation *sti, KitManager::kitInformation())
+ setValue(sti->id(), sti->defaultValue(this));
setDisplayName(QCoreApplication::translate("ProjectExplorer::Kit", "Unnamed"));
- setIconPath(QLatin1String(":///DESKTOP///"));
+ setIconPath(Utils::FileName::fromString(QLatin1String(":///DESKTOP///")));
}
Kit::~Kit()
@@ -163,6 +152,7 @@ Kit *Kit::clone(bool keepName) const
k->d->m_icon = d->m_icon;
k->d->m_iconPath = d->m_iconPath;
k->d->m_sticky = d->m_sticky;
+ k->d->m_mutable = d->m_mutable;
return k;
}
@@ -177,6 +167,7 @@ void Kit::copyFrom(const Kit *k)
d->m_mustNotify = true;
d->m_mustNotifyAboutDisplayName = true;
d->m_sticky = k->d->m_sticky;
+ d->m_mutable = k->d->m_mutable;
}
bool Kit::isValid() const
@@ -192,7 +183,7 @@ bool Kit::hasWarning() const
QList<Task> Kit::validate() const
{
QList<Task> result;
- QList<KitInformation *> infoList = KitManager::instance()->kitInformation();
+ QList<KitInformation *> infoList = KitManager::kitInformation();
d->m_isValid = true;
d->m_hasWarning = false;
foreach (KitInformation *i, infoList) {
@@ -212,7 +203,7 @@ QList<Task> Kit::validate() const
void Kit::fix()
{
KitGuard g(this);
- foreach (KitInformation *i, KitManager::instance()->kitInformation())
+ foreach (KitInformation *i, KitManager::kitInformation())
i->fix(this);
}
@@ -221,7 +212,7 @@ void Kit::setup()
KitGuard g(this);
// Process the KitInfos in reverse order: They may only be based on other information lower in
// the stack.
- QList<KitInformation *> info = KitManager::instance()->kitInformation();
+ QList<KitInformation *> info = KitManager::kitInformation();
for (int i = info.count() - 1; i >= 0; --i)
info.at(i)->setup(this);
}
@@ -254,7 +245,7 @@ QStringList Kit::candidateNameList(const QString &base) const
{
QStringList result;
result << base;
- foreach (KitInformation *ki, KitManager::instance()->kitInformation()) {
+ foreach (KitInformation *ki, KitManager::kitInformation()) {
const QString postfix = ki->displayNamePostfix(this);
if (!postfix.isEmpty())
result << candidateName(base, postfix);
@@ -264,14 +255,14 @@ QStringList Kit::candidateNameList(const QString &base) const
QString Kit::fileSystemFriendlyName() const
{
- QString name = cleanName(displayName());
- foreach (Kit *i, KitManager::instance()->kits()) {
+ QString name = Utils::FileUtils::fileSystemFriendlyName(displayName());
+ foreach (Kit *i, KitManager::kits()) {
if (i == this)
continue;
- if (name == cleanName(i->displayName())) {
+ if (name == Utils::FileUtils::fileSystemFriendlyName(i->displayName())) {
// append part of the kit id: That should be unique enough;-)
// Leading { will be turned into _ which should be fine.
- name = cleanName(name + QLatin1Char('_') + (id().toString().left(7)));
+ name = Utils::FileUtils::fileSystemFriendlyName(name + QLatin1Char('_') + (id().toString().left(7)));
break;
}
}
@@ -298,22 +289,30 @@ QIcon Kit::icon() const
return d->m_icon;
}
-QString Kit::iconPath() const
+QIcon Kit::icon(const Utils::FileName &path)
+{
+ if (path.isEmpty())
+ return QIcon();
+ if (path == Utils::FileName::fromString(QLatin1String(":///DESKTOP///")))
+ return qApp->style()->standardIcon(QStyle::SP_ComputerIcon);
+
+ QFileInfo fi(path.toString());
+ if (fi.isFile() && fi.isReadable())
+ return QIcon(path.toString());
+ return QIcon();
+}
+
+Utils::FileName Kit::iconPath() const
{
return d->m_iconPath;
}
-void Kit::setIconPath(const QString &path)
+void Kit::setIconPath(const Utils::FileName &path)
{
if (d->m_iconPath == path)
return;
d->m_iconPath = path;
- if (path.isNull())
- d->m_icon = QIcon();
- else if (path == QLatin1String(":///DESKTOP///"))
- d->m_icon = qApp->style()->standardIcon(QStyle::SP_ComputerIcon);
- else
- d->m_icon = QIcon(path);
+ d->m_icon = icon(path);
kitUpdated();
}
@@ -341,6 +340,7 @@ void Kit::removeKey(Id key)
return;
d->m_data.remove(key);
d->m_sticky.remove(key);
+ d->m_mutable.remove(key);
kitUpdated();
}
@@ -358,7 +358,9 @@ bool Kit::isEqual(const Kit *other) const
{
return isDataEqual(other)
&& d->m_iconPath == other->d->m_iconPath
- && d->m_displayName == other->d->m_displayName;
+ && d->m_displayName == other->d->m_displayName
+ && d->m_mutable == other->d->m_mutable;
+
}
QVariantMap Kit::toMap() const
@@ -370,7 +372,12 @@ QVariantMap Kit::toMap() const
data.insert(QLatin1String(DISPLAYNAME_KEY), d->m_displayName);
data.insert(QLatin1String(AUTODETECTED_KEY), d->m_autodetected);
data.insert(QLatin1String(SDK_PROVIDED_KEY), d->m_sdkProvided);
- data.insert(QLatin1String(ICON_KEY), d->m_iconPath);
+ data.insert(QLatin1String(ICON_KEY), d->m_iconPath.toString());
+
+ QStringList mutableInfo;
+ foreach (const Core::Id &id, d->m_mutable.values())
+ mutableInfo << id.toString();
+ data.insert(QLatin1String(MUTABLE_INFO_KEY), mutableInfo);
QVariantMap extra;
@@ -384,22 +391,17 @@ QVariantMap Kit::toMap() const
void Kit::addToEnvironment(Utils::Environment &env) const
{
- QList<KitInformation *> infoList = KitManager::instance()->kitInformation();
+ QList<KitInformation *> infoList = KitManager::kitInformation();
foreach (KitInformation *ki, infoList)
ki->addToEnvironment(this, env);
}
IOutputParser *Kit::createOutputParser() const
{
- IOutputParser *first = 0;
- QList<KitInformation *> infoList = KitManager::instance()->kitInformation();
- foreach (KitInformation *ki, infoList) {
- IOutputParser *next = ki->createOutputParser(this);
- if (!first)
- first = next;
- else
- first->appendOutputParser(next);
- }
+ IOutputParser *first = new OsParser;
+ QList<KitInformation *> infoList = KitManager::kitInformation();
+ foreach (KitInformation *ki, infoList)
+ first->appendOutputParser(ki->createOutputParser(this));
return first;
}
@@ -432,7 +434,7 @@ QString Kit::toHtml() const
str << "</p>";
}
- QList<KitInformation *> infoList = KitManager::instance()->kitInformation();
+ QList<KitInformation *> infoList = KitManager::kitInformation();
foreach (KitInformation *ki, infoList) {
KitInformation::ItemList list = ki->toUserOutput(this);
foreach (const KitInformation::Item &j, list)
@@ -457,7 +459,7 @@ bool Kit::fromMap(const QVariantMap &data)
else
d->m_sdkProvided = d->m_autodetected;
setDisplayName(data.value(QLatin1String(DISPLAYNAME_KEY)).toString());
- setIconPath(data.value(QLatin1String(ICON_KEY)).toString());
+ setIconPath(Utils::FileName::fromString(data.value(QLatin1String(ICON_KEY)).toString()));
QVariantMap extra = data.value(QLatin1String(DATA_KEY)).toMap();
d->m_data.clear(); // remove default values
@@ -465,6 +467,11 @@ bool Kit::fromMap(const QVariantMap &data)
for (QVariantMap::ConstIterator it = extra.constBegin(); it != cend; ++it)
setValue(Id::fromString(it.key()), it.value());
+ QStringList mutableInfoList = data.value(QLatin1String(MUTABLE_INFO_KEY)).toStringList();
+ foreach (const QString &mutableInfo, mutableInfoList) {
+ d->m_mutable.insert(Core::Id::fromString(mutableInfo));
+ }
+
return true;
}
@@ -480,15 +487,36 @@ void Kit::setSdkProvided(bool sdkProvided)
void Kit::makeSticky()
{
- foreach (KitInformation *ki, KitManager::instance()->kitInformation()) {
- if (hasValue(ki->dataId()))
- makeSticky(ki->dataId());
+ foreach (KitInformation *ki, KitManager::kitInformation()) {
+ if (hasValue(ki->id()))
+ setSticky(ki->id(), true);
}
}
-void Kit::makeSticky(Core::Id id)
+void Kit::setSticky(Core::Id id, bool b)
+{
+ if (b)
+ d->m_sticky.insert(id);
+ else
+ d->m_sticky.remove(id);
+}
+
+void Kit::makeUnSticky()
+{
+ d->m_sticky.clear();
+}
+
+void Kit::setMutable(Id id, bool b)
+{
+ if (b)
+ d->m_mutable.insert(id);
+ else
+ d->m_mutable.remove(id);
+}
+
+bool Kit::isMutable(Id id) const
{
- d->m_sticky.insert(id);
+ return d->m_mutable.contains(id);
}
void Kit::kitUpdated()
@@ -498,7 +526,7 @@ void Kit::kitUpdated()
return;
}
validate();
- KitManager::instance()->notifyAboutUpdate(this);
+ KitManager::notifyAboutUpdate(this);
}
void Kit::kitDisplayNameChanged()
@@ -509,7 +537,7 @@ void Kit::kitDisplayNameChanged()
return;
}
validate();
- KitManager::instance()->notifyAboutDisplayNameChange(this);
+ KitManager::notifyAboutDisplayNameChange(this);
}
} // namespace ProjectExplorer
diff --git a/src/plugins/projectexplorer/kit.h b/src/plugins/projectexplorer/kit.h
index 0b1e292158..72deab3edd 100644
--- a/src/plugins/projectexplorer/kit.h
+++ b/src/plugins/projectexplorer/kit.h
@@ -80,8 +80,9 @@ public:
Core::Id id() const;
QIcon icon() const;
- QString iconPath() const;
- void setIconPath(const QString &path);
+ static QIcon icon(const Utils::FileName &path);
+ Utils::FileName iconPath() const;
+ void setIconPath(const Utils::FileName &path);
QVariant value(Core::Id key, const QVariant &unset = QVariant()) const;
bool hasValue(Core::Id key) const;
@@ -99,12 +100,17 @@ public:
Kit *clone(bool keepName = false) const;
void copyFrom(const Kit *k);
+ // Note: Stickyness is *not* saved!
void setAutoDetected(bool detected);
+ void makeSticky();
+ void setSticky(Core::Id id, bool b);
+ void makeUnSticky();
+
+ void setMutable(Core::Id id, bool b);
+ bool isMutable(Core::Id id) const;
private:
void setSdkProvided(bool sdkProvided);
- void makeSticky();
- void makeSticky(Core::Id id);
~Kit();
diff --git a/src/plugins/projectexplorer/kitchooser.cpp b/src/plugins/projectexplorer/kitchooser.cpp
index ff5bdafdcb..44bfdcff9c 100644
--- a/src/plugins/projectexplorer/kitchooser.cpp
+++ b/src/plugins/projectexplorer/kitchooser.cpp
@@ -31,8 +31,13 @@
#include "kitinformation.h"
#include "kitmanager.h"
+#include "projectexplorerconstants.h"
#include <coreplugin/icore.h>
+
+#include <QComboBox>
+#include <QHBoxLayout>
+#include <QPushButton>
#include <QSettings>
namespace ProjectExplorer {
@@ -40,9 +45,25 @@ namespace ProjectExplorer {
const char lastKitKey[] = "LastSelectedKit";
KitChooser::KitChooser(QWidget *parent) :
- QComboBox(parent)
+ QWidget(parent)
+{
+ m_chooser = new QComboBox(this);
+ m_manageButton = new QPushButton(tr("Manage..."), this);
+
+ QHBoxLayout *layout = new QHBoxLayout(this);
+ layout->setContentsMargins(0, 0, 0, 0);
+ layout->addWidget(m_chooser);
+ layout->addWidget(m_manageButton);
+
+ connect(m_chooser, SIGNAL(currentIndexChanged(int)), SLOT(onCurrentIndexChanged(int)));
+ connect(m_manageButton, SIGNAL(clicked()), SLOT(onManageButtonClicked()));
+ connect(KitManager::instance(), SIGNAL(kitsChanged()), SLOT(populate()));
+}
+
+void KitChooser::onManageButtonClicked()
{
- connect(this, SIGNAL(currentIndexChanged(int)), SLOT(onCurrentIndexChanged(int)));
+ Core::ICore::showOptionsDialog(Constants::PROJECTEXPLORER_SETTINGS_CATEGORY,
+ Constants::KITS_SETTINGS_PAGE_ID, this);
}
void KitChooser::onCurrentIndexChanged(int index)
@@ -51,6 +72,7 @@ void KitChooser::onCurrentIndexChanged(int index)
setToolTip(kitToolTip(kit));
else
setToolTip(QString());
+ emit currentIndexChanged(index);
}
bool KitChooser::kitMatches(const Kit *k) const
@@ -70,31 +92,31 @@ QString KitChooser::kitToolTip(Kit *k) const
void KitChooser::populate()
{
- clear();
- foreach (Kit *kit, KitManager::instance()->kits()) {
+ m_chooser->clear();
+ foreach (Kit *kit, KitManager::kits()) {
if (kitMatches(kit)) {
- addItem(kitText(kit), qVariantFromValue(kit->id()));
- setItemData(count() - 1, kitToolTip(kit), Qt::ToolTipRole);
+ m_chooser->addItem(kitText(kit), qVariantFromValue(kit->id()));
+ m_chooser->setItemData(m_chooser->count() - 1, kitToolTip(kit), Qt::ToolTipRole);
}
}
- setEnabled(count() > 1);
+ m_chooser->setEnabled(m_chooser->count() > 1);
const int index = Core::ICore::settings()->value(QLatin1String(lastKitKey)).toInt();
- setCurrentIndex(qMin(index, count()));
+ m_chooser->setCurrentIndex(qMin(index, m_chooser->count()));
}
Kit *KitChooser::currentKit() const
{
- const int index = currentIndex();
+ const int index = m_chooser->currentIndex();
Core::ICore::settings()->setValue(QLatin1String(lastKitKey), index);
return index == -1 ? 0 : kitAt(index);
}
void KitChooser::setCurrentKitId(Core::Id id)
{
- for (int i = 0, n = count(); i != n; ++i) {
+ for (int i = 0, n = m_chooser->count(); i != n; ++i) {
if (kitAt(i)->id() == id) {
- setCurrentIndex(i);
+ m_chooser->setCurrentIndex(i);
break;
}
}
@@ -108,8 +130,8 @@ Core::Id KitChooser::currentKitId() const
Kit *KitChooser::kitAt(int index) const
{
- Core::Id id = qvariant_cast<Core::Id>(itemData(index));
- return KitManager::instance()->find(id);
+ Core::Id id = qvariant_cast<Core::Id>(m_chooser->itemData(index));
+ return KitManager::find(id);
}
} // namespace ProjectExplorer
diff --git a/src/plugins/projectexplorer/kitchooser.h b/src/plugins/projectexplorer/kitchooser.h
index 3439741d66..eb16ca296c 100644
--- a/src/plugins/projectexplorer/kitchooser.h
+++ b/src/plugins/projectexplorer/kitchooser.h
@@ -32,7 +32,12 @@
#include "projectexplorer_export.h"
-#include <QComboBox>
+#include <QWidget>
+
+QT_BEGIN_NAMESPACE
+class QComboBox;
+class QPushButton;
+QT_END_NAMESPACE
namespace Core { class Id; }
@@ -41,7 +46,7 @@ namespace ProjectExplorer {
class Kit;
// Let the user pick a kit.
-class PROJECTEXPLORER_EXPORT KitChooser : public QComboBox
+class PROJECTEXPLORER_EXPORT KitChooser : public QWidget
{
Q_OBJECT
@@ -53,11 +58,15 @@ public:
Kit *currentKit() const;
+signals:
+ void currentIndexChanged(int);
+
public slots:
void populate();
private slots:
void onCurrentIndexChanged(int index);
+ void onManageButtonClicked();
protected:
virtual bool kitMatches(const Kit *k) const;
@@ -66,6 +75,8 @@ protected:
private:
Kit *kitAt(int index) const;
+ QComboBox *m_chooser;
+ QPushButton *m_manageButton;
};
} // namespace ProjectExplorer
diff --git a/src/plugins/projectexplorer/kitconfigwidget.cpp b/src/plugins/projectexplorer/kitconfigwidget.cpp
new file mode 100644
index 0000000000..2504cf682c
--- /dev/null
+++ b/src/plugins/projectexplorer/kitconfigwidget.cpp
@@ -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.
+**
+****************************************************************************/
+
+#include "kitconfigwidget.h"
+
+#include "kit.h"
+#include "kitinformation.h"
+
+namespace ProjectExplorer {
+
+KitConfigWidget::KitConfigWidget(Kit *kit, const KitInformation *ki) : m_kit(kit),
+ m_kitInformation(ki), m_isSticky(kit->isSticky(ki->id()))
+{ }
+
+Core::Id KitConfigWidget::kitInformationId() const
+{
+ return m_kitInformation->id();
+}
+
+bool KitConfigWidget::isMutable() const
+{
+ return m_kit->isMutable(m_kitInformation->id());
+}
+
+void KitConfigWidget::setMutable(bool b)
+{
+ m_kit->setMutable(m_kitInformation->id(), b);
+}
+
+} // namespace ProjectExplorer
diff --git a/src/plugins/projectexplorer/kitconfigwidget.h b/src/plugins/projectexplorer/kitconfigwidget.h
index a218684e4c..fbb4b745f8 100644
--- a/src/plugins/projectexplorer/kitconfigwidget.h
+++ b/src/plugins/projectexplorer/kitconfigwidget.h
@@ -32,11 +32,14 @@
#include "projectexplorer_export.h"
+#include <coreplugin/id.h>
+
#include <QWidget>
namespace ProjectExplorer {
class Kit;
+class KitInformation;
// --------------------------------------------------------------------------
// KitConfigWidget
@@ -47,7 +50,9 @@ class PROJECTEXPLORER_EXPORT KitConfigWidget : public QObject
Q_OBJECT
public:
- KitConfigWidget(Kit *kit, bool sticky) : m_kit(kit), m_isSticky(sticky) { }
+ KitConfigWidget(Kit *kit, const KitInformation *ki);
+
+ Core::Id kitInformationId() const;
virtual QString displayName() const = 0;
virtual QString toolTip() const { return QString(); }
@@ -58,13 +63,16 @@ public:
virtual QWidget *mainWidget() const = 0;
virtual QWidget *buttonWidget() const { return 0; }
- bool isSticky() { return m_isSticky; }
+ bool isSticky() const { return m_isSticky; }
+ bool isMutable() const;
+ void setMutable(bool b);
signals:
void dirty();
protected:
- ProjectExplorer::Kit *m_kit;
+ Kit *m_kit;
+ const KitInformation *m_kitInformation;
bool m_isSticky;
};
diff --git a/src/plugins/projectexplorer/kitinformation.cpp b/src/plugins/projectexplorer/kitinformation.cpp
index 27ea9e3ff8..23edc2d2ab 100644
--- a/src/plugins/projectexplorer/kitinformation.cpp
+++ b/src/plugins/projectexplorer/kitinformation.cpp
@@ -49,22 +49,11 @@ namespace ProjectExplorer {
// SysRootInformation:
// --------------------------------------------------------------------------
-static const char SYSROOT_INFORMATION[] = "PE.Profile.SysRoot";
-
SysRootKitInformation::SysRootKitInformation()
{
setObjectName(QLatin1String("SysRootInformation"));
-}
-
-Core::Id SysRootKitInformation::dataId() const
-{
- static const Core::Id id(SYSROOT_INFORMATION);
- return id;
-}
-
-unsigned int SysRootKitInformation::priority() const
-{
- return 31000;
+ setId(SysRootKitInformation::id());
+ setPriority(31000);
}
QVariant SysRootKitInformation::defaultValue(Kit *k) const
@@ -86,7 +75,7 @@ QList<Task> SysRootKitInformation::validate(const Kit *k) const
KitConfigWidget *SysRootKitInformation::createConfigWidget(Kit *k) const
{
- return new Internal::SysRootInformationConfigWidget(k, isSticky(k));
+ return new Internal::SysRootInformationConfigWidget(k, this);
}
KitInformation::ItemList SysRootKitInformation::toUserOutput(const Kit *k) const
@@ -94,10 +83,15 @@ KitInformation::ItemList SysRootKitInformation::toUserOutput(const Kit *k) const
return ItemList() << qMakePair(tr("Sys Root"), sysRoot(k).toUserOutput());
}
+Core::Id SysRootKitInformation::id()
+{
+ return "PE.Profile.SysRoot";
+}
+
bool SysRootKitInformation::hasSysRoot(const Kit *k)
{
if (k)
- return !k->value(Core::Id(SYSROOT_INFORMATION)).toString().isEmpty();
+ return !k->value(SysRootKitInformation::id()).toString().isEmpty();
return false;
}
@@ -105,46 +99,36 @@ Utils::FileName SysRootKitInformation::sysRoot(const Kit *k)
{
if (!k)
return Utils::FileName();
- return Utils::FileName::fromString(k->value(Core::Id(SYSROOT_INFORMATION)).toString());
+ return Utils::FileName::fromString(k->value(SysRootKitInformation::id()).toString());
}
void SysRootKitInformation::setSysRoot(Kit *k, const Utils::FileName &v)
{
- k->setValue(Core::Id(SYSROOT_INFORMATION), v.toString());
+ k->setValue(SysRootKitInformation::id(), v.toString());
}
// --------------------------------------------------------------------------
// ToolChainInformation:
// --------------------------------------------------------------------------
-static const char TOOLCHAIN_INFORMATION[] = "PE.Profile.ToolChain";
-
ToolChainKitInformation::ToolChainKitInformation()
{
setObjectName(QLatin1String("ToolChainInformation"));
+ setId(ToolChainKitInformation::id());
+ setPriority(30000);
+
connect(KitManager::instance(), SIGNAL(kitsLoaded()),
this, SLOT(kitsWereLoaded()));
}
-Core::Id ToolChainKitInformation::dataId() const
-{
- static const Core::Id id(TOOLCHAIN_INFORMATION);
- return id;
-}
-
-unsigned int ToolChainKitInformation::priority() const
-{
- return 30000;
-}
-
QVariant ToolChainKitInformation::defaultValue(Kit *k) const
{
Q_UNUSED(k);
- QList<ToolChain *> tcList = ToolChainManager::instance()->toolChains();
+ QList<ToolChain *> tcList = ToolChainManager::toolChains();
if (tcList.isEmpty())
return QString();
- ProjectExplorer::Abi abi = ProjectExplorer::Abi::hostAbi();
+ Abi abi = Abi::hostAbi();
foreach (ToolChain *tc, tcList) {
if (tc->targetAbi() == abi)
@@ -170,7 +154,7 @@ QList<Task> ToolChainKitInformation::validate(const Kit *k) const
void ToolChainKitInformation::fix(Kit *k)
{
- QTC_ASSERT(ToolChainManager::instance()->isLoaded(), return);
+ QTC_ASSERT(ToolChainManager::isLoaded(), return);
if (toolChain(k))
return;
@@ -181,17 +165,17 @@ void ToolChainKitInformation::fix(Kit *k)
void ToolChainKitInformation::setup(Kit *k)
{
- QTC_ASSERT(ToolChainManager::instance()->isLoaded(), return);
- const QString id = k->value(Core::Id(TOOLCHAIN_INFORMATION)).toString();
+ QTC_ASSERT(ToolChainManager::isLoaded(), return);
+ const QString id = k->value(ToolChainKitInformation::id()).toString();
if (id.isEmpty())
return;
- ToolChain *tc = ToolChainManager::instance()->findToolChain(id);
+ ToolChain *tc = ToolChainManager::findToolChain(id);
if (tc)
return;
// ID is not found: Might be an ABI string...
- foreach (ToolChain *current, ToolChainManager::instance()->toolChains()) {
+ foreach (ToolChain *current, ToolChainManager::toolChains()) {
if (current->targetAbi().toString() == id)
return setToolChain(k, current);
}
@@ -199,7 +183,7 @@ void ToolChainKitInformation::setup(Kit *k)
KitConfigWidget *ToolChainKitInformation::createConfigWidget(Kit *k) const
{
- return new Internal::ToolChainInformationConfigWidget(k, isSticky(k));
+ return new Internal::ToolChainInformationConfigWidget(k, this);
}
QString ToolChainKitInformation::displayNamePostfix(const Kit *k) const
@@ -229,18 +213,22 @@ IOutputParser *ToolChainKitInformation::createOutputParser(const Kit *k) const
return 0;
}
+Core::Id ToolChainKitInformation::id()
+{
+ return "PE.Profile.ToolChain";
+}
+
ToolChain *ToolChainKitInformation::toolChain(const Kit *k)
{
- QTC_ASSERT(ToolChainManager::instance()->isLoaded(), return 0);
+ QTC_ASSERT(ToolChainManager::isLoaded(), return 0);
if (!k)
return 0;
- return ToolChainManager::instance()
- ->findToolChain(k->value(Core::Id(TOOLCHAIN_INFORMATION)).toString());
+ return ToolChainManager::findToolChain(k->value(ToolChainKitInformation::id()).toString());
}
void ToolChainKitInformation::setToolChain(Kit *k, ToolChain *tc)
{
- k->setValue(Core::Id(TOOLCHAIN_INFORMATION), tc ? tc->id() : QString());
+ k->setValue(ToolChainKitInformation::id(), tc ? tc->id() : QString());
}
QString ToolChainKitInformation::msgNoToolChainInTarget()
@@ -250,7 +238,7 @@ QString ToolChainKitInformation::msgNoToolChainInTarget()
void ToolChainKitInformation::kitsWereLoaded()
{
- foreach (Kit *k, KitManager::instance()->kits())
+ foreach (Kit *k, KitManager::kits())
fix(k);
connect(ToolChainManager::instance(), SIGNAL(toolChainRemoved(ProjectExplorer::ToolChain*)),
@@ -259,17 +247,16 @@ void ToolChainKitInformation::kitsWereLoaded()
this, SLOT(toolChainUpdated(ProjectExplorer::ToolChain*)));
}
-void ToolChainKitInformation::toolChainUpdated(ProjectExplorer::ToolChain *tc)
+void ToolChainKitInformation::toolChainUpdated(ToolChain *tc)
{
- ToolChainMatcher m(tc);
- foreach (Kit *k, KitManager::instance()->kits(&m))
+ foreach (Kit *k, KitManager::matchingKits(ToolChainMatcher(tc)))
notifyAboutUpdate(k);
}
-void ToolChainKitInformation::toolChainRemoved(ProjectExplorer::ToolChain *tc)
+void ToolChainKitInformation::toolChainRemoved(ToolChain *tc)
{
Q_UNUSED(tc);
- foreach (Kit *k, KitManager::instance()->kits())
+ foreach (Kit *k, KitManager::kits())
fix(k);
}
@@ -277,22 +264,11 @@ void ToolChainKitInformation::toolChainRemoved(ProjectExplorer::ToolChain *tc)
// DeviceTypeInformation:
// --------------------------------------------------------------------------
-static const char DEVICETYPE_INFORMATION[] = "PE.Profile.DeviceType";
-
DeviceTypeKitInformation::DeviceTypeKitInformation()
{
setObjectName(QLatin1String("DeviceTypeInformation"));
-}
-
-Core::Id DeviceTypeKitInformation::dataId() const
-{
- static const Core::Id id(DEVICETYPE_INFORMATION);
- return id;
-}
-
-unsigned int DeviceTypeKitInformation::priority() const
-{
- return 33000;
+ setId(DeviceTypeKitInformation::id());
+ setPriority(33000);
}
QVariant DeviceTypeKitInformation::defaultValue(Kit *k) const
@@ -309,7 +285,7 @@ QList<Task> DeviceTypeKitInformation::validate(const Kit *k) const
KitConfigWidget *DeviceTypeKitInformation::createConfigWidget(Kit *k) const
{
- return new Internal::DeviceTypeInformationConfigWidget(k, isSticky(k));
+ return new Internal::DeviceTypeInformationConfigWidget(k, this);
}
KitInformation::ItemList DeviceTypeKitInformation::toUserOutput(const Kit *k) const
@@ -318,7 +294,7 @@ KitInformation::ItemList DeviceTypeKitInformation::toUserOutput(const Kit *k) co
QString typeDisplayName = tr("Unknown device type");
if (type.isValid()) {
QList<IDeviceFactory *> factories
- = ExtensionSystem::PluginManager::instance()->getObjects<IDeviceFactory>();
+ = ExtensionSystem::PluginManager::getObjects<IDeviceFactory>();
foreach (IDeviceFactory *factory, factories) {
if (factory->availableCreationIds().contains(type)) {
typeDisplayName = factory->displayNameForId(type);
@@ -329,40 +305,35 @@ KitInformation::ItemList DeviceTypeKitInformation::toUserOutput(const Kit *k) co
return ItemList() << qMakePair(tr("Device type"), typeDisplayName);
}
+const Core::Id DeviceTypeKitInformation::id()
+{
+ return "PE.Profile.DeviceType";
+}
+
const Core::Id DeviceTypeKitInformation::deviceTypeId(const Kit *k)
{
- return k ? Core::Id::fromSetting(k->value(DEVICETYPE_INFORMATION)) : Core::Id();
+ return k ? Core::Id::fromSetting(k->value(DeviceTypeKitInformation::id())) : Core::Id();
}
void DeviceTypeKitInformation::setDeviceTypeId(Kit *k, Core::Id type)
{
- k->setValue(DEVICETYPE_INFORMATION, type.toSetting());
+ k->setValue(DeviceTypeKitInformation::id(), type.toSetting());
}
// --------------------------------------------------------------------------
// DeviceInformation:
// --------------------------------------------------------------------------
-static const char DEVICE_INFORMATION[] = "PE.Profile.Device";
-
DeviceKitInformation::DeviceKitInformation()
{
setObjectName(QLatin1String("DeviceInformation"));
+ setId(DeviceKitInformation::id());
+ setPriority(32000);
+
connect(KitManager::instance(), SIGNAL(kitsLoaded()),
this, SLOT(kitsWereLoaded()));
}
-Core::Id DeviceKitInformation::dataId() const
-{
- static const Core::Id id(DEVICE_INFORMATION);
- return id;
-}
-
-unsigned int DeviceKitInformation::priority() const
-{
- return 32000;
-}
-
QVariant DeviceKitInformation::defaultValue(Kit *k) const
{
Core::Id type = DeviceTypeKitInformation::deviceTypeId(k);
@@ -405,7 +376,7 @@ void DeviceKitInformation::setup(Kit *k)
KitConfigWidget *DeviceKitInformation::createConfigWidget(Kit *k) const
{
- return new Internal::DeviceInformationConfigWidget(k, isSticky(k));
+ return new Internal::DeviceInformationConfigWidget(k, this);
}
QString DeviceKitInformation::displayNamePostfix(const Kit *k) const
@@ -420,6 +391,11 @@ KitInformation::ItemList DeviceKitInformation::toUserOutput(const Kit *k) const
return ItemList() << qMakePair(tr("Device"), dev.isNull() ? tr("Unconfigured") : dev->displayName());
}
+Core::Id DeviceKitInformation::id()
+{
+ return "PE.Profile.Device";
+}
+
IDevice::ConstPtr DeviceKitInformation::device(const Kit *k)
{
QTC_ASSERT(DeviceManager::instance()->isLoaded(), return IDevice::ConstPtr());
@@ -428,7 +404,7 @@ IDevice::ConstPtr DeviceKitInformation::device(const Kit *k)
Core::Id DeviceKitInformation::deviceId(const Kit *k)
{
- return k ? Core::Id::fromSetting(k->value(DEVICE_INFORMATION)) : Core::Id();
+ return k ? Core::Id::fromSetting(k->value(DeviceKitInformation::id())) : Core::Id();
}
void DeviceKitInformation::setDevice(Kit *k, IDevice::ConstPtr dev)
@@ -438,16 +414,16 @@ void DeviceKitInformation::setDevice(Kit *k, IDevice::ConstPtr dev)
void DeviceKitInformation::setDeviceId(Kit *k, const Core::Id id)
{
- k->setValue(DEVICE_INFORMATION, id.toSetting());
+ k->setValue(DeviceKitInformation::id(), id.toSetting());
}
void DeviceKitInformation::kitsWereLoaded()
{
- foreach (Kit *k, KitManager::instance()->kits())
+ foreach (Kit *k, KitManager::kits())
fix(k);
DeviceManager *dm = DeviceManager::instance();
- connect(dm, SIGNAL(deviceListChanged()), this, SLOT(devicesChanged()));
+ connect(dm, SIGNAL(deviceListReplaced()), this, SLOT(devicesChanged()));
connect(dm, SIGNAL(deviceAdded(Core::Id)), this, SLOT(devicesChanged()));
connect(dm, SIGNAL(deviceRemoved(Core::Id)), this, SLOT(devicesChanged()));
connect(dm, SIGNAL(deviceUpdated(Core::Id)), this, SLOT(deviceUpdated(Core::Id)));
@@ -460,7 +436,7 @@ void DeviceKitInformation::kitsWereLoaded()
void DeviceKitInformation::deviceUpdated(const Core::Id &id)
{
- foreach (Kit *k, KitManager::instance()->kits()) {
+ foreach (Kit *k, KitManager::kits()) {
if (deviceId(k) == id)
notifyAboutUpdate(k);
}
@@ -473,7 +449,7 @@ void DeviceKitInformation::kitUpdated(Kit *k)
void DeviceKitInformation::devicesChanged()
{
- foreach (Kit *k, KitManager::instance()->kits())
+ foreach (Kit *k, KitManager::kits())
setup(k); // Set default device if necessary
}
diff --git a/src/plugins/projectexplorer/kitinformation.h b/src/plugins/projectexplorer/kitinformation.h
index 60d322e126..8de48b27ae 100644
--- a/src/plugins/projectexplorer/kitinformation.h
+++ b/src/plugins/projectexplorer/kitinformation.h
@@ -53,9 +53,6 @@ class PROJECTEXPLORER_EXPORT SysRootKitInformation : public KitInformation
public:
SysRootKitInformation();
- Core::Id dataId() const;
- unsigned int priority() const;
-
QVariant defaultValue(Kit *k) const;
QList<Task> validate(const Kit *k) const;
@@ -64,6 +61,7 @@ public:
ItemList toUserOutput(const Kit *k) const;
+ static Core::Id id();
static bool hasSysRoot(const Kit *k);
static Utils::FileName sysRoot(const Kit *k);
static void setSysRoot(Kit *k, const Utils::FileName &v);
@@ -95,9 +93,6 @@ class PROJECTEXPLORER_EXPORT ToolChainKitInformation : public KitInformation
public:
ToolChainKitInformation();
- Core::Id dataId() const;
- unsigned int priority() const;
-
QVariant defaultValue(Kit *k) const;
QList<Task> validate(const Kit *k) const;
@@ -113,10 +108,12 @@ public:
void addToEnvironment(const Kit *k, Utils::Environment &env) const;
IOutputParser *createOutputParser(const Kit *k) const;
+ static Core::Id id();
static ToolChain *toolChain(const Kit *k);
static void setToolChain(Kit *k, ToolChain *tc);
static QString msgNoToolChainInTarget();
+
private slots:
void kitsWereLoaded();
void toolChainUpdated(ProjectExplorer::ToolChain *tc);
@@ -149,9 +146,6 @@ class PROJECTEXPLORER_EXPORT DeviceTypeKitInformation : public KitInformation
public:
DeviceTypeKitInformation();
- Core::Id dataId() const;
- unsigned int priority() const;
-
QVariant defaultValue(Kit *k) const;
QList<Task> validate(const Kit *k) const;
@@ -160,6 +154,7 @@ public:
ItemList toUserOutput(const Kit *k) const;
+ static const Core::Id id();
static const Core::Id deviceTypeId(const Kit *k);
static void setDeviceTypeId(Kit *k, Core::Id type);
};
@@ -193,9 +188,6 @@ class PROJECTEXPLORER_EXPORT DeviceKitInformation : public KitInformation
public:
DeviceKitInformation();
- Core::Id dataId() const;
- unsigned int priority() const;
-
QVariant defaultValue(Kit *k) const;
QList<Task> validate(const Kit *k) const;
@@ -208,14 +200,15 @@ public:
ItemList toUserOutput(const Kit *k) const;
+ static Core::Id id();
static IDevice::ConstPtr device(const Kit *k);
static Core::Id deviceId(const Kit *k);
static void setDevice(Kit *k, IDevice::ConstPtr dev);
- static void setDeviceId(Kit *k, const Core::Id id);
+ static void setDeviceId(Kit *k, const Core::Id dataId);
private slots:
void kitsWereLoaded();
- void deviceUpdated(const Core::Id &id);
+ void deviceUpdated(const Core::Id &dataId);
void devicesChanged();
void kitUpdated(ProjectExplorer::Kit *k);
};
diff --git a/src/plugins/projectexplorer/kitinformationconfigwidget.cpp b/src/plugins/projectexplorer/kitinformationconfigwidget.cpp
index 84bcebfead..d3a43ba096 100644
--- a/src/plugins/projectexplorer/kitinformationconfigwidget.cpp
+++ b/src/plugins/projectexplorer/kitinformationconfigwidget.cpp
@@ -55,8 +55,8 @@ namespace Internal {
// SysRootInformationConfigWidget:
// --------------------------------------------------------------------------
-SysRootInformationConfigWidget::SysRootInformationConfigWidget(Kit *k, bool sticky) :
- KitConfigWidget(k, sticky),
+SysRootInformationConfigWidget::SysRootInformationConfigWidget(Kit *k, const KitInformation *ki) :
+ KitConfigWidget(k, ki),
m_ignoreChange(false)
{
m_chooser = new Utils::PathChooser;
@@ -65,6 +65,11 @@ SysRootInformationConfigWidget::SysRootInformationConfigWidget(Kit *k, bool stic
connect(m_chooser, SIGNAL(changed(QString)), this, SLOT(pathWasChanged()));
}
+SysRootInformationConfigWidget::~SysRootInformationConfigWidget()
+{
+ delete m_chooser;
+}
+
QString SysRootInformationConfigWidget::displayName() const
{
return tr("Sysroot:");
@@ -73,7 +78,7 @@ QString SysRootInformationConfigWidget::displayName() const
QString SysRootInformationConfigWidget::toolTip() const
{
return tr("The root directory of the system image to use.<br>"
- "Leave empty when building for the desktop.");
+ "Leave empty when building for the desktop.");
}
void SysRootInformationConfigWidget::refresh()
@@ -108,15 +113,14 @@ void SysRootInformationConfigWidget::pathWasChanged()
// ToolChainInformationConfigWidget:
// --------------------------------------------------------------------------
-ToolChainInformationConfigWidget::ToolChainInformationConfigWidget(Kit *k, bool sticky) :
- KitConfigWidget(k, sticky), m_isReadOnly(false)
+ToolChainInformationConfigWidget::ToolChainInformationConfigWidget(Kit *k, const KitInformation *ki) :
+ KitConfigWidget(k, ki)
{
- ToolChainManager *tcm = ToolChainManager::instance();
-
m_comboBox = new QComboBox;
m_comboBox->setEnabled(false);
+ m_comboBox->setToolTip(toolTip());
- foreach (ToolChain *tc, tcm->toolChains())
+ foreach (ToolChain *tc, ToolChainManager::toolChains())
toolChainAdded(tc);
updateComboBox();
@@ -128,6 +132,7 @@ ToolChainInformationConfigWidget::ToolChainInformationConfigWidget(Kit *k, bool
m_manageButton->setContentsMargins(0, 0, 0, 0);
connect(m_manageButton, SIGNAL(clicked()), this, SLOT(manageToolChains()));
+ QObject *tcm = ToolChainManager::instance();
connect(tcm, SIGNAL(toolChainAdded(ProjectExplorer::ToolChain*)),
this, SLOT(toolChainAdded(ProjectExplorer::ToolChain*)));
connect(tcm, SIGNAL(toolChainRemoved(ProjectExplorer::ToolChain*)),
@@ -136,6 +141,12 @@ ToolChainInformationConfigWidget::ToolChainInformationConfigWidget(Kit *k, bool
this, SLOT(toolChainUpdated(ProjectExplorer::ToolChain*)));
}
+ToolChainInformationConfigWidget::~ToolChainInformationConfigWidget()
+{
+ delete m_comboBox;
+ delete m_manageButton;
+}
+
QString ToolChainInformationConfigWidget::displayName() const
{
return tr("Compiler:");
@@ -199,8 +210,7 @@ void ToolChainInformationConfigWidget::manageToolChains()
void ToolChainInformationConfigWidget::currentToolChainChanged(int idx)
{
const QString id = m_comboBox->itemData(idx).toString();
- ToolChain *tc = ToolChainManager::instance()->findToolChain(id);
- ToolChainKitInformation::setToolChain(m_kit, tc);
+ ToolChainKitInformation::setToolChain(m_kit, ToolChainManager::findToolChain(id));
}
void ToolChainInformationConfigWidget::updateComboBox()
@@ -214,7 +224,7 @@ void ToolChainInformationConfigWidget::updateComboBox()
m_comboBox->addItem(tr("<No compiler available>"), QString());
m_comboBox->setEnabled(false);
} else {
- m_comboBox->setEnabled(!m_isReadOnly);
+ m_comboBox->setEnabled(true);
}
}
@@ -232,20 +242,27 @@ int ToolChainInformationConfigWidget::indexOf(const ToolChain *tc)
// DeviceTypeInformationConfigWidget:
// --------------------------------------------------------------------------
-DeviceTypeInformationConfigWidget::DeviceTypeInformationConfigWidget(Kit *workingCopy, bool sticky) :
- KitConfigWidget(workingCopy, sticky), m_isReadOnly(false), m_comboBox(new QComboBox)
+DeviceTypeInformationConfigWidget::DeviceTypeInformationConfigWidget(Kit *workingCopy, const KitInformation *ki) :
+ KitConfigWidget(workingCopy, ki), m_comboBox(new QComboBox)
{
QList<IDeviceFactory *> factories
- = ExtensionSystem::PluginManager::instance()->getObjects<IDeviceFactory>();
+ = ExtensionSystem::PluginManager::getObjects<IDeviceFactory>();
foreach (IDeviceFactory *factory, factories) {
foreach (Core::Id id, factory->availableCreationIds())
m_comboBox->addItem(factory->displayNameForId(id), id.uniqueIdentifier());
}
+ m_comboBox->setToolTip(toolTip());
+
refresh();
connect(m_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(currentTypeChanged(int)));
}
+DeviceTypeInformationConfigWidget::~DeviceTypeInformationConfigWidget()
+{
+ delete m_comboBox;
+}
+
QWidget *DeviceTypeInformationConfigWidget::mainWidget() const
{
return m_comboBox;
@@ -289,8 +306,8 @@ void DeviceTypeInformationConfigWidget::currentTypeChanged(int idx)
// DeviceInformationConfigWidget:
// --------------------------------------------------------------------------
-DeviceInformationConfigWidget::DeviceInformationConfigWidget(Kit *workingCopy, bool sticky) :
- KitConfigWidget(workingCopy, sticky),
+DeviceInformationConfigWidget::DeviceInformationConfigWidget(Kit *workingCopy, const KitInformation *ki) :
+ KitConfigWidget(workingCopy, ki),
m_isReadOnly(false),
m_ignoreChange(false),
m_comboBox(new QComboBox),
@@ -301,12 +318,21 @@ DeviceInformationConfigWidget::DeviceInformationConfigWidget(Kit *workingCopy, b
m_manageButton = new QPushButton(tr("Manage"));
refresh();
+ m_comboBox->setToolTip(toolTip());
+
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()));
}
+DeviceInformationConfigWidget::~DeviceInformationConfigWidget()
+{
+ delete m_comboBox;
+ delete m_model;
+ delete m_manageButton;
+}
+
QWidget *DeviceInformationConfigWidget::mainWidget() const
{
return m_comboBox;
diff --git a/src/plugins/projectexplorer/kitinformationconfigwidget.h b/src/plugins/projectexplorer/kitinformationconfigwidget.h
index 5847a9de8b..36d710a707 100644
--- a/src/plugins/projectexplorer/kitinformationconfigwidget.h
+++ b/src/plugins/projectexplorer/kitinformationconfigwidget.h
@@ -57,7 +57,8 @@ class SysRootInformationConfigWidget : public KitConfigWidget
Q_OBJECT
public:
- explicit SysRootInformationConfigWidget(Kit *k, bool sticky);
+ SysRootInformationConfigWidget(Kit *k, const KitInformation *ki);
+ ~SysRootInformationConfigWidget();
QString displayName() const;
void refresh();
@@ -83,7 +84,8 @@ class ToolChainInformationConfigWidget : public KitConfigWidget
Q_OBJECT
public:
- explicit ToolChainInformationConfigWidget(Kit *k, bool sticky);
+ ToolChainInformationConfigWidget(Kit *k, const KitInformation *ki);
+ ~ToolChainInformationConfigWidget();
QString displayName() const;
void refresh();
@@ -103,7 +105,6 @@ private:
void updateComboBox();
int indexOf(const ToolChain *tc);
- bool m_isReadOnly;
QComboBox *m_comboBox;
QPushButton *m_manageButton;
};
@@ -117,7 +118,8 @@ class DeviceTypeInformationConfigWidget : public KitConfigWidget
Q_OBJECT
public:
- explicit DeviceTypeInformationConfigWidget(Kit *workingCopy, bool sticky);
+ DeviceTypeInformationConfigWidget(Kit *workingCopy, const KitInformation *ki);
+ ~DeviceTypeInformationConfigWidget();
QWidget *mainWidget() const;
QString displayName() const;
@@ -129,7 +131,6 @@ private slots:
void currentTypeChanged(int idx);
private:
- bool m_isReadOnly;
QComboBox *m_comboBox;
};
@@ -142,7 +143,8 @@ class DeviceInformationConfigWidget : public KitConfigWidget
Q_OBJECT
public:
- explicit DeviceInformationConfigWidget(Kit *workingCopy, bool sticky);
+ DeviceInformationConfigWidget(Kit *workingCopy, const KitInformation *ki);
+ ~DeviceInformationConfigWidget();
QWidget *mainWidget() const;
QWidget *buttonWidget() const;
diff --git a/src/plugins/projectexplorer/kitmanager.cpp b/src/plugins/projectexplorer/kitmanager.cpp
index 4f83acf79f..88f5ed77af 100644
--- a/src/plugins/projectexplorer/kitmanager.cpp
+++ b/src/plugins/projectexplorer/kitmanager.cpp
@@ -60,9 +60,6 @@ static Utils::FileName settingsFileName()
}
namespace ProjectExplorer {
-
-KitManager *KitManager::m_instance = 0;
-
namespace Internal {
// --------------------------------------------------------------------------
@@ -129,15 +126,18 @@ KitManagerPrivate::~KitManagerPrivate()
// KitManager:
// --------------------------------------------------------------------------
-KitManager *KitManager::instance()
+static Internal::KitManagerPrivate *d;
+static KitManager *m_instance;
+
+QObject *KitManager::instance()
{
return m_instance;
}
KitManager::KitManager(QObject *parent) :
- QObject(parent),
- d(new Internal::KitManagerPrivate())
+ QObject(parent)
{
+ d = new Internal::KitManagerPrivate;
QTC_CHECK(!m_instance);
m_instance = this;
@@ -217,9 +217,9 @@ void KitManager::restoreKits()
// Overwrite settings that the SDK sets to those values:
foreach (const KitInformation *ki, kitInformation()) {
// Copy sticky settings over:
- if (current->isSticky(ki->dataId())) {
- toStore->setValue(ki->dataId(), current->value(ki->dataId()));
- toStore->makeSticky(ki->dataId());
+ if (current->isSticky(ki->id())) {
+ toStore->setValue(ki->id(), current->value(ki->id()));
+ toStore->setSticky(ki->id(), true);
}
}
@@ -244,7 +244,7 @@ void KitManager::restoreKits()
defaultKit->setDisplayName(tr("Desktop"));
defaultKit->setSdkProvided(false);
defaultKit->setAutoDetected(false);
- defaultKit->setIconPath(QLatin1String(":///DESKTOP///"));
+ defaultKit->setIconPath(Utils::FileName::fromString(QLatin1String(":///DESKTOP///")));
defaultKit->setup();
@@ -292,6 +292,11 @@ void KitManager::saveKits()
d->m_writer->save(data, Core::ICore::mainWindow());
}
+static bool isLoaded()
+{
+ return d->m_initialized;
+}
+
bool greaterPriority(KitInformation *a, KitInformation *b)
{
return a->priority() > b->priority();
@@ -300,17 +305,19 @@ bool greaterPriority(KitInformation *a, KitInformation *b)
void KitManager::registerKitInformation(KitInformation *ki)
{
QTC_CHECK(!isLoaded());
+ QTC_ASSERT(!d->m_informationList.contains(ki), return);
QList<KitInformation *>::iterator it
- = qLowerBound(d->m_informationList.begin(), d->m_informationList.end(), ki, greaterPriority);
+ = qLowerBound(d->m_informationList.begin(),
+ d->m_informationList.end(), ki, greaterPriority);
d->m_informationList.insert(it, ki);
- if (!d->m_initialized)
+ if (!isLoaded())
return;
foreach (Kit *k, kits()) {
- if (!k->hasValue(ki->dataId()))
- k->setValue(ki->dataId(), ki->defaultValue(k));
+ if (!k->hasValue(ki->id()))
+ k->setValue(ki->id(), ki->defaultValue(k));
else
ki->fix(k);
}
@@ -321,7 +328,7 @@ void KitManager::registerKitInformation(KitInformation *ki)
void KitManager::deregisterKitInformation(KitInformation *ki)
{
QTC_CHECK(d->m_informationList.contains(ki));
- d->m_informationList.removeAll(ki);
+ d->m_informationList.removeOne(ki);
delete ki;
}
@@ -373,17 +380,21 @@ KitManager::KitList KitManager::restoreKits(const Utils::FileName &fileName)
return result;
}
-QList<Kit *> KitManager::kits(const KitMatcher *m) const
+QList<Kit *> KitManager::kits()
+{
+ return d->m_kitList;
+}
+
+QList<Kit *> KitManager::matchingKits(const KitMatcher &matcher)
{
QList<Kit *> result;
- foreach (Kit *k, d->m_kitList) {
- if (!m || m->matches(k))
+ foreach (Kit *k, d->m_kitList)
+ if (matcher.matches(k))
result.append(k);
- }
return result;
}
-Kit *KitManager::find(const Core::Id &id) const
+Kit *KitManager::find(const Core::Id &id)
{
if (!id.isValid())
return 0;
@@ -395,26 +406,28 @@ Kit *KitManager::find(const Core::Id &id) const
return 0;
}
-Kit *KitManager::find(const KitMatcher *m) const
+Kit *KitManager::find(const KitMatcher &matcher)
{
- QList<Kit *> matched = kits(m);
- return matched.isEmpty() ? 0 : matched.first();
+ foreach (Kit *k, d->m_kitList)
+ if (matcher.matches(k))
+ return k;
+ return 0;
}
-Kit *KitManager::defaultKit() const
+Kit *KitManager::defaultKit()
{
return d->m_defaultKit;
}
-QList<KitInformation *> KitManager::kitInformation() const
+QList<KitInformation *> KitManager::kitInformation()
{
return d->m_informationList;
}
-Internal::KitManagerConfigWidget *KitManager::createConfigWidget(Kit *k) const
+Internal::KitManagerConfigWidget *KitManager::createConfigWidget(Kit *k)
{
Internal::KitManagerConfigWidget *result = new Internal::KitManagerConfigWidget(k);
- foreach (KitInformation *ki, d->m_informationList)
+ foreach (KitInformation *ki, kitInformation())
result->addConfigWidget(ki->createConfigWidget(result->workingCopy()));
result->updateVisibility();
@@ -424,15 +437,10 @@ Internal::KitManagerConfigWidget *KitManager::createConfigWidget(Kit *k) const
void KitManager::deleteKit(Kit *k)
{
- QTC_ASSERT(!KitManager::instance()->kits().contains(k), return);
+ QTC_ASSERT(!KitManager::kits().contains(k), return);
delete k;
}
-bool KitManager::isLoaded() const
-{
- return d->m_initialized;
-}
-
QString KitManager::uniqueKitName(const Kit *k, const QString name, const QList<Kit *> &allKits)
{
QStringList nameList;
@@ -473,13 +481,13 @@ void KitManager::notifyAboutDisplayNameChange(Kit *k)
void KitManager::notifyAboutUpdate(ProjectExplorer::Kit *k)
{
- if (!k || !d->m_initialized)
+ if (!k || !isLoaded())
return;
if (d->m_kitList.contains(k))
- emit kitUpdated(k);
+ emit m_instance->kitUpdated(k);
else
- emit unmanagedKitUpdated(k);
+ emit m_instance->unmanagedKitUpdated(k);
}
bool KitManager::registerKit(ProjectExplorer::Kit *k)
@@ -495,9 +503,8 @@ bool KitManager::registerKit(ProjectExplorer::Kit *k)
k->setDisplayName(uniqueKitName(k, k->displayName(), kits()));
// make sure we have all the information in our kits:
- addKit(k);
- if (d->m_initialized)
- emit kitAdded(k);
+ m_instance->addKit(k);
+ emit m_instance->kitAdded(k);
return true;
}
@@ -506,7 +513,7 @@ void KitManager::deregisterKit(Kit *k)
if (!k || !kits().contains(k))
return;
d->m_kitList.removeOne(k);
- if (d->m_defaultKit == k) {
+ if (defaultKit() == k) {
QList<Kit *> stList = kits();
Kit *newDefault = 0;
foreach (Kit *cur, stList) {
@@ -517,20 +524,18 @@ void KitManager::deregisterKit(Kit *k)
}
setDefaultKit(newDefault);
}
- if (d->m_initialized)
- emit kitRemoved(k);
+ emit m_instance->kitRemoved(k);
delete k;
}
void KitManager::setDefaultKit(Kit *k)
{
- if (d->m_defaultKit == k)
+ if (defaultKit() == k)
return;
if (k && !kits().contains(k))
return;
d->m_defaultKit = k;
- if (d->m_initialized)
- emit defaultkitChanged();
+ emit m_instance->defaultkitChanged();
}
void KitManager::addKit(Kit *k)
@@ -541,8 +546,8 @@ void KitManager::addKit(Kit *k)
{
KitGuard g(k);
foreach (KitInformation *ki, d->m_informationList) {
- if (!k->hasValue(ki->dataId()))
- k->setValue(ki->dataId(), ki->defaultValue(k));
+ if (!k->hasValue(ki->id()))
+ k->setValue(ki->id(), ki->defaultValue(k));
else
ki->fix(k);
}
@@ -574,14 +579,9 @@ QString KitInformation::displayNamePostfix(const Kit *k) const
return QString();
}
-bool KitInformation::isSticky(const Kit *k) const
-{
- return k->isSticky(dataId());
-}
-
void KitInformation::notifyAboutUpdate(Kit *k)
{
- KitManager::instance()->notifyAboutUpdate(k);
+ KitManager::notifyAboutUpdate(k);
}
} // namespace ProjectExplorer
diff --git a/src/plugins/projectexplorer/kitmanager.h b/src/plugins/projectexplorer/kitmanager.h
index 27dfe46f41..5c201aa14f 100644
--- a/src/plugins/projectexplorer/kitmanager.h
+++ b/src/plugins/projectexplorer/kitmanager.h
@@ -51,7 +51,6 @@ class KitManager;
namespace Internal {
class KitManagerConfigWidget;
-class KitManagerPrivate;
class KitModel;
} // namespace Internal
@@ -70,9 +69,8 @@ public:
typedef QPair<QString, QString> Item;
typedef QList<Item> ItemList;
- virtual Core::Id dataId() const = 0;
-
- virtual unsigned int priority() const = 0; // the higher the closer to the top.
+ Core::Id id() const { return m_id; }
+ int priority() const { return m_priority; }
virtual QVariant defaultValue(Kit *) const = 0;
@@ -92,10 +90,14 @@ public:
virtual QString displayNamePostfix(const Kit *k) const;
- bool isSticky(const Kit *k) const;
-
protected:
+ void setId(Core::Id id) { m_id = id; }
+ void setPriority(int priority) { m_priority = priority; }
void notifyAboutUpdate(Kit *k);
+
+private:
+ Core::Id m_id;
+ int m_priority; // The higher the closer to the top.
};
class PROJECTEXPLORER_EXPORT KitMatcher
@@ -110,33 +112,32 @@ class PROJECTEXPLORER_EXPORT KitManager : public QObject
Q_OBJECT
public:
- static KitManager *instance();
+ static QObject *instance();
~KitManager();
- QList<Kit *> kits(const KitMatcher *m = 0) const;
- Kit *find(const Core::Id &id) const;
- Kit *find(const KitMatcher *m) const;
- Kit *defaultKit() const;
+ static QList<Kit *> kits();
+ static QList<Kit *> matchingKits(const KitMatcher &matcher);
+ static Kit *find(const Core::Id &id);
+ static Kit *find(const KitMatcher &matcher);
+ static Kit *defaultKit();
- QList<KitInformation *> kitInformation() const;
+ static QList<KitInformation *> kitInformation();
- Internal::KitManagerConfigWidget *createConfigWidget(Kit *k) const;
+ static Internal::KitManagerConfigWidget *createConfigWidget(Kit *k);
static void deleteKit(Kit *k);
- bool isLoaded() const;
-
static QString uniqueKitName(const Kit *k, const QString name, const QList<Kit *> &allKits);
-public slots:
- bool registerKit(ProjectExplorer::Kit *k);
- void deregisterKit(ProjectExplorer::Kit *k);
- void setDefaultKit(ProjectExplorer::Kit *k);
+ static bool registerKit(ProjectExplorer::Kit *k);
+ static void deregisterKit(ProjectExplorer::Kit *k);
+ static void setDefaultKit(ProjectExplorer::Kit *k);
- void saveKits();
+ static void registerKitInformation(ProjectExplorer::KitInformation *ki);
+ static void deregisterKitInformation(ProjectExplorer::KitInformation *ki);
- void registerKitInformation(ProjectExplorer::KitInformation *ki);
- void deregisterKitInformation(ProjectExplorer::KitInformation *ki);
+public slots:
+ void saveKits();
signals:
void kitAdded(ProjectExplorer::Kit *);
@@ -155,7 +156,7 @@ signals:
private:
explicit KitManager(QObject *parent = 0);
- bool setKeepDisplayNameUnique(bool unique);
+ static bool setKeepDisplayNameUnique(bool unique);
// Make sure the this is only called after all
// KitInformation are registered!
@@ -170,15 +171,10 @@ private:
};
KitList restoreKits(const Utils::FileName &fileName);
- void notifyAboutDisplayNameChange(ProjectExplorer::Kit *k);
- void notifyAboutUpdate(ProjectExplorer::Kit *k);
+ static void notifyAboutDisplayNameChange(ProjectExplorer::Kit *k);
+ static void notifyAboutUpdate(ProjectExplorer::Kit *k);
void addKit(Kit *k);
- Internal::KitManagerPrivate *const d;
-
- static KitManager *m_instance;
-
- friend class Internal::KitManagerPrivate; // for the restoreToolChains methods
friend class ProjectExplorerPlugin; // for constructor
friend class Kit;
friend class Internal::KitModel;
diff --git a/src/plugins/projectexplorer/kitmanagerconfigwidget.cpp b/src/plugins/projectexplorer/kitmanagerconfigwidget.cpp
index 5afe809c74..dfb05b59da 100644
--- a/src/plugins/projectexplorer/kitmanagerconfigwidget.cpp
+++ b/src/plugins/projectexplorer/kitmanagerconfigwidget.cpp
@@ -35,6 +35,7 @@
#include <utils/detailswidget.h>
#include <utils/qtcassert.h>
+#include <QAction>
#include <QFileDialog>
#include <QGridLayout>
#include <QLabel>
@@ -87,7 +88,7 @@ KitManagerConfigWidget::KitManagerConfigWidget(Kit *k) :
connect(m_iconButton, SIGNAL(clicked()), this, SLOT(setIcon()));
connect(m_nameEdit, SIGNAL(textChanged(QString)), this, SLOT(setDisplayName()));
- KitManager *km = KitManager::instance();
+ QObject *km = KitManager::instance();
connect(km, SIGNAL(unmanagedKitUpdated(ProjectExplorer::Kit*)),
this, SLOT(workingCopyWasUpdated(ProjectExplorer::Kit*)));
connect(km, SIGNAL(kitUpdated(ProjectExplorer::Kit*)),
@@ -98,10 +99,12 @@ KitManagerConfigWidget::~KitManagerConfigWidget()
{
qDeleteAll(m_widgets);
m_widgets.clear();
+ qDeleteAll(m_actions);
+ m_actions.clear();
KitManager::deleteKit(m_modifiedKit);
// Make sure our workingCopy did not get registered somehow:
- foreach (const Kit *k, KitManager::instance()->kits())
+ foreach (const Kit *k, KitManager::kits())
QTC_CHECK(k->id() != Core::Id(WORKING_COPY_KIT_ID));
}
@@ -113,7 +116,6 @@ QString KitManagerConfigWidget::displayName() const
void KitManagerConfigWidget::apply()
{
bool mustSetDefault = m_isDefaultKit;
- KitManager *km = KitManager::instance();
bool mustRegister = false;
if (!m_kit) {
mustRegister = true;
@@ -121,10 +123,10 @@ void KitManagerConfigWidget::apply()
}
m_kit->copyFrom(m_modifiedKit);//m_isDefaultKit is reset in discard() here.
if (mustRegister)
- km->registerKit(m_kit);
+ KitManager::registerKit(m_kit);
if (mustSetDefault)
- km->setDefaultKit(m_kit);
+ KitManager::setDefaultKit(m_kit);
m_isDefaultKit = mustSetDefault;
emit dirty();
@@ -134,7 +136,7 @@ void KitManagerConfigWidget::discard()
{
if (m_kit) {
m_modifiedKit->copyFrom(m_kit);
- m_isDefaultKit = (m_kit == KitManager::instance()->defaultKit());
+ m_isDefaultKit = (m_kit == KitManager::defaultKit());
} else {
// This branch will only ever get reached once during setup of widget for a not-yet-existing
// kit.
@@ -149,7 +151,7 @@ bool KitManagerConfigWidget::isDirty() const
{
return !m_kit
|| !m_kit->isEqual(m_modifiedKit)
- || m_isDefaultKit != (KitManager::instance()->defaultKit() == m_kit);
+ || m_isDefaultKit != (KitManager::defaultKit() == m_kit);
}
bool KitManagerConfigWidget::isValid() const
@@ -175,6 +177,16 @@ void KitManagerConfigWidget::addConfigWidget(ProjectExplorer::KitConfigWidget *w
QString name = widget->displayName();
QString toolTip = widget->toolTip();
+ QAction *action = new QAction(tr("Mark as Mutable"), 0);
+ action->setCheckable(true);
+ action->setData(QVariant::fromValue(qobject_cast<QObject *>(widget)));
+ action->setChecked(widget->isMutable());
+ action->setEnabled(!widget->isSticky());
+ widget->mainWidget()->addAction(action);
+ widget->mainWidget()->setContextMenuPolicy(Qt::ActionsContextMenu);
+ connect(action, SIGNAL(toggled(bool)), this, SLOT(updateMutableState()));
+ m_actions << action;
+
int row = m_layout->rowCount();
m_layout->addWidget(widget->mainWidget(), row, WidgetColumn);
if (QWidget *button = widget->buttonWidget())
@@ -207,8 +219,6 @@ void KitManagerConfigWidget::makeStickySubWidgetsReadOnly()
if (w->isSticky())
w->makeReadOnly();
}
- m_iconButton->setEnabled(false);
- m_nameEdit->setEnabled(false);
}
Kit *KitManagerConfigWidget::workingCopy() const
@@ -238,16 +248,19 @@ void KitManagerConfigWidget::removeKit()
{
if (!m_kit)
return;
- KitManager::instance()->deregisterKit(m_kit);
+ KitManager::deregisterKit(m_kit);
}
void KitManagerConfigWidget::setIcon()
{
- const QString path = QFileDialog::getOpenFileName(this, tr("Select Icon"), m_modifiedKit->iconPath(), tr("Images (*.png *.xpm *.jpg)"));
+ const Utils::FileName path = Utils::FileName::fromString(
+ QFileDialog::getOpenFileName(this, tr("Select Icon"),
+ m_modifiedKit->iconPath().toString(),
+ tr("Images (*.png *.xpm *.jpg)")));
if (path.isEmpty())
return;
- const QIcon icon = QIcon(path);
+ const QIcon icon = Kit::icon(path);
if (icon.isNull())
return;
@@ -287,6 +300,18 @@ void KitManagerConfigWidget::kitWasUpdated(Kit *k)
updateVisibility();
}
+void KitManagerConfigWidget::updateMutableState()
+{
+ QAction *action = qobject_cast<QAction *>(sender());
+ if (!action)
+ return;
+ KitConfigWidget *widget = qobject_cast<KitConfigWidget *>(action->data().value<QObject *>());
+ if (!widget)
+ return;
+ widget->setMutable(action->isChecked());
+ emit dirty();
+}
+
QLabel *KitManagerConfigWidget::createLabel(const QString &name, const QString &toolTip)
{
QLabel *label = new QLabel(name);
diff --git a/src/plugins/projectexplorer/kitmanagerconfigwidget.h b/src/plugins/projectexplorer/kitmanagerconfigwidget.h
index 1fcf346dc0..13aac9977c 100644
--- a/src/plugins/projectexplorer/kitmanagerconfigwidget.h
+++ b/src/plugins/projectexplorer/kitmanagerconfigwidget.h
@@ -80,6 +80,7 @@ private slots:
void setDisplayName();
void workingCopyWasUpdated(ProjectExplorer::Kit *k);
void kitWasUpdated(ProjectExplorer::Kit *k);
+ void updateMutableState();
private:
enum LayoutColumns {
@@ -101,6 +102,7 @@ private:
bool m_isDefaultKit;
bool m_fixingKit;
QPixmap m_background;
+ QList<QAction *> m_actions;
};
} // namespace Internal
diff --git a/src/plugins/projectexplorer/kitmodel.cpp b/src/plugins/projectexplorer/kitmodel.cpp
index 087d822743..3cd58bd2b5 100644
--- a/src/plugins/projectexplorer/kitmodel.cpp
+++ b/src/plugins/projectexplorer/kitmodel.cpp
@@ -57,7 +57,7 @@ public:
if (kn)
kn->childNodes.append(this);
- widget = KitManager::instance()->createConfigWidget(k);
+ widget = KitManager::createConfigWidget(k);
if (widget) {
if (k && k->isAutoDetected())
widget->makeStickySubWidgetsReadOnly();
@@ -104,7 +104,7 @@ KitModel::KitModel(QBoxLayout *parentLayout, QObject *parent) :
m_autoRoot = new KitNode(m_root);
m_manualRoot = new KitNode(m_root);
- foreach (Kit *k, KitManager::instance()->kits())
+ foreach (Kit *k, KitManager::kits())
addKit(k);
changeDefaultKit();
@@ -285,8 +285,7 @@ void KitModel::apply()
}
// Update kits:
- KitManager *km = KitManager::instance();
- bool unique = km->setKeepDisplayNameUnique(false);
+ bool unique = KitManager::setKeepDisplayNameUnique(false);
nodes = m_autoRoot->childNodes; // These can be dirty due to being made default!
nodes.append(m_manualRoot->childNodes);
foreach (KitNode *n, nodes) {
@@ -297,7 +296,7 @@ void KitModel::apply()
emit dataChanged(index(n, 0), index(n, columnCount(QModelIndex())));
}
}
- km->setKeepDisplayNameUnique(unique);
+ KitManager::setKeepDisplayNameUnique(unique);
}
void KitModel::markForRemoval(Kit *k)
@@ -475,7 +474,7 @@ void KitModel::updateKit(Kit *k)
void KitModel::changeDefaultKit()
{
- Kit *defaultKit = KitManager::instance()->defaultKit();
+ Kit *defaultKit = KitManager::defaultKit();
QList<KitNode *> nodes = m_autoRoot->childNodes;
nodes << m_manualRoot->childNodes;
foreach (KitNode *n, nodes) {
diff --git a/src/plugins/projectexplorer/ldparser.cpp b/src/plugins/projectexplorer/ldparser.cpp
index a75188e790..ff32ad8a16 100644
--- a/src/plugins/projectexplorer/ldparser.cpp
+++ b/src/plugins/projectexplorer/ldparser.cpp
@@ -31,6 +31,8 @@
#include "projectexplorerconstants.h"
#include "task.h"
+#include <utils/qtcassert.h>
+
using namespace ProjectExplorer;
namespace {
@@ -38,7 +40,7 @@ namespace {
const char * const FILE_PATTERN = "(([A-Za-z]:)?[^:]+\\.[^:]+):";
// line no. or elf segment + offset (1 bracket)
// const char * const POSITION_PATTERN = "(\\d+|\\(\\.[^:]+[+-]0x[a-fA-F0-9]+\\):)";
- const char * const POSITION_PATTERN = "(\\d|\\(\\..+[+-]0x[a-fA-F0-9]+\\):)";
+ const char * const POSITION_PATTERN = "(\\d+|\\(\\..+[+-]0x[a-fA-F0-9]+\\)):";
const char * const COMMAND_PATTERN = "^(.*[\\\\/])?([a-z0-9]+-[a-z0-9]+-[a-z0-9]+-)?(ld|gold)(-[0-9\\.]+)?(\\.exe)?: ";
}
@@ -50,9 +52,11 @@ LdParser::LdParser()
QString::fromLatin1(FILE_PATTERN) + QLatin1String(")?(") +
QLatin1String(POSITION_PATTERN) + QLatin1String(")?\\s(.+)$"));
m_regExpLinker.setMinimal(true);
+ QTC_CHECK(m_regExpLinker.isValid());
m_regExpGccNames.setPattern(QLatin1String(COMMAND_PATTERN));
m_regExpGccNames.setMinimal(true);
+ QTC_CHECK(m_regExpGccNames.isValid());
}
void LdParser::stdError(const QString &line)
@@ -70,7 +74,7 @@ void LdParser::stdError(const QString &line)
lne /* description */,
Utils::FileName() /* filename */,
-1 /* linenumber */,
- Core::Id(Constants::TASK_CATEGORY_COMPILE)));
+ Constants::TASK_CATEGORY_COMPILE));
return;
} else if (m_regExpGccNames.indexIn(lne) > -1) {
QString description = lne.mid(m_regExpGccNames.matchedLength());
@@ -78,7 +82,7 @@ void LdParser::stdError(const QString &line)
description,
Utils::FileName(), /* filename */
-1, /* line */
- Core::Id(Constants::TASK_CATEGORY_COMPILE));
+ Constants::TASK_CATEGORY_COMPILE);
if (description.startsWith(QLatin1String("warning: "))) {
task.type = Task::Warning;
task.description = description.mid(9);
@@ -93,17 +97,22 @@ void LdParser::stdError(const QString &line)
if (!ok)
lineno = -1;
Utils::FileName filename = Utils::FileName::fromUserInput(m_regExpLinker.cap(1));
- if (!m_regExpLinker.cap(4).isEmpty()
- && !m_regExpLinker.cap(4).startsWith(QLatin1String("(.text")))
- filename = Utils::FileName::fromUserInput(m_regExpLinker.cap(4));
+ const QString sourceFileName = m_regExpLinker.cap(4);
+ if (!sourceFileName.isEmpty()
+ && !sourceFileName.startsWith(QLatin1String("(.text"))
+ && !sourceFileName.startsWith(QLatin1String("(.data"))) {
+ filename = Utils::FileName::fromUserInput(sourceFileName);
+ }
QString description = m_regExpLinker.cap(8).trimmed();
Task task(Task::Error, description, filename, lineno,
- Core::Id(Constants::TASK_CATEGORY_COMPILE));
+ Constants::TASK_CATEGORY_COMPILE);
if (description.startsWith(QLatin1String("At global scope")) ||
description.startsWith(QLatin1String("At top level")) ||
description.startsWith(QLatin1String("instantiated from ")) ||
- description.startsWith(QLatin1String("In ")))
+ description.startsWith(QLatin1String("In ")) ||
+ description.startsWith(QLatin1String("first defined here"))) {
task.type = Task::Unknown;
+ }
if (description.startsWith(QLatin1String("warning: "), Qt::CaseInsensitive)) {
task.type = Task::Warning;
task.description = description.mid(9);
diff --git a/src/plugins/projectexplorer/linuxiccparser.cpp b/src/plugins/projectexplorer/linuxiccparser.cpp
index bdd6f3ac1f..a9de97acbf 100644
--- a/src/plugins/projectexplorer/linuxiccparser.cpp
+++ b/src/plugins/projectexplorer/linuxiccparser.cpp
@@ -31,6 +31,8 @@
#include "ldparser.h"
#include "projectexplorerconstants.h"
+#include <utils/qtcassert.h>
+
using namespace ProjectExplorer;
LinuxIccParser::LinuxIccParser()
@@ -44,16 +46,19 @@ LinuxIccParser::LinuxIccParser()
" ((error|warning)( #\\d+)?: )?" // optional type (cap 4) and optional error number // TODO really optional ?
"(.*)$")); // description (cap 6)
//m_firstLine.setMinimal(true);
+ QTC_CHECK(m_firstLine.isValid());
// Note pattern also matches caret lines
m_continuationLines.setPattern(QLatin1String("^\\s+" // At least one whitespace
"(.*)$"));// description
m_continuationLines.setMinimal(true);
+ QTC_CHECK(m_continuationLines.isValid());
m_caretLine.setPattern(QLatin1String("^\\s*" // Whitespaces
"\\^" // a caret
"\\s*$")); // and again whitespaces
m_caretLine.setMinimal(true);
+ QTC_CHECK(m_caretLine.isValid());
appendOutputParser(new LdParser);
}
@@ -65,7 +70,7 @@ void LinuxIccParser::stdError(const QString &line)
m_temporary = ProjectExplorer::Task(Task::Unknown, m_firstLine.cap(6).trimmed(),
Utils::FileName::fromUserInput(m_firstLine.cap(1)),
m_firstLine.cap(2).toInt(),
- Core::Id(Constants::TASK_CATEGORY_COMPILE));
+ Constants::TASK_CATEGORY_COMPILE);
QString category = m_firstLine.cap(4);
if (category == QLatin1String("error"))
m_temporary.type = Task::Error;
@@ -147,7 +152,7 @@ void ProjectExplorerPlugin::testLinuxIccOutputParsers_data()
<< Task(Task::Error,
QLatin1String("identifier \"f\" is undefined\nf(0);"),
Utils::FileName::fromUserInput(QLatin1String("main.cpp")), 13,
- Core::Id(Constants::TASK_CATEGORY_COMPILE)))
+ Constants::TASK_CATEGORY_COMPILE))
<< QString();
QTest::newRow("private function")
@@ -161,7 +166,7 @@ void ProjectExplorerPlugin::testLinuxIccOutputParsers_data()
<< Task(Task::Error,
QLatin1String("function \"AClass::privatefunc\" (declared at line 4 of \"main.h\") is inaccessible\nb.privatefunc();"),
Utils::FileName::fromUserInput(QLatin1String("main.cpp")), 53,
- Core::Id(Constants::TASK_CATEGORY_COMPILE)))
+ Constants::TASK_CATEGORY_COMPILE))
<< QString();
QTest::newRow("simple warning")
@@ -175,7 +180,7 @@ void ProjectExplorerPlugin::testLinuxIccOutputParsers_data()
<< Task(Task::Warning,
QLatin1String("use of \"=\" where \"==\" may have been intended\nwhile (a = true)"),
Utils::FileName::fromUserInput(QLatin1String("main.cpp")), 41,
- Core::Id(Constants::TASK_CATEGORY_COMPILE)))
+ Constants::TASK_CATEGORY_COMPILE))
<< QString();
}
diff --git a/src/plugins/projectexplorer/localapplicationruncontrol.cpp b/src/plugins/projectexplorer/localapplicationruncontrol.cpp
index 2ff14ef297..ff19195f15 100644
--- a/src/plugins/projectexplorer/localapplicationruncontrol.cpp
+++ b/src/plugins/projectexplorer/localapplicationruncontrol.cpp
@@ -84,8 +84,8 @@ LocalApplicationRunControl::LocalApplicationRunControl(LocalApplicationRunConfig
this, SLOT(slotAppendMessage(QString,Utils::OutputFormat)));
connect(&m_applicationLauncher, SIGNAL(processStarted()),
this, SLOT(processStarted()));
- connect(&m_applicationLauncher, SIGNAL(processExited(int)),
- this, SLOT(processExited(int)));
+ connect(&m_applicationLauncher, SIGNAL(processExited(int,QProcess::ExitStatus)),
+ this, SLOT(processExited(int,QProcess::ExitStatus)));
connect(&m_applicationLauncher, SIGNAL(bringToForegroundRequested(qint64)),
this, SLOT(bringApplicationToForeground(qint64)));
}
@@ -141,12 +141,18 @@ void LocalApplicationRunControl::processStarted()
setApplicationProcessHandle(ProcessHandle(m_applicationLauncher.applicationPID()));
}
-void LocalApplicationRunControl::processExited(int exitCode)
+void LocalApplicationRunControl::processExited(int exitCode, QProcess::ExitStatus status)
{
m_running = false;
setApplicationProcessHandle(ProcessHandle());
- QString msg = tr("%1 exited with code %2\n")
- .arg(QDir::toNativeSeparators(m_executable)).arg(exitCode);
+ QString msg;
+ if (status == QProcess::CrashExit) {
+ msg = tr("%1 crashed\n")
+ .arg(QDir::toNativeSeparators(m_executable));
+ } else {
+ msg = tr("%1 exited with code %2\n")
+ .arg(QDir::toNativeSeparators(m_executable)).arg(exitCode);
+ }
appendMessage(msg, Utils::NormalMessageFormat);
emit finished();
}
diff --git a/src/plugins/projectexplorer/localapplicationruncontrol.h b/src/plugins/projectexplorer/localapplicationruncontrol.h
index 0904f3d529..983de25766 100644
--- a/src/plugins/projectexplorer/localapplicationruncontrol.h
+++ b/src/plugins/projectexplorer/localapplicationruncontrol.h
@@ -60,7 +60,7 @@ public:
virtual QIcon icon() const;
private slots:
void processStarted();
- void processExited(int exitCode);
+ void processExited(int exitCode, QProcess::ExitStatus status);
void slotAppendMessage(const QString &err, Utils::OutputFormat isError);
private:
ProjectExplorer::ApplicationLauncher m_applicationLauncher;
diff --git a/src/plugins/projectexplorer/localenvironmentaspect.cpp b/src/plugins/projectexplorer/localenvironmentaspect.cpp
index 1ec0d7f489..faef642a17 100644
--- a/src/plugins/projectexplorer/localenvironmentaspect.cpp
+++ b/src/plugins/projectexplorer/localenvironmentaspect.cpp
@@ -88,22 +88,16 @@ void LocalEnvironmentAspect::buildEnvironmentHasChanged()
emit environmentChanged();
}
-LocalEnvironmentAspect::LocalEnvironmentAspect(RunConfiguration *rc) :
- EnvironmentAspect(rc)
+LocalEnvironmentAspect::LocalEnvironmentAspect(RunConfiguration *parent) :
+ EnvironmentAspect(parent)
{
- connect(rc->target(), SIGNAL(environmentChanged()),
+ connect(parent->target(), SIGNAL(environmentChanged()),
this, SLOT(buildEnvironmentHasChanged()));
}
-LocalEnvironmentAspect::LocalEnvironmentAspect(const LocalEnvironmentAspect *other,
- ProjectExplorer::RunConfiguration *parent) :
- EnvironmentAspect(other, parent)
-{ }
-
-LocalEnvironmentAspect *LocalEnvironmentAspect::clone(RunConfiguration *parent) const
+LocalEnvironmentAspect *LocalEnvironmentAspect::create(RunConfiguration *parent) const
{
- Q_UNUSED(parent);
- return new LocalEnvironmentAspect(this, parent);
+ return new LocalEnvironmentAspect(parent);
}
} // namespace ProjectExplorer
diff --git a/src/plugins/projectexplorer/localenvironmentaspect.h b/src/plugins/projectexplorer/localenvironmentaspect.h
index 5379b1db03..3aa3623ec4 100644
--- a/src/plugins/projectexplorer/localenvironmentaspect.h
+++ b/src/plugins/projectexplorer/localenvironmentaspect.h
@@ -39,9 +39,8 @@ class PROJECTEXPLORER_EXPORT LocalEnvironmentAspect : public EnvironmentAspect
Q_OBJECT
public:
- LocalEnvironmentAspect(RunConfiguration *rc);
-
- LocalEnvironmentAspect *clone(RunConfiguration *parent) const;
+ LocalEnvironmentAspect(RunConfiguration *parent);
+ LocalEnvironmentAspect *create(RunConfiguration *parent) const;
QList<int> possibleBaseEnvironments() const;
QString baseEnvironmentDisplayName(int base) const;
@@ -56,8 +55,6 @@ private:
SystemEnvironmentBase,
BuildEnvironmentBase
};
-
- LocalEnvironmentAspect(const LocalEnvironmentAspect *other, RunConfiguration *parent);
};
} // namespace ProjectExplorer
diff --git a/src/plugins/projectexplorer/miniprojecttargetselector.cpp b/src/plugins/projectexplorer/miniprojecttargetselector.cpp
index af399f4862..25270eb353 100644
--- a/src/plugins/projectexplorer/miniprojecttargetselector.cpp
+++ b/src/plugins/projectexplorer/miniprojecttargetselector.cpp
@@ -28,12 +28,14 @@
****************************************************************************/
#include "miniprojecttargetselector.h"
+#include "kit.h"
+#include "kitconfigwidget.h"
+#include "kitmanager.h"
#include "target.h"
#include <utils/styledbar.h>
#include <utils/stylehelper.h>
-#include <coreplugin/idocument.h>
#include <coreplugin/icore.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/modemanager.h>
@@ -210,16 +212,17 @@ int ListWidget::padding()
////////
// ProjectListWidget
////////
-ProjectListWidget::ProjectListWidget(SessionManager *sessionManager, QWidget *parent)
- : ListWidget(parent), m_sessionManager(sessionManager), m_ignoreIndexChange(false)
+ProjectListWidget::ProjectListWidget(QWidget *parent)
+ : ListWidget(parent), m_ignoreIndexChange(false)
{
- connect(m_sessionManager, SIGNAL(projectAdded(ProjectExplorer::Project*)),
+ QObject *sessionManager = SessionManager::instance();
+ connect(sessionManager, SIGNAL(projectAdded(ProjectExplorer::Project*)),
this, SLOT(addProject(ProjectExplorer::Project*)));
- connect(m_sessionManager, SIGNAL(aboutToRemoveProject(ProjectExplorer::Project*)),
+ connect(sessionManager, SIGNAL(aboutToRemoveProject(ProjectExplorer::Project*)),
this, SLOT(removeProject(ProjectExplorer::Project*)));
- connect(m_sessionManager, SIGNAL(startupProjectChanged(ProjectExplorer::Project*)),
+ connect(sessionManager, SIGNAL(startupProjectChanged(ProjectExplorer::Project*)),
this, SLOT(changeStartupProject(ProjectExplorer::Project*)));
- connect(m_sessionManager, SIGNAL(projectDisplayNameChanged(ProjectExplorer::Project*)),
+ connect(sessionManager, SIGNAL(projectDisplayNameChanged(ProjectExplorer::Project*)),
this, SLOT(projectDisplayNameChanged(ProjectExplorer::Project*)));
connect(this, SIGNAL(currentRowChanged(int)),
this, SLOT(setProject(int)));
@@ -237,7 +240,7 @@ QListWidgetItem *ProjectListWidget::itemForProject(Project *project)
QString ProjectListWidget::fullName(ProjectExplorer::Project *project)
{
- return tr("%1 (%2)").arg(project->displayName(), project->document()->fileName());
+ return tr("%1 (%2)").arg(project->displayName(), project->projectFilePath());
}
void ProjectListWidget::addProject(Project *project)
@@ -268,7 +271,7 @@ void ProjectListWidget::addProject(Project *project)
item->setText(displayName);
insertItem(pos, item);
- if (project == ProjectExplorerPlugin::instance()->startupProject())
+ if (project == SessionManager::startupProject())
setCurrentItem(item);
QFontMetrics fn(font());
@@ -364,7 +367,7 @@ void ProjectListWidget::setProject(int index)
if (index < 0)
return;
Project *p = item(index)->data(Qt::UserRole).value<Project *>();
- m_sessionManager->setStartupProject(p);
+ SessionManager::setStartupProject(p);
}
void ProjectListWidget::changeStartupProject(Project *project)
@@ -520,6 +523,81 @@ QListWidgetItem *GenericListWidget::itemForProjectConfiguration(ProjectConfigura
return 0;
}
+/////////
+// KitAreaWidget
+/////////
+
+KitAreaWidget::KitAreaWidget(QWidget *parent) : QWidget(parent),
+ m_layout(new QGridLayout(this)), m_kit(0)
+{
+ m_layout->setMargin(3);
+ setKit(0);
+}
+
+void KitAreaWidget::setKit(Kit *k)
+{
+ foreach (KitConfigWidget *w, m_widgets)
+ w->deleteLater();
+ m_widgets.clear();
+ foreach (QLabel *l, m_labels)
+ l->deleteLater();
+ m_labels.clear();
+
+ if (m_kit) {
+ disconnect(KitManager::instance(), SIGNAL(kitUpdated(ProjectExplorer::Kit*)),
+ this, SLOT(updateKit(ProjectExplorer::Kit*)));
+ }
+
+ int row = 0;
+ foreach (KitInformation *ki, KitManager::kitInformation()) {
+ if (k && k->isMutable(ki->id())) {
+ KitConfigWidget *widget = ki->createConfigWidget(k);
+ m_widgets << widget;
+ QLabel *label = new QLabel(widget->displayName());
+ m_labels << label;
+
+ m_layout->addWidget(label, row, 0);
+ m_layout->addWidget(widget->mainWidget(), row, 1);
+ ++row;
+ }
+ }
+ m_kit = k;
+
+ if (m_kit) {
+ connect(KitManager::instance(), SIGNAL(kitUpdated(ProjectExplorer::Kit*)),
+ this, SLOT(updateKit(ProjectExplorer::Kit*)));
+ }
+
+ setHidden(m_widgets.isEmpty());
+}
+
+void KitAreaWidget::updateKit(Kit *k)
+{
+ if (!m_kit || m_kit != k)
+ return;
+
+ // Check whether our widgets changed
+ bool mustRegenerate = false;
+ QList<Core::Id> knownIdList;
+ foreach (KitConfigWidget *w, m_widgets)
+ knownIdList << w->kitInformationId();
+
+ foreach (KitInformation *ki, KitManager::kitInformation()) {
+ Core::Id currentId = ki->id();
+ if (m_kit->isMutable(currentId) && !knownIdList.removeOne(currentId)) {
+ mustRegenerate = true;
+ break;
+ }
+ }
+
+ if (mustRegenerate || !knownIdList.isEmpty())
+ setKit(m_kit);
+}
+
+/////////
+// MiniProjectTargetSelector
+/////////
+
QWidget *MiniProjectTargetSelector::createTitleLabel(const QString &text)
{
Utils::StyledBar *bar = new Utils::StyledBar(this);
@@ -540,8 +618,8 @@ QWidget *MiniProjectTargetSelector::createTitleLabel(const QString &text)
return bar;
}
-MiniProjectTargetSelector::MiniProjectTargetSelector(QAction *targetSelectorAction, SessionManager *sessionManager, QWidget *parent) :
- QWidget(parent), m_projectAction(targetSelectorAction), m_sessionManager(sessionManager),
+MiniProjectTargetSelector::MiniProjectTargetSelector(QAction *targetSelectorAction, QWidget *parent) :
+ QWidget(parent), m_projectAction(targetSelectorAction),
m_project(0),
m_target(0),
m_buildConfiguration(0),
@@ -559,6 +637,8 @@ MiniProjectTargetSelector::MiniProjectTargetSelector(QAction *targetSelectorActi
targetSelectorAction->setIcon(style()->standardIcon(QStyle::SP_ComputerIcon));
targetSelectorAction->setProperty("titledAction", true);
+ m_kitAreaWidget = new KitAreaWidget(this);
+
m_summaryLabel = new QLabel(this);
m_summaryLabel->setMargin(3);
m_summaryLabel->setAlignment(Qt::AlignLeft | Qt::AlignTop);
@@ -571,7 +651,7 @@ MiniProjectTargetSelector::MiniProjectTargetSelector(QAction *targetSelectorActi
m_listWidgets[PROJECT] = 0; //project is not a generic list widget
m_titleWidgets[PROJECT] = createTitleLabel(tr("Project"));
- m_projectListWidget = new ProjectListWidget(m_sessionManager, this);
+ m_projectListWidget = new ProjectListWidget(this);
QStringList titles;
titles << tr("Kit") << tr("Build")
@@ -582,21 +662,23 @@ MiniProjectTargetSelector::MiniProjectTargetSelector(QAction *targetSelectorActi
m_listWidgets[i] = new GenericListWidget(this);
}
- changeStartupProject(m_sessionManager->startupProject());
- if (m_sessionManager->startupProject())
- activeTargetChanged(m_sessionManager->startupProject()->activeTarget());
+ Project *startup = SessionManager::startupProject();
+ changeStartupProject(startup);
+ if (startup)
+ activeTargetChanged(startup->activeTarget());
connect(m_summaryLabel, SIGNAL(linkActivated(QString)),
this, SLOT(switchToProjectsMode()));
- connect(m_sessionManager, SIGNAL(startupProjectChanged(ProjectExplorer::Project*)),
+ QObject *sessionManager = SessionManager::instance();
+ connect(sessionManager, SIGNAL(startupProjectChanged(ProjectExplorer::Project*)),
this, SLOT(changeStartupProject(ProjectExplorer::Project*)));
- connect(m_sessionManager, SIGNAL(projectAdded(ProjectExplorer::Project*)),
+ connect(sessionManager, SIGNAL(projectAdded(ProjectExplorer::Project*)),
this, SLOT(projectAdded(ProjectExplorer::Project*)));
- connect(m_sessionManager, SIGNAL(projectRemoved(ProjectExplorer::Project*)),
+ connect(sessionManager, SIGNAL(projectRemoved(ProjectExplorer::Project*)),
this, SLOT(projectRemoved(ProjectExplorer::Project*)));
- connect(m_sessionManager, SIGNAL(projectDisplayNameChanged(ProjectExplorer::Project*)),
+ connect(sessionManager, SIGNAL(projectDisplayNameChanged(ProjectExplorer::Project*)),
this, SLOT(updateActionAndSummary()));
// for icon changes:
@@ -745,8 +827,15 @@ void MiniProjectTargetSelector::doLayout(bool keepSize)
static QWidget *actionBar = Core::ICore::mainWindow()->findChild<QWidget*>(QLatin1String("actionbar"));
Q_ASSERT(actionBar);
+ m_kitAreaWidget->move(0, 0);
+
+ int oldSummaryLabelY = m_summaryLabel->y();
+
+ int kitAreaHeight = m_kitAreaWidget->isVisible() ? m_kitAreaWidget->sizeHint().height() : 0;
+
// 1. Calculate the summary label height
- int summaryLabelY = 1;
+ int summaryLabelY = 1 + kitAreaHeight;
+
int summaryLabelHeight = 0;
int oldSummaryLabelHeight = m_summaryLabel->height();
bool onlySummary = false;
@@ -761,7 +850,7 @@ void MiniProjectTargetSelector::doLayout(bool keepSize)
onlySummary = true;
} else {
if (visibleLineCount < 3) {
- foreach (Project *p, m_sessionManager->projects()) {
+ foreach (Project *p, SessionManager::projects()) {
if (p->needsConfiguration()) {
visibleLineCount = 3;
break;
@@ -783,7 +872,7 @@ void MiniProjectTargetSelector::doLayout(bool keepSize)
if (actionBar->isVisible())
alignedWithActionHeight = actionBar->height() - statusBar->height();
int bottomMargin = 9;
- int totalHeight = 0;
+ int heightWithoutKitArea = 0;
if (!onlySummary) {
// list widget heigth
@@ -793,22 +882,24 @@ void MiniProjectTargetSelector::doLayout(bool keepSize)
int titleWidgetsHeight = m_titleWidgets.first()->height();
if (keepSize) {
- totalHeight = height();
+ heightWithoutKitArea = height() - oldSummaryLabelY + 1;
} else {
// Clamp the size of the listwidgets to be
// at least as high as the the sidebar button
// and at most twice as high
- totalHeight = summaryLabelHeight + qBound(alignedWithActionHeight,
- maxItemCount * 30 + bottomMargin + titleWidgetsHeight,
- alignedWithActionHeight * 2);
+ heightWithoutKitArea = summaryLabelHeight
+ + qBound(alignedWithActionHeight,
+ maxItemCount * 30 + bottomMargin + titleWidgetsHeight,
+ alignedWithActionHeight * 2);
}
int titleY = summaryLabelY + summaryLabelHeight;
int listY = titleY + titleWidgetsHeight;
- int listHeight = totalHeight - bottomMargin - listY + 1;
+ int listHeight = heightWithoutKitArea + kitAreaHeight - bottomMargin - listY + 1;
// list widget widths
int minWidth = qMax(m_summaryLabel->sizeHint().width(), 250);
+ minWidth = qMax(minWidth, m_kitAreaWidget->sizeHint().width());
if (keepSize) {
// Do not make the widget smaller then it was before
int oldTotalListWidgetWidth = m_projectListWidget->isVisibleTo(this) ?
@@ -835,19 +926,21 @@ void MiniProjectTargetSelector::doLayout(bool keepSize)
}
m_summaryLabel->resize(x - 1, summaryLabelHeight);
- setFixedSize(x, totalHeight);
+ m_kitAreaWidget->resize(x - 1, kitAreaHeight);
+ setFixedSize(x, heightWithoutKitArea + kitAreaHeight);
} else {
if (keepSize)
- totalHeight = height();
+ heightWithoutKitArea = height() - oldSummaryLabelY + 1;
else
- totalHeight = qMax(summaryLabelHeight + bottomMargin, alignedWithActionHeight);
- m_summaryLabel->resize(m_summaryLabel->sizeHint().width(), totalHeight - bottomMargin);
- setFixedSize(m_summaryLabel->width() + 1, totalHeight); //1 extra pixel for the border
+ heightWithoutKitArea = qMax(summaryLabelHeight + bottomMargin, alignedWithActionHeight);
+ m_summaryLabel->resize(m_summaryLabel->sizeHint().width(), heightWithoutKitArea - bottomMargin);
+ m_kitAreaWidget->resize(m_kitAreaWidget->sizeHint());
+ setFixedSize(m_summaryLabel->width() + 1, heightWithoutKitArea + kitAreaHeight); //1 extra pixel for the border
}
if (isVisibleTo(parentWidget())) {
QPoint moveTo = statusBar->mapToGlobal(QPoint(0,0));
- moveTo -= QPoint(0, totalHeight);
+ moveTo -= QPoint(0, height());
move(moveTo);
}
}
@@ -1064,10 +1157,11 @@ void MiniProjectTargetSelector::slotRemovedRunConfiguration(ProjectExplorer::Run
void MiniProjectTargetSelector::updateProjectListVisible()
{
- bool visible = m_sessionManager->projects().size() > 1;
+ int count = SessionManager::projects().size();
+ bool visible = count > 1;
m_projectListWidget->setVisible(visible);
- m_projectListWidget->setMaxCount(m_sessionManager->projects().size());
+ m_projectListWidget->setMaxCount(count);
m_titleWidgets[PROJECT]->setVisible(visible);
updateSummary();
@@ -1076,7 +1170,7 @@ void MiniProjectTargetSelector::updateProjectListVisible()
void MiniProjectTargetSelector::updateTargetListVisible()
{
int maxCount = 0;
- foreach (Project *p, m_sessionManager->projects())
+ foreach (Project *p, SessionManager::projects())
maxCount = qMax(p->targets().size(), maxCount);
bool visible = maxCount > 1;
@@ -1089,7 +1183,7 @@ void MiniProjectTargetSelector::updateTargetListVisible()
void MiniProjectTargetSelector::updateBuildListVisible()
{
int maxCount = 0;
- foreach (Project *p, m_sessionManager->projects())
+ foreach (Project *p, SessionManager::projects())
foreach (Target *t, p->targets())
maxCount = qMax(t->buildConfigurations().size(), maxCount);
@@ -1103,7 +1197,7 @@ void MiniProjectTargetSelector::updateBuildListVisible()
void MiniProjectTargetSelector::updateDeployListVisible()
{
int maxCount = 0;
- foreach (Project *p, m_sessionManager->projects())
+ foreach (Project *p, SessionManager::projects())
foreach (Target *t, p->targets())
maxCount = qMax(t->deployConfigurations().size(), maxCount);
@@ -1117,7 +1211,7 @@ void MiniProjectTargetSelector::updateDeployListVisible()
void MiniProjectTargetSelector::updateRunListVisible()
{
int maxCount = 0;
- foreach (Project *p, m_sessionManager->projects())
+ foreach (Project *p, SessionManager::projects())
foreach (Target *t, p->targets())
maxCount = qMax(t->runConfigurations().size(), maxCount);
@@ -1174,6 +1268,8 @@ void MiniProjectTargetSelector::activeTargetChanged(ProjectExplorer::Target *tar
m_target = target;
+ m_kitAreaWidget->setKit(m_target ? m_target->kit() : 0);
+
m_listWidgets[TARGET]->setActiveProjectConfiguration(m_target);
if (m_buildConfiguration)
@@ -1390,12 +1486,12 @@ void MiniProjectTargetSelector::updateActionAndSummary()
QString runConfig;
QIcon targetIcon = style()->standardIcon(QStyle::SP_ComputerIcon);
- Project *project = ProjectExplorerPlugin::instance()->startupProject();
+ Project *project = SessionManager::startupProject();
if (project) {
projectName = project->displayName();
- foreach (Project *p, ProjectExplorerPlugin::instance()->session()->projects()) {
+ foreach (Project *p, SessionManager::projects()) {
if (p != project && p->displayName() == projectName) {
- fileName = project->document()->fileName();
+ fileName = project->projectFilePath();
break;
}
}
@@ -1445,10 +1541,10 @@ void MiniProjectTargetSelector::updateActionAndSummary()
void MiniProjectTargetSelector::updateSummary()
{
QString summary;
- if (Project *startupProject = m_sessionManager->startupProject()) {
+ if (Project *startupProject = SessionManager::startupProject()) {
if (!m_projectListWidget->isVisibleTo(this))
summary.append(tr("Project: <b>%1</b><br/>").arg(startupProject->displayName()));
- if (Target *activeTarget = m_sessionManager->startupProject()->activeTarget()) {
+ if (Target *activeTarget = startupProject->activeTarget()) {
if (!m_listWidgets[TARGET]->isVisibleTo(this))
summary.append(tr("Kit: <b>%1</b><br/>").arg( activeTarget->displayName()));
if (!m_listWidgets[BUILD]->isVisibleTo(this) && activeTarget->activeBuildConfiguration())
@@ -1496,6 +1592,6 @@ void MiniProjectTargetSelector::paintEvent(QPaintEvent *)
void MiniProjectTargetSelector::switchToProjectsMode()
{
- Core::ICore::instance()->modeManager()->activateMode(Constants::MODE_SESSION);
+ Core::ModeManager::activateMode(Constants::MODE_SESSION);
hide();
}
diff --git a/src/plugins/projectexplorer/miniprojecttargetselector.h b/src/plugins/projectexplorer/miniprojecttargetselector.h
index f7b3aa90ca..062e4ca7fe 100644
--- a/src/plugins/projectexplorer/miniprojecttargetselector.h
+++ b/src/plugins/projectexplorer/miniprojecttargetselector.h
@@ -35,19 +35,20 @@
QT_BEGIN_NAMESPACE
class QComboBox;
+class QGridLayout;
class QLabel;
class QStackedWidget;
QT_END_NAMESPACE
namespace ProjectExplorer {
class Kit;
+class KitConfigWidget;
class Project;
class Target;
class BuildConfiguration;
class DeployConfiguration;
class ProjectConfiguration;
class RunConfiguration;
-class SessionManager;
namespace Internal {
@@ -75,7 +76,7 @@ class ProjectListWidget : public ListWidget
{
Q_OBJECT
public:
- explicit ProjectListWidget(SessionManager *sessionManager, QWidget *parent = 0);
+ explicit ProjectListWidget(QWidget *parent = 0);
private slots:
void addProject(ProjectExplorer::Project *project);
void removeProject(ProjectExplorer::Project *project);
@@ -85,10 +86,28 @@ private slots:
private:
QListWidgetItem *itemForProject(Project *project);
QString fullName(ProjectExplorer::Project *project);
- SessionManager *m_sessionManager;
bool m_ignoreIndexChange;
};
+class KitAreaWidget : public QWidget
+{
+ Q_OBJECT
+public:
+ explicit KitAreaWidget(QWidget *parent = 0);
+
+public slots:
+ void setKit(ProjectExplorer::Kit *k);
+
+private slots:
+ void updateKit(ProjectExplorer::Kit *k);
+
+private:
+ QGridLayout *m_layout;
+ Kit *m_kit;
+ QList<KitConfigWidget *> m_widgets;
+ QList<QLabel *> m_labels;
+};
+
class GenericListWidget : public ListWidget
{
Q_OBJECT
@@ -114,7 +133,7 @@ class MiniProjectTargetSelector : public QWidget
{
Q_OBJECT
public:
- explicit MiniProjectTargetSelector(QAction *projectAction, SessionManager *sessionManager, QWidget *parent = 0);
+ explicit MiniProjectTargetSelector(QAction *projectAction, QWidget *parent = 0);
void setVisible(bool visible);
void keyPressEvent(QKeyEvent *ke);
@@ -175,10 +194,10 @@ private:
QWidget *createTitleLabel(const QString &text);
QAction *m_projectAction;
- SessionManager *m_sessionManager;
enum TYPES { PROJECT = 0, TARGET = 1, BUILD = 2, DEPLOY = 3, RUN = 4, LAST = 5 };
ProjectListWidget *m_projectListWidget;
+ KitAreaWidget *m_kitAreaWidget;
QVector<GenericListWidget *> m_listWidgets;
QVector<QWidget *> m_titleWidgets;
QLabel *m_summaryLabel;
diff --git a/src/plugins/projectexplorer/msvcparser.cpp b/src/plugins/projectexplorer/msvcparser.cpp
index b3fa47cfd3..0bc41b7b84 100644
--- a/src/plugins/projectexplorer/msvcparser.cpp
+++ b/src/plugins/projectexplorer/msvcparser.cpp
@@ -30,6 +30,7 @@
#include "msvcparser.h"
#include "projectexplorerconstants.h"
+#include <utils/qtcassert.h>
#ifdef Q_OS_WIN
#include <utils/winutils.h>
#endif
@@ -74,8 +75,10 @@ MsvcParser::MsvcParser()
+ QLatin1String("(Command line |fatal )?(warning|error) (")
+ QLatin1String(ERROR_PATTERN) + QLatin1String(".*)$"));
m_compileRegExp.setMinimal(true);
+ QTC_CHECK(m_compileRegExp.isValid());
m_additionalInfoRegExp.setPattern(QString::fromLatin1("^ (.*)\\((\\d+)\\) : (.*)$"));
m_additionalInfoRegExp.setMinimal(true);
+ QTC_CHECK(m_additionalInfoRegExp.isValid());
}
void MsvcParser::stdOutput(const QString &line)
@@ -114,7 +117,7 @@ void MsvcParser::stdOutput(const QString &line)
line.mid(6).trimmed(), /* description */
Utils::FileName(), /* fileName */
-1, /* linenumber */
- Core::Id(Constants::TASK_CATEGORY_COMPILE));
+ Constants::TASK_CATEGORY_COMPILE);
return;
}
if (line.startsWith(QLatin1String("Warning:"))) {
@@ -122,7 +125,7 @@ void MsvcParser::stdOutput(const QString &line)
line.mid(8).trimmed(), /* description */
Utils::FileName(), /* fileName */
-1, /* linenumber */
- Core::Id(Constants::TASK_CATEGORY_COMPILE));
+ Constants::TASK_CATEGORY_COMPILE);
return;
}
if (infoPos > -1) {
@@ -130,7 +133,7 @@ void MsvcParser::stdOutput(const QString &line)
m_additionalInfoRegExp.cap(3).trimmed(), /* description */
Utils::FileName::fromUserInput(m_additionalInfoRegExp.cap(1)), /* fileName */
m_additionalInfoRegExp.cap(2).toInt(), /* linenumber */
- Core::Id(Constants::TASK_CATEGORY_COMPILE));
+ Constants::TASK_CATEGORY_COMPILE);
return;
}
IOutputParser::stdOutput(line);
@@ -140,6 +143,15 @@ void MsvcParser::stdError(const QString &line)
{
if (processCompileLine(line))
return;
+ // Jom outputs errors to stderr
+ if (line.startsWith(QLatin1String("Error:"))) {
+ m_lastTask = Task(Task::Error,
+ line.mid(6).trimmed(), /* description */
+ Utils::FileName(), /* fileName */
+ -1, /* linenumber */
+ Constants::TASK_CATEGORY_COMPILE);
+ return;
+ }
IOutputParser::stdError(line);
}
@@ -152,7 +164,7 @@ bool MsvcParser::processCompileLine(const QString &line)
m_lastTask = Task(Task::Unknown,
m_compileRegExp.cap(4).trimmed() /* description */,
position.first, position.second,
- Core::Id(Constants::TASK_CATEGORY_COMPILE));
+ Constants::TASK_CATEGORY_COMPILE);
if (m_compileRegExp.cap(3) == QLatin1String("warning"))
m_lastTask.type = Task::Warning;
else if (m_compileRegExp.cap(3) == QLatin1String("error"))
@@ -183,6 +195,7 @@ void MsvcParser::doFlush()
# include "projectexplorer/outputparser_test.h"
using namespace ProjectExplorer::Internal;
+using namespace ProjectExplorer;
void ProjectExplorerPlugin::testMsvcOutputParsers_data()
{
@@ -190,39 +203,39 @@ void ProjectExplorerPlugin::testMsvcOutputParsers_data()
QTest::addColumn<OutputParserTester::Channel>("inputChannel");
QTest::addColumn<QString>("childStdOutLines");
QTest::addColumn<QString>("childStdErrLines");
- QTest::addColumn<QList<ProjectExplorer::Task> >("tasks");
+ QTest::addColumn<QList<Task> >("tasks");
QTest::addColumn<QString>("outputLines");
QTest::newRow("pass-through stdout")
<< QString::fromLatin1("Sometext") << OutputParserTester::STDOUT
<< QString::fromLatin1("Sometext\n") << QString()
- << QList<ProjectExplorer::Task>()
+ << QList<Task>()
<< QString();
QTest::newRow("pass-through stderr")
<< QString::fromLatin1("Sometext") << OutputParserTester::STDERR
<< QString() << QString::fromLatin1("Sometext\n")
- << QList<ProjectExplorer::Task>()
+ << QList<Task>()
<< QString();
QTest::newRow("labeled error")
<< QString::fromLatin1("qmlstandalone\\main.cpp(54) : error C4716: 'findUnresolvedModule' : must return a value") << OutputParserTester::STDOUT
<< QString() << QString()
- << (QList<ProjectExplorer::Task>()
+ << (QList<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)))
+ 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>()
+ << (QList<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)))
+ Constants::TASK_CATEGORY_COMPILE))
<< QString();
QTest::newRow("additional information")
@@ -230,26 +243,26 @@ void ProjectExplorerPlugin::testMsvcOutputParsers_data()
" x:\\src\\plugins\\texteditor\\completionsupport.h(39) : see declaration of 'TextEditor::CompletionItem'")
<< OutputParserTester::STDOUT
<< QString() << QString()
- << (QList<ProjectExplorer::Task>()
+ << (QList<Task>()
<< Task(Task::Warning,
QLatin1String("C4099: 'TextEditor::CompletionItem' : type name first seen using 'struct' now seen using 'class'"),
Utils::FileName::fromUserInput(QLatin1String("x:\\src\\plugins\\texteditor\\icompletioncollector.h")), 50,
- Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_COMPILE))
+ Constants::TASK_CATEGORY_COMPILE)
<< Task(Task::Unknown,
QLatin1String("see declaration of 'TextEditor::CompletionItem'"),
Utils::FileName::fromUserInput(QLatin1String("x:\\src\\plugins\\texteditor\\completionsupport.h")), 39,
- Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_COMPILE)))
+ Constants::TASK_CATEGORY_COMPILE))
<< QString();
QTest::newRow("fatal linker error")
<< QString::fromLatin1("LINK : fatal error LNK1146: no argument specified with option '/LIBPATH:'")
<< OutputParserTester::STDOUT
<< QString() << QString()
- << (QList<ProjectExplorer::Task>()
+ << (QList<Task>()
<< Task(Task::Error,
QLatin1String("LNK1146: no argument specified with option '/LIBPATH:'"),
Utils::FileName(), -1,
- Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_COMPILE)))
+ Constants::TASK_CATEGORY_COMPILE))
<< QString();
// This actually comes through stderr!
@@ -257,11 +270,11 @@ void ProjectExplorerPlugin::testMsvcOutputParsers_data()
<< QString::fromLatin1("cl : Command line warning D9002 : ignoring unknown option '-fopenmp'")
<< OutputParserTester::STDERR
<< QString() << QString()
- << (QList<ProjectExplorer::Task>()
+ << (QList<Task>()
<< Task(Task::Warning,
QLatin1String("D9002 : ignoring unknown option '-fopenmp'"),
Utils::FileName(), -1,
- Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_COMPILE)))
+ Constants::TASK_CATEGORY_COMPILE))
<< QString();
QTest::newRow("complex error")
<< QString::fromLatin1("..\\untitled\\main.cpp(19) : error C2440: 'initializing' : cannot convert from 'int' to 'std::_Tree<_Traits>::iterator'\n"
@@ -272,7 +285,7 @@ void ProjectExplorerPlugin::testMsvcOutputParsers_data()
" No constructor could take the source type, or constructor overload resolution was ambiguous")
<< OutputParserTester::STDOUT
<< QString() << QString()
- << (QList<ProjectExplorer::Task>()
+ << (QList<Task>()
<< Task(Task::Error,
QLatin1String("C2440: 'initializing' : cannot convert from 'int' to 'std::_Tree<_Traits>::iterator'\n"
"with\n"
@@ -281,37 +294,48 @@ void ProjectExplorerPlugin::testMsvcOutputParsers_data()
"]\n"
"No constructor could take the source type, or constructor overload resolution was ambiguous"),
Utils::FileName::fromUserInput(QLatin1String("..\\untitled\\main.cpp")), 19,
- Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_COMPILE)))
+ Constants::TASK_CATEGORY_COMPILE))
<< QString();
QTest::newRow("Linker error 1")
<< QString::fromLatin1("main.obj : error LNK2019: unresolved external symbol \"public: void __thiscall Data::doit(void)\" (?doit@Data@@QAEXXZ) referenced in function _main")
<< OutputParserTester::STDOUT
<< QString() << QString()
- << (QList<ProjectExplorer::Task>()
+ << (QList<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(QLatin1String("main.obj")), -1,
- Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_COMPILE)))
+ Constants::TASK_CATEGORY_COMPILE))
<< QString();
QTest::newRow("Linker error 2")
<< QString::fromLatin1("debug\\Experimentation.exe : fatal error LNK1120: 1 unresolved externals")
<< OutputParserTester::STDOUT
<< QString() << QString()
- << (QList<ProjectExplorer::Task>()
+ << (QList<Task>()
<< Task(Task::Error,
QLatin1String("LNK1120: 1 unresolved externals"),
Utils::FileName::fromUserInput(QLatin1String("debug\\Experimentation.exe")), -1,
- Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_COMPILE)))
+ Constants::TASK_CATEGORY_COMPILE))
<< QString();
- QTest::newRow("Linker error 3")
+
+ QTest::newRow("nmake error")
<< QString::fromLatin1("Error: dependent '..\\..\\..\\..\\creator-2.5\\src\\plugins\\coreplugin\\ifile.h' does not exist.")
<< OutputParserTester::STDOUT
<< QString() << QString()
- << (QList<ProjectExplorer::Task>()
+ << (QList<Task>()
<< Task(Task::Error,
QLatin1String("dependent '..\\..\\..\\..\\creator-2.5\\src\\plugins\\coreplugin\\ifile.h' does not exist."),
Utils::FileName(), -1,
- Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_COMPILE)))
+ Constants::TASK_CATEGORY_COMPILE))
+ << QString();
+ QTest::newRow("jom error")
+ << QString::fromLatin1("Error: dependent 'main.cpp' does not exist.")
+ << OutputParserTester::STDERR
+ << QString() << QString()
+ << (QList<Task>()
+ << Task(Task::Error,
+ QLatin1String("dependent 'main.cpp' does not exist."),
+ Utils::FileName(), -1,
+ Constants::TASK_CATEGORY_COMPILE))
<< QString();
QTest::newRow("Multiline error")
@@ -325,15 +349,15 @@ void ProjectExplorerPlugin::testMsvcOutputParsers_data()
" ]")
<< OutputParserTester::STDOUT
<< QString() << QString()
- << (QList<ProjectExplorer::Task>()
+ << (QList<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(QLatin1String("c:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\VC\\INCLUDE\\xutility")), 2227,
- Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_COMPILE))
+ Constants::TASK_CATEGORY_COMPILE)
<< Task(Task::Unknown,
QLatin1String("see declaration of 'std::_Copy_impl'"),
Utils::FileName::fromUserInput(QLatin1String("c:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\VC\\INCLUDE\\xutility")), 2212,
- Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_COMPILE))
+ 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"
"with\n"
@@ -342,7 +366,7 @@ void ProjectExplorerPlugin::testMsvcOutputParsers_data()
" _InIt=const unsigned char *\n"
"]"),
Utils::FileName::fromUserInput(QLatin1String("symbolgroupvalue.cpp")), 2314,
- Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_COMPILE)))
+ Constants::TASK_CATEGORY_COMPILE))
<< QString();
}
diff --git a/src/plugins/projectexplorer/msvctoolchain.cpp b/src/plugins/projectexplorer/msvctoolchain.cpp
index 63a3b9bdb4..e3544f7949 100644
--- a/src/plugins/projectexplorer/msvctoolchain.cpp
+++ b/src/plugins/projectexplorer/msvctoolchain.cpp
@@ -304,8 +304,8 @@ Utils::Environment MsvcToolChain::readEnvironmentSetting(Utils::Environment& env
// --------------------------------------------------------------------------
MsvcToolChain::MsvcToolChain(const QString &name, const Abi &abi,
- const QString &varsBat, const QString &varsBatArg, bool autodetect) :
- AbstractMsvcToolChain(QLatin1String(Constants::MSVC_TOOLCHAIN_ID), autodetect, abi, varsBat),
+ const QString &varsBat, const QString &varsBatArg, Detection d) :
+ AbstractMsvcToolChain(QLatin1String(Constants::MSVC_TOOLCHAIN_ID), d, abi, varsBat),
m_varsBatArg(varsBatArg)
{
Q_ASSERT(!name.isEmpty());
@@ -322,7 +322,7 @@ bool MsvcToolChain::isValid() const
}
MsvcToolChain::MsvcToolChain() :
- AbstractMsvcToolChain(QLatin1String(Constants::MSVC_TOOLCHAIN_ID), false)
+ AbstractMsvcToolChain(QLatin1String(Constants::MSVC_TOOLCHAIN_ID), ManualDetection)
{
}
@@ -429,14 +429,10 @@ void MsvcToolChainConfigWidget::setFromToolChain()
// MsvcToolChainFactory
// --------------------------------------------------------------------------
-QString MsvcToolChainFactory::displayName() const
+MsvcToolChainFactory::MsvcToolChainFactory()
{
- return tr("MSVC");
-}
-
-QString MsvcToolChainFactory::id() const
-{
- return QLatin1String(Constants::MSVC_TOOLCHAIN_ID);
+ setId(Constants::MSVC_TOOLCHAIN_ID);
+ setDisplayName(tr("MSVC"));
}
bool MsvcToolChainFactory::checkForVisualStudioInstallation(const QString &vsName)
@@ -501,14 +497,14 @@ QList<ToolChain *> MsvcToolChainFactory::autoDetect()
QList<ToolChain *> tmp;
tmp.append(new MsvcToolChain(generateDisplayName(name, MsvcToolChain::WindowsSDK, MsvcToolChain::x86),
findAbiOfMsvc(MsvcToolChain::WindowsSDK, MsvcToolChain::x86, sdkKey),
- fi.absoluteFilePath(), QLatin1String("/x86"), true));
+ fi.absoluteFilePath(), QLatin1String("/x86"), ToolChain::AutoDetection));
// Add all platforms, cross-compiler is automatically selected by SetEnv.cmd if needed
tmp.append(new MsvcToolChain(generateDisplayName(name, MsvcToolChain::WindowsSDK, MsvcToolChain::amd64),
findAbiOfMsvc(MsvcToolChain::WindowsSDK, MsvcToolChain::amd64, sdkKey),
- fi.absoluteFilePath(), QLatin1String("/x64"), true));
+ fi.absoluteFilePath(), QLatin1String("/x64"), ToolChain::AutoDetection));
tmp.append(new MsvcToolChain(generateDisplayName(name, MsvcToolChain::WindowsSDK, MsvcToolChain::ia64),
findAbiOfMsvc(MsvcToolChain::WindowsSDK, MsvcToolChain::ia64, sdkKey),
- fi.absoluteFilePath(), QLatin1String("/ia64"), true));
+ fi.absoluteFilePath(), QLatin1String("/ia64"), ToolChain::AutoDetection));
// Make sure the default is front.
if (folder == defaultSdkPath)
results = tmp + results;
@@ -543,23 +539,23 @@ QList<ToolChain *> MsvcToolChainFactory::autoDetect()
if (QFileInfo(vcVarsBatFor(path, QLatin1String("x86"))).isFile())
results.append(new MsvcToolChain(generateDisplayName(vsName, MsvcToolChain::VS, MsvcToolChain::x86),
findAbiOfMsvc(MsvcToolChain::VS, MsvcToolChain::x86, vsName),
- vcvarsAllbat, QLatin1String("x86"), true));
+ vcvarsAllbat, QLatin1String("x86"), ToolChain::AutoDetection));
if (arch == Utils::HostOsInfo::HostArchitectureX86) {
if (QFileInfo(vcVarsBatFor(path, QLatin1String("x86_amd64"))).isFile())
results.append(new MsvcToolChain(generateDisplayName(vsName, MsvcToolChain::VS, MsvcToolChain::amd64),
findAbiOfMsvc(MsvcToolChain::VS, MsvcToolChain::amd64, vsName),
- vcvarsAllbat, QLatin1String("x86_amd64"), true));
+ vcvarsAllbat, QLatin1String("x86_amd64"), ToolChain::AutoDetection));
} else if (arch == Utils::HostOsInfo::HostArchitectureAMD64) {
if (QFileInfo(vcVarsBatFor(path, QLatin1String("amd64"))).isFile()) {
results.append(new MsvcToolChain(generateDisplayName(vsName, MsvcToolChain::VS, MsvcToolChain::amd64),
findAbiOfMsvc(MsvcToolChain::VS, MsvcToolChain::amd64, vsName),
- vcvarsAllbat, QLatin1String("amd64"), true));
+ vcvarsAllbat, QLatin1String("amd64"), ToolChain::AutoDetection));
} else if (QFileInfo(vcVarsBatFor(path, QLatin1String("x86_amd64"))).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));
+ vcvarsAllbat, QLatin1String("x86_amd64"), ToolChain::AutoDetection));
}
}
@@ -568,25 +564,25 @@ QList<ToolChain *> MsvcToolChainFactory::autoDetect()
if (QFileInfo(vcVarsBatFor(path, QLatin1String("x86_arm"))).isFile())
results.append(new MsvcToolChain(generateDisplayName(vsName, MsvcToolChain::VS, MsvcToolChain::arm),
findAbiOfMsvc(MsvcToolChain::VS, MsvcToolChain::arm, vsName),
- vcvarsAllbat, QLatin1String("x86_arm"), true));
+ vcvarsAllbat, QLatin1String("x86_arm"), ToolChain::AutoDetection));
} else if (arch == Utils::HostOsInfo::HostArchitectureArm) {
if (QFileInfo(vcVarsBatFor(path, QLatin1String("arm"))).isFile())
results.append(new MsvcToolChain(generateDisplayName(vsName, MsvcToolChain::VS, MsvcToolChain::arm),
findAbiOfMsvc(MsvcToolChain::VS, MsvcToolChain::arm, vsName),
- vcvarsAllbat, QLatin1String("arm"), true));
+ vcvarsAllbat, QLatin1String("arm"), ToolChain::AutoDetection));
}
if (arch == Utils::HostOsInfo::HostArchitectureItanium) {
if (QFileInfo(vcVarsBatFor(path, QLatin1String("ia64"))).isFile())
results.append(new MsvcToolChain(generateDisplayName(vsName, MsvcToolChain::VS, MsvcToolChain::ia64),
findAbiOfMsvc(MsvcToolChain::VS, MsvcToolChain::ia64, vsName),
- vcvarsAllbat, QLatin1String("ia64"), true));
+ vcvarsAllbat, QLatin1String("ia64"), ToolChain::AutoDetection));
} else if (arch == Utils::HostOsInfo::HostArchitectureX86
|| arch == Utils::HostOsInfo::HostArchitectureAMD64) {
if (QFileInfo(vcVarsBatFor(path, QLatin1String("x86_ia64"))).isFile())
results.append(new MsvcToolChain(generateDisplayName(vsName, MsvcToolChain::VS, MsvcToolChain::ia64),
findAbiOfMsvc(MsvcToolChain::VS, MsvcToolChain::ia64, vsName),
- vcvarsAllbat, QLatin1String("x86_ia64"), true));
+ vcvarsAllbat, QLatin1String("x86_ia64"), ToolChain::AutoDetection));
}
} else {
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 92162bed49..29d5387a1f 100644
--- a/src/plugins/projectexplorer/msvctoolchain.h
+++ b/src/plugins/projectexplorer/msvctoolchain.h
@@ -54,7 +54,7 @@ public:
};
MsvcToolChain(const QString &name, const Abi &abi,
- const QString &varsBat, const QString &varsBatArg, bool autodetect = false);
+ const QString &varsBat, const QString &varsBatArg, Detection d = ManualDetection);
bool isValid() const;
QList<Utils::FileName> suggestedMkspecList() const;
@@ -94,13 +94,12 @@ class MsvcToolChainFactory : public ToolChainFactory
Q_OBJECT
public:
- QString displayName() const;
- QString id() const;
+ MsvcToolChainFactory();
QList<ToolChain *> autoDetect();
- virtual bool canRestore(const QVariantMap &data);
- virtual ToolChain *restore(const QVariantMap &data)
+ bool canRestore(const QVariantMap &data);
+ ToolChain *restore(const QVariantMap &data)
{ return MsvcToolChain::readFromMap(data); }
ToolChainConfigWidget *configurationWidget(ToolChain *);
diff --git a/src/plugins/projectexplorer/nodesvisitor.cpp b/src/plugins/projectexplorer/nodesvisitor.cpp
index 3f9a3894ab..ba64f18752 100644
--- a/src/plugins/projectexplorer/nodesvisitor.cpp
+++ b/src/plugins/projectexplorer/nodesvisitor.cpp
@@ -35,7 +35,7 @@ using namespace ProjectExplorer;
/*!
\class NodesVisitor
- \short Base class for visitors that can be used to traverse a node hierarchy.
+ \brief Base class for visitors that can be used to traverse a node hierarchy.
The class follows the visitor pattern as described in Gamma et al. Pass
an instance of NodesVisitor to FolderNode::accept(): The visit methods
@@ -45,7 +45,7 @@ using namespace ProjectExplorer;
*/
/*!
- \method NodesVisitor::visitSessionNode(SessionNode *)
+ \fn NodesVisitor::visitSessionNode(SessionNode *)
Called for the root session node.
@@ -53,7 +53,7 @@ using namespace ProjectExplorer;
*/
/*!
- \method NodesVisitor::visitProjectNode(SessionNode *)
+ \fn NodesVisitor::visitProjectNode(SessionNode *)
Called for a project node.
@@ -61,7 +61,7 @@ using namespace ProjectExplorer;
*/
/*!
- \method NodesVisitor::visitFolderNode(SessionNode *)
+ \fn NodesVisitor::visitFolderNode(SessionNode *)
Called for a folder node that is _not_ a SessionNode or a ProjectNode.
diff --git a/src/plugins/cmakeprojectmanager/cmakeuicodemodelsupport.cpp b/src/plugins/projectexplorer/osparser.cpp
index f490b2554c..3747b6dd76 100644
--- a/src/plugins/cmakeprojectmanager/cmakeuicodemodelsupport.cpp
+++ b/src/plugins/projectexplorer/osparser.cpp
@@ -27,37 +27,40 @@
**
****************************************************************************/
-#include "cmakeuicodemodelsupport.h"
-#include "cmakeproject.h"
-#include "cmakebuildconfiguration.h"
+#include "osparser.h"
+#include "projectexplorerconstants.h"
+#include "task.h"
-#include <cpptools/cppmodelmanagerinterface.h>
-#include <projectexplorer/target.h>
+#include <utils/hostosinfo.h>
-#include <QProcess>
+using namespace ProjectExplorer;
-using namespace CMakeProjectManager;
-using namespace Internal;
-
-CMakeUiCodeModelSupport::CMakeUiCodeModelSupport(CppTools::CppModelManagerInterface *modelmanager,
- CMakeProject *project,
- const QString &source,
- const QString &uiHeaderFile)
- : CppTools::UiCodeModelSupport(modelmanager, source, uiHeaderFile),
- m_project(project)
-{ }
+OsParser::OsParser() :
+ m_hasFatalError(false)
+{
+ setObjectName(QLatin1String("OsParser"));
+}
-CMakeUiCodeModelSupport::~CMakeUiCodeModelSupport()
-{ }
+void OsParser::stdError(const QString &line)
+{
+ IOutputParser::stdError(line);
+}
-QString CMakeUiCodeModelSupport::uicCommand() const
+void OsParser::stdOutput(const QString &line)
{
- return m_project->uicCommand();
+ if (Utils::HostOsInfo::isWindowsHost()) {
+ const QString trimmed = line.trimmed();
+ if (trimmed == QLatin1String("The process cannot access the file because it is being used by another process.")) {
+ addTask(Task(Task::Error, tr("The process can not access the file because it is being used by another process.\n"
+ "Please close all running instances of your application before starting a build."),
+ Utils::FileName(), -1, Constants::TASK_CATEGORY_COMPILE));
+ m_hasFatalError = true;
+ }
+ }
+ IOutputParser::stdOutput(line);
}
-QStringList CMakeUiCodeModelSupport::environment() const
+bool OsParser::hasFatalErrors() const
{
- if (!m_project || !m_project->activeTarget() || !m_project->activeTarget()->activeBuildConfiguration())
- return QStringList();
- return m_project->activeTarget()->activeBuildConfiguration()->environment().toStringList();
+ return m_hasFatalError || IOutputParser::hasFatalErrors();
}
diff --git a/src/plugins/projectexplorer/osparser.h b/src/plugins/projectexplorer/osparser.h
new file mode 100644
index 0000000000..ccc4364ca0
--- /dev/null
+++ b/src/plugins/projectexplorer/osparser.h
@@ -0,0 +1,59 @@
+/****************************************************************************
+**
+** 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 OSPARSER_H
+#define OSPARSER_H
+
+#include "ioutputparser.h"
+
+#include <projectexplorer/task.h>
+
+#include <QRegExp>
+
+namespace ProjectExplorer {
+
+class OsParser : public ProjectExplorer::IOutputParser
+{
+ Q_OBJECT
+
+public:
+ OsParser();
+
+ void stdError(const QString &line);
+ void stdOutput(const QString &line);
+
+ bool hasFatalErrors() const;
+
+private:
+ bool m_hasFatalError;
+};
+
+} // namespace ProjectExplorer
+
+#endif // OSPARSER_H
diff --git a/src/plugins/projectexplorer/pluginfilefactory.cpp b/src/plugins/projectexplorer/pluginfilefactory.cpp
index 64353d644c..f3393f1973 100644
--- a/src/plugins/projectexplorer/pluginfilefactory.cpp
+++ b/src/plugins/projectexplorer/pluginfilefactory.cpp
@@ -49,24 +49,11 @@ using namespace ProjectExplorer::Internal;
*/
ProjectFileFactory::ProjectFileFactory(IProjectManager *manager)
- : m_mimeTypes(manager->mimeType()),
- m_manager(manager)
+ : m_manager(manager)
{
-}
-
-QStringList ProjectFileFactory::mimeTypes() const
-{
- return m_mimeTypes;
-}
-
-Core::Id ProjectFileFactory::id() const
-{
- return Core::Id(Constants::FILE_FACTORY_ID);
-}
-
-QString ProjectFileFactory::displayName() const
-{
- return tr("Project File Factory", "ProjectExplorer::ProjectFileFactory display name.");
+ setId(Constants::FILE_FACTORY_ID);
+ setDisplayName(tr("Project File Factory", "ProjectExplorer::ProjectFileFactory display name."));
+ addMimeType(manager->mimeType());
}
Core::IDocument *ProjectFileFactory::open(const QString &fileName)
@@ -95,7 +82,7 @@ QList<ProjectFileFactory *> ProjectFileFactory::createFactories(QString *filterS
if (!filterString->isEmpty())
*filterString += filterSeparator;
const QString mimeType = manager->mimeType();
- Core::MimeType mime = Core::ICore::mimeDatabase()->findByType(mimeType);
+ Core::MimeType mime = Core::MimeDatabase::findByType(mimeType);
const QString pFilterString = mime.filterString();
allGlobPatterns.append(mime.globPatterns());
*filterString += pFilterString;
diff --git a/src/plugins/projectexplorer/pluginfilefactory.h b/src/plugins/projectexplorer/pluginfilefactory.h
index 68cb962b4c..61dbbfb87e 100644
--- a/src/plugins/projectexplorer/pluginfilefactory.h
+++ b/src/plugins/projectexplorer/pluginfilefactory.h
@@ -48,16 +48,11 @@ class ProjectFileFactory : public Core::IDocumentFactory
explicit ProjectFileFactory(ProjectExplorer::IProjectManager *manager);
public:
- virtual QStringList mimeTypes() const;
- Core::Id id() const;
- QString displayName() const;
-
Core::IDocument *open(const QString &fileName);
static QList<ProjectFileFactory*> createFactories(QString *filterString);
private:
- const QStringList m_mimeTypes;
ProjectExplorer::IProjectManager *m_manager;
};
diff --git a/src/plugins/projectexplorer/processstep.cpp b/src/plugins/projectexplorer/processstep.cpp
index cb0915ad2d..93114501f7 100644
--- a/src/plugins/projectexplorer/processstep.cpp
+++ b/src/plugins/projectexplorer/processstep.cpp
@@ -88,9 +88,7 @@ bool ProcessStep::init()
pp->setArguments(m_arguments);
pp->resolveAll();
- IOutputParser *parser = target()->kit()->createOutputParser();
- if (parser)
- setOutputParser(parser);
+ setOutputParser(target()->kit()->createOutputParser());
return AbstractProcessStep::init();
}
diff --git a/src/plugins/projectexplorer/project.cpp b/src/plugins/projectexplorer/project.cpp
index ac10056b82..7dc2ddac01 100644
--- a/src/plugins/projectexplorer/project.cpp
+++ b/src/plugins/projectexplorer/project.cpp
@@ -29,6 +29,7 @@
#include "project.h"
+#include "buildinfo.h"
#include "buildconfiguration.h"
#include "editorconfiguration.h"
#include "projectexplorer.h"
@@ -111,6 +112,11 @@ Project::~Project()
delete d;
}
+QString Project::projectFilePath() const
+{
+ return document()->filePath();
+}
+
bool Project::hasActiveBuildSettings() const
{
return activeTarget() && IBuildConfigurationFactory::find(activeTarget());
@@ -169,9 +175,7 @@ bool Project::removeTarget(Target *target)
if (!target || !d->m_targets.contains(target))
return false;
- ProjectExplorer::BuildManager *bm =
- ProjectExplorer::ProjectExplorerPlugin::instance()->buildManager();
- if (bm->isBuilding(target))
+ if (BuildManager::isBuilding(target))
return false;
if (target == activeTarget()) {
@@ -267,7 +271,7 @@ Target *Project::restoreTarget(const QVariantMap &data)
return 0;
}
- Kit *k = KitManager::instance()->find(id);
+ Kit *k = KitManager::find(id);
if (!k) {
qWarning("Warning: No kit '%s' found. Continuing.", qPrintable(id.toString()));
return 0;
@@ -278,6 +282,7 @@ Target *Project::restoreTarget(const QVariantMap &data)
delete t;
return 0;
}
+
return t;
}
@@ -330,7 +335,7 @@ QVariantMap Project::toMap() const
QString Project::projectDirectory() const
{
- return projectDirectory(document()->fileName());
+ return projectDirectory(document()->filePath());
}
QString Project::projectDirectory(const QString &top)
@@ -475,6 +480,44 @@ bool Project::needsSpecialDeployment() const
return false;
}
+void Project::setup(QList<const BuildInfo *> infoList)
+{
+ QList<Target *> toRegister;
+ foreach (const BuildInfo *info, infoList) {
+ Kit *k = KitManager::find(info->kitId);
+ if (!k)
+ continue;
+ Target *t = target(k);
+ if (!t) {
+ foreach (Target *i, toRegister) {
+ if (i->kit() == k) {
+ t = i;
+ break;
+ }
+ }
+ }
+ if (!t) {
+ t = new Target(this, k);
+ toRegister << t;
+ }
+
+ BuildConfiguration *bc = info->factory()->create(t, info);
+ if (!bc)
+ continue;
+ t->addBuildConfiguration(bc);
+ }
+ foreach (Target *t, toRegister) {
+ t->updateDefaultDeployConfigurations();
+ t->updateDefaultRunConfigurations();
+ addTarget(t);
+ }
+}
+
+ProjectImporter *Project::createProjectImporter() const
+{
+ return 0;
+}
+
void Project::onBuildDirectoryChanged()
{
Target *target = qobject_cast<Target *>(sender());
diff --git a/src/plugins/projectexplorer/project.h b/src/plugins/projectexplorer/project.h
index 75f90d729d..962512c7b1 100644
--- a/src/plugins/projectexplorer/project.h
+++ b/src/plugins/projectexplorer/project.h
@@ -44,10 +44,13 @@ class Context;
namespace ProjectExplorer {
+class BuildInfo;
class IProjectManager;
class EditorConfiguration;
+class ProjectImporter;
class ProjectNode;
class Kit;
+class KitMatcher;
class NamedWidget;
class Target;
class ProjectPrivate;
@@ -74,6 +77,8 @@ public:
virtual Core::IDocument *document() const = 0;
virtual IProjectManager *projectManager() const = 0;
+ QString projectFilePath() const;
+
bool hasActiveBuildSettings() const;
// EditorConfiguration:
@@ -122,9 +127,14 @@ public:
virtual void configureAsExampleProject(const QStringList &platforms);
virtual bool supportsNoTargetPanel() const;
+ virtual ProjectImporter *createProjectImporter() const;
+ virtual KitMatcher *createRequiredKitMatcher() const { return 0; }
+ virtual KitMatcher *createPreferredKitMatcher() const { return 0; }
virtual bool needsSpecialDeployment() const;
+ void setup(QList<const BuildInfo *> infoList);
+
signals:
void displayNameChanged();
void fileListChanged();
diff --git a/src/plugins/projectexplorer/projectexplorer.cpp b/src/plugins/projectexplorer/projectexplorer.cpp
index ce3a5657e5..dad6d1720f 100644
--- a/src/plugins/projectexplorer/projectexplorer.cpp
+++ b/src/plugins/projectexplorer/projectexplorer.cpp
@@ -37,6 +37,7 @@
#include "projectexplorersettings.h"
#include "projectmacroexpander.h"
#include "removetaskhandler.h"
+#include "unconfiguredprojectpanel.h"
#include "kitmanager.h"
#include "kitoptionspage.h"
#include "target.h"
@@ -61,7 +62,6 @@
#include "appoutputpane.h"
#include "pluginfilefactory.h"
#include "processstep.h"
-#include "customwizard.h"
#include "kitinformation.h"
#include "projectfilewizardextension.h"
#include "projecttreewidget.h"
@@ -71,12 +71,12 @@
#include "projectnodes.h"
#include "sessiondialog.h"
#include "projectexplorersettingspage.h"
-#include "projectwelcomepage.h"
#include "corelistenercheckingforrunningbuild.h"
#include "buildconfiguration.h"
#include "miniprojecttargetselector.h"
#include "taskhub.h"
#include "customtoolchain.h"
+#include <projectexplorer/customwizard/customwizard.h>
#include "devicesupport/desktopdevice.h"
#include "devicesupport/desktopdevicefactory.h"
#include "devicesupport/devicemanager.h"
@@ -90,6 +90,12 @@
# include "wincetoolchain.h"
#endif
+#define HAS_WELCOME_PAGE (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
+
+#if HAS_WELCOME_PAGE
+#include "projectwelcomepage.h"
+#endif
+
#include <extensionsystem/pluginspec.h>
#include <coreplugin/icore.h>
#include <coreplugin/editormanager/ieditor.h>
@@ -109,6 +115,7 @@
#include <coreplugin/variablemanager.h>
#include <coreplugin/fileutils.h>
#include <coreplugin/removefiledialog.h>
+#include <texteditor/findinfiles.h>
#include <utils/qtcassert.h>
#include <utils/parameteraction.h>
@@ -149,6 +156,8 @@ bool debug = false;
const char EXTERNAL_FILE_WARNING[] = "ExternalFile";
}
+using namespace Core;
+
namespace ProjectExplorer {
struct ProjectExplorerPluginPrivate {
@@ -208,15 +217,12 @@ struct ProjectExplorerPluginPrivate {
QAction *m_runSubProject;
Internal::ProjectWindow *m_proWindow;
- SessionManager *m_session;
QString m_sessionToRestoreAtStartup;
Project *m_currentProject;
- Core::Context m_lastProjectContext;
+ Context m_lastProjectContext;
Node *m_currentNode;
- BuildManager *m_buildManager;
-
QList<Internal::ProjectFileFactory*> m_fileFactories;
QStringList m_profileMimeTypes;
Internal::AppOutputPane *m_outputPane;
@@ -230,9 +236,12 @@ struct ProjectExplorerPluginPrivate {
QString m_projectFilterString;
Internal::MiniProjectTargetSelector * m_targetSelector;
Internal::ProjectExplorerSettings m_projectExplorerSettings;
- Internal::ProjectWelcomePage *m_welcomePage;
- Core::IMode *m_projectsMode;
+
+#if HAS_WELCOME_PAGE
+ Internal::ProjectWelcomePage *m_welcomePage;
+#endif
+ IMode *m_projectsMode;
TaskHub *m_taskHub;
KitManager *m_kitManager;
@@ -255,13 +264,13 @@ ProjectExplorerPluginPrivate::ProjectExplorerPluginPrivate() :
{
}
-class ProjectsMode : public Core::IMode
+class ProjectsMode : public IMode
{
public:
ProjectsMode(QWidget *proWindow)
{
setWidget(proWindow);
- setContext(Core::Context(Constants::C_PROJECTEXPLORER));
+ setContext(Context(Constants::C_PROJECTEXPLORER));
setDisplayName(QCoreApplication::translate("ProjectExplorer::ProjectsMode", "Projects"));
setIcon(QIcon(QLatin1String(":/fancyactionbar/images/mode_Project.png")));
setPriority(Constants::P_MODE_SESSION);
@@ -286,8 +295,10 @@ ProjectExplorerPlugin::ProjectExplorerPlugin()
ProjectExplorerPlugin::~ProjectExplorerPlugin()
{
+#if HAS_WELCOME_PAGE
removeObject(d->m_welcomePage);
delete d->m_welcomePage;
+#endif
removeObject(this);
// Force sequence of deletion:
delete d->m_kitManager; // remove all the profile informations
@@ -338,59 +349,60 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
d->m_toolChainManager = new ToolChainManager;
// Register KitInformation:
- KitManager::instance()->registerKitInformation(new DeviceTypeKitInformation);
- KitManager::instance()->registerKitInformation(new DeviceKitInformation);
- KitManager::instance()->registerKitInformation(new ToolChainKitInformation);
- KitManager::instance()->registerKitInformation(new SysRootKitInformation);
+ KitManager::registerKitInformation(new DeviceTypeKitInformation);
+ KitManager::registerKitInformation(new DeviceKitInformation);
+ KitManager::registerKitInformation(new ToolChainKitInformation);
+ KitManager::registerKitInformation(new SysRootKitInformation);
addAutoReleasedObject(new Internal::ToolChainOptionsPage);
addAutoReleasedObject(new KitOptionsPage);
- d->m_taskHub = new TaskHub;
- addAutoReleasedObject(d->m_taskHub);
+ addAutoReleasedObject(new TaskHub);
- connect(Core::ICore::instance(), SIGNAL(newItemsDialogRequested()), this, SLOT(loadCustomWizards()));
+ connect(ICore::instance(), SIGNAL(newItemsDialogRequested()), this, SLOT(loadCustomWizards()));
+#if HAS_WELCOME_PAGE
d->m_welcomePage = new ProjectWelcomePage;
connect(d->m_welcomePage, SIGNAL(manageSessions()), this, SLOT(showSessionManager()));
addObject(d->m_welcomePage);
+#endif
- connect(Core::DocumentManager::instance(), SIGNAL(currentFileChanged(QString)),
+ connect(DocumentManager::instance(), SIGNAL(currentFileChanged(QString)),
this, SLOT(setCurrentFile(QString)));
- d->m_session = new SessionManager(this);
+ QObject *sessionManager = new SessionManager(this);
- connect(d->m_session, SIGNAL(projectAdded(ProjectExplorer::Project*)),
+ connect(sessionManager, SIGNAL(projectAdded(ProjectExplorer::Project*)),
this, SIGNAL(fileListChanged()));
- connect(d->m_session, SIGNAL(aboutToRemoveProject(ProjectExplorer::Project*)),
+ connect(sessionManager, SIGNAL(aboutToRemoveProject(ProjectExplorer::Project*)),
this, SLOT(invalidateProject(ProjectExplorer::Project*)));
- connect(d->m_session, SIGNAL(projectRemoved(ProjectExplorer::Project*)),
+ connect(sessionManager, SIGNAL(projectRemoved(ProjectExplorer::Project*)),
this, SIGNAL(fileListChanged()));
- connect(d->m_session, SIGNAL(projectAdded(ProjectExplorer::Project*)),
+ connect(sessionManager, SIGNAL(projectAdded(ProjectExplorer::Project*)),
this, SLOT(projectAdded(ProjectExplorer::Project*)));
- connect(d->m_session, SIGNAL(projectRemoved(ProjectExplorer::Project*)),
+ connect(sessionManager, SIGNAL(projectRemoved(ProjectExplorer::Project*)),
this, SLOT(projectRemoved(ProjectExplorer::Project*)));
- connect(d->m_session, SIGNAL(startupProjectChanged(ProjectExplorer::Project*)),
+ connect(sessionManager, SIGNAL(startupProjectChanged(ProjectExplorer::Project*)),
this, SLOT(startupProjectChanged()));
- connect(d->m_session, SIGNAL(projectDisplayNameChanged(ProjectExplorer::Project*)),
+ connect(sessionManager, SIGNAL(projectDisplayNameChanged(ProjectExplorer::Project*)),
this, SLOT(projectDisplayNameChanged(ProjectExplorer::Project*)));
- connect(d->m_session, SIGNAL(dependencyChanged(ProjectExplorer::Project*,ProjectExplorer::Project*)),
+ connect(sessionManager, SIGNAL(dependencyChanged(ProjectExplorer::Project*,ProjectExplorer::Project*)),
this, SLOT(updateActions()));
- connect(d->m_session, SIGNAL(sessionLoaded(QString)),
+ connect(sessionManager, SIGNAL(sessionLoaded(QString)),
this, SLOT(updateActions()));
- connect(d->m_session, SIGNAL(sessionLoaded(QString)),
+ connect(sessionManager, SIGNAL(sessionLoaded(QString)),
this, SLOT(updateWelcomePage()));
d->m_proWindow = new ProjectWindow;
addAutoReleasedObject(d->m_proWindow);
- Core::Context globalcontext(Core::Constants::C_GLOBAL);
- Core::Context projecTreeContext(Constants::C_PROJECT_TREE);
+ Context globalcontext(Core::Constants::C_GLOBAL);
+ Context projecTreeContext(Constants::C_PROJECT_TREE);
d->m_projectsMode = new ProjectsMode(d->m_proWindow);
d->m_projectsMode->setEnabled(false);
addAutoReleasedObject(d->m_projectsMode);
- d->m_proWindow->layout()->addWidget(new Core::FindToolBarPlaceHolder(d->m_proWindow));
+ d->m_proWindow->layout()->addWidget(new FindToolBarPlaceHolder(d->m_proWindow));
addAutoReleasedObject(new CopyTaskHandler);
addAutoReleasedObject(new ShowInEditorTaskHandler);
@@ -400,7 +412,7 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
d->m_outputPane = new AppOutputPane;
addAutoReleasedObject(d->m_outputPane);
- connect(d->m_session, SIGNAL(projectRemoved(ProjectExplorer::Project*)),
+ connect(SessionManager::instance(), SIGNAL(projectRemoved(ProjectExplorer::Project*)),
d->m_outputPane, SLOT(projectRemoved()));
connect(d->m_outputPane, SIGNAL(runControlStarted(ProjectExplorer::RunControl*)),
@@ -408,26 +420,20 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
connect(d->m_outputPane, SIGNAL(runControlFinished(ProjectExplorer::RunControl*)),
this, SIGNAL(runControlFinished(ProjectExplorer::RunControl*)));
- AllProjectsFilter *allProjectsFilter = new AllProjectsFilter(this);
- addAutoReleasedObject(allProjectsFilter);
-
- CurrentProjectFilter *currentProjectFilter = new CurrentProjectFilter(this);
- addAutoReleasedObject(currentProjectFilter);
+ addAutoReleasedObject(new AllProjectsFilter);
+ addAutoReleasedObject(new CurrentProjectFilter);
addAutoReleasedObject(new BuildSettingsPanelFactory);
addAutoReleasedObject(new RunSettingsPanelFactory);
addAutoReleasedObject(new EditorSettingsPanelFactory);
addAutoReleasedObject(new CodeStyleSettingsPanelFactory);
- addAutoReleasedObject(new DependenciesPanelFactory(d->m_session));
-
- ProcessStepFactory *processStepFactory = new ProcessStepFactory;
- addAutoReleasedObject(processStepFactory);
+ addAutoReleasedObject(new DependenciesPanelFactory);
- AllProjectsFind *allProjectsFind = new AllProjectsFind(this);
- addAutoReleasedObject(allProjectsFind);
+ addAutoReleasedObject(new ProcessStepFactory);
+ addAutoReleasedObject(new UnconfiguredProjectPanel);
- CurrentProjectFind *currentProjectFind = new CurrentProjectFind(this);
- addAutoReleasedObject(currentProjectFind);
+ addAutoReleasedObject(new AllProjectsFind);
+ addAutoReleasedObject(new CurrentProjectFind);
addAutoReleasedObject(new LocalApplicationRunControlFactory);
@@ -438,16 +444,16 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
addAutoReleasedObject(new DeviceSettingsPage);
// context menus
- Core::ActionContainer *msessionContextMenu =
- Core::ActionManager::createMenu(Constants::M_SESSIONCONTEXT);
- Core::ActionContainer *mprojectContextMenu =
- Core::ActionManager::createMenu(Constants::M_PROJECTCONTEXT);
- Core::ActionContainer *msubProjectContextMenu =
- Core::ActionManager::createMenu(Constants::M_SUBPROJECTCONTEXT);
- Core::ActionContainer *mfolderContextMenu =
- Core::ActionManager::createMenu(Constants::M_FOLDERCONTEXT);
- Core::ActionContainer *mfileContextMenu =
- Core::ActionManager::createMenu(Constants::M_FILECONTEXT);
+ ActionContainer *msessionContextMenu =
+ ActionManager::createMenu(Constants::M_SESSIONCONTEXT);
+ ActionContainer *mprojectContextMenu =
+ ActionManager::createMenu(Constants::M_PROJECTCONTEXT);
+ ActionContainer *msubProjectContextMenu =
+ ActionManager::createMenu(Constants::M_SUBPROJECTCONTEXT);
+ ActionContainer *mfolderContextMenu =
+ ActionManager::createMenu(Constants::M_FOLDERCONTEXT);
+ ActionContainer *mfileContextMenu =
+ ActionManager::createMenu(Constants::M_FILECONTEXT);
d->m_sessionContextMenu = msessionContextMenu->menu();
d->m_projectMenu = mprojectContextMenu->menu();
@@ -455,25 +461,25 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
d->m_folderMenu = mfolderContextMenu->menu();
d->m_fileMenu = mfileContextMenu->menu();
- Core::ActionContainer *mfile =
- Core::ActionManager::actionContainer(Core::Constants::M_FILE);
- Core::ActionContainer *menubar =
- Core::ActionManager::actionContainer(Core::Constants::MENU_BAR);
+ ActionContainer *mfile =
+ ActionManager::actionContainer(Core::Constants::M_FILE);
+ ActionContainer *menubar =
+ ActionManager::actionContainer(Core::Constants::MENU_BAR);
// build menu
- Core::ActionContainer *mbuild =
- Core::ActionManager::createMenu(Constants::M_BUILDPROJECT);
+ ActionContainer *mbuild =
+ ActionManager::createMenu(Constants::M_BUILDPROJECT);
mbuild->menu()->setTitle(tr("&Build"));
menubar->addMenu(mbuild, Core::Constants::G_VIEW);
// debug menu
- Core::ActionContainer *mdebug =
- Core::ActionManager::createMenu(Constants::M_DEBUG);
+ ActionContainer *mdebug =
+ ActionManager::createMenu(Constants::M_DEBUG);
mdebug->menu()->setTitle(tr("&Debug"));
menubar->addMenu(mdebug, Core::Constants::G_VIEW);
- Core::ActionContainer *mstartdebugging =
- Core::ActionManager::createMenu(Constants::M_DEBUG_STARTDEBUGGING);
+ ActionContainer *mstartdebugging =
+ ActionManager::createMenu(Constants::M_DEBUG_STARTDEBUGGING);
mstartdebugging->menu()->setTitle(tr("&Start Debugging"));
mdebug->addMenu(mstartdebugging, Core::Constants::G_DEFAULT_ONE);
@@ -509,8 +515,8 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
msubProjectContextMenu->appendGroup(Constants::G_PROJECT_LAST);
msubProjectContextMenu->appendGroup(Constants::G_PROJECT_TREE);
- Core::ActionContainer *runMenu = Core::ActionManager::createMenu(Constants::RUNMENUCONTEXTMENU);
- runMenu->setOnAllDisabledBehavior(Core::ActionContainer::Hide);
+ ActionContainer *runMenu = ActionManager::createMenu(Constants::RUNMENUCONTEXTMENU);
+ runMenu->setOnAllDisabledBehavior(ActionContainer::Hide);
QIcon runIcon = QIcon(QLatin1String(Constants::ICON_RUN));
runIcon.addFile(QLatin1String(Constants::ICON_RUN_SMALL));
runMenu->menu()->setIcon(runIcon);
@@ -527,20 +533,20 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
mfileContextMenu->appendGroup(Constants::G_FILE_CONFIG);
mfileContextMenu->appendGroup(Constants::G_PROJECT_TREE);
// "open with" submenu
- Core::ActionContainer * const openWith =
- Core::ActionManager::createMenu(ProjectExplorer::Constants::M_OPENFILEWITHCONTEXT);
- openWith->setOnAllDisabledBehavior(Core::ActionContainer::Show);
+ ActionContainer * const openWith =
+ ActionManager::createMenu(ProjectExplorer::Constants::M_OPENFILEWITHCONTEXT);
+ openWith->setOnAllDisabledBehavior(ActionContainer::Show);
d->m_openWithMenu = openWith->menu();
d->m_openWithMenu->setTitle(tr("Open With"));
connect(d->m_openWithMenu, SIGNAL(triggered(QAction*)),
- Core::DocumentManager::instance(), SLOT(slotExecuteOpenWithMenuAction(QAction*)));
+ DocumentManager::instance(), SLOT(slotExecuteOpenWithMenuAction(QAction*)));
//
// Separators
//
- Core::Command *cmd;
+ Command *cmd;
msessionContextMenu->addSeparator(projecTreeContext, Constants::G_SESSION_REBUILD);
@@ -560,13 +566,13 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
// new action
d->m_newAction = new QAction(tr("New Project..."), this);
- cmd = Core::ActionManager::registerAction(d->m_newAction, Constants::NEWPROJECT, globalcontext);
+ cmd = ActionManager::registerAction(d->m_newAction, Constants::NEWPROJECT, globalcontext);
cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+Shift+N")));
msessionContextMenu->addAction(cmd, Constants::G_SESSION_FILES);
// open action
d->m_loadAction = new QAction(tr("Load Project..."), this);
- cmd = Core::ActionManager::registerAction(d->m_loadAction, Constants::LOAD, globalcontext);
+ cmd = ActionManager::registerAction(d->m_loadAction, Constants::LOAD, globalcontext);
#ifndef Q_OS_MAC
cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+Shift+O")));
#endif
@@ -574,24 +580,26 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
// Default open action
d->m_openFileAction = new QAction(tr("Open File"), this);
- cmd = Core::ActionManager::registerAction(d->m_openFileAction, ProjectExplorer::Constants::OPENFILE,
+ cmd = ActionManager::registerAction(d->m_openFileAction, ProjectExplorer::Constants::OPENFILE,
projecTreeContext);
mfileContextMenu->addAction(cmd, Constants::G_FILE_OPEN);
- d->m_searchOnFileSystem = new QAction(FolderNavigationWidget::msgFindOnFileSystem(), this);
- cmd = Core::ActionManager::registerAction(d->m_searchOnFileSystem, ProjectExplorer::Constants::SEARCHONFILESYSTEM, projecTreeContext);
+ d->m_searchOnFileSystem = new QAction(FileUtils::msgFindInDirectory(), this);
+ cmd = ActionManager::registerAction(d->m_searchOnFileSystem, ProjectExplorer::Constants::SEARCHONFILESYSTEM, projecTreeContext);
+
+ mfileContextMenu->addAction(cmd, Constants::G_FILE_OTHER);
mfolderContextMenu->addAction(cmd, Constants::G_FOLDER_CONFIG);
msubProjectContextMenu->addAction(cmd, Constants::G_PROJECT_LAST);
mprojectContextMenu->addAction(cmd, Constants::G_PROJECT_LAST);
- d->m_showInGraphicalShell = new QAction(Core::FileUtils::msgGraphicalShellAction(), this);
- cmd = Core::ActionManager::registerAction(d->m_showInGraphicalShell, ProjectExplorer::Constants::SHOWINGRAPHICALSHELL,
+ d->m_showInGraphicalShell = new QAction(FileUtils::msgGraphicalShellAction(), this);
+ cmd = ActionManager::registerAction(d->m_showInGraphicalShell, ProjectExplorer::Constants::SHOWINGRAPHICALSHELL,
projecTreeContext);
mfileContextMenu->addAction(cmd, Constants::G_FILE_OPEN);
mfolderContextMenu->addAction(cmd, Constants::G_FOLDER_FILES);
- d->m_openTerminalHere = new QAction(Core::FileUtils::msgTerminalAction(), this);
- cmd = Core::ActionManager::registerAction(d->m_openTerminalHere, ProjectExplorer::Constants::OPENTERMIANLHERE,
+ d->m_openTerminalHere = new QAction(FileUtils::msgTerminalAction(), this);
+ cmd = ActionManager::registerAction(d->m_openTerminalHere, ProjectExplorer::Constants::OPENTERMIANLHERE,
projecTreeContext);
mfileContextMenu->addAction(cmd, Constants::G_FILE_OPEN);
mfolderContextMenu->addAction(cmd, Constants::G_FOLDER_FILES);
@@ -600,18 +608,18 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
mfileContextMenu->addMenu(openWith, ProjectExplorer::Constants::G_FILE_OPEN);
// recent projects menu
- Core::ActionContainer *mrecent =
- Core::ActionManager::createMenu(Constants::M_RECENTPROJECTS);
+ ActionContainer *mrecent =
+ ActionManager::createMenu(Constants::M_RECENTPROJECTS);
mrecent->menu()->setTitle(tr("Recent P&rojects"));
- mrecent->setOnAllDisabledBehavior(Core::ActionContainer::Show);
+ mrecent->setOnAllDisabledBehavior(ActionContainer::Show);
mfile->addMenu(mrecent, Core::Constants::G_FILE_OPEN);
connect(mfile->menu(), SIGNAL(aboutToShow()),
this, SLOT(updateRecentProjectMenu()));
// session menu
- Core::ActionContainer *msession = Core::ActionManager::createMenu(Constants::M_SESSION);
+ ActionContainer *msession = ActionManager::createMenu(Constants::M_SESSION);
msession->menu()->setTitle(tr("Sessions"));
- msession->setOnAllDisabledBehavior(Core::ActionContainer::Show);
+ msession->setOnAllDisabledBehavior(ActionContainer::Show);
mfile->addMenu(msession, Core::Constants::G_FILE_OPEN);
d->m_sessionMenu = msession->menu();
connect(mfile->menu(), SIGNAL(aboutToShow()),
@@ -619,7 +627,7 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
// session manager action
d->m_sessionManagerAction = new QAction(tr("Session Manager..."), this);
- cmd = Core::ActionManager::registerAction(d->m_sessionManagerAction, Constants::NEWSESSION, globalcontext);
+ cmd = ActionManager::registerAction(d->m_sessionManagerAction, Constants::NEWSESSION, globalcontext);
mfile->addAction(cmd, Core::Constants::G_FILE_OPEN);
cmd->setDefaultKeySequence(QKeySequence());
@@ -628,14 +636,14 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
// unload action
d->m_unloadAction = new Utils::ParameterAction(tr("Close Project"), tr("Close Project \"%1\""),
Utils::ParameterAction::EnabledWithParameter, this);
- cmd = Core::ActionManager::registerAction(d->m_unloadAction, Constants::UNLOAD, globalcontext);
- cmd->setAttribute(Core::Command::CA_UpdateText);
+ cmd = ActionManager::registerAction(d->m_unloadAction, Constants::UNLOAD, globalcontext);
+ cmd->setAttribute(Command::CA_UpdateText);
cmd->setDescription(d->m_unloadAction->text());
mfile->addAction(cmd, Core::Constants::G_FILE_PROJECT);
// unload session action
d->m_closeAllProjects = new QAction(tr("Close All Projects and Editors"), this);
- cmd = Core::ActionManager::registerAction(d->m_closeAllProjects, Constants::CLEARSESSION, globalcontext);
+ cmd = ActionManager::registerAction(d->m_closeAllProjects, Constants::CLEARSESSION, globalcontext);
mfile->addAction(cmd, Core::Constants::G_FILE_PROJECT);
msessionContextMenu->addAction(cmd, Constants::G_SESSION_FILES);
@@ -643,14 +651,14 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
QIcon buildIcon = QIcon(QLatin1String(Constants::ICON_BUILD));
buildIcon.addFile(QLatin1String(Constants::ICON_BUILD_SMALL));
d->m_buildSessionAction = new QAction(buildIcon, tr("Build All"), this);
- cmd = Core::ActionManager::registerAction(d->m_buildSessionAction, Constants::BUILDSESSION, globalcontext);
+ cmd = ActionManager::registerAction(d->m_buildSessionAction, Constants::BUILDSESSION, globalcontext);
cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+Shift+B")));
mbuild->addAction(cmd, Constants::G_BUILD_BUILD);
msessionContextMenu->addAction(cmd, Constants::G_SESSION_BUILD);
// deploy session
d->m_deploySessionAction = new QAction(tr("Deploy All"), this);
- cmd = Core::ActionManager::registerAction(d->m_deploySessionAction, Constants::DEPLOYSESSION, globalcontext);
+ cmd = ActionManager::registerAction(d->m_deploySessionAction, Constants::DEPLOYSESSION, globalcontext);
mbuild->addAction(cmd, Constants::G_BUILD_DEPLOY);
msessionContextMenu->addAction(cmd, Constants::G_SESSION_BUILD);
@@ -658,7 +666,7 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
QIcon rebuildIcon = QIcon(QLatin1String(Constants::ICON_REBUILD));
rebuildIcon.addFile(QLatin1String(Constants::ICON_REBUILD_SMALL));
d->m_rebuildSessionAction = new QAction(rebuildIcon, tr("Rebuild All"), this);
- cmd = Core::ActionManager::registerAction(d->m_rebuildSessionAction, Constants::REBUILDSESSION, globalcontext);
+ cmd = ActionManager::registerAction(d->m_rebuildSessionAction, Constants::REBUILDSESSION, globalcontext);
mbuild->addAction(cmd, Constants::G_BUILD_REBUILD);
msessionContextMenu->addAction(cmd, Constants::G_SESSION_REBUILD);
@@ -666,7 +674,7 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
QIcon cleanIcon = QIcon(QLatin1String(Constants::ICON_CLEAN));
cleanIcon.addFile(QLatin1String(Constants::ICON_CLEAN_SMALL));
d->m_cleanSessionAction = new QAction(cleanIcon, tr("Clean All"), this);
- cmd = Core::ActionManager::registerAction(d->m_cleanSessionAction, Constants::CLEANSESSION, globalcontext);
+ cmd = ActionManager::registerAction(d->m_cleanSessionAction, Constants::CLEANSESSION, globalcontext);
mbuild->addAction(cmd, Constants::G_BUILD_CLEAN);
msessionContextMenu->addAction(cmd, Constants::G_SESSION_REBUILD);
@@ -674,36 +682,36 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
d->m_buildAction = new Utils::ParameterAction(tr("Build Project"), tr("Build Project \"%1\""),
Utils::ParameterAction::AlwaysEnabled, this);
d->m_buildAction->setIcon(buildIcon);
- cmd = Core::ActionManager::registerAction(d->m_buildAction, Constants::BUILD, globalcontext);
- cmd->setAttribute(Core::Command::CA_UpdateText);
+ cmd = ActionManager::registerAction(d->m_buildAction, Constants::BUILD, globalcontext);
+ cmd->setAttribute(Command::CA_UpdateText);
cmd->setDescription(d->m_buildAction->text());
cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+B")));
mbuild->addAction(cmd, Constants::G_BUILD_BUILD);
// Add to mode bar
- Core::ModeManager::addAction(cmd->action(), Constants::P_ACTION_BUILDPROJECT);
+ ModeManager::addAction(cmd->action(), Constants::P_ACTION_BUILDPROJECT);
// deploy action
d->m_deployAction = new Utils::ParameterAction(tr("Deploy Project"), tr("Deploy Project \"%1\""),
Utils::ParameterAction::AlwaysEnabled, this);
- cmd = Core::ActionManager::registerAction(d->m_deployAction, Constants::DEPLOY, globalcontext);
- cmd->setAttribute(Core::Command::CA_UpdateText);
+ cmd = ActionManager::registerAction(d->m_deployAction, Constants::DEPLOY, globalcontext);
+ cmd->setAttribute(Command::CA_UpdateText);
cmd->setDescription(d->m_deployAction->text());
mbuild->addAction(cmd, Constants::G_BUILD_DEPLOY);
// rebuild action
d->m_rebuildAction = new Utils::ParameterAction(tr("Rebuild Project"), tr("Rebuild Project \"%1\""),
Utils::ParameterAction::AlwaysEnabled, this);
- cmd = Core::ActionManager::registerAction(d->m_rebuildAction, Constants::REBUILD, globalcontext);
- cmd->setAttribute(Core::Command::CA_UpdateText);
+ cmd = ActionManager::registerAction(d->m_rebuildAction, Constants::REBUILD, globalcontext);
+ cmd->setAttribute(Command::CA_UpdateText);
cmd->setDescription(d->m_rebuildAction->text());
mbuild->addAction(cmd, Constants::G_BUILD_REBUILD);
// clean action
d->m_cleanAction = new Utils::ParameterAction(tr("Clean Project"), tr("Clean Project \"%1\""),
Utils::ParameterAction::AlwaysEnabled, this);
- cmd = Core::ActionManager::registerAction(d->m_cleanAction, Constants::CLEAN, globalcontext);
- cmd->setAttribute(Core::Command::CA_UpdateText);
+ cmd = ActionManager::registerAction(d->m_cleanAction, Constants::CLEAN, globalcontext);
+ cmd->setAttribute(Command::CA_UpdateText);
cmd->setDescription(d->m_cleanAction->text());
mbuild->addAction(cmd, Constants::G_BUILD_CLEAN);
@@ -711,79 +719,79 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
QIcon stopIcon = QIcon(QLatin1String(Constants::ICON_STOP));
stopIcon.addFile(QLatin1String(Constants::ICON_STOP_SMALL));
d->m_cancelBuildAction = new QAction(stopIcon, tr("Cancel Build"), this);
- cmd = Core::ActionManager::registerAction(d->m_cancelBuildAction, Constants::CANCELBUILD, globalcontext);
+ cmd = ActionManager::registerAction(d->m_cancelBuildAction, Constants::CANCELBUILD, globalcontext);
mbuild->addAction(cmd, Constants::G_BUILD_CANCEL);
// run action
d->m_runAction = new QAction(runIcon, tr("Run"), this);
- cmd = Core::ActionManager::registerAction(d->m_runAction, Constants::RUN, globalcontext);
- cmd->setAttribute(Core::Command::CA_UpdateText);
+ cmd = ActionManager::registerAction(d->m_runAction, Constants::RUN, globalcontext);
+ cmd->setAttribute(Command::CA_UpdateText);
cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+R")));
mbuild->addAction(cmd, Constants::G_BUILD_RUN);
- Core::ModeManager::addAction(cmd->action(), Constants::P_ACTION_RUN);
+ ModeManager::addAction(cmd->action(), Constants::P_ACTION_RUN);
// Run without deployment action
d->m_runWithoutDeployAction = new QAction(tr("Run Without Deployment"), this);
- cmd = Core::ActionManager::registerAction(d->m_runWithoutDeployAction, Constants::RUNWITHOUTDEPLOY, globalcontext);
+ cmd = ActionManager::registerAction(d->m_runWithoutDeployAction, Constants::RUNWITHOUTDEPLOY, globalcontext);
mbuild->addAction(cmd, Constants::G_BUILD_RUN);
// Publish action
d->m_publishAction = new Utils::ParameterAction(tr("Publish Project..."), tr("Publish Project \"%1\"..."),
Utils::ParameterAction::AlwaysEnabled, this);
- cmd = Core::ActionManager::registerAction(d->m_publishAction, Constants::PUBLISH, globalcontext);
- cmd->setAttribute(Core::Command::CA_UpdateText);
+ cmd = ActionManager::registerAction(d->m_publishAction, Constants::PUBLISH, globalcontext);
+ cmd->setAttribute(Command::CA_UpdateText);
cmd->setDescription(d->m_publishAction->text());
mbuild->addAction(cmd, Constants::G_BUILD_RUN);
// 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);
+ cmd = ActionManager::registerAction(d->m_buildActionContextMenu, Constants::BUILDCM, projecTreeContext);
+ cmd->setAttribute(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);
+ cmd = ActionManager::registerAction(d->m_rebuildActionContextMenu, Constants::REBUILDCM, projecTreeContext);
+ cmd->setAttribute(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);
+ cmd = ActionManager::registerAction(d->m_cleanActionContextMenu, Constants::CLEANCM, projecTreeContext);
+ cmd->setAttribute(Command::CA_UpdateText);
mprojectContextMenu->addAction(cmd, Constants::G_PROJECT_REBUILD);
// build without dependencies action
d->m_buildProjectOnlyAction = new QAction(tr("Build Without Dependencies"), this);
- cmd = Core::ActionManager::registerAction(d->m_buildProjectOnlyAction, Constants::BUILDPROJECTONLY, globalcontext);
+ cmd = ActionManager::registerAction(d->m_buildProjectOnlyAction, Constants::BUILDPROJECTONLY, globalcontext);
// rebuild without dependencies action
d->m_rebuildProjectOnlyAction = new QAction(tr("Rebuild Without Dependencies"), this);
- cmd = Core::ActionManager::registerAction(d->m_rebuildProjectOnlyAction, Constants::REBUILDPROJECTONLY, globalcontext);
+ cmd = ActionManager::registerAction(d->m_rebuildProjectOnlyAction, Constants::REBUILDPROJECTONLY, globalcontext);
// deploy without dependencies action
d->m_deployProjectOnlyAction = new QAction(tr("Deploy Without Dependencies"), this);
- cmd = Core::ActionManager::registerAction(d->m_deployProjectOnlyAction, Constants::DEPLOYPROJECTONLY, globalcontext);
+ cmd = ActionManager::registerAction(d->m_deployProjectOnlyAction, Constants::DEPLOYPROJECTONLY, globalcontext);
// clean without dependencies action
d->m_cleanProjectOnlyAction = new QAction(tr("Clean Without Dependencies"), this);
- cmd = Core::ActionManager::registerAction(d->m_cleanProjectOnlyAction, Constants::CLEANPROJECTONLY, globalcontext);
+ cmd = ActionManager::registerAction(d->m_cleanProjectOnlyAction, Constants::CLEANPROJECTONLY, globalcontext);
// deploy action (context menu)
d->m_deployActionContextMenu = new QAction(tr("Deploy"), this);
- cmd = Core::ActionManager::registerAction(d->m_deployActionContextMenu, Constants::DEPLOYCM, projecTreeContext);
+ cmd = ActionManager::registerAction(d->m_deployActionContextMenu, Constants::DEPLOYCM, projecTreeContext);
mprojectContextMenu->addAction(cmd, Constants::G_PROJECT_RUN);
d->m_runActionContextMenu = new QAction(runIcon, tr("Run"), this);
- cmd = Core::ActionManager::registerAction(d->m_runActionContextMenu, Constants::RUNCONTEXTMENU, projecTreeContext);
+ cmd = ActionManager::registerAction(d->m_runActionContextMenu, Constants::RUNCONTEXTMENU, projecTreeContext);
mprojectContextMenu->addAction(cmd, Constants::G_PROJECT_RUN);
msubProjectContextMenu->addAction(cmd, Constants::G_PROJECT_RUN);
// add new file action
d->m_addNewFileAction = new QAction(tr("Add New..."), this);
- cmd = Core::ActionManager::registerAction(d->m_addNewFileAction, ProjectExplorer::Constants::ADDNEWFILE,
+ cmd = ActionManager::registerAction(d->m_addNewFileAction, ProjectExplorer::Constants::ADDNEWFILE,
projecTreeContext);
mprojectContextMenu->addAction(cmd, Constants::G_PROJECT_FILES);
msubProjectContextMenu->addAction(cmd, Constants::G_PROJECT_FILES);
@@ -791,7 +799,7 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
// add existing file action
d->m_addExistingFilesAction = new QAction(tr("Add Existing Files..."), this);
- cmd = Core::ActionManager::registerAction(d->m_addExistingFilesAction, ProjectExplorer::Constants::ADDEXISTINGFILES,
+ cmd = ActionManager::registerAction(d->m_addExistingFilesAction, ProjectExplorer::Constants::ADDEXISTINGFILES,
projecTreeContext);
mprojectContextMenu->addAction(cmd, Constants::G_PROJECT_FILES);
msubProjectContextMenu->addAction(cmd, Constants::G_PROJECT_FILES);
@@ -799,37 +807,37 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
// new subproject action
d->m_addNewSubprojectAction = new QAction(tr("New Subproject..."), this);
- cmd = Core::ActionManager::registerAction(d->m_addNewSubprojectAction, ProjectExplorer::Constants::ADDNEWSUBPROJECT,
+ cmd = ActionManager::registerAction(d->m_addNewSubprojectAction, ProjectExplorer::Constants::ADDNEWSUBPROJECT,
projecTreeContext);
mprojectContextMenu->addAction(cmd, Constants::G_PROJECT_FILES);
msubProjectContextMenu->addAction(cmd, Constants::G_PROJECT_FILES);
// unload project again, in right position
- mprojectContextMenu->addAction(Core::ActionManager::command(Constants::UNLOAD), Constants::G_PROJECT_LAST);
+ mprojectContextMenu->addAction(ActionManager::command(Constants::UNLOAD), Constants::G_PROJECT_LAST);
// remove file action
d->m_removeFileAction = new QAction(tr("Remove File..."), this);
- cmd = Core::ActionManager::registerAction(d->m_removeFileAction, ProjectExplorer::Constants::REMOVEFILE,
+ cmd = ActionManager::registerAction(d->m_removeFileAction, ProjectExplorer::Constants::REMOVEFILE,
projecTreeContext);
cmd->setDefaultKeySequence(QKeySequence::Delete);
mfileContextMenu->addAction(cmd, Constants::G_FILE_OTHER);
//: Remove project from parent profile (Project explorer view); will not physically delete any files.
d->m_removeProjectAction = new QAction(tr("Remove Project..."), this);
- cmd = Core::ActionManager::registerAction(d->m_removeProjectAction, ProjectExplorer::Constants::REMOVEPROJECT,
+ cmd = ActionManager::registerAction(d->m_removeProjectAction, ProjectExplorer::Constants::REMOVEPROJECT,
projecTreeContext);
msubProjectContextMenu->addAction(cmd, Constants::G_PROJECT_FILES);
// delete file action
d->m_deleteFileAction = new QAction(tr("Delete File..."), this);
- cmd = Core::ActionManager::registerAction(d->m_deleteFileAction, ProjectExplorer::Constants::DELETEFILE,
+ cmd = ActionManager::registerAction(d->m_deleteFileAction, ProjectExplorer::Constants::DELETEFILE,
projecTreeContext);
cmd->setDefaultKeySequence(QKeySequence::Delete);
mfileContextMenu->addAction(cmd, Constants::G_FILE_OTHER);
// renamefile action
d->m_renameFileAction = new QAction(tr("Rename..."), this);
- cmd = Core::ActionManager::registerAction(d->m_renameFileAction, ProjectExplorer::Constants::RENAMEFILE,
+ cmd = ActionManager::registerAction(d->m_renameFileAction, ProjectExplorer::Constants::RENAMEFILE,
projecTreeContext);
mfileContextMenu->addAction(cmd, Constants::G_FILE_OTHER);
// Not yet used by anyone, so hide for now
@@ -841,17 +849,17 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
d->m_setStartupProjectAction = new Utils::ParameterAction(tr("Set as Active Project"),
tr("Set \"%1\" as Active Project"),
Utils::ParameterAction::AlwaysEnabled, this);
- cmd = Core::ActionManager::registerAction(d->m_setStartupProjectAction, ProjectExplorer::Constants::SETSTARTUP,
+ cmd = ActionManager::registerAction(d->m_setStartupProjectAction, ProjectExplorer::Constants::SETSTARTUP,
projecTreeContext);
- cmd->setAttribute(Core::Command::CA_UpdateText);
+ cmd->setAttribute(Command::CA_UpdateText);
cmd->setDescription(d->m_setStartupProjectAction->text());
mprojectContextMenu->addAction(cmd, Constants::G_PROJECT_FIRST);
// Collapse All.
d->m_projectTreeCollapseAllAction = new QAction(tr("Collapse All"), this);
- cmd = Core::ActionManager::registerAction(d->m_projectTreeCollapseAllAction, Constants::PROJECTTREE_COLLAPSE_ALL,
+ cmd = ActionManager::registerAction(d->m_projectTreeCollapseAllAction, Constants::PROJECTTREE_COLLAPSE_ALL,
projecTreeContext);
- const Core::Id treeGroup = Constants::G_PROJECT_TREE;
+ const Id treeGroup = Constants::G_PROJECT_TREE;
mfileContextMenu->addSeparator(globalcontext, treeGroup);
mfileContextMenu->addAction(cmd, treeGroup);
msubProjectContextMenu->addSeparator(globalcontext, treeGroup);
@@ -867,16 +875,16 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
d->m_projectSelectorAction = new QAction(this);
d->m_projectSelectorAction->setCheckable(true);
d->m_projectSelectorAction->setEnabled(false);
- QWidget *mainWindow = Core::ICore::mainWindow();
- d->m_targetSelector = new Internal::MiniProjectTargetSelector(d->m_projectSelectorAction, d->m_session, mainWindow);
+ QWidget *mainWindow = ICore::mainWindow();
+ d->m_targetSelector = new Internal::MiniProjectTargetSelector(d->m_projectSelectorAction, mainWindow);
connect(d->m_projectSelectorAction, SIGNAL(triggered()), d->m_targetSelector, SLOT(show()));
- Core::ModeManager::addProjectSelector(d->m_projectSelectorAction);
+ ModeManager::addProjectSelector(d->m_projectSelectorAction);
d->m_projectSelectorActionMenu = new QAction(this);
d->m_projectSelectorActionMenu->setEnabled(false);
d->m_projectSelectorActionMenu->setText(tr("Open Build and Run Kit Selector..."));
connect(d->m_projectSelectorActionMenu, SIGNAL(triggered()), d->m_targetSelector, SLOT(toggleVisible()));
- cmd = Core::ActionManager::registerAction(d->m_projectSelectorActionMenu, ProjectExplorer::Constants::SELECTTARGET,
+ cmd = ActionManager::registerAction(d->m_projectSelectorActionMenu, ProjectExplorer::Constants::SELECTTARGET,
globalcontext);
mbuild->addAction(cmd, Constants::G_BUILD_RUN);
@@ -884,17 +892,17 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
d->m_projectSelectorActionQuick->setEnabled(false);
d->m_projectSelectorActionQuick->setText(tr("Quick Switch Kit Selector"));
connect(d->m_projectSelectorActionQuick, SIGNAL(triggered()), d->m_targetSelector, SLOT(nextOrShow()));
- cmd = Core::ActionManager::registerAction(d->m_projectSelectorActionQuick, ProjectExplorer::Constants::SELECTTARGETQUICK, globalcontext);
+ cmd = ActionManager::registerAction(d->m_projectSelectorActionQuick, ProjectExplorer::Constants::SELECTTARGETQUICK, globalcontext);
cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+T")));
- connect(Core::ICore::instance(), SIGNAL(saveSettingsRequested()),
+ connect(ICore::instance(), SIGNAL(saveSettingsRequested()),
this, SLOT(savePersistentSettings()));
addAutoReleasedObject(new ProjectTreeWidgetFactory);
addAutoReleasedObject(new FolderNavigationWidgetFactory);
addAutoReleasedObject(new DeployConfigurationFactory);
- QSettings *s = Core::ICore::settings();
+ QSettings *s = ICore::settings();
const QStringList fileNames =
s->value(QLatin1String("ProjectExplorer/RecentProjects/FileNames")).toStringList();
const QStringList displayNames =
@@ -979,32 +987,32 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
connect(this, SIGNAL(updateRunActions()), this, SLOT(slotUpdateRunActions()));
connect(this, SIGNAL(settingsChanged()), this, SLOT(updateRunWithoutDeployMenu()));
- d->m_buildManager = new BuildManager(this, d->m_cancelBuildAction);
- connect(d->m_buildManager, SIGNAL(buildStateChanged(ProjectExplorer::Project*)),
+ QObject *buildManager = new BuildManager(this, d->m_cancelBuildAction);
+ connect(buildManager, SIGNAL(buildStateChanged(ProjectExplorer::Project*)),
this, SLOT(buildStateChanged(ProjectExplorer::Project*)));
- connect(d->m_buildManager, SIGNAL(buildQueueFinished(bool)),
+ connect(buildManager, SIGNAL(buildQueueFinished(bool)),
this, SLOT(buildQueueFinished(bool)));
updateActions();
- connect(Core::ICore::instance(), SIGNAL(coreAboutToOpen()),
+ connect(ICore::instance(), SIGNAL(coreAboutToOpen()),
this, SLOT(determineSessionToRestoreAtStartup()));
- connect(Core::ICore::instance(), SIGNAL(coreOpened()), this, SLOT(restoreSession()));
+ connect(ICore::instance(), SIGNAL(coreOpened()), this, SLOT(restoreSession()));
updateWelcomePage();
- Core::VariableManager::registerFileVariables(Constants::VAR_CURRENTPROJECT_PREFIX, tr("Current project's main file"));
- Core::VariableManager::registerVariable(Constants::VAR_CURRENTPROJECT_BUILDPATH,
+ VariableManager::registerFileVariables(Constants::VAR_CURRENTPROJECT_PREFIX, tr("Current project's main file"));
+ VariableManager::registerVariable(Constants::VAR_CURRENTPROJECT_BUILDPATH,
tr("Full build path of the current project's active build configuration."));
- Core::VariableManager::registerVariable(Constants::VAR_CURRENTPROJECT_NAME, tr("The current project's name."));
- Core::VariableManager::registerVariable(Constants::VAR_CURRENTKIT_NAME, tr("The currently active kit's name."));
- Core::VariableManager::registerVariable(Constants::VAR_CURRENTKIT_FILESYSTEMNAME,
+ VariableManager::registerVariable(Constants::VAR_CURRENTPROJECT_NAME, tr("The current project's name."));
+ VariableManager::registerVariable(Constants::VAR_CURRENTKIT_NAME, tr("The currently active kit's name."));
+ VariableManager::registerVariable(Constants::VAR_CURRENTKIT_FILESYSTEMNAME,
tr("The currently active kit's name in a filesystem friendly version."));
- Core::VariableManager::registerVariable(Constants::VAR_CURRENTKIT_ID, tr("The currently active kit's id."));
- Core::VariableManager::registerVariable(Constants::VAR_CURRENTBUILD_NAME, tr("The currently active build configuration's name."));
- Core::VariableManager::registerVariable(Constants::VAR_CURRENTBUILD_TYPE, tr("The currently active build configuration's type."));
+ VariableManager::registerVariable(Constants::VAR_CURRENTKIT_ID, tr("The currently active kit's id."));
+ VariableManager::registerVariable(Constants::VAR_CURRENTBUILD_NAME, tr("The currently active build configuration's name."));
+ VariableManager::registerVariable(Constants::VAR_CURRENTBUILD_TYPE, tr("The currently active build configuration's type."));
- connect(Core::VariableManager::instance(), SIGNAL(variableUpdateRequested(QByteArray)),
+ connect(VariableManager::instance(), SIGNAL(variableUpdateRequested(QByteArray)),
this, SLOT(updateVariable(QByteArray)));
return true;
@@ -1020,12 +1028,10 @@ void ProjectExplorerPlugin::loadAction()
// for your special convenience, we preselect a pro file if it is
// the current file
- if (Core::IEditor *editor = Core::EditorManager::currentEditor()) {
- if (const Core::IDocument *document= editor->document()) {
- const QString fn = document->fileName();
- const bool isProject = d->m_profileMimeTypes.contains(document->mimeType());
- dir = isProject ? fn : QFileInfo(fn).absolutePath();
- }
+ if (const IDocument *document = EditorManager::currentDocument()) {
+ const QString fn = document->filePath();
+ const bool isProject = d->m_profileMimeTypes.contains(document->mimeType());
+ dir = isProject ? fn : QFileInfo(fn).absolutePath();
}
QString filename = QFileDialog::getOpenFileName(0, tr("Load Project"),
@@ -1037,7 +1043,7 @@ void ProjectExplorerPlugin::loadAction()
openProject(filename, &errorMessage);
if (!errorMessage.isEmpty())
- QMessageBox::critical(Core::ICore::mainWindow(), tr("Failed to open project"), errorMessage);
+ QMessageBox::critical(ICore::mainWindow(), tr("Failed to open project"), errorMessage);
updateActions();
}
@@ -1046,7 +1052,7 @@ void ProjectExplorerPlugin::unloadProject()
if (debug)
qDebug() << "ProjectExplorerPlugin::unloadProject";
- if (buildManager()->isBuilding(d->m_currentProject)) {
+ if (BuildManager::isBuilding(d->m_currentProject)) {
QMessageBox box;
QPushButton *closeAnyway = box.addButton(tr("Cancel Build && Unload"), QMessageBox::AcceptRole);
QPushButton *cancelClose = box.addButton(tr("Do Not Unload"), QMessageBox::RejectRole);
@@ -1057,32 +1063,32 @@ void ProjectExplorerPlugin::unloadProject()
box.exec();
if (box.clickedButton() != closeAnyway)
return;
- buildManager()->cancel();
+ BuildManager::cancel();
}
- Core::IDocument *document = d->m_currentProject->document();
+ IDocument *document = d->m_currentProject->document();
- if (!document || document->fileName().isEmpty()) //nothing to save?
+ if (!document || document->filePath().isEmpty()) //nothing to save?
return;
- QList<Core::IDocument*> documentsToSave;
+ QList<IDocument*> documentsToSave;
documentsToSave << document;
bool success = false;
if (document->isFileReadOnly())
- success = Core::DocumentManager::saveModifiedDocuments(documentsToSave).isEmpty();
+ success = DocumentManager::saveModifiedDocuments(documentsToSave).isEmpty();
else
- success = Core::DocumentManager::saveModifiedDocumentsSilently(documentsToSave).isEmpty();
+ success = DocumentManager::saveModifiedDocumentsSilently(documentsToSave).isEmpty();
if (!success)
return;
- addToRecentProjects(document->fileName(), d->m_currentProject->displayName());
+ addToRecentProjects(document->filePath(), d->m_currentProject->displayName());
unloadProject(d->m_currentProject);
}
void ProjectExplorerPlugin::unloadProject(Project *project)
{
- d->m_session->removeProject(project);
+ SessionManager::removeProject(project);
updateActions();
}
@@ -1091,13 +1097,15 @@ void ProjectExplorerPlugin::closeAllProjects()
if (debug)
qDebug() << "ProjectExplorerPlugin::closeAllProject";
- if (!Core::ICore::editorManager()->closeAllEditors())
+ if (!EditorManager::closeAllEditors())
return; // Action has been cancelled
- d->m_session->closeAllProjects();
+ SessionManager::closeAllProjects();
updateActions();
- Core::ModeManager::activateMode(Core::Id(Core::Constants::MODE_WELCOME));
+#if HAS_WELCOME_PAGE
+ ModeManager::activateMode(Core::Constants::MODE_WELCOME);
+#endif
}
void ProjectExplorerPlugin::extensionsInitialized()
@@ -1108,11 +1116,11 @@ void ProjectExplorerPlugin::extensionsInitialized()
d->m_profileMimeTypes += pf->mimeTypes();
addAutoReleasedObject(pf);
}
- d->m_buildManager->extensionsInitialized();
+ BuildManager::extensionsInitialized();
DeviceManager::instance()->addDevice(IDevice::Ptr(new DesktopDevice));
DeviceManager::instance()->load();
- d->m_toolChainManager->restoreToolChains();
+ ToolChainManager::restoreToolChains();
d->m_kitManager->restoreKits();
}
@@ -1123,7 +1131,7 @@ void ProjectExplorerPlugin::loadCustomWizards()
static bool firstTime = true;
if (firstTime) {
firstTime = false;
- foreach (Core::IWizard *cpw, ProjectExplorer::CustomWizard::createWizards())
+ foreach (IWizard *cpw, ProjectExplorer::CustomWizard::createWizards())
addAutoReleasedObject(cpw);
}
}
@@ -1132,10 +1140,10 @@ void ProjectExplorerPlugin::updateVariable(const QByteArray &variable)
{
if (variable == Constants::VAR_CURRENTPROJECT_BUILDPATH) {
if (currentProject() && currentProject()->activeTarget() && currentProject()->activeTarget()->activeBuildConfiguration()) {
- Core::VariableManager::insert(variable,
- currentProject()->activeTarget()->activeBuildConfiguration()->buildDirectory());
+ VariableManager::insert(variable,
+ currentProject()->activeTarget()->activeBuildConfiguration()->buildDirectory().toUserOutput());
} else {
- Core::VariableManager::remove(variable);
+ VariableManager::remove(variable);
}
} else if (variable == Constants::VAR_CURRENTBUILD_TYPE) {
if (currentProject() && currentProject()->activeTarget() && currentProject()->activeTarget()->activeBuildConfiguration()) {
@@ -1147,9 +1155,9 @@ void ProjectExplorerPlugin::updateVariable(const QByteArray &variable)
typeString = tr("release");
else
typeString = tr("unknown");
- Core::VariableManager::insert(variable, typeString);
+ VariableManager::insert(variable, typeString);
} else {
- Core::VariableManager::remove(variable);
+ VariableManager::remove(variable);
}
} else {
QString projectName;
@@ -1158,8 +1166,8 @@ void ProjectExplorerPlugin::updateVariable(const QByteArray &variable)
QString buildConfigurationName;
if (Project *project = currentProject()) {
projectName = project->displayName();
- if (Core::IDocument *doc = project->document())
- projectFilePath = doc->fileName();
+ if (IDocument *doc = project->document())
+ projectFilePath = doc->filePath();
if (Target *target = project->activeTarget()) {
kit = target->kit();
if (BuildConfiguration *buildConfiguration = target->activeBuildConfiguration()) {
@@ -1170,9 +1178,9 @@ void ProjectExplorerPlugin::updateVariable(const QByteArray &variable)
ProjectMacroExpander expander(projectFilePath, projectName, kit, buildConfigurationName);
QString result;
if (expander.resolveProjectMacro(QString::fromUtf8(variable), &result))
- Core::VariableManager::insert(variable, result);
+ VariableManager::insert(variable, result);
else
- Core::VariableManager::remove(variable);
+ VariableManager::remove(variable);
}
}
@@ -1184,7 +1192,7 @@ void ProjectExplorerPlugin::updateRunWithoutDeployMenu()
ExtensionSystem::IPlugin::ShutdownFlag ProjectExplorerPlugin::aboutToShutdown()
{
d->m_proWindow->aboutToShutdown(); // disconnect from session
- d->m_session->closeAllProjects();
+ SessionManager::closeAllProjects();
d->m_projectsMode = 0;
d->m_shuttingDown = true;
// Attempt to synchronously shutdown all run controls.
@@ -1202,8 +1210,8 @@ void ProjectExplorerPlugin::newProject()
if (debug)
qDebug() << "ProjectExplorerPlugin::newProject";
- Core::ICore::showNewItemDialog(tr("New Project", "Title of dialog"),
- Core::IWizard::wizardsOfKind(Core::IWizard::ProjectWizard));
+ ICore::showNewItemDialog(tr("New Project", "Title of dialog"),
+ IWizard::wizardsOfKind(IWizard::ProjectWizard));
updateActions();
}
@@ -1212,21 +1220,23 @@ void ProjectExplorerPlugin::showSessionManager()
if (debug)
qDebug() << "ProjectExplorerPlugin::showSessionManager";
- if (d->m_session->isDefaultVirgin()) {
+ if (SessionManager::isDefaultVirgin()) {
// do not save new virgin default sessions
} else {
- d->m_session->save();
+ SessionManager::save();
}
- SessionDialog sessionDialog(d->m_session, Core::ICore::mainWindow());
+ SessionDialog sessionDialog(ICore::mainWindow());
sessionDialog.setAutoLoadSession(d->m_projectExplorerSettings.autorestoreLastSession);
sessionDialog.exec();
d->m_projectExplorerSettings.autorestoreLastSession = sessionDialog.autoLoadSession();
updateActions();
- Core::IMode *welcomeMode = Core::ModeManager::mode(Core::Constants::MODE_WELCOME);
- if (Core::ModeManager::currentMode() == welcomeMode)
+#if HAS_WELCOME_PAGE
+ IMode *welcomeMode = ModeManager::mode(Core::Constants::MODE_WELCOME);
+ if (ModeManager::currentMode() == welcomeMode)
updateWelcomePage();
+#endif
}
void ProjectExplorerPlugin::setStartupProject(Project *project)
@@ -1236,13 +1246,13 @@ void ProjectExplorerPlugin::setStartupProject(Project *project)
if (!project)
return;
- d->m_session->setStartupProject(project);
+ SessionManager::setStartupProject(project);
updateActions();
}
void ProjectExplorerPlugin::publishProject()
{
- const Project * const project = d->m_session->startupProject();
+ const Project * const project = SessionManager::startupProject();
QTC_ASSERT(project, return);
PublishingWizardSelectionDialog selectionDialog(project);
if (selectionDialog.exec() == QDialog::Accepted) {
@@ -1261,19 +1271,19 @@ void ProjectExplorerPlugin::savePersistentSettings()
if (d->m_shuttingDown)
return;
- if (!d->m_session->loadingSession()) {
- foreach (Project *pro, d->m_session->projects())
+ if (!SessionManager::loadingSession()) {
+ foreach (Project *pro, SessionManager::projects())
pro->saveSettings();
- if (d->m_session->isDefaultVirgin()) {
+ if (SessionManager::isDefaultVirgin()) {
// do not save new virgin default sessions
} else {
- d->m_session->save();
+ SessionManager::save();
}
}
- QSettings *s = Core::ICore::settings();
- s->setValue(QLatin1String("ProjectExplorer/StartupSession"), d->m_session->activeSession());
+ QSettings *s = ICore::settings();
+ s->setValue(QLatin1String("ProjectExplorer/StartupSession"), SessionManager::activeSession());
s->remove(QLatin1String("ProjectExplorer/RecentProjects/Files"));
QStringList fileNames;
@@ -1309,7 +1319,7 @@ void ProjectExplorerPlugin::openProjectWelcomePage(const QString &fileName)
QString errorMessage;
openProject(fileName, &errorMessage);
if (!errorMessage.isEmpty())
- QMessageBox::critical(Core::ICore::mainWindow(), tr("Failed to Open Project"), errorMessage);
+ QMessageBox::critical(ICore::mainWindow(), tr("Failed to Open Project"), errorMessage);
}
Project *ProjectExplorerPlugin::openProject(const QString &fileName, QString *errorString)
@@ -1320,7 +1330,7 @@ Project *ProjectExplorerPlugin::openProject(const QString &fileName, QString *er
QList<Project *> list = openProjects(QStringList() << fileName, errorString);
if (!list.isEmpty()) {
addToRecentProjects(fileName, list.first()->displayName());
- d->m_session->setStartupProject(list.first());
+ SessionManager::setStartupProject(list.first());
return list.first();
}
return 0;
@@ -1355,8 +1365,8 @@ QList<Project *> ProjectExplorerPlugin::openProjects(const QStringList &fileName
QFileInfo fi = QFileInfo(fileName);
QString canonicalFilePath = fi.canonicalFilePath();
bool found = false;
- foreach (ProjectExplorer::Project *pi, session()->projects()) {
- if (canonicalFilePath == pi->document()->fileName()) {
+ foreach (Project *pi, SessionManager::projects()) {
+ if (canonicalFilePath == pi->projectFilePath()) {
found = true;
break;
}
@@ -1364,18 +1374,18 @@ QList<Project *> ProjectExplorerPlugin::openProjects(const QStringList &fileName
if (found) {
appendError(errorString, tr("Failed opening project '%1': Project already open")
.arg(QDir::toNativeSeparators(fileName)));
- d->m_session->reportProjectLoadingProgress();
+ SessionManager::reportProjectLoadingProgress();
continue;
}
- if (const Core::MimeType mt = Core::ICore::mimeDatabase()->findByFile(QFileInfo(fileName))) {
+ if (const MimeType mt = MimeDatabase::findByFile(QFileInfo(fileName))) {
foreach (IProjectManager *manager, projectManagers) {
if (manager->mimeType() == mt.type()) {
QString tmp;
if (Project *pro = manager->openProject(canonicalFilePath, &tmp)) {
if (pro->restoreSettings()) {
connect(pro, SIGNAL(fileListChanged()), this, SIGNAL(fileListChanged()));
- d->m_session->addProject(pro);
+ SessionManager::addProject(pro);
// Make sure we always have a current project / node
if (!d->m_currentProject && !openedPro.isEmpty())
setCurrentNode(pro->rootProjectNode());
@@ -1390,7 +1400,7 @@ QList<Project *> ProjectExplorerPlugin::openProjects(const QStringList &fileName
}
}
}
- d->m_session->reportProjectLoadingProgress();
+ SessionManager::reportProjectLoadingProgress();
}
updateActions();
@@ -1404,10 +1414,10 @@ QList<Project *> ProjectExplorerPlugin::openProjects(const QStringList &fileName
if (!openedPro.isEmpty()) {
if (switchToProjectsMode)
- Core::ModeManager::activateMode(ProjectExplorer::Constants::MODE_SESSION);
+ ModeManager::activateMode(ProjectExplorer::Constants::MODE_SESSION);
else
- Core::ModeManager::activateMode(Core::Constants::MODE_EDIT);
- Core::ModeManager::setFocusToCurrentMode();
+ ModeManager::activateMode(Core::Constants::MODE_EDIT);
+ ModeManager::setFocusToCurrentMode();
}
return openedPro;
@@ -1439,7 +1449,7 @@ void ProjectExplorerPlugin::setCurrentFile(const QString &filePath)
{
if (d->m_ignoreDocumentManagerChangedFile)
return;
- Project *project = d->m_session->projectForFile(filePath);
+ Project *project = SessionManager::projectForFile(filePath);
// If the file is not in any project, stay with the current project
// e.g. on opening a git diff buffer, git log buffer, we don't change the project
// I'm not 100% sure this is correct
@@ -1450,28 +1460,17 @@ void ProjectExplorerPlugin::setCurrentFile(const QString &filePath)
void ProjectExplorerPlugin::setCurrentNode(Node *node)
{
- setCurrent(d->m_session->projectForNode(node), QString(), node);
-}
-
-SessionManager *ProjectExplorerPlugin::session() const
-{
- return d->m_session;
-}
-
-Project *ProjectExplorerPlugin::startupProject() const
-{
- if (debug)
- qDebug() << "ProjectExplorerPlugin::startupProject";
-
- return d->m_session->startupProject();
+ setCurrent(SessionManager::projectForNode(node), QString(), node);
}
void ProjectExplorerPlugin::updateWelcomePage()
{
+#if HAS_WELCOME_PAGE
d->m_welcomePage->reloadWelcomeScreenData();
+#endif
}
-void ProjectExplorerPlugin::currentModeChanged(Core::IMode *mode, Core::IMode *oldMode)
+void ProjectExplorerPlugin::currentModeChanged(IMode *mode, IMode *oldMode)
{
Q_UNUSED(oldMode);
if (mode && mode->id() == Core::Constants::MODE_WELCOME)
@@ -1482,10 +1481,10 @@ void ProjectExplorerPlugin::determineSessionToRestoreAtStartup()
{
// Process command line arguments first:
if (pluginSpec()->arguments().contains(QLatin1String("-lastsession")))
- d->m_sessionToRestoreAtStartup = d->m_session->lastSession();
+ d->m_sessionToRestoreAtStartup = SessionManager::lastSession();
QStringList arguments = ExtensionSystem::PluginManager::arguments();
if (d->m_sessionToRestoreAtStartup.isNull()) {
- QStringList sessions = d->m_session->sessions();
+ QStringList sessions = SessionManager::sessions();
// We have command line arguments, try to find a session in them
// Default to no session loading
foreach (const QString &arg, arguments) {
@@ -1499,20 +1498,19 @@ void ProjectExplorerPlugin::determineSessionToRestoreAtStartup()
// Handle settings only after command line arguments:
if (d->m_sessionToRestoreAtStartup.isNull()
&& d->m_projectExplorerSettings.autorestoreLastSession)
- d->m_sessionToRestoreAtStartup = d->m_session->lastSession();
+ d->m_sessionToRestoreAtStartup = SessionManager::lastSession();
if (!d->m_sessionToRestoreAtStartup.isNull())
- Core::ModeManager::activateMode(Core::Constants::MODE_EDIT);
+ 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 (const MimeType mimeType = MimeDatabase::findByType(ipm->mimeType())) {
+ const QList<MimeGlobPattern> patterns = mimeType.globPatterns();
if (!patterns.isEmpty())
result.push_back(patterns.front().pattern());
}
@@ -1545,7 +1543,7 @@ void ProjectExplorerPlugin::restoreSession()
// In addition, convert "filename" "+45" or "filename" ":23" into
// "filename+45" and "filename:23".
if (!arguments.isEmpty()) {
- const QStringList sessions = d->m_session->sessions();
+ const QStringList sessions = SessionManager::sessions();
QStringList projectGlobs = projectFileGlobs();
for (int a = 0; a < arguments.size(); ) {
const QString &arg = arguments.at(a);
@@ -1584,15 +1582,16 @@ void ProjectExplorerPlugin::restoreSession()
} // !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);
+ SessionManager::loadSession(d->m_sessionToRestoreAtStartup);
// update welcome page
- connect(Core::ModeManager::instance(),
+ connect(ModeManager::instance(),
SIGNAL(currentModeChanged(Core::IMode*,Core::IMode*)),
SLOT(currentModeChanged(Core::IMode*,Core::IMode*)));
+#if HAS_WELCOME_PAGE
connect(d->m_welcomePage, SIGNAL(requestSession(QString)), this, SLOT(loadSession(QString)));
connect(d->m_welcomePage, SIGNAL(requestProject(QString)), this, SLOT(openProjectWelcomePage(QString)));
-
+#endif
d->m_arguments = arguments;
QTimer::singleShot(0, this, SLOT(restoreSession2()));
updateActions();
@@ -1601,14 +1600,14 @@ void ProjectExplorerPlugin::restoreSession()
void ProjectExplorerPlugin::restoreSession2()
{
QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
- Core::ICore::openFiles(d->m_arguments, Core::ICore::OpenFilesFlags(Core::ICore::CanContainLineNumbers | Core::ICore::SwitchMode));
+ ICore::openFiles(d->m_arguments, ICore::OpenFilesFlags(ICore::CanContainLineNumbers | ICore::SwitchMode));
}
void ProjectExplorerPlugin::loadSession(const QString &session)
{
if (debug)
qDebug() << "ProjectExplorerPlugin::loadSession" << session;
- d->m_session->loadSession(session);
+ SessionManager::loadSession(session);
}
@@ -1617,16 +1616,16 @@ void ProjectExplorerPlugin::showContextMenu(QWidget *view, const QPoint &globalP
QMenu *contextMenu = 0;
if (!node)
- node = d->m_session->sessionNode();
+ node = SessionManager::sessionNode();
if (node->nodeType() != SessionNodeType) {
- Project *project = d->m_session->projectForNode(node);
+ Project *project = SessionManager::projectForNode(node);
setCurrentNode(node);
emit aboutToShowContextMenu(project, node);
switch (node->nodeType()) {
case ProjectNodeType:
- if (node->parentFolderNode() == d->m_session->sessionNode())
+ if (node->parentFolderNode() == SessionManager::sessionNode())
contextMenu = d->m_projectMenu;
else
contextMenu = d->m_subProjectMenu;
@@ -1654,21 +1653,11 @@ void ProjectExplorerPlugin::showContextMenu(QWidget *view, const QPoint &globalP
contextMenu->popup(globalPos);
}
-BuildManager *ProjectExplorerPlugin::buildManager() const
-{
- return d->m_buildManager;
-}
-
-TaskHub *ProjectExplorerPlugin::taskHub() const
-{
- return d->m_taskHub;
-}
-
void ProjectExplorerPlugin::buildStateChanged(Project * pro)
{
if (debug) {
qDebug() << "buildStateChanged";
- qDebug() << pro->document()->fileName() << "isBuilding()" << d->m_buildManager->isBuilding(pro);
+ qDebug() << pro->projectFilePath() << "isBuilding()" << BuildManager::isBuilding(pro);
}
Q_UNUSED(pro)
updateActions();
@@ -1697,12 +1686,12 @@ void ProjectExplorerPlugin::showRunErrorMessage(const QString &errorMessage)
{
if (errorMessage.isNull()) {
// a error occured, but message was not set
- QMessageBox::critical(Core::ICore::mainWindow(), tr("Unknown error"), errorMessage);
+ QMessageBox::critical(ICore::mainWindow(), tr("Unknown error"), errorMessage);
} else if (errorMessage.isEmpty()) {
// a error, but the message was set to empty
// hack for qml observer warning, show nothing at all
} else {
- QMessageBox::critical(Core::ICore::mainWindow(), tr("Could Not Run"), errorMessage);
+ QMessageBox::critical(ICore::mainWindow(), tr("Could Not Run"), errorMessage);
}
}
@@ -1733,8 +1722,8 @@ void ProjectExplorerPlugin::buildQueueFinished(bool success)
updateActions();
bool ignoreErrors = true;
- if (d->m_delayedRunConfiguration && success && d->m_buildManager->getErrorTaskCount() > 0) {
- ignoreErrors = QMessageBox::question(Core::ICore::mainWindow(),
+ if (d->m_delayedRunConfiguration && success && BuildManager::getErrorTaskCount() > 0) {
+ ignoreErrors = QMessageBox::question(ICore::mainWindow(),
tr("Ignore all errors?"),
tr("Found some build errors in current task.\n"
"Do you want to ignore them?"),
@@ -1745,8 +1734,8 @@ void ProjectExplorerPlugin::buildQueueFinished(bool success)
if (success && ignoreErrors && d->m_delayedRunConfiguration) {
executeRunConfiguration(d->m_delayedRunConfiguration, d->m_runMode);
} else {
- if (d->m_buildManager->tasksAvailable())
- d->m_buildManager->showTaskWindow();
+ if (BuildManager::tasksAvailable())
+ BuildManager::showTaskWindow();
}
d->m_delayedRunConfiguration = 0;
d->m_runMode = NoRunMode;
@@ -1754,53 +1743,48 @@ void ProjectExplorerPlugin::buildQueueFinished(bool success)
void ProjectExplorerPlugin::updateExternalFileWarning()
{
- Core::IEditor *editor = qobject_cast<Core::IEditor *>(sender());
- if (!editor || editor->isTemporary())
+ IDocument *document = qobject_cast<IDocument *>(sender());
+ if (!document || document->filePath().isEmpty())
return;
- Core::IDocument *document = editor->document();
- if (!document)
- return;
- Core::InfoBar *infoBar = document->infoBar();
- Core::Id externalFileId(EXTERNAL_FILE_WARNING);
+ InfoBar *infoBar = document->infoBar();
+ Id externalFileId(EXTERNAL_FILE_WARNING);
if (!document->isModified()) {
infoBar->removeInfo(externalFileId);
return;
}
if (!d->m_currentProject || !infoBar->canInfoBeAdded(externalFileId))
return;
- Utils::FileName fileName = Utils::FileName::fromString(document->fileName());
- if (fileName.isEmpty())
- return;
+ Utils::FileName fileName = Utils::FileName::fromString(document->filePath());
Utils::FileName projectDir = Utils::FileName::fromString(d->m_currentProject->projectDirectory());
if (projectDir.isEmpty() || fileName.isChildOf(projectDir))
return;
// External file. Test if it under the same VCS
QString topLevel;
- if (Core::ICore::vcsManager()->findVersionControlForDirectory(projectDir.toString(), &topLevel)
+ if (VcsManager::findVersionControlForDirectory(projectDir.toString(), &topLevel)
&& fileName.isChildOf(Utils::FileName::fromString(topLevel))) {
return;
}
- infoBar->addInfo(Core::InfoBarEntry(externalFileId,
+ infoBar->addInfo(InfoBarEntry(externalFileId,
tr("<b>Warning:</b> This file is outside the project directory."),
- Core::InfoBarEntry::GlobalSuppressionEnabled));
+ InfoBarEntry::GlobalSuppressionEnabled));
}
void ProjectExplorerPlugin::updateContext()
{
- Core::Context oldContext;
+ Context oldContext;
oldContext.add(d->m_lastProjectContext);
- Core::Context newContext;
+ Context newContext;
if (d->m_currentProject) {
newContext.add(d->m_currentProject->projectContext());
newContext.add(d->m_currentProject->projectLanguages());
d->m_lastProjectContext = newContext;
} else {
- d->m_lastProjectContext = Core::Context();
+ d->m_lastProjectContext = Context();
}
- Core::ICore::updateAdditionalContexts(oldContext, newContext);
+ ICore::updateAdditionalContexts(oldContext, newContext);
}
void ProjectExplorerPlugin::setCurrent(Project *project, QString filePath, Node *node)
@@ -1812,7 +1796,7 @@ void ProjectExplorerPlugin::setCurrent(Project *project, QString filePath, Node
if (node)
filePath = node->path();
else
- node = d->m_session->nodeForFile(filePath, project);
+ node = SessionManager::nodeForFile(filePath, project);
bool projectChanged = false;
if (d->m_currentProject != project) {
@@ -1832,8 +1816,8 @@ void ProjectExplorerPlugin::setCurrent(Project *project, QString filePath, Node
}
d->m_currentProject = project;
- if (!node && Core::EditorManager::currentEditor()) {
- connect(Core::EditorManager::currentEditor(), SIGNAL(changed()),
+ if (!node && EditorManager::currentDocument()) {
+ connect(EditorManager::currentDocument(), SIGNAL(changed()),
this, SLOT(updateExternalFileWarning()), Qt::UniqueConnection);
}
if (projectChanged || d->m_currentNode != node) {
@@ -1851,7 +1835,7 @@ void ProjectExplorerPlugin::setCurrent(Project *project, QString filePath, Node
}
d->m_ignoreDocumentManagerChangedFile = true;
- Core::DocumentManager::setCurrentFile(filePath);
+ DocumentManager::setCurrentFile(filePath);
updateContext();
d->m_ignoreDocumentManagerChangedFile = false;
}
@@ -1861,11 +1845,12 @@ void ProjectExplorerPlugin::updateActions()
if (debug)
qDebug() << "ProjectExplorerPlugin::updateActions";
- QPair<bool, QString> buildActionState = buildSettingsEnabled(startupProject());
+ Project *project = SessionManager::startupProject();
+
+ QPair<bool, QString> buildActionState = buildSettingsEnabled(project);
QPair<bool, QString> buildActionContextState = buildSettingsEnabled(d->m_currentProject);
QPair<bool, QString> buildSessionState = buildSettingsEnabledForSession();
- Project *project = startupProject();
QString projectName = project ? project->displayName() : QString();
QString projectNameContextMenu = d->m_currentProject ? d->m_currentProject->displayName() : QString();
@@ -1888,7 +1873,7 @@ void ProjectExplorerPlugin::updateActions()
// Context menu actions
d->m_setStartupProjectAction->setParameter(projectNameContextMenu);
- bool hasDependencies = session()->projectOrder(d->m_currentProject).size() > 1;
+ bool hasDependencies = SessionManager::projectOrder(d->m_currentProject).size() > 1;
if (hasDependencies) {
d->m_buildActionContextMenu->setText(tr("Build Without Dependencies"));
d->m_rebuildActionContextMenu->setText(tr("Rebuild Without Dependencies"));
@@ -1917,7 +1902,7 @@ void ProjectExplorerPlugin::updateActions()
d->m_cleanProjectOnlyAction->setToolTip(buildActionState.second);
// Session actions
- d->m_closeAllProjects->setEnabled(!d->m_session->projects().isEmpty());
+ d->m_closeAllProjects->setEnabled(SessionManager::hasProjects());
d->m_buildSessionAction->setEnabled(buildSessionState.first);
d->m_rebuildSessionAction->setEnabled(buildSessionState.first);
@@ -1927,7 +1912,7 @@ void ProjectExplorerPlugin::updateActions()
d->m_rebuildSessionAction->setToolTip(buildSessionState.second);
d->m_cleanSessionAction->setToolTip(buildSessionState.second);
- d->m_cancelBuildAction->setEnabled(d->m_buildManager->isBuilding());
+ d->m_cancelBuildAction->setEnabled(BuildManager::isBuilding());
bool canPublish = false;
if (project) {
@@ -1942,9 +1927,10 @@ void ProjectExplorerPlugin::updateActions()
}
d->m_publishAction->setEnabled(canPublish);
- d->m_projectSelectorAction->setEnabled(!session()->projects().isEmpty());
- d->m_projectSelectorActionMenu->setEnabled(!session()->projects().isEmpty());
- d->m_projectSelectorActionQuick->setEnabled(!session()->projects().isEmpty());
+ const bool hasProjects = SessionManager::hasProjects();
+ d->m_projectSelectorAction->setEnabled(hasProjects);
+ d->m_projectSelectorActionMenu->setEnabled(hasProjects);
+ d->m_projectSelectorActionQuick->setEnabled(hasProjects);
updateDeployActions();
updateRunWithoutDeployMenu();
@@ -1955,10 +1941,10 @@ void ProjectExplorerPlugin::updateActions()
QStringList ProjectExplorerPlugin::allFilesWithDependencies(Project *pro)
{
if (debug)
- qDebug() << "ProjectExplorerPlugin::allFilesWithDependencies(" << pro->document()->fileName() << ")";
+ qDebug() << "ProjectExplorerPlugin::allFilesWithDependencies(" << pro->projectFilePath() << ")";
QStringList filesToSave;
- foreach (Project *p, d->m_session->projectOrder(pro)) {
+ foreach (Project *p, SessionManager::projectOrder(pro)) {
FindAllFilesVisitor filesVisitor;
p->rootProjectNode()->accept(&filesVisitor);
filesToSave << filesVisitor.filePaths();
@@ -1972,17 +1958,17 @@ bool ProjectExplorerPlugin::saveModifiedFiles()
if (debug)
qDebug() << "ProjectExplorerPlugin::saveModifiedFiles";
- QList<Core::IDocument *> documentsToSave = Core::DocumentManager::modifiedDocuments();
+ QList<IDocument *> documentsToSave = DocumentManager::modifiedDocuments();
if (!documentsToSave.isEmpty()) {
if (d->m_projectExplorerSettings.saveBeforeBuild) {
bool cancelled = false;
- Core::DocumentManager::saveModifiedDocumentsSilently(documentsToSave, &cancelled);
+ DocumentManager::saveModifiedDocumentsSilently(documentsToSave, &cancelled);
if (cancelled)
return false;
} else {
bool cancelled = false;
bool alwaysSave = false;
- Core::DocumentManager::saveModifiedDocuments(documentsToSave, &cancelled, QString(),
+ DocumentManager::saveModifiedDocuments(documentsToSave, &cancelled, QString(),
tr("Always save files before build"), &alwaysSave);
if (cancelled)
@@ -1999,14 +1985,14 @@ bool ProjectExplorerPlugin::saveModifiedFiles()
void ProjectExplorerPlugin::deploy(QList<Project *> projects)
{
- QList<Core::Id> steps;
+ QList<Id> steps;
if (d->m_projectExplorerSettings.buildBeforeDeploy)
- steps << Core::Id(Constants::BUILDSTEPS_BUILD);
- steps << Core::Id(Constants::BUILDSTEPS_DEPLOY);
+ steps << Id(Constants::BUILDSTEPS_BUILD);
+ steps << Id(Constants::BUILDSTEPS_DEPLOY);
queue(projects, steps);
}
-QString ProjectExplorerPlugin::displayNameForStepId(Core::Id stepId)
+QString ProjectExplorerPlugin::displayNameForStepId(Id stepId)
{
if (stepId == Constants::BUILDSTEPS_CLEAN)
return tr("Clean");
@@ -2017,13 +2003,13 @@ QString ProjectExplorerPlugin::displayNameForStepId(Core::Id stepId)
return tr("Build", "Build step");
}
-int ProjectExplorerPlugin::queue(QList<Project *> projects, QList<Core::Id> stepIds)
+int ProjectExplorerPlugin::queue(QList<Project *> projects, QList<Id> stepIds)
{
if (debug) {
QStringList projectNames, stepNames;
foreach (const Project *p, projects)
projectNames << p->displayName();
- foreach (const Core::Id id, stepIds)
+ foreach (const Id id, stepIds)
stepNames << id.toString();
qDebug() << "Building" << stepNames << "for projects" << projectNames;
}
@@ -2039,7 +2025,7 @@ int ProjectExplorerPlugin::queue(QList<Project *> projects, QList<Core::Id> step
if (pro && pro->needsConfiguration())
preambleMessage.append(tr("The project %1 is not configured, skipping it.\n")
.arg(pro->displayName()));
- foreach (Core::Id id, stepIds) {
+ foreach (Id id, stepIds) {
foreach (Project *pro, projects) {
if (!pro || !pro->activeTarget())
continue;
@@ -2060,20 +2046,20 @@ int ProjectExplorerPlugin::queue(QList<Project *> projects, QList<Core::Id> step
if (stepLists.isEmpty())
return 0;
- if (!d->m_buildManager->buildLists(stepLists, names, preambleMessage))
+ if (!BuildManager::buildLists(stepLists, names, preambleMessage))
return -1;
return stepLists.count();
}
void ProjectExplorerPlugin::buildProjectOnly()
{
- queue(QList<Project *>() << session()->startupProject(), QList<Core::Id>() << Core::Id(Constants::BUILDSTEPS_BUILD));
+ queue(QList<Project *>() << SessionManager::startupProject(), QList<Id>() << Id(Constants::BUILDSTEPS_BUILD));
}
-void ProjectExplorerPlugin::buildProject(ProjectExplorer::Project *p)
+void ProjectExplorerPlugin::buildProject(Project *p)
{
- queue(d->m_session->projectOrder(p),
- QList<Core::Id>() << Core::Id(Constants::BUILDSTEPS_BUILD));
+ queue(SessionManager::projectOrder(p),
+ QList<Id>() << Id(Constants::BUILDSTEPS_BUILD));
}
void ProjectExplorerPlugin::requestProjectModeUpdate(Project *p)
@@ -2083,54 +2069,54 @@ void ProjectExplorerPlugin::requestProjectModeUpdate(Project *p)
void ProjectExplorerPlugin::buildProject()
{
- queue(d->m_session->projectOrder(session()->startupProject()),
- QList<Core::Id>() << Core::Id(Constants::BUILDSTEPS_BUILD));
+ queue(SessionManager::projectOrder(SessionManager::startupProject()),
+ QList<Id>() << Id(Constants::BUILDSTEPS_BUILD));
}
void ProjectExplorerPlugin::buildProjectContextMenu()
{
queue(QList<Project *>() << d->m_currentProject,
- QList<Core::Id>() << Core::Id(Constants::BUILDSTEPS_BUILD));
+ QList<Id>() << Id(Constants::BUILDSTEPS_BUILD));
}
void ProjectExplorerPlugin::buildSession()
{
- queue(d->m_session->projectOrder(),
- QList<Core::Id>() << Core::Id(Constants::BUILDSTEPS_BUILD));
+ queue(SessionManager::projectOrder(),
+ QList<Id>() << Id(Constants::BUILDSTEPS_BUILD));
}
void ProjectExplorerPlugin::rebuildProjectOnly()
{
- queue(QList<Project *>() << session()->startupProject(),
- QList<Core::Id>() << Core::Id(Constants::BUILDSTEPS_CLEAN) << Core::Id(Constants::BUILDSTEPS_BUILD));
+ queue(QList<Project *>() << SessionManager::startupProject(),
+ QList<Id>() << Id(Constants::BUILDSTEPS_CLEAN) << Id(Constants::BUILDSTEPS_BUILD));
}
void ProjectExplorerPlugin::rebuildProject()
{
- queue(d->m_session->projectOrder(session()->startupProject()),
- QList<Core::Id>() << Core::Id(Constants::BUILDSTEPS_CLEAN) << Core::Id(Constants::BUILDSTEPS_BUILD));
+ queue(SessionManager::projectOrder(SessionManager::startupProject()),
+ QList<Id>() << Id(Constants::BUILDSTEPS_CLEAN) << Id(Constants::BUILDSTEPS_BUILD));
}
void ProjectExplorerPlugin::rebuildProjectContextMenu()
{
queue(QList<Project *>() << d->m_currentProject,
- QList<Core::Id>() << Core::Id(Constants::BUILDSTEPS_CLEAN) << Core::Id(Constants::BUILDSTEPS_BUILD));
+ QList<Id>() << Id(Constants::BUILDSTEPS_CLEAN) << Id(Constants::BUILDSTEPS_BUILD));
}
void ProjectExplorerPlugin::rebuildSession()
{
- queue(d->m_session->projectOrder(),
- QList<Core::Id>() << Core::Id(Constants::BUILDSTEPS_CLEAN) << Core::Id(Constants::BUILDSTEPS_BUILD));
+ queue(SessionManager::projectOrder(),
+ QList<Id>() << Id(Constants::BUILDSTEPS_CLEAN) << Id(Constants::BUILDSTEPS_BUILD));
}
void ProjectExplorerPlugin::deployProjectOnly()
{
- deploy(QList<Project *>() << session()->startupProject());
+ deploy(QList<Project *>() << SessionManager::startupProject());
}
void ProjectExplorerPlugin::deployProject()
{
- deploy(d->m_session->projectOrder(session()->startupProject()));
+ deploy(SessionManager::projectOrder(SessionManager::startupProject()));
}
void ProjectExplorerPlugin::deployProjectContextMenu()
@@ -2140,41 +2126,41 @@ void ProjectExplorerPlugin::deployProjectContextMenu()
void ProjectExplorerPlugin::deploySession()
{
- deploy(d->m_session->projectOrder());
+ deploy(SessionManager::projectOrder());
}
void ProjectExplorerPlugin::cleanProjectOnly()
{
- queue(QList<Project *>() << session()->startupProject(),
- QList<Core::Id>() << Core::Id(Constants::BUILDSTEPS_CLEAN));
+ queue(QList<Project *>() << SessionManager::startupProject(),
+ QList<Id>() << Id(Constants::BUILDSTEPS_CLEAN));
}
void ProjectExplorerPlugin::cleanProject()
{
- queue(d->m_session->projectOrder(session()->startupProject()),
- QList<Core::Id>() << Core::Id(Constants::BUILDSTEPS_CLEAN));
+ queue(SessionManager::projectOrder(SessionManager::startupProject()),
+ QList<Id>() << Id(Constants::BUILDSTEPS_CLEAN));
}
void ProjectExplorerPlugin::cleanProjectContextMenu()
{
queue(QList<Project *>() << d->m_currentProject,
- QList<Core::Id>() << Core::Id(Constants::BUILDSTEPS_CLEAN));
+ QList<Id>() << Id(Constants::BUILDSTEPS_CLEAN));
}
void ProjectExplorerPlugin::cleanSession()
{
- queue(d->m_session->projectOrder(),
- QList<Core::Id>() << Core::Id(Constants::BUILDSTEPS_CLEAN));
+ queue(SessionManager::projectOrder(),
+ QList<Id>() << Id(Constants::BUILDSTEPS_CLEAN));
}
void ProjectExplorerPlugin::runProject()
{
- runProject(startupProject(), NormalRunMode);
+ runProject(SessionManager::startupProject(), NormalRunMode);
}
void ProjectExplorerPlugin::runProjectWithoutDeploy()
{
- runProject(startupProject(), NormalRunMode, true);
+ runProject(SessionManager::startupProject(), NormalRunMode, true);
}
void ProjectExplorerPlugin::runProjectContextMenu()
@@ -2195,8 +2181,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, SessionManager::projectOrder(pro))
if (project
&& project->activeTarget()
&& project->activeTarget()->activeBuildConfiguration())
@@ -2211,7 +2196,7 @@ QPair<bool, QString> ProjectExplorerPlugin::buildSettingsEnabled(Project *pro)
if (!pro) {
result.first = false;
result.second = tr("No project loaded.");
- } else if (d->m_buildManager->isBuilding(pro)) {
+ } else if (BuildManager::isBuilding(pro)) {
result.first = false;
result.second = tr("Currently building the active project.");
} else if (pro->needsConfiguration()) {
@@ -2221,7 +2206,7 @@ QPair<bool, QString> ProjectExplorerPlugin::buildSettingsEnabled(Project *pro)
result.first = false;
result.second = tr("Project has no build settings.");
} else {
- const QList<Project *> & projects = d->m_session->projectOrder(pro);
+ const QList<Project *> & projects = SessionManager::projectOrder(pro);
foreach (Project *project, projects) {
if (project
&& project->activeTarget()
@@ -2241,18 +2226,17 @@ QPair<bool, QString> ProjectExplorerPlugin::buildSettingsEnabledForSession()
{
QPair<bool, QString> result;
result.first = true;
- if (d->m_session->projects().isEmpty()) {
+ if (!SessionManager::hasProjects()) {
result.first = false;
result.second = tr("No project loaded");
- } else if (d->m_buildManager->isBuilding()) {
+ } else if (BuildManager::isBuilding()) {
result.first = false;
result.second = tr("A build is in progress");
} else if (!hasBuildSettings(0)) {
result.first = false;
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, SessionManager::projectOrder(0)) {
if (project
&& project->activeTarget()
&& project->activeTarget()->activeBuildConfiguration()
@@ -2269,7 +2253,7 @@ QPair<bool, QString> ProjectExplorerPlugin::buildSettingsEnabledForSession()
bool ProjectExplorerPlugin::coreAboutToClose()
{
- if (d->m_buildManager->isBuilding()) {
+ if (BuildManager::isBuilding()) {
QMessageBox box;
QPushButton *closeAnyway = box.addButton(tr("Cancel Build && Close"), QMessageBox::AcceptRole);
QPushButton *cancelClose = box.addButton(tr("Do Not Close"), QMessageBox::RejectRole);
@@ -2288,8 +2272,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, SessionManager::projectOrder(pro))
if (project->activeTarget()
&& project->activeTarget()->activeDeployConfiguration()
&& !project->activeTarget()->activeDeployConfiguration()->stepList()->isEmpty())
@@ -2307,23 +2290,22 @@ void ProjectExplorerPlugin::runProject(Project *pro, RunMode mode, const bool fo
runRunConfiguration(rc, mode, forceSkipDeploy);
}
-void ProjectExplorerPlugin::runRunConfiguration(ProjectExplorer::RunConfiguration *rc,
+void ProjectExplorerPlugin::runRunConfiguration(RunConfiguration *rc,
RunMode runMode,
const bool forceSkipDeploy)
{
if (!rc->isEnabled())
return;
- QList<Core::Id> stepIds;
+ QList<Id> stepIds;
if (!forceSkipDeploy && d->m_projectExplorerSettings.deployBeforeRun) {
if (d->m_projectExplorerSettings.buildBeforeDeploy)
- stepIds << Core::Id(Constants::BUILDSTEPS_BUILD);
- stepIds << Core::Id(Constants::BUILDSTEPS_DEPLOY);
+ stepIds << Id(Constants::BUILDSTEPS_BUILD);
+ stepIds << Id(Constants::BUILDSTEPS_DEPLOY);
}
Project *pro = rc->target()->project();
- const QList<Project *> &projects = d->m_session->projectOrder(pro);
- int queueCount = queue(projects, stepIds);
+ int queueCount = queue(SessionManager::projectOrder(pro), stepIds);
if (queueCount < 0) // something went wrong
return;
@@ -2355,7 +2337,7 @@ void ProjectExplorerPlugin::projectAdded(ProjectExplorer::Project *pro)
void ProjectExplorerPlugin::projectRemoved(ProjectExplorer::Project * pro)
{
if (d->m_projectsMode)
- d->m_projectsMode->setEnabled(!session()->projects().isEmpty());
+ d->m_projectsMode->setEnabled(SessionManager::hasProjects());
// more specific action en and disabling ?
disconnect(pro, SIGNAL(buildConfigurationEnabledChanged()),
this, SLOT(updateActions()));
@@ -2363,14 +2345,14 @@ void ProjectExplorerPlugin::projectRemoved(ProjectExplorer::Project * pro)
void ProjectExplorerPlugin::projectDisplayNameChanged(Project *pro)
{
- addToRecentProjects(pro->document()->fileName(), pro->displayName());
+ addToRecentProjects(pro->projectFilePath(), pro->displayName());
updateActions();
}
void ProjectExplorerPlugin::startupProjectChanged()
{
static QPointer<Project> previousStartupProject = 0;
- Project *project = startupProject();
+ Project *project = SessionManager::startupProject();
if (project == previousStartupProject)
return;
@@ -2394,8 +2376,9 @@ void ProjectExplorerPlugin::activeTargetChanged()
{
static QPointer<Target> previousTarget = 0;
Target *target = 0;
- if (startupProject())
- target = startupProject()->activeTarget();
+ Project *startupProject = SessionManager::startupProject();
+ if (startupProject)
+ target = startupProject->activeTarget();
if (target == previousTarget)
return;
@@ -2417,8 +2400,9 @@ void ProjectExplorerPlugin::activeRunConfigurationChanged()
{
static QPointer<RunConfiguration> previousRunConfiguration = 0;
RunConfiguration *rc = 0;
- if (startupProject() && startupProject()->activeTarget())
- rc = startupProject()->activeTarget()->activeRunConfiguration();
+ Project *startupProject = SessionManager::startupProject();
+ if (startupProject && startupProject->activeTarget())
+ rc = startupProject->activeTarget()->activeRunConfiguration();
if (rc == previousRunConfiguration)
return;
if (previousRunConfiguration) {
@@ -2445,13 +2429,13 @@ IRunControlFactory *ProjectExplorerPlugin::findRunControlFactory(RunConfiguratio
void ProjectExplorerPlugin::updateDeployActions()
{
- Project *project = startupProject();
+ Project *project = SessionManager::startupProject();
bool enableDeployActions = project
- && ! (d->m_buildManager->isBuilding(project))
+ && !BuildManager::isBuilding(project)
&& hasDeploySettings(project);
bool enableDeployActionsContextMenu = d->m_currentProject
- && ! (d->m_buildManager->isBuilding(d->m_currentProject))
+ && !BuildManager::isBuilding(d->m_currentProject)
&& hasDeploySettings(d->m_currentProject);
if (d->m_projectExplorerSettings.buildBeforeDeploy) {
@@ -2464,8 +2448,7 @@ void ProjectExplorerPlugin::updateDeployActions()
}
const QString projectName = project ? project->displayName() : QString();
- const QString projectNameContextMenu = d->m_currentProject ? d->m_currentProject->displayName() : QString();
- bool hasProjects = !d->m_session->projects().isEmpty();
+ bool hasProjects = SessionManager::hasProjects();
d->m_deployAction->setParameter(projectName);
d->m_deployAction->setEnabled(enableDeployActions);
@@ -2476,8 +2459,7 @@ void ProjectExplorerPlugin::updateDeployActions()
bool enableDeploySessionAction = true;
if (d->m_projectExplorerSettings.buildBeforeDeploy) {
- const QList<Project *> & projects = d->m_session->projectOrder(0);
- foreach (Project *project, projects) {
+ foreach (Project *project, SessionManager::projectOrder(0)) {
if (project
&& project->activeTarget()
&& project->activeTarget()->activeBuildConfiguration()
@@ -2487,9 +2469,7 @@ void ProjectExplorerPlugin::updateDeployActions()
}
}
}
- if (!hasProjects
- || !hasDeploySettings(0)
- || d->m_buildManager->isBuilding())
+ if (!hasProjects || !hasDeploySettings(0) || BuildManager::isBuilding())
enableDeploySessionAction = false;
d->m_deploySessionAction->setEnabled(enableDeploySessionAction);
@@ -2515,8 +2495,7 @@ bool ProjectExplorerPlugin::canRun(Project *project, RunMode runMode)
bool canRun = findRunControlFactory(activeRC, runMode)
&& activeRC->isEnabled();
- const bool building = d->m_buildManager->isBuilding();
- return (canRun && !building);
+ return canRun && !BuildManager::isBuilding();
}
QString ProjectExplorerPlugin::cannotRunReason(Project *project, RunMode runMode)
@@ -2552,15 +2531,14 @@ QString ProjectExplorerPlugin::cannotRunReason(Project *project, RunMode runMode
if (!findRunControlFactory(activeRC, runMode))
return tr("Cannot run '%1'.").arg(activeRC->displayName());
-
- if (d->m_buildManager->isBuilding())
+ if (BuildManager::isBuilding())
return tr("A build is still in progress.");
return QString();
}
void ProjectExplorerPlugin::slotUpdateRunActions()
{
- Project *project = startupProject();
+ Project *project = SessionManager::startupProject();
const bool state = canRun(project, NormalRunMode);
d->m_runAction->setEnabled(state);
d->m_runAction->setToolTip(cannotRunReason(project, NormalRunMode));
@@ -2572,8 +2550,8 @@ void ProjectExplorerPlugin::cancelBuild()
if (debug)
qDebug() << "ProjectExplorerPlugin::cancelBuild";
- if (d->m_buildManager->isBuilding())
- d->m_buildManager->cancel();
+ if (BuildManager::isBuilding())
+ BuildManager::cancel();
}
void ProjectExplorerPlugin::addToRecentProjects(const QString &fileName, const QString &displayName)
@@ -2606,8 +2584,8 @@ void ProjectExplorerPlugin::updateRecentProjectMenu()
if (debug)
qDebug() << "ProjectExplorerPlugin::updateRecentProjectMenu";
- Core::ActionContainer *aci =
- Core::ActionManager::actionContainer(Constants::M_RECENTPROJECTS);
+ ActionContainer *aci =
+ ActionManager::actionContainer(Constants::M_RECENTPROJECTS);
QMenu *menu = aci->menu();
menu->clear();
@@ -2654,7 +2632,7 @@ void ProjectExplorerPlugin::openRecentProject()
QString errorMessage;
openProject(fileName, &errorMessage);
if (!errorMessage.isEmpty())
- QMessageBox::critical(Core::ICore::mainWindow(), tr("Failed to open project"), errorMessage);
+ QMessageBox::critical(ICore::mainWindow(), tr("Failed to open project"), errorMessage);
}
}
@@ -2689,7 +2667,7 @@ void ProjectExplorerPlugin::updateContextMenuActions()
d->m_deleteFileAction->setVisible(true);
d->m_runActionContextMenu->setVisible(false);
- Core::ActionContainer *runMenu = Core::ActionManager::actionContainer(Constants::RUNMENUCONTEXTMENU);
+ ActionContainer *runMenu = ActionManager::actionContainer(Constants::RUNMENUCONTEXTMENU);
runMenu->menu()->clear();
if (d->m_currentNode && d->m_currentNode->projectNode()) {
@@ -2786,14 +2764,14 @@ void ProjectExplorerPlugin::addNewFile()
QVariantMap map;
map.insert(QLatin1String(Constants::PREFERED_PROJECT_NODE), d->m_currentNode->projectNode()->path());
if (d->m_currentProject) {
- QList<Core::Id> profileIds;
+ QList<Id> profileIds;
foreach (Target *target, d->m_currentProject->targets())
profileIds << target->id();
map.insert(QLatin1String(Constants::PROJECT_KIT_IDS), QVariant::fromValue(profileIds));
}
- Core::ICore::showNewItemDialog(tr("New File", "Title of dialog"),
- Core::IWizard::wizardsOfKind(Core::IWizard::FileWizard)
- + Core::IWizard::wizardsOfKind(Core::IWizard::ClassWizard),
+ ICore::showNewItemDialog(tr("New File", "Title of dialog"),
+ IWizard::wizardsOfKind(IWizard::FileWizard)
+ + IWizard::wizardsOfKind(IWizard::ClassWizard),
location, map);
}
@@ -2808,14 +2786,14 @@ void ProjectExplorerPlugin::addNewSubproject()
QVariantMap map;
map.insert(QLatin1String(Constants::PREFERED_PROJECT_NODE), d->m_currentNode->projectNode()->path());
if (d->m_currentProject) {
- QList<Core::Id> profileIds;
+ QList<Id> profileIds;
foreach (Target *target, d->m_currentProject->targets())
profileIds << target->id();
map.insert(QLatin1String(Constants::PROJECT_KIT_IDS), QVariant::fromValue(profileIds));
}
- Core::ICore::showNewItemDialog(tr("New Subproject", "Title of dialog"),
- Core::IWizard::wizardsOfKind(Core::IWizard::ProjectWizard),
+ ICore::showNewItemDialog(tr("New Subproject", "Title of dialog"),
+ IWizard::wizardsOfKind(IWizard::ProjectWizard),
location, map);
}
}
@@ -2824,7 +2802,7 @@ void ProjectExplorerPlugin::addExistingFiles()
{
QTC_ASSERT(d->m_currentNode, return);
- QStringList fileNames = QFileDialog::getOpenFileNames(Core::ICore::mainWindow(),
+ QStringList fileNames = QFileDialog::getOpenFileNames(ICore::mainWindow(),
tr("Add Existing Files"), directoryFor(d->m_currentNode));
if (fileNames.isEmpty())
return;
@@ -2844,26 +2822,19 @@ void ProjectExplorerPlugin::addExistingFiles(ProjectNode *projectNode, const QSt
const QString dir = directoryFor(projectNode);
QStringList fileNames = filePaths;
- QHash<FileType, QString> fileTypeToFiles;
- foreach (const QString &fileName, fileNames) {
- FileType fileType = typeForFileName(Core::ICore::mimeDatabase(), QFileInfo(fileName));
- fileTypeToFiles.insertMulti(fileType, fileName);
- }
-
QStringList notAdded;
- foreach (const FileType type, fileTypeToFiles.uniqueKeys()) {
- projectNode->addFiles(type, fileTypeToFiles.values(type), &notAdded);
- }
+ projectNode->addFiles(fileNames, &notAdded);
+
if (!notAdded.isEmpty()) {
QString message = tr("Could not add following files to project %1:\n").arg(projectNode->displayName());
QString files = notAdded.join(QString(QLatin1Char('\n')));
- QMessageBox::warning(Core::ICore::mainWindow(), tr("Adding Files to Project Failed"),
+ QMessageBox::warning(ICore::mainWindow(), tr("Adding Files to Project Failed"),
message + files);
foreach (const QString &file, notAdded)
fileNames.removeOne(file);
}
- Core::ICore::vcsManager()->promptToAdd(dir, fileNames);
+ VcsManager::promptToAdd(dir, fileNames);
}
void ProjectExplorerPlugin::removeProject()
@@ -2871,7 +2842,7 @@ void ProjectExplorerPlugin::removeProject()
ProjectNode *subProjectNode = qobject_cast<ProjectNode*>(d->m_currentNode->projectNode());
ProjectNode *projectNode = qobject_cast<ProjectNode *>(subProjectNode->parentFolderNode());
if (projectNode) {
- Core::RemoveFileDialog removeFileDialog(subProjectNode->path(), Core::ICore::mainWindow());
+ RemoveFileDialog removeFileDialog(subProjectNode->path(), ICore::mainWindow());
removeFileDialog.setDeleteFileVisible(false);
if (removeFileDialog.exec() == QDialog::Accepted)
projectNode->removeSubProjects(QStringList() << subProjectNode->path());
@@ -2881,13 +2852,13 @@ void ProjectExplorerPlugin::removeProject()
void ProjectExplorerPlugin::openFile()
{
QTC_ASSERT(d->m_currentNode, return);
- Core::EditorManager::openEditor(d->m_currentNode->path());
+ EditorManager::openEditor(d->m_currentNode->path());
}
void ProjectExplorerPlugin::searchOnFileSystem()
{
QTC_ASSERT(d->m_currentNode, return);
- FolderNavigationWidget::findOnFileSystem(pathFor(d->m_currentNode));
+ TextEditor::FindInFiles::findOnFileSystem(pathFor(d->m_currentNode));
}
void ProjectExplorerPlugin::showInGraphicalShell()
@@ -2910,7 +2881,7 @@ void ProjectExplorerPlugin::removeFile()
FileNode *fileNode = qobject_cast<FileNode*>(d->m_currentNode);
QString filePath = d->m_currentNode->path();
- Core::RemoveFileDialog removeFileDialog(filePath, Core::ICore::mainWindow());
+ RemoveFileDialog removeFileDialog(filePath, ICore::mainWindow());
if (removeFileDialog.exec() == QDialog::Accepted) {
const bool deleteFile = removeFileDialog.isDeleteFileChecked();
@@ -2919,8 +2890,8 @@ void ProjectExplorerPlugin::removeFile()
ProjectNode *projectNode = fileNode->projectNode();
Q_ASSERT(projectNode);
- if (!projectNode->removeFiles(fileNode->fileType(), QStringList(filePath))) {
- QMessageBox::warning(Core::ICore::mainWindow(), tr("Removing File Failed"),
+ if (!projectNode->removeFiles(QStringList(filePath))) {
+ QMessageBox::warning(ICore::mainWindow(), tr("Removing File Failed"),
tr("Could not remove file %1 from project %2.").arg(filePath).arg(projectNode->displayName()));
return;
}
@@ -2937,7 +2908,7 @@ void ProjectExplorerPlugin::deleteFile()
QString filePath = d->m_currentNode->path();
QMessageBox::StandardButton button =
- QMessageBox::question(Core::ICore::mainWindow(),
+ QMessageBox::question(ICore::mainWindow(),
tr("Delete File"),
tr("Delete %1 from file system?").arg(filePath),
QMessageBox::Yes | QMessageBox::No);
@@ -2947,20 +2918,20 @@ void ProjectExplorerPlugin::deleteFile()
ProjectNode *projectNode = fileNode->projectNode();
QTC_ASSERT(projectNode, return);
- projectNode->deleteFiles(fileNode->fileType(), QStringList(filePath));
+ projectNode->deleteFiles(QStringList(filePath));
- Core::DocumentManager::expectFileChange(filePath);
- if (Core::IVersionControl *vc =
- Core::ICore::vcsManager()->findVersionControlForDirectory(QFileInfo(filePath).absolutePath())) {
+ DocumentManager::expectFileChange(filePath);
+ if (IVersionControl *vc =
+ VcsManager::findVersionControlForDirectory(QFileInfo(filePath).absolutePath())) {
vc->vcsDelete(filePath);
}
QFile file(filePath);
if (file.exists()) {
if (!file.remove())
- QMessageBox::warning(Core::ICore::mainWindow(), tr("Deleting File Failed"),
+ QMessageBox::warning(ICore::mainWindow(), tr("Deleting File Failed"),
tr("Could not delete file %1.").arg(filePath));
}
- Core::DocumentManager::unexpectFileChange(filePath);
+ DocumentManager::unexpectFileChange(filePath);
}
void ProjectExplorerPlugin::renameFile()
@@ -2988,14 +2959,14 @@ void ProjectExplorerPlugin::renameFile(Node *node, const QString &to)
if (Core::FileUtils::renameFile(orgFilePath, newFilePath)) {
// Tell the project plugin about rename
ProjectNode *projectNode = fileNode->projectNode();
- if (!projectNode->renameFile(fileNode->fileType(), orgFilePath, newFilePath)) {
- QMessageBox::warning(Core::ICore::mainWindow(), tr("Project Editing Failed"),
+ if (!projectNode->renameFile(orgFilePath, newFilePath)) {
+ QMessageBox::warning(ICore::mainWindow(), tr("Project Editing Failed"),
tr("The file %1 was renamed to %2, but the project file %3 could not be automatically changed.")
.arg(orgFilePath)
.arg(newFilePath)
.arg(projectNode->displayName()));
} else {
- setCurrent(d->m_session->projectForFile(newFilePath), newFilePath, 0);
+ setCurrent(SessionManager::projectForFile(newFilePath), newFilePath, 0);
}
}
}
@@ -3007,7 +2978,7 @@ void ProjectExplorerPlugin::setStartupProject()
void ProjectExplorerPlugin::populateOpenWithMenu()
{
- Core::DocumentManager::populateOpenWithMenu(d->m_openWithMenu, currentNode()->path());
+ DocumentManager::populateOpenWithMenu(d->m_openWithMenu, currentNode()->path());
}
void ProjectExplorerPlugin::updateSessionMenu()
@@ -3015,8 +2986,8 @@ void ProjectExplorerPlugin::updateSessionMenu()
d->m_sessionMenu->clear();
QActionGroup *ag = new QActionGroup(d->m_sessionMenu);
connect(ag, SIGNAL(triggered(QAction*)), this, SLOT(setSession(QAction*)));
- const QString &activeSession = d->m_session->activeSession();
- foreach (const QString &session, d->m_session->sessions()) {
+ const QString activeSession = SessionManager::activeSession();
+ foreach (const QString &session, SessionManager::sessions()) {
QAction *act = ag->addAction(session);
act->setCheckable(true);
if (session == activeSession)
@@ -3029,42 +3000,41 @@ void ProjectExplorerPlugin::updateSessionMenu()
void ProjectExplorerPlugin::setSession(QAction *action)
{
QString session = action->text();
- if (session != d->m_session->activeSession())
- d->m_session->loadSession(session);
+ if (session != SessionManager::activeSession())
+ SessionManager::loadSession(session);
}
-void ProjectExplorerPlugin::setProjectExplorerSettings(const Internal::ProjectExplorerSettings &pes)
+void ProjectExplorerPlugin::setProjectExplorerSettings(const ProjectExplorerSettings &pes)
{
- QTC_ASSERT(d->m_projectExplorerSettings.environmentId == pes.environmentId, return);
+ QTC_ASSERT(m_instance->d->m_projectExplorerSettings.environmentId == pes.environmentId, return);
- if (d->m_projectExplorerSettings == pes)
+ if (m_instance->d->m_projectExplorerSettings == pes)
return;
- d->m_projectExplorerSettings = pes;
- emit settingsChanged();
+ m_instance->d->m_projectExplorerSettings = pes;
+ emit m_instance->settingsChanged();
}
-Internal::ProjectExplorerSettings ProjectExplorerPlugin::projectExplorerSettings() const
+ProjectExplorerSettings ProjectExplorerPlugin::projectExplorerSettings()
{
- return d->m_projectExplorerSettings;
+ return m_instance->d->m_projectExplorerSettings;
}
QStringList ProjectExplorerPlugin::projectFilePatterns()
{
QStringList patterns;
- const Core::MimeDatabase *mdb = Core::ICore::mimeDatabase();
foreach (const IProjectManager *pm, allProjectManagers())
- if (const Core::MimeType mt = mdb->findByType(pm->mimeType()))
- foreach (const Core::MimeGlobPattern &gp, mt.globPatterns())
+ if (const MimeType mt = MimeDatabase::findByType(pm->mimeType()))
+ foreach (const MimeGlobPattern &gp, mt.globPatterns())
patterns.append(gp.pattern());
return patterns;
}
void ProjectExplorerPlugin::openOpenProjectDialog()
{
- const QString path = Core::DocumentManager::useProjectsDirectory() ? Core::DocumentManager::projectsDirectory() : QString();
- const QStringList files = Core::DocumentManager::getOpenFileNames(d->m_projectFilterString, path);
+ const QString path = DocumentManager::useProjectsDirectory() ? DocumentManager::projectsDirectory() : QString();
+ const QStringList files = DocumentManager::getOpenFileNames(d->m_projectFilterString, path);
if (!files.isEmpty())
- Core::ICore::openFiles(files, Core::ICore::SwitchMode);
+ ICore::openFiles(files, ICore::SwitchMode);
}
QList<QPair<QString, QString> > ProjectExplorerPlugin::recentProjects()
diff --git a/src/plugins/projectexplorer/projectexplorer.h b/src/plugins/projectexplorer/projectexplorer.h
index 640346dc7b..ba8190d02f 100644
--- a/src/plugins/projectexplorer/projectexplorer.h
+++ b/src/plugins/projectexplorer/projectexplorer.h
@@ -49,9 +49,7 @@ class Id;
}
namespace ProjectExplorer {
-class BuildManager;
class RunControl;
-class SessionManager;
class RunConfiguration;
class IRunControlFactory;
class Project;
@@ -81,19 +79,12 @@ public:
Q_SLOT void openProjectWelcomePage(const QString &fileName);
void unloadProject(Project *project);
- SessionManager *session() const;
-
static Project *currentProject();
Node *currentNode() const;
void setCurrentFile(Project *project, const QString &file);
void setCurrentNode(Node *node);
- Project *startupProject() const;
-
- BuildManager *buildManager() const;
- TaskHub *taskHub() const;
-
bool saveModifiedFiles();
void showContextMenu(QWidget *view, const QPoint &globalPos, Node *node);
@@ -103,8 +94,8 @@ public:
void extensionsInitialized();
ShutdownFlag aboutToShutdown();
- void setProjectExplorerSettings(const Internal::ProjectExplorerSettings &pes);
- Internal::ProjectExplorerSettings projectExplorerSettings() const;
+ static void setProjectExplorerSettings(const Internal::ProjectExplorerSettings &pes);
+ static Internal::ProjectExplorerSettings projectExplorerSettings();
void startRunControl(RunControl *runControl, RunMode runMode);
static void showRunErrorMessage(const QString &errorMessage);
@@ -246,6 +237,9 @@ private slots:
void testGccOutputParsers_data();
void testGccOutputParsers();
+ void testCustomOutputParsers_data();
+ void testCustomOutputParsers();
+
void testClangOutputParser_data();
void testClangOutputParser();
diff --git a/src/plugins/projectexplorer/projectexplorer.pro b/src/plugins/projectexplorer/projectexplorer.pro
index fb71346958..425920fc17 100644
--- a/src/plugins/projectexplorer/projectexplorer.pro
+++ b/src/plugins/projectexplorer/projectexplorer.pro
@@ -1,4 +1,4 @@
-QT += xml script declarative
+QT += xml script
include(../../qtcreatorplugin.pri)
include(customwizard/customwizard.pri)
@@ -6,15 +6,22 @@ HEADERS += projectexplorer.h \
abi.h \
abiwidget.h \
ansifilterparser.h \
+ buildinfo.h \
clangparser.h \
environmentaspect.h \
environmentaspectwidget.h \
gcctoolchain.h \
+ importwidget.h \
localapplicationrunconfiguration.h \
localenvironmentaspect.h \
+ osparser.h \
projectexplorer_export.h \
+ projectimporter.h \
projectwindow.h \
removetaskhandler.h \
+ targetsetuppage.h \
+ targetsetupwidget.h \
+ unconfiguredprojectpanel.h \
kit.h \
kitchooser.h \
kitconfigwidget.h \
@@ -83,7 +90,6 @@ HEADERS += projectexplorer.h \
cesdkhandler.h \
gccparser.h \
projectexplorersettingspage.h \
- projectwelcomepage.h \
baseprojectwizarddialog.h \
miniprojecttargetselector.h \
targetselector.h \
@@ -113,23 +119,30 @@ HEADERS += projectexplorer.h \
devicesupport/desktopdevicefactory.h \
devicesupport/idevicewidget.h \
devicesupport/idevicefactory.h \
+ devicesupport/desktopdeviceprocess.h \
devicesupport/devicecheckbuildstep.h \
devicesupport/devicemanager.h \
devicesupport/devicemanagermodel.h \
devicesupport/devicefactoryselectiondialog.h \
+ devicesupport/deviceprocess.h \
devicesupport/deviceprocesslist.h \
devicesupport/deviceprocessesdialog.h \
devicesupport/devicesettingswidget.h \
devicesupport/devicesettingspage.h \
+ devicesupport/devicetestdialog.h \
devicesupport/deviceusedportsgatherer.h \
devicesupport/deviceapplicationrunner.h \
devicesupport/localprocesslist.h \
+ devicesupport/sshdeviceprocess.h \
devicesupport/sshdeviceprocesslist.h \
devicesupport/desktopdeviceconfigurationwidget.h \
+ devicesupport/desktopprocesssignaloperation.h \
deploymentdata.h \
buildtargetinfo.h \
customtoolchain.h \
- projectmacroexpander.h
+ projectmacroexpander.h \
+ customparser.h \
+ customparserconfigdialog.h
SOURCES += projectexplorer.cpp \
abi.cpp \
@@ -139,12 +152,19 @@ SOURCES += projectexplorer.cpp \
environmentaspect.cpp \
environmentaspectwidget.cpp \
gcctoolchain.cpp \
+ importwidget.cpp \
localapplicationrunconfiguration.cpp \
localenvironmentaspect.cpp \
+ osparser.cpp \
+ projectimporter.cpp \
projectwindow.cpp \
removetaskhandler.cpp \
+ targetsetuppage.cpp \
+ targetsetupwidget.cpp \
+ unconfiguredprojectpanel.cpp \
kit.cpp \
kitchooser.cpp \
+ kitconfigwidget.cpp \
kitinformation.cpp \
kitinformationconfigwidget.cpp \
kitmanager.cpp \
@@ -205,7 +225,6 @@ SOURCES += projectexplorer.cpp \
cesdkhandler.cpp \
gccparser.cpp \
projectexplorersettingspage.cpp \
- projectwelcomepage.cpp \
corelistenercheckingforrunningbuild.cpp \
baseprojectwizarddialog.cpp \
miniprojecttargetselector.cpp \
@@ -229,22 +248,29 @@ SOURCES += projectexplorer.cpp \
devicesupport/desktopdevice.cpp \
devicesupport/desktopdevicefactory.cpp \
devicesupport/idevicefactory.cpp \
+ devicesupport/desktopdeviceprocess.cpp \
devicesupport/devicecheckbuildstep.cpp \
devicesupport/devicemanager.cpp \
devicesupport/devicemanagermodel.cpp \
devicesupport/devicefactoryselectiondialog.cpp \
+ devicesupport/deviceprocess.cpp \
devicesupport/deviceprocesslist.cpp \
devicesupport/deviceprocessesdialog.cpp \
devicesupport/devicesettingswidget.cpp \
devicesupport/devicesettingspage.cpp \
+ devicesupport/devicetestdialog.cpp \
devicesupport/deviceusedportsgatherer.cpp \
devicesupport/deviceapplicationrunner.cpp \
devicesupport/localprocesslist.cpp \
+ devicesupport/sshdeviceprocess.cpp \
devicesupport/sshdeviceprocesslist.cpp \
devicesupport/desktopdeviceconfigurationwidget.cpp \
+ devicesupport/desktopprocesssignaloperation.cpp \
deployablefile.cpp \
customtoolchain.cpp \
- projectmacroexpander.cpp
+ projectmacroexpander.cpp \
+ customparser.cpp \
+ customparserconfigdialog.cpp
FORMS += processstep.ui \
editorsettingspropertiespage.ui \
@@ -257,7 +283,9 @@ FORMS += processstep.ui \
codestylesettingspropertiespage.ui \
devicesupport/devicefactoryselectiondialog.ui \
devicesupport/devicesettingswidget.ui \
- devicesupport/desktopdeviceconfigurationwidget.ui
+ devicesupport/devicetestdialog.ui \
+ devicesupport/desktopdeviceconfigurationwidget.ui \
+ customparserconfigdialog.ui
WINSOURCES += \
windebuginterface.cpp \
@@ -285,6 +313,11 @@ equals(TEST, 1) {
outputparser_test.h
}
+greaterThan(QT_MAJOR_VERSION, 4) {
+ QT += quick
+ HEADERS += projectwelcomepage.h
+ SOURCES += projectwelcomepage.cpp
+}
macx:LIBS += -framework Carbon
RESOURCES += projectexplorer.qrc
diff --git a/src/plugins/projectexplorer/projectexplorer.qbs b/src/plugins/projectexplorer/projectexplorer.qbs
index 55dd5a3432..3772f33c08 100644
--- a/src/plugins/projectexplorer/projectexplorer.qbs
+++ b/src/plugins/projectexplorer/projectexplorer.qbs
@@ -1,12 +1,13 @@
import qbs.base 1.0
+import "../../../qbs/functions.js" as QtcFunctions
import "../QtcPlugin.qbs" as QtcPlugin
-import "../../../qbs/defaults.js" as Defaults
QtcPlugin {
name: "ProjectExplorer"
- Depends { name: "Qt"; submodules: ["widgets", "xml", "network", "script", "declarative"] }
+ Depends { name: "Qt"; submodules: ["widgets", "xml", "network", "script"] }
+ Depends { name: "Qt.quick"; condition: QtcFunctions.versionIsAtLeast(Qt.core.version, "5.1"); }
Depends { name: "Core" }
Depends { name: "Locator" }
Depends { name: "Find" }
@@ -14,327 +15,248 @@ QtcPlugin {
Depends { name: "QtcSsh" }
cpp.defines: base.concat("QTC_CPU=X86Architecture")
- cpp.includePaths: base.concat([
- "customwizard",
- "publishing"
- ])
+ Properties {
+ condition: qbs.targetOS.contains("osx")
+ cpp.frameworks: base.concat(["Carbon"])
+ }
+
+ Group {
+ name: "General"
+ files: [
+ "abi.cpp", "abi.h",
+ "abiwidget.cpp", "abiwidget.h",
+ "abstractprocessstep.cpp", "abstractprocessstep.h",
+ "allprojectsfilter.cpp", "allprojectsfilter.h",
+ "allprojectsfind.cpp", "allprojectsfind.h",
+ "ansifilterparser.cpp", "ansifilterparser.h",
+ "applicationlauncher.cpp", "applicationlauncher.h",
+ "appoutputpane.cpp", "appoutputpane.h",
+ "baseprojectwizarddialog.cpp", "baseprojectwizarddialog.h",
+ "buildconfiguration.cpp", "buildconfiguration.h",
+ "buildconfigurationmodel.cpp", "buildconfigurationmodel.h",
+ "buildenvironmentwidget.cpp", "buildenvironmentwidget.h",
+ "buildinfo.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",
+ "customparser.cpp", "customparser.h",
+ "customparserconfigdialog.cpp", "customparserconfigdialog.h", "customparserconfigdialog.ui",
+ "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",
+ "environmentaspect.cpp", "environmentaspect.h",
+ "environmentaspectwidget.cpp", "environmentaspectwidget.h",
+ "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",
+ "importwidget.cpp", "importwidget.h",
+ "ioutputparser.cpp", "ioutputparser.h",
+ "iprojectmanager.h",
+ "iprojectproperties.h",
+ "itaskhandler.h",
+ "kit.cpp", "kit.h",
+ "kitchooser.cpp", "kitchooser.h",
+ "kitconfigwidget.cpp", "kitconfigwidget.h",
+ "kitinformation.cpp", "kitinformation.h",
+ "kitinformationconfigwidget.cpp", "kitinformationconfigwidget.h",
+ "kitmanager.cpp", "kitmanager.h",
+ "kitmanagerconfigwidget.cpp", "kitmanagerconfigwidget.h",
+ "kitmodel.cpp", "kitmodel.h",
+ "kitoptionspage.cpp", "kitoptionspage.h",
+ "ldparser.cpp", "ldparser.h",
+ "linuxiccparser.cpp", "linuxiccparser.h",
+ "localapplicationrunconfiguration.cpp", "localapplicationrunconfiguration.h",
+ "localapplicationruncontrol.cpp", "localapplicationruncontrol.h",
+ "localenvironmentaspect.cpp", "localenvironmentaspect.h",
+ "metatypedeclarations.h",
+ "miniprojecttargetselector.cpp", "miniprojecttargetselector.h",
+ "namedwidget.cpp", "namedwidget.h",
+ "nodesvisitor.cpp", "nodesvisitor.h",
+ "osparser.cpp", "osparser.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",
+ "projectimporter.cpp", "projectimporter.h",
+ "projectmacroexpander.cpp", "projectmacroexpander.h",
+ "projectmodels.cpp", "projectmodels.h",
+ "projectnodes.cpp", "projectnodes.h",
+ "projecttreewidget.cpp", "projecttreewidget.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",
+ "showoutputtaskhandler.cpp", "showoutputtaskhandler.h",
+ "target.cpp", "target.h",
+ "targetselector.cpp", "targetselector.h",
+ "targetsettingspanel.cpp", "targetsettingspanel.h",
+ "targetsettingswidget.cpp", "targetsettingswidget.h", "targetsettingswidget.ui",
+ "targetsetuppage.cpp", "targetsetuppage.h",
+ "targetsetupwidget.cpp", "targetsetupwidget.h",
+ "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.cpp", "toolchainmanager.h",
+ "toolchainoptionspage.cpp", "toolchainoptionspage.h",
+ "unconfiguredprojectpanel.cpp", "unconfiguredprojectpanel.h",
+ "vcsannotatetaskhandler.cpp", "vcsannotatetaskhandler.h",
+ ]
+ }
+
+ Group {
+ name: "Project Welcome Page"
+ condition: QtcFunctions.versionIsAtLeast(Qt.core.version, "5.1")
+ files: [
+ "projectwelcomepage.cpp",
+ "projectwelcomepage.h"
+ ]
+ }
+
+ Group {
+ name: "CustomWizard"
+ prefix: "customwizard/"
+ files: [
+ "customwizard.cpp", "customwizard.h",
+ "customwizardpage.cpp", "customwizardpage.h",
+ "customwizardparameters.cpp", "customwizardparameters.h",
+ "customwizardpreprocessor.cpp", "customwizardpreprocessor.h",
+ "customwizardscriptgenerator.cpp", "customwizardscriptgenerator.h"
+ ]
+ }
+
+ Group {
+ name: "Device Support"
+ prefix: "devicesupport/"
+ files: [
+ "desktopdevice.cpp", "desktopdevice.h",
+ "desktopdevicefactory.cpp", "desktopdevicefactory.h",
+ "deviceapplicationrunner.cpp", "deviceapplicationrunner.h",
+ "devicecheckbuildstep.cpp", "devicecheckbuildstep.h",
+ "devicefactoryselectiondialog.cpp", "devicefactoryselectiondialog.h", "devicefactoryselectiondialog.ui",
+ "devicemanager.cpp", "devicemanager.h",
+ "devicemanagermodel.cpp", "devicemanagermodel.h",
+ "deviceprocess.cpp", "deviceprocess.h",
+ "deviceprocessesdialog.cpp", "deviceprocessesdialog.h",
+ "deviceprocesslist.cpp", "deviceprocesslist.h",
+ "devicesettingspage.cpp", "devicesettingspage.h",
+ "devicesettingswidget.cpp", "devicesettingswidget.h", "devicesettingswidget.ui",
+ "devicetestdialog.cpp", "devicetestdialog.h", "devicetestdialog.ui",
+ "deviceusedportsgatherer.cpp", "deviceusedportsgatherer.h",
+ "idevice.cpp", "idevice.h",
+ "idevicefactory.cpp", "idevicefactory.h",
+ "idevicewidget.h",
+ "desktopdeviceprocess.cpp", "desktopdeviceprocess.h",
+ "localprocesslist.cpp", "localprocesslist.h",
+ "sshdeviceprocess.cpp", "sshdeviceprocess.h",
+ "sshdeviceprocesslist.cpp", "sshdeviceprocesslist.h",
+ "desktopprocesssignaloperation.cpp", "desktopprocesssignaloperation.h",
+ "desktopdeviceconfigurationwidget.cpp", "desktopdeviceconfigurationwidget.h", "desktopdeviceconfigurationwidget.ui"
+ ]
+ }
- files: [
- "abi.cpp",
- "abi.h",
- "abiwidget.cpp",
- "abiwidget.h",
- "abstractprocessstep.cpp",
- "abstractprocessstep.h",
- "allprojectsfilter.cpp",
- "allprojectsfilter.h",
- "allprojectsfind.cpp",
- "allprojectsfind.h",
- "ansifilterparser.cpp",
- "ansifilterparser.h",
- "applicationlauncher.cpp",
- "applicationlauncher.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",
- "environmentaspect.cpp",
- "environmentaspect.h",
- "environmentaspectwidget.cpp",
- "environmentaspectwidget.h",
- "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",
- "ioutputparser.h",
- "iprojectmanager.h",
- "iprojectproperties.h",
- "itaskhandler.h",
- "kit.cpp",
- "kit.h",
- "kitchooser.cpp",
- "kitchooser.h",
- "kitconfigwidget.h",
- "kitinformation.cpp",
- "kitinformation.h",
- "kitinformationconfigwidget.cpp",
- "kitinformationconfigwidget.h",
- "kitmanager.cpp",
- "kitmanager.h",
- "kitmanagerconfigwidget.cpp",
- "kitmanagerconfigwidget.h",
- "kitmodel.cpp",
- "kitmodel.h",
- "kitoptionspage.cpp",
- "kitoptionspage.h",
- "ldparser.cpp",
- "ldparser.h",
- "linuxiccparser.cpp",
- "linuxiccparser.h",
- "localapplicationrunconfiguration.cpp",
- "localapplicationrunconfiguration.h",
- "localapplicationruncontrol.cpp",
- "localapplicationruncontrol.h",
- "localenvironmentaspect.cpp",
- "localenvironmentaspect.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",
- "showoutputtaskhandler.cpp",
- "showoutputtaskhandler.h",
- "target.cpp",
- "target.h",
- "targetselector.cpp",
- "targetselector.h",
- "targetsettingspanel.cpp",
- "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.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",
- "devicesupport/desktopdevice.cpp",
- "devicesupport/desktopdevice.h",
- "devicesupport/desktopdevicefactory.cpp",
- "devicesupport/desktopdevicefactory.h",
- "devicesupport/deviceapplicationrunner.cpp",
- "devicesupport/deviceapplicationrunner.h",
- "devicesupport/devicecheckbuildstep.cpp",
- "devicesupport/devicecheckbuildstep.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",
- "devicesupport/desktopdeviceconfigurationwidget.cpp",
- "devicesupport/desktopdeviceconfigurationwidget.h",
- "devicesupport/desktopdeviceconfigurationwidget.ui",
- "images/BuildSettings.png",
- "images/CodeStyleSettings.png",
- "images/Desktop.png",
- "images/DeviceConnected.png",
- "images/DeviceDisconnected.png",
- "images/DeviceReadyToUse.png",
- "images/EditorSettings.png",
- "images/MaemoDevice.png",
- "images/ProjectDependencies.png",
- "images/RunSettings.png",
- "images/Simulator.png",
- "images/build.png",
- "images/build_32.png",
- "images/build_small.png",
- "images/clean.png",
- "images/clean_small.png",
- "images/closetab.png",
- "images/compile_error.png",
- "images/compile_warning.png",
- "images/debugger_start.png",
- "images/debugger_start_small.png",
- "images/findallprojects.png",
- "images/findproject.png",
- "images/leftselection.png",
- "images/midselection.png",
- "images/projectexplorer.png",
- "images/rebuild.png",
- "images/rebuild_small.png",
- "images/rightselection.png",
- "images/run.png",
- "images/run_small.png",
- "images/session.png",
- "images/stop.png",
- "images/stop_small.png",
- "images/targetbuildselected.png",
- "images/targetleftbutton.png",
- "images/targetpanel_bottom.png",
- "images/targetpanel_gradient.png",
- "images/targetrightbutton.png",
- "images/targetrunselected.png",
- "images/targetseparatorbackground.png",
- "images/targetunselected.png",
- "images/window.png",
- "publishing/ipublishingwizardfactory.h",
- "publishing/publishingwizardselectiondialog.cpp",
- "publishing/publishingwizardselectiondialog.h",
- "publishing/publishingwizardselectiondialog.ui",
- ]
+ Group {
+ name: "Images"
+ prefix: "images/"
+ files: [
+ "BuildSettings.png",
+ "CodeStyleSettings.png",
+ "Desktop.png",
+ "DeviceConnected.png",
+ "DeviceDisconnected.png",
+ "DeviceReadyToUse.png",
+ "EditorSettings.png",
+ "MaemoDevice.png",
+ "ProjectDependencies.png",
+ "RunSettings.png",
+ "Simulator.png",
+ "build.png",
+ "build_32.png",
+ "build_small.png",
+ "clean.png",
+ "clean_small.png",
+ "closetab.png",
+ "compile_error.png",
+ "compile_warning.png",
+ "debugger_start.png",
+ "debugger_start_small.png",
+ "findallprojects.png",
+ "findproject.png",
+ "leftselection.png",
+ "midselection.png",
+ "projectexplorer.png",
+ "rebuild.png",
+ "rebuild_small.png",
+ "rightselection.png",
+ "run.png",
+ "run_small.png",
+ "session.png",
+ "stop.png",
+ "stop_small.png",
+ "targetbuildselected.png",
+ "targetleftbutton.png",
+ "targetpanel_bottom.png",
+ "targetpanel_gradient.png",
+ "targetrightbutton.png",
+ "targetrunselected.png",
+ "targetseparatorbackground.png",
+ "targetunselected.png",
+ "window.png",
+ ]
+ }
+
+ Group {
+ name: "Publishing"
+ prefix: "publishing/"
+ files: [
+ "ipublishingwizardfactory.h",
+ "publishingwizardselectiondialog.cpp", "publishingwizardselectiondialog.h", "publishingwizardselectiondialog.ui",
+ ]
+ }
Group {
name: "WindowsToolChains"
- condition: qbs.targetOS.contains("windows") || Defaults.testsEnabled(qbs)
+ condition: qbs.targetOS.contains("windows") || project.testsEnabled
files: [
"abstractmsvctoolchain.cpp",
"abstractmsvctoolchain.h",
@@ -351,7 +273,7 @@ QtcPlugin {
Group {
name: "Tests"
- condition: Defaults.testsEnabled(qbs)
+ condition: project.testsEnabled
files: ["outputparser_test.h", "outputparser_test.cpp"]
}
diff --git a/src/plugins/projectexplorer/projectexplorerconstants.h b/src/plugins/projectexplorer/projectexplorerconstants.h
index e68ae893f4..0acabbf38e 100644
--- a/src/plugins/projectexplorer/projectexplorerconstants.h
+++ b/src/plugins/projectexplorer/projectexplorerconstants.h
@@ -162,8 +162,6 @@ const char ICON_STOP[] = ":/projectexplorer/images/stop.png";
const char ICON_STOP_SMALL[] = ":/projectexplorer/images/stop_small.png";
const char ICON_WINDOW[] = ":/projectexplorer/images/window.png";
-const char TASK_BUILD[] = "ProjectExplorer.Task.Build";
-
// Mime types
const char C_SOURCE_MIMETYPE[] = "text/x-csrc";
const char C_HEADER_MIMETYPE[] = "text/x-chdr";
@@ -179,6 +177,7 @@ const char PROJECTEXPLORER_SETTINGS_TR_CATEGORY[] = QT_TRANSLATE_NOOP("ProjectEx
const char PROJECTEXPLORER_SETTINGS_CATEGORY_ICON[] = ":/core/images/category_buildrun.png";
const char PROJECTEXPLORER_SETTINGS_ID[] = "A.ProjectExplorer.ProjectExplorer";
const char TOOLCHAIN_SETTINGS_PAGE_ID[] = "M.ProjectExplorer.ToolChainOptions";
+const char DEBUGGER_SETTINGS_PAGE_ID[] = "N.ProjectExplorer.DebuggerOptions";
const char KITS_SETTINGS_PAGE_ID[] = "D.ProjectExplorer.KitsOptions";
// Device settings page
@@ -188,6 +187,7 @@ const char DEVICE_SETTINGS_PAGE_ID[] = "AA.Device Settings";
// Task categories
const char TASK_CATEGORY_COMPILE[] = "Task.Category.Compile";
const char TASK_CATEGORY_BUILDSYSTEM[] = "Task.Category.Buildsystem";
+const char TASK_CATEGORY_DEPLOYMENT[] = "Task.Category.Deploy";
// Wizard categories
const char QT_PROJECT_WIZARD_CATEGORY[] = "H.QtProjects";
@@ -246,6 +246,9 @@ const char VAR_CURRENTKIT_ID[] = "CurrentKit:Id";
const char VAR_CURRENTBUILD_NAME[] = "CurrentBuild:Name";
const char VAR_CURRENTBUILD_TYPE[] = "CurrentBuild:Type";
+// Unconfigured Panel
+const char UNCONFIGURED_PANEL_PAGE_ID[] = "UnconfiguredPanel";
+
} // namespace Constants
// Run modes
diff --git a/src/plugins/projectexplorer/projectexplorersettingspage.cpp b/src/plugins/projectexplorer/projectexplorersettingspage.cpp
index e9e934183a..6ad0591fed 100644
--- a/src/plugins/projectexplorer/projectexplorersettingspage.cpp
+++ b/src/plugins/projectexplorer/projectexplorersettingspage.cpp
@@ -191,7 +191,7 @@ ProjectExplorerSettingsPage::~ProjectExplorerSettingsPage()
QWidget *ProjectExplorerSettingsPage::createPage(QWidget *parent)
{
m_widget = new ProjectExplorerSettingsWidget(parent);
- m_widget->setSettings(ProjectExplorerPlugin::instance()->projectExplorerSettings());
+ m_widget->setSettings(ProjectExplorerPlugin::projectExplorerSettings());
m_widget->setProjectsDirectory(Core::DocumentManager::projectsDirectory());
m_widget->setUseProjectsDirectory(Core::DocumentManager::useProjectsDirectory());
m_widget->setBuildDirectory(Core::DocumentManager::buildDirectory());
@@ -203,7 +203,7 @@ QWidget *ProjectExplorerSettingsPage::createPage(QWidget *parent)
void ProjectExplorerSettingsPage::apply()
{
if (m_widget) {
- ProjectExplorerPlugin::instance()->setProjectExplorerSettings(m_widget->settings());
+ ProjectExplorerPlugin::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/projectfilewizardextension.cpp b/src/plugins/projectexplorer/projectfilewizardextension.cpp
index ea72628237..05fd1c2cf3 100644
--- a/src/plugins/projectexplorer/projectfilewizardextension.cpp
+++ b/src/plugins/projectexplorer/projectfilewizardextension.cpp
@@ -107,7 +107,7 @@ private:
ProjectNodeList AllProjectNodesVisitor::allProjects(ProjectNode::ProjectAction action)
{
AllProjectNodesVisitor visitor(action);
- ProjectExplorerPlugin::instance()->session()->sessionNode()->accept(&visitor);
+ SessionManager::sessionNode()->accept(&visitor);
return visitor.m_projectNodes;
}
@@ -349,7 +349,7 @@ void ProjectFileWizardExtension::initializeVersionControlChoices()
QStringList versionControlChoices = QStringList(tr("<None>"));
if (!m_context->commonDirectory.isEmpty()) {
- Core::IVersionControl *managingControl = Core::ICore::vcsManager()->findVersionControlForDirectory(m_context->commonDirectory);
+ Core::IVersionControl *managingControl = Core::VcsManager::findVersionControlForDirectory(m_context->commonDirectory);
if (managingControl) {
// Under VCS
if (managingControl->supportsOperation(Core::IVersionControl::AddOperation)) {
@@ -473,8 +473,6 @@ bool ProjectFileWizardExtension::processProject(
const QList<Core::GeneratedFile> &files,
bool *removeOpenProjectAttribute, QString *errorMessage)
{
- typedef QMultiMap<FileType, QString> TypeFileMap;
-
*removeOpenProjectAttribute = false;
QString generatedProject = generatedProjectFilePath(files);
@@ -492,20 +490,13 @@ bool ProjectFileWizardExtension::processProject(
}
*removeOpenProjectAttribute = true;
} else {
- // Split into lists by file type and bulk-add them.
- TypeFileMap typeFileMap;
- const Core::MimeDatabase *mdb = Core::ICore::mimeDatabase();
- foreach (const Core::GeneratedFile &generatedFile, files) {
- const QString path = generatedFile.path();
- typeFileMap.insert(typeForFileName(mdb, path), path);
- }
- foreach (FileType type, typeFileMap.uniqueKeys()) {
- const QStringList typeFiles = typeFileMap.values(type);
- if (!project->addFiles(type, typeFiles)) {
- *errorMessage = tr("Failed to add one or more files to project\n'%1' (%2).").
- arg(project->path(), typeFiles.join(QString(QLatin1Char(','))));
- return false;
- }
+ QStringList filePaths;
+ foreach (const Core::GeneratedFile &generatedFile, files)
+ filePaths << generatedFile.path();
+ if (!project->addFiles(filePaths)) {
+ *errorMessage = tr("Failed to add one or more files to project\n'%1' (%2).").
+ arg(project->path(), filePaths.join(QString(QLatin1Char(','))));
+ return false;
}
}
return true;
@@ -547,7 +538,7 @@ static TextEditor::ICodeStylePreferences *codeStylePreferences(ProjectExplorer::
if (project)
return project->editorConfiguration()->codeStyle(languageId);
- return TextEditor::TextEditorSettings::instance()->codeStyle(languageId);
+ return TextEditor::TextEditorSettings::codeStyle(languageId);
}
void ProjectFileWizardExtension::applyCodeStyle(Core::GeneratedFile *file) const
@@ -555,9 +546,8 @@ void ProjectFileWizardExtension::applyCodeStyle(Core::GeneratedFile *file) const
if (file->isBinary() || file->contents().isEmpty())
return; // nothing to do
- const Core::MimeDatabase *mdb = Core::ICore::mimeDatabase();
- Core::MimeType mt = mdb->findByFile(QFileInfo(file->path()));
- Core::Id languageId = TextEditor::TextEditorSettings::instance()->languageId(mt.type());
+ Core::MimeType mt = Core::MimeDatabase::findByFile(QFileInfo(file->path()));
+ Core::Id languageId = TextEditor::TextEditorSettings::languageId(mt.type());
if (!languageId.isValid())
return; // don't modify files like *.ui *.pro
@@ -567,11 +557,10 @@ void ProjectFileWizardExtension::applyCodeStyle(Core::GeneratedFile *file) const
if (projectIndex >= 0 && projectIndex < m_context->projects.size())
project = m_context->projects.at(projectIndex).node;
- ProjectExplorer::Project *baseProject
- = ProjectExplorer::ProjectExplorerPlugin::instance()->session()->projectForNode(project);
+ Project *baseProject = SessionManager::projectForNode(project);
TextEditor::ICodeStylePreferencesFactory *factory
- = TextEditor::TextEditorSettings::instance()->codeStyleFactory(languageId);
+ = TextEditor::TextEditorSettings::codeStyleFactory(languageId);
TextEditor::Indenter *indenter = 0;
if (factory)
@@ -586,7 +575,7 @@ void ProjectFileWizardExtension::applyCodeStyle(Core::GeneratedFile *file) const
cursor.select(QTextCursor::Document);
indenter->indent(&doc, cursor, QChar::Null, codeStylePrefs->currentTabSettings());
delete indenter;
- if (TextEditor::TextEditorSettings::instance()->storageSettings().m_cleanWhitespace) {
+ if (TextEditor::TextEditorSettings::storageSettings().m_cleanWhitespace) {
QTextBlock block = doc.firstBlock();
while (block.isValid()) {
codeStylePrefs->currentTabSettings().removeTrailingWhitespace(cursor, block);
diff --git a/src/plugins/projectexplorer/projectimporter.cpp b/src/plugins/projectexplorer/projectimporter.cpp
new file mode 100644
index 0000000000..6c8378dc06
--- /dev/null
+++ b/src/plugins/projectexplorer/projectimporter.cpp
@@ -0,0 +1,130 @@
+/****************************************************************************
+**
+** 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 "projectimporter.h"
+
+#include "kit.h"
+#include "kitmanager.h"
+#include "project.h"
+
+#include <coreplugin/idocument.h>
+
+#include <utils/qtcassert.h>
+
+namespace ProjectExplorer {
+
+static const Core::Id KIT_IS_TEMPORARY("PE.TempKit");
+static const Core::Id KIT_TEMPORARY_NAME("PE.TempName");
+static const Core::Id KIT_FINAL_NAME("PE.FinalName");
+static const Core::Id TEMPORARY_OF_PROJECTS("PE.TempProject");
+
+ProjectImporter::ProjectImporter(const QString &path) : m_projectPath(path), m_isUpdating(false)
+{ }
+
+ProjectImporter::~ProjectImporter()
+{
+ foreach (Kit *k, KitManager::kits())
+ removeProject(k, m_projectPath);
+}
+
+void ProjectImporter::markTemporary(Kit *k)
+{
+ QTC_ASSERT(!k->hasValue(KIT_IS_TEMPORARY), return);
+
+ setIsUpdating(true);
+
+ const QString name = k->displayName();
+ k->setDisplayName(QCoreApplication::translate("ProjectExplorer::ProjectImporter",
+ "%1 - temporary").arg(name));
+
+ k->setValue(KIT_TEMPORARY_NAME, k->displayName());
+ k->setValue(KIT_FINAL_NAME, name);
+ k->setValue(KIT_IS_TEMPORARY, true);
+
+ setIsUpdating(false);
+}
+
+void ProjectImporter::makePermanent(Kit *k)
+{
+ if (!k->hasValue(KIT_IS_TEMPORARY))
+ return;
+
+ setIsUpdating(true);
+
+ k->removeKey(KIT_IS_TEMPORARY);
+ k->removeKey(TEMPORARY_OF_PROJECTS);
+ const QString tempName = k->value(KIT_TEMPORARY_NAME).toString();
+ if (!tempName.isNull() && k->displayName() == tempName)
+ k->setDisplayName(k->value(KIT_FINAL_NAME).toString());
+ k->removeKey(KIT_TEMPORARY_NAME);
+ k->removeKey(KIT_FINAL_NAME);
+
+ setIsUpdating(false);
+}
+
+void ProjectImporter::cleanupKit(Kit *k)
+{
+ Q_UNUSED(k);
+}
+
+void ProjectImporter::addProject(Kit *k)
+{
+ if (!k->hasValue(KIT_IS_TEMPORARY))
+ return;
+
+ QStringList projects = k->value(TEMPORARY_OF_PROJECTS, QStringList()).toStringList();
+
+ projects.append(m_projectPath); // note: There can be more than one instance of the project added!
+
+ setIsUpdating(true);
+
+ k->setValue(TEMPORARY_OF_PROJECTS, projects);
+
+ setIsUpdating(false);
+}
+
+void ProjectImporter::removeProject(Kit *k, const QString &path)
+{
+ if (!k->hasValue(KIT_IS_TEMPORARY))
+ return;
+
+ QStringList projects = k->value(TEMPORARY_OF_PROJECTS, QStringList()).toStringList();
+ projects.removeOne(path);
+
+ setIsUpdating(true);
+
+ if (projects.isEmpty())
+ ProjectExplorer::KitManager::deregisterKit(k);
+ else
+ k->setValue(TEMPORARY_OF_PROJECTS, projects);
+
+ setIsUpdating(false);
+}
+
+} // namespace ProjectExplorer
diff --git a/src/plugins/projectexplorer/projectimporter.h b/src/plugins/projectexplorer/projectimporter.h
new file mode 100644
index 0000000000..1bd5243dc1
--- /dev/null
+++ b/src/plugins/projectexplorer/projectimporter.h
@@ -0,0 +1,78 @@
+/****************************************************************************
+**
+** 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 PROJECTIMPORTER_H
+#define PROJECTIMPORTER_H
+
+#include "projectexplorer_export.h"
+
+#include <utils/fileutils.h>
+
+namespace ProjectExplorer {
+
+class BuildInfo;
+class Kit;
+class Project;
+class Target;
+
+// Documentation inside.
+class PROJECTEXPLORER_EXPORT ProjectImporter
+{
+public:
+ ProjectImporter(const QString &path);
+ virtual ~ProjectImporter();
+
+ const QString projectFilePath() const { return m_projectPath; }
+
+ virtual QList<BuildInfo *> import(const Utils::FileName &importPath, bool silent = false) = 0;
+ virtual QStringList importCandidates(const Utils::FileName &projectFilePath) = 0;
+ virtual Target *preferredTarget(const QList<Target *> &possibleTargets) = 0;
+
+ bool isUpdating() const { return m_isUpdating; }
+
+ virtual void markTemporary(Kit *k);
+ virtual void makePermanent(Kit *k);
+
+ // Additional cleanup that has to happen when kits are removed
+ virtual void cleanupKit(Kit *k);
+
+ void addProject(Kit *k);
+ void removeProject(Kit *k, const QString &path);
+
+protected:
+ void setIsUpdating(bool b) { m_isUpdating = b; }
+
+private:
+ const QString m_projectPath;
+ bool m_isUpdating;
+};
+
+} // namespace ProjectExplorer
+
+#endif // PROJECTIMPORTER_H
diff --git a/src/plugins/projectexplorer/projectmodels.cpp b/src/plugins/projectexplorer/projectmodels.cpp
index f9a7e7091e..c229112958 100644
--- a/src/plugins/projectexplorer/projectmodels.cpp
+++ b/src/plugins/projectexplorer/projectmodels.cpp
@@ -42,7 +42,6 @@
using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;
-using Core::FileIconProvider;
namespace {
@@ -271,7 +270,7 @@ QVariant FlatModel::data(const QModelIndex &index, int role) const
const QString vcsTopic = node->vcsTopic();
if (!vcsTopic.isEmpty())
- name += QLatin1String(" (") + vcsTopic + QLatin1Char(')');
+ name += QLatin1String(" [") + vcsTopic + QLatin1Char(']');
}
result = name;
@@ -289,7 +288,7 @@ QVariant FlatModel::data(const QModelIndex &index, int role) const
if (folderNode)
result = folderNode->icon();
else
- result = FileIconProvider::instance()->icon(QFileInfo(node->path()));
+ result = Core::FileIconProvider::icon(node->path());
break;
}
case Qt::FontRole: {
diff --git a/src/plugins/projectexplorer/projectnodes.cpp b/src/plugins/projectexplorer/projectnodes.cpp
index 01b25b1681..e1f97cf178 100644
--- a/src/plugins/projectexplorer/projectnodes.cpp
+++ b/src/plugins/projectexplorer/projectnodes.cpp
@@ -252,7 +252,7 @@ QIcon FolderNode::icon() const
{
// Instantiating the Icon provider is expensive.
if (m_icon.isNull())
- m_icon = Core::FileIconProvider::instance()->icon(QFileIconProvider::Folder);
+ m_icon = Core::FileIconProvider::icon(QFileIconProvider::Folder);
return m_icon;
}
@@ -353,11 +353,12 @@ ProjectNode::ProjectNode(const QString &projectFilePath)
setDisplayName(QFileInfo(projectFilePath).fileName());
}
-QString ProjectNode::vcsTopic() const {
+QString ProjectNode::vcsTopic() const
+{
const QString dir = QFileInfo(path()).absolutePath();
if (Core::IVersionControl *const vc =
- Core::ICore::vcsManager()->findVersionControlForDirectory(dir))
+ Core::VcsManager::findVersionControlForDirectory(dir))
return vc->vcsTopic(dir);
return QString();
@@ -850,27 +851,3 @@ NodesWatcher::NodesWatcher(QObject *parent)
: QObject(parent)
{
}
-
-// TODO Maybe put this in core, so that all can benefit
-FileType typeForFileName(const Core::MimeDatabase *db, const QFileInfo &file)
-{
- const Core::MimeType mt = db->findByFile(file);
- if (!mt)
- return UnknownFileType;
-
- const QString typeName = mt.type();
- if (typeName == QLatin1String(Constants::CPP_SOURCE_MIMETYPE)
- || typeName == QLatin1String(Constants::C_SOURCE_MIMETYPE))
- return SourceType;
- if (typeName == QLatin1String(Constants::CPP_HEADER_MIMETYPE)
- || typeName == QLatin1String(Constants::C_HEADER_MIMETYPE))
- return HeaderType;
- if (typeName == QLatin1String(Constants::RESOURCE_MIMETYPE))
- return ResourceType;
- if (typeName == QLatin1String(Constants::FORM_MIMETYPE))
- return FormType;
- 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 90e965ee33..b324dff4ec 100644
--- a/src/plugins/projectexplorer/projectnodes.h
+++ b/src/plugins/projectexplorer/projectnodes.h
@@ -214,18 +214,10 @@ public:
virtual bool removeSubProjects(const QStringList &proFilePaths) = 0;
- virtual bool addFiles(const FileType fileType,
- const QStringList &filePaths,
- QStringList *notAdded = 0) = 0;
- // TODO: Maybe remove fileType, can be detected by project
- virtual bool removeFiles(const FileType fileType,
- const QStringList &filePaths,
- QStringList *notRemoved = 0) = 0;
- virtual bool deleteFiles(const FileType fileType,
- const QStringList &filePaths) = 0;
- virtual bool renameFile(const FileType fileType,
- const QString &filePath,
- const QString &newFilePath) = 0;
+ virtual bool addFiles(const QStringList &filePaths, QStringList *notAdded = 0) = 0;
+ virtual bool removeFiles(const QStringList &filePaths, QStringList *notRemoved = 0) = 0;
+ virtual bool deleteFiles(const QStringList &filePaths) = 0;
+ virtual bool renameFile(const QString &filePath, const QString &newFilePath) = 0;
// by default returns false
virtual bool deploysFolder(const QString &folder) const;
@@ -343,7 +335,4 @@ private:
} // namespace ProjectExplorer
-// HACK: THERE SHOULD BE ONE PLACE TO MAKE THE FILE ENDING->FILE TYPE ASSOCIATION
-ProjectExplorer::FileType typeForFileName(const Core::MimeDatabase *db, const QFileInfo &file);
-
#endif // PROJECTNODES_H
diff --git a/src/plugins/projectexplorer/projecttreewidget.cpp b/src/plugins/projectexplorer/projecttreewidget.cpp
index 2df69b1bd6..66e69cf8ff 100644
--- a/src/plugins/projectexplorer/projecttreewidget.cpp
+++ b/src/plugins/projectexplorer/projecttreewidget.cpp
@@ -112,12 +112,12 @@ ProjectTreeWidget::ProjectTreeWidget(QWidget *parent)
m_autoSync(false),
m_autoExpand(true)
{
- m_model = new FlatModel(m_explorer->session()->sessionNode(), this);
- Project *pro = m_explorer->session()->startupProject();
+ m_model = new FlatModel(SessionManager::sessionNode(), this);
+ Project *pro = SessionManager::startupProject();
if (pro)
m_model->setStartupProject(pro->rootProjectNode());
NodesWatcher *watcher = new NodesWatcher(this);
- m_explorer->session()->sessionNode()->registerWatcher(watcher);
+ SessionManager::sessionNode()->registerWatcher(watcher);
connect(watcher, SIGNAL(foldersAboutToBeRemoved(FolderNode*,QList<FolderNode*>)),
this, SLOT(foldersAboutToBeRemoved(FolderNode*,QList<FolderNode*>)));
@@ -154,16 +154,18 @@ ProjectTreeWidget::ProjectTreeWidget(QWidget *parent)
this, SLOT(handleCurrentItemChange(QModelIndex)));
connect(m_view, SIGNAL(customContextMenuRequested(QPoint)),
this, SLOT(showContextMenu(QPoint)));
- connect(m_explorer->session(), SIGNAL(singleProjectAdded(ProjectExplorer::Project*)),
+
+ QObject *sessionManager = SessionManager::instance();
+ connect(sessionManager, SIGNAL(singleProjectAdded(ProjectExplorer::Project*)),
this, SLOT(handleProjectAdded(ProjectExplorer::Project*)));
- connect(m_explorer->session(), SIGNAL(startupProjectChanged(ProjectExplorer::Project*)),
+ connect(sessionManager, SIGNAL(startupProjectChanged(ProjectExplorer::Project*)),
this, SLOT(startupProjectChanged(ProjectExplorer::Project*)));
- connect(m_explorer->session(), SIGNAL(aboutToLoadSession(QString)),
+ connect(sessionManager, SIGNAL(aboutToLoadSession(QString)),
this, SLOT(disableAutoExpand()));
- connect(m_explorer->session(), SIGNAL(sessionLoaded(QString)),
+ connect(sessionManager, SIGNAL(sessionLoaded(QString)),
this, SLOT(loadExpandData()));
- connect(m_explorer->session(), SIGNAL(aboutToSaveSession()),
+ connect(sessionManager, SIGNAL(aboutToSaveSession()),
this, SLOT(saveExpandData()));
m_toggleSync = new QToolButton;
@@ -184,7 +186,7 @@ void ProjectTreeWidget::disableAutoExpand()
void ProjectTreeWidget::loadExpandData()
{
m_autoExpand = true;
- QStringList data = m_explorer->session()->value(QLatin1String("ProjectTree.ExpandData")).toStringList();
+ QStringList data = SessionManager::value(QLatin1String("ProjectTree.ExpandData")).toStringList();
recursiveLoadExpandData(m_view->rootIndex(), data.toSet());
}
@@ -203,7 +205,7 @@ void ProjectTreeWidget::saveExpandData()
QStringList data;
recursiveSaveExpandData(m_view->rootIndex(), &data);
// TODO if there are multiple ProjectTreeWidgets, the last one saves the data
- m_explorer->session()->setValue(QLatin1String("ProjectTree.ExpandData"), data);
+ SessionManager::setValue(QLatin1String("ProjectTree.ExpandData"), data);
}
void ProjectTreeWidget::recursiveSaveExpandData(const QModelIndex &index, QStringList *data)
@@ -373,7 +375,7 @@ void ProjectTreeWidget::openItem(const QModelIndex &mainIndex)
if (node->nodeType() != FileNodeType)
return;
IEditor *editor = EditorManager::openEditor(node->path());
- if (node->line() >= 0)
+ if (editor && node->line() >= 0)
editor->gotoLine(node->line());
}
@@ -420,7 +422,7 @@ int ProjectTreeWidgetFactory::priority() const
Id ProjectTreeWidgetFactory::id() const
{
- return Id("Projects");
+ return "Projects";
}
QKeySequence ProjectTreeWidgetFactory::activationSequence() const
diff --git a/src/plugins/projectexplorer/projectwelcomepage.cpp b/src/plugins/projectexplorer/projectwelcomepage.cpp
index 3faa2c603c..db71fccfa8 100644
--- a/src/plugins/projectexplorer/projectwelcomepage.cpp
+++ b/src/plugins/projectexplorer/projectwelcomepage.cpp
@@ -31,8 +31,8 @@
#include <utils/stringutils.h>
-#include <QDeclarativeEngine>
-#include <QDeclarativeContext>
+#include <QQmlContext>
+#include <QQmlEngine>
#include <QFileInfo>
#include <QDir>
@@ -40,7 +40,7 @@
#include <coreplugin/dialogs/iwizard.h>
#include <projectexplorer/session.h>
#include <projectexplorer/projectexplorer.h>
-#include <sessiondialog.h>
+#include <projectexplorer/sessiondialog.h>
#ifdef Q_OS_WIN
#include <utils/winutils.h>
@@ -49,8 +49,8 @@
namespace ProjectExplorer {
namespace Internal {
-SessionModel::SessionModel(SessionManager *manager, QObject *parent)
- : QAbstractListModel(parent), m_manager(manager)
+SessionModel::SessionModel(QObject *parent)
+ : QAbstractListModel(parent)
{
QHash<int, QByteArray> roleNames;
roleNames[Qt::DisplayRole] = "sessionName";
@@ -60,12 +60,12 @@ SessionModel::SessionModel(SessionManager *manager, QObject *parent)
roleNames[ProjectsPathRole] = "projectsPath";
roleNames[ProjectsDisplayRole] = "projectsName";
setRoleNames(roleNames);
- connect(manager, SIGNAL(sessionLoaded(QString)), SLOT(resetSessions()));
+ connect(SessionManager::instance(), SIGNAL(sessionLoaded(QString)), SLOT(resetSessions()));
}
int SessionModel::rowCount(const QModelIndex &) const
{
- return m_manager->sessions().count();
+ return SessionManager::sessions().count();
}
QStringList pathsToBaseNames(const QStringList &paths)
@@ -90,26 +90,26 @@ QVariant SessionModel::data(const QModelIndex &index, int role) const
{
if (role == Qt::DisplayRole || role == DefaultSessionRole ||
role == LastSessionRole || role == ActiveSessionRole || role == ProjectsPathRole || role == ProjectsDisplayRole) {
- QString sessionName = m_manager->sessions().at(index.row());
+ QString sessionName = SessionManager::sessions().at(index.row());
if (role == Qt::DisplayRole)
return sessionName;
else if (role == DefaultSessionRole)
- return m_manager->isDefaultSession(sessionName);
+ return SessionManager::isDefaultSession(sessionName);
else if (role == LastSessionRole)
- return m_manager->lastSession() == sessionName;
+ return SessionManager::lastSession() == sessionName;
else if (role == ActiveSessionRole)
- return m_manager->activeSession() == sessionName;
+ return SessionManager::activeSession() == sessionName;
else if (role == ProjectsPathRole)
- return pathsWithTildeHomePath(m_manager->projectsForSessionName(sessionName));
+ return pathsWithTildeHomePath(SessionManager::projectsForSessionName(sessionName));
else if (role == ProjectsDisplayRole)
- return pathsToBaseNames(m_manager->projectsForSessionName(sessionName));
+ return pathsToBaseNames(SessionManager::projectsForSessionName(sessionName));
}
return QVariant();
}
bool SessionModel::isDefaultVirgin() const
{
- return m_manager->isDefaultVirgin();
+ return SessionManager::isDefaultVirgin();
}
void SessionModel::resetSessions()
@@ -120,48 +120,48 @@ void SessionModel::resetSessions()
void SessionModel::cloneSession(const QString &session)
{
- SessionNameInputDialog newSessionInputDialog(m_manager->sessions(), 0);
+ SessionNameInputDialog newSessionInputDialog(SessionManager::sessions(), 0);
newSessionInputDialog.setWindowTitle(tr("New session name"));
newSessionInputDialog.setValue(session + QLatin1String(" (2)"));
if (newSessionInputDialog.exec() == QDialog::Accepted) {
QString newSession = newSessionInputDialog.value();
- if (newSession.isEmpty() || m_manager->sessions().contains(newSession))
+ if (newSession.isEmpty() || SessionManager::sessions().contains(newSession))
return;
beginResetModel();
- m_manager->cloneSession(session, newSession);
+ SessionManager::cloneSession(session, newSession);
endResetModel();
if (newSessionInputDialog.isSwitchToRequested())
- m_manager->loadSession(newSession);
+ SessionManager::loadSession(newSession);
}
}
void SessionModel::deleteSession(const QString &session)
{
- if (!m_manager->confirmSessionDelete(session))
+ if (!SessionManager::confirmSessionDelete(session))
return;
beginResetModel();
- m_manager->deleteSession(session);
+ SessionManager::deleteSession(session);
endResetModel();
}
void SessionModel::renameSession(const QString &session)
{
- SessionNameInputDialog newSessionInputDialog(m_manager->sessions(), 0);
+ SessionNameInputDialog newSessionInputDialog(SessionManager::sessions(), 0);
newSessionInputDialog.setWindowTitle(tr("New session name"));
newSessionInputDialog.setValue(session);
if (newSessionInputDialog.exec() == QDialog::Accepted) {
QString newSession = newSessionInputDialog.value();
- if (newSession.isEmpty() || m_manager->sessions().contains(newSession))
+ if (newSession.isEmpty() || SessionManager::sessions().contains(newSession))
return;
beginResetModel();
- m_manager->renameSession(session, newSession);
+ SessionManager::renameSession(session, newSession);
endResetModel();
if (newSessionInputDialog.isSwitchToRequested())
- m_manager->loadSession(newSession);
+ SessionManager::loadSession(newSession);
}
}
@@ -212,13 +212,12 @@ ProjectWelcomePage::ProjectWelcomePage() :
{
}
-void ProjectWelcomePage::facilitateQml(QDeclarativeEngine *engine)
+void ProjectWelcomePage::facilitateQml(QQmlEngine *engine)
{
- ProjectExplorerPlugin *pePlugin = ProjectExplorer::ProjectExplorerPlugin::instance();
- m_sessionModel = new SessionModel(pePlugin->session(), this);
- m_projectModel = new ProjectModel(pePlugin, this);
+ m_sessionModel = new SessionModel(this);
+ m_projectModel = new ProjectModel(ProjectExplorerPlugin::instance(), this);
- QDeclarativeContext *ctx = engine->rootContext();
+ QQmlContext *ctx = engine->rootContext();
ctx->setContextProperty(QLatin1String("sessionList"), m_sessionModel);
ctx->setContextProperty(QLatin1String("projectList"), m_projectModel);
ctx->setContextProperty(QLatin1String("projectWelcomePage"), this);
diff --git a/src/plugins/projectexplorer/projectwelcomepage.h b/src/plugins/projectexplorer/projectwelcomepage.h
index 01d6693774..96a6f6c027 100644
--- a/src/plugins/projectexplorer/projectwelcomepage.h
+++ b/src/plugins/projectexplorer/projectwelcomepage.h
@@ -35,13 +35,12 @@
#include <utils/iwelcomepage.h>
QT_BEGIN_NAMESPACE
-class QDeclarativeEngine;
+class QQmlEngine;
QT_END_NAMESPACE
namespace ProjectExplorer {
class ProjectExplorerPlugin;
-class SessionManager;
namespace Internal {
@@ -51,7 +50,7 @@ class SessionModel : public QAbstractListModel
public:
enum { DefaultSessionRole = Qt::UserRole+1, LastSessionRole, ActiveSessionRole, ProjectsPathRole, ProjectsDisplayRole };
- SessionModel(SessionManager* manager, QObject* parent = 0);
+ explicit SessionModel(QObject *parent = 0);
int rowCount(const QModelIndex &parent) const;
QVariant data(const QModelIndex &index, int role) const;
@@ -62,9 +61,6 @@ public slots:
void cloneSession(const QString &session);
void deleteSession(const QString &session);
void renameSession(const QString &session);
-
-private:
- SessionManager *m_manager;
};
@@ -91,7 +87,7 @@ class ProjectWelcomePage : public Utils::IWelcomePage
public:
ProjectWelcomePage();
- void facilitateQml(QDeclarativeEngine *engine);
+ void facilitateQml(QQmlEngine *engine);
QUrl pageLocation() const;
QWidget *page() { return 0; }
QString title() const { return tr("Develop"); }
diff --git a/src/plugins/projectexplorer/projectwindow.cpp b/src/plugins/projectexplorer/projectwindow.cpp
index c4a0891769..61d7289365 100644
--- a/src/plugins/projectexplorer/projectwindow.cpp
+++ b/src/plugins/projectexplorer/projectwindow.cpp
@@ -228,8 +228,6 @@ ProjectWindow::ProjectWindow(QWidget *parent)
m_currentWidget(0),
m_previousTargetSubIndex(-1)
{
- ProjectExplorer::SessionManager *session = ProjectExplorerPlugin::instance()->session();
-
// Setup overall layout:
QVBoxLayout *viewLayout = new QVBoxLayout(this);
viewLayout->setMargin(0);
@@ -242,19 +240,20 @@ ProjectWindow::ProjectWindow(QWidget *parent)
m_centralWidget = new QStackedWidget(this);
viewLayout->addWidget(m_centralWidget);
- // connects:
+ // Connections
connect(m_tabWidget, SIGNAL(currentIndexChanged(int,int)),
this, SLOT(showProperties(int,int)));
- connect(session, SIGNAL(projectAdded(ProjectExplorer::Project*)),
+ QObject *sessionManager = SessionManager::instance();
+ connect(sessionManager, SIGNAL(projectAdded(ProjectExplorer::Project*)),
this, SLOT(registerProject(ProjectExplorer::Project*)));
- connect(session, SIGNAL(aboutToRemoveProject(ProjectExplorer::Project*)),
+ connect(sessionManager, SIGNAL(aboutToRemoveProject(ProjectExplorer::Project*)),
this, SLOT(deregisterProject(ProjectExplorer::Project*)));
- connect(session, SIGNAL(startupProjectChanged(ProjectExplorer::Project*)),
+ connect(sessionManager, SIGNAL(startupProjectChanged(ProjectExplorer::Project*)),
this, SLOT(startupProjectChanged(ProjectExplorer::Project*)));
- connect(session, SIGNAL(projectDisplayNameChanged(ProjectExplorer::Project*)),
+ connect(sessionManager, SIGNAL(projectDisplayNameChanged(ProjectExplorer::Project*)),
this, SLOT(projectUpdated(ProjectExplorer::Project*)));
// Update properties to empty project for now:
@@ -274,7 +273,7 @@ void ProjectWindow::aboutToShutdown()
{
showProperties(-1, -1); // that's a bit stupid, but otherwise stuff is still
// connected to the session
- disconnect(ProjectExplorerPlugin::instance()->session(), 0, this, 0);
+ disconnect(SessionManager::instance(), 0, this, 0);
}
void ProjectWindow::removedTarget(Target *)
@@ -347,7 +346,7 @@ void ProjectWindow::registerProject(ProjectExplorer::Project *project)
}
m_tabIndexToProject.insert(index, project);
- m_tabWidget->insertTab(index, project->displayName(), project->document()->fileName(), subtabs);
+ m_tabWidget->insertTab(index, project->displayName(), project->projectFilePath(), subtabs);
connect(project, SIGNAL(removedTarget(ProjectExplorer::Target*)),
this, SLOT(removedTarget(ProjectExplorer::Target*)));
@@ -434,7 +433,7 @@ void ProjectWindow::showProperties(int index, int subIndex)
}
- ProjectExplorerPlugin::instance()->session()->setStartupProject(project);
+ SessionManager::setStartupProject(project);
}
void ProjectWindow::removeCurrentWidget()
diff --git a/src/plugins/projectexplorer/removetaskhandler.cpp b/src/plugins/projectexplorer/removetaskhandler.cpp
index 3138a25885..cf8f81c451 100644
--- a/src/plugins/projectexplorer/removetaskhandler.cpp
+++ b/src/plugins/projectexplorer/removetaskhandler.cpp
@@ -29,7 +29,6 @@
#include "removetaskhandler.h"
-#include "projectexplorer.h"
#include "task.h"
#include "taskhub.h"
@@ -39,7 +38,7 @@ using namespace ProjectExplorer::Internal;
void RemoveTaskHandler::handle(const ProjectExplorer::Task &task)
{
- ProjectExplorerPlugin::instance()->taskHub()->removeTask(task);
+ TaskHub::removeTask(task);
}
QAction *RemoveTaskHandler::createAction(QObject *parent) const
diff --git a/src/plugins/projectexplorer/runconfiguration.cpp b/src/plugins/projectexplorer/runconfiguration.cpp
index 43d53b742a..9f08ff1860 100644
--- a/src/plugins/projectexplorer/runconfiguration.cpp
+++ b/src/plugins/projectexplorer/runconfiguration.cpp
@@ -52,16 +52,6 @@
using namespace ProjectExplorer;
-namespace {
-
-const char USE_CPP_DEBUGGER_KEY[] = "RunConfiguration.UseCppDebugger";
-const char USE_QML_DEBUGGER_KEY[] = "RunConfiguration.UseQmlDebugger";
-const char USE_QML_DEBUGGER_AUTO_KEY[] = "RunConfiguration.UseQmlDebuggerAuto";
-const char QML_DEBUG_SERVER_PORT_KEY[] = "RunConfiguration.QmlDebugServerPort";
-const char USE_MULTIPROCESS_KEY[] = "RunConfiguration.UseMultiProcess";
-
-} // namespace
-
/*!
\class ProjectExplorer::ProcessHandle
\brief The ProcessHandle class is a helper class to describe a process.
@@ -103,16 +93,101 @@ bool ProcessHandle::equals(const ProcessHandle &rhs) const
return m_pid == rhs.m_pid;
}
+///////////////////////////////////////////////////////////////////////
+//
+// ISettingsAspect
+//
+///////////////////////////////////////////////////////////////////////
+
+ISettingsAspect *ISettingsAspect::clone() const
+{
+ ISettingsAspect *other = create();
+ QVariantMap data;
+ toMap(data);
+ other->fromMap(data);
+ return other;
+}
+
+///////////////////////////////////////////////////////////////////////
+//
+// IRunConfigurationAspect
+//
+///////////////////////////////////////////////////////////////////////
+
+IRunConfigurationAspect::IRunConfigurationAspect(RunConfiguration *parent)
+{
+ m_runConfiguration = parent;
+ m_projectSettings = 0;
+ m_globalSettings = 0;
+ m_useGlobalSettings = false;
+ connect(this, SIGNAL(requestRunActionsUpdate()), parent, SIGNAL(requestRunActionsUpdate()));
+}
+
+IRunConfigurationAspect::~IRunConfigurationAspect()
+{
+ delete m_projectSettings;
+}
/*!
Returns the widget used to configure this run configuration. Ownership is
transferred to the caller.
*/
+
RunConfigWidget *IRunConfigurationAspect::createConfigurationWidget()
{
return 0;
}
+void IRunConfigurationAspect::setProjectSettings(ISettingsAspect *settings)
+{
+ m_projectSettings = settings;
+}
+
+void IRunConfigurationAspect::setGlobalSettings(ISettingsAspect *settings)
+{
+ m_globalSettings = settings;
+}
+
+void IRunConfigurationAspect::setUsingGlobalSettings(bool value)
+{
+ m_useGlobalSettings = value;
+}
+
+ISettingsAspect *IRunConfigurationAspect::currentSettings() const
+{
+ return m_useGlobalSettings ? m_globalSettings : m_projectSettings;
+}
+
+void IRunConfigurationAspect::fromMap(const QVariantMap &map)
+{
+ m_projectSettings->fromMap(map);
+ m_useGlobalSettings = map.value(m_id.toString() + QLatin1String(".UseGlobalSettings"), true).toBool();
+}
+
+void IRunConfigurationAspect::toMap(QVariantMap &map) const
+{
+ m_projectSettings->toMap(map);
+ map.insert(m_id.toString() + QLatin1String(".UseGlobalSettings"), m_useGlobalSettings);
+}
+
+IRunConfigurationAspect *IRunConfigurationAspect::clone(RunConfiguration *parent) const
+{
+ IRunConfigurationAspect *other = create(parent);
+ if (m_projectSettings)
+ other->m_projectSettings = m_projectSettings->clone();
+ other->m_globalSettings = m_globalSettings;
+ other->m_useGlobalSettings = m_useGlobalSettings;
+ return other;
+}
+
+void IRunConfigurationAspect::resetProjectToGlobalSettings()
+{
+ QTC_ASSERT(m_globalSettings, return);
+ QVariantMap map;
+ m_globalSettings->toMap(map);
+ m_projectSettings->fromMap(map);
+}
+
/*!
\class ProjectExplorer::RunConfiguration
@@ -225,7 +300,7 @@ QVariantMap RunConfiguration::toMap() const
QVariantMap map = ProjectConfiguration::toMap();
foreach (IRunConfigurationAspect *aspect, m_aspects)
- map.unite(aspect->toMap());
+ aspect->toMap(map);
return map;
}
@@ -274,6 +349,14 @@ QList<IRunConfigurationAspect *> RunConfiguration::extraAspects() const
QTC_ASSERT(m_aspectsInitialized, return QList<IRunConfigurationAspect *>());
return m_aspects;
}
+IRunConfigurationAspect *RunConfiguration::extraAspect(Core::Id id) const
+{
+ QTC_ASSERT(m_aspectsInitialized, return 0);
+ foreach (IRunConfigurationAspect *aspect, m_aspects)
+ if (aspect->id() == id)
+ return aspect;
+ return 0;
+}
Utils::OutputFormatter *RunConfiguration::createOutputFormatter() const
{
@@ -347,7 +430,7 @@ RunConfiguration *IRunConfigurationFactory::restore(Target *parent, const QVaria
IRunConfigurationFactory *IRunConfigurationFactory::find(Target *parent, const QVariantMap &map)
{
QList<IRunConfigurationFactory *> factories
- = ExtensionSystem::PluginManager::instance()->getObjects<IRunConfigurationFactory>();
+ = ExtensionSystem::PluginManager::getObjects<IRunConfigurationFactory>();
foreach (IRunConfigurationFactory *factory, factories) {
if (factory->canRestore(parent, map))
return factory;
@@ -358,7 +441,7 @@ IRunConfigurationFactory *IRunConfigurationFactory::find(Target *parent, const Q
IRunConfigurationFactory *IRunConfigurationFactory::find(Target *parent, RunConfiguration *rc)
{
QList<IRunConfigurationFactory *> factories
- = ExtensionSystem::PluginManager::instance()->getObjects<IRunConfigurationFactory>();
+ = ExtensionSystem::PluginManager::getObjects<IRunConfigurationFactory>();
foreach (IRunConfigurationFactory *factory, factories) {
if (factory->canClone(parent, rc))
return factory;
@@ -369,7 +452,7 @@ IRunConfigurationFactory *IRunConfigurationFactory::find(Target *parent, RunConf
QList<IRunConfigurationFactory *> IRunConfigurationFactory::find(Target *parent)
{
QList<IRunConfigurationFactory *> factories
- = ExtensionSystem::PluginManager::instance()->getObjects<IRunConfigurationFactory>();
+ = ExtensionSystem::PluginManager::getObjects<IRunConfigurationFactory>();
QList<IRunConfigurationFactory *> result;
foreach (IRunConfigurationFactory *factory, factories) {
if (!factory->availableCreationIds(parent).isEmpty())
@@ -385,9 +468,8 @@ QList<IRunConfigurationFactory *> IRunConfigurationFactory::find(Target *parent)
run configuration.
*/
-
/*!
- \fn RunConfigWidget *ProjectExplorer::IRunControlFactory::createConfigurationWidget(RunConfiguration *runConfiguration)
+ \fn RunConfigWidget *ProjectExplorer::IRunConfigurationAspect::createConfigurationWidget()
Returns a widget used to configure this runner. Ownership is transferred to
the caller.
diff --git a/src/plugins/projectexplorer/runconfiguration.h b/src/plugins/projectexplorer/runconfiguration.h
index f51f8006b3..583ed05988 100644
--- a/src/plugins/projectexplorer/runconfiguration.h
+++ b/src/plugins/projectexplorer/runconfiguration.h
@@ -47,6 +47,7 @@ namespace Utils { class OutputFormatter; }
namespace ProjectExplorer {
class Abi;
class BuildConfiguration;
+class IRunConfigurationAspect;
class RunConfiguration;
class RunConfigWidget;
class RunControl;
@@ -72,19 +73,85 @@ private:
inline bool operator==(const ProcessHandle &p1, const ProcessHandle &p2) { return p1.equals(p2); }
inline bool operator!=(const ProcessHandle &p1, const ProcessHandle &p2) { return !p1.equals(p2); }
-class PROJECTEXPLORER_EXPORT IRunConfigurationAspect
+/**
+ * An interface for a hunk of global or per-project
+ * configuration data.
+ *
+ */
+
+class PROJECTEXPLORER_EXPORT ISettingsAspect : public QObject
{
+ Q_OBJECT
+
public:
- virtual ~IRunConfigurationAspect() {}
- virtual QVariantMap toMap() const = 0;
- virtual QString displayName() const = 0;
+ ISettingsAspect() {}
+
+ /// Create a configuration widget for this settings aspect.
+ virtual QWidget *createConfigWidget(QWidget *parent) = 0;
+ /// "Virtual default constructor"
+ virtual ISettingsAspect *create() const = 0;
+ /// "Virtual copy constructor"
+ ISettingsAspect *clone() const;
+
+protected:
+ ///
+ friend class IRunConfigurationAspect;
+ /// Converts current object into map for storage.
+ virtual void toMap(QVariantMap &map) const = 0;
+ /// Read object state from @p map.
+ virtual void fromMap(const QVariantMap &map) = 0;
+};
+
+
+/**
+ * An interface to facilitate switching between hunks of
+ * global and per-project configuration data.
+ *
+ */
+
+class PROJECTEXPLORER_EXPORT IRunConfigurationAspect : public QObject
+{
+ Q_OBJECT
- virtual IRunConfigurationAspect *clone(RunConfiguration *parent) const = 0;
+public:
+ explicit IRunConfigurationAspect(RunConfiguration *parent);
+ ~IRunConfigurationAspect();
+
+ virtual IRunConfigurationAspect *create(RunConfiguration *parent) const = 0;
+ virtual IRunConfigurationAspect *clone(RunConfiguration *parent) const;
virtual RunConfigWidget *createConfigurationWidget();
+ void setId(Core::Id id) { m_id = id; }
+ void setDisplayName(const QString &displayName) { m_displayName = displayName; }
+ void setProjectSettings(ISettingsAspect *settings);
+ void setGlobalSettings(ISettingsAspect *settings);
+
+ QString displayName() const { return m_displayName; }
+ Core::Id id() const { return m_id; }
+ bool isUsingGlobalSettings() const { return m_useGlobalSettings; }
+ void setUsingGlobalSettings(bool value);
+ void resetProjectToGlobalSettings();
+
+ ISettingsAspect *projectSettings() const { return m_projectSettings; }
+ ISettingsAspect *globalSettings() const { return m_globalSettings; }
+ ISettingsAspect *currentSettings() const;
+ RunConfiguration *runConfiguration() const { return m_runConfiguration; }
+
+signals:
+ void requestRunActionsUpdate();
+
protected:
friend class RunConfiguration;
- virtual void fromMap(const QVariantMap &map) = 0;
+ virtual void fromMap(const QVariantMap &map);
+ virtual void toMap(QVariantMap &data) const;
+
+private:
+ Core::Id m_id;
+ QString m_displayName;
+ bool m_useGlobalSettings;
+ RunConfiguration *m_runConfiguration;
+ ISettingsAspect *m_projectSettings; // Owned if present.
+ ISettingsAspect *m_globalSettings; // Not owned.
};
// Documentation inside.
@@ -110,17 +177,15 @@ public:
QVariantMap toMap() const;
QList<IRunConfigurationAspect *> extraAspects() const;
+ IRunConfigurationAspect *extraAspect(Core::Id id) const;
+
template <typename T> T *extraAspect() const
{
QTC_ASSERT(m_aspectsInitialized, return 0);
- IRunConfigurationAspect *typeCheck = static_cast<T *>(0);
- Q_UNUSED(typeCheck);
- T *result = 0;
- foreach (IRunConfigurationAspect *a, m_aspects) {
- if ((result = dynamic_cast<T *>(a)) != 0)
- break;
- }
- return result;
+ foreach (IRunConfigurationAspect *aspect, m_aspects)
+ if (T *result = qobject_cast<T *>(aspect))
+ return result;
+ return 0;
}
virtual ProjectExplorer::Abi abi() const;
diff --git a/src/plugins/projectexplorer/runsettingspropertiespage.cpp b/src/plugins/projectexplorer/runsettingspropertiespage.cpp
index edb8e26046..0cf020a9c7 100644
--- a/src/plugins/projectexplorer/runsettingspropertiespage.cpp
+++ b/src/plugins/projectexplorer/runsettingspropertiespage.cpp
@@ -273,16 +273,22 @@ RunSettingsWidget::~RunSettingsWidget()
{
}
+static bool actionLessThan(const QAction *action1, const QAction *action2)
+{
+ return action1->text() < action2->text();
+}
void RunSettingsWidget::aboutToShowAddMenu()
{
m_addRunMenu->clear();
QList<IRunConfigurationFactory *> factories =
ExtensionSystem::PluginManager::getObjects<IRunConfigurationFactory>();
+
+ QList<QAction *> menuActions;
foreach (IRunConfigurationFactory *factory, factories) {
QList<Core::Id> ids = factory->availableCreationIds(m_target);
foreach (Core::Id id, ids) {
- QAction *action = m_addRunMenu->addAction(factory->displayNameForId(id));;
+ QAction *action = new QAction(factory->displayNameForId(id), m_addRunMenu);
FactoryAndId fai;
fai.factory = factory;
fai.id = id;
@@ -291,8 +297,13 @@ void RunSettingsWidget::aboutToShowAddMenu()
action->setData(v);
connect(action, SIGNAL(triggered()),
this, SLOT(addRunConfiguration()));
+ menuActions.append(action);
}
}
+
+ qSort(menuActions.begin(), menuActions.end(), actionLessThan);
+ foreach (QAction *action, menuActions)
+ m_addRunMenu->addAction(action);
}
void RunSettingsWidget::addRunConfiguration()
@@ -425,8 +436,7 @@ void RunSettingsWidget::addDeployConfiguration()
void RunSettingsWidget::removeDeployConfiguration()
{
DeployConfiguration *dc = m_target->activeDeployConfiguration();
- ProjectExplorer::BuildManager *bm = ProjectExplorerPlugin::instance()->buildManager();
- if (bm->isBuilding(dc)) {
+ if (BuildManager::isBuilding(dc)) {
QMessageBox box;
QPushButton *closeAnyway = box.addButton(tr("Cancel Build && Remove Deploy Configuration"), QMessageBox::AcceptRole);
QPushButton *cancelClose = box.addButton(tr("Do Not Remove"), QMessageBox::RejectRole);
@@ -437,7 +447,7 @@ void RunSettingsWidget::removeDeployConfiguration()
box.exec();
if (box.clickedButton() != closeAnyway)
return;
- bm->cancel();
+ BuildManager::cancel();
} else {
QMessageBox msgBox(QMessageBox::Question, tr("Remove Deploy Configuration?"),
tr("Do you really want to delete deploy configuration <b>%1</b>?").arg(dc->displayName()),
diff --git a/src/plugins/projectexplorer/session.cpp b/src/plugins/projectexplorer/session.cpp
index ae7c3bde35..eb9c60378a 100644
--- a/src/plugins/projectexplorer/session.cpp
+++ b/src/plugins/projectexplorer/session.cpp
@@ -53,17 +53,14 @@
#include <QMessageBox>
#include <QPushButton>
-namespace {
- bool debug = false;
-}
+namespace { bool debug = false; }
using namespace Core;
-using Utils::PersistentSettingsReader;
-using Utils::PersistentSettingsWriter;
-
-using namespace ProjectExplorer;
+using namespace Utils;
using namespace ProjectExplorer::Internal;
+namespace ProjectExplorer {
+
/*!
\class ProjectExplorer::SessionManager
@@ -75,44 +72,92 @@ using namespace ProjectExplorer::Internal;
This could be improved.
*/
+class SessionManagerPrivate
+{
+public:
+ SessionManagerPrivate() :
+ m_sessionName(QLatin1String("default")),
+ m_virginSession(true),
+ m_loadingSession(false),
+ m_startupProject(0),
+ m_writer(0)
+ {}
+
+ bool projectContainsFile(Project *p, const QString &fileName) const;
+ void restoreValues(const PersistentSettingsReader &reader);
+ void restoreDependencies(const PersistentSettingsReader &reader);
+ void restoreStartupProject(const PersistentSettingsReader &reader);
+ void restoreEditors(const PersistentSettingsReader &reader);
+ void restoreProjects(const QStringList &fileList);
+ void askUserAboutFailedProjects();
+ void sessionLoadingProgress();
+
+ bool recursiveDependencyCheck(const QString &newDep, const QString &checkDep) const;
+ QStringList dependencies(const QString &proName) const;
+ QStringList dependenciesOrder() const;
+ void dependencies(const QString &proName, QStringList &result) const;
+
+public:
+ SessionNode *m_sessionNode;
+ QString m_sessionName;
+ bool m_virginSession;
+
+ mutable QStringList m_sessions;
+
+ mutable QHash<Project *, QStringList> m_projectFileCache;
+ bool m_loadingSession;
+
+ Project *m_startupProject;
+ QList<Project *> m_projects;
+ QStringList m_failedProjects;
+ QMap<QString, QStringList> m_depMap;
+ QMap<QString, QVariant> m_values;
+ QFutureInterface<void> m_future;
+ PersistentSettingsWriter *m_writer;
+};
+
+static SessionManager *m_instance = 0;
+static SessionManagerPrivate *d = 0;
+
SessionManager::SessionManager(QObject *parent)
- : QObject(parent),
- m_sessionNode(new SessionNode(this)),
- m_sessionName(QLatin1String("default")),
- m_virginSession(true),
- m_loadingSession(false),
- m_startupProject(0),
- m_writer(0)
+ : QObject(parent)
{
+ m_instance = this;
+ d = new SessionManagerPrivate;
+
+ d->m_sessionNode = new SessionNode(this);
+
connect(ModeManager::instance(), SIGNAL(currentModeChanged(Core::IMode*)),
this, SLOT(saveActiveMode(Core::IMode*)));
- EditorManager *em = ICore::editorManager();
-
- connect(em, SIGNAL(editorCreated(Core::IEditor*,QString)),
+ connect(EditorManager::instance(), SIGNAL(editorCreated(Core::IEditor*,QString)),
this, SLOT(configureEditor(Core::IEditor*,QString)));
connect(ProjectExplorerPlugin::instance(), SIGNAL(currentProjectChanged(ProjectExplorer::Project*)),
this, SLOT(updateWindowTitle()));
- connect(em, SIGNAL(editorOpened(Core::IEditor*)),
+ connect(EditorManager::instance(), SIGNAL(editorOpened(Core::IEditor*)),
this, SLOT(markSessionFileDirty()));
- connect(em, SIGNAL(editorsClosed(QList<Core::IEditor*>)),
+ connect(EditorManager::instance(), SIGNAL(editorsClosed(QList<Core::IEditor*>)),
this, SLOT(markSessionFileDirty()));
}
SessionManager::~SessionManager()
{
- emit aboutToUnloadSession(m_sessionName);
- delete m_writer;
+ emit m_instance->aboutToUnloadSession(d->m_sessionName);
+ delete d->m_writer;
+ delete d;
}
+QObject *SessionManager::instance()
+{
+ return m_instance;
+}
-bool SessionManager::isDefaultVirgin() const
+bool SessionManager::isDefaultVirgin()
{
- return isDefaultSession(m_sessionName)
- && m_virginSession;
+ return isDefaultSession(d->m_sessionName) && d->m_virginSession;
}
-bool SessionManager::isDefaultSession(const QString &session) const
+bool SessionManager::isDefaultSession(const QString &session)
{
return session == QLatin1String("default");
}
@@ -127,22 +172,21 @@ void SessionManager::clearProjectFileCache()
{
// If triggered by the fileListChanged signal of one project
// only invalidate cache for this project
- Project *pro = qobject_cast<Project*>(sender());
+ Project *pro = qobject_cast<Project*>(m_instance->sender());
if (pro)
- m_projectFileCache.remove(pro);
+ d->m_projectFileCache.remove(pro);
else
- m_projectFileCache.clear();
+ d->m_projectFileCache.clear();
}
-bool SessionManager::recursiveDependencyCheck(const QString &newDep, const QString &checkDep) const
+bool SessionManagerPrivate::recursiveDependencyCheck(const QString &newDep, const QString &checkDep) const
{
if (newDep == checkDep)
return false;
- foreach (const QString &dependency, m_depMap.value(checkDep)) {
+ foreach (const QString &dependency, m_depMap.value(checkDep))
if (!recursiveDependencyCheck(newDep, dependency))
return false;
- }
return true;
}
@@ -154,10 +198,10 @@ bool SessionManager::recursiveDependencyCheck(const QString &newDep, const QStri
* filenames when saving.
*/
-QList<Project *> SessionManager::dependencies(const Project *project) const
+QList<Project *> SessionManager::dependencies(const Project *project)
{
- const QString &proName = project->document()->fileName();
- const QStringList &proDeps = m_depMap.value(proName);
+ const QString proName = project->projectFilePath();
+ const QStringList proDeps = d->m_depMap.value(proName);
QList<Project *> projects;
foreach (const QString &dep, proDeps) {
@@ -168,54 +212,54 @@ QList<Project *> SessionManager::dependencies(const Project *project) const
return projects;
}
-bool SessionManager::hasDependency(const Project *project, const Project *depProject) const
+bool SessionManager::hasDependency(const Project *project, const Project *depProject)
{
- const QString &proName = project->document()->fileName();
- const QString &depName = depProject->document()->fileName();
+ const QString proName = project->projectFilePath();
+ const QString depName = depProject->projectFilePath();
- const QStringList &proDeps = m_depMap.value(proName);
+ const QStringList proDeps = d->m_depMap.value(proName);
return proDeps.contains(depName);
}
-bool SessionManager::canAddDependency(const Project *project, const Project *depProject) const
+bool SessionManager::canAddDependency(const Project *project, const Project *depProject)
{
- const QString &newDep = project->document()->fileName();
- const QString &checkDep = depProject->document()->fileName();
+ const QString newDep = project->projectFilePath();
+ const QString checkDep = depProject->projectFilePath();
- return recursiveDependencyCheck(newDep, checkDep);
+ return d->recursiveDependencyCheck(newDep, checkDep);
}
bool SessionManager::addDependency(Project *project, Project *depProject)
{
- const QString &proName = project->document()->fileName();
- const QString &depName = depProject->document()->fileName();
+ const QString proName = project->projectFilePath();
+ const QString depName = depProject->projectFilePath();
// check if this dependency is valid
- if (!recursiveDependencyCheck(proName, depName))
+ if (!d->recursiveDependencyCheck(proName, depName))
return false;
- QStringList proDeps = m_depMap.value(proName);
+ QStringList proDeps = d->m_depMap.value(proName);
if (!proDeps.contains(depName)) {
proDeps.append(depName);
- m_depMap[proName] = proDeps;
+ d->m_depMap[proName] = proDeps;
}
- emit dependencyChanged(project, depProject);
+ emit m_instance->dependencyChanged(project, depProject);
return true;
}
void SessionManager::removeDependency(Project *project, Project *depProject)
{
- const QString &proName = project->document()->fileName();
- const QString &depName = depProject->document()->fileName();
+ const QString proName = project->projectFilePath();
+ const QString depName = depProject->projectFilePath();
- QStringList proDeps = m_depMap.value(proName);
+ QStringList proDeps = d->m_depMap.value(proName);
proDeps.removeAll(depName);
if (proDeps.isEmpty())
- m_depMap.remove(proName);
+ d->m_depMap.remove(proName);
else
- m_depMap[proName] = proDeps;
- emit dependencyChanged(project, depProject);
+ d->m_depMap[proName] = proDeps;
+ emit m_instance->dependencyChanged(project, depProject);
}
void SessionManager::setStartupProject(Project *startupProject)
@@ -224,19 +268,19 @@ void SessionManager::setStartupProject(Project *startupProject)
qDebug() << Q_FUNC_INFO << (startupProject ? startupProject->displayName() : QLatin1String("0"));
if (startupProject) {
- Q_ASSERT(m_projects.contains(startupProject));
+ Q_ASSERT(d->m_projects.contains(startupProject));
}
- if (m_startupProject == startupProject)
+ if (d->m_startupProject == startupProject)
return;
- m_startupProject = startupProject;
- emit startupProjectChanged(startupProject);
+ d->m_startupProject = startupProject;
+ emit m_instance->startupProjectChanged(startupProject);
}
-Project *SessionManager::startupProject() const
+Project *SessionManager::startupProject()
{
- return m_startupProject;
+ return d->m_startupProject;
}
void SessionManager::addProject(Project *project)
@@ -246,36 +290,35 @@ void SessionManager::addProject(Project *project)
void SessionManager::addProjects(const QList<Project*> &projects)
{
- m_virginSession = false;
+ d->m_virginSession = false;
QList<Project*> clearedList;
foreach (Project *pro, projects) {
- if (!m_projects.contains(pro)) {
+ if (!d->m_projects.contains(pro)) {
clearedList.append(pro);
- m_projects.append(pro);
- m_sessionNode->addProjectNodes(QList<ProjectNode *>() << pro->rootProjectNode());
+ d->m_projects.append(pro);
+ d->m_sessionNode->addProjectNodes(QList<ProjectNode *>() << pro->rootProjectNode());
connect(pro, SIGNAL(fileListChanged()),
- this, SLOT(clearProjectFileCache()));
+ m_instance, SLOT(clearProjectFileCache()));
connect(pro, SIGNAL(displayNameChanged()),
- this, SLOT(projectDisplayNameChanged()));
+ m_instance, SLOT(projectDisplayNameChanged()));
if (debug)
qDebug() << "SessionManager - adding project " << pro->displayName();
}
}
- foreach (Project *pro, clearedList) {
- emit projectAdded(pro);
- }
+ foreach (Project *pro, clearedList)
+ emit m_instance->projectAdded(pro);
if (clearedList.count() == 1)
- emit singleProjectAdded(clearedList.first());
+ emit m_instance->singleProjectAdded(clearedList.first());
}
void SessionManager::removeProject(Project *project)
{
- m_virginSession = false;
+ d->m_virginSession = false;
if (project == 0) {
qDebug() << "SessionManager::removeProject(0) ... THIS SHOULD NOT HAPPEN";
return;
@@ -285,28 +328,28 @@ void SessionManager::removeProject(Project *project)
bool SessionManager::loadingSession()
{
- return m_loadingSession;
+ return d->m_loadingSession;
}
bool SessionManager::save()
{
if (debug)
- qDebug() << "SessionManager - saving session" << m_sessionName;
+ qDebug() << "SessionManager - saving session" << d->m_sessionName;
- emit aboutToSaveSession();
+ emit m_instance->aboutToSaveSession();
- if (!m_writer || m_writer->fileName() != sessionNameToFileName(m_sessionName)) {
- delete m_writer;
- m_writer = new Utils::PersistentSettingsWriter(sessionNameToFileName(m_sessionName),
+ if (!d->m_writer || d->m_writer->fileName() != sessionNameToFileName(d->m_sessionName)) {
+ delete d->m_writer;
+ d->m_writer = new PersistentSettingsWriter(sessionNameToFileName(d->m_sessionName),
QLatin1String("QtCreatorSession"));
}
QVariantMap data;
// save the startup project
- if (m_startupProject)
- data.insert(QLatin1String("StartupProject"), m_startupProject->document()->fileName());
+ if (d->m_startupProject)
+ data.insert(QLatin1String("StartupProject"), d->m_startupProject->projectFilePath());
- QColor c = Utils::StyleHelper::requestedBaseColor();
+ QColor c = StyleHelper::requestedBaseColor();
if (c.isValid()) {
QString tmp = QString::fromLatin1("#%1%2%3")
.arg(c.red(), 2, 16, QLatin1Char('0'))
@@ -316,20 +359,20 @@ bool SessionManager::save()
}
QStringList projectFiles;
- foreach (Project *pro, m_projects)
- projectFiles << pro->document()->fileName();
+ foreach (Project *pro, d->m_projects)
+ projectFiles << pro->projectFilePath();
// Restore infromation on projects that failed to load:
// don't readd projects to the list, which the user loaded
- foreach (const QString &failed, m_failedProjects)
+ foreach (const QString &failed, d->m_failedProjects)
if (!projectFiles.contains(failed))
projectFiles << failed;
data.insert(QLatin1String("ProjectList"), projectFiles);
QMap<QString, QVariant> depMap;
- QMap<QString, QStringList>::const_iterator i = m_depMap.constBegin();
- while (i != m_depMap.constEnd()) {
+ QMap<QString, QStringList>::const_iterator i = d->m_depMap.constBegin();
+ while (i != d->m_depMap.constEnd()) {
QString key = i.key();
QStringList values;
foreach (const QString &value, i.value()) {
@@ -339,31 +382,21 @@ bool SessionManager::save()
++i;
}
data.insert(QLatin1String("ProjectDependencies"), QVariant(depMap));
+ data.insert(QLatin1String("EditorSettings"), EditorManager::saveState().toBase64());
- int editorCount = 0;
- QList<Core::IEditor *> editors = ICore::editorManager()->openedEditors();
- foreach (Core::IEditor *editor, editors) {
- Q_ASSERT(editor);
- if (!editor->isTemporary())
- ++editorCount;
- }
- data.insert(QLatin1String("OpenEditors"), editorCount);
- data.insert(QLatin1String("EditorSettings"), ICore::editorManager()->saveState().toBase64());
-
- QMap<QString, QVariant>::const_iterator it, end;
- end = m_values.constEnd();
+ QMap<QString, QVariant>::const_iterator it, end = d->m_values.constEnd();
QStringList keys;
- for (it = m_values.constBegin(); it != end; ++it) {
+ for (it = d->m_values.constBegin(); it != end; ++it) {
data.insert(QLatin1String("value-") + it.key(), it.value());
keys << it.key();
}
data.insert(QLatin1String("valueKeys"), keys);
- bool result = m_writer->save(data, Core::ICore::mainWindow());
+ bool result = d->m_writer->save(data, Core::ICore::mainWindow());
if (!result) {
QMessageBox::warning(0, tr("Error while saving session"),
- tr("Could not save session to file %1").arg(m_writer->fileName().toUserOutput()));
+ tr("Could not save session to file %1").arg(d->m_writer->fileName().toUserOutput()));
}
if (debug)
@@ -381,19 +414,24 @@ void SessionManager::closeAllProjects()
removeProjects(projects());
}
-const QList<Project *> &SessionManager::projects() const
+const QList<Project *> &SessionManager::projects()
+{
+ return d->m_projects;
+}
+
+bool SessionManager::hasProjects()
{
- return m_projects;
+ return !d->m_projects.isEmpty();
}
-QStringList SessionManager::dependencies(const QString &proName) const
+QStringList SessionManagerPrivate::dependencies(const QString &proName) const
{
QStringList result;
dependencies(proName, result);
return result;
}
-void SessionManager::dependencies(const QString &proName, QStringList &result) const
+void SessionManagerPrivate::dependencies(const QString &proName, QStringList &result) const
{
QStringList depends = m_depMap.value(proName);
@@ -404,16 +442,15 @@ void SessionManager::dependencies(const QString &proName, QStringList &result) c
result.append(proName);
}
-QStringList SessionManager::dependenciesOrder() const
+QStringList SessionManagerPrivate::dependenciesOrder() const
{
QList<QPair<QString, QStringList> > unordered;
QStringList ordered;
// copy the map to a temporary list
- foreach (Project *pro, projects()) {
- const QString &proName = pro->document()->fileName();
- unordered << QPair<QString, QStringList>
- (proName, m_depMap.value(proName));
+ foreach (Project *pro, m_projects) {
+ const QString &proName = pro->projectFilePath();
+ unordered << QPair<QString, QStringList>(proName, m_depMap.value(proName));
}
while (!unordered.isEmpty()) {
@@ -438,19 +475,19 @@ QStringList SessionManager::dependenciesOrder() const
return ordered;
}
-QList<Project *> SessionManager::projectOrder(Project *project) const
+QList<Project *> SessionManager::projectOrder(Project *project)
{
QList<Project *> result;
QStringList pros;
if (project)
- pros = dependencies(project->document()->fileName());
+ pros = d->dependencies(project->projectFilePath());
else
- pros = dependenciesOrder();
+ pros = d->dependenciesOrder();
foreach (const QString &proFile, pros) {
foreach (Project *pro, projects()) {
- if (pro->document()->fileName() == proFile) {
+ if (pro->projectFilePath() == proFile) {
result << pro;
break;
}
@@ -460,37 +497,33 @@ QList<Project *> SessionManager::projectOrder(Project *project) const
return result;
}
-Project *SessionManager::projectForNode(Node *node) const
+Project *SessionManager::projectForNode(Node *node)
{
if (!node)
return 0;
- Project *project = 0;
-
FolderNode *rootProjectNode = qobject_cast<FolderNode*>(node);
if (!rootProjectNode)
rootProjectNode = node->parentFolderNode();
- while (rootProjectNode && rootProjectNode->parentFolderNode() != m_sessionNode)
+
+ while (rootProjectNode && rootProjectNode->parentFolderNode() != d->m_sessionNode)
rootProjectNode = rootProjectNode->parentFolderNode();
Q_ASSERT(rootProjectNode);
- QList<Project *> projectList = projects();
- foreach (Project *p, projectList) {
- if (p->rootProjectNode() == rootProjectNode) {
- project = p;
- break;
- }
- }
+ foreach (Project *p, d->m_projects)
+ if (p->rootProjectNode() == rootProjectNode)
+ return p;
- return project;
+ return 0;
}
-Node *SessionManager::nodeForFile(const QString &fileName, Project *project) const
+Node *SessionManager::nodeForFile(const QString &fileName, Project *project)
{
Node *node = 0;
if (!project)
project = projectForFile(fileName);
+
if (project) {
FindNodesForFileVisitor findNodes(fileName);
project->rootProjectNode()->accept(&findNodes);
@@ -505,7 +538,7 @@ Node *SessionManager::nodeForFile(const QString &fileName, Project *project) con
return node;
}
-Project *SessionManager::projectForFile(const QString &fileName) const
+Project *SessionManager::projectForFile(const QString &fileName)
{
if (debug)
qDebug() << "SessionManager::projectForFile(" << fileName << ")";
@@ -514,16 +547,17 @@ Project *SessionManager::projectForFile(const QString &fileName) const
// Check current project first
Project *currentProject = ProjectExplorerPlugin::currentProject();
- if (currentProject && projectContainsFile(currentProject, fileName))
+ if (currentProject && d->projectContainsFile(currentProject, fileName))
return currentProject;
foreach (Project *p, projectList)
- if (p != currentProject && projectContainsFile(p, fileName))
+ if (p != currentProject && d->projectContainsFile(p, fileName))
return p;
+
return 0;
}
-bool SessionManager::projectContainsFile(Project *p, const QString &fileName) const
+bool SessionManagerPrivate::projectContainsFile(Project *p, const QString &fileName) const
{
if (!m_projectFileCache.contains(p))
m_projectFileCache.insert(p, p->files(Project::AllFiles));
@@ -543,16 +577,16 @@ void SessionManager::configureEditor(Core::IEditor *editor, const QString &fileN
void SessionManager::updateWindowTitle()
{
- if (isDefaultSession(m_sessionName)) {
+ if (isDefaultSession(d->m_sessionName)) {
if (Project *currentProject = ProjectExplorerPlugin::currentProject())
- ICore::editorManager()->setWindowTitleAddition(currentProject->displayName());
+ EditorManager::setWindowTitleAddition(currentProject->displayName());
else
- ICore::editorManager()->setWindowTitleAddition(QString());
+ EditorManager::setWindowTitleAddition(QString());
} else {
- QString sessionName = m_sessionName;
+ QString sessionName = d->m_sessionName;
if (sessionName.isEmpty())
sessionName = tr("Untitled");
- ICore::editorManager()->setWindowTitleAddition(sessionName);
+ EditorManager::setWindowTitleAddition(sessionName);
}
}
@@ -563,7 +597,7 @@ void SessionManager::removeProjects(QList<Project *> remove)
foreach (Project *pro, remove) {
if (debug)
qDebug() << "SessionManager - emitting aboutToRemoveProject(" << pro->displayName() << ")";
- emit aboutToRemoveProject(pro);
+ emit m_instance->aboutToRemoveProject(pro);
}
@@ -571,13 +605,13 @@ void SessionManager::removeProjects(QList<Project *> remove)
QSet<QString> projectFiles;
foreach (Project *pro, projects()) {
if (!remove.contains(pro))
- projectFiles.insert(pro->document()->fileName());
+ projectFiles.insert(pro->projectFilePath());
}
QSet<QString>::const_iterator i = projectFiles.begin();
while (i != projectFiles.end()) {
QStringList dependencies;
- foreach (const QString &dependency, m_depMap.value(*i)) {
+ foreach (const QString &dependency, d->m_depMap.value(*i)) {
if (projectFiles.contains(dependency))
dependencies << dependency;
}
@@ -586,32 +620,31 @@ void SessionManager::removeProjects(QList<Project *> remove)
++i;
}
- m_depMap = resMap;
+ d->m_depMap = resMap;
// TODO: Clear m_modelProjectHash
// Delete projects
foreach (Project *pro, remove) {
pro->saveSettings();
- m_projects.removeOne(pro);
+ d->m_projects.removeOne(pro);
- if (pro == m_startupProject)
+ if (pro == d->m_startupProject)
setStartupProject(0);
- disconnect(pro, SIGNAL(fileListChanged()),
- this, SLOT(clearProjectFileCache()));
- m_projectFileCache.remove(pro);
+ disconnect(pro, SIGNAL(fileListChanged()), m_instance, SLOT(clearProjectFileCache()));
+ d->m_projectFileCache.remove(pro);
if (debug)
qDebug() << "SessionManager - emitting projectRemoved(" << pro->displayName() << ")";
- m_sessionNode->removeProjectNodes(QList<ProjectNode *>() << pro->rootProjectNode());
- emit projectRemoved(pro);
+ d->m_sessionNode->removeProjectNodes(QList<ProjectNode *>() << pro->rootProjectNode());
+ emit m_instance->projectRemoved(pro);
delete pro;
}
if (startupProject() == 0)
- if (!m_projects.isEmpty())
- setStartupProject(m_projects.first());
+ if (!d->m_projects.isEmpty())
+ setStartupProject(d->m_projects.first());
}
/*!
@@ -620,41 +653,41 @@ void SessionManager::removeProjects(QList<Project *> remove)
void SessionManager::setValue(const QString &name, const QVariant &value)
{
- if (m_values.value(name) == value)
+ if (d->m_values.value(name) == value)
return;
- m_values.insert(name, value);
+ d->m_values.insert(name, value);
markSessionFileDirty(false);
}
QVariant SessionManager::value(const QString &name)
{
- QMap<QString, QVariant>::const_iterator it = m_values.find(name);
- return (it == m_values.constEnd()) ? QVariant() : *it;
+ QMap<QString, QVariant>::const_iterator it = d->m_values.find(name);
+ return (it == d->m_values.constEnd()) ? QVariant() : *it;
}
-QString SessionManager::activeSession() const
+QString SessionManager::activeSession()
{
- return m_sessionName;
+ return d->m_sessionName;
}
-QStringList SessionManager::sessions() const
+QStringList SessionManager::sessions()
{
- if (m_sessions.isEmpty()) {
+ if (d->m_sessions.isEmpty()) {
// We are not initialized yet, so do that now
QDir sessionDir(Core::ICore::userResourcePath());
QList<QFileInfo> sessionFiles = sessionDir.entryInfoList(QStringList() << QLatin1String("*.qws"), QDir::NoFilter, QDir::Time);
- Q_FOREACH(const QFileInfo& fileInfo, sessionFiles) {
+ foreach (const QFileInfo &fileInfo, sessionFiles) {
if (fileInfo.completeBaseName() != QLatin1String("default"))
- m_sessions << fileInfo.completeBaseName();
+ d->m_sessions << fileInfo.completeBaseName();
}
- m_sessions.prepend(QLatin1String("default"));
+ d->m_sessions.prepend(QLatin1String("default"));
}
- return m_sessions;
+ return d->m_sessions;
}
-Utils::FileName SessionManager::sessionNameToFileName(const QString &session) const
+FileName SessionManager::sessionNameToFileName(const QString &session)
{
- return Utils::FileName::fromString(ICore::userResourcePath() + QLatin1Char('/') + session + QLatin1String(".qws"));
+ return FileName::fromString(ICore::userResourcePath() + QLatin1Char('/') + session + QLatin1String(".qws"));
}
/*!
@@ -665,8 +698,8 @@ bool SessionManager::createSession(const QString &session)
{
if (sessions().contains(session))
return false;
- Q_ASSERT(m_sessions.size() > 0);
- m_sessions.insert(1, session);
+ Q_ASSERT(d->m_sessions.size() > 0);
+ d->m_sessions.insert(1, session);
return true;
}
@@ -696,9 +729,9 @@ bool SessionManager::confirmSessionDelete(const QString &session)
*/
bool SessionManager::deleteSession(const QString &session)
{
- if (!m_sessions.contains(session))
+ if (!d->m_sessions.contains(session))
return false;
- m_sessions.removeOne(session);
+ d->m_sessions.removeOne(session);
QFile fi(sessionNameToFileName(session).toString());
if (fi.exists())
return fi.remove();
@@ -707,29 +740,29 @@ bool SessionManager::deleteSession(const QString &session)
bool SessionManager::cloneSession(const QString &original, const QString &clone)
{
- if (!m_sessions.contains(original))
+ if (!d->m_sessions.contains(original))
return false;
QFile fi(sessionNameToFileName(original).toString());
// If the file does not exist, we can still clone
if (!fi.exists() || fi.copy(sessionNameToFileName(clone).toString())) {
- Q_ASSERT(m_sessions.size() > 0);
- m_sessions.insert(1, clone);
+ Q_ASSERT(d->m_sessions.size() > 0);
+ d->m_sessions.insert(1, clone);
return true;
}
return false;
}
-void SessionManager::restoreValues(const Utils::PersistentSettingsReader &reader)
+void SessionManagerPrivate::restoreValues(const PersistentSettingsReader &reader)
{
- const QStringList &keys = reader.restoreValue(QLatin1String("valueKeys")).toStringList();
+ const QStringList keys = reader.restoreValue(QLatin1String("valueKeys")).toStringList();
foreach (const QString &key, keys) {
QVariant value = reader.restoreValue(QLatin1String("value-") + key);
m_values.insert(key, value);
}
}
-void SessionManager::restoreDependencies(const Utils::PersistentSettingsReader &reader)
+void SessionManagerPrivate::restoreDependencies(const PersistentSettingsReader &reader)
{
QMap<QString, QVariant> depMap = reader.restoreValue(QLatin1String("ProjectDependencies")).toMap();
QMap<QString, QVariant>::const_iterator i = depMap.constBegin();
@@ -747,18 +780,18 @@ void SessionManager::restoreDependencies(const Utils::PersistentSettingsReader &
}
}
-void SessionManager::askUserAboutFailedProjects()
+void SessionManagerPrivate::askUserAboutFailedProjects()
{
QStringList failedProjects = m_failedProjects;
if (!failedProjects.isEmpty()) {
QString fileList =
QDir::toNativeSeparators(failedProjects.join(QLatin1String("<br>")));
QMessageBox * box = new QMessageBox(QMessageBox::Warning,
- tr("Failed to restore project files"),
- tr("Could not restore the following project files:<br><b>%1</b>").
+ SessionManager::tr("Failed to restore project files"),
+ SessionManager::tr("Could not restore the following project files:<br><b>%1</b>").
arg(fileList));
- QPushButton * keepButton = new QPushButton(tr("Keep projects in Session"), box);
- QPushButton * removeButton = new QPushButton(tr("Remove projects from Session"), box);
+ QPushButton * keepButton = new QPushButton(SessionManager::tr("Keep projects in Session"), box);
+ QPushButton * removeButton = new QPushButton(SessionManager::tr("Remove projects from Session"), box);
box->addButton(keepButton, QMessageBox::AcceptRole);
box->addButton(removeButton, QMessageBox::DestructiveRole);
@@ -769,41 +802,37 @@ void SessionManager::askUserAboutFailedProjects()
}
}
-void SessionManager::restoreStartupProject(const Utils::PersistentSettingsReader &reader)
+void SessionManagerPrivate::restoreStartupProject(const PersistentSettingsReader &reader)
{
const QString startupProject = reader.restoreValue(QLatin1String("StartupProject")).toString();
if (!startupProject.isEmpty()) {
- foreach (Project *pro, m_projects) {
- if (QDir::cleanPath(pro->document()->fileName()) == startupProject) {
- setStartupProject(pro);
+ foreach (Project *pro, d->m_projects) {
+ if (QDir::cleanPath(pro->projectFilePath()) == startupProject) {
+ m_instance->setStartupProject(pro);
break;
}
}
}
if (!m_startupProject) {
qWarning() << "Could not find startup project" << startupProject;
- if (!projects().isEmpty())
- setStartupProject(projects().first());
+ if (!m_projects.isEmpty())
+ m_instance->setStartupProject(m_projects.first());
}
}
-void SessionManager::restoreEditors(const Utils::PersistentSettingsReader &reader)
+void SessionManagerPrivate::restoreEditors(const PersistentSettingsReader &reader)
{
- const QVariant &editorsettings = reader.restoreValue(QLatin1String("EditorSettings"));
+ const QVariant editorsettings = reader.restoreValue(QLatin1String("EditorSettings"));
if (editorsettings.isValid()) {
- connect(ICore::editorManager(), SIGNAL(editorOpened(Core::IEditor*)),
- this, SLOT(sessionLoadingProgress()));
- ICore::editorManager()->restoreState(
- QByteArray::fromBase64(editorsettings.toByteArray()));
- disconnect(ICore::editorManager(), SIGNAL(editorOpened(Core::IEditor*)),
- this, SLOT(sessionLoadingProgress()));
+ EditorManager::restoreState(QByteArray::fromBase64(editorsettings.toByteArray()));
+ sessionLoadingProgress();
}
}
/*!
Loads a session, takes a session name (not filename).
*/
-void SessionManager::restoreProjects(const QStringList &fileList)
+void SessionManagerPrivate::restoreProjects(const QStringList &fileList)
{
// indirectly adds projects to session
// Keep projects that failed to load in the session!
@@ -812,9 +841,9 @@ void SessionManager::restoreProjects(const QStringList &fileList)
QString errors;
QList<Project *> projects = ProjectExplorerPlugin::instance()->openProjects(fileList, &errors);
if (!errors.isEmpty())
- QMessageBox::critical(Core::ICore::mainWindow(), tr("Failed to open project"), errors);
+ QMessageBox::critical(Core::ICore::mainWindow(), SessionManager::tr("Failed to open project"), errors);
foreach (Project *p, projects)
- m_failedProjects.removeAll(p->document()->fileName());
+ m_failedProjects.removeAll(p->projectFilePath());
}
}
@@ -823,14 +852,14 @@ bool SessionManager::loadSession(const QString &session)
// Do nothing if we have that session already loaded,
// exception if the session is the default virgin session
// we still want to be able to load the default session
- if (session == m_sessionName && !isDefaultVirgin())
+ if (session == d->m_sessionName && !isDefaultVirgin())
return true;
if (!sessions().contains(session))
return false;
// Try loading the file
- Utils::FileName fileName = sessionNameToFileName(session);
+ FileName fileName = sessionNameToFileName(session);
PersistentSettingsReader reader;
if (fileName.toFileInfo().exists()) {
if (!reader.load(fileName)) {
@@ -840,66 +869,68 @@ bool SessionManager::loadSession(const QString &session)
}
}
- m_loadingSession = true;
+ d->m_loadingSession = true;
// Allow everyone to set something in the session and before saving
- emit aboutToUnloadSession(m_sessionName);
+ emit m_instance->aboutToUnloadSession(d->m_sessionName);
if (!isDefaultVirgin()) {
if (!save()) {
- m_loadingSession = false;
+ d->m_loadingSession = false;
return false;
}
}
// Clean up
- if (!ICore::editorManager()->closeAllEditors()) {
- m_loadingSession = false;
+ if (!EditorManager::closeAllEditors()) {
+ d->m_loadingSession = false;
return false;
}
setStartupProject(0);
removeProjects(projects());
- m_failedProjects.clear();
- m_depMap.clear();
- m_values.clear();
+ d->m_failedProjects.clear();
+ d->m_depMap.clear();
+ d->m_values.clear();
- m_sessionName = session;
+ d->m_sessionName = session;
updateWindowTitle();
if (fileName.toFileInfo().exists()) {
- m_virginSession = false;
+ d->m_virginSession = false;
- ICore::progressManager()->addTask(m_future.future(), tr("Session"),
- QLatin1String("ProjectExplorer.SessionFile.Load"));
+ ProgressManager::addTask(d->m_future.future(), tr("Session"),
+ "ProjectExplorer.SessionFile.Load");
- restoreValues(reader);
- emit aboutToLoadSession(session);
+ d->m_future.setProgressRange(0, 1);
+ d->m_future.setProgressValue(0);
+
+ d->restoreValues(reader);
+ emit m_instance->aboutToLoadSession(session);
QColor c = QColor(reader.restoreValue(QLatin1String("Color")).toString());
if (c.isValid())
- Utils::StyleHelper::setBaseColor(c);
+ StyleHelper::setBaseColor(c);
QStringList fileList =
reader.restoreValue(QLatin1String("ProjectList")).toStringList();
- int openEditorsCount = reader.restoreValue(QLatin1String("OpenEditors")).toInt();
- m_future.setProgressRange(0, fileList.count() + openEditorsCount + 2);
- m_future.setProgressValue(1);
+ d->m_future.setProgressRange(0, fileList.count() + 1/*initialization above*/ + 1/*editors*/);
+ d->m_future.setProgressValue(1);
// if one processEvents doesn't get the job done
// just use two!
QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
- restoreProjects(fileList);
- sessionLoadingProgress();
- restoreDependencies(reader);
- restoreStartupProject(reader);
- restoreEditors(reader);
+ d->restoreProjects(fileList);
+ d->sessionLoadingProgress();
+ d->restoreDependencies(reader);
+ d->restoreStartupProject(reader);
+ d->restoreEditors(reader);
- m_future.reportFinished();
- m_future = QFutureInterface<void>();
+ d->m_future.reportFinished();
+ d->m_future = QFutureInterface<void>();
// restore the active mode
Id modeId = Id::fromSetting(value(QLatin1String("ActiveMode")));
@@ -912,36 +943,36 @@ bool SessionManager::loadSession(const QString &session)
ModeManager::activateMode(Id(Core::Constants::MODE_EDIT));
ModeManager::setFocusToCurrentMode();
}
- emit sessionLoaded(session);
+ emit m_instance->sessionLoaded(session);
// Starts a event loop, better do that at the very end
- askUserAboutFailedProjects();
- m_loadingSession = false;
+ d->askUserAboutFailedProjects();
+ d->m_loadingSession = false;
return true;
}
-QString SessionManager::lastSession() const
+QString SessionManager::lastSession()
{
return ICore::settings()->value(QLatin1String("ProjectExplorer/StartupSession")).toString();
}
-SessionNode *SessionManager::sessionNode() const
+SessionNode *SessionManager::sessionNode()
{
- return m_sessionNode;
+ return d->m_sessionNode;
}
void SessionManager::reportProjectLoadingProgress()
{
- sessionLoadingProgress();
+ d->sessionLoadingProgress();
}
void SessionManager::markSessionFileDirty(bool makeDefaultVirginDirty)
{
if (makeDefaultVirginDirty)
- m_virginSession = false;
+ d->m_virginSession = false;
}
-void SessionManager::sessionLoadingProgress()
+void SessionManagerPrivate::sessionLoadingProgress()
{
m_future.setProgressValue(m_future.progressValue() + 1);
QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
@@ -949,7 +980,7 @@ void SessionManager::sessionLoadingProgress()
void SessionManager::projectDisplayNameChanged()
{
- Project *pro = qobject_cast<Project*>(sender());
+ Project *pro = qobject_cast<Project*>(m_instance->sender());
if (pro) {
Node *currentNode = 0;
if (ProjectExplorerPlugin::currentProject() == pro)
@@ -958,19 +989,19 @@ void SessionManager::projectDisplayNameChanged()
// Fix node sorting
QList<ProjectNode *> nodes;
nodes << pro->rootProjectNode();
- m_sessionNode->removeProjectNodes(nodes);
- m_sessionNode->addProjectNodes(nodes);
+ d->m_sessionNode->removeProjectNodes(nodes);
+ d->m_sessionNode->addProjectNodes(nodes);
if (currentNode)
ProjectExplorerPlugin::instance()->setCurrentNode(currentNode);
- emit projectDisplayNameChanged(pro);
+ emit m_instance->projectDisplayNameChanged(pro);
}
}
-QStringList ProjectExplorer::SessionManager::projectsForSessionName(const QString &session) const
+QStringList SessionManager::projectsForSessionName(const QString &session)
{
- const Utils::FileName fileName = sessionNameToFileName(session);
+ const FileName fileName = sessionNameToFileName(session);
PersistentSettingsReader reader;
if (fileName.toFileInfo().exists()) {
if (!reader.load(fileName)) {
@@ -980,3 +1011,5 @@ QStringList ProjectExplorer::SessionManager::projectsForSessionName(const QStrin
}
return reader.restoreValue(QLatin1String("ProjectList")).toStringList();
}
+
+} // namespace ProjectExplorer
diff --git a/src/plugins/projectexplorer/session.h b/src/plugins/projectexplorer/session.h
index e983c2a197..d5dd205b2d 100644
--- a/src/plugins/projectexplorer/session.h
+++ b/src/plugins/projectexplorer/session.h
@@ -48,7 +48,6 @@ QT_END_NAMESPACE
namespace Core {
class IMode;
class IEditor;
-class IDocument;
}
namespace ProjectExplorer {
@@ -56,7 +55,6 @@ namespace ProjectExplorer {
class Project;
class Node;
class SessionNode;
-class SessionManager;
class PROJECTEXPLORER_EXPORT SessionManager : public QObject
{
@@ -66,62 +64,66 @@ public:
explicit SessionManager(QObject *parent = 0);
~SessionManager();
+ static QObject *instance();
+
// higher level session management
- QString activeSession() const;
- QString lastSession() const;
- QStringList sessions() const;
+ static QString activeSession();
+ static QString lastSession();
+ static QStringList sessions();
- bool createSession(const QString &session);
+ static bool createSession(const QString &session);
- bool confirmSessionDelete(const QString &session);
- bool deleteSession(const QString &session);
+ static bool confirmSessionDelete(const QString &session);
+ static bool deleteSession(const QString &session);
- bool cloneSession(const QString &original, const QString &clone);
- bool renameSession(const QString &original, const QString &newName);
+ static bool cloneSession(const QString &original, const QString &clone);
+ static bool renameSession(const QString &original, const QString &newName);
- bool loadSession(const QString &session);
+ static bool loadSession(const QString &session);
- bool save();
- void closeAllProjects();
+ static bool save();
+ static void closeAllProjects();
- void addProject(Project *project);
- void addProjects(const QList<Project*> &projects);
- void removeProject(Project *project);
- void removeProjects(QList<Project *> remove);
+ static void addProject(Project *project);
+ static void addProjects(const QList<Project*> &projects);
+ static void removeProject(Project *project);
+ static void removeProjects(QList<Project *> remove);
- void setStartupProject(Project *startupProject);
+ static void setStartupProject(Project *startupProject);
- QList<Project *> dependencies(const Project *project) const;
- bool hasDependency(const Project *project, const Project *depProject) const;
- bool canAddDependency(const Project *project, const Project *depProject) const;
- bool addDependency(Project *project, Project *depProject);
- void removeDependency(Project *project, Project *depProject);
+ static QList<Project *> dependencies(const Project *project);
+ static bool hasDependency(const Project *project, const Project *depProject);
+ static bool canAddDependency(const Project *project, const Project *depProject);
+ static bool addDependency(Project *project, Project *depProject);
+ static void removeDependency(Project *project, Project *depProject);
- Utils::FileName sessionNameToFileName(const QString &session) const;
- Project *startupProject() const;
+ static Utils::FileName sessionNameToFileName(const QString &session);
+ static Project *startupProject();
- const QList<Project *> &projects() const;
+ static const QList<Project *> &projects();
+ static bool hasProjects();
- bool isDefaultVirgin() const;
- bool isDefaultSession(const QString &session) const;
+ static bool isDefaultVirgin();
+ static bool isDefaultSession(const QString &session);
// Let other plugins store persistent values within the session file
- void setValue(const QString &name, const QVariant &value);
- QVariant value(const QString &name);
+ static void setValue(const QString &name, const QVariant &value);
+ static QVariant value(const QString &name);
// NBS rewrite projectOrder (dependency management)
- QList<Project *> projectOrder(Project *project = 0) const;
+ static QList<Project *> projectOrder(Project *project = 0);
+
+ static SessionNode *sessionNode();
- SessionNode *sessionNode() const;
+ static Project *projectForNode(ProjectExplorer::Node *node);
+ static Node *nodeForFile(const QString &fileName, Project *project = 0);
+ static Project *projectForFile(const QString &fileName);
- Project *projectForNode(ProjectExplorer::Node *node) const;
- Node *nodeForFile(const QString &fileName, Project *project = 0) const;
- Project *projectForFile(const QString &fileName) const;
+ static QStringList projectsForSessionName(const QString &session);
- QStringList projectsForSessionName(const QString &session) const;
+ static void reportProjectLoadingProgress();
+ static bool loadingSession();
- void reportProjectLoadingProgress();
- bool loadingSession();
signals:
void projectAdded(ProjectExplorer::Project *project);
void singleProjectAdded(ProjectExplorer::Project *project);
@@ -138,46 +140,12 @@ signals:
void dependencyChanged(ProjectExplorer::Project *a, ProjectExplorer::Project *b);
private slots:
- void saveActiveMode(Core::IMode *mode);
- void clearProjectFileCache();
- void configureEditor(Core::IEditor *editor, const QString &fileName);
- void updateWindowTitle();
-
- void markSessionFileDirty(bool makeDefaultVirginDirty = true);
- void sessionLoadingProgress();
-
- void projectDisplayNameChanged();
-
-private:
- bool projectContainsFile(Project *p, const QString &fileName) const;
- void restoreValues(const Utils::PersistentSettingsReader &reader);
- void restoreDependencies(const Utils::PersistentSettingsReader &reader);
- void restoreStartupProject(const Utils::PersistentSettingsReader &reader);
- void restoreEditors(const Utils::PersistentSettingsReader &reader);
- void restoreProjects(const QStringList &fileList);
- void askUserAboutFailedProjects();
-
- bool recursiveDependencyCheck(const QString &newDep, const QString &checkDep) const;
- QStringList dependencies(const QString &proName) const;
- QStringList dependenciesOrder() const;
- void dependencies(const QString &proName, QStringList &result) const;
-
- SessionNode *m_sessionNode;
- QString m_sessionName;
- bool m_virginSession;
-
- mutable QStringList m_sessions;
-
- mutable QHash<Project *, QStringList> m_projectFileCache;
- bool m_loadingSession;
-
- Project *m_startupProject;
- QList<Project *> m_projects;
- QStringList m_failedProjects;
- QMap<QString, QStringList> m_depMap;
- QMap<QString, QVariant> m_values;
- QFutureInterface<void> m_future;
- Utils::PersistentSettingsWriter *m_writer;
+ static void saveActiveMode(Core::IMode *mode);
+ static void clearProjectFileCache();
+ static void configureEditor(Core::IEditor *editor, const QString &fileName);
+ static void updateWindowTitle();
+ static void markSessionFileDirty(bool makeDefaultVirginDirty = true);
+ static void projectDisplayNameChanged();
};
} // namespace ProjectExplorer
diff --git a/src/plugins/projectexplorer/sessiondialog.cpp b/src/plugins/projectexplorer/sessiondialog.cpp
index 75ac0a6af2..0aa6b5be98 100644
--- a/src/plugins/projectexplorer/sessiondialog.cpp
+++ b/src/plugins/projectexplorer/sessiondialog.cpp
@@ -122,8 +122,8 @@ bool SessionNameInputDialog::isSwitchToRequested() const
}
-SessionDialog::SessionDialog(SessionManager *sessionManager, QWidget *parent)
- : QDialog(parent), m_sessionManager(sessionManager)
+SessionDialog::SessionDialog(QWidget *parent)
+ : QDialog(parent)
{
m_ui.setupUi(this);
@@ -161,10 +161,10 @@ bool SessionDialog::autoLoadSession() const
void SessionDialog::addItems(bool setDefaultSession)
{
- QStringList sessions = m_sessionManager->sessions();
+ QStringList sessions = SessionManager::sessions();
foreach (const QString &session, sessions) {
m_ui.sessionList->addItem(session);
- if (setDefaultSession && session == m_sessionManager->activeSession())
+ if (setDefaultSession && session == SessionManager::activeSession())
m_ui.sessionList->setCurrentRow(m_ui.sessionList->count() - 1);
}
}
@@ -174,11 +174,11 @@ void SessionDialog::markItems()
QListWidgetItem *item = m_ui.sessionList->item(i);
QFont f = item->font();
QString session = item->data(Qt::DisplayRole).toString();
- if (m_sessionManager->isDefaultSession(session))
+ if (SessionManager::isDefaultSession(session))
f.setItalic(true);
else
f.setItalic(false);
- if (m_sessionManager->activeSession() == session && !m_sessionManager->isDefaultVirgin())
+ if (SessionManager::activeSession() == session && !SessionManager::isDefaultVirgin())
f.setBold(true);
else
f.setBold(false);
@@ -190,7 +190,7 @@ void SessionDialog::updateActions()
{
if (m_ui.sessionList->currentItem()) {
bool isDefault = (m_ui.sessionList->currentItem()->text() == QLatin1String("default"));
- bool isActive = (m_ui.sessionList->currentItem()->text() == m_sessionManager->activeSession());
+ bool isActive = (m_ui.sessionList->currentItem()->text() == SessionManager::activeSession());
m_ui.btDelete->setEnabled(!isActive && !isDefault);
m_ui.btRename->setEnabled(!isDefault);
m_ui.btClone->setEnabled(true);
@@ -205,17 +205,17 @@ void SessionDialog::updateActions()
void SessionDialog::createNew()
{
- SessionNameInputDialog newSessionInputDialog(m_sessionManager->sessions(), this);
+ SessionNameInputDialog newSessionInputDialog(SessionManager::sessions(), this);
newSessionInputDialog.setWindowTitle(tr("New session name"));
if (newSessionInputDialog.exec() == QDialog::Accepted) {
QString newSession = newSessionInputDialog.value();
- if (newSession.isEmpty() || m_sessionManager->sessions().contains(newSession))
+ if (newSession.isEmpty() || SessionManager::sessions().contains(newSession))
return;
- m_sessionManager->createSession(newSession);
+ SessionManager::createSession(newSession);
m_ui.sessionList->clear();
- QStringList sessions = m_sessionManager->sessions();
+ QStringList sessions = SessionManager::sessions();
m_ui.sessionList->addItems(sessions);
m_ui.sessionList->setCurrentRow(sessions.indexOf(newSession));
markItems();
@@ -226,15 +226,15 @@ void SessionDialog::createNew()
void SessionDialog::clone()
{
- SessionNameInputDialog newSessionInputDialog(m_sessionManager->sessions(), this);
+ SessionNameInputDialog newSessionInputDialog(SessionManager::sessions(), this);
newSessionInputDialog.setValue(m_ui.sessionList->currentItem()->text());
newSessionInputDialog.setWindowTitle(tr("New session name"));
if (newSessionInputDialog.exec() == QDialog::Accepted) {
QString newSession = newSessionInputDialog.value();
- if (m_sessionManager->cloneSession(m_ui.sessionList->currentItem()->text(), newSession)) {
+ if (SessionManager::cloneSession(m_ui.sessionList->currentItem()->text(), newSession)) {
m_ui.sessionList->clear();
- QStringList sessions = m_sessionManager->sessions();
+ QStringList sessions = SessionManager::sessions();
m_ui.sessionList->addItems(sessions);
m_ui.sessionList->setCurrentRow(sessions.indexOf(newSession));
markItems();
@@ -246,9 +246,9 @@ void SessionDialog::remove()
{
const QString name = m_ui.sessionList->currentItem()->text();
- if (!m_sessionManager->confirmSessionDelete(name))
+ if (!SessionManager::confirmSessionDelete(name))
return;
- m_sessionManager->deleteSession(name);
+ SessionManager::deleteSession(name);
m_ui.sessionList->clear();
addItems(false);
markItems();
@@ -256,12 +256,12 @@ void SessionDialog::remove()
void SessionDialog::rename()
{
- SessionNameInputDialog newSessionInputDialog(m_sessionManager->sessions(), this);
+ SessionNameInputDialog newSessionInputDialog(SessionManager::sessions(), this);
newSessionInputDialog.setValue(m_ui.sessionList->currentItem()->text());
newSessionInputDialog.setWindowTitle(tr("Rename session"));
if (newSessionInputDialog.exec() == QDialog::Accepted) {
- m_sessionManager->renameSession(m_ui.sessionList->currentItem()->text(), newSessionInputDialog.value());
+ SessionManager::renameSession(m_ui.sessionList->currentItem()->text(), newSessionInputDialog.value());
m_ui.sessionList->clear();
addItems(false);
markItems();
@@ -271,7 +271,7 @@ void SessionDialog::rename()
void SessionDialog::switchToSession()
{
QString session = m_ui.sessionList->currentItem()->text();
- m_sessionManager->loadSession(session);
+ SessionManager::loadSession(session);
markItems();
updateActions();
reject();
diff --git a/src/plugins/projectexplorer/sessiondialog.h b/src/plugins/projectexplorer/sessiondialog.h
index 5ce4e35676..a00cff6e17 100644
--- a/src/plugins/projectexplorer/sessiondialog.h
+++ b/src/plugins/projectexplorer/sessiondialog.h
@@ -30,27 +30,25 @@
#ifndef SESSIONDIALOG_H
#define SESSIONDIALOG_H
+#include "ui_sessiondialog.h"
+
#include <QString>
#include <QDialog>
-#include "ui_sessiondialog.h"
-
QT_BEGIN_NAMESPACE
class QLineEdit;
class QPushButton;
QT_END_NAMESPACE
namespace ProjectExplorer {
-
-class SessionManager;
-
namespace Internal {
class SessionDialog : public QDialog
{
Q_OBJECT
+
public:
- SessionDialog(SessionManager *sessionManager, QWidget *parent = 0);
+ explicit SessionDialog(QWidget *parent = 0);
void setAutoLoadSession(bool);
bool autoLoadSession() const;
@@ -68,7 +66,6 @@ private:
void addItems(bool setDefaultSession);
void markItems();
Ui::SessionDialog m_ui;
- SessionManager *m_sessionManager;
};
class SessionNameInputDialog : public QDialog
diff --git a/src/plugins/projectexplorer/settingsaccessor.cpp b/src/plugins/projectexplorer/settingsaccessor.cpp
index 3df96c5324..6fe011ef75 100644
--- a/src/plugins/projectexplorer/settingsaccessor.cpp
+++ b/src/plugins/projectexplorer/settingsaccessor.cpp
@@ -42,7 +42,6 @@
#include "kitmanager.h"
#include <coreplugin/icore.h>
-#include <coreplugin/idocument.h>
#include <extensionsystem/pluginmanager.h>
#include <utils/persistentsettings.h>
#include <utils/hostosinfo.h>
@@ -53,6 +52,8 @@
#include <QFile>
#include <QMessageBox>
+using namespace Utils;
+
namespace ProjectExplorer {
namespace Internal {
@@ -112,11 +113,8 @@ QVariantMap UserFileVersionHandler::renameKeys(const QList<Change> &changes, QVa
} // Internal
} // ProjectExplorer
-
using namespace ProjectExplorer;
using namespace Internal;
-using Utils::PersistentSettingsReader;
-using Utils::PersistentSettingsWriter;
namespace {
@@ -422,6 +420,23 @@ public:
QVariantMap update(Project *project, const QVariantMap &map);
};
+// Version 14 Move builddir into BuildConfiguration
+class Version14Handler : public UserFileVersionHandler
+{
+public:
+ int userFileVersion() const
+ {
+ return 14;
+ }
+
+ QString displayUserFileVersion() const
+ {
+ return QLatin1String("3.0-pre1");
+ }
+
+ QVariantMap update(Project *project, const QVariantMap &map);
+};
+
} // namespace
//
@@ -514,6 +529,7 @@ SettingsAccessor::SettingsAccessor(Project *project) :
addVersionHandler(new Version11Handler);
addVersionHandler(new Version12Handler);
addVersionHandler(new Version13Handler);
+ addVersionHandler(new Version14Handler);
}
SettingsAccessor::~SettingsAccessor()
@@ -652,7 +668,7 @@ bool SettingsAccessor::saveSettings(const QVariantMap &map) const
backupUserFile();
SettingsData settings(map);
- settings.m_fileName = Utils::FileName::fromString(defaultFileName(m_userFileAcessor.suffix()));
+ settings.m_fileName = FileName::fromString(defaultFileName(m_userFileAcessor.suffix()));
const QVariant &shared = m_project->property(SHARED_SETTINGS);
if (shared.isValid())
trackUserStickySettings(settings.m_map, shared.toMap());
@@ -713,12 +729,12 @@ QStringList SettingsAccessor::findSettingsFiles(const QString &suffix) const
QByteArray SettingsAccessor::creatorId()
{
- return ProjectExplorerPlugin::instance()->projectExplorerSettings().environmentId.toByteArray();
+ return ProjectExplorerPlugin::projectExplorerSettings().environmentId.toByteArray();
}
QString SettingsAccessor::defaultFileName(const QString &suffix) const
{
- return project()->document()->fileName() + suffix;
+ return project()->projectFilePath() + suffix;
}
int SettingsAccessor::currentVersion() const
@@ -729,7 +745,7 @@ int SettingsAccessor::currentVersion() const
void SettingsAccessor::backupUserFile() const
{
SettingsData oldSettings;
- oldSettings.m_fileName = Utils::FileName::fromString(defaultFileName(m_userFileAcessor.suffix()));
+ oldSettings.m_fileName = FileName::fromString(defaultFileName(m_userFileAcessor.suffix()));
if (!m_userFileAcessor.readFile(&oldSettings))
return;
@@ -821,8 +837,8 @@ SettingsAccessor::SettingsData SettingsAccessor::readUserSettings() const
SettingsAccessor::SettingsData SettingsAccessor::readSharedSettings() const
{
SettingsData sharedSettings;
- QString fn = project()->document()->fileName() + m_sharedFileAcessor.suffix();
- sharedSettings.m_fileName = Utils::FileName::fromString(fn);
+ QString fn = project()->projectFilePath() + m_sharedFileAcessor.suffix();
+ sharedSettings.m_fileName = FileName::fromString(fn);
if (!m_sharedFileAcessor.readFile(&sharedSettings))
return sharedSettings;
@@ -862,7 +878,7 @@ SettingsAccessor::SettingsData SettingsAccessor::findBestSettings(const QStringL
foreach (const QString &file, candidates) {
tmp.clear();
- tmp.m_fileName = Utils::FileName::fromString(file);
+ tmp.m_fileName = FileName::fromString(file);
if (!m_userFileAcessor.readFile(&tmp))
continue;
@@ -1009,7 +1025,7 @@ bool SettingsAccessor::FileAccessor::writeFile(const SettingsData *settings) con
{
if (!m_writer || m_writer->fileName() != settings->fileName()) {
delete m_writer;
- m_writer = new Utils::PersistentSettingsWriter(settings->fileName(), QLatin1String("QtCreatorProject"));
+ m_writer = new PersistentSettingsWriter(settings->fileName(), QLatin1String("QtCreatorProject"));
}
QVariantMap data;
@@ -1994,7 +2010,7 @@ static QVariant version8ArgNodeHandler(const QVariant &var)
{
QString ret;
foreach (const QVariant &svar, var.toList()) {
- if (Utils::HostOsInfo::isAnyUnixHost()) {
+ if (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();
@@ -2003,10 +2019,10 @@ static QVariant version8ArgNodeHandler(const QVariant &var)
s.replace(QLatin1Char('`'), QLatin1String("\\`"));
if (s != svar.toString() || hasSpecialChars(s))
s.prepend(QLatin1Char('"')).append(QLatin1Char('"'));
- Utils::QtcProcess::addArgs(&ret, s);
+ QtcProcess::addArgs(&ret, s);
} else {
// Under windows, env expansions cannot be quoted anyway.
- Utils::QtcProcess::addArg(&ret, svar.toString());
+ QtcProcess::addArg(&ret, svar.toString());
}
}
return QVariant(ret);
@@ -2017,7 +2033,7 @@ static QVariant version8LameArgNodeHandler(const QVariant &var)
{
QString ret;
foreach (const QVariant &svar, var.toList())
- Utils::QtcProcess::addArgs(&ret, svar.toString());
+ QtcProcess::addArgs(&ret, svar.toString());
return QVariant(ret);
}
@@ -2062,7 +2078,7 @@ static const char * const envExpandedKeys[] = {
static QString version8NewVar(const QString &old)
{
QString ret = old;
- if (Utils::HostOsInfo::isAnyUnixHost()) {
+ if (HostOsInfo::isAnyUnixHost()) {
ret.prepend(QLatin1String("${"));
ret.append(QLatin1Char('}'));
} else {
@@ -2082,7 +2098,7 @@ static QVariant version8EnvNodeTransform(const QVariant &var)
QLatin1String("%{sourceDir}"));
result.replace(QRegExp(QLatin1String("%BUILDDIR%|\\$(BUILDDIR\\b|\\{BUILDDIR\\})")),
QLatin1String("%{buildDir}"));
- if (Utils::HostOsInfo::isAnyUnixHost()) {
+ if (HostOsInfo::isAnyUnixHost()) {
for (int vStart = -1, i = 0; i < result.length(); ) {
QChar c = result.at(i++);
if (c == QLatin1Char('%')) {
@@ -2298,10 +2314,9 @@ Version11Handler::Version11Handler()
Version11Handler::~Version11Handler()
{
- KitManager *km = KitManager::instance();
- if (!km) // Can happen during teardown!
+ if (!KitManager::instance()) // Can happen during teardown!
return;
- QList<Kit *> knownKits = km->kits();
+ QList<Kit *> knownKits = KitManager::kits();
foreach (Kit *k, m_targets.keys()) {
if (!knownKits.contains(k))
KitManager::deleteKit(k);
@@ -2321,8 +2336,7 @@ QVariantMap Version11Handler::update(Project *project, const QVariantMap &map)
parseToolChainFile();
QVariantMap result;
- KitManager *km = KitManager::instance();
- foreach (Kit *k, km->kits())
+ foreach (Kit *k, KitManager::kits())
m_targets.insert(k, QVariantMap());
QMapIterator<QString, QVariant> globalIt(map);
@@ -2399,37 +2413,37 @@ QVariantMap Version11Handler::update(Project *project, const QVariantMap &map)
Kit *tmpKit = rawKit;
if (oldTargetId == QLatin1String("Qt4ProjectManager.Target.AndroidDeviceTarget")) {
- tmpKit->setIconPath(QLatin1String(":/android/images/QtAndroid.png"));
- tmpKit->setValue(Core::Id("PE.Profile.DeviceType"), QString::fromLatin1("Desktop"));
- tmpKit->setValue(Core::Id("PE.Profile.Device"), QString());
+ tmpKit->setIconPath(FileName::fromString(QLatin1String(":/android/images/QtAndroid.png")));
+ tmpKit->setValue("PE.Profile.DeviceType", QString::fromLatin1("Desktop"));
+ tmpKit->setValue("PE.Profile.Device", QString());
} else if (oldTargetId == QLatin1String("RemoteLinux.EmbeddedLinuxTarget")) {
- tmpKit->setIconPath(QLatin1String(":///DESKTOP///"));
- tmpKit->setValue(Core::Id("PE.Profile.DeviceType"), QString::fromLatin1("GenericLinuxOsType"));
- tmpKit->setValue(Core::Id("PE.Profile.Device"), QString());
+ tmpKit->setIconPath(FileName::fromString(QLatin1String(":///DESKTOP///")));
+ tmpKit->setValue("PE.Profile.DeviceType", QString::fromLatin1("GenericLinuxOsType"));
+ tmpKit->setValue("PE.Profile.Device", QString());
} else if (oldTargetId == QLatin1String("Qt4ProjectManager.Target.HarmattanDeviceTarget")) {
- tmpKit->setIconPath(QLatin1String(":/projectexplorer/images/MaemoDevice.png"));
- tmpKit->setValue(Core::Id("PE.Profile.DeviceType"), QString::fromLatin1("HarmattanOsType"));
- tmpKit->setValue(Core::Id("PE.Profile.Device"), QString());
+ tmpKit->setIconPath(FileName::fromString(QLatin1String(":/projectexplorer/images/MaemoDevice.png")));
+ tmpKit->setValue("PE.Profile.DeviceType", QString::fromLatin1("HarmattanOsType"));
+ tmpKit->setValue("PE.Profile.Device", QString());
} else if (oldTargetId == QLatin1String("Qt4ProjectManager.Target.MaemoDeviceTarget")) {
- tmpKit->setIconPath(QLatin1String(":/projectexplorer/images/MaemoDevice.png"));
- tmpKit->setValue(Core::Id("PE.Profile.DeviceType"), QString::fromLatin1("Maemo5OsType"));
- tmpKit->setValue(Core::Id("PE.Profile.Device"), QString());
+ tmpKit->setIconPath(FileName::fromString(QLatin1String(":/projectexplorer/images/MaemoDevice.png")));
+ tmpKit->setValue("PE.Profile.DeviceType", QString::fromLatin1("Maemo5OsType"));
+ tmpKit->setValue("PE.Profile.Device", QString());
} else if (oldTargetId == QLatin1String("Qt4ProjectManager.Target.MeegoDeviceTarget")) {
- tmpKit->setIconPath(QLatin1String(":/projectexplorer/images/MaemoDevice.png"));
- tmpKit->setValue(Core::Id("PE.Profile.DeviceType"), QString::fromLatin1("MeegoOsType"));
- tmpKit->setValue(Core::Id("PE.Profile.Device"), QString());
+ tmpKit->setIconPath(FileName::fromString(QLatin1String(":/projectexplorer/images/MaemoDevice.png")));
+ tmpKit->setValue("PE.Profile.DeviceType", QString::fromLatin1("MeegoOsType"));
+ tmpKit->setValue("PE.Profile.Device", QString());
} else if (oldTargetId == QLatin1String("Qt4ProjectManager.Target.S60DeviceTarget")) {
- tmpKit->setIconPath(QLatin1String(":/projectexplorer/images/SymbianDevice.png"));
- tmpKit->setValue(Core::Id("PE.Profile.DeviceType"), QString::fromLatin1("Qt4ProjectManager.SymbianDevice"));
- tmpKit->setValue(Core::Id("PE.Profile.Device"), QString::fromLatin1("Symbian Device"));
+ tmpKit->setIconPath(FileName::fromString(QLatin1String(":/projectexplorer/images/SymbianDevice.png")));
+ tmpKit->setValue("PE.Profile.DeviceType", QString::fromLatin1("Qt4ProjectManager.SymbianDevice"));
+ tmpKit->setValue("PE.Profile.Device", QString::fromLatin1("Symbian Device"));
} else if (oldTargetId == QLatin1String("Qt4ProjectManager.Target.QtSimulatorTarget")) {
- tmpKit->setIconPath(QLatin1String(":/projectexplorer/images/Simulator.png"));
- tmpKit->setValue(Core::Id("PE.Profile.DeviceType"), QString::fromLatin1("Desktop"));
- tmpKit->setValue(Core::Id("PE.Profile.Device"), QString::fromLatin1("Desktop Device"));
+ tmpKit->setIconPath(FileName::fromString(QLatin1String(":/projectexplorer/images/Simulator.png")));
+ tmpKit->setValue("PE.Profile.DeviceType", QString::fromLatin1("Desktop"));
+ tmpKit->setValue("PE.Profile.Device", QString::fromLatin1("Desktop Device"));
} else {
- tmpKit->setIconPath(QLatin1String(":///DESKTOP///"));
- tmpKit->setValue(Core::Id("PE.Profile.DeviceType"), QString::fromLatin1("Desktop"));
- tmpKit->setValue(Core::Id("PE.Profile.Device"), QString::fromLatin1("Desktop Device"));
+ tmpKit->setIconPath(FileName::fromString(QLatin1String(":///DESKTOP///")));
+ tmpKit->setValue("PE.Profile.DeviceType", QString::fromLatin1("Desktop"));
+ tmpKit->setValue("PE.Profile.Device", QString::fromLatin1("Desktop Device"));
}
// Tool chain
@@ -2459,19 +2473,19 @@ QVariantMap Version11Handler::update(Project *project, const QVariantMap &map)
for (int j = i + 2; j < split.count(); ++j)
debuggerPath = debuggerPath + QLatin1Char('.') + split.at(j);
- foreach (ToolChain *tc, ToolChainManager::instance()->toolChains()) {
- if ((tc->compilerCommand() == Utils::FileName::fromString(compilerPath))
+ foreach (ToolChain *tc, ToolChainManager::toolChains()) {
+ if ((tc->compilerCommand() == FileName::fromString(compilerPath))
&& (tc->targetAbi() == compilerAbi)) {
tcId = tc->id();
break;
}
}
}
- tmpKit->setValue(Core::Id("PE.Profile.ToolChain"), tcId);
+ tmpKit->setValue("PE.Profile.ToolChain", tcId);
// QtVersion
int qtVersionId = bc.value(QLatin1String("Qt4ProjectManager.Qt4BuildConfiguration.QtVersionId"), -1).toInt();
- tmpKit->setValue(Core::Id("QtSupport.QtInformation"), qtVersionId);
+ tmpKit->setValue("QtSupport.QtInformation", qtVersionId);
// Debugger + mkspec
QVariantMap debugger;
@@ -2479,18 +2493,18 @@ QVariantMap Version11Handler::update(Project *project, const QVariantMap &map)
if (m_toolChainExtras.contains(origTcId)) {
debuggerPath = m_toolChainExtras.value(origTcId).m_debugger;
if (!debuggerPath.isEmpty() && !QFileInfo(debuggerPath).isAbsolute())
- debuggerPath = Utils::Environment::systemEnvironment().searchInPath(debuggerPath);
+ debuggerPath = Environment::systemEnvironment().searchInPath(debuggerPath);
if (debuggerPath.contains(QLatin1String("cdb")))
debuggerEngine = 4; // CDB
mkspec = m_toolChainExtras.value(origTcId).m_mkspec;
}
debugger.insert(QLatin1String("EngineType"), debuggerEngine);
debugger.insert(QLatin1String("Binary"), debuggerPath);
- tmpKit->setValue(Core::Id("Debugger.Information"), debugger);
- tmpKit->setValue(Core::Id("QtPM4.mkSpecInformation"), mkspec);
+ tmpKit->setValue("Debugger.Information", debugger);
+ tmpKit->setValue("QtPM4.mkSpecInformation", mkspec);
// SysRoot
- tmpKit->setValue(Core::Id("PE.Profile.SysRoot"), m_qtVersionExtras.value(qtVersionId));
+ tmpKit->setValue("PE.Profile.SysRoot", m_qtVersionExtras.value(qtVersionId));
QMapIterator<int, QVariantMap> deployIt(dcs);
while (deployIt.hasNext()) {
@@ -2503,7 +2517,7 @@ QVariantMap Version11Handler::update(Project *project, const QVariantMap &map)
devId = QByteArray("Desktop Device");
if (!devId.isEmpty() && !DeviceManager::instance()->find(Core::Id::fromName(devId))) // We do not know that device
devId.clear();
- tmpKit->setValue(Core::Id("PE.Profile.Device"), devId);
+ tmpKit->setValue("PE.Profile.Device", devId);
// Set display name last:
tmpKit->setDisplayName(extraTargetData.value(QLatin1String("ProjectExplorer.ProjectConfiguration.DisplayName")).toString());
@@ -2527,7 +2541,7 @@ QVariantMap Version11Handler::update(Project *project, const QVariantMap &map)
if (data.isEmpty())
continue;
- km->registerKit(k);
+ KitManager::registerKit(k);
data.insert(QLatin1String("ProjectExplorer.ProjectConfiguration.Id"), k->id().name());
data.insert(QLatin1String("ProjectExplorer.Target.Profile"), k->id().name());
@@ -2546,22 +2560,22 @@ QVariantMap Version11Handler::update(Project *project, const QVariantMap &map)
Kit *Version11Handler::uniqueKit(Kit *k)
{
- const QString tc = k->value(Core::Id("PE.Profile.ToolChain")).toString();
- const int qt = k->value(Core::Id("QtSupport.QtInformation")).toInt();
- const QString debugger = k->value(Core::Id("Debugger.Information")).toString();
- const QString mkspec = k->value(Core::Id("QtPM4.mkSpecInformation")).toString();
- const QString deviceType = k->value(Core::Id("PE.Profile.DeviceType")).toString();
- const QString device = k->value(Core::Id("PE.Profile.Device")).toString();
- const QString sysroot = k->value(Core::Id("PE.Profile.SysRoot")).toString();
+ const QString tc = k->value("PE.Profile.ToolChain").toString();
+ const int qt = k->value("QtSupport.QtInformation").toInt();
+ const QString debugger = k->value("Debugger.Information").toString();
+ const QString mkspec = k->value("QtPM4.mkSpecInformation").toString();
+ const QString deviceType = k->value("PE.Profile.DeviceType").toString();
+ const QString device = k->value("PE.Profile.Device").toString();
+ const QString sysroot = k->value("PE.Profile.SysRoot").toString();
foreach (Kit *i, m_targets.keys()) {
- const QString currentTc = i->value(Core::Id("PE.Profile.ToolChain")).toString();
- const int currentQt = i->value(Core::Id("QtSupport.QtInformation")).toInt();
- const QString currentDebugger = i->value(Core::Id("Debugger.Information")).toString();
- const QString currentMkspec = i->value(Core::Id("QtPM4.mkSpecInformation")).toString();
- const QString currentDeviceType = i->value(Core::Id("PE.Profile.DeviceType")).toString();
- const QString currentDevice = i->value(Core::Id("PE.Profile.Device")).toString();
- const QString currentSysroot = i->value(Core::Id("PE.Profile.SysRoot")).toString();
+ const QString currentTc = i->value("PE.Profile.ToolChain").toString();
+ const int currentQt = i->value("QtSupport.QtInformation").toInt();
+ const QString currentDebugger = i->value("Debugger.Information").toString();
+ const QString currentMkspec = i->value("QtPM4.mkSpecInformation").toString();
+ const QString currentDeviceType = i->value("PE.Profile.DeviceType").toString();
+ const QString currentDevice = i->value("PE.Profile.Device").toString();
+ const QString currentSysroot = i->value("PE.Profile.SysRoot").toString();
bool deviceTypeOk = deviceType == currentDeviceType;
bool deviceOk = device.isEmpty() || currentDevice == device;
@@ -2635,7 +2649,7 @@ void Version11Handler::addRunConfigurations(Kit *k,
if (!proFile.isEmpty()) {
QString newId = rcData.value(QLatin1String("ProjectExplorer.ProjectConfiguration.Id")).toString();
newId.append(QLatin1Char(':'));
- Utils::FileName fn = Utils::FileName::fromString(projectDir);
+ FileName fn = FileName::fromString(projectDir);
fn.appendPath(proFile);
newId.append(fn.toString());
rcData.insert(QLatin1String("ProjectExplorer.ProjectConfiguration.Id"), newId);
@@ -2650,7 +2664,7 @@ void Version11Handler::addRunConfigurations(Kit *k,
static QString targetRoot(const QString &qmakePath)
{
return QDir::cleanPath(qmakePath).remove(QLatin1String("/bin/qmake" QTC_HOST_EXE_SUFFIX),
- Utils::HostOsInfo::fileNameCaseSensitivity());
+ HostOsInfo::fileNameCaseSensitivity());
}
static QString maddeRoot(const QString &qmakePath)
@@ -2663,8 +2677,8 @@ static QString maddeRoot(const QString &qmakePath)
void Version11Handler::parseQtversionFile()
{
QFileInfo settingsLocation(Core::ICore::settings()->fileName());
- Utils::FileName fileName = Utils::FileName::fromString(settingsLocation.absolutePath() + QLatin1String("/qtversion.xml"));
- Utils::PersistentSettingsReader reader;
+ FileName fileName = FileName::fromString(settingsLocation.absolutePath() + QLatin1String("/qtversion.xml"));
+ PersistentSettingsReader reader;
if (!reader.load(fileName)) {
qWarning("Failed to open legacy qtversions.xml file.");
return;
@@ -2706,8 +2720,8 @@ void Version11Handler::parseQtversionFile()
void Version11Handler::parseToolChainFile()
{
QFileInfo settingsLocation(Core::ICore::settings()->fileName());
- Utils::FileName fileName = Utils::FileName::fromString(settingsLocation.absolutePath() + QLatin1String("/toolChains.xml"));
- Utils::PersistentSettingsReader reader;
+ FileName fileName = FileName::fromString(settingsLocation.absolutePath() + QLatin1String("/toolChains.xml"));
+ PersistentSettingsReader reader;
if (!reader.load(fileName)) {
qWarning("Failed to open legacy toolChains.xml file.");
return;
@@ -2771,3 +2785,23 @@ QVariantMap Version13Handler::update(Project *project, const QVariantMap &map)
}
return result;
}
+
+QVariantMap Version14Handler::update(Project *project, const QVariantMap &map)
+{
+ QVariantMap result;
+ QMapIterator<QString, QVariant> it(map);
+ while (it.hasNext()) {
+ it.next();
+ if (it.value().type() == QVariant::Map)
+ result.insert(it.key(), update(project, it.value().toMap()));
+ else if (it.key() == QLatin1String("AutotoolsProjectManager.AutotoolsBuildConfiguration.BuildDirectory")
+ || it.key() == QLatin1String("CMakeProjectManager.CMakeBuildConfiguration.BuildDirectory")
+ || it.key() == QLatin1String("GenericProjectManager.GenericBuildConfiguration.BuildDirectory")
+ || it.key() == QLatin1String("Qbs.BuildDirectory")
+ || it.key() == QLatin1String("Qt4ProjectManager.Qt4BuildConfiguration.BuildDirectory"))
+ result.insert(QLatin1String("ProjectExplorer.BuildConfiguration.BuildDirectory"), it.value());
+ else
+ result.insert(it.key(), it.value());
+ }
+ return result;
+}
diff --git a/src/plugins/projectexplorer/target.cpp b/src/plugins/projectexplorer/target.cpp
index 5a5585f485..b867943518 100644
--- a/src/plugins/projectexplorer/target.cpp
+++ b/src/plugins/projectexplorer/target.cpp
@@ -29,6 +29,7 @@
#include "target.h"
+#include "buildinfo.h"
#include "buildtargetinfo.h"
#include "deploymentdata.h"
#include "kit.h"
@@ -130,7 +131,7 @@ Target::Target(Project *project, Kit *k) :
setDisplayName(d->m_kit->displayName());
setIcon(d->m_kit->icon());
- KitManager *km = KitManager::instance();
+ QObject *km = KitManager::instance();
connect(km, SIGNAL(kitUpdated(ProjectExplorer::Kit*)),
this, SLOT(handleKitUpdates(ProjectExplorer::Kit*)));
connect(km, SIGNAL(kitRemoved(ProjectExplorer::Kit*)),
@@ -248,9 +249,7 @@ bool Target::removeBuildConfiguration(BuildConfiguration *configuration)
if (!d->m_buildConfigurations.contains(configuration))
return false;
- ProjectExplorer::BuildManager *bm =
- ProjectExplorer::ProjectExplorerPlugin::instance()->buildManager();
- if (bm->isBuilding(configuration))
+ if (BuildManager::isBuilding(configuration))
return false;
d->m_buildConfigurations.removeOne(configuration);
@@ -325,9 +324,7 @@ bool Target::removeDeployConfiguration(DeployConfiguration *dc)
if (!d->m_deployConfigurations.contains(dc))
return false;
- ProjectExplorer::BuildManager *bm =
- ProjectExplorer::ProjectExplorerPlugin::instance()->buildManager();
- if (bm->isBuilding(dc))
+ if (BuildManager::isBuilding(dc))
return false;
d->m_deployConfigurations.removeOne(dc);
@@ -531,16 +528,14 @@ void Target::updateDefaultBuildConfigurations()
qWarning("No build configuration factory found for target id '%s'.", qPrintable(id().toString()));
return;
}
- QList<Core::Id> bcIds = bcFactory->availableCreationIds(this);
- foreach (Core::Id id, bcIds) {
- if (!bcFactory->canCreate(this, id))
- continue;
- BuildConfiguration *bc = bcFactory->create(this, id, tr("Default build"));
+ QList<BuildInfo *> infoList = bcFactory->availableSetups(this->kit(), project()->projectFilePath());
+ foreach (BuildInfo *info, infoList) {
+ BuildConfiguration *bc = bcFactory->create(this, info);
if (!bc)
continue;
- QTC_CHECK(bc->id() == id);
addBuildConfiguration(bc);
}
+ qDeleteAll(infoList);
}
void Target::updateDefaultDeployConfigurations()
@@ -676,9 +671,9 @@ void Target::updateDefaultRunConfigurations()
// Make sure a configured RC is active:
if (activeRunConfiguration() && !activeRunConfiguration()->isConfigured()) {
- if (!existingConfigured.isEmpty())
+ if (!existingConfigured.isEmpty()) {
setActiveRunConfiguration(existingConfigured.at(0));
- else if (!newConfigured.isEmpty()) {
+ } else if (!newConfigured.isEmpty()) {
RunConfiguration *selected = newConfigured.at(0);
// Try to find a runconfiguration that matches the project name. That is a good
// candidate for something to run initially.
@@ -770,7 +765,7 @@ bool Target::fromMap(const QVariantMap &map)
if (!ProjectConfiguration::fromMap(map))
return false;
- d->m_kit = KitManager::instance()->find(id());
+ d->m_kit = KitManager::find(id());
if (!d->m_kit)
return false;
diff --git a/src/plugins/projectexplorer/target.h b/src/plugins/projectexplorer/target.h
index b9f36113c5..7171f2637d 100644
--- a/src/plugins/projectexplorer/target.h
+++ b/src/plugins/projectexplorer/target.h
@@ -30,7 +30,6 @@
#ifndef TARGET_H
#define TARGET_H
-#include "devicesupport/idevice.h"
#include "projectconfiguration.h"
#include "projectexplorer_export.h"
diff --git a/src/plugins/projectexplorer/targetsettingspanel.cpp b/src/plugins/projectexplorer/targetsettingspanel.cpp
index 72bfbbad10..d062862a2c 100644
--- a/src/plugins/projectexplorer/targetsettingspanel.cpp
+++ b/src/plugins/projectexplorer/targetsettingspanel.cpp
@@ -270,7 +270,7 @@ void TargetSettingsPanelWidget::menuShown(int targetIndex)
void TargetSettingsPanelWidget::changeActionTriggered(QAction *action)
{
- Kit *k = KitManager::instance()->find(action->data().value<Core::Id>());
+ Kit *k = KitManager::find(action->data().value<Core::Id>());
Target *sourceTarget = m_targets.at(m_menuTargetIndex);
Target *newTarget = cloneTarget(sourceTarget, k);
@@ -283,7 +283,7 @@ void TargetSettingsPanelWidget::changeActionTriggered(QAction *action)
void TargetSettingsPanelWidget::duplicateActionTriggered(QAction *action)
{
- Kit *k = KitManager::instance()->find(action->data().value<Core::Id>());
+ Kit *k = KitManager::find(action->data().value<Core::Id>());
Target *newTarget = cloneTarget(m_targets.at(m_menuTargetIndex), k);
if (newTarget) {
@@ -294,7 +294,7 @@ void TargetSettingsPanelWidget::duplicateActionTriggered(QAction *action)
void TargetSettingsPanelWidget::addActionTriggered(QAction *action)
{
- Kit *k = KitManager::instance()->find(action->data().value<Core::Id>());
+ Kit *k = KitManager::find(action->data().value<Core::Id>());
QTC_ASSERT(!m_project->target(k), return);
Target *target = m_project->createTarget(k);
@@ -443,8 +443,7 @@ void TargetSettingsPanelWidget::removeTarget()
void TargetSettingsPanelWidget::removeTarget(Target *t)
{
- ProjectExplorer::BuildManager *bm = ProjectExplorerPlugin::instance()->buildManager();
- if (bm->isBuilding(t)) {
+ if (BuildManager::isBuilding(t)) {
QMessageBox box;
QPushButton *closeAnyway = box.addButton(tr("Cancel Build && Remove Kit"), QMessageBox::AcceptRole);
QPushButton *cancelClose = box.addButton(tr("Do Not Remove"), QMessageBox::RejectRole);
@@ -455,7 +454,7 @@ void TargetSettingsPanelWidget::removeTarget(Target *t)
box.exec();
if (box.clickedButton() != closeAnyway)
return;
- bm->cancel();
+ BuildManager::cancel();
} else {
// We don't show the generic message box on removing the target, if we showed the still building one
int ret = QMessageBox::warning(this, tr("Qt Creator"),
@@ -563,7 +562,7 @@ void TargetSettingsPanelWidget::updateTargetButtons()
this, SLOT(duplicateActionTriggered(QAction*)));
connect(removeAction, SIGNAL(triggered()), this, SLOT(removeTarget()));
- QList<Kit *> kits = KitManager::instance()->kits();
+ QList<Kit *> kits = KitManager::kits();
qSort(kits.begin(), kits.end(), diplayNameSorter);
foreach (Kit *k, kits) {
if (m_project->target(k))
diff --git a/src/plugins/projectexplorer/targetsetuppage.cpp b/src/plugins/projectexplorer/targetsetuppage.cpp
new file mode 100644
index 0000000000..0b9c5e9a2d
--- /dev/null
+++ b/src/plugins/projectexplorer/targetsetuppage.cpp
@@ -0,0 +1,533 @@
+/****************************************************************************
+**
+** 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 "targetsetuppage.h"
+#include "buildconfiguration.h"
+#include "buildinfo.h"
+#include "kit.h"
+#include "kitmanager.h"
+#include "importwidget.h"
+#include "project.h"
+#include "projectexplorerconstants.h"
+#include "target.h"
+#include "targetsetupwidget.h"
+
+#include <coreplugin/icore.h>
+#include <utils/qtcassert.h>
+#include <utils/qtcprocess.h>
+
+#include <QFileInfo>
+#include <QLabel>
+#include <QMessageBox>
+#include <QScrollArea>
+#include <QVBoxLayout>
+
+namespace ProjectExplorer {
+namespace Internal {
+
+class TargetSetupPageUi
+{
+public:
+ QWidget *centralWidget;
+ QWidget *scrollAreaWidget;
+ QScrollArea *scrollArea;
+ QLabel *headerLabel;
+ QLabel *descriptionLabel;
+ QLabel *noValidKitLabel;
+ QLabel *optionHintLabel;
+
+ 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);
+ headerLabel->setVisible(false);
+
+ noValidKitLabel = new QLabel(setupTargetPage);
+ noValidKitLabel->setWordWrap(true);
+ noValidKitLabel->setText(TargetSetupPage::tr("<span style=\" font-weight:600;\">No valid kits found.</span>"));
+
+
+ optionHintLabel = new QLabel(setupTargetPage);
+ optionHintLabel->setWordWrap(true);
+ optionHintLabel->setText(TargetSetupPage::tr(
+ "Please add a kit in the <a href=\"buildandrun\">options</a> "
+ "or via the maintenance tool of the SDK."));
+ optionHintLabel->setTextInteractionFlags(Qt::TextBrowserInteraction);
+ optionHintLabel->setVisible(false);
+
+ centralWidget = new QWidget(setupTargetPage);
+ QSizePolicy policy(QSizePolicy::Preferred, QSizePolicy::Fixed);
+ policy.setHorizontalStretch(0);
+ policy.setVerticalStretch(0);
+ policy.setHeightForWidth(centralWidget->sizePolicy().hasHeightForWidth());
+ centralWidget->setSizePolicy(policy);
+
+ scrollAreaWidget = new QWidget(setupTargetPage);
+ scrollArea = new QScrollArea(scrollAreaWidget);
+ scrollArea->setWidgetResizable(true);
+
+ QWidget *scrollAreaWidgetContents;
+ scrollAreaWidgetContents = new QWidget();
+ scrollAreaWidgetContents->setGeometry(QRect(0, 0, 230, 81));
+ scrollArea->setWidget(scrollAreaWidgetContents);
+
+ QVBoxLayout *verticalLayout = new QVBoxLayout(scrollAreaWidget);
+ verticalLayout->setSpacing(0);
+ verticalLayout->setContentsMargins(0, 0, 0, 0);
+ verticalLayout->addWidget(scrollArea);
+
+ QVBoxLayout *verticalLayout_2 = new QVBoxLayout(setupTargetPage);
+ verticalLayout_2->addWidget(headerLabel);
+ verticalLayout_2->addWidget(noValidKitLabel);
+ verticalLayout_2->addWidget(descriptionLabel);
+ verticalLayout_2->addWidget(optionHintLabel);
+ verticalLayout_2->addWidget(centralWidget);
+ verticalLayout_2->addWidget(scrollAreaWidget);
+
+ QVBoxLayout *verticalLayout_3 = new QVBoxLayout(q);
+ verticalLayout_3->setContentsMargins(0, 0, 0, -1);
+ verticalLayout_3->addWidget(setupTargetPage);
+
+ QObject::connect(optionHintLabel, SIGNAL(linkActivated(QString)),
+ q, SLOT(openOptions()));
+ }
+};
+
+} // namespace Internal
+
+using namespace Internal;
+
+TargetSetupPage::TargetSetupPage(QWidget *parent) :
+ QWizardPage(parent),
+ m_requiredMatcher(0),
+ m_preferredMatcher(0),
+ m_importer(0),
+ m_baseLayout(0),
+ m_importSearch(false),
+ m_firstWidget(0),
+ m_ui(new TargetSetupPageUi),
+ m_importWidget(new Internal::ImportWidget(this)),
+ m_spacer(new QSpacerItem(0,0, QSizePolicy::Minimum, QSizePolicy::MinimumExpanding)),
+ m_forceOptionHint(false)
+{
+ setObjectName(QLatin1String("TargetSetupPage"));
+ setWindowTitle(tr("Select Kits for Your Project"));
+ m_ui->setupUi(this);
+
+ QSizePolicy policy(QSizePolicy::Preferred, QSizePolicy::Preferred);
+ policy.setHorizontalStretch(0);
+ policy.setVerticalStretch(0);
+ policy.setHeightForWidth(sizePolicy().hasHeightForWidth());
+ setSizePolicy(policy);
+
+ QWidget *centralWidget = new QWidget(this);
+ m_ui->scrollArea->setWidget(centralWidget);
+ centralWidget->setLayout(new QVBoxLayout);
+ m_ui->centralWidget->setLayout(new QVBoxLayout);
+ m_ui->centralWidget->layout()->setMargin(0);
+
+ setUseScrollArea(true);
+ setImportSearch(false);
+
+ setTitle(tr("Kit Selection"));
+
+ QObject *km = KitManager::instance();
+ connect(km, SIGNAL(kitAdded(ProjectExplorer::Kit*)),
+ this, SLOT(handleKitAddition(ProjectExplorer::Kit*)));
+ connect(km, SIGNAL(kitRemoved(ProjectExplorer::Kit*)),
+ this, SLOT(handleKitRemoval(ProjectExplorer::Kit*)));
+ connect(km, SIGNAL(kitUpdated(ProjectExplorer::Kit*)),
+ this, SLOT(handleKitUpdate(ProjectExplorer::Kit*)));
+ connect(m_importWidget, SIGNAL(importFrom(Utils::FileName)),
+ this, SLOT(import(Utils::FileName)));
+}
+
+void TargetSetupPage::initializePage()
+{
+ m_baseLayout->addWidget(m_importWidget);
+ m_baseLayout->addItem(m_spacer);
+
+ reset();
+
+ setupWidgets();
+ setupImports();
+ selectAtLeastOneKit();
+}
+
+void TargetSetupPage::setRequiredKitMatcher(KitMatcher *matcher)
+{
+ m_requiredMatcher = matcher;
+}
+
+QList<Core::Id> TargetSetupPage::selectedKits() const
+{
+ QList<Core::Id> result;
+ QMap<Core::Id, Internal::TargetSetupWidget *>::const_iterator it, end;
+ it = m_widgets.constBegin();
+ end = m_widgets.constEnd();
+
+ for ( ; it != end; ++it) {
+ if (isKitSelected(it.key()))
+ result << it.key();
+ }
+ return result;
+}
+
+void TargetSetupPage::setPreferredKitMatcher(KitMatcher *matcher)
+{
+ m_preferredMatcher = matcher;
+}
+
+TargetSetupPage::~TargetSetupPage()
+{
+ reset();
+ delete m_ui;
+ delete m_preferredMatcher;
+ delete m_requiredMatcher;
+ delete m_importer;
+}
+
+bool TargetSetupPage::isKitSelected(Core::Id id) const
+{
+ TargetSetupWidget *widget = m_widgets.value(id);
+ return widget && widget->isKitSelected();
+}
+
+void TargetSetupPage::setKitSelected(Core::Id id, bool selected)
+{
+ TargetSetupWidget *widget = m_widgets.value(id);
+ if (widget)
+ widget->setKitSelected(selected);
+}
+
+bool TargetSetupPage::isComplete() const
+{
+ foreach (TargetSetupWidget *widget, m_widgets.values())
+ if (widget->isKitSelected())
+ return true;
+ return false;
+}
+
+void TargetSetupPage::setImportSearch(bool b)
+{
+ m_importSearch = b;
+ m_importWidget->setVisible(b);
+}
+
+void TargetSetupPage::setupWidgets()
+{
+ QList<Kit *> kitList;
+ // Known profiles:
+ if (m_requiredMatcher)
+ kitList = KitManager::matchingKits(*m_requiredMatcher);
+ else
+ kitList = KitManager::kits();
+
+ foreach (Kit *k, kitList)
+ addWidget(k);
+
+ // Setup import widget:
+ Utils::FileName path = Utils::FileName::fromString(m_projectPath);
+ path = path.parentDir(); // base dir
+ path = path.parentDir(); // parent dir
+ m_importWidget->setCurrentDirectory(path);
+
+ updateVisibility();
+}
+
+void TargetSetupPage::reset()
+{
+ foreach (TargetSetupWidget *widget, m_widgets.values()) {
+ Kit *k = widget->kit();
+ if (!k)
+ continue;
+ if (m_importer)
+ m_importer->removeProject(k, m_projectPath);
+ delete widget;
+ }
+
+ m_widgets.clear();
+ m_firstWidget = 0;
+}
+
+void TargetSetupPage::setProjectPath(const QString &path)
+{
+ m_projectPath = path;
+ if (!m_projectPath.isEmpty())
+ m_ui->headerLabel->setText(tr("Qt Creator can use the following kits for project <b>%1</b>:",
+ "%1: Project name").arg(QFileInfo(m_projectPath).baseName()));
+ m_ui->headerLabel->setVisible(!m_projectPath.isEmpty());
+
+ if (m_widgets.isEmpty())
+ return;
+
+ reset();
+ setupWidgets();
+}
+
+void TargetSetupPage::setProjectImporter(ProjectImporter *importer)
+{
+ if (m_importer)
+ delete m_importer;
+ m_importer = importer;
+
+ reset();
+ setupWidgets();
+}
+
+void TargetSetupPage::setNoteText(const QString &text)
+{
+ m_ui->descriptionLabel->setText(text);
+ m_ui->descriptionLabel->setVisible(!text.isEmpty());
+}
+
+void TargetSetupPage::showOptionsHint(bool show)
+{
+ m_forceOptionHint = show;
+ updateVisibility();
+}
+
+void TargetSetupPage::setupImports()
+{
+ if (!m_importer || !m_importSearch || m_projectPath.isEmpty())
+ return;
+
+ QStringList toImport = m_importer->importCandidates(Utils::FileName::fromString(m_projectPath));
+ foreach (const QString &path, toImport)
+ import(Utils::FileName::fromString(path), true);
+}
+
+void TargetSetupPage::handleKitAddition(Kit *k)
+{
+ if (isUpdating())
+ return;
+
+ Q_ASSERT(!m_widgets.contains(k->id()));
+ addWidget(k);
+ updateVisibility();
+}
+
+void TargetSetupPage::handleKitRemoval(Kit *k)
+{
+ if (m_importer)
+ m_importer->cleanupKit(k);
+
+ if (isUpdating())
+ return;
+
+ removeWidget(k);
+ updateVisibility();
+}
+
+void TargetSetupPage::handleKitUpdate(Kit *k)
+{
+ if (isUpdating())
+ return;
+
+ if (m_importer)
+ m_importer->makePermanent(k);
+
+ TargetSetupWidget *widget = m_widgets.value(k->id());
+
+ bool acceptable = true;
+ if (m_requiredMatcher && !m_requiredMatcher->matches(k))
+ acceptable = false;
+
+ if (widget && !acceptable)
+ removeWidget(k);
+ else if (!widget && acceptable)
+ addWidget(k);
+
+ updateVisibility();
+}
+
+void TargetSetupPage::selectAtLeastOneKit()
+{
+ bool atLeastOneKitSelected = false;
+ foreach (TargetSetupWidget *w, m_widgets.values()) {
+ if (w->isKitSelected()) {
+ atLeastOneKitSelected = true;
+ break;
+ }
+ }
+
+ if (!atLeastOneKitSelected) {
+ TargetSetupWidget *widget = m_firstWidget;
+ Kit *defaultKit = KitManager::defaultKit();
+ if (defaultKit)
+ widget = m_widgets.value(defaultKit->id(), m_firstWidget);
+ if (widget)
+ widget->setKitSelected(true);
+ m_firstWidget = 0;
+ }
+ emit completeChanged(); // Is this necessary?
+}
+
+void TargetSetupPage::updateVisibility()
+{
+ // Always show the widgets, the import widget always makes sense to show.
+ m_ui->scrollAreaWidget->setVisible(m_baseLayout == m_ui->scrollArea->widget()->layout());
+ m_ui->centralWidget->setVisible(m_baseLayout == m_ui->centralWidget->layout());
+
+ bool hasKits = !m_widgets.isEmpty();
+ m_ui->noValidKitLabel->setVisible(!hasKits);
+ m_ui->optionHintLabel->setVisible(m_forceOptionHint || !hasKits);
+
+ emit completeChanged();
+}
+
+void TargetSetupPage::openOptions()
+{
+ Core::ICore::instance()->showOptionsDialog(Constants::PROJECTEXPLORER_SETTINGS_CATEGORY,
+ Constants::KITS_SETTINGS_PAGE_ID,
+ this);
+}
+
+void TargetSetupPage::import(const Utils::FileName &path)
+{
+ import(path, false);
+}
+
+bool TargetSetupPage::isUpdating() const
+{
+ if (m_importer)
+ return m_importer->isUpdating();
+ return false;
+}
+
+void TargetSetupPage::import(const Utils::FileName &path, bool silent)
+{
+ if (!m_importer)
+ return;
+
+ QList<BuildInfo *> toImport = m_importer->import(path, silent);
+ foreach (BuildInfo *info, toImport) {
+ TargetSetupWidget *widget = m_widgets.value(info->kitId, 0);
+ if (!widget) {
+ Kit *k = KitManager::find(info->kitId);
+ Q_ASSERT(k);
+ addWidget(k);
+ }
+ widget = m_widgets.value(info->kitId, 0);
+ if (!widget) {
+ delete info;
+ continue;
+ }
+
+ widget->addBuildInfo(info, true);
+ widget->setKitSelected(true);
+ }
+}
+
+void TargetSetupPage::removeWidget(Kit *k)
+{
+ TargetSetupWidget *widget = m_widgets.value(k->id());
+ if (!widget)
+ return;
+ if (widget == m_firstWidget)
+ m_firstWidget = 0;
+ widget->deleteLater();
+ m_widgets.remove(k->id());
+}
+
+TargetSetupWidget *TargetSetupPage::addWidget(Kit *k)
+{
+ if (!k || (m_requiredMatcher && !m_requiredMatcher->matches(k)))
+ return 0;
+
+ IBuildConfigurationFactory *factory
+ = IBuildConfigurationFactory::find(k, m_projectPath);
+ if (!factory)
+ return 0;
+
+ QList<BuildInfo *> infoList = factory->availableSetups(k, m_projectPath);
+ TargetSetupWidget *widget = infoList.isEmpty() ? 0 : new TargetSetupWidget(k, m_projectPath, infoList);
+ if (!widget)
+ return 0;
+
+ m_baseLayout->removeWidget(m_importWidget);
+ m_baseLayout->removeItem(m_spacer);
+
+ widget->setKitSelected(m_preferredMatcher && m_preferredMatcher->matches(k));
+ m_widgets.insert(k->id(), widget);
+ m_baseLayout->addWidget(widget);
+
+ m_baseLayout->addWidget(m_importWidget);
+ m_baseLayout->addItem(m_spacer);
+
+ connect(widget, SIGNAL(selectedToggled()),
+ this, SIGNAL(completeChanged()));
+
+ if (!m_firstWidget)
+ m_firstWidget = widget;
+
+ return widget;
+}
+
+bool TargetSetupPage::setupProject(Project *project)
+{
+ QList<const BuildInfo *> toSetUp; // Pointers are managed by the widgets!
+ foreach (TargetSetupWidget *widget, m_widgets.values()) {
+ if (!widget->isKitSelected())
+ continue;
+
+ Kit *k = widget->kit();
+ if (m_importer)
+ m_importer->makePermanent(k);
+ toSetUp << widget->selectedBuildInfoList();
+ widget->clearKit();
+ }
+
+ project->setup(toSetUp);
+
+ reset(); // This will delete the pointers held in toSetUp!
+ toSetUp.clear();
+
+ Target *activeTarget = 0;
+ if (m_importer)
+ activeTarget = m_importer->preferredTarget(project->targets());
+ if (activeTarget)
+ project->setActiveTarget(activeTarget);
+
+ return true;
+}
+
+void TargetSetupPage::setUseScrollArea(bool b)
+{
+ m_baseLayout = b ? m_ui->scrollArea->widget()->layout() : m_ui->centralWidget->layout();
+ m_ui->scrollAreaWidget->setVisible(b);
+ m_ui->centralWidget->setVisible(!b);
+}
+
+} // namespace ProjectExplorer
diff --git a/src/plugins/qt4projectmanager/wizards/targetsetuppage.h b/src/plugins/projectexplorer/targetsetuppage.h
index 73dd8a601c..7018b5a7b0 100644
--- a/src/plugins/qt4projectmanager/wizards/targetsetuppage.h
+++ b/src/plugins/projectexplorer/targetsetuppage.h
@@ -30,7 +30,9 @@
#ifndef TARGETSETUPPAGE_H
#define TARGETSETUPPAGE_H
-#include "../qt4projectmanager_global.h"
+#include "projectexplorer_export.h"
+
+#include "projectimporter.h"
#include <QString>
#include <QWizardPage>
@@ -38,44 +40,36 @@
QT_FORWARD_DECLARE_CLASS(QSpacerItem)
+namespace Core { class Id; }
namespace Utils { class FileName; }
-namespace Core {
-class Id;
-} // namespace Core
-
namespace ProjectExplorer {
class Kit;
class KitMatcher;
-} // namespace ProjectExplorer
-
-namespace QtSupport { class BaseQtVersion; }
-
-namespace Qt4ProjectManager {
-class Qt4Project;
-class Qt4TargetSetupWidget;
+class Project;
namespace Internal {
class ImportWidget;
class TargetSetupPageUi;
+class TargetSetupWidget;
} // namespace Internal
/// \internal
-class QT4PROJECTMANAGER_EXPORT TargetSetupPage : public QWizardPage
+class PROJECTEXPLORER_EXPORT TargetSetupPage : public QWizardPage
{
Q_OBJECT
public:
- explicit TargetSetupPage(QWidget* parent = 0);
+ explicit TargetSetupPage(QWidget *parent = 0);
~TargetSetupPage();
/// Initializes the TargetSetupPage
- /// \note The import information is gathered in initializePage(), make sure that the right proFilePath is set before
+ /// \note The import information is gathered in initializePage(), make sure that the right projectPath is set before
void initializePage();
// Call these before initializePage!
- void setRequiredKitMatcher(ProjectExplorer::KitMatcher *matcher);
- void setPreferredKitMatcher(ProjectExplorer::KitMatcher *matcher);
+ void setRequiredKitMatcher(KitMatcher *matcher);
+ void setPreferredKitMatcher(KitMatcher *matcher);
void setImportSearch(bool b);
/// Sets whether the targetsetupage uses a scrollarea
@@ -84,50 +78,46 @@ public:
void setUseScrollArea(bool b);
bool isComplete() const;
- bool setupProject(Qt4ProjectManager::Qt4Project *project);
+ bool setupProject(Project *project);
bool isKitSelected(Core::Id id) const;
void setKitSelected(Core::Id id, bool selected);
QList<Core::Id> selectedKits() const;
- void setProFilePath(const QString &dir);
+ void setProjectPath(const QString &dir);
+ void setProjectImporter(ProjectImporter *importer);
/// Overrides the summary text of the targetsetuppage
void setNoteText(const QString &text);
void showOptionsHint(bool show);
private slots:
- void import(const Utils::FileName &path);
- void handleQtUpdate(const QList<int> &add, const QList<int> &rm, const QList<int> &mod);
void handleKitAddition(ProjectExplorer::Kit *k);
void handleKitRemoval(ProjectExplorer::Kit *k);
void handleKitUpdate(ProjectExplorer::Kit *k);
void updateVisibility();
void openOptions();
+ void import(const Utils::FileName &path);
private:
+ bool isUpdating() const;
void selectAtLeastOneKit();
- void import(const Utils::FileName &path, const bool silent);
- void removeWidget(ProjectExplorer::Kit *k);
- Qt4TargetSetupWidget *addWidget(ProjectExplorer::Kit *k);
+ void removeWidget(Kit *k);
+ Internal::TargetSetupWidget *addWidget(Kit *k);
void setupImports();
+ void import(const Utils::FileName &path, bool silent);
void setupWidgets();
void reset();
- ProjectExplorer::Kit *createTemporaryKit(QtSupport::BaseQtVersion *version, bool temporaryVersion, const Utils::FileName &parsedSpec);
- void cleanKit(ProjectExplorer::Kit *k);
- void makeQtPersistent(ProjectExplorer::Kit *k);
- void addProject(ProjectExplorer::Kit *k, const QString &path);
- void removeProject(ProjectExplorer::Kit *k, const QString &path);
-
- ProjectExplorer::KitMatcher *m_requiredMatcher;
- ProjectExplorer::KitMatcher *m_preferredMatcher;
+
+ KitMatcher *m_requiredMatcher;
+ KitMatcher *m_preferredMatcher;
+ ProjectImporter *m_importer;
QLayout *m_baseLayout;
bool m_importSearch;
- bool m_ignoreUpdates;
- QString m_proFilePath;
+ QString m_projectPath;
QString m_defaultShadowBuildLocation;
- QMap<Core::Id, Qt4TargetSetupWidget *> m_widgets;
- Qt4TargetSetupWidget *m_firstWidget;
+ QMap<Core::Id, Internal::TargetSetupWidget *> m_widgets;
+ Internal::TargetSetupWidget *m_firstWidget;
Internal::TargetSetupPageUi *m_ui;
@@ -137,6 +127,6 @@ private:
bool m_forceOptionHint;
};
-} // namespace Qt4ProjectManager
+} // namespace ProjectExplorer
#endif // TARGETSETUPPAGE_H
diff --git a/src/plugins/qt4projectmanager/qt4targetsetupwidget.cpp b/src/plugins/projectexplorer/targetsetupwidget.cpp
index 638276b9c3..239e1f3e4e 100644
--- a/src/plugins/qt4projectmanager/qt4targetsetupwidget.cpp
+++ b/src/plugins/projectexplorer/targetsetupwidget.cpp
@@ -27,17 +27,17 @@
**
****************************************************************************/
-#include "qt4targetsetupwidget.h"
+#include "targetsetupwidget.h"
-#include "buildconfigurationinfo.h"
-#include "qt4buildconfiguration.h"
+#include "buildconfiguration.h"
+#include "buildinfo.h"
+#include "projectexplorerconstants.h"
+#include "kit.h"
+#include "kitmanager.h"
+#include "kitoptionspage.h"
#include <coreplugin/icore.h>
#include <extensionsystem/pluginmanager.h>
-#include <projectexplorer/projectexplorerconstants.h>
-#include <projectexplorer/kitoptionspage.h>
-#include <qtsupport/qtkitinformation.h>
-
#include <utils/detailsbutton.h>
#include <utils/detailswidget.h>
#include <utils/hostosinfo.h>
@@ -49,15 +49,16 @@
#include <QLabel>
#include <QPushButton>
-namespace Qt4ProjectManager {
+namespace ProjectExplorer {
+namespace Internal {
// -------------------------------------------------------------------------
-// Qt4TargetSetupWidget
+// TargetSetupWidget
// -------------------------------------------------------------------------
-Qt4TargetSetupWidget::Qt4TargetSetupWidget(ProjectExplorer::Kit *k,
- const QString &proFilePath,
- const QList<BuildConfigurationInfo> &infoList) :
+TargetSetupWidget::TargetSetupWidget(Kit *k,
+ const QString &projectPath,
+ const QList<BuildInfo *> &infoList) :
m_kit(k),
m_haveImported(false),
m_ignoreChange(false),
@@ -100,45 +101,48 @@ Qt4TargetSetupWidget::Qt4TargetSetupWidget(ProjectExplorer::Kit *k,
widget->setEnabled(false);
m_detailsWidget->setWidget(widget);
- foreach (const BuildConfigurationInfo &info, infoList)
- addBuildConfigurationInfo(info);
+ foreach (BuildInfo *info, infoList)
+ addBuildInfo(info, false);
- setProFilePath(proFilePath);
+ setProjectPath(projectPath);
connect(m_detailsWidget, SIGNAL(checked(bool)),
this, SLOT(targetCheckBoxToggled(bool)));
- connect(ProjectExplorer::KitManager::instance(), SIGNAL(kitUpdated(ProjectExplorer::Kit*)),
+ connect(KitManager::instance(), SIGNAL(kitUpdated(ProjectExplorer::Kit*)),
this, SLOT(handleKitUpdate(ProjectExplorer::Kit*)));
connect(m_manageButton, SIGNAL(clicked()), this, SLOT(manageKit()));
}
-Qt4TargetSetupWidget::~Qt4TargetSetupWidget()
-{ }
+TargetSetupWidget::~TargetSetupWidget()
+{
+ qDeleteAll(m_infoList);
+ m_infoList.clear();
+}
-ProjectExplorer::Kit *Qt4TargetSetupWidget::kit()
+Kit *TargetSetupWidget::kit()
{
return m_kit;
}
-void Qt4TargetSetupWidget::clearKit()
+void TargetSetupWidget::clearKit()
{
m_kit = 0;
}
-bool Qt4TargetSetupWidget::isKitSelected() const
+bool TargetSetupWidget::isKitSelected() const
{
if (!m_detailsWidget->isChecked())
return false;
- return !selectedBuildConfigurationInfoList().isEmpty();
+ return !selectedBuildInfoList().isEmpty();
}
-void Qt4TargetSetupWidget::setKitSelected(bool b)
+void TargetSetupWidget::setKitSelected(bool b)
{
// Only check target if there are build configurations possible
- b &= !selectedBuildConfigurationInfoList().isEmpty();
+ b &= !selectedBuildInfoList().isEmpty();
m_ignoreChange = true;
m_detailsWidget->setChecked(b);
m_detailsWidget->widget()->setEnabled(b);
@@ -147,39 +151,36 @@ void Qt4TargetSetupWidget::setKitSelected(bool b)
m_detailsWidget->setState(b ? Utils::DetailsWidget::Expanded : Utils::DetailsWidget::Collapsed);
}
-void Qt4TargetSetupWidget::addBuildConfigurationInfo(const BuildConfigurationInfo &info, bool importing)
+void TargetSetupWidget::addBuildInfo(BuildInfo *info, bool isImport)
{
- if (importing) {
- if (!m_haveImported) {
- // disable everything on first import
- for (int i = 0; i < m_enabled.count(); ++i) {
- m_enabled[i] = false;
- m_checkboxes[i]->setChecked(false);
- }
- m_selected = 0;
+ if (isImport && !m_haveImported) {
+ // disable everything on first import
+ for (int i = 0; i < m_enabled.count(); ++i) {
+ m_enabled[i] = false;
+ m_checkboxes[i]->setChecked(false);
}
+ m_selected = 0;
m_haveImported = true;
}
+
int pos = m_pathChoosers.count();
m_enabled.append(true);
++m_selected;
- m_infoList.append(info);
+ m_infoList << info;
QCheckBox *checkbox = new QCheckBox;
- checkbox->setText(Qt4BuildConfigurationFactory::buildConfigurationDisplayName(info));
+ checkbox->setText(info->displayName);
checkbox->setChecked(m_enabled.at(pos));
checkbox->setAttribute(Qt::WA_LayoutUsesWidgetRect);
m_newBuildsLayout->addWidget(checkbox, pos * 2, 0);
Utils::PathChooser *pathChooser = new Utils::PathChooser();
pathChooser->setExpectedKind(Utils::PathChooser::Directory);
- pathChooser->setPath(info.directory);
- QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(m_kit);
- if (!version)
- return;
- pathChooser->setReadOnly(!version->supportsShadowBuilds() || importing);
+ pathChooser->setFileName(info->buildDirectory);
+ pathChooser->setEnabled(info->supportsShadowBuild);
+ pathChooser->setReadOnly(!info->supportsShadowBuild || isImport);
m_newBuildsLayout->addWidget(pathChooser, pos * 2, 1);
QLabel *reportIssuesLabel = new QLabel;
@@ -203,7 +204,7 @@ void Qt4TargetSetupWidget::addBuildConfigurationInfo(const BuildConfigurationInf
emit selectedToggled();
}
-void Qt4TargetSetupWidget::targetCheckBoxToggled(bool b)
+void TargetSetupWidget::targetCheckBoxToggled(bool b)
{
if (m_ignoreChange)
return;
@@ -215,37 +216,45 @@ void Qt4TargetSetupWidget::targetCheckBoxToggled(bool b)
break;
}
}
+ } else {
+ m_detailsWidget->setState(Utils::DetailsWidget::Collapsed);
}
emit selectedToggled();
}
-void Qt4TargetSetupWidget::manageKit()
+void TargetSetupWidget::manageKit()
{
ProjectExplorer::KitOptionsPage *page =
- ExtensionSystem::PluginManager::instance()->getObject<ProjectExplorer::KitOptionsPage>();
+ ExtensionSystem::PluginManager::getObject<ProjectExplorer::KitOptionsPage>();
if (!page || !m_kit)
return;
page->showKit(m_kit);
- Core::ICore::showOptionsDialog(ProjectExplorer::Constants::PROJECTEXPLORER_SETTINGS_CATEGORY,
- ProjectExplorer::Constants::KITS_SETTINGS_PAGE_ID);
+ Core::ICore::showOptionsDialog(Constants::PROJECTEXPLORER_SETTINGS_CATEGORY,
+ Constants::KITS_SETTINGS_PAGE_ID);
}
-void Qt4TargetSetupWidget::setProFilePath(const QString &proFilePath)
+void TargetSetupWidget::setProjectPath(const QString &projectPath)
{
if (!m_kit)
return;
- m_proFilePath = proFilePath;
+ m_projectPath = projectPath;
clear();
- QList<BuildConfigurationInfo> infoList
- = Qt4BuildConfigurationFactory::availableBuildConfigurations(m_kit, proFilePath);
- foreach (const BuildConfigurationInfo &info, infoList)
- addBuildConfigurationInfo(info);
+ IBuildConfigurationFactory *factory
+ = IBuildConfigurationFactory::find(m_kit, projectPath);
+
+ if (!factory)
+ return;
+
+ QList<BuildInfo *> infoList
+ = factory->availableSetups(m_kit, projectPath);
+ foreach (BuildInfo *info, infoList)
+ addBuildInfo(info, false);
}
-void Qt4TargetSetupWidget::handleKitUpdate(ProjectExplorer::Kit *k)
+void TargetSetupWidget::handleKitUpdate(Kit *k)
{
if (k != m_kit)
return;
@@ -254,9 +263,9 @@ void Qt4TargetSetupWidget::handleKitUpdate(ProjectExplorer::Kit *k)
m_detailsWidget->setSummaryText(k->displayName());
}
-QList<BuildConfigurationInfo> Qt4TargetSetupWidget::selectedBuildConfigurationInfoList() const
+QList<const BuildInfo *> TargetSetupWidget::selectedBuildInfoList() const
{
- QList<BuildConfigurationInfo> result;
+ QList<const BuildInfo *> result;
for (int i = 0; i < m_infoList.count(); ++i) {
if (m_enabled.at(i))
result.append(m_infoList.at(i));
@@ -264,12 +273,7 @@ QList<BuildConfigurationInfo> Qt4TargetSetupWidget::selectedBuildConfigurationIn
return result;
}
-QList<BuildConfigurationInfo> Qt4TargetSetupWidget::allBuildConfigurationInfoList() const
-{
- return m_infoList;
-}
-
-void Qt4TargetSetupWidget::clear()
+void TargetSetupWidget::clear()
{
qDeleteAll(m_checkboxes);
m_checkboxes.clear();
@@ -277,8 +281,9 @@ void Qt4TargetSetupWidget::clear()
m_pathChoosers.clear();
qDeleteAll(m_reportIssuesLabels);
m_reportIssuesLabels.clear();
-
+ qDeleteAll(m_infoList);
m_infoList.clear();
+
m_issues.clear();
m_enabled.clear();
m_selected = 0;
@@ -287,7 +292,7 @@ void Qt4TargetSetupWidget::clear()
emit selectedToggled();
}
-void Qt4TargetSetupWidget::checkBoxToggled(bool b)
+void TargetSetupWidget::checkBoxToggled(bool b)
{
QCheckBox *box = qobject_cast<QCheckBox *>(sender());
if (!box)
@@ -305,7 +310,7 @@ void Qt4TargetSetupWidget::checkBoxToggled(bool b)
}
}
-void Qt4TargetSetupWidget::pathChanged()
+void TargetSetupWidget::pathChanged()
{
if (m_ignoreChange)
return;
@@ -315,45 +320,41 @@ void Qt4TargetSetupWidget::pathChanged()
int index = m_pathChoosers.indexOf(pathChooser);
if (index == -1)
return;
- m_infoList[index].directory = pathChooser->path();
+ m_infoList[index]->buildDirectory = pathChooser->fileName();
reportIssues(index);
}
-void Qt4TargetSetupWidget::reportIssues(int index)
+void TargetSetupWidget::reportIssues(int index)
{
- QPair<ProjectExplorer::Task::TaskType, QString> issues = findIssues(m_infoList.at(index));
+ QPair<Task::TaskType, QString> issues = findIssues(m_infoList.at(index));
QLabel *reportIssuesLabel = m_reportIssuesLabels.at(index);
reportIssuesLabel->setText(issues.second);
- bool error = issues.first != ProjectExplorer::Task::Unknown;
+ bool error = issues.first != Task::Unknown;
reportIssuesLabel->setVisible(error);
m_issues[index] = error;
}
-QPair<ProjectExplorer::Task::TaskType, QString> Qt4TargetSetupWidget::findIssues(const BuildConfigurationInfo &info)
+QPair<Task::TaskType, QString> TargetSetupWidget::findIssues(const BuildInfo *info)
{
- if (m_proFilePath.isEmpty())
- return qMakePair(ProjectExplorer::Task::Unknown, QString());
-
- QString buildDir = info.directory;
- QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(m_kit);
- if (!version)
- return qMakePair(ProjectExplorer::Task::Unknown, QString());
+ if (m_projectPath.isEmpty())
+ return qMakePair(Task::Unknown, QString());
- QList<ProjectExplorer::Task> issues = version->reportIssues(m_proFilePath, buildDir);
+ QString buildDir = info->buildDirectory.toString();
+ QList<Task> issues = info->reportIssues(m_projectPath, buildDir);
QString text;
- ProjectExplorer::Task::TaskType highestType = ProjectExplorer::Task::Unknown;
- foreach (const ProjectExplorer::Task &t, issues) {
+ Task::TaskType highestType = Task::Unknown;
+ foreach (const Task &t, issues) {
if (!text.isEmpty())
text.append(QLatin1String("<br>"));
// set severity:
QString severity;
- if (t.type == ProjectExplorer::Task::Error) {
- highestType = ProjectExplorer::Task::Error;
+ if (t.type == Task::Error) {
+ highestType = Task::Error;
severity = tr("<b>Error:</b> ", "Severity is Task::Error");
- } else if (t.type == ProjectExplorer::Task::Warning) {
- if (highestType == ProjectExplorer::Task::Unknown)
- highestType = ProjectExplorer::Task::Warning;
+ } else if (t.type == Task::Warning) {
+ if (highestType == Task::Unknown)
+ highestType = Task::Warning;
severity = tr("<b>Warning:</b> ", "Severity is Task::Warning");
}
text.append(severity + t.description);
@@ -363,4 +364,5 @@ QPair<ProjectExplorer::Task::TaskType, QString> Qt4TargetSetupWidget::findIssues
return qMakePair(highestType, text);
}
-} // namespace Qt4ProjectManager
+} // namespace Internal
+} // namespace ProjectExplorer
diff --git a/src/plugins/qt4projectmanager/qt4targetsetupwidget.h b/src/plugins/projectexplorer/targetsetupwidget.h
index a17fe6a51a..0c67e86167 100644
--- a/src/plugins/qt4projectmanager/qt4targetsetupwidget.h
+++ b/src/plugins/projectexplorer/targetsetupwidget.h
@@ -27,12 +27,13 @@
**
****************************************************************************/
-#ifndef QT4TARGETSETUPWIDGET_H
-#define QT4TARGETSETUPWIDGET_H
+#ifndef TARGETSETUPWIDGET_H
+#define TARGETSETUPWIDGET_H
-#include "qt4projectmanager_global.h"
+#include "projectexplorer_export.h"
-#include <projectexplorer/task.h>
+#include "buildinfo.h"
+#include "task.h"
#include <QWidget>
@@ -45,38 +46,36 @@ class QPushButton;
class QSpacerItem;
QT_END_NAMESPACE
-namespace ProjectExplorer { class Kit; }
-namespace QtSupport {
-class BaseQtVersion;
-} // namespace QtSupport
namespace Utils {
class DetailsWidget;
class PathChooser;
} // namespace Utils
-namespace Qt4ProjectManager {
-class BuildConfigurationInfo;
+namespace ProjectExplorer {
+class BuildInfo;
+class Kit;
-class QT4PROJECTMANAGER_EXPORT Qt4TargetSetupWidget : public QWidget
+namespace Internal {
+
+class TargetSetupWidget : public QWidget
{
Q_OBJECT
public:
- Qt4TargetSetupWidget(ProjectExplorer::Kit *k,
- const QString &proFilePath,
- const QList<BuildConfigurationInfo> &infoList);
- ~Qt4TargetSetupWidget();
+ TargetSetupWidget(Kit *k,
+ const QString &projectPath,
+ const QList<BuildInfo *> &infoList);
+ ~TargetSetupWidget();
- ProjectExplorer::Kit *kit();
+ Kit *kit();
void clearKit();
bool isKitSelected() const;
void setKitSelected(bool b);
- void addBuildConfigurationInfo(const BuildConfigurationInfo &info, bool importing = false);
+ void addBuildInfo(BuildInfo *info, bool isImport);
- QList<BuildConfigurationInfo> selectedBuildConfigurationInfoList() const;
- QList<BuildConfigurationInfo> allBuildConfigurationInfoList() const;
- void setProFilePath(const QString &proFilePath);
+ QList<const BuildInfo *> selectedBuildInfoList() const;
+ void setProjectPath(const QString &projectPath);
signals:
void selectedToggled() const;
@@ -91,18 +90,18 @@ private slots:
private:
void reportIssues(int index);
- QPair<ProjectExplorer::Task::TaskType, QString> findIssues(const BuildConfigurationInfo &info);
+ QPair<Task::TaskType, QString> findIssues(const BuildInfo *info);
void clear();
- ProjectExplorer::Kit *m_kit;
- QString m_proFilePath;
+ Kit *m_kit;
+ QString m_projectPath;
bool m_haveImported;
Utils::DetailsWidget *m_detailsWidget;
QPushButton *m_manageButton;
QGridLayout *m_newBuildsLayout;
QList<QCheckBox *> m_checkboxes;
QList<Utils::PathChooser *> m_pathChoosers;
- QList<BuildConfigurationInfo> m_infoList;
+ QList<BuildInfo *> m_infoList;
QList<bool> m_enabled;
QList<QLabel *> m_reportIssuesLabels;
QList<bool> m_issues;
@@ -110,6 +109,7 @@ private:
int m_selected; // Number of selected buildconfiguartions
};
-} // namespace Qt4ProjectManager
+} // namespace Internal
+} // namespace ProjectExplorer
-#endif // QT4TARGETSETUPWIDGET_H
+#endif // TARGETSETUPWIDGET_H
diff --git a/src/plugins/projectexplorer/task.cpp b/src/plugins/projectexplorer/task.cpp
index 8fb79e097a..9f6796e1b8 100644
--- a/src/plugins/projectexplorer/task.cpp
+++ b/src/plugins/projectexplorer/task.cpp
@@ -44,7 +44,7 @@ Task::Task() : taskId(0), type(Unknown), line(-1)
{ }
Task::Task(TaskType type_, const QString &description_,
- const Utils::FileName &file_, int line_, const Core::Id &category_) :
+ const Utils::FileName &file_, int line_, Core::Id category_) :
taskId(s_nextId), type(type_), description(description_),
file(file_), line(line_), movedLine(line_), category(category_)
{
@@ -57,7 +57,9 @@ void Task::addMark(TextEditor::BaseTextMark *mark)
}
bool Task::isNull() const
-{ return taskId == 0; }
+{
+ return taskId == 0;
+}
void Task::clear()
{
diff --git a/src/plugins/projectexplorer/task.h b/src/plugins/projectexplorer/task.h
index a789f8951e..98782b201d 100644
--- a/src/plugins/projectexplorer/task.h
+++ b/src/plugins/projectexplorer/task.h
@@ -53,8 +53,8 @@ public:
};
Task();
- Task(TaskType type_, const QString &description_,
- const Utils::FileName &file_, int line_, const Core::Id &category_);
+ Task(TaskType type, const QString &description,
+ const Utils::FileName &file, int line, Core::Id category);
bool isNull() const;
void clear();
diff --git a/src/plugins/projectexplorer/taskhub.cpp b/src/plugins/projectexplorer/taskhub.cpp
index eb7272db09..1cc702050b 100644
--- a/src/plugins/projectexplorer/taskhub.cpp
+++ b/src/plugins/projectexplorer/taskhub.cpp
@@ -28,11 +28,14 @@
****************************************************************************/
#include "taskhub.h"
-#include "projectexplorer.h"
+
#include <coreplugin/ioutputpane.h>
+#include <utils/qtcassert.h>
using namespace ProjectExplorer;
+TaskHub *m_instance = 0;
+
class TaskMark : public TextEditor::BaseTextMark
{
public:
@@ -54,19 +57,19 @@ private:
void TaskMark::updateLineNumber(int lineNumber)
{
- ProjectExplorerPlugin::instance()->taskHub()->updateTaskLineNumber(m_id, lineNumber);
+ TaskHub::updateTaskLineNumber(m_id, lineNumber);
BaseTextMark::updateLineNumber(lineNumber);
}
void TaskMark::updateFileName(const QString &fileName)
{
- ProjectExplorerPlugin::instance()->taskHub()->updateTaskFileName(m_id, fileName);
+ TaskHub::updateTaskFileName(m_id, fileName);
BaseTextMark::updateFileName(fileName);
}
void TaskMark::removedFromEditor()
{
- ProjectExplorerPlugin::instance()->taskHub()->updateTaskLineNumber(m_id, -1);
+ TaskHub::updateTaskLineNumber(m_id, -1);
}
bool TaskMark::isClickable() const
@@ -76,25 +79,37 @@ bool TaskMark::isClickable() const
void TaskMark::clicked()
{
- ProjectExplorerPlugin::instance()->taskHub()->taskMarkClicked(m_id);
+ TaskHub::taskMarkClicked(m_id);
}
TaskHub::TaskHub()
: m_errorIcon(QLatin1String(":/projectexplorer/images/compile_error.png")),
m_warningIcon(QLatin1String(":/projectexplorer/images/compile_warning.png"))
{
+ m_instance = this;
qRegisterMetaType<ProjectExplorer::Task>("ProjectExplorer::Task");
qRegisterMetaType<QList<ProjectExplorer::Task> >("QList<ProjectExplorer::Task>");
}
TaskHub::~TaskHub()
{
+ m_instance = 0;
+}
+void TaskHub::addCategory(Core::Id categoryId, const QString &displayName, bool visible)
+{
+ QTC_CHECK(!displayName.isEmpty());
+ emit m_instance->categoryAdded(categoryId, displayName, visible);
+}
+
+QObject *TaskHub::instance()
+{
+ return m_instance;
}
-void TaskHub::addCategory(const Core::Id &categoryId, const QString &displayName, bool visible)
+void TaskHub::addTask(Task::TaskType type, const QString &description, Core::Id category, const Utils::FileName &file, int line)
{
- emit categoryAdded(categoryId, displayName, visible);
+ addTask(Task(type, description, file, line, category));
}
void TaskHub::addTask(Task task)
@@ -105,60 +120,60 @@ void TaskHub::addTask(Task task)
mark->setIcon(taskTypeIcon(task.type));
mark->setPriority(TextEditor::ITextMark::LowPriority);
task.addMark(mark);
- emit taskAdded(task);
+ emit m_instance->taskAdded(task);
mark->init();
} else {
- emit taskAdded(task);
+ emit m_instance->taskAdded(task);
}
}
-void TaskHub::clearTasks(const Core::Id &categoryId)
+void TaskHub::clearTasks(Core::Id categoryId)
{
- emit tasksCleared(categoryId);
+ emit m_instance->tasksCleared(categoryId);
}
void TaskHub::removeTask(const Task &task)
{
- emit taskRemoved(task);
+ emit m_instance->taskRemoved(task);
}
void TaskHub::updateTaskFileName(unsigned int id, const QString &fileName)
{
- emit taskFileNameUpdated(id, fileName);
+ emit m_instance->taskFileNameUpdated(id, fileName);
}
void TaskHub::updateTaskLineNumber(unsigned int id, int line)
{
- emit taskLineNumberUpdated(id, line);
+ emit m_instance->taskLineNumberUpdated(id, line);
}
void TaskHub::taskMarkClicked(unsigned int id)
{
- emit showTask(id);
+ emit m_instance->showTask(id);
}
void TaskHub::showTaskInEditor(unsigned int id)
{
- emit openTask(id);
+ emit m_instance->openTask(id);
}
void TaskHub::setCategoryVisibility(const Core::Id &categoryId, bool visible)
{
- emit categoryVisibilityChanged(categoryId, visible);
+ emit m_instance->categoryVisibilityChanged(categoryId, visible);
}
void TaskHub::requestPopup()
{
- emit popupRequested(Core::IOutputPane::NoModeSwitch);
+ emit m_instance->popupRequested(Core::IOutputPane::NoModeSwitch);
}
-QIcon TaskHub::taskTypeIcon(Task::TaskType t) const
+QIcon TaskHub::taskTypeIcon(Task::TaskType t)
{
switch (t) {
case Task::Warning:
- return m_warningIcon;
+ return m_instance->m_warningIcon;
case Task::Error:
- return m_errorIcon;
+ return m_instance->m_errorIcon;
case Task::Unknown:
break;
}
diff --git a/src/plugins/projectexplorer/taskhub.h b/src/plugins/projectexplorer/taskhub.h
index 90f77abd75..0c4f82e772 100644
--- a/src/plugins/projectexplorer/taskhub.h
+++ b/src/plugins/projectexplorer/taskhub.h
@@ -36,46 +36,59 @@
#include <QIcon>
namespace ProjectExplorer {
-class Task;
+
+class ProjectExplorerPlugin;
class PROJECTEXPLORER_EXPORT TaskHub : public QObject
{
Q_OBJECT
public:
- TaskHub();
- virtual ~TaskHub();
+ static QObject *instance();
+
+ // Convenience overload
+ static void addTask(Task::TaskType type, const QString &description,
+ Core::Id category,
+ const Utils::FileName &file = Utils::FileName(),
+ int line = -1);
public slots:
- void addCategory(const Core::Id &categoryId, const QString &displayName, bool visible = true);
- void addTask(ProjectExplorer::Task task);
- void clearTasks(const Core::Id &categoryId = Core::Id());
- void removeTask(const ProjectExplorer::Task &task);
+ static void addTask(ProjectExplorer::Task task);
+ static void clearTasks(Core::Id categoryId = Core::Id());
+ static void removeTask(const ProjectExplorer::Task &task);
public:
- void updateTaskFileName(unsigned int id, const QString &fileName);
- void updateTaskLineNumber(unsigned int id, int line);
- void taskMarkClicked(unsigned int id);
- void showTaskInEditor(unsigned int id);
- void setCategoryVisibility(const Core::Id &categoryId, bool visible);
+ static void addCategory(Core::Id categoryId, const QString &displayName, bool visible = true);
+ static void updateTaskFileName(unsigned int id, const QString &fileName);
+ static void updateTaskLineNumber(unsigned int id, int line);
+ static void taskMarkClicked(unsigned int id);
+ static void showTaskInEditor(unsigned int id);
+ static void setCategoryVisibility(const Core::Id &categoryId, bool visible);
- void requestPopup();
+ static void requestPopup();
- QIcon taskTypeIcon(ProjectExplorer::Task::TaskType t) const;
+ static QIcon taskTypeIcon(ProjectExplorer::Task::TaskType t);
signals:
- void categoryAdded(const Core::Id &categoryId, const QString &displayName, bool visible);
+ void categoryAdded(Core::Id categoryId, const QString &displayName, bool visible);
void taskAdded(const ProjectExplorer::Task &task);
void taskRemoved(const ProjectExplorer::Task &task);
- void tasksCleared(const Core::Id &categoryId);
+ void tasksCleared(Core::Id categoryId);
void taskFileNameUpdated(unsigned int id, const QString &fileName);
void taskLineNumberUpdated(unsigned int id, int line);
void categoryVisibilityChanged(const Core::Id &categoryId, bool visible);
void popupRequested(int);
void showTask(unsigned int id);
void openTask(unsigned int id);
+
private:
+ TaskHub();
+ ~TaskHub();
+
const QIcon m_errorIcon;
const QIcon m_warningIcon;
+
+ friend class ProjectExplorerPlugin;
};
+
} // namespace ProjectExplorer
#endif // TASKHUB_H
diff --git a/src/plugins/projectexplorer/taskmodel.cpp b/src/plugins/projectexplorer/taskmodel.cpp
index c4234ecc90..85f38123f5 100644
--- a/src/plugins/projectexplorer/taskmodel.cpp
+++ b/src/plugins/projectexplorer/taskmodel.cpp
@@ -341,7 +341,7 @@ void TaskModel::setFileNotFound(const QModelIndex &idx, bool b)
/////
TaskFilterModel::TaskFilterModel(TaskModel *sourceModel, QObject *parent) : QAbstractItemModel(parent),
- m_sourceModel(sourceModel)
+ m_mappingUpToDate(false), m_sourceModel(sourceModel)
{
Q_ASSERT(m_sourceModel);
connect(m_sourceModel, SIGNAL(rowsInserted(QModelIndex,int,int)),
diff --git a/src/plugins/projectexplorer/taskwindow.cpp b/src/plugins/projectexplorer/taskwindow.cpp
index d89e0a7aae..ce094aeff8 100644
--- a/src/plugins/projectexplorer/taskwindow.cpp
+++ b/src/plugins/projectexplorer/taskwindow.cpp
@@ -198,7 +198,6 @@ public:
QToolButton *m_filterWarningsButton;
QToolButton *m_categoriesButton;
QMenu *m_categoriesMenu;
- TaskHub *m_taskHub;
int m_badgeCount;
QList<QAction *> m_actions;
};
@@ -217,7 +216,7 @@ static QToolButton *createFilterButton(QIcon icon, const QString &toolTip,
return button;
}
-TaskWindow::TaskWindow(TaskHub *taskhub) : d(new TaskWindowPrivate)
+TaskWindow::TaskWindow() : d(new TaskWindowPrivate)
{
d->m_defaultHandler = 0;
@@ -236,7 +235,6 @@ TaskWindow::TaskWindow(TaskHub *taskhub) : d(new TaskWindowPrivate)
d->m_listview->setAttribute(Qt::WA_MacShowFocusRect, false);
d->m_taskWindowContext = new Internal::TaskWindowContext(d->m_listview);
- d->m_taskHub = taskhub;
d->m_badgeCount = 0;
Core::ICore::addContextObject(d->m_taskWindowContext);
@@ -270,25 +268,26 @@ TaskWindow::TaskWindow(TaskHub *taskhub) : d(new TaskWindowPrivate)
d->m_categoriesButton->setMenu(d->m_categoriesMenu);
- connect(d->m_taskHub, SIGNAL(categoryAdded(Core::Id,QString,bool)),
+ QObject *hub = TaskHub::instance();
+ connect(hub, SIGNAL(categoryAdded(Core::Id,QString,bool)),
this, SLOT(addCategory(Core::Id,QString,bool)));
- connect(d->m_taskHub, SIGNAL(taskAdded(ProjectExplorer::Task)),
+ connect(hub, SIGNAL(taskAdded(ProjectExplorer::Task)),
this, SLOT(addTask(ProjectExplorer::Task)));
- connect(d->m_taskHub, SIGNAL(taskRemoved(ProjectExplorer::Task)),
+ connect(hub, SIGNAL(taskRemoved(ProjectExplorer::Task)),
this, SLOT(removeTask(ProjectExplorer::Task)));
- connect(d->m_taskHub, SIGNAL(taskLineNumberUpdated(uint,int)),
+ connect(hub, SIGNAL(taskLineNumberUpdated(uint,int)),
this, SLOT(updatedTaskLineNumber(uint,int)));
- connect(d->m_taskHub, SIGNAL(taskFileNameUpdated(uint,QString)),
+ connect(hub, SIGNAL(taskFileNameUpdated(uint,QString)),
this, SLOT(updatedTaskFileName(uint,QString)));
- connect(d->m_taskHub, SIGNAL(tasksCleared(Core::Id)),
+ connect(hub, SIGNAL(tasksCleared(Core::Id)),
this, SLOT(clearTasks(Core::Id)));
- connect(d->m_taskHub, SIGNAL(categoryVisibilityChanged(Core::Id,bool)),
+ connect(hub, SIGNAL(categoryVisibilityChanged(Core::Id,bool)),
this, SLOT(setCategoryVisibility(Core::Id,bool)));
- connect(d->m_taskHub, SIGNAL(popupRequested(int)),
+ connect(hub, SIGNAL(popupRequested(int)),
this, SLOT(popup(int)));
- connect(d->m_taskHub, SIGNAL(showTask(uint)),
+ connect(hub, SIGNAL(showTask(uint)),
this, SLOT(showTask(uint)));
- connect(d->m_taskHub, SIGNAL(openTask(uint)),
+ connect(hub, SIGNAL(openTask(uint)),
this, SLOT(openTask(uint)));
}
@@ -595,7 +594,7 @@ void TaskWindow::clearContents()
{
// clear all tasks in all displays
// Yeah we are that special
- d->m_taskHub->clearTasks();
+ TaskHub::clearTasks();
}
bool TaskWindow::hasFocus() const
diff --git a/src/plugins/projectexplorer/taskwindow.h b/src/plugins/projectexplorer/taskwindow.h
index a9d8f45263..70ff0059d8 100644
--- a/src/plugins/projectexplorer/taskwindow.h
+++ b/src/plugins/projectexplorer/taskwindow.h
@@ -52,7 +52,7 @@ class TaskWindow : public Core::IOutputPane
Q_OBJECT
public:
- TaskWindow(ProjectExplorer::TaskHub *taskHub);
+ TaskWindow();
virtual ~TaskWindow();
void delayedInitialization();
diff --git a/src/plugins/projectexplorer/toolchain.cpp b/src/plugins/projectexplorer/toolchain.cpp
index f0b8669ab4..d6b3d2d919 100644
--- a/src/plugins/projectexplorer/toolchain.cpp
+++ b/src/plugins/projectexplorer/toolchain.cpp
@@ -53,8 +53,10 @@ namespace Internal {
class ToolChainPrivate
{
public:
- ToolChainPrivate(const QString &id, bool autodetect) :
- m_autodetect(autodetect)
+ typedef ToolChain::Detection Detection;
+
+ explicit ToolChainPrivate(const QString &id, Detection d) :
+ m_detection(d)
{
m_id = createId(id);
}
@@ -67,7 +69,7 @@ public:
}
QString m_id;
- bool m_autodetect;
+ Detection m_detection;
mutable QString m_displayName;
};
@@ -81,12 +83,12 @@ public:
// --------------------------------------------------------------------------
-ToolChain::ToolChain(const QString &id, bool autodetect) :
- d(new Internal::ToolChainPrivate(id, autodetect))
+ToolChain::ToolChain(const QString &id, Detection d) :
+ d(new Internal::ToolChainPrivate(id, d))
{ }
ToolChain::ToolChain(const ToolChain &other) :
- d(new Internal::ToolChainPrivate(other.d->m_id, false))
+ d(new Internal::ToolChainPrivate(other.d->m_id, ManualDetection))
{
// leave the autodetection bit at false.
d->m_displayName = QCoreApplication::translate("ProjectExplorer::ToolChain", "Clone of %1")
@@ -114,9 +116,9 @@ void ToolChain::setDisplayName(const QString &name)
toolChainUpdated();
}
-bool ToolChain::isAutoDetected() const
+ToolChain::Detection ToolChain::detection() const
{
- return d->m_autodetect;
+ return d->m_detection;
}
QString ToolChain::id() const
@@ -131,7 +133,7 @@ QList<Utils::FileName> ToolChain::suggestedMkspecList() const
Utils::FileName ToolChain::suggestedDebugger() const
{
- return ToolChainManager::instance()->defaultDebugger(targetAbi());
+ return ToolChainManager::defaultDebugger(targetAbi());
}
bool ToolChain::canClone() const
@@ -169,14 +171,14 @@ QVariantMap ToolChain::toMap() const
void ToolChain::toolChainUpdated()
{
- ToolChainManager::instance()->notifyAboutUpdate(this);
+ ToolChainManager::notifyAboutUpdate(this);
}
-void ToolChain::setAutoDetected(bool autodetect)
+void ToolChain::setDetection(ToolChain::Detection de)
{
- if (d->m_autodetect == autodetect)
+ if (d->m_detection == de)
return;
- d->m_autodetect = autodetect;
+ d->m_detection = de;
toolChainUpdated();
}
@@ -191,7 +193,8 @@ bool ToolChain::fromMap(const QVariantMap &data)
d->m_displayName = data.value(QLatin1String(DISPLAY_NAME_KEY)).toString();
// make sure we have new style ids:
d->m_id = data.value(QLatin1String(ID_KEY)).toString();
- d->m_autodetect = data.value(QLatin1String(AUTODETECT_KEY), false).toBool();
+ const bool autoDetect = data.value(QLatin1String(AUTODETECT_KEY), false).toBool();
+ d->m_detection = autoDetect ? AutoDetectionFromSettings : ManualDetection;
return true;
}
diff --git a/src/plugins/projectexplorer/toolchain.h b/src/plugins/projectexplorer/toolchain.h
index 04f114aedf..71b7b1e244 100644
--- a/src/plugins/projectexplorer/toolchain.h
+++ b/src/plugins/projectexplorer/toolchain.h
@@ -31,6 +31,7 @@
#define TOOLCHAIN_H
#include "projectexplorer_export.h"
+#include <coreplugin/id.h>
#include <QObject>
#include <QString>
@@ -63,12 +64,20 @@ class Kit;
class PROJECTEXPLORER_EXPORT ToolChain
{
public:
+ enum Detection {
+ ManualDetection,
+ AutoDetection,
+ AutoDetectionFromSettings
+ };
+
virtual ~ToolChain();
QString displayName() const;
void setDisplayName(const QString &name);
- bool isAutoDetected() const;
+ inline bool isAutoDetected() const { return detection() != ManualDetection; }
+ Detection detection() const;
+
QString id() const;
virtual QList<Utils::FileName> suggestedMkspecList() const;
@@ -145,7 +154,7 @@ public:
virtual QVariantMap toMap() const;
virtual QList<Task> validateKit(const Kit *k) const;
protected:
- ToolChain(const QString &id, bool autoDetect);
+ explicit ToolChain(const QString &id, Detection d);
explicit ToolChain(const ToolChain &);
void toolChainUpdated();
@@ -154,7 +163,7 @@ protected:
virtual bool fromMap(const QVariantMap &data);
private:
- void setAutoDetected(bool);
+ void setDetection(Detection d);
Internal::ToolChainPrivate *const d;
@@ -167,8 +176,8 @@ class PROJECTEXPLORER_EXPORT ToolChainFactory : public QObject
Q_OBJECT
public:
- virtual QString displayName() const = 0;
- virtual QString id() const = 0;
+ Core::Id id() const { return m_id; }
+ QString displayName() const { return m_displayName; }
virtual QList<ToolChain *> autoDetect();
@@ -181,6 +190,14 @@ public:
static QString idFromMap(const QVariantMap &data);
static void idToMap(QVariantMap &data, const QString id);
static void autoDetectionToMap(QVariantMap &data, bool detected);
+
+protected:
+ void setId(Core::Id id) { m_id = id; }
+ void setDisplayName(const QString &name) { m_displayName = name; }
+
+private:
+ QString m_displayName;
+ Core::Id m_id;
};
} // namespace ProjectExplorer
diff --git a/src/plugins/projectexplorer/toolchainmanager.cpp b/src/plugins/projectexplorer/toolchainmanager.cpp
index 91bef09955..8c0f2dc99c 100644
--- a/src/plugins/projectexplorer/toolchainmanager.cpp
+++ b/src/plugins/projectexplorer/toolchainmanager.cpp
@@ -53,19 +53,15 @@ static const char DEFAULT_DEBUGGER_PATH_KEY[] = "DefaultDebugger.Path.";
static const char TOOLCHAIN_FILENAME[] = "/qtcreator/toolchains.xml";
static const char LEGACY_TOOLCHAIN_FILENAME[] = "/toolChains.xml";
-using Utils::PersistentSettingsWriter;
-using Utils::PersistentSettingsReader;
+using namespace Utils;
-static Utils::FileName settingsFileName(const QString &path)
+static FileName settingsFileName(const QString &path)
{
QFileInfo settingsLocation(Core::ICore::settings()->fileName());
- return Utils::FileName::fromString(settingsLocation.absolutePath() + path);
+ return FileName::fromString(settingsLocation.absolutePath() + path);
}
namespace ProjectExplorer {
-
-ToolChainManager *ToolChainManager::m_instance = 0;
-
namespace Internal {
// --------------------------------------------------------------------------
@@ -75,20 +71,15 @@ namespace Internal {
class ToolChainManagerPrivate
{
public:
- ToolChainManagerPrivate(ToolChainManager *parent);
+ ToolChainManagerPrivate() : m_writer(0) {}
~ToolChainManagerPrivate();
- ToolChainManager *q;
- QMap<QString, Utils::FileName> m_abiToDebugger;
- Utils::PersistentSettingsWriter *m_writer;
+ QMap<QString, FileName> m_abiToDebugger;
+ PersistentSettingsWriter *m_writer;
QList<ToolChain *> m_toolChains;
};
-ToolChainManagerPrivate::ToolChainManagerPrivate(ToolChainManager *parent)
- : q(parent), m_writer(0)
-{ }
-
ToolChainManagerPrivate::~ToolChainManagerPrivate()
{
qDeleteAll(m_toolChains);
@@ -96,24 +87,25 @@ ToolChainManagerPrivate::~ToolChainManagerPrivate()
delete m_writer;
}
+static ToolChainManager *m_instance = 0;
+static ToolChainManagerPrivate *d;
+
} // namespace Internal
+using namespace Internal;
+
// --------------------------------------------------------------------------
// ToolChainManager
// --------------------------------------------------------------------------
-ToolChainManager *ToolChainManager::instance()
-{
- return m_instance;
-}
-
ToolChainManager::ToolChainManager(QObject *parent) :
- QObject(parent),
- d(new Internal::ToolChainManagerPrivate(this))
+ QObject(parent)
{
Q_ASSERT(!m_instance);
m_instance = this;
+ d = new ToolChainManagerPrivate;
+
connect(Core::ICore::instance(), SIGNAL(saveSettingsRequested()),
this, SLOT(saveToolChains()));
connect(this, SIGNAL(toolChainAdded(ProjectExplorer::ToolChain*)),
@@ -124,11 +116,78 @@ ToolChainManager::ToolChainManager(QObject *parent) :
this, SIGNAL(toolChainsChanged()));
}
+ToolChainManager::~ToolChainManager()
+{
+ delete d;
+ m_instance = 0;
+}
+
+QObject *ToolChainManager::instance()
+{
+ return m_instance;
+}
+
+static QList<ToolChain *> restoreFromFile(const FileName &fileName)
+{
+ QList<ToolChain *> result;
+
+ PersistentSettingsReader reader;
+ if (!reader.load(fileName))
+ return result;
+ QVariantMap data = reader.restoreValues();
+
+ // Check version:
+ int version = data.value(QLatin1String(TOOLCHAIN_FILE_VERSION_KEY), 0).toInt();
+ if (version < 1)
+ return result;
+
+ // Read default debugger settings (if any)
+ int count = data.value(QLatin1String(DEFAULT_DEBUGGER_COUNT_KEY)).toInt();
+ for (int i = 0; i < count; ++i) {
+ const QString abiKey = QString::fromLatin1(DEFAULT_DEBUGGER_ABI_KEY) + QString::number(i);
+ if (!data.contains(abiKey))
+ continue;
+ const QString pathKey = QString::fromLatin1(DEFAULT_DEBUGGER_PATH_KEY) + QString::number(i);
+ if (!data.contains(pathKey))
+ continue;
+ d->m_abiToDebugger.insert(data.value(abiKey).toString(),
+ FileName::fromString(data.value(pathKey).toString()));
+ }
+
+ QList<ToolChainFactory *> factories = ExtensionSystem::PluginManager::getObjects<ToolChainFactory>();
+
+ count = data.value(QLatin1String(TOOLCHAIN_COUNT_KEY), 0).toInt();
+ for (int i = 0; i < count; ++i) {
+ const QString key = QString::fromLatin1(TOOLCHAIN_DATA_KEY) + QString::number(i);
+ if (!data.contains(key))
+ break;
+
+ const QVariantMap tcMap = data.value(key).toMap();
+
+ bool restored = false;
+ foreach (ToolChainFactory *f, factories) {
+ if (f->canRestore(tcMap)) {
+ if (ToolChain *tc = f->restore(tcMap)) {
+ result.append(tc);
+ restored = true;
+ break;
+ }
+ }
+ }
+ if (!restored)
+ qWarning("Warning: Unable to restore compiler '%s' stored in %s.",
+ qPrintable(ToolChainFactory::idFromMap(tcMap)),
+ qPrintable(fileName.toUserOutput()));
+ }
+
+ return result;
+}
+
void ToolChainManager::restoreToolChains()
{
QTC_ASSERT(!d->m_writer, return);
d->m_writer =
- new Utils::PersistentSettingsWriter(settingsFileName(QLatin1String(TOOLCHAIN_FILENAME)), QLatin1String("QtCreatorToolChains"));
+ new PersistentSettingsWriter(settingsFileName(QLatin1String(TOOLCHAIN_FILENAME)), QLatin1String("QtCreatorToolChains"));
QList<ToolChain *> tcsToRegister;
QList<ToolChain *> tcsToCheck;
@@ -136,20 +195,20 @@ void ToolChainManager::restoreToolChains()
// read all tool chains from SDK
QFileInfo systemSettingsFile(Core::ICore::settings(QSettings::SystemScope)->fileName());
QList<ToolChain *> readTcs =
- restoreToolChains(Utils::FileName::fromString(systemSettingsFile.absolutePath() + QLatin1String(TOOLCHAIN_FILENAME)));
+ restoreFromFile(FileName::fromString(systemSettingsFile.absolutePath() + QLatin1String(TOOLCHAIN_FILENAME)));
// make sure we mark these as autodetected!
foreach (ToolChain *tc, readTcs)
- tc->setAutoDetected(true);
+ tc->setDetection(ToolChain::AutoDetection);
tcsToRegister = readTcs; // SDK TCs are always considered to be up-to-date, so no need to
// recheck them.
// read all tool chains from user file.
// Read legacy settings once and keep them around...
- Utils::FileName fileName = settingsFileName(QLatin1String(TOOLCHAIN_FILENAME));
+ FileName fileName = settingsFileName(QLatin1String(TOOLCHAIN_FILENAME));
if (!fileName.toFileInfo().exists())
fileName = settingsFileName(QLatin1String(LEGACY_TOOLCHAIN_FILENAME));
- readTcs = restoreToolChains(fileName);
+ readTcs = restoreFromFile(fileName);
foreach (ToolChain *tc, readTcs) {
if (tc->isAutoDetected())
@@ -180,10 +239,12 @@ void ToolChainManager::restoreToolChains()
foreach (ToolChain *currentDetected, detectedTcs) {
toStore = currentDetected;
- // Check whether we had this TC stored and prefer the old one with the old id:
+ // Check whether we had this TC stored and prefer the old one with the old id, marked
+ // as auto-detection.
for (int i = 0; i < tcsToCheck.count(); ++i) {
if (*(tcsToCheck.at(i)) == *currentDetected) {
toStore = tcsToCheck.at(i);
+ toStore->setDetection(ToolChain::AutoDetection);
tcsToCheck.removeAt(i);
delete currentDetected;
break;
@@ -207,13 +268,7 @@ void ToolChainManager::restoreToolChains()
foreach (ToolChain *tc, tcsToRegister)
registerToolChain(tc);
- emit toolChainsLoaded();
-}
-
-ToolChainManager::~ToolChainManager()
-{
- delete d;
- m_instance = 0;
+ emit m_instance->toolChainsLoaded();
}
void ToolChainManager::saveToolChains()
@@ -237,68 +292,12 @@ void ToolChainManager::saveToolChains()
// Do not save default debuggers! Those are set by the SDK!
}
-QList<ToolChain *> ToolChainManager::restoreToolChains(const Utils::FileName &fileName)
-{
- QList<ToolChain *> result;
-
- PersistentSettingsReader reader;
- if (!reader.load(fileName))
- return result;
- QVariantMap data = reader.restoreValues();
-
- // Check version:
- int version = data.value(QLatin1String(TOOLCHAIN_FILE_VERSION_KEY), 0).toInt();
- if (version < 1)
- return result;
-
- // Read default debugger settings (if any)
- int count = data.value(QLatin1String(DEFAULT_DEBUGGER_COUNT_KEY)).toInt();
- for (int i = 0; i < count; ++i) {
- const QString abiKey = QString::fromLatin1(DEFAULT_DEBUGGER_ABI_KEY) + QString::number(i);
- if (!data.contains(abiKey))
- continue;
- const QString pathKey = QString::fromLatin1(DEFAULT_DEBUGGER_PATH_KEY) + QString::number(i);
- if (!data.contains(pathKey))
- continue;
- d->m_abiToDebugger.insert(data.value(abiKey).toString(),
- Utils::FileName::fromString(data.value(pathKey).toString()));
- }
-
- QList<ToolChainFactory *> factories = ExtensionSystem::PluginManager::getObjects<ToolChainFactory>();
-
- count = data.value(QLatin1String(TOOLCHAIN_COUNT_KEY), 0).toInt();
- for (int i = 0; i < count; ++i) {
- const QString key = QString::fromLatin1(TOOLCHAIN_DATA_KEY) + QString::number(i);
- if (!data.contains(key))
- break;
-
- const QVariantMap tcMap = data.value(key).toMap();
-
- bool restored = false;
- foreach (ToolChainFactory *f, factories) {
- if (f->canRestore(tcMap)) {
- if (ToolChain *tc = f->restore(tcMap)) {
- result.append(tc);
- restored = true;
- break;
- }
- }
- }
- if (!restored)
- qWarning("Warning: Unable to restore compiler '%s' stored in %s.",
- qPrintable(ToolChainFactory::idFromMap(tcMap)),
- qPrintable(fileName.toUserOutput()));
- }
-
- return result;
-}
-
-QList<ToolChain *> ToolChainManager::toolChains() const
+QList<ToolChain *> ToolChainManager::toolChains()
{
return d->m_toolChains;
}
-QList<ToolChain *> ToolChainManager::findToolChains(const Abi &abi) const
+QList<ToolChain *> ToolChainManager::findToolChains(const Abi &abi)
{
QList<ToolChain *> result;
foreach (ToolChain *tc, d->m_toolChains) {
@@ -309,7 +308,7 @@ QList<ToolChain *> ToolChainManager::findToolChains(const Abi &abi) const
return result;
}
-ToolChain *ToolChainManager::findToolChain(const QString &id) const
+ToolChain *ToolChainManager::findToolChain(const QString &id)
{
if (id.isEmpty())
return 0;
@@ -321,21 +320,21 @@ ToolChain *ToolChainManager::findToolChain(const QString &id) const
return 0;
}
-Utils::FileName ToolChainManager::defaultDebugger(const Abi &abi) const
+FileName ToolChainManager::defaultDebugger(const Abi &abi)
{
return d->m_abiToDebugger.value(abi.toString());
}
-bool ToolChainManager::isLoaded() const
+bool ToolChainManager::isLoaded()
{
return d->m_writer;
}
-void ToolChainManager::notifyAboutUpdate(ProjectExplorer::ToolChain *tc)
+void ToolChainManager::notifyAboutUpdate(ToolChain *tc)
{
if (!tc || !d->m_toolChains.contains(tc))
return;
- emit toolChainUpdated(tc);
+ emit m_instance->toolChainUpdated(tc);
}
bool ToolChainManager::registerToolChain(ToolChain *tc)
@@ -351,7 +350,7 @@ bool ToolChainManager::registerToolChain(ToolChain *tc)
}
d->m_toolChains.append(tc);
- emit toolChainAdded(tc);
+ emit m_instance->toolChainAdded(tc);
return true;
}
@@ -360,7 +359,7 @@ void ToolChainManager::deregisterToolChain(ToolChain *tc)
if (!tc || !d->m_toolChains.contains(tc))
return;
d->m_toolChains.removeOne(tc);
- emit toolChainRemoved(tc);
+ emit m_instance->toolChainRemoved(tc);
delete tc;
}
diff --git a/src/plugins/projectexplorer/toolchainmanager.h b/src/plugins/projectexplorer/toolchainmanager.h
index 2202643aac..e9e1af70db 100644
--- a/src/plugins/projectexplorer/toolchainmanager.h
+++ b/src/plugins/projectexplorer/toolchainmanager.h
@@ -32,22 +32,18 @@
#include "projectexplorer_export.h"
-
#include <QList>
#include <QObject>
#include <QString>
namespace Utils { class FileName; }
+
namespace ProjectExplorer {
+
class ProjectExplorerPlugin;
class ToolChain;
-class ToolChainFactory;
class Abi;
-namespace Internal {
-class ToolChainManagerPrivate;
-}
-
// --------------------------------------------------------------------------
// ToolChainManager
// --------------------------------------------------------------------------
@@ -57,21 +53,21 @@ class PROJECTEXPLORER_EXPORT ToolChainManager : public QObject
Q_OBJECT
public:
- static ToolChainManager *instance();
+ static QObject *instance();
~ToolChainManager();
- QList<ToolChain *> toolChains() const;
- QList<ToolChain *> findToolChains(const Abi &abi) const;
- ToolChain *findToolChain(const QString &id) const;
+ static QList<ToolChain *> toolChains();
+ static QList<ToolChain *> findToolChains(const Abi &abi);
+ static ToolChain *findToolChain(const QString &id);
- Utils::FileName defaultDebugger(const Abi &abi) const;
+ static Utils::FileName defaultDebugger(const Abi &abi);
- bool isLoaded() const;
+ static bool isLoaded();
-public slots:
- bool registerToolChain(ProjectExplorer::ToolChain *tc);
- void deregisterToolChain(ProjectExplorer::ToolChain *tc);
+ static bool registerToolChain(ToolChain *tc);
+ static void deregisterToolChain(ToolChain *tc);
+public slots:
void saveToolChains();
signals:
@@ -80,9 +76,9 @@ signals:
void toolChainRemoved(ProjectExplorer::ToolChain *);
// Tool chain was updated.
void toolChainUpdated(ProjectExplorer::ToolChain *);
- // Something changed:
+ // Something changed.
void toolChainsChanged();
-
+ //
void toolChainsLoaded();
private:
@@ -90,16 +86,9 @@ private:
// Make sure the this is only called after all
// Tool chain Factories are registered!
- void restoreToolChains();
- QList<ToolChain *> restoreToolChains(const Utils::FileName &fileName);
-
- void notifyAboutUpdate(ProjectExplorer::ToolChain *);
-
- Internal::ToolChainManagerPrivate *const d;
-
- static ToolChainManager *m_instance;
+ static void restoreToolChains();
+ static void notifyAboutUpdate(ToolChain *);
- friend class Internal::ToolChainManagerPrivate; // for the restoreToolChains methods
friend class ProjectExplorerPlugin; // for constructor
friend class ToolChain;
};
diff --git a/src/plugins/projectexplorer/toolchainoptionspage.cpp b/src/plugins/projectexplorer/toolchainoptionspage.cpp
index 61219d7865..44b1a82191 100644
--- a/src/plugins/projectexplorer/toolchainoptionspage.cpp
+++ b/src/plugins/projectexplorer/toolchainoptionspage.cpp
@@ -106,9 +106,8 @@ ToolChainModel::ToolChainModel(QObject *parent) :
m_autoRoot = new ToolChainNode(m_root);
m_manualRoot = new ToolChainNode(m_root);
- foreach (ToolChain *tc, ToolChainManager::instance()->toolChains()) {
+ foreach (ToolChain *tc, ToolChainManager::toolChains())
addToolChain(tc);
- }
}
ToolChainModel::~ToolChainModel()
@@ -278,7 +277,7 @@ void ToolChainModel::apply()
QList<ToolChainNode *> nodes = m_toRemoveList;
foreach (ToolChainNode *n, nodes) {
Q_ASSERT(!n->parent);
- ToolChainManager::instance()->deregisterToolChain(n->toolChain);
+ ToolChainManager::deregisterToolChain(n->toolChain);
}
Q_ASSERT(m_toRemoveList.isEmpty());
@@ -299,7 +298,7 @@ void ToolChainModel::apply()
QStringList removedTcs;
nodes = m_toAddList;
foreach (ToolChainNode *n, nodes) {
- if (!ToolChainManager::instance()->registerToolChain(n->toolChain))
+ if (!ToolChainManager::registerToolChain(n->toolChain))
removedTcs << n->toolChain->displayName();
}
//
@@ -626,7 +625,7 @@ void ToolChainOptionsPage::updateState()
ToolChain *tc = m_model->toolChain(currentIndex());
if (tc) {
canCopy = tc->isValid() && tc->canClone();
- canDelete = !tc->isAutoDetected();
+ canDelete = tc->detection() != ToolChain::AutoDetection;
}
m_cloneButton->setEnabled(canCopy);
diff --git a/src/plugins/qt4projectmanager/unconfiguredprojectpanel.cpp b/src/plugins/projectexplorer/unconfiguredprojectpanel.cpp
index eedebc4bf4..0e38fa6f29 100644
--- a/src/plugins/qt4projectmanager/unconfiguredprojectpanel.cpp
+++ b/src/plugins/projectexplorer/unconfiguredprojectpanel.cpp
@@ -28,38 +28,36 @@
****************************************************************************/
#include "unconfiguredprojectpanel.h"
-#include "wizards/targetsetuppage.h"
-#include "qt4projectmanagerconstants.h"
-#include "qt4project.h"
+#include "kit.h"
+#include "kitmanager.h"
+#include "project.h"
+#include "projectexplorer.h"
+#include "projectexplorerconstants.h"
+#include "session.h"
+#include "targetsetuppage.h"
-#include <coreplugin/idocument.h>
#include <coreplugin/icore.h>
#include <coreplugin/modemanager.h>
#include <coreplugin/coreconstants.h>
-#include <qtsupport/qtkitinformation.h>
-
-#include <projectexplorer/projectexplorer.h>
-#include <projectexplorer/session.h>
#include <QVBoxLayout>
#include <QPushButton>
#include <QDialogButtonBox>
-using namespace Qt4ProjectManager;
-using namespace Qt4ProjectManager::Internal;
-
+namespace ProjectExplorer {
+namespace Internal {
UnconfiguredProjectPanel::UnconfiguredProjectPanel()
{
}
-QString Qt4ProjectManager::Internal::UnconfiguredProjectPanel::id() const
+QString UnconfiguredProjectPanel::id() const
{
return QLatin1String(Constants::UNCONFIGURED_PANEL_PAGE_ID);
}
-QString Qt4ProjectManager::Internal::UnconfiguredProjectPanel::displayName() const
+QString UnconfiguredProjectPanel::displayName() const
{
return tr("Configure Project");
}
@@ -69,16 +67,14 @@ int UnconfiguredProjectPanel::priority() const
return -10;
}
-bool Qt4ProjectManager::Internal::UnconfiguredProjectPanel::supports(ProjectExplorer::Project *project)
+bool UnconfiguredProjectPanel::supports(Project *project)
{
- if (qobject_cast<Qt4Project *>(project) && project->targets().isEmpty())
- return true;
- return false;
+ return project->targets().isEmpty() && project->supportsNoTargetPanel();
}
-ProjectExplorer::PropertiesPanel *Qt4ProjectManager::Internal::UnconfiguredProjectPanel::createPanel(ProjectExplorer::Project *project)
+PropertiesPanel *UnconfiguredProjectPanel::createPanel(Project *project)
{
- ProjectExplorer::PropertiesPanel *panel = new ProjectExplorer::PropertiesPanel;
+ PropertiesPanel *panel = new PropertiesPanel;
panel->setDisplayName(displayName());
panel->setIcon(QIcon(QLatin1String(":/projectexplorer/images/unconfigured.png")));
@@ -91,20 +87,22 @@ ProjectExplorer::PropertiesPanel *Qt4ProjectManager::Internal::UnconfiguredProje
/// TargetSetupPageWrapper
////////
-TargetSetupPageWrapper::TargetSetupPageWrapper(ProjectExplorer::Project *project)
- : QWidget(), m_project(qobject_cast<Qt4Project *>(project))
+TargetSetupPageWrapper::TargetSetupPageWrapper(Project *project) :
+ QWidget(), m_project(project)
{
QVBoxLayout *layout = new QVBoxLayout();
layout->setMargin(0);
setLayout(layout);
m_targetSetupPage = new TargetSetupPage(this);
- m_targetSetupPage->setRequiredKitMatcher(new QtSupport::QtVersionKitMatcher);
+ m_targetSetupPage->setProjectImporter(project->createProjectImporter());
m_targetSetupPage->setUseScrollArea(false);
m_targetSetupPage->setImportSearch(true);
- m_targetSetupPage->setProFilePath(project->document()->fileName());
+ m_targetSetupPage->setProjectPath(project->projectFilePath());
m_targetSetupPage->initializePage();
m_targetSetupPage->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
+ m_targetSetupPage->setRequiredKitMatcher(project->createRequiredKitMatcher());
+ m_targetSetupPage->setPreferredKitMatcher(project->createPreferredKitMatcher());
updateNoteText();
layout->addWidget(m_targetSetupPage);
@@ -137,21 +135,21 @@ TargetSetupPageWrapper::TargetSetupPageWrapper(ProjectExplorer::Project *project
this, SLOT(cancel()));
connect(m_targetSetupPage, SIGNAL(completeChanged()),
this, SLOT(completeChanged()));
- connect(ProjectExplorer::KitManager::instance(), SIGNAL(defaultkitChanged()),
+ connect(KitManager::instance(), SIGNAL(defaultkitChanged()),
this, SLOT(updateNoteText()));
- connect(ProjectExplorer::KitManager::instance(), SIGNAL(kitUpdated(ProjectExplorer::Kit*)),
+ connect(KitManager::instance(), SIGNAL(kitUpdated(ProjectExplorer::Kit*)),
this, SLOT(kitUpdated(ProjectExplorer::Kit*)));
}
-void TargetSetupPageWrapper::kitUpdated(ProjectExplorer::Kit *k)
+void TargetSetupPageWrapper::kitUpdated(Kit *k)
{
- if (k == ProjectExplorer::KitManager::instance()->defaultKit())
+ if (k == KitManager::defaultKit())
updateNoteText();
}
void TargetSetupPageWrapper::updateNoteText()
{
- ProjectExplorer::Kit *k = ProjectExplorer::KitManager::instance()->defaultKit();
+ Kit *k = KitManager::defaultKit();
QString text;
bool showHint = false;
@@ -195,19 +193,22 @@ void TargetSetupPageWrapper::keyReleaseEvent(QKeyEvent *event)
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);
+ ProjectExplorerPlugin::instance()->unloadProject(m_project);
+ if (!SessionManager::hasProjects())
+ Core::ModeManager::activateMode(Core::Constants::MODE_WELCOME);
}
void TargetSetupPageWrapper::done()
{
m_targetSetupPage->setupProject(m_project);
- ProjectExplorer::ProjectExplorerPlugin::instance()->requestProjectModeUpdate(m_project);
- Core::ICore::instance()->modeManager()->activateMode(Core::Constants::MODE_EDIT);
+ ProjectExplorerPlugin::instance()->requestProjectModeUpdate(m_project);
+ Core::ModeManager::activateMode(Core::Constants::MODE_EDIT);
}
void TargetSetupPageWrapper::completeChanged()
{
m_configureButton->setEnabled(m_targetSetupPage->isComplete());
}
+
+} // namespace Internal
+} // namespace ProjectExplorer
diff --git a/src/plugins/qt4projectmanager/unconfiguredprojectpanel.h b/src/plugins/projectexplorer/unconfiguredprojectpanel.h
index e71e7d2ef1..4e13fe4391 100644
--- a/src/plugins/qt4projectmanager/unconfiguredprojectpanel.h
+++ b/src/plugins/projectexplorer/unconfiguredprojectpanel.h
@@ -30,21 +30,19 @@
#ifndef UNCONFIGUREDPROJECTPANEL_H
#define UNCONFIGUREDPROJECTPANEL_H
-#include <projectexplorer/iprojectproperties.h>
+#include "iprojectproperties.h"
#include <QString>
QT_FORWARD_DECLARE_CLASS(QPushButton)
-namespace ProjectExplorer { class Kit; }
-
-namespace Qt4ProjectManager {
+namespace ProjectExplorer {
+class Kit;
class TargetSetupPage;
-class Qt4Project;
namespace Internal {
-class UnconfiguredProjectPanel : public ProjectExplorer::IProjectPanelFactory
+class UnconfiguredProjectPanel : public IProjectPanelFactory
{
Q_OBJECT
public:
@@ -52,15 +50,15 @@ public:
virtual QString id() const;
virtual QString displayName() const;
int priority() const;
- virtual bool supports(ProjectExplorer::Project *project);
- virtual ProjectExplorer::PropertiesPanel *createPanel(ProjectExplorer::Project *project);
+ virtual bool supports(Project *project);
+ virtual PropertiesPanel *createPanel(Project *project);
};
class TargetSetupPageWrapper : public QWidget
{
Q_OBJECT
public:
- TargetSetupPageWrapper(ProjectExplorer::Project *project);
+ TargetSetupPageWrapper(Project *project);
protected:
void keyReleaseEvent(QKeyEvent *event);
void keyPressEvent(QKeyEvent *event);
@@ -72,13 +70,13 @@ private slots:
void completeChanged();
private:
- Qt4Project *m_project;
+ Project *m_project;
TargetSetupPage *m_targetSetupPage;
QPushButton *m_configureButton;
QPushButton *m_cancelButton;
};
-}
-}
+} // namespace Internal
+} // namespace ProjectExplorer
#endif // UNCONFIGUREDPROJECTPANEL_H
diff --git a/src/plugins/projectexplorer/vcsannotatetaskhandler.cpp b/src/plugins/projectexplorer/vcsannotatetaskhandler.cpp
index 773b2567d1..d3419fd4ad 100644
--- a/src/plugins/projectexplorer/vcsannotatetaskhandler.cpp
+++ b/src/plugins/projectexplorer/vcsannotatetaskhandler.cpp
@@ -31,33 +31,35 @@
#include "task.h"
-#include <coreplugin/icore.h>
#include <coreplugin/iversioncontrol.h>
#include <coreplugin/vcsmanager.h>
+#include <utils/qtcassert.h>
+#include <QAction>
#include <QFileInfo>
-#include <QAction>
+using namespace Core;
-using namespace ProjectExplorer::Internal;
+namespace ProjectExplorer {
+namespace Internal {
-bool VcsAnnotateTaskHandler::canHandle(const ProjectExplorer::Task &task) const
+bool VcsAnnotateTaskHandler::canHandle(const Task &task) const
{
QFileInfo fi(task.file.toFileInfo());
if (!fi.exists() || !fi.isFile() || !fi.isReadable())
return false;
- Core::IVersionControl *vc = Core::ICore::vcsManager()->findVersionControlForDirectory(fi.absolutePath());
+ IVersionControl *vc = VcsManager::findVersionControlForDirectory(fi.absolutePath());
if (!vc)
return false;
- return vc->supportsOperation(Core::IVersionControl::AnnotateOperation);
+ return vc->supportsOperation(IVersionControl::AnnotateOperation);
}
-void VcsAnnotateTaskHandler::handle(const ProjectExplorer::Task &task)
+void VcsAnnotateTaskHandler::handle(const Task &task)
{
QFileInfo fi(task.file.toFileInfo());
- Core::IVersionControl *vc = Core::ICore::vcsManager()->findVersionControlForDirectory(fi.absolutePath());
- Q_ASSERT(vc);
- Q_ASSERT(vc->supportsOperation(Core::IVersionControl::AnnotateOperation));
+ IVersionControl *vc = VcsManager::findVersionControlForDirectory(fi.absolutePath());
+ QTC_ASSERT(vc, return);
+ QTC_ASSERT(vc->supportsOperation(IVersionControl::AnnotateOperation), return);
vc->vcsAnnotate(fi.absoluteFilePath(), task.movedLine);
}
@@ -67,3 +69,6 @@ QAction *VcsAnnotateTaskHandler::createAction(QObject *parent) const
vcsannotateAction->setToolTip(tr("Annotate using version control system"));
return vcsannotateAction;
}
+
+} // namespace Internal
+} // namespace ProjectExplorer
diff --git a/src/plugins/projectexplorer/wincetoolchain.cpp b/src/plugins/projectexplorer/wincetoolchain.cpp
index cb26749fed..cac9c1373e 100644
--- a/src/plugins/projectexplorer/wincetoolchain.cpp
+++ b/src/plugins/projectexplorer/wincetoolchain.cpp
@@ -67,7 +67,7 @@ static QString findMsvcVer(int version)
if (version == 10)
return QLatin1String("msvc2010");
if (version == 9)
- return QLatin1String("msvc2008");;
+ return QLatin1String("msvc2008");
return QLatin1String("msvc2005");
}
@@ -93,8 +93,7 @@ static QString winExpandDelayedEnvReferences(QString in, const Utils::Environmen
if (replacement.isEmpty()) {
qWarning() << "No replacement for var: " << var;
pos = nextPos;
- }
- else {
+ } else {
// Not sure about this, but we need to account for the case where
// the end of the replacement doesn't have the directory seperator and
// neither does the start of the insert. This solution assumes:
@@ -241,8 +240,8 @@ WinCEToolChain::WinCEToolChain(const QString &name,
const QString &binPath,
const QString &includePath,
const QString &libPath,
- bool autodetect) :
- AbstractMsvcToolChain(QLatin1String(Constants::WINCE_TOOLCHAIN_ID), autodetect, abi, vcvarsBat),
+ Detection d) :
+ AbstractMsvcToolChain(QLatin1String(Constants::WINCE_TOOLCHAIN_ID), d, abi, vcvarsBat),
m_msvcVer(msvcVer),
m_ceVer(ceVer),
m_binPath(binPath),
@@ -258,7 +257,7 @@ WinCEToolChain::WinCEToolChain(const QString &name,
}
WinCEToolChain::WinCEToolChain() :
- AbstractMsvcToolChain(QLatin1String(Constants::WINCE_TOOLCHAIN_ID), false)
+ AbstractMsvcToolChain(QLatin1String(Constants::WINCE_TOOLCHAIN_ID), ManualDetection)
{
}
@@ -352,14 +351,10 @@ ToolChain *WinCEToolChain::clone() const
// WinCEToolChainFactory
// --------------------------------------------------------------------------
-QString WinCEToolChainFactory::displayName() const
-{
- return tr("WinCE");
-}
-
-QString WinCEToolChainFactory::id() const
+WinCEToolChainFactory::WinCEToolChainFactory()
{
- return QLatin1String(Constants::WINCE_TOOLCHAIN_ID);
+ setId(Constants::WINCE_TOOLCHAIN_ID);
+ setDisplayName(tr("WinCE"));
}
@@ -415,7 +410,7 @@ QList<ToolChain *> WinCEToolChainFactory::autoDetect()
binPath,
includePath,
libPath,
- true);
+ ToolChain::AutoDetection);
results.append(pChain);
}
}
diff --git a/src/plugins/projectexplorer/wincetoolchain.h b/src/plugins/projectexplorer/wincetoolchain.h
index 152a98200d..fddf6fa684 100644
--- a/src/plugins/projectexplorer/wincetoolchain.h
+++ b/src/plugins/projectexplorer/wincetoolchain.h
@@ -48,7 +48,7 @@ public:
const QString &binPath,
const QString &includePath,
const QString &libPath,
- bool autodetect = false);
+ Detection d = ManualDetection);
QList<Utils::FileName> suggestedMkspecList() const;
@@ -104,8 +104,7 @@ class WinCEToolChainFactory : public ToolChainFactory
Q_OBJECT
public:
- QString displayName() const;
- QString id() const;
+ WinCEToolChainFactory();
QList<ToolChain *> autoDetect();
diff --git a/src/plugins/pythoneditor/PythonEditor.pluginspec.in b/src/plugins/pythoneditor/PythonEditor.pluginspec.in
index 0b1f5b065b..5dae98ebbf 100644
--- a/src/plugins/pythoneditor/PythonEditor.pluginspec.in
+++ b/src/plugins/pythoneditor/PythonEditor.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"PythonEditor\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"PythonEditor\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/pythoneditor/pythoneditor.cpp b/src/plugins/pythoneditor/pythoneditor.cpp
index 629e326e2f..6afb318e7b 100644
--- a/src/plugins/pythoneditor/pythoneditor.cpp
+++ b/src/plugins/pythoneditor/pythoneditor.cpp
@@ -45,6 +45,7 @@
#include <QFileInfo>
namespace PythonEditor {
+namespace Internal {
PythonEditor::PythonEditor(EditorWidget *editorWidget)
:BaseTextEditor(editorWidget)
@@ -78,16 +79,10 @@ bool PythonEditor::open(QString *errorString,
const QString &fileName,
const QString &realFileName)
{
- Core::MimeType mimeType;
- Core::MimeDatabase *mimeDB = Core::ICore::instance()->mimeDatabase();
-
- mimeType = mimeDB->findByFile(QFileInfo(fileName));
+ Core::MimeType mimeType = Core::MimeDatabase::findByFile(QFileInfo(fileName));
editorWidget()->setMimeType(mimeType.type());
-
- bool status = TextEditor::BaseTextEditor::open(errorString,
- fileName,
- realFileName);
- return status;
+ return TextEditor::BaseTextEditor::open(errorString, fileName, realFileName);
}
+} // namespace Internal
} // namespace PythonEditor
diff --git a/src/plugins/pythoneditor/pythoneditor.h b/src/plugins/pythoneditor/pythoneditor.h
index 435fb08560..f56802ea8a 100644
--- a/src/plugins/pythoneditor/pythoneditor.h
+++ b/src/plugins/pythoneditor/pythoneditor.h
@@ -30,14 +30,14 @@
#ifndef PYTHONEDITOR_EDITOR_H
#define PYTHONEDITOR_EDITOR_H
-#include "pythoneditor_global.h"
#include <texteditor/basetexteditor.h>
namespace PythonEditor {
+namespace Internal {
class EditorWidget;
-class PYEDITOR_EXPORT PythonEditor : public TextEditor::BaseTextEditor
+class PythonEditor : public TextEditor::BaseTextEditor
{
Q_OBJECT
@@ -49,7 +49,6 @@ public:
Core::IEditor *duplicate(QWidget *parent);
Core::Id id() const;
- bool isTemporary() const { return false; }
/**
Opens file for editing, actual work performed by base class
@@ -59,6 +58,7 @@ public:
const QString &realFileName);
};
+} // namespace Internal
} // namespace PythonEditor
#endif // PYTHONEDITOR_EDITOR_H
diff --git a/src/plugins/pythoneditor/pythoneditor.pro b/src/plugins/pythoneditor/pythoneditor.pro
index a4e0c55675..9d87e03a12 100644
--- a/src/plugins/pythoneditor/pythoneditor.pro
+++ b/src/plugins/pythoneditor/pythoneditor.pro
@@ -7,7 +7,6 @@ RESOURCES += \
pythoneditorplugin.qrc
HEADERS += \
- pythoneditor_global.h \
pythoneditorplugin.h \
pythoneditorfactory.h \
pythoneditor.h \
@@ -19,6 +18,7 @@ HEADERS += \
wizard/pythonclasswizarddialog.h \
wizard/pythonsourcegenerator.h \
tools/pythonhighlighter.h \
+ tools/pythonhighlighterfactory.h \
tools/pythonindenter.h \
tools/lexical/pythonformattoken.h \
tools/lexical/pythonscanner.h \
@@ -35,5 +35,6 @@ SOURCES += \
wizard/pythonclassnamepage.cpp \
wizard/pythonsourcegenerator.cpp \
tools/pythonhighlighter.cpp \
+ tools/pythonhighlighterfactory.cpp \
tools/pythonindenter.cpp \
tools/lexical/pythonscanner.cpp
diff --git a/src/plugins/pythoneditor/pythoneditor.qbs b/src/plugins/pythoneditor/pythoneditor.qbs
index 40b3ee891d..3b0a4899a6 100644
--- a/src/plugins/pythoneditor/pythoneditor.qbs
+++ b/src/plugins/pythoneditor/pythoneditor.qbs
@@ -12,36 +12,41 @@ QtcPlugin {
Depends { name: "QtSupport" }
Depends { name: "ProjectExplorer" }
- files: [
- "pythoneditor.cpp",
- "pythoneditor.h",
- "pythoneditor_global.h",
- "pythoneditorconstants.h",
- "pythoneditorfactory.cpp",
- "pythoneditorfactory.h",
- "pythoneditorplugin.cpp",
- "pythoneditorplugin.h",
- "pythoneditorplugin.qrc",
- "pythoneditorwidget.cpp",
- "pythoneditorwidget.h",
- "tools/lexical/sourcecodestream.h",
- "tools/lexical/pythonscanner.h",
- "tools/lexical/pythonformattoken.h",
- "tools/lexical/pythonscanner.cpp",
- "tools/pythonhighlighter.h",
- "tools/pythonindenter.cpp",
- "tools/pythonhighlighter.cpp",
- "tools/pythonindenter.h",
- "wizard/pythonfilewizard.h",
- "wizard/pythonfilewizard.cpp",
- "wizard/pythonclasswizard.h",
- "wizard/pythonclassnamepage.h",
- "wizard/pythonclasswizarddialog.h",
- "wizard/pythonsourcegenerator.h",
- "wizard/pythonclasswizarddialog.cpp",
- "wizard/pythonclasswizard.cpp",
- "wizard/pythonclassnamepage.cpp",
- "wizard/pythonsourcegenerator.cpp"
- ]
+ Group {
+ name: "General"
+ files: [
+ "pythoneditor.cpp", "pythoneditor.h",
+ "pythoneditorconstants.h",
+ "pythoneditorfactory.cpp", "pythoneditorfactory.h",
+ "pythoneditorplugin.cpp", "pythoneditorplugin.h",
+ "pythoneditorplugin.qrc",
+ "pythoneditorwidget.cpp", "pythoneditorwidget.h",
+ ]
+ }
+
+ Group {
+ name: "Tools"
+ prefix: "tools/"
+ files: [
+ "lexical/pythonformattoken.h",
+ "lexical/pythonscanner.h", "lexical/pythonscanner.cpp",
+ "lexical/sourcecodestream.h",
+ "pythonhighlighter.h", "pythonhighlighter.cpp",
+ "pythonhighlighterfactory.h", "pythonhighlighterfactory.cpp",
+ "pythonindenter.cpp", "pythonindenter.h"
+ ]
+ }
+
+ Group {
+ name: "Wizard"
+ prefix: "wizard/"
+ files: [
+ "pythonclassnamepage.cpp", "pythonclassnamepage.h",
+ "pythonclasswizard.h", "pythonclasswizard.cpp",
+ "pythonclasswizarddialog.h", "pythonclasswizarddialog.cpp",
+ "pythonfilewizard.h", "pythonfilewizard.cpp",
+ "pythonsourcegenerator.h", "pythonsourcegenerator.cpp"
+ ]
+ }
}
diff --git a/src/plugins/pythoneditor/pythoneditorfactory.cpp b/src/plugins/pythoneditor/pythoneditorfactory.cpp
index 5dc783f6ae..2851d611af 100644
--- a/src/plugins/pythoneditor/pythoneditorfactory.cpp
+++ b/src/plugins/pythoneditor/pythoneditorfactory.cpp
@@ -39,21 +39,14 @@
#include <QDebug>
namespace PythonEditor {
+namespace Internal {
EditorFactory::EditorFactory(QObject *parent)
: Core::IEditorFactory(parent)
{
- m_mimeTypes << QLatin1String(Constants::C_PY_MIMETYPE);
-}
-
-Core::Id EditorFactory::id() const
-{
- return Constants::C_PYTHONEDITOR_ID;
-}
-
-QString EditorFactory::displayName() const
-{
- return tr(Constants::C_EDITOR_DISPLAY_NAME);
+ setId(Constants::C_PYTHONEDITOR_ID);
+ setDisplayName(tr(Constants::C_EDITOR_DISPLAY_NAME));
+ addMimeType(QLatin1String(Constants::C_PY_MIMETYPE));
}
Core::IEditor *EditorFactory::createEditor(QWidget *parent)
@@ -64,9 +57,5 @@ Core::IEditor *EditorFactory::createEditor(QWidget *parent)
return widget->editor();
}
-QStringList EditorFactory::mimeTypes() const
-{
- return m_mimeTypes;
-}
-
+} // namespace Internal
} // namespace PythonEditor
diff --git a/src/plugins/pythoneditor/pythoneditorfactory.h b/src/plugins/pythoneditor/pythoneditorfactory.h
index 5879e6fe39..79e4d54e4e 100644
--- a/src/plugins/pythoneditor/pythoneditorfactory.h
+++ b/src/plugins/pythoneditor/pythoneditorfactory.h
@@ -30,13 +30,12 @@
#ifndef PYTHONEDITORFACTORY_H
#define PYTHONEDITORFACTORY_H
-#include "pythoneditor_global.h"
#include <coreplugin/editormanager/ieditorfactory.h>
-#include <QStringList>
namespace PythonEditor {
+namespace Internal {
-class PYEDITOR_EXPORT EditorFactory : public Core::IEditorFactory
+class EditorFactory : public Core::IEditorFactory
{
Q_OBJECT
@@ -44,25 +43,12 @@ public:
EditorFactory(QObject *parent);
/**
- Returns MIME types handled by editor
- */
- QStringList mimeTypes() const;
-
- /**
- Unique editor class identifier, see Constants::C_PYEDITOR_ID
- */
- Core::Id id() const;
- QString displayName() const;
-
- /**
Creates and initializes new editor widget
*/
Core::IEditor *createEditor(QWidget *parent);
-
-private:
- QStringList m_mimeTypes;
};
+} // namespace Internal
} // namespace PythonEditor
#endif // PYTHONEDITORFACTORY_H
diff --git a/src/plugins/pythoneditor/pythoneditorplugin.cpp b/src/plugins/pythoneditor/pythoneditorplugin.cpp
index d027bf986d..856c0677a7 100644
--- a/src/plugins/pythoneditor/pythoneditorplugin.cpp
+++ b/src/plugins/pythoneditor/pythoneditorplugin.cpp
@@ -33,6 +33,7 @@
#include "wizard/pythonclasswizard.h"
#include "pythoneditorwidget.h"
#include "pythoneditorfactory.h"
+#include "tools/pythonhighlighterfactory.h"
#include <coreplugin/icore.h>
#include <coreplugin/coreconstants.h>
@@ -183,6 +184,7 @@ static const char *const LIST_OF_PYTHON_BUILTINS[] = {
};
namespace PythonEditor {
+namespace Internal {
PythonEditorPlugin *PythonEditorPlugin::m_instance = 0;
@@ -210,24 +212,17 @@ PythonEditorPlugin::~PythonEditorPlugin()
m_instance = 0;
}
-bool PythonEditorPlugin::initialize(
- const QStringList &arguments, QString *errorMessage)
+bool PythonEditorPlugin::initialize(const QStringList &arguments, QString *errorMessage)
{
Q_UNUSED(arguments)
- if (! Core::ICore::mimeDatabase()->addMimeTypes(
- QLatin1String(RC_PY_MIME_XML),
- errorMessage))
- {
+ if (!Core::MimeDatabase::addMimeTypes(QLatin1String(RC_PY_MIME_XML), errorMessage))
return false;
- }
m_factory = new EditorFactory(this);
addObject(m_factory);
- ////////////////////////////////////////////////////////////////////////////
// Initialize editor actions handler
- ////////////////////////////////////////////////////////////////////////////
m_actionHandler.reset(new TextEditor::TextEditorActionHandler(
C_PYTHONEDITOR_ID,
TextEditor::TextEditorActionHandler::Format
@@ -235,22 +230,15 @@ bool PythonEditorPlugin::initialize(
| TextEditor::TextEditorActionHandler::UnCollapseAll));
m_actionHandler->initializeActions();
- ////////////////////////////////////////////////////////////////////////////
// Add MIME overlay icons (these icons displayed at Project dock panel)
- ////////////////////////////////////////////////////////////////////////////
const QIcon icon = QIcon::fromTheme(QLatin1String(C_PY_MIME_ICON));
- if (!icon.isNull()) {
- Core::FileIconProvider *iconProv = Core::FileIconProvider::instance();
- Core::MimeDatabase *mimeDB = Core::ICore::instance()->mimeDatabase();
- iconProv->registerIconOverlayForMimeType(
- icon, mimeDB->findByType(QLatin1String(C_PY_MIMETYPE)));
- }
+ if (!icon.isNull())
+ Core::FileIconProvider::registerIconOverlayForMimeType(icon, C_PY_MIMETYPE);
- ////////////////////////////////////////////////////////////////////////////
// Add Python files and classes creation dialogs
- ////////////////////////////////////////////////////////////////////////////
- addAutoReleasedObject(new FileWizard(Core::ICore::instance()));
- addAutoReleasedObject(new ClassWizard(Core::ICore::instance()));
+ addAutoReleasedObject(new FileWizard);
+ addAutoReleasedObject(new ClassWizard);
+ addAutoReleasedObject(new Internal::PythonHighlighterFactory);
return true;
}
@@ -262,7 +250,7 @@ void PythonEditorPlugin::extensionsInitialized()
void PythonEditorPlugin::initializeEditor(EditorWidget *widget)
{
instance()->m_actionHandler->setupActions(widget);
- TextEditor::TextEditorSettings::instance()->initializeEditor(widget);
+ TextEditor::TextEditorSettings::initializeEditor(widget);
}
QSet<QString> PythonEditorPlugin::keywords()
@@ -280,7 +268,7 @@ QSet<QString> PythonEditorPlugin::builtins()
return instance()->m_builtins;
}
+} // namespace Internal
} // namespace PythonEditor
-Q_EXPORT_PLUGIN(PythonEditor::PythonEditorPlugin)
-
+Q_EXPORT_PLUGIN(PythonEditor::Internal::PythonEditorPlugin)
diff --git a/src/plugins/pythoneditor/pythoneditorplugin.h b/src/plugins/pythoneditor/pythoneditorplugin.h
index 093536dddb..f6c730cb69 100644
--- a/src/plugins/pythoneditor/pythoneditorplugin.h
+++ b/src/plugins/pythoneditor/pythoneditorplugin.h
@@ -36,6 +36,7 @@
#include <QScopedPointer>
namespace PythonEditor {
+namespace Internal {
class EditorFactory;
class EditorWidget;
@@ -71,6 +72,7 @@ private:
QSet<QString> m_builtins;
};
+} // namespace Internal
} // namespace PythonEditor
#endif // PYTHONEDITOR_PLUGIN_H
diff --git a/src/plugins/pythoneditor/pythoneditorwidget.cpp b/src/plugins/pythoneditor/pythoneditorwidget.cpp
index 15010ffa52..a8588e3e07 100644
--- a/src/plugins/pythoneditor/pythoneditorwidget.cpp
+++ b/src/plugins/pythoneditor/pythoneditorwidget.cpp
@@ -45,6 +45,7 @@
#include <texteditor/autocompleter.h>
namespace PythonEditor {
+namespace Internal {
EditorWidget::EditorWidget(QWidget *parent)
:TextEditor::BaseTextEditorWidget(parent)
@@ -92,4 +93,5 @@ TextEditor::BaseTextEditor *EditorWidget::createEditor()
return new PythonEditor(this);
}
+} // namespace Internal
} // namespace PythonEditor
diff --git a/src/plugins/pythoneditor/pythoneditorwidget.h b/src/plugins/pythoneditor/pythoneditorwidget.h
index 63f646b79f..24258dfa5c 100644
--- a/src/plugins/pythoneditor/pythoneditorwidget.h
+++ b/src/plugins/pythoneditor/pythoneditorwidget.h
@@ -30,14 +30,13 @@
#ifndef PYTHONEDITORWIDGET_H
#define PYTHONEDITORWIDGET_H
-#include "pythoneditor_global.h"
-
#include <texteditor/basetexteditor.h>
#include <utils/uncommentselection.h>
namespace PythonEditor {
+namespace Internal {
-class PYEDITOR_EXPORT EditorWidget : public TextEditor::BaseTextEditorWidget
+class EditorWidget : public TextEditor::BaseTextEditorWidget
{
Q_OBJECT
@@ -57,6 +56,7 @@ private:
Utils::CommentDefinition m_commentDefinition;
};
+} // namespace Internal
} // namespace PythonEditor
#endif // PYTHONEDITORWIDGET_H
diff --git a/src/plugins/pythoneditor/tools/lexical/pythonscanner.cpp b/src/plugins/pythoneditor/tools/lexical/pythonscanner.cpp
index 1aa2c68529..6506a8d67d 100644
--- a/src/plugins/pythoneditor/tools/lexical/pythonscanner.cpp
+++ b/src/plugins/pythoneditor/tools/lexical/pythonscanner.cpp
@@ -225,11 +225,6 @@ inline static bool isValidIntegerSuffix(QChar ch)
return (ch == QLatin1Char('l') || ch == QLatin1Char('L'));
}
-inline static bool isValidComplexSuffix(QChar ch)
-{
- return (ch == QLatin1Char('j') || ch == QLatin1Char('J'));
-}
-
FormatToken Scanner::readNumber()
{
if (!m_src.isEnd()) {
diff --git a/src/plugins/pythoneditor/tools/pythonhighlighter.cpp b/src/plugins/pythoneditor/tools/pythonhighlighter.cpp
index 6e59d4a013..32c59ef6b0 100644
--- a/src/plugins/pythoneditor/tools/pythonhighlighter.cpp
+++ b/src/plugins/pythoneditor/tools/pythonhighlighter.cpp
@@ -40,9 +40,7 @@
#include "pythonhighlighter.h"
#include "lexical/pythonscanner.h"
-#include <texteditor/basetextdocumentlayout.h>
#include <texteditor/basetextdocument.h>
-#include <texteditor/fontsettings.h>
#include <texteditor/texteditorconstants.h>
namespace PythonEditor {
@@ -67,47 +65,42 @@ using namespace PythonEditor::Internal;
* @endcode
*/
-/// @return List that maps enum Format values to TextEditor plugin formats
-QVector<TextEditor::TextStyle> initFormatCategories()
+PythonHighlighter::PythonHighlighter(QTextDocument *parent) :
+ TextEditor::SyntaxHighlighter(parent)
{
- QVector<TextEditor::TextStyle> categories(Format_FormatsAmount);
- categories[Format_Number] = TextEditor::C_NUMBER;
- categories[Format_String] = TextEditor::C_STRING;
- categories[Format_Keyword] = TextEditor::C_KEYWORD;
- categories[Format_Type] = TextEditor::C_TYPE;
- categories[Format_ClassField] = TextEditor::C_FIELD;
- categories[Format_MagicAttr] = TextEditor::C_JS_SCOPE_VAR;
- categories[Format_Operator] = TextEditor::C_OPERATOR;
- categories[Format_Comment] = TextEditor::C_COMMENT;
- categories[Format_Doxygen] = TextEditor::C_DOXYGEN_COMMENT;
- categories[Format_Whitespace] = TextEditor::C_VISUAL_WHITESPACE;
- categories[Format_Identifier] = TextEditor::C_TEXT;
- categories[Format_ImportedModule] = TextEditor::C_STRING;
-
- return categories;
+ init();
}
/// New instance created when opening any document in editor
PythonHighlighter::PythonHighlighter(TextEditor::BaseTextDocument *parent) :
TextEditor::SyntaxHighlighter(parent)
{
+ init();
}
-/// Instance destroyed when one of documents closed from editor
-PythonHighlighter::~PythonHighlighter()
+void PythonHighlighter::init()
{
+ static QVector<TextEditor::TextStyle> categories;
+ if (categories.isEmpty()) {
+ categories << TextEditor::C_NUMBER
+ << TextEditor::C_STRING
+ << TextEditor::C_KEYWORD
+ << TextEditor::C_TYPE
+ << TextEditor::C_FIELD
+ << TextEditor::C_JS_SCOPE_VAR
+ << TextEditor::C_OPERATOR
+ << TextEditor::C_COMMENT
+ << TextEditor::C_DOXYGEN_COMMENT
+ << TextEditor::C_TEXT
+ << TextEditor::C_VISUAL_WHITESPACE
+ << TextEditor::C_STRING;
+ }
+ setTextFormatCategories(categories);
}
-/**
- QtCreator has own fonts&color settings. Highlighter wants get access to
- this settings before highlightBlock() called first time.
- Settings provided by PyEditor::EditorWidget class.
- */
-void PythonHighlighter::setFontSettings(const TextEditor::FontSettings &fs)
+/// Instance destroyed when one of documents closed from editor
+PythonHighlighter::~PythonHighlighter()
{
- QVector<TextEditor::TextStyle> categories = initFormatCategories();
- m_formats = fs.toTextCharFormats(categories);
- rehighlight();
}
/**
@@ -155,13 +148,13 @@ int PythonHighlighter::highlightLine(const QString &text, int initialState)
if (format == Format_Keyword) {
QString value = scanner.value(tk);
if (isImportKeyword(value) && hasOnlyWhitespace) {
- setFormat(tk.begin(), tk.length(), m_formats[format]);
+ setFormat(tk.begin(), tk.length(), formatForCategory(format));
highlightImport(scanner);
break;
}
}
- setFormat(tk.begin(), tk.length(), m_formats[format]);
+ setFormat(tk.begin(), tk.length(), formatForCategory(format));
if (format != Format_Whitespace)
hasOnlyWhitespace = false;
}
@@ -178,7 +171,7 @@ void PythonHighlighter::highlightImport(Scanner &scanner)
Format format = tk.format();
if (tk.format() == Format_Identifier)
format = Format_ImportedModule;
- setFormat(tk.begin(), tk.length(), m_formats[format]);
+ setFormat(tk.begin(), tk.length(), formatForCategory(format));
}
}
diff --git a/src/plugins/pythoneditor/tools/pythonhighlighter.h b/src/plugins/pythoneditor/tools/pythonhighlighter.h
index cb2a72e243..d5287fc0b5 100644
--- a/src/plugins/pythoneditor/tools/pythonhighlighter.h
+++ b/src/plugins/pythoneditor/tools/pythonhighlighter.h
@@ -30,31 +30,27 @@
#ifndef PYTHONHIGHLIGHTER_H
#define PYTHONHIGHLIGHTER_H
-#include "../pythoneditor_global.h"
#include <texteditor/syntaxhighlighter.h>
-#include <texteditor/fontsettings.h>
-#include <QMap>
namespace PythonEditor {
namespace Internal { class Scanner; }
-class PYEDITOR_EXPORT PythonHighlighter : public TextEditor::SyntaxHighlighter
+class PythonHighlighter : public TextEditor::SyntaxHighlighter
{
Q_OBJECT
public:
+ explicit PythonHighlighter(QTextDocument *parent = 0);
explicit PythonHighlighter(TextEditor::BaseTextDocument *parent);
virtual ~PythonHighlighter();
- void setFontSettings(const TextEditor::FontSettings &fs);
-
protected:
virtual void highlightBlock(const QString &text);
private:
int highlightLine(const QString &text, int initialState);
void highlightImport(Internal::Scanner &scanner);
- QVector<QTextCharFormat> m_formats;
+ void init();
};
} // namespace PythonEditor
diff --git a/src/plugins/pythoneditor/tools/pythonhighlighterfactory.cpp b/src/plugins/pythoneditor/tools/pythonhighlighterfactory.cpp
new file mode 100644
index 0000000000..43b912606c
--- /dev/null
+++ b/src/plugins/pythoneditor/tools/pythonhighlighterfactory.cpp
@@ -0,0 +1,45 @@
+/****************************************************************************
+**
+** 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 "pythonhighlighterfactory.h"
+#include "../pythoneditorconstants.h"
+#include "pythonhighlighter.h"
+
+using namespace PythonEditor::Internal;
+
+PythonHighlighterFactory::PythonHighlighterFactory()
+{
+ setId(Constants::C_PYTHONEDITOR_ID);
+ addMimeType(QLatin1String(Constants::C_PY_MIMETYPE));
+}
+
+TextEditor::SyntaxHighlighter *PythonHighlighterFactory::createHighlighter() const
+{
+ return new PythonHighlighter;
+}
diff --git a/src/plugins/pythoneditor/tools/pythonhighlighterfactory.h b/src/plugins/pythoneditor/tools/pythonhighlighterfactory.h
new file mode 100644
index 0000000000..fa7dc02825
--- /dev/null
+++ b/src/plugins/pythoneditor/tools/pythonhighlighterfactory.h
@@ -0,0 +1,51 @@
+/****************************************************************************
+**
+** 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 PYTHONHIGHLIGHTERFACTORY_H
+#define PYTHONHIGHLIGHTERFACTORY_H
+
+#include <texteditor/ihighlighterfactory.h>
+
+namespace PythonEditor {
+namespace Internal {
+
+class PythonHighlighterFactory : public TextEditor::IHighlighterFactory
+{
+ Q_OBJECT
+
+public:
+ PythonHighlighterFactory();
+
+ virtual TextEditor::SyntaxHighlighter *createHighlighter() const;
+};
+
+} // namespace Internal
+} // namespace PythonEditor
+
+#endif // PYTHONHIGHLIGHTERFACTORY_H
diff --git a/src/plugins/pythoneditor/tools/pythonindenter.h b/src/plugins/pythoneditor/tools/pythonindenter.h
index 3e0fc04319..10bf4d809b 100644
--- a/src/plugins/pythoneditor/tools/pythonindenter.h
+++ b/src/plugins/pythoneditor/tools/pythonindenter.h
@@ -30,13 +30,12 @@
#ifndef PYTHONINDENTER_H
#define PYTHONINDENTER_H
-#include "../pythoneditor_global.h"
#include <texteditor/indenter.h>
#include <QStringList>
namespace PythonEditor {
-class PYEDITOR_EXPORT PythonIndenter : public TextEditor::Indenter
+class PythonIndenter : public TextEditor::Indenter
{
public:
PythonIndenter();
diff --git a/src/plugins/pythoneditor/wizard/pythonclassnamepage.cpp b/src/plugins/pythoneditor/wizard/pythonclassnamepage.cpp
index 96548386e3..33024396a0 100644
--- a/src/plugins/pythoneditor/wizard/pythonclassnamepage.cpp
+++ b/src/plugins/pythoneditor/wizard/pythonclassnamepage.cpp
@@ -37,6 +37,7 @@
#include <QVBoxLayout>
namespace PythonEditor {
+namespace Internal {
ClassNamePage::ClassNamePage(QWidget *parent)
: QWizardPage(parent)
@@ -91,4 +92,5 @@ void ClassNamePage::slotValidChanged()
}
}
+} // namespace Internal
} // namespace PythonEditor
diff --git a/src/plugins/pythoneditor/wizard/pythonclassnamepage.h b/src/plugins/pythoneditor/wizard/pythonclassnamepage.h
index ca8c98a35a..55d542f11b 100644
--- a/src/plugins/pythoneditor/wizard/pythonclassnamepage.h
+++ b/src/plugins/pythoneditor/wizard/pythonclassnamepage.h
@@ -36,6 +36,7 @@
namespace Utils { class NewClassWidget; }
namespace PythonEditor {
+namespace Internal {
class ClassNamePage : public QWizardPage
{
@@ -58,6 +59,7 @@ private:
bool m_isValid;
};
+} // namespace Internal
} // namespace PythonEditor
#endif // PYTHONEDITOR_CLASSNAMEPAGE_H
diff --git a/src/plugins/pythoneditor/wizard/pythonclasswizard.cpp b/src/plugins/pythoneditor/wizard/pythonclasswizard.cpp
index f172d1ce1d..c3c3cb29b5 100644
--- a/src/plugins/pythoneditor/wizard/pythonclasswizard.cpp
+++ b/src/plugins/pythoneditor/wizard/pythonclasswizard.cpp
@@ -43,23 +43,16 @@
using namespace ProjectExplorer;
namespace PythonEditor {
+namespace Internal {
-static Core::BaseFileWizardParameters getDefaultParams()
-{
- Core::BaseFileWizardParameters p(Core::IWizard::FileWizard);
-
- p.setId(QLatin1String(Constants::C_PY_CLASS_WIZARD_ID));
- p.setCategory(QLatin1String(Constants::C_PY_WIZARD_CATEGORY));
- p.setDisplayCategory(QLatin1String(Constants::C_PY_DISPLAY_CATEGORY));
- p.setDisplayName(ClassWizard::tr(Constants::EN_PY_CLASS_DISPLAY_NAME));
- p.setDescription(ClassWizard::tr(Constants::EN_PY_CLASS_DESCRIPTION));
-
- return p;
-}
-
-ClassWizard::ClassWizard(QObject *parent) :
- Core::BaseFileWizard(getDefaultParams(), parent)
+ClassWizard::ClassWizard()
{
+ setWizardKind(Core::IWizard::FileWizard);
+ setId(QLatin1String(Constants::C_PY_CLASS_WIZARD_ID));
+ setCategory(QLatin1String(Constants::C_PY_WIZARD_CATEGORY));
+ setDisplayCategory(QLatin1String(Constants::C_PY_DISPLAY_CATEGORY));
+ setDisplayName(ClassWizard::tr(Constants::EN_PY_CLASS_DISPLAY_NAME));
+ setDescription(ClassWizard::tr(Constants::EN_PY_CLASS_DESCRIPTION));
}
QWizard *ClassWizard::createWizardDialog(
@@ -112,12 +105,13 @@ Kit *ClassWizard::kitForWizard(const ClassWizardDialog *wizard) const
const QString nodePath = wizard->extraValues().value(key).toString();
// projectForFile doesn't find project if project file path passed
- Node *node = ProjectExplorerPlugin::instance()->session()->nodeForFile(nodePath);
- Project *proj = ProjectExplorerPlugin::instance()->session()->projectForNode(node);
+ Node *node = SessionManager::nodeForFile(nodePath);
+ Project *proj = SessionManager::projectForNode(node);
if (proj && proj->activeTarget())
return proj->activeTarget()->kit();
- return KitManager::instance()->defaultKit();
+ return KitManager::defaultKit();
}
+} // namespace Internal
} // namespace PythonEditor
diff --git a/src/plugins/pythoneditor/wizard/pythonclasswizard.h b/src/plugins/pythoneditor/wizard/pythonclasswizard.h
index 763be1b9f6..147d005a87 100644
--- a/src/plugins/pythoneditor/wizard/pythonclasswizard.h
+++ b/src/plugins/pythoneditor/wizard/pythonclasswizard.h
@@ -37,6 +37,8 @@ namespace Utils { class NewClassWidget; }
namespace ProjectExplorer { class Kit; }
namespace PythonEditor {
+namespace Internal {
+
class ClassWizardDialog;
class ClassWizard : public Core::BaseFileWizard
@@ -44,9 +46,9 @@ class ClassWizard : public Core::BaseFileWizard
Q_OBJECT
public:
- explicit ClassWizard(QObject *parent = 0);
+ ClassWizard();
-protected:
+private:
QWizard *createWizardDialog(QWidget *parent,
const Core::WizardDialogParameters &params) const;
@@ -56,6 +58,7 @@ protected:
ProjectExplorer::Kit *kitForWizard(const ClassWizardDialog *wizard) const;
};
+} // namespace Internal
} // namespace PythonEditor
#endif // PYTHONEDITOR_CLASSWIZARD_H
diff --git a/src/plugins/pythoneditor/wizard/pythonclasswizarddialog.cpp b/src/plugins/pythoneditor/wizard/pythonclasswizarddialog.cpp
index 80d5f0e4b5..040a9c222b 100644
--- a/src/plugins/pythoneditor/wizard/pythonclasswizarddialog.cpp
+++ b/src/plugins/pythoneditor/wizard/pythonclasswizarddialog.cpp
@@ -34,6 +34,7 @@
#include <coreplugin/basefilewizard.h>
namespace PythonEditor {
+namespace Internal {
ClassWizardDialog::ClassWizardDialog(QWidget *parent)
: Utils::Wizard(parent)
@@ -77,4 +78,5 @@ void ClassWizardDialog::setPath(const QString &path)
m_classNamePage->newClassWidget()->setPath(path);
}
+} // namespace Internal
} // namespace PythonEditor
diff --git a/src/plugins/pythoneditor/wizard/pythonclasswizarddialog.h b/src/plugins/pythoneditor/wizard/pythonclasswizarddialog.h
index 5e9d011f5f..5743f86be5 100644
--- a/src/plugins/pythoneditor/wizard/pythonclasswizarddialog.h
+++ b/src/plugins/pythoneditor/wizard/pythonclasswizarddialog.h
@@ -36,6 +36,7 @@
#include <QVariantMap>
namespace PythonEditor {
+namespace Internal {
class ClassNamePage;
@@ -67,6 +68,7 @@ private:
QVariantMap m_extraValues;
};
+} // namespace Internal
} // namespace PythonEditor
#endif // PYTHONEDITOR_CLASSWIZARDDIALOG_H
diff --git a/src/plugins/pythoneditor/wizard/pythonfilewizard.cpp b/src/plugins/pythoneditor/wizard/pythonfilewizard.cpp
index 8d3314c42f..67b21367bd 100644
--- a/src/plugins/pythoneditor/wizard/pythonfilewizard.cpp
+++ b/src/plugins/pythoneditor/wizard/pythonfilewizard.cpp
@@ -42,31 +42,17 @@
namespace PythonEditor {
/**
- * @brief GetDefaultParams
- * @return Default parameters for menu item "Files&Classes->Python->Python file"
- */
-static const Core::BaseFileWizardParameters GetDefaultParams()
-{
- Core::BaseFileWizardParameters p(Core::IWizard::FileWizard);
-
- p.setId(QLatin1String(Constants::C_PY_SOURCE_WIZARD_ID));
- p.setCategory(QLatin1String(Constants::C_PY_WIZARD_CATEGORY));
- p.setDisplayCategory(QLatin1String(Constants::C_PY_DISPLAY_CATEGORY));
- p.setDisplayName(
- FileWizard::tr(Constants::EN_PY_SOURCE_DISPLAY_NAME));
- p.setDescription(
- FileWizard::tr(Constants::EN_PY_SOURCE_DESCRIPTION));
-
- return p;
-}
-
-/**
* @brief Initialize wizard and add new option to "New..." dialog.
* @param parent
*/
-FileWizard::FileWizard(QObject *parent)
- :Core::BaseFileWizard(GetDefaultParams(), parent)
+FileWizard::FileWizard()
{
+ setWizardKind(Core::IWizard::FileWizard);
+ setId(QLatin1String(Constants::C_PY_SOURCE_WIZARD_ID));
+ setCategory(QLatin1String(Constants::C_PY_WIZARD_CATEGORY));
+ setDisplayCategory(QLatin1String(Constants::C_PY_DISPLAY_CATEGORY));
+ setDisplayName(FileWizard::tr(Constants::EN_PY_SOURCE_DISPLAY_NAME));
+ setDescription(FileWizard::tr(Constants::EN_PY_SOURCE_DESCRIPTION));
}
FileWizard::~FileWizard()
diff --git a/src/plugins/pythoneditor/wizard/pythonfilewizard.h b/src/plugins/pythoneditor/wizard/pythonfilewizard.h
index d64e1e3bc6..ba689c59cf 100644
--- a/src/plugins/pythoneditor/wizard/pythonfilewizard.h
+++ b/src/plugins/pythoneditor/wizard/pythonfilewizard.h
@@ -39,16 +39,14 @@ class FileWizard : public Core::BaseFileWizard
Q_OBJECT
public:
- explicit FileWizard(QObject *parent = 0);
- virtual ~FileWizard();
+ FileWizard();
+ ~FileWizard();
protected:
- virtual QWizard *createWizardDialog(
- QWidget *parent,
+ QWizard *createWizardDialog(QWidget *parent,
const Core::WizardDialogParameters &params) const;
- virtual Core::GeneratedFiles generateFiles(
- const QWizard *dialog,
+ Core::GeneratedFiles generateFiles( const QWizard *dialog,
QString *errorMessage) const;
};
diff --git a/src/plugins/pythoneditor/wizard/pythonsourcegenerator.cpp b/src/plugins/pythoneditor/wizard/pythonsourcegenerator.cpp
index d1407a06ec..87f2e04c13 100644
--- a/src/plugins/pythoneditor/wizard/pythonsourcegenerator.cpp
+++ b/src/plugins/pythoneditor/wizard/pythonsourcegenerator.cpp
@@ -31,6 +31,7 @@
#include <QSet>
namespace PythonEditor {
+namespace Internal {
static const char BASH_RUN_HEADER[] = "#!/usr/bin/env python\n";
static const char ENCODING_HEADER[] = "# -*- coding: utf-8 -*-\n";
@@ -207,4 +208,5 @@ QString SourceGenerator::moduleForQWidget() const
return QLatin1String("QtWidgets");
}
+} // namespace Internal
} // namespace PythonEditor
diff --git a/src/plugins/pythoneditor/wizard/pythonsourcegenerator.h b/src/plugins/pythoneditor/wizard/pythonsourcegenerator.h
index ef82955351..d638ac8d87 100644
--- a/src/plugins/pythoneditor/wizard/pythonsourcegenerator.h
+++ b/src/plugins/pythoneditor/wizard/pythonsourcegenerator.h
@@ -30,14 +30,14 @@
#ifndef PYTHON_SOURCEGENERATOR_H
#define PYTHON_SOURCEGENERATOR_H
-#include "../pythoneditor_global.h"
#include <utils/newclasswidget.h>
#include <QSet>
#include <QString>
namespace PythonEditor {
+namespace Internal {
-class PYEDITOR_EXPORT SourceGenerator
+class SourceGenerator
{
public:
enum QtBinding {
@@ -70,6 +70,7 @@ private:
QtVersion m_pythonQtVersion;
};
+} // namespace Internal
} // namespace PythonEditor
#endif // PYTHON_SOURCEGENERATOR_H
diff --git a/src/plugins/qbsprojectmanager/QbsProjectManager.pluginspec.in b/src/plugins/qbsprojectmanager/QbsProjectManager.pluginspec.in
index e776d3e0f6..8c45537a20 100644
--- a/src/plugins/qbsprojectmanager/QbsProjectManager.pluginspec.in
+++ b/src/plugins/qbsprojectmanager/QbsProjectManager.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"QbsProjectManager\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\" experimental=\"true\">
+<plugin name=\"QbsProjectManager\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\" experimental=\"true\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/qbsprojectmanager/defaultpropertyprovider.cpp b/src/plugins/qbsprojectmanager/defaultpropertyprovider.cpp
new file mode 100644
index 0000000000..a5444559d2
--- /dev/null
+++ b/src/plugins/qbsprojectmanager/defaultpropertyprovider.cpp
@@ -0,0 +1,125 @@
+/****************************************************************************
+**
+** 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 "defaultpropertyprovider.h"
+#include "qbsconstants.h"
+
+#include <projectexplorer/kit.h>
+#include <projectexplorer/kitinformation.h>
+#include <projectexplorer/toolchain.h>
+#include <qtsupport/baseqtversion.h>
+#include <qtsupport/qtkitinformation.h>
+#include <utils/qtcassert.h>
+
+#include <QFileInfo>
+
+namespace QbsProjectManager {
+using namespace Constants;
+
+QVariantMap DefaultPropertyProvider::properties(const ProjectExplorer::Kit *k, const QVariantMap &defaultData) const
+{
+ QTC_ASSERT(k, return defaultData);
+ QVariantMap data = defaultData;
+ QtSupport::BaseQtVersion *qt = QtSupport::QtKitInformation::qtVersion(k);
+ if (qt) {
+ data.insert(QLatin1String(QTCORE_BINPATH), qt->binPath().toUserOutput());
+ QStringList builds;
+ if (qt->hasDebugBuild())
+ builds << QLatin1String("debug");
+ if (qt->hasReleaseBuild())
+ builds << QLatin1String("release");
+ data.insert(QLatin1String(QTCORE_BUILDVARIANT), builds);
+ data.insert(QLatin1String(QTCORE_DOCPATH), qt->docsPath().toUserOutput());
+ data.insert(QLatin1String(QTCORE_INCPATH), qt->headerPath().toUserOutput());
+ data.insert(QLatin1String(QTCORE_LIBPATH), qt->libraryPath().toUserOutput());
+ data.insert(QLatin1String(QTCORE_PLUGINPATH), qt->pluginPath().toUserOutput());
+ Utils::FileName mkspecPath = qt->mkspecsPath();
+ mkspecPath.appendPath(qt->mkspec().toString());
+ data.insert(QLatin1String(QTCORE_MKSPEC), mkspecPath.toUserOutput());
+ data.insert(QLatin1String(QTCORE_NAMESPACE), qt->qtNamespace());
+ data.insert(QLatin1String(QTCORE_LIBINFIX), qt->qtLibInfix());
+ data.insert(QLatin1String(QTCORE_VERSION), qt->qtVersionString());
+ if (qt->isFrameworkBuild())
+ data.insert(QLatin1String(QTCORE_FRAMEWORKBUILD), true);
+ }
+
+ if (ProjectExplorer::SysRootKitInformation::hasSysRoot(k))
+ data.insert(QLatin1String(QBS_SYSROOT), ProjectExplorer::SysRootKitInformation::sysRoot(k).toUserOutput());
+
+ ProjectExplorer::ToolChain *tc = ProjectExplorer::ToolChainKitInformation::toolChain(k);
+ if (tc) {
+ // FIXME/CLARIFY: How to pass the sysroot?
+ ProjectExplorer::Abi targetAbi = tc->targetAbi();
+ QString architecture = ProjectExplorer::Abi::toString(targetAbi.architecture());
+ if (targetAbi.wordWidth() == 64)
+ architecture.append(QLatin1String("_64"));
+ data.insert(QLatin1String(QBS_ARCHITECTURE), architecture);
+
+ if (targetAbi.endianness() == ProjectExplorer::Abi::BigEndian)
+ data.insert(QLatin1String(QBS_ENDIANNESS), QLatin1String("big"));
+ else
+ data.insert(QLatin1String(QBS_ENDIANNESS), QLatin1String("little"));
+
+ if (targetAbi.os() == ProjectExplorer::Abi::WindowsOS) {
+ data.insert(QLatin1String(QBS_TARGETOS), QLatin1String("windows"));
+ data.insert(QLatin1String(QBS_TOOLCHAIN),
+ targetAbi.osFlavor() == ProjectExplorer::Abi::WindowsMSysFlavor
+ ? QStringList() << QLatin1String("mingw") << QLatin1String("gcc")
+ : QStringList() << QLatin1String("msvc"));
+ } else if (targetAbi.os() == ProjectExplorer::Abi::MacOS) {
+ data.insert(QLatin1String(QBS_TARGETOS), QStringList() << QLatin1String("osx")
+ << QLatin1String("darwin") << QLatin1String("unix"));
+ if (tc->type() != QLatin1String("clang")) {
+ data.insert(QLatin1String(QBS_TOOLCHAIN), QLatin1String("gcc"));
+ } else {
+ data.insert(QLatin1String(QBS_TOOLCHAIN),
+ QStringList() << QLatin1String("clang")
+ << QLatin1String("llvm")
+ << QLatin1String("gcc"));
+ }
+ } else if (targetAbi.os() == ProjectExplorer::Abi::LinuxOS) {
+ data.insert(QLatin1String(QBS_TARGETOS), QStringList() << QLatin1String("linux")
+ << QLatin1String("unix"));
+ if (tc->type() != QLatin1String("clang")) {
+ data.insert(QLatin1String(QBS_TOOLCHAIN), QLatin1String("gcc"));
+ } else {
+ data.insert(QLatin1String(QBS_TOOLCHAIN),
+ QStringList() << QLatin1String("clang")
+ << QLatin1String("llvm")
+ << QLatin1String("gcc"));
+ }
+ }
+ Utils::FileName cxx = tc->compilerCommand();
+ data.insert(QLatin1String(CPP_TOOLCHAINPATH), cxx.toFileInfo().absolutePath());
+ data.insert(QLatin1String(CPP_COMPILERNAME), cxx.toFileInfo().fileName());
+ }
+ return data;
+}
+
+} // namespace QbsProjectManager
diff --git a/src/plugins/qbsprojectmanager/defaultpropertyprovider.h b/src/plugins/qbsprojectmanager/defaultpropertyprovider.h
new file mode 100644
index 0000000000..5b1d2961b6
--- /dev/null
+++ b/src/plugins/qbsprojectmanager/defaultpropertyprovider.h
@@ -0,0 +1,48 @@
+/****************************************************************************
+**
+** 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 DEFAULTPROPERTYPROVIDER_H
+#define DEFAULTPROPERTYPROVIDER_H
+
+#include "propertyprovider.h"
+
+namespace QbsProjectManager {
+
+class DefaultPropertyProvider : public PropertyProvider
+{
+ Q_OBJECT
+
+public:
+ bool canHandle(const ProjectExplorer::Kit *k) const { return k; }
+ QVariantMap properties(const ProjectExplorer::Kit *k, const QVariantMap &defaultData) const;
+};
+
+} // namespace QbsProjectManager
+
+#endif // DEFAULTPROPERTYPROVIDER_H
diff --git a/src/plugins/qbsprojectmanager/propertyprovider.h b/src/plugins/qbsprojectmanager/propertyprovider.h
new file mode 100644
index 0000000000..fd310c0182
--- /dev/null
+++ b/src/plugins/qbsprojectmanager/propertyprovider.h
@@ -0,0 +1,53 @@
+/****************************************************************************
+**
+** 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 PROPERTYPROVIDER_H
+#define PROPERTYPROVIDER_H
+
+#include "qbsprojectmanager_global.h"
+
+#include <QObject>
+#include <QVariantMap>
+
+namespace ProjectExplorer { class Kit; }
+
+namespace QbsProjectManager {
+
+class QBSPROJECTMANAGER_EXPORT PropertyProvider : public QObject
+{
+ Q_OBJECT
+
+public:
+ virtual bool canHandle(const ProjectExplorer::Kit *k) const = 0;
+ virtual QVariantMap properties(const ProjectExplorer::Kit *k, const QVariantMap &defaultData) const = 0;
+};
+
+} // namespace QbsProjectManager
+
+#endif // PROPERTYPROVIDER_H
diff --git a/src/plugins/qbsprojectmanager/qbsbuildconfiguration.cpp b/src/plugins/qbsprojectmanager/qbsbuildconfiguration.cpp
index 35769432c9..fd54f2d3e8 100644
--- a/src/plugins/qbsprojectmanager/qbsbuildconfiguration.cpp
+++ b/src/plugins/qbsprojectmanager/qbsbuildconfiguration.cpp
@@ -30,11 +30,14 @@
#include "qbsbuildconfiguration.h"
#include "qbsbuildconfigurationwidget.h"
+#include "qbsbuildinfo.h"
#include "qbsbuildstep.h"
#include "qbscleanstep.h"
#include "qbsproject.h"
#include "qbsprojectmanagerconstants.h"
+#include <coreplugin/icore.h>
+#include <coreplugin/mimedatabase.h>
#include <utils/qtcassert.h>
#include <projectexplorer/buildsteplist.h>
#include <projectexplorer/kit.h>
@@ -46,7 +49,6 @@
#include <QInputDialog>
static const char QBS_BC_ID[] = "Qbs.QbsBuildConfiguration";
-static const char QBS_BUILD_DIRECTORY_KEY[] = "Qbs.BuildDirectory";
namespace QbsProjectManager {
namespace Internal {
@@ -74,19 +76,11 @@ QbsBuildConfiguration::QbsBuildConfiguration(ProjectExplorer::Target *target, co
{ }
QbsBuildConfiguration::QbsBuildConfiguration(ProjectExplorer::Target *target, QbsBuildConfiguration *source) :
- BuildConfiguration(target, source),
- m_buildDirectory(source->m_buildDirectory)
+ BuildConfiguration(target, source)
{
cloneSteps(source);
}
-QVariantMap QbsBuildConfiguration::toMap() const
-{
- QVariantMap map(BuildConfiguration::toMap());
- map.insert(QLatin1String(QBS_BUILD_DIRECTORY_KEY), m_buildDirectory.toUserOutput());
- return map;
-}
-
bool QbsBuildConfiguration::fromMap(const QVariantMap &map)
{
if (!BuildConfiguration::fromMap(map))
@@ -101,8 +95,6 @@ bool QbsBuildConfiguration::fromMap(const QVariantMap &map)
connect(bs, SIGNAL(qbsConfigurationChanged()), this, SIGNAL(qbsConfigurationChanged()));
}
- m_buildDirectory = Utils::FileName::fromUserInput(map.value(QLatin1String(QBS_BUILD_DIRECTORY_KEY)).toString());
-
return true;
}
@@ -139,12 +131,6 @@ QVariantMap QbsBuildConfiguration::qbsConfiguration() const
return config;
}
-QString QbsBuildConfiguration::buildDirectory() const
-{
- QString path = QDir::cleanPath(environment().expandVariables(m_buildDirectory.toString()));
- return QDir::cleanPath(QDir(target()->project()->projectDirectory()).absoluteFilePath(path));
-}
-
Internal::QbsProject *QbsBuildConfiguration::project() const
{
return qobject_cast<Internal::QbsProject *>(target()->project());
@@ -193,6 +179,16 @@ QStringList QbsBuildConfiguration::changedFiles() const
return m_changedFiles;
}
+void QbsBuildConfiguration::setActiveFileTags(const QStringList &fileTags)
+{
+ m_activeFileTags = fileTags;
+}
+
+QStringList QbsBuildConfiguration::activeFileTags() const
+{
+ return m_activeFileTags;
+}
+
void QbsBuildConfiguration::setProducts(const QStringList &products)
{
m_products = products;
@@ -229,14 +225,6 @@ QbsBuildConfiguration *QbsBuildConfiguration::setup(ProjectExplorer::Target *t,
return bc;
}
-void QbsBuildConfiguration::setBuildDirectory(const Utils::FileName &dir)
-{
- if (m_buildDirectory == dir)
- return;
- m_buildDirectory = dir;
- emit buildDirectoryChanged();
-}
-
// ---------------------------------------------------------------------------
// QbsBuildConfigurationFactory:
// ---------------------------------------------------------------------------
@@ -253,66 +241,84 @@ bool QbsBuildConfigurationFactory::canHandle(const ProjectExplorer::Target *t) c
return qobject_cast<Internal::QbsProject *>(t->project());
}
-QList<Core::Id> QbsBuildConfigurationFactory::availableCreationIds(const ProjectExplorer::Target *parent) const
+ProjectExplorer::BuildInfo *QbsBuildConfigurationFactory::createBuildInfo(const ProjectExplorer::Kit *k,
+ const Utils::FileName &buildDirectory,
+ ProjectExplorer::BuildConfiguration::BuildType type) const
{
- if (!canHandle(parent))
- return QList<Core::Id>();
- return QList<Core::Id>() << Core::Id(QBS_BC_ID);
+ QbsBuildInfo *info = new QbsBuildInfo(this);
+ info->typeName = tr("Build");
+ info->buildDirectory = buildDirectory;
+ info->kitId = k->id();
+ info->type = type;
+ info->supportsShadowBuild = true;
+ return info;
}
-QString QbsBuildConfigurationFactory::displayNameForId(const Core::Id id) const
+bool QbsBuildConfigurationFactory::canCreate(const ProjectExplorer::Target *parent) const
{
- if (id == QBS_BC_ID)
- return tr("Qbs based build");
- return QString();
+ return canHandle(parent);
}
-bool QbsBuildConfigurationFactory::canCreate(const ProjectExplorer::Target *parent, const Core::Id id) const
+QList<ProjectExplorer::BuildInfo *> QbsBuildConfigurationFactory::availableBuilds(const ProjectExplorer::Target *parent) const
{
- if (!canHandle(parent))
- return false;
- return id == QBS_BC_ID;
+ QList<ProjectExplorer::BuildInfo *> result;
+ QTC_ASSERT(canCreate(parent), return result);
+
+ const Utils::FileName buildDirectory = QbsProject::defaultBuildDirectory(parent->project()->projectFilePath());
+
+ ProjectExplorer::BuildInfo *info = createBuildInfo(parent->kit(), buildDirectory,
+ ProjectExplorer::BuildConfiguration::Debug);
+ result << info;
+
+ return result;
}
-ProjectExplorer::BuildConfiguration *QbsBuildConfigurationFactory::create(ProjectExplorer::Target *parent,
- const Core::Id id,
- const QString &name)
+bool QbsBuildConfigurationFactory::canSetup(const ProjectExplorer::Kit *k, const QString &projectPath) const
{
- if (!canCreate(parent, id))
- return 0;
+ return k && Core::MimeDatabase::findByFile(QFileInfo(projectPath))
+ .matchesType(QLatin1String(Constants::MIME_TYPE));
+}
- Internal::QbsProject *project = static_cast<Internal::QbsProject *>(parent->project());
-
- bool ok = true;
- QString buildConfigurationName = name;
- if (buildConfigurationName.isNull())
- buildConfigurationName = QInputDialog::getText(0,
- tr("New Configuration"),
- tr("New configuration name:"),
- QLineEdit::Normal,
- QString(), &ok);
- buildConfigurationName = buildConfigurationName.trimmed();
- if (!ok || buildConfigurationName.isEmpty())
- return 0;
+QList<ProjectExplorer::BuildInfo *> QbsBuildConfigurationFactory::availableSetups(const ProjectExplorer::Kit *k, const QString &projectPath) const
+{
+ QList<ProjectExplorer::BuildInfo *> result;
+ QTC_ASSERT(canSetup(k, projectPath), return result);
- //: Debug build configuration. We recommend not translating it.
- QString firstName = tr("%1 Debug").arg(buildConfigurationName).trimmed();
+ const Utils::FileName buildDirectory = QbsProject::defaultBuildDirectory(projectPath);
- //: Release build configuration. We recommend not translating it.
- QString secondName = tr("%1 Release").arg(buildConfigurationName).trimmed();
+ ProjectExplorer::BuildInfo *info = createBuildInfo(k, buildDirectory, ProjectExplorer::BuildConfiguration::Debug);
+ //: The name of the debug build configuration created by default for a qbs project.
+ info->displayName = tr("Debug");
+ result << info;
+
+ info = createBuildInfo(k, buildDirectory, ProjectExplorer::BuildConfiguration::Release);
+ //: The name of the release build configuration created by default for a qbs project.
+ info->displayName = tr("Release");
+ result << info;
+
+ return result;
+}
+
+ProjectExplorer::BuildConfiguration *QbsBuildConfigurationFactory::create(ProjectExplorer::Target *parent,
+ const ProjectExplorer::BuildInfo *info) const
+{
+ QTC_ASSERT(canCreate(parent), return 0);
+ QTC_ASSERT(info->factory() == this, return 0);
+ QTC_ASSERT(info->kitId == parent->kit()->id(), return 0);
+ QTC_ASSERT(!info->displayName.isEmpty(), return 0);
+
+ const QbsBuildInfo *qbsInfo = static_cast<const QbsBuildInfo *>(info);
QVariantMap configData;
configData.insert(QLatin1String(Constants::QBS_CONFIG_VARIANT_KEY),
- QLatin1String(Constants::QBS_VARIANT_DEBUG));
+ (qbsInfo->type == ProjectExplorer::BuildConfiguration::Release)
+ ? QLatin1String(Constants::QBS_VARIANT_RELEASE)
+ : QLatin1String(Constants::QBS_VARIANT_DEBUG));
ProjectExplorer::BuildConfiguration *bc
- = QbsBuildConfiguration::setup(parent, firstName, firstName,
- configData, project->defaultBuildDirectory());
- configData.insert(QLatin1String(Constants::QBS_CONFIG_VARIANT_KEY),
- QLatin1String(Constants::QBS_VARIANT_RELEASE));
- parent->addBuildConfiguration(
- QbsBuildConfiguration::setup(parent, secondName, secondName,
- configData, project->defaultBuildDirectory()));
+ = QbsBuildConfiguration::setup(parent, info->displayName, info->displayName,
+ configData, info->buildDirectory);
+
return bc;
}
diff --git a/src/plugins/qbsprojectmanager/qbsbuildconfiguration.h b/src/plugins/qbsprojectmanager/qbsbuildconfiguration.h
index 6304bf7adc..61bde2f9c3 100644
--- a/src/plugins/qbsprojectmanager/qbsbuildconfiguration.h
+++ b/src/plugins/qbsprojectmanager/qbsbuildconfiguration.h
@@ -57,12 +57,9 @@ public:
QbsBuildStep *qbsStep() const;
QVariantMap qbsConfiguration() const;
- QString buildDirectory() const;
Internal::QbsProject *project() const;
- QVariantMap toMap() const;
-
ProjectExplorer::IOutputParser *createOutputParser() const;
bool isEnabled() const;
@@ -73,6 +70,9 @@ public:
void setChangedFiles(const QStringList &files);
QStringList changedFiles() const;
+ void setActiveFileTags(const QStringList &fileTags);
+ QStringList activeFileTags() const;
+
void setProducts(const QStringList &products);
QStringList products() const;
@@ -93,12 +93,11 @@ private:
const QString &displayName,
const QVariantMap &buildData,
const Utils::FileName &directory);
- void setBuildDirectory(const Utils::FileName &dir);
bool m_isParsing;
bool m_parsingError;
- Utils::FileName m_buildDirectory;
QStringList m_changedFiles;
+ QStringList m_activeFileTags;
QStringList m_products;
friend class QbsBuildConfigurationFactory;
@@ -113,11 +112,14 @@ public:
explicit QbsBuildConfigurationFactory(QObject *parent = 0);
~QbsBuildConfigurationFactory();
- QList<Core::Id> availableCreationIds(const ProjectExplorer::Target *parent) const;
- QString displayNameForId(const Core::Id id) const;
+ bool canCreate(const ProjectExplorer::Target *parent) const;
+ QList<ProjectExplorer::BuildInfo *> availableBuilds(const ProjectExplorer::Target *parent) const;
+ bool canSetup(const ProjectExplorer::Kit *k, const QString &projectPath) const;
+ QList<ProjectExplorer::BuildInfo *> availableSetups(const ProjectExplorer::Kit *k,
+ const QString &projectPath) const;
+ ProjectExplorer::BuildConfiguration *create(ProjectExplorer::Target *parent,
+ const ProjectExplorer::BuildInfo *info) const;
- bool canCreate(const ProjectExplorer::Target *parent, const Core::Id id) const;
- ProjectExplorer::BuildConfiguration *create(ProjectExplorer::Target *parent, const Core::Id id, const QString &name = QString());
bool canClone(const ProjectExplorer::Target *parent, ProjectExplorer::BuildConfiguration *source) const;
ProjectExplorer::BuildConfiguration *clone(ProjectExplorer::Target *parent, ProjectExplorer::BuildConfiguration *source);
bool canRestore(const ProjectExplorer::Target *parent, const QVariantMap &map) const;
@@ -125,6 +127,9 @@ public:
private:
bool canHandle(const ProjectExplorer::Target *t) const;
+ ProjectExplorer::BuildInfo *createBuildInfo(const ProjectExplorer::Kit *k,
+ const Utils::FileName &buildDirectory,
+ ProjectExplorer::BuildConfiguration::BuildType type) const;
};
} // namespace Internal
diff --git a/src/plugins/qbsprojectmanager/qbsbuildconfigurationwidget.cpp b/src/plugins/qbsprojectmanager/qbsbuildconfigurationwidget.cpp
index b6f6c90743..45e6135718 100644
--- a/src/plugins/qbsprojectmanager/qbsbuildconfigurationwidget.cpp
+++ b/src/plugins/qbsprojectmanager/qbsbuildconfigurationwidget.cpp
@@ -31,6 +31,8 @@
#include "qbsbuildconfiguration.h"
+#include <projectexplorer/target.h>
+#include <projectexplorer/project.h>
#include <utils/detailswidget.h>
#include <utils/pathchooser.h>
@@ -45,8 +47,8 @@ QbsBuildConfigurationWidget::QbsBuildConfigurationWidget(QbsProjectManager::Inte
m_buildConfiguration(bc),
m_ignoreChange(false)
{
- connect(m_buildConfiguration, SIGNAL(buildDirectoryChanged()),
- this, SLOT(buildDirectoryChanged()));
+ connect(bc, SIGNAL(buildDirectoryChanged()), this, SLOT(buildDirectoryChanged()));
+ connect(bc, SIGNAL(environmentChanged()), this, SLOT(environmentHasChanged()));
QVBoxLayout *vbox = new QVBoxLayout(this);
vbox->setMargin(0);
@@ -63,6 +65,8 @@ QbsBuildConfigurationWidget::QbsBuildConfigurationWidget(QbsProjectManager::Inte
m_buildDirChooser = new Utils::PathChooser;
m_buildDirChooser->setExpectedKind(Utils::PathChooser::Directory);
+ m_buildDirChooser->setBaseDirectory(bc->target()->project()->projectDirectory());
+ m_buildDirChooser->setEnvironment(bc->environment());
layout->addWidget(m_buildDirChooser, 0, 1);
connect(m_buildDirChooser, SIGNAL(changed(QString)), this, SLOT(buildDirEdited()));
@@ -81,7 +85,12 @@ void QbsBuildConfigurationWidget::buildDirectoryChanged()
if (m_ignoreChange)
return;
- m_buildDirChooser->setPath(m_buildConfiguration->buildDirectory());
+ m_buildDirChooser->setPath(m_buildConfiguration->rawBuildDirectory().toString());
+}
+
+void QbsBuildConfigurationWidget::environmentHasChanged()
+{
+ m_buildDirChooser->setEnvironment(m_buildConfiguration->environment());
}
} // namespace Internal
diff --git a/src/plugins/qbsprojectmanager/qbsbuildconfigurationwidget.h b/src/plugins/qbsprojectmanager/qbsbuildconfigurationwidget.h
index 0625e5ae39..b91e7d8e90 100644
--- a/src/plugins/qbsprojectmanager/qbsbuildconfigurationwidget.h
+++ b/src/plugins/qbsprojectmanager/qbsbuildconfigurationwidget.h
@@ -53,6 +53,7 @@ private slots:
// Changes triggered from creator
void buildDirectoryChanged();
+ void environmentHasChanged();
private:
Internal::QbsBuildConfiguration *m_buildConfiguration;
diff --git a/src/plugins/qbsprojectmanager/qbsbuildinfo.h b/src/plugins/qbsprojectmanager/qbsbuildinfo.h
new file mode 100644
index 0000000000..913c24bfb1
--- /dev/null
+++ b/src/plugins/qbsprojectmanager/qbsbuildinfo.h
@@ -0,0 +1,52 @@
+/****************************************************************************
+**
+** 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 QBSBUILDINFO_H
+#define QBSBUILDINFO_H
+
+#include "qbsbuildconfiguration.h"
+
+#include <projectexplorer/buildinfo.h>
+#include <qtsupport/baseqtversion.h>
+
+namespace QbsProjectManager {
+namespace Internal {
+
+class QbsBuildInfo : public ProjectExplorer::BuildInfo
+{
+public:
+ QbsBuildInfo(const QbsBuildConfigurationFactory *f) : ProjectExplorer::BuildInfo(f) { }
+
+ ProjectExplorer::BuildConfiguration::BuildType type;
+};
+
+} // namespace Internal
+} // namespace QbsProjectManager
+
+#endif // QBSBUILDINFO_H
diff --git a/src/plugins/qbsprojectmanager/qbsbuildstep.cpp b/src/plugins/qbsprojectmanager/qbsbuildstep.cpp
index 9c6a4ceb0e..d576239768 100644
--- a/src/plugins/qbsprojectmanager/qbsbuildstep.cpp
+++ b/src/plugins/qbsprojectmanager/qbsbuildstep.cpp
@@ -107,6 +107,7 @@ bool QbsBuildStep::init()
m_parser->appendOutputParser(parser);
m_changedFiles = bc->changedFiles();
+ m_activeFileTags = bc->activeFileTags();
m_products = bc->products();
connect(m_parser, SIGNAL(addOutput(QString,ProjectExplorer::BuildStep::OutputFormat)),
@@ -124,6 +125,7 @@ void QbsBuildStep::run(QFutureInterface<bool> &fi)
QbsProject *pro = static_cast<QbsProject *>(project());
qbs::BuildOptions options(m_qbsBuildOptions);
options.setChangedFiles(m_changedFiles);
+ options.setActiveFileTags(m_activeFileTags);
m_job = pro->build(options, m_products);
diff --git a/src/plugins/qbsprojectmanager/qbsbuildstep.h b/src/plugins/qbsprojectmanager/qbsbuildstep.h
index fce407b658..a6e6827da9 100644
--- a/src/plugins/qbsprojectmanager/qbsbuildstep.h
+++ b/src/plugins/qbsprojectmanager/qbsbuildstep.h
@@ -100,6 +100,7 @@ private:
// Temporary data:
QStringList m_changedFiles;
+ QStringList m_activeFileTags;
QStringList m_products;
QFutureInterface<bool> *m_fi;
diff --git a/src/plugins/qbsprojectmanager/qbsbuildstepconfigwidget.ui b/src/plugins/qbsprojectmanager/qbsbuildstepconfigwidget.ui
index c0284b6315..0533f059ec 100644
--- a/src/plugins/qbsprojectmanager/qbsbuildstepconfigwidget.ui
+++ b/src/plugins/qbsprojectmanager/qbsbuildstepconfigwidget.ui
@@ -168,7 +168,7 @@
<customwidget>
<class>QbsPropertyLineEdit</class>
<extends>QLineEdit</extends>
- <header>qbspropertylineedit.h</header>
+ <header location="global">qbsprojectmanager/qbspropertylineedit.h</header>
</customwidget>
</customwidgets>
<resources/>
diff --git a/src/plugins/qbsprojectmanager/qbsconstants.h b/src/plugins/qbsprojectmanager/qbsconstants.h
new file mode 100644
index 0000000000..9b8cf7c15f
--- /dev/null
+++ b/src/plugins/qbsprojectmanager/qbsconstants.h
@@ -0,0 +1,62 @@
+/****************************************************************************
+**
+** 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 QBSCONSTANTS_H
+#define QBSCONSTANTS_H
+
+namespace QbsProjectManager {
+namespace Constants {
+
+// Qt related settings:
+const char QTCORE_BINPATH[] = "Qt.core.binPath";
+const char QTCORE_BUILDVARIANT[] = "Qt.core.buildVariant";
+const char QTCORE_DOCPATH[] = "Qt.core.docPath";
+const char QTCORE_INCPATH[] = "Qt.core.incPath";
+const char QTCORE_LIBPATH[] = "Qt.core.libPath";
+const char QTCORE_PLUGINPATH[] = "Qt.core.pluginPath";
+const char QTCORE_VERSION[] = "Qt.core.version";
+const char QTCORE_NAMESPACE[] = "Qt.core.namespace";
+const char QTCORE_LIBINFIX[] = "Qt.core.libInfix";
+const char QTCORE_MKSPEC[] = "Qt.core.mkspecPath";
+const char QTCORE_FRAMEWORKBUILD[] = "Qt.core.frameworkBuild";
+
+
+// Toolchain related settings:
+const char QBS_TARGETOS[] = "qbs.targetOS";
+const char QBS_SYSROOT[] = "qbs.sysroot";
+const char QBS_ARCHITECTURE[] = "qbs.architecture";
+const char QBS_ENDIANNESS[] = "qbs.endianness";
+const char QBS_TOOLCHAIN[] = "qbs.toolchain";
+const char CPP_TOOLCHAINPATH[] = "cpp.toolchainInstallPath";
+const char CPP_COMPILERNAME[] = "cpp.compilerName";
+
+} // namespace Constants
+} // namespace QbsProjectManager
+
+#endif // QBSCONSTANTS_H
diff --git a/src/plugins/qbsprojectmanager/qbsdeployconfigurationfactory.cpp b/src/plugins/qbsprojectmanager/qbsdeployconfigurationfactory.cpp
index 50a5ddcce9..abd0028eb7 100644
--- a/src/plugins/qbsprojectmanager/qbsdeployconfigurationfactory.cpp
+++ b/src/plugins/qbsprojectmanager/qbsdeployconfigurationfactory.cpp
@@ -33,6 +33,8 @@
#include "qbsproject.h"
#include <projectexplorer/buildsteplist.h>
+#include <projectexplorer/kitinformation.h>
+#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/target.h>
namespace QbsProjectManager {
@@ -48,7 +50,7 @@ static QString genericQbsDisplayName() {
static Core::Id genericQbsDeployConfigurationId()
{
- return Core::Id("Qbs.Deploy");
+ return "Qbs.Deploy";
}
// --------------------------------------------------------------------
@@ -88,8 +90,11 @@ QbsDeployConfigurationFactory::QbsDeployConfigurationFactory(QObject *parent) :
QList<Core::Id> QbsDeployConfigurationFactory::availableCreationIds(ProjectExplorer::Target *parent) const
{
QList<Core::Id> ids;
- if (qobject_cast<QbsProject *>(parent->project()))
+ const Core::Id deviceId = ProjectExplorer::DeviceKitInformation::deviceId(parent->kit());
+ if (qobject_cast<QbsProject *>(parent->project())
+ && deviceId == ProjectExplorer::Constants::DESKTOP_DEVICE_ID) {
ids << genericQbsDeployConfigurationId();
+ }
return ids;
}
diff --git a/src/plugins/qbsprojectmanager/qbslogsink.cpp b/src/plugins/qbsprojectmanager/qbslogsink.cpp
index e22cd6391c..a206b962b2 100644
--- a/src/plugins/qbsprojectmanager/qbslogsink.cpp
+++ b/src/plugins/qbsprojectmanager/qbslogsink.cpp
@@ -49,9 +49,9 @@ namespace Internal {
QbsLogSink::QbsLogSink(QObject *parent) : QObject(parent)
{
- ProjectExplorer::TaskHub *hub = ProjectExplorer::ProjectExplorerPlugin::instance()->taskHub();
connect(this, SIGNAL(newTask(ProjectExplorer::Task)),
- hub, SLOT(addTask(ProjectExplorer::Task)), Qt::QueuedConnection);
+ ProjectExplorer::TaskHub::instance(),
+ SLOT(addTask(ProjectExplorer::Task)), Qt::QueuedConnection);
}
void QbsLogSink::sendMessages()
@@ -63,9 +63,8 @@ void QbsLogSink::sendMessages()
m_messages.clear();
}
- Core::MessageManager *mm = Core::MessageManager::instance();
foreach (const QString &msg, toSend)
- mm->printToOutputPane(msg, Core::MessageManager::NoModeSwitch);
+ Core::MessageManager::write(msg);
}
void QbsLogSink::doPrintWarning(const qbs::ErrorInfo &warning)
diff --git a/src/plugins/qbsprojectmanager/qbsnodes.cpp b/src/plugins/qbsprojectmanager/qbsnodes.cpp
index f4b0fe5f9b..16caaed3ec 100644
--- a/src/plugins/qbsprojectmanager/qbsnodes.cpp
+++ b/src/plugins/qbsprojectmanager/qbsnodes.cpp
@@ -286,32 +286,28 @@ bool QbsBaseProjectNode::removeSubProjects(const QStringList &proFilePaths)
return false;
}
-bool QbsBaseProjectNode::addFiles(const ProjectExplorer::FileType fileType, const QStringList &filePaths, QStringList *notAdded)
+bool QbsBaseProjectNode::addFiles(const QStringList &filePaths, QStringList *notAdded)
{
- Q_UNUSED(fileType);
Q_UNUSED(filePaths);
Q_UNUSED(notAdded);
return false;
}
-bool QbsBaseProjectNode::removeFiles(const ProjectExplorer::FileType fileType, const QStringList &filePaths, QStringList *notRemoved)
+bool QbsBaseProjectNode::removeFiles(const QStringList &filePaths, QStringList *notRemoved)
{
- Q_UNUSED(fileType);
Q_UNUSED(filePaths);
Q_UNUSED(notRemoved);
return false;
}
-bool QbsBaseProjectNode::deleteFiles(const ProjectExplorer::FileType fileType, const QStringList &filePaths)
+bool QbsBaseProjectNode::deleteFiles(const QStringList &filePaths)
{
- Q_UNUSED(fileType);
Q_UNUSED(filePaths);
return false;
}
-bool QbsBaseProjectNode::renameFile(const ProjectExplorer::FileType fileType, const QString &filePath, const QString &newFilePath)
+bool QbsBaseProjectNode::renameFile(const QString &filePath, const QString &newFilePath)
{
- Q_UNUSED(fileType);
Q_UNUSED(filePath);
Q_UNUSED(newFilePath);
return false;
@@ -539,8 +535,8 @@ QList<ProjectExplorer::RunConfiguration *> QbsProductNode::runConfigurationsFor(
Q_UNUSED(node);
QList<ProjectExplorer::RunConfiguration *> result;
QbsProjectNode *pn = qobject_cast<QbsProjectNode *>(projectNode());
- if (!isEnabled() || !pn || pn->qbsProject()->targetExecutable(m_qbsProductData,
- qbs::InstallOptions()).isEmpty()) {
+ if (!isEnabled() || !pn || !pn->qbsProject().isValid()
+ || pn->qbsProject().targetExecutable(m_qbsProductData, qbs::InstallOptions()).isEmpty()) {
return result;
}
@@ -570,15 +566,15 @@ QbsGroupNode *QbsProductNode::findGroupNode(const QString &name)
// --------------------------------------------------------------------
QbsProjectNode::QbsProjectNode(QbsProject *project) :
- QbsBaseProjectNode(project->document()->fileName()),
- m_project(project), m_qbsProject(0)
+ QbsBaseProjectNode(project->projectFilePath()),
+ m_project(project)
{
ctor();
}
QbsProjectNode::QbsProjectNode(const QString &path) :
QbsBaseProjectNode(path),
- m_project(0), m_qbsProject(0)
+ m_project(0)
{
ctor();
}
@@ -586,14 +582,11 @@ QbsProjectNode::QbsProjectNode(const QString &path) :
QbsProjectNode::~QbsProjectNode()
{
// do not delete m_project
- delete m_qbsProject;
}
-void QbsProjectNode::update(const qbs::Project *prj)
+void QbsProjectNode::update(const qbs::Project &prj)
{
- update(prj ? prj->projectData() : qbs::ProjectData());
-
- delete m_qbsProject;
+ update(prj.isValid() ? prj.projectData() : qbs::ProjectData());
m_qbsProject = prj;
}
@@ -642,10 +635,10 @@ QbsProject *QbsProjectNode::project() const
return m_project;
}
-const qbs::Project *QbsProjectNode::qbsProject() const
+const qbs::Project QbsProjectNode::qbsProject() const
{
QbsProjectNode *parent = qobject_cast<QbsProjectNode *>(projectNode());
- if (!m_qbsProject && parent != this)
+ if (!m_qbsProject.isValid() && parent != this)
return parent->qbsProject();
return m_qbsProject;
}
diff --git a/src/plugins/qbsprojectmanager/qbsnodes.h b/src/plugins/qbsprojectmanager/qbsnodes.h
index 2070483493..268f636468 100644
--- a/src/plugins/qbsprojectmanager/qbsnodes.h
+++ b/src/plugins/qbsprojectmanager/qbsnodes.h
@@ -32,7 +32,7 @@
#include <projectexplorer/projectnodes.h>
-#include <api/projectdata.h>
+#include <qbs.h>
#include <QIcon>
@@ -90,17 +90,10 @@ public:
bool removeSubProjects(const QStringList &proFilePaths);
- bool addFiles(const ProjectExplorer::FileType fileType,
- const QStringList &filePaths,
- QStringList *notAdded = 0);
- bool removeFiles(const ProjectExplorer::FileType fileType,
- const QStringList &filePaths,
- QStringList *notRemoved = 0);
- bool deleteFiles(const ProjectExplorer::FileType fileType,
- const QStringList &filePaths);
- bool renameFile(const ProjectExplorer::FileType fileType,
- const QString &filePath,
- const QString &newFilePath);
+ bool addFiles(const QStringList &filePaths, QStringList *notAdded = 0);
+ bool removeFiles(const QStringList &filePaths, QStringList *notRemoved = 0);
+ bool deleteFiles(const QStringList &filePaths);
+ bool renameFile(const QString &filePath, const QString &newFilePath);
QList<ProjectExplorer::RunConfiguration *> runConfigurationsFor(Node *node);
@@ -177,11 +170,11 @@ public:
explicit QbsProjectNode(const QString &path);
~QbsProjectNode();
- void update(const qbs::Project *prj);
+ void update(const qbs::Project &prj);
void update(const qbs::ProjectData &prjData);
QbsProject *project() const;
- const qbs::Project *qbsProject() const;
+ const qbs::Project qbsProject() const;
const qbs::ProjectData qbsProjectData() const;
private:
@@ -192,7 +185,7 @@ private:
QbsProject *m_project;
- const qbs::Project *m_qbsProject;
+ qbs::Project m_qbsProject;
qbs::ProjectData m_qbsProjectData;
static QIcon m_projectIcon;
};
diff --git a/src/plugins/qbsprojectmanager/qbsproject.cpp b/src/plugins/qbsprojectmanager/qbsproject.cpp
index 89b51c4619..5fdd1a7871 100644
--- a/src/plugins/qbsprojectmanager/qbsproject.cpp
+++ b/src/plugins/qbsprojectmanager/qbsproject.cpp
@@ -38,15 +38,15 @@
#include <coreplugin/documentmanager.h>
#include <utils/qtcassert.h>
-#include <language/language.h>
-
#include <coreplugin/icontext.h>
#include <coreplugin/icore.h>
#include <coreplugin/id.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <coreplugin/mimedatabase.h>
-#include <cpptools/cppmodelmanager.h>
+#include <cpptools/cppmodelmanagerinterface.h>
#include <projectexplorer/buildenvironmentwidget.h>
+#include <projectexplorer/buildtargetinfo.h>
+#include <projectexplorer/deploymentdata.h>
#include <projectexplorer/kit.h>
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/projectexplorer.h>
@@ -56,15 +56,22 @@
#include <projectexplorer/toolchain.h>
#include <projectexplorer/headerpath.h>
#include <qtsupport/qtkitinformation.h>
+#include <qtsupport/uicodemodelsupport.h>
#include <qmljstools/qmljsmodelmanager.h>
#include <qmljs/qmljsmodelmanagerinterface.h>
#include <qbs.h>
-#include <tools/scripttools.h> // qbs, remove once there is a expand method in Qbs itself!
#include <QFileInfo>
+using namespace Core;
+using namespace ProjectExplorer;
+using namespace Utils;
+
+namespace QbsProjectManager {
+namespace Internal {
+
// --------------------------------------------------------------------
// Constants:
// --------------------------------------------------------------------
@@ -76,23 +83,9 @@ static const char CONFIG_DEFINES[] = "defines";
static const char CONFIG_INCLUDEPATHS[] = "includePaths";
static const char CONFIG_FRAMEWORKPATHS[] = "frameworkPaths";
static const char CONFIG_PRECOMPILEDHEADER[] = "precompiledHeader";
-
static const char CONFIGURATION_PATH[] = "<configuration>";
// --------------------------------------------------------------------
-// HELPERS:
-// --------------------------------------------------------------------
-
-ProjectExplorer::TaskHub *taskHub()
-{
- return ProjectExplorer::ProjectExplorerPlugin::instance()->taskHub();
-}
-
-
-namespace QbsProjectManager {
-namespace Internal {
-
-// --------------------------------------------------------------------
// QbsProject:
// --------------------------------------------------------------------
@@ -109,8 +102,8 @@ QbsProject::QbsProject(QbsManager *manager, const QString &fileName) :
{
m_parsingDelay.setInterval(1000); // delay parsing by 1s.
- setProjectContext(Core::Context(Constants::PROJECT_ID));
- setProjectLanguages(Core::Context(ProjectExplorer::Constants::LANG_CXX));
+ setProjectContext(Context(Constants::PROJECT_ID));
+ setProjectLanguages(Context(ProjectExplorer::Constants::LANG_CXX));
connect(this, SIGNAL(activeTargetChanged(ProjectExplorer::Target*)),
this, SLOT(changeActiveTarget(ProjectExplorer::Target*)));
@@ -127,6 +120,11 @@ QbsProject::QbsProject(QbsManager *manager, const QString &fileName) :
QbsProject::~QbsProject()
{
m_codeModelFuture.cancel();
+ if (m_qbsSetupProjectJob) {
+ m_qbsSetupProjectJob->disconnect(this);
+ m_qbsSetupProjectJob->cancel();
+ delete m_qbsSetupProjectJob;
+ }
}
QString QbsProject::displayName() const
@@ -134,15 +132,15 @@ QString QbsProject::displayName() const
return m_projectName;
}
-Core::Id QbsProject::id() const
+Id QbsProject::id() const
{
- return Core::Id(Constants::PROJECT_ID);
+ return Constants::PROJECT_ID;
}
-Core::IDocument *QbsProject::document() const
+IDocument *QbsProject::document() const
{
- foreach (Core::IDocument *doc, m_qbsDocuments) {
- if (doc->fileName() == m_fileName)
+ foreach (IDocument *doc, m_qbsDocuments) {
+ if (doc->filePath() == m_fileName)
return doc;
}
QTC_ASSERT(false, return 0);
@@ -153,12 +151,12 @@ QbsManager *QbsProject::projectManager() const
return m_manager;
}
-ProjectExplorer::ProjectNode *QbsProject::rootProjectNode() const
+ProjectNode *QbsProject::rootProjectNode() const
{
return m_rootProjectNode;
}
-QStringList QbsProject::files(ProjectExplorer::Project::FilesMode fileMode) const
+QStringList QbsProject::files(Project::FilesMode fileMode) const
{
Q_UNUSED(fileMode);
QSet<QString> result;
@@ -183,10 +181,10 @@ void QbsProject::invalidate()
qbs::BuildJob *QbsProject::build(const qbs::BuildOptions &opts, QStringList productNames)
{
- if (!qbsProject() || isParsing())
+ if (!qbsProject().isValid() || isParsing())
return 0;
if (productNames.isEmpty()) {
- return qbsProject()->buildAllProducts(opts);
+ return qbsProject().buildAllProducts(opts);
} else {
QList<qbs::ProductData> products;
foreach (const QString &productName, productNames) {
@@ -202,25 +200,25 @@ qbs::BuildJob *QbsProject::build(const qbs::BuildOptions &opts, QStringList prod
return 0;
}
- return qbsProject()->buildSomeProducts(products, opts);
+ return qbsProject().buildSomeProducts(products, opts);
}
}
qbs::CleanJob *QbsProject::clean(const qbs::CleanOptions &opts)
{
- if (!qbsProject())
+ if (!qbsProject().isValid())
return 0;
- return qbsProject()->cleanAllProducts(opts);
+ return qbsProject().cleanAllProducts(opts);
}
qbs::InstallJob *QbsProject::install(const qbs::InstallOptions &opts)
{
- if (!qbsProject())
+ if (!qbsProject().isValid())
return 0;
- return qbsProject()->installAllProducts(opts);
+ return qbsProject().installAllProducts(opts);
}
-QString QbsProject::profileForTarget(const ProjectExplorer::Target *t) const
+QString QbsProject::profileForTarget(const Target *t) const
{
return m_manager->profileForKit(t->kit());
}
@@ -232,20 +230,25 @@ bool QbsProject::isParsing() const
bool QbsProject::hasParseResult() const
{
- return qbsProject();
+ return qbsProject().isValid();
+}
+
+FileName QbsProject::defaultBuildDirectory() const
+{
+ return defaultBuildDirectory(m_fileName);
}
-Utils::FileName QbsProject::defaultBuildDirectory() const
+Utils::FileName QbsProject::defaultBuildDirectory(const QString &path)
{
- QFileInfo fi(m_fileName);
+ QFileInfo fi(path);
const QString buildDir = QDir(fi.canonicalPath()).absoluteFilePath(QString::fromLatin1("../%1-build").arg(fi.baseName()));
- return Utils::FileName::fromString(buildDir);
+ return FileName::fromString(buildDir);
}
-const qbs::Project *QbsProject::qbsProject() const
+qbs::Project QbsProject::qbsProject() const
{
if (!m_rootProjectNode)
- return 0;
+ return qbs::Project();
return m_rootProjectNode->qbsProject();
}
@@ -266,9 +269,9 @@ void QbsProject::handleQbsParsingDone(bool success)
QTC_ASSERT(m_qbsSetupProjectJob, return);
QTC_ASSERT(m_qbsUpdateFutureInterface, return);
- qbs::Project *project = 0;
+ qbs::Project project;
if (success) {
- project = new qbs::Project(m_qbsSetupProjectJob->project());
+ project = m_qbsSetupProjectJob->project();
} else {
generateErrors(m_qbsSetupProjectJob->error());
m_qbsUpdateFutureInterface->reportCanceled();
@@ -282,12 +285,14 @@ void QbsProject::handleQbsParsingDone(bool success)
m_rootProjectNode->update(project);
- updateDocuments(project ? project->buildSystemFiles() : QSet<QString>() << m_fileName);
+ updateDocuments(project.isValid() ? project.buildSystemFiles() : QSet<QString>() << m_fileName);
updateCppCodeModel(m_rootProjectNode->qbsProjectData());
updateQmlJsCodeModel(m_rootProjectNode->qbsProjectData());
+ updateApplicationTargets(m_rootProjectNode->qbsProjectData());
+ updateDeploymentInfo(m_rootProjectNode->qbsProject());
- foreach (ProjectExplorer::Target *t, targets())
+ foreach (Target *t, targets())
t->updateDefaultRunConfigurations();
emit fileListChanged();
@@ -309,22 +314,22 @@ void QbsProject::handleQbsParsingTaskSetup(const QString &description, int maxim
}
}
-void QbsProject::targetWasAdded(ProjectExplorer::Target *t)
+void QbsProject::targetWasAdded(Target *t)
{
connect(t, SIGNAL(activeBuildConfigurationChanged(ProjectExplorer::BuildConfiguration*)),
this, SLOT(delayForcedParsing()));
connect(t, SIGNAL(buildDirectoryChanged()), this, SLOT(delayForcedParsing()));
}
-void QbsProject::changeActiveTarget(ProjectExplorer::Target *t)
+void QbsProject::changeActiveTarget(Target *t)
{
- ProjectExplorer::BuildConfiguration *bc = 0;
+ BuildConfiguration *bc = 0;
if (t && t->kit())
bc = t->activeBuildConfiguration();
buildConfigurationChanged(bc);
}
-void QbsProject::buildConfigurationChanged(ProjectExplorer::BuildConfiguration *bc)
+void QbsProject::buildConfigurationChanged(BuildConfiguration *bc)
{
if (m_currentBc)
disconnect(m_currentBc, SIGNAL(qbsConfigurationChanged()), this, SLOT(delayParsing()));
@@ -358,7 +363,7 @@ void QbsProject::parseCurrentBuildConfiguration()
QbsBuildConfiguration *bc = qobject_cast<QbsBuildConfiguration *>(activeTarget()->activeBuildConfiguration());
if (!bc)
return;
- parse(bc->qbsConfiguration(), bc->environment(), bc->buildDirectory());
+ parse(bc->qbsConfiguration(), bc->environment(), bc->buildDirectory().toString());
}
bool QbsProject::fromMap(const QVariantMap &map)
@@ -366,9 +371,9 @@ bool QbsProject::fromMap(const QVariantMap &map)
if (!Project::fromMap(map))
return false;
- ProjectExplorer::KitManager *km = ProjectExplorer::KitManager::instance();
- if (!activeTarget() && km->defaultKit()) {
- ProjectExplorer::Target *t = new ProjectExplorer::Target(this, km->defaultKit());
+ Kit *defaultKit = KitManager::defaultKit();
+ if (!activeTarget() && defaultKit) {
+ Target *t = new Target(this, defaultKit);
t->updateDefaultBuildConfigurations();
t->updateDefaultDeployConfigurations();
t->updateDefaultRunConfigurations();
@@ -381,21 +386,17 @@ bool QbsProject::fromMap(const QVariantMap &map)
void QbsProject::generateErrors(const qbs::ErrorInfo &e)
{
foreach (const qbs::ErrorItem &item, e.items())
- taskHub()->addTask(ProjectExplorer::Task(ProjectExplorer::Task::Error,
- item.description(),
- Utils::FileName::fromString(item.codeLocation().fileName()),
- item.codeLocation().line(),
- ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM));
+ TaskHub::addTask(Task::Error, item.description(),
+ ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM,
+ FileName::fromString(item.codeLocation().fileName()),
+ item.codeLocation().line());
+
}
-void QbsProject::parse(const QVariantMap &config, const Utils::Environment &env, const QString &dir)
+void QbsProject::parse(const QVariantMap &config, const Environment &env, const QString &dir)
{
QTC_ASSERT(!dir.isNull(), return);
- // Clear buildsystem related tasks:
- ProjectExplorer::ProjectExplorerPlugin::instance()->taskHub()
- ->clearTasks(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM);
-
qbs::SetupProjectParameters params;
params.setBuildConfiguration(config);
qbs::ErrorInfo err = params.expandBuildConfiguration(m_manager->settings());
@@ -405,11 +406,11 @@ void QbsProject::parse(const QVariantMap &config, const Utils::Environment &env,
}
// Avoid useless reparsing:
- const qbs::Project *currentProject = qbsProject();
+ const qbs::Project &currentProject = qbsProject();
if (!m_forceParsing
- && currentProject
- && currentProject->projectConfiguration() == params.buildConfiguration()) {
- QHash<QString, QString> usedEnv = currentProject->usedEnvironment();
+ && currentProject.isValid()
+ && currentProject.projectConfiguration() == params.buildConfiguration()) {
+ QHash<QString, QString> usedEnv = currentProject.usedEnvironment();
bool canSkip = true;
for (QHash<QString, QString>::const_iterator i = usedEnv.constBegin();
i != usedEnv.constEnd(); ++i) {
@@ -427,9 +428,9 @@ void QbsProject::parse(const QVariantMap &config, const Utils::Environment &env,
params.setIgnoreDifferentProjectFilePath(false);
params.setEnvironment(env.toProcessEnvironment());
qbs::Preferences *prefs = QbsManager::preferences();
- const QString buildDir = qbsBuildDir();
- params.setSearchPaths(prefs->searchPaths(buildDir));
- params.setPluginPaths(prefs->pluginPaths(buildDir));
+ const QString qbsDir = qbsDirectory();
+ params.setSearchPaths(prefs->searchPaths(qbsDir));
+ params.setPluginPaths(prefs->pluginPaths(qbsDir));
// Do the parsing:
prepareForParsing();
@@ -452,20 +453,24 @@ void QbsProject::prepareForParsing()
{
m_forceParsing = false;
- taskHub()->clearTasks(ProjectExplorer::Constants::TASK_CATEGORY_COMPILE);
+ TaskHub::clearTasks(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM);
if (m_qbsUpdateFutureInterface)
m_qbsUpdateFutureInterface->reportCanceled();
delete m_qbsUpdateFutureInterface;
m_qbsUpdateFutureInterface = 0;
- delete m_qbsSetupProjectJob;
- m_qbsSetupProjectJob = 0;
+ if (m_qbsSetupProjectJob) {
+ m_qbsSetupProjectJob->disconnect(this);
+ m_qbsSetupProjectJob->cancel();
+ m_qbsSetupProjectJob->deleteLater();
+ m_qbsSetupProjectJob = 0;
+ }
m_currentProgressBase = 0;
m_qbsUpdateFutureInterface = new QFutureInterface<void>();
m_qbsUpdateFutureInterface->setProgressRange(0, 0);
- Core::ICore::progressManager()->addTask(m_qbsUpdateFutureInterface->future(), tr("Evaluating"),
- QLatin1String(Constants::QBS_EVALUATE));
+ ProgressManager::addTask(m_qbsUpdateFutureInterface->future(),
+ tr("Evaluating"), "Qbs.QbsEvaluate");
m_qbsUpdateFutureInterface->reportStarted();
}
@@ -475,26 +480,26 @@ void QbsProject::updateDocuments(const QSet<QString> &files)
QSet<QString> newFiles = files;
QTC_ASSERT(!newFiles.isEmpty(), newFiles << m_fileName);
QSet<QString> oldFiles;
- foreach (Core::IDocument *doc, m_qbsDocuments)
- oldFiles.insert(doc->fileName());
+ foreach (IDocument *doc, m_qbsDocuments)
+ oldFiles.insert(doc->filePath());
QSet<QString> filesToAdd = newFiles;
filesToAdd.subtract(oldFiles);
QSet<QString> filesToRemove = oldFiles;
filesToRemove.subtract(newFiles);
- QSet<Core::IDocument *> currentDocuments = m_qbsDocuments;
- foreach (Core::IDocument *doc, currentDocuments) {
- if (filesToRemove.contains(doc->fileName())) {
+ QSet<IDocument *> currentDocuments = m_qbsDocuments;
+ foreach (IDocument *doc, currentDocuments) {
+ if (filesToRemove.contains(doc->filePath())) {
m_qbsDocuments.remove(doc);
delete doc;
}
}
- QSet<Core::IDocument *> toAdd;
+ QSet<IDocument *> toAdd;
foreach (const QString &f, filesToAdd)
toAdd.insert(new QbsProjectFile(this, f));
- Core::DocumentManager::instance()->addDocuments(toAdd.toList());
+ DocumentManager::addDocuments(toAdd.toList());
m_qbsDocuments.unite(toAdd);
}
@@ -503,12 +508,12 @@ void QbsProject::updateCppCodeModel(const qbs::ProjectData &prj)
if (!prj.isValid())
return;
- ProjectExplorer::Kit *k = 0;
+ Kit *k = 0;
QtSupport::BaseQtVersion *qtVersion = 0;
- if (ProjectExplorer::Target *target = activeTarget())
+ if (Target *target = activeTarget())
k = target->kit();
else
- k = ProjectExplorer::KitManager::instance()->defaultKit();
+ k = KitManager::defaultKit();
qtVersion = QtSupport::QtKitInformation::qtVersion(k);
CppTools::CppModelManagerInterface *modelmanager =
@@ -528,6 +533,7 @@ void QbsProject::updateCppCodeModel(const qbs::ProjectData &prj)
qtVersionForPart = CppTools::ProjectPart::Qt5;
}
+ QHash<QString, QString> uiFiles;
QStringList allFiles;
foreach (const qbs::ProductData &prd, prj.allProducts()) {
foreach (const qbs::GroupData &grp, prd.groups()) {
@@ -557,7 +563,7 @@ void QbsProject::updateCppCodeModel(const qbs::ProjectData &prj)
QLatin1String(CONFIG_INCLUDEPATHS));
QStringList grpIncludePaths;
foreach (const QString &p, list) {
- const QString cp = Utils::FileName::fromUserInput(p).toString();
+ const QString cp = FileName::fromUserInput(p).toString();
grpIncludePaths.append(cp);
}
@@ -565,7 +571,7 @@ void QbsProject::updateCppCodeModel(const qbs::ProjectData &prj)
QLatin1String(CONFIG_FRAMEWORKPATHS));
QStringList grpFrameworkPaths;
foreach (const QString &p, list) {
- const QString cp = Utils::FileName::fromUserInput(p).toString();
+ const QString cp = FileName::fromUserInput(p).toString();
grpFrameworkPaths.append(cp);
}
@@ -573,15 +579,22 @@ void QbsProject::updateCppCodeModel(const qbs::ProjectData &prj)
QLatin1String(CONFIG_PRECOMPILEDHEADER)).toString();
CppTools::ProjectPart::Ptr part(new CppTools::ProjectPart);
- part->evaluateToolchain(ProjectExplorer::ToolChainKitInformation::toolChain(k),
+ part->evaluateToolchain(ToolChainKitInformation::toolChain(k),
cxxFlags,
cFlags,
- ProjectExplorer::SysRootKitInformation::sysRoot(k));
+ SysRootKitInformation::sysRoot(k));
CppTools::ProjectFileAdder adder(part->files);
- foreach (const QString &file, grp.allFilePaths())
+ foreach (const QString &file, grp.allFilePaths()) {
+ if (file.endsWith(QLatin1String(".ui"))) {
+ QStringList generated = m_rootProjectNode->qbsProject()
+ .generatedFiles(prd, file, QStringList(QLatin1String("hpp")));
+ if (generated.count() == 1)
+ uiFiles.insert(file, generated.at(0));
+ }
if (adder.maybeAdd(file))
allFiles.append(file);
+ }
part->files << CppTools::ProjectFile(QLatin1String(CONFIGURATION_PATH),
CppTools::ProjectFile::CXXHeader);
@@ -599,6 +612,8 @@ void QbsProject::updateCppCodeModel(const qbs::ProjectData &prj)
if (pinfo.projectParts().isEmpty())
return;
+ QtSupport::UiCodeModelManager::update(this, uiFiles);
+
// Register update the code model:
m_codeModelFuture = modelmanager->updateProjectInfo(pinfo);
}
@@ -617,13 +632,43 @@ void QbsProject::updateQmlJsCodeModel(const qbs::ProjectData &prj)
modelManager->updateProjectInfo(projectInfo);
}
-QString QbsProject::qbsBuildDir() const
+void QbsProject::updateApplicationTargets(const qbs::ProjectData &projectData)
+{
+ ProjectExplorer::BuildTargetInfoList applications;
+ foreach (const qbs::ProductData &productData, projectData.allProducts()) {
+ foreach (const qbs::TargetArtifact &ta, productData.targetArtifacts()) {
+ QTC_ASSERT(ta.isValid(), continue);
+ if (!ta.isExecutable())
+ continue;
+ applications.list << ProjectExplorer::BuildTargetInfo(Utils::FileName::fromString(ta.filePath()),
+ Utils::FileName::fromString(productData.location().fileName()));
+ }
+ }
+ activeTarget()->setApplicationTargets(applications);
+}
+
+void QbsProject::updateDeploymentInfo(const qbs::Project &project)
+{
+ ProjectExplorer::DeploymentData deploymentData;
+ if (project.isValid()) {
+ qbs::InstallOptions installOptions;
+ installOptions.setInstallRoot(QLatin1String("/"));
+ foreach (const qbs::InstallableFile &f,
+ project.installableFilesForProject(project.projectData(), installOptions)) {
+ deploymentData.addFile(f.sourceFilePath(), f.targetDirectory(), f.isExecutable()
+ ? ProjectExplorer::DeployableFile::TypeExecutable
+ : ProjectExplorer::DeployableFile::TypeNormal);
+ }
+ }
+ activeTarget()->setDeploymentData(deploymentData);
+}
+
+QString QbsProject::qbsDirectory() const
{
- QString buildDir = Utils::Environment::systemEnvironment()
- .value(QLatin1String("QBS_BUILD_DIR"));
- if (buildDir.isEmpty())
- buildDir = Core::ICore::resourcePath() + QLatin1String("/qbs");
- return buildDir;
+ const QString qbsInstallDir = QLatin1String(QBS_INSTALL_DIR);
+ if (!qbsInstallDir.isEmpty())
+ return qbsInstallDir;
+ return ICore::resourcePath() + QLatin1String("/qbs");
}
} // namespace Internal
diff --git a/src/plugins/qbsprojectmanager/qbsproject.h b/src/plugins/qbsprojectmanager/qbsproject.h
index b8f44c2f1c..1a8d9232d8 100644
--- a/src/plugins/qbsprojectmanager/qbsproject.h
+++ b/src/plugins/qbsprojectmanager/qbsproject.h
@@ -32,9 +32,6 @@
#include "qbsprojectmanager.h"
-#include <language/language.h>
-#include <tools/buildoptions.h>
-
#include <projectexplorer/project.h>
#include <projectexplorer/projectnodes.h>
#include <projectexplorer/task.h>
@@ -51,6 +48,12 @@ class CleanJob;
class Error;
class ProjectData;
class SetupProjectJob;
+class CleanOptions;
+class InstallJob;
+class InstallOptions;
+class Project;
+class ErrorInfo;
+class BuildOptions;
} // namespace qbs
namespace Core { class IDocument; }
@@ -90,8 +93,9 @@ public:
bool hasParseResult() const;
Utils::FileName defaultBuildDirectory() const;
+ static Utils::FileName defaultBuildDirectory(const QString &path);
- const qbs::Project *qbsProject() const;
+ qbs::Project qbsProject() const;
const qbs::ProjectData qbsProjectData() const;
bool needsSpecialDeployment() const;
@@ -125,7 +129,9 @@ private:
void updateDocuments(const QSet<QString> &files);
void updateCppCodeModel(const qbs::ProjectData &prj);
void updateQmlJsCodeModel(const qbs::ProjectData &prj);
- QString qbsBuildDir() const;
+ void updateApplicationTargets(const qbs::ProjectData &projectData);
+ void updateDeploymentInfo(const qbs::Project &project);
+ QString qbsDirectory() const;
QbsManager *const m_manager;
const QString m_projectName;
diff --git a/src/plugins/qbsprojectmanager/qbsprojectfile.cpp b/src/plugins/qbsprojectmanager/qbsprojectfile.cpp
index 14ea3b3e96..3bd663ffc4 100644
--- a/src/plugins/qbsprojectmanager/qbsprojectfile.cpp
+++ b/src/plugins/qbsprojectmanager/qbsprojectfile.cpp
@@ -36,9 +36,10 @@ namespace QbsProjectManager {
namespace Internal {
QbsProjectFile::QbsProjectFile(QbsProject *parent, QString fileName) : Core::IDocument(parent),
- m_project(parent),
- m_fileName(fileName)
-{ }
+ m_project(parent)
+{
+ setFilePath(fileName);
+}
QbsProjectFile::~QbsProjectFile()
{ }
@@ -48,11 +49,6 @@ bool QbsProjectFile::save(QString *, const QString &, bool)
return false;
}
-QString QbsProjectFile::fileName() const
-{
- return m_fileName;
-}
-
bool QbsProjectFile::isReadOnly() const
{
return true;
@@ -100,13 +96,6 @@ bool QbsProjectFile::reload(QString *errorString, ReloadFlag flag, ChangeType ty
return true;
}
-void QbsProjectFile::rename(const QString &newName)
-{
- // Can't happen
- Q_UNUSED(newName);
- Q_ASSERT(false);
-}
-
} // namespace Internal
} // namespace QbsProjectManager
diff --git a/src/plugins/qbsprojectmanager/qbsprojectfile.h b/src/plugins/qbsprojectmanager/qbsprojectfile.h
index bc45062b3c..6eea015168 100644
--- a/src/plugins/qbsprojectmanager/qbsprojectfile.h
+++ b/src/plugins/qbsprojectmanager/qbsprojectfile.h
@@ -46,7 +46,6 @@ public:
~QbsProjectFile();
bool save(QString *errorString, const QString &fileName, bool autoSave);
- QString fileName() const;
bool isReadOnly() const;
QString defaultPath() const;
@@ -58,11 +57,9 @@ public:
ReloadBehavior reloadBehavior(ChangeTrigger state, ChangeType type) const;
bool reload(QString *errorString, ReloadFlag flag, ChangeType type);
- void rename(const QString &newName);
private:
QbsProject *m_project;
- QString m_fileName;
};
} // namespace Internal
diff --git a/src/plugins/qbsprojectmanager/qbsprojectmanager.cpp b/src/plugins/qbsprojectmanager/qbsprojectmanager.cpp
index 57b7d5d69a..25c03da351 100644
--- a/src/plugins/qbsprojectmanager/qbsprojectmanager.cpp
+++ b/src/plugins/qbsprojectmanager/qbsprojectmanager.cpp
@@ -29,20 +29,17 @@
#include "qbsprojectmanager.h"
+#include "defaultpropertyprovider.h"
#include "qbslogsink.h"
#include "qbsproject.h"
#include "qbsprojectmanagerconstants.h"
#include "qbsprojectmanagerplugin.h"
-#include <projectexplorer/kitinformation.h>
+#include <extensionsystem/pluginmanager.h>
+#include <projectexplorer/kit.h>
#include <projectexplorer/kitmanager.h>
#include <projectexplorer/projectexplorer.h>
-#include <projectexplorer/projectexplorerconstants.h>
-#include <projectexplorer/toolchain.h>
#include <qmljstools/qmljstoolsconstants.h>
-#include <qtsupport/baseqtversion.h>
-#include <qtsupport/qtkitinformation.h>
-#include <utils/qtcassert.h>
#include <QVariantMap>
@@ -52,28 +49,6 @@
const char PROFILE_LIST[] = "preferences.qtcreator.kit.";
const char PROFILES_PREFIX[] = "profiles.";
-// Qt related settings:
-const char QTCORE_BINPATH[] = ".Qt.core.binPath";
-const char QTCORE_BUILDVARIANT[] = ".Qt.core.buildVariant";
-const char QTCORE_DOCPATH[] = ".Qt.core.docPath";
-const char QTCORE_INCPATH[] = ".Qt.core.incPath";
-const char QTCORE_LIBPATH[] = ".Qt.core.libPath";
-const char QTCORE_VERSION[] = ".Qt.core.version";
-const char QTCORE_NAMESPACE[] = ".Qt.core.namespace";
-const char QTCORE_LIBINFIX[] = ".Qt.core.libInfix";
-const char QTCORE_MKSPEC[] = ".Qt.core.mkspecPath";
-const char QTCORE_FRAMEWORKBUILD[] = ".Qt.core.frameworkBuild";
-
-
-// Toolchain related settings:
-const char QBS_TARGETOS[] = ".qbs.targetOS";
-const char QBS_SYSROOT[] = ".qbs.sysroot";
-const char QBS_ARCHITECTURE[] = ".qbs.architecture";
-const char QBS_ENDIANNESS[] = ".qbs.endianness";
-const char QBS_TOOLCHAIN[] = ".qbs.toolchain";
-const char CPP_TOOLCHAINPATH[] = ".cpp.toolchainInstallPath";
-const char CPP_COMPILERNAME[] = ".cpp.compilerName";
-
const QChar sep = QChar(QLatin1Char('.'));
namespace QbsProjectManager {
@@ -82,7 +57,8 @@ qbs::Settings *QbsManager::m_settings = 0;
qbs::Preferences *QbsManager::m_preferences = 0;
QbsManager::QbsManager(Internal::QbsProjectManagerPlugin *plugin) :
- m_plugin(plugin)
+ m_plugin(plugin),
+ m_defaultPropertyProvider(new DefaultPropertyProvider)
{
if (!m_settings)
m_settings = new qbs::Settings(QLatin1String("QtProject"), QLatin1String("qbs"));
@@ -111,6 +87,7 @@ QbsManager::QbsManager(Internal::QbsProjectManagerPlugin *plugin) :
QbsManager::~QbsManager()
{
+ delete m_defaultPropertyProvider;
delete m_settings;
}
@@ -172,7 +149,7 @@ qbs::Preferences *QbsManager::preferences()
void QbsManager::addProfile(const QString &name, const QVariantMap &data)
{
- const QString base = QLatin1String(PROFILES_PREFIX) + name;
+ const QString base = QLatin1String(PROFILES_PREFIX) + name + sep;
const QVariantMap::ConstIterator cend = data.constEnd();
for (QVariantMap::ConstIterator it = data.constBegin(); it != cend; ++it)
m_settings->setValue(base + it.key(), it.value());
@@ -209,79 +186,14 @@ void QbsManager::addProfileFromKit(const ProjectExplorer::Kit *k)
QString::fromLatin1("qtc_") + k->fileSystemFriendlyName(), usedProfileNames);
setProfileForKit(name, k);
- QVariantMap data;
- QtSupport::BaseQtVersion *qt = QtSupport::QtKitInformation::qtVersion(k);
- if (qt) {
- data.insert(QLatin1String(QTCORE_BINPATH), qt->binPath().toUserOutput());
- QStringList builds;
- if (qt->hasDebugBuild())
- builds << QLatin1String("debug");
- if (qt->hasReleaseBuild())
- builds << QLatin1String("release");
- data.insert(QLatin1String(QTCORE_BUILDVARIANT), builds);
- data.insert(QLatin1String(QTCORE_DOCPATH), qt->docsPath().toUserOutput());
- data.insert(QLatin1String(QTCORE_INCPATH), qt->headerPath().toUserOutput());
- data.insert(QLatin1String(QTCORE_LIBPATH), qt->libraryPath().toUserOutput());
- Utils::FileName mkspecPath = qt->mkspecsPath();
- mkspecPath.appendPath(qt->mkspec().toString());
- data.insert(QLatin1String(QTCORE_MKSPEC), mkspecPath.toUserOutput());
- data.insert(QLatin1String(QTCORE_NAMESPACE), qt->qtNamespace());
- data.insert(QLatin1String(QTCORE_LIBINFIX), qt->qtLibInfix());
- data.insert(QLatin1String(QTCORE_VERSION), qt->qtVersionString());
- if (qt->isFrameworkBuild())
- data.insert(QLatin1String(QTCORE_FRAMEWORKBUILD), true);
+ // set up properties:
+ QVariantMap data = m_defaultPropertyProvider->properties(k, QVariantMap());
+ QList<PropertyProvider *> providerList = ExtensionSystem::PluginManager::getObjects<PropertyProvider>();
+ foreach (PropertyProvider *provider, providerList) {
+ if (provider->canHandle(k))
+ data = provider->properties(k, data);
}
- if (ProjectExplorer::SysRootKitInformation::hasSysRoot(k))
- data.insert(QLatin1String(QBS_SYSROOT), ProjectExplorer::SysRootKitInformation::sysRoot(k).toUserOutput());
-
- ProjectExplorer::ToolChain *tc = ProjectExplorer::ToolChainKitInformation::toolChain(k);
- if (tc) {
- // FIXME/CLARIFY: How to pass the sysroot?
- ProjectExplorer::Abi targetAbi = tc->targetAbi();
- QString architecture = ProjectExplorer::Abi::toString(targetAbi.architecture());
- if (targetAbi.wordWidth() == 64)
- architecture.append(QLatin1String("_64"));
- data.insert(QLatin1String(QBS_ARCHITECTURE), architecture);
-
- if (targetAbi.endianness() == ProjectExplorer::Abi::BigEndian)
- data.insert(QLatin1String(QBS_ENDIANNESS), QLatin1String("big"));
- else
- data.insert(QLatin1String(QBS_ENDIANNESS), QLatin1String("little"));
-
- if (targetAbi.os() == ProjectExplorer::Abi::WindowsOS) {
- data.insert(QLatin1String(QBS_TARGETOS), QLatin1String("windows"));
- data.insert(QLatin1String(QBS_TOOLCHAIN),
- targetAbi.osFlavor() == ProjectExplorer::Abi::WindowsMSysFlavor
- ? QStringList() << QLatin1String("mingw") << QLatin1String("gcc")
- : QStringList() << QLatin1String("msvc"));
- } else if (targetAbi.os() == ProjectExplorer::Abi::MacOS) {
- data.insert(QLatin1String(QBS_TARGETOS), QStringList() << QLatin1String("osx")
- << QLatin1String("darwin") << QLatin1String("unix"));
- if (tc->type() != QLatin1String("clang")) {
- data.insert(QLatin1String(QBS_TOOLCHAIN), QLatin1String("gcc"));
- } else {
- data.insert(QLatin1String(QBS_TOOLCHAIN),
- QStringList() << QLatin1String("clang")
- << QLatin1String("llvm")
- << QLatin1String("gcc"));
- }
- } else if (targetAbi.os() == ProjectExplorer::Abi::LinuxOS) {
- data.insert(QLatin1String(QBS_TARGETOS), QStringList() << QLatin1String("linux")
- << QLatin1String("unix"));
- if (tc->type() != QLatin1String("clang")) {
- data.insert(QLatin1String(QBS_TOOLCHAIN), QLatin1String("gcc"));
- } else {
- data.insert(QLatin1String(QBS_TOOLCHAIN),
- QStringList() << QLatin1String("clang")
- << QLatin1String("llvm")
- << QLatin1String("gcc"));
- }
- }
- Utils::FileName cxx = tc->compilerCommand();
- data.insert(QLatin1String(CPP_TOOLCHAINPATH), cxx.toFileInfo().absolutePath());
- data.insert(QLatin1String(CPP_COMPILERNAME), cxx.toFileInfo().fileName());
- }
addProfile(name, data);
}
@@ -291,7 +203,7 @@ void QbsManager::pushKitsToQbs()
removeCreatorProfiles();
// add definitions from our kits
- foreach (const ProjectExplorer::Kit *k, ProjectExplorer::KitManager::instance()->kits())
+ foreach (const ProjectExplorer::Kit *k, ProjectExplorer::KitManager::kits())
addProfileFromKit(k);
}
diff --git a/src/plugins/qbsprojectmanager/qbsprojectmanager.h b/src/plugins/qbsprojectmanager/qbsprojectmanager.h
index 5ad0103338..ccb42c8cbb 100644
--- a/src/plugins/qbsprojectmanager/qbsprojectmanager.h
+++ b/src/plugins/qbsprojectmanager/qbsprojectmanager.h
@@ -34,9 +34,13 @@
#include <projectexplorer/iprojectmanager.h>
-#include <qbs.h>
+namespace qbs {
+class Settings;
+class Preferences;
+} // namespace qbs
#include <QString>
+#include <QVariantMap>
namespace ProjectExplorer {
class Kit;
@@ -52,6 +56,8 @@ class QbsProject;
class QbsProjectManagerPlugin;
} // namespace Internal
+class DefaultPropertyProvider;
+
class QbsManager : public ProjectExplorer::IProjectManager
{
Q_OBJECT
@@ -76,7 +82,6 @@ private slots:
void pushKitsToQbs();
private:
-
void addProfile(const QString &name, const QVariantMap &data);
void removeCreatorProfiles();
void addProfileFromKit(const ProjectExplorer::Kit *k);
@@ -85,6 +90,8 @@ private:
Internal::QbsLogSink *m_logSink;
static qbs::Settings *m_settings;
static qbs::Preferences *m_preferences;
+
+ DefaultPropertyProvider *m_defaultPropertyProvider;
};
} // namespace QbsProjectManager
diff --git a/src/plugins/qbsprojectmanager/qbsprojectmanager.pro b/src/plugins/qbsprojectmanager/qbsprojectmanager.pro
index 0ee60584b0..8f8319e037 100644
--- a/src/plugins/qbsprojectmanager/qbsprojectmanager.pro
+++ b/src/plugins/qbsprojectmanager/qbsprojectmanager.pro
@@ -1,21 +1,26 @@
include(../../qtcreatorplugin.pri)
-# Look for qbs in the environment (again)
-QBS_SOURCE_DIR = $$PWD/../../shared/qbs
-QBS_BUILD_DIR = $$IDE_BUILD_TREE/src/shared/qbs
+# Look for qbs in the environment
+isEmpty(QBS_INSTALL_DIR): QBS_INSTALL_DIR = $$(QBS_INSTALL_DIR)
+isEmpty(QBS_INSTALL_DIR) {
+ QBS_SOURCE_DIR = $$PWD/../../shared/qbs
+ include($$QBS_SOURCE_DIR/src/lib/use.pri)
+ macx:QMAKE_LFLAGS += -Wl,-rpath,@loader_path/../ # Mac: fix rpath for qbscore soname
+} else {
+ include($${QBS_INSTALL_DIR}/include/qbs/use_installed.pri)
+}
+QBS_INSTALL_DIR_FWD_SLASHES = $$replace(QBS_INSTALL_DIR, \\\\, /)
+DEFINES += QBS_INSTALL_DIR=\\\"$$QBS_INSTALL_DIR_FWD_SLASHES\\\"
-include($$QBS_SOURCE_DIR/src/lib/use.pri)
-# Mac: fix rpath for qbscore soname
-macx:QMAKE_LFLAGS += -Wl,-rpath,@loader_path/../
-
-QBS_BUILD_DIR_FWD_SLASHES = $$replace(QBS_BUILD_DIR, \\\\, /)
-DEFINES += QBS_BUILD_DIR=\\\"$$QBS_BUILD_DIR_FWD_SLASHES\\\"
DEFINES += \
QBSPROJECTMANAGER_LIBRARY
HEADERS = \
+ defaultpropertyprovider.h \
+ propertyprovider.h \
qbsbuildconfiguration.h \
qbsbuildconfigurationwidget.h \
+ qbsbuildinfo.h \
qbsbuildstep.h \
qbscleanstep.h \
qbsdeployconfigurationfactory.h \
@@ -31,9 +36,11 @@ HEADERS = \
qbsprojectmanagerplugin.h \
qbspropertylineedit.h \
qbsrunconfiguration.h \
- qbsstep.h
+ qbsstep.h \
+ qbsconstants.h
SOURCES = \
+ defaultpropertyprovider.cpp \
qbsbuildconfiguration.cpp \
qbsbuildconfigurationwidget.cpp \
qbsbuildstep.cpp \
diff --git a/src/plugins/qbsprojectmanager/qbsprojectmanager.qbs b/src/plugins/qbsprojectmanager/qbsprojectmanager.qbs
index 654a72ada6..ad64844f78 100644
--- a/src/plugins/qbsprojectmanager/qbsprojectmanager.qbs
+++ b/src/plugins/qbsprojectmanager/qbsprojectmanager.qbs
@@ -1,15 +1,17 @@
import qbs.base 1.0
+import qbs.FileInfo
import "../QtcPlugin.qbs" as QtcPlugin
QtcPlugin {
name: "QbsProjectManager"
- property var externalQbsDefines: project.useExternalQbs
- ? ['QBS_BUILD_DIR="' + project.qbs_build_dir +'"'] : []
- property var externalQbsIncludes: project.useExternalQbs ? [project.qbs_source_dir + "/src/lib"] : []
- property var externalQbsLibraryPaths: project.useExternalQbs ? [project.qbs_build_dir + "/lib"] : []
- property var externalQbsRPaths: project.useExternalQbs ? [project.qbs_build_dir + "/lib"] : []
+ property var externalQbsIncludes: project.useExternalQbs
+ ? [project.qbs_install_dir + "/include/qbs"] : []
+ property var externalQbsLibraryPaths: project.useExternalQbs
+ ? [project.qbs_install_dir + "/lib"] : []
+ property var externalQbsRPaths: project.useExternalQbs
+ ? [project.qbs_install_dir + "/lib"] : []
property var externalQbsDynamicLibraries: {
var libs = []
if (!project.useExternalQbs)
@@ -26,7 +28,7 @@ QtcPlugin {
return libs
}
- condition: project.useExternalQbs || project.qbsSubModuleExists
+ condition: project.buildQbsProjectManager
Depends { name: "Qt"; submodules: [ "widgets", "script" ] }
Depends { name: "ProjectExplorer" }
@@ -42,18 +44,27 @@ QtcPlugin {
}
cpp.defines: base.concat([
- 'QML_BUILD_STATIC_LIB'
- ]).concat(externalQbsDefines)
+ 'QML_BUILD_STATIC_LIB',
+ 'QBS_INSTALL_DIR="'
+ + (project.useExternalQbs
+ ? FileInfo.fromWindowsSeparators(project.qbs_install_dir)
+ : '')
+ + '"'
+ ])
cpp.includePaths: base.concat(externalQbsIncludes)
cpp.libraryPaths: base.concat(externalQbsLibraryPaths)
cpp.rpaths: base.concat(externalQbsRPaths)
cpp.dynamicLibraries: base.concat(externalQbsDynamicLibraries)
files: [
+ "defaultpropertyprovider.cpp",
+ "defaultpropertyprovider.h",
+ "propertyprovider.h",
"qbsbuildconfiguration.cpp",
"qbsbuildconfiguration.h",
"qbsbuildconfigurationwidget.cpp",
"qbsbuildconfigurationwidget.h",
+ "qbsbuildinfo.h",
"qbsbuildstep.cpp",
"qbsbuildstep.h",
"qbsbuildstepconfigwidget.ui",
diff --git a/src/plugins/qbsprojectmanager/qbsprojectmanagerconstants.h b/src/plugins/qbsprojectmanager/qbsprojectmanagerconstants.h
index e59a0ede8c..2566214522 100644
--- a/src/plugins/qbsprojectmanager/qbsprojectmanagerconstants.h
+++ b/src/plugins/qbsprojectmanager/qbsprojectmanagerconstants.h
@@ -39,10 +39,7 @@ namespace Constants {
const char PROJECT_ID[] = "Qbs.QbsProject";
// MIME types:
-const char MIME_TYPE[] = "application/vnd.qtproject.qbsproject";
-
-// Progress reports:
-const char QBS_EVALUATE[] = "Qbs.QbsEvaluate";
+const char MIME_TYPE[] = "application/x-qt.qbs+qml";
// Actions:
const char ACTION_REPARSE_QBS[] = "Qbs.Reparse";
diff --git a/src/plugins/qbsprojectmanager/qbsprojectmanagerplugin.cpp b/src/plugins/qbsprojectmanager/qbsprojectmanagerplugin.cpp
index de5b91b028..f02597b715 100644
--- a/src/plugins/qbsprojectmanager/qbsprojectmanagerplugin.cpp
+++ b/src/plugins/qbsprojectmanager/qbsprojectmanagerplugin.cpp
@@ -45,9 +45,9 @@
#include <coreplugin/coreconstants.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/editormanager/ieditor.h>
+#include <coreplugin/featureprovider.h>
#include <coreplugin/icore.h>
#include <coreplugin/fileiconprovider.h>
-#include <coreplugin/mimedatabase.h>
#include <projectexplorer/buildmanager.h>
#include <projectexplorer/project.h>
#include <projectexplorer/projectexplorer.h>
@@ -60,9 +60,22 @@
#include <QAction>
#include <QtPlugin>
+using namespace ProjectExplorer;
+
namespace QbsProjectManager {
namespace Internal {
+class QbsFeatureProvider : public Core::IFeatureProvider
+{
+ Core::FeatureSet availableFeatures(const QString & /* platform */) const {
+ return Core::FeatureSet("Qbs.QbsSupport");
+ }
+
+ QStringList availablePlatforms() const { return QStringList(); }
+ QString displayNameForPlatform(const QString & /* platform */) const { return QString(); }
+};
+
+
QbsProjectManagerPlugin::QbsProjectManagerPlugin() :
m_manager(0),
m_projectExplorer(0),
@@ -73,17 +86,15 @@ QbsProjectManagerPlugin::QbsProjectManagerPlugin() :
bool QbsProjectManagerPlugin::initialize(const QStringList &arguments, QString *errorMessage)
{
+ Q_UNUSED(arguments);
Q_UNUSED(errorMessage);
+
m_manager = new QbsManager(this);
m_projectExplorer = ProjectExplorer::ProjectExplorerPlugin::instance();
const Core::Context projectContext(::QbsProjectManager::Constants::PROJECT_ID);
const Core::Context globalcontext(Core::Constants::C_GLOBAL);
- Q_UNUSED(arguments);
-
- Core::FileIconProvider::instance()
- ->registerIconOverlayForSuffix(QIcon(QLatin1String(QtSupport::Constants::ICON_QT_PROJECT)),
- QLatin1String("qbs"));
+ Core::FileIconProvider::registerIconOverlayForSuffix(QtSupport::Constants::ICON_QT_PROJECT, "qbs");
//create and register objects
addAutoReleasedObject(m_manager);
@@ -93,6 +104,7 @@ bool QbsProjectManagerPlugin::initialize(const QStringList &arguments, QString *
addAutoReleasedObject(new QbsInstallStepFactory);
addAutoReleasedObject(new QbsDeployConfigurationFactory);
addAutoReleasedObject(new QbsRunConfigurationFactory);
+ addAutoReleasedObject(new QbsFeatureProvider);
//menus
// Build Menu:
@@ -158,7 +170,7 @@ bool QbsProjectManagerPlugin::initialize(const QStringList &arguments, QString *
connect(m_projectExplorer, SIGNAL(currentNodeChanged(ProjectExplorer::Node*,ProjectExplorer::Project*)),
this, SLOT(updateContextActions(ProjectExplorer::Node*,ProjectExplorer::Project*)));
- connect(m_projectExplorer->buildManager(), SIGNAL(buildStateChanged(ProjectExplorer::Project*)),
+ connect(BuildManager::instance(), SIGNAL(buildStateChanged(ProjectExplorer::Project*)),
this, SLOT(buildStateChanged(ProjectExplorer::Project*)));
connect(Core::EditorManager::instance(), SIGNAL(currentEditorChanged(Core::IEditor*)),
@@ -199,7 +211,7 @@ void QbsProjectManagerPlugin::updateContextActions(ProjectExplorer::Node *node,
activeTargetChanged();
- bool isBuilding = m_projectExplorer->buildManager()->isBuilding(project);
+ bool isBuilding = BuildManager::isBuilding(project);
bool isFile = m_currentProject && node && (node->nodeType() == ProjectExplorer::FileNodeType);
bool isProduct = m_currentProject && node && qobject_cast<QbsProductNode *>(node->projectNode());
bool isFileEnabled = isFile && node->isEnabled();
@@ -212,7 +224,7 @@ void QbsProjectManagerPlugin::updateContextActions(ProjectExplorer::Node *node,
void QbsProjectManagerPlugin::updateReparseQbsAction()
{
m_reparseQbs->setEnabled(m_currentProject
- && !m_projectExplorer->buildManager()->isBuilding(m_currentProject)
+ && !BuildManager::isBuilding(m_currentProject)
&& !m_currentProject->isParsing());
}
@@ -225,16 +237,14 @@ void QbsProjectManagerPlugin::updateBuildActions()
QString file;
- if (Core::IEditor *currentEditor = Core::EditorManager::currentEditor()) {
- file = currentEditor->document()->fileName();
- ProjectExplorer::SessionManager *session = m_projectExplorer->session();
- ProjectExplorer::Node *node = session->nodeForFile(file);
- ProjectExplorer::Project *project
- = qobject_cast<QbsProject *>(session->projectForFile(file));
+ if (Core::IDocument *currentDocument= Core::EditorManager::currentDocument()) {
+ file = currentDocument->filePath();
+ Node *node = SessionManager::nodeForFile(file);
+ Project *project = qobject_cast<QbsProject *>(SessionManager::projectForFile(file));
m_buildFile->setParameter(QFileInfo(file).fileName());
fileVisible = project && node && qobject_cast<QbsBaseProjectNode *>(node->projectNode());
- fileEnabled = !m_projectExplorer->buildManager()->isBuilding(project)
+ fileEnabled = !BuildManager::isBuilding(project)
&& m_currentProject && !m_currentProject->isParsing();
if (QbsProductNode *productNode
@@ -289,22 +299,22 @@ void QbsProjectManagerPlugin::buildFileContextMenu()
QTC_ASSERT(m_currentNode, return);
QTC_ASSERT(m_currentProject, return);
- buildFiles(m_currentProject, QStringList(m_currentNode->path()));
+ buildSingleFile(m_currentProject, m_currentNode->path());
}
void QbsProjectManagerPlugin::buildFile()
{
QString file;
QbsProject *project = 0;
- if (Core::IEditor *currentEditor = Core::EditorManager::currentEditor()) {
- file = currentEditor->document()->fileName();
- project = qobject_cast<QbsProject *>(m_projectExplorer->session()->projectForFile(file));
+ if (Core::IDocument *currentDocument= Core::EditorManager::currentDocument()) {
+ file = currentDocument->filePath();
+ project = qobject_cast<QbsProject *>(SessionManager::projectForFile(file));
}
if (!project || file.isEmpty())
return;
- buildFiles(project, QStringList(file));
+ buildSingleFile(project, file);
}
void QbsProjectManagerPlugin::buildProductContextMenu()
@@ -319,12 +329,11 @@ void QbsProjectManagerPlugin::buildProduct()
{
QbsProject *project = 0;
QbsProductNode *product = 0;
- if (Core::IEditor *currentEditor = Core::EditorManager::currentEditor()) {
- const QString file = currentEditor->document()->fileName();
- ProjectExplorer::SessionManager *session = m_projectExplorer->session();
+ if (Core::IDocument *currentDocument= Core::EditorManager::currentDocument()) {
+ const QString file = currentDocument->filePath();
- project = qobject_cast<QbsProject *>(session->projectForFile(file));
- product = qobject_cast<QbsProductNode *>(session->nodeForFile(file)->projectNode());
+ project = qobject_cast<QbsProject *>(SessionManager::projectForFile(file));
+ product = qobject_cast<QbsProductNode *>(SessionManager::nodeForFile(file)->projectNode());
}
if (!project || !product)
@@ -333,7 +342,8 @@ void QbsProjectManagerPlugin::buildProduct()
buildProducts(project, QStringList(product->displayName()));
}
-void QbsProjectManagerPlugin::buildFiles(QbsProject *project, const QStringList &files)
+void QbsProjectManagerPlugin::buildFiles(QbsProject *project, const QStringList &files,
+ const QStringList &activeFileTags)
{
QTC_ASSERT(project, return);
QTC_ASSERT(!files.isEmpty(), return);
@@ -345,21 +355,27 @@ void QbsProjectManagerPlugin::buildFiles(QbsProject *project, const QStringList
if (!bc)
return;
- ProjectExplorer::ProjectExplorerPlugin *pe = ProjectExplorer::ProjectExplorerPlugin::instance();
- if (!pe->saveModifiedFiles())
+ if (!ProjectExplorerPlugin::instance()->saveModifiedFiles())
return;
bc->setChangedFiles(files);
+ bc->setActiveFileTags(activeFileTags);
bc->setProducts(QStringList());
- const Core::Id buildStep = Core::Id(ProjectExplorer::Constants::BUILDSTEPS_BUILD);
+ const Core::Id buildStep = ProjectExplorer::Constants::BUILDSTEPS_BUILD;
const QString name = ProjectExplorer::ProjectExplorerPlugin::displayNameForStepId(buildStep);
- pe->buildManager()->buildList(bc->stepList(buildStep), name);
+ BuildManager::buildList(bc->stepList(buildStep), name);
bc->setChangedFiles(QStringList());
}
+void QbsProjectManagerPlugin::buildSingleFile(QbsProject *project, const QString &file)
+{
+ buildFiles(project, QStringList(file), QStringList()
+ << QLatin1String("obj") << QLatin1String("hpp"));
+}
+
void QbsProjectManagerPlugin::buildProducts(QbsProject *project, const QStringList &products)
{
QTC_ASSERT(project, return);
@@ -372,17 +388,16 @@ void QbsProjectManagerPlugin::buildProducts(QbsProject *project, const QStringLi
if (!bc)
return;
- ProjectExplorer::ProjectExplorerPlugin *pe = ProjectExplorer::ProjectExplorerPlugin::instance();
- if (!pe->saveModifiedFiles())
+ if (!ProjectExplorerPlugin::instance()->saveModifiedFiles())
return;
bc->setChangedFiles(QStringList());
bc->setProducts(products);
- const Core::Id buildStep = Core::Id(ProjectExplorer::Constants::BUILDSTEPS_BUILD);
+ const Core::Id buildStep = ProjectExplorer::Constants::BUILDSTEPS_BUILD;
- const QString name = ProjectExplorer::ProjectExplorerPlugin::displayNameForStepId(buildStep);
- pe->buildManager()->buildList(bc->stepList(buildStep), name);
+ const QString name = ProjectExplorerPlugin::displayNameForStepId(buildStep);
+ BuildManager::buildList(bc->stepList(buildStep), name);
bc->setProducts(QStringList());
}
diff --git a/src/plugins/qbsprojectmanager/qbsprojectmanagerplugin.h b/src/plugins/qbsprojectmanager/qbsprojectmanagerplugin.h
index 9951f30a2f..807b29b5d4 100644
--- a/src/plugins/qbsprojectmanager/qbsprojectmanagerplugin.h
+++ b/src/plugins/qbsprojectmanager/qbsprojectmanagerplugin.h
@@ -80,7 +80,9 @@ private slots:
void reparseCurrentProject();
private:
- void buildFiles(QbsProject *project, const QStringList &files);
+ void buildFiles(QbsProject *project, const QStringList &files,
+ const QStringList &activeFileTags);
+ void buildSingleFile(QbsProject *project, const QString &file);
void buildProducts(QbsProject *project, const QStringList &products);
QbsManager *m_manager;
diff --git a/src/plugins/qbsprojectmanager/qbsrunconfiguration.cpp b/src/plugins/qbsprojectmanager/qbsrunconfiguration.cpp
index f0196aaedb..2a63ac88ec 100644
--- a/src/plugins/qbsprojectmanager/qbsrunconfiguration.cpp
+++ b/src/plugins/qbsprojectmanager/qbsrunconfiguration.cpp
@@ -196,22 +196,31 @@ QString QbsRunConfiguration::executable() const
QbsProject *pro = static_cast<QbsProject *>(target()->project());
const qbs::ProductData product = findProduct(pro->qbsProjectData(), m_qbsProduct);
- if (!product.isValid() || !pro->qbsProject())
+ if (!product.isValid() || !pro->qbsProject().isValid())
return QString();
- return pro->qbsProject()->targetExecutable(product, installOptions());
+ return pro->qbsProject().targetExecutable(product, installOptions());
}
ProjectExplorer::LocalApplicationRunConfiguration::RunMode QbsRunConfiguration::runMode() const
{
- if (m_forcedGuiMode)
+ if (forcedGuiMode())
return LocalApplicationRunConfiguration::Gui;
+
return m_runMode;
}
bool QbsRunConfiguration::forcedGuiMode() const
{
- return m_forcedGuiMode;
+ QbsProject *pro = static_cast<QbsProject *>(target()->project());
+ const qbs::ProductData product = findProduct(pro->qbsProjectData(), m_qbsProduct);
+ foreach (const qbs::TargetArtifact &ta, product.targetArtifacts()) {
+ if (ta.isExecutable())
+ return !ta.properties().getProperty(QLatin1String("consoleApplication")).toBool();
+ }
+
+ QTC_ASSERT(false, qDebug("No executable target in product '%s'", qPrintable(product.name())));
+ return false;
}
QString QbsRunConfiguration::workingDirectory() const
@@ -559,11 +568,11 @@ QList<Core::Id> QbsRunConfigurationFactory::availableCreationIds(ProjectExplorer
return result;
QbsProject *project = static_cast<QbsProject *>(parent->project());
- if (!project || !project->qbsProject())
+ if (!project || !project->qbsProject().isValid())
return result;
foreach (const qbs::ProductData &product, project->qbsProjectData().allProducts()) {
- if (!project->qbsProject()->targetExecutable(product, qbs::InstallOptions()).isEmpty())
+ if (!project->qbsProject().targetExecutable(product, qbs::InstallOptions()).isEmpty())
result << Core::Id::fromString(QString::fromLatin1(QBS_RC_PREFIX) + product.name());
}
return result;
diff --git a/src/plugins/qbsprojectmanager/qbsrunconfiguration.h b/src/plugins/qbsprojectmanager/qbsrunconfiguration.h
index 5f7afeec43..469c6089cf 100644
--- a/src/plugins/qbsprojectmanager/qbsrunconfiguration.h
+++ b/src/plugins/qbsprojectmanager/qbsrunconfiguration.h
@@ -128,7 +128,6 @@ private:
// Cached startup sub project information
ProjectExplorer::LocalApplicationRunConfiguration::RunMode m_runMode;
- bool m_forcedGuiMode;
bool m_userSetName;
QString m_userWorkingDirectory;
diff --git a/src/plugins/qmldesigner/QmlDesigner.pluginspec.in b/src/plugins/qmldesigner/QmlDesigner.pluginspec.in
index 693fd5f814..0ff37672d2 100644
--- a/src/plugins/qmldesigner/QmlDesigner.pluginspec.in
+++ b/src/plugins/qmldesigner/QmlDesigner.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"QmlDesigner\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"QmlDesigner\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
@@ -20,4 +20,7 @@ will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.</license>
<description>Visual Designer for QML files.</description>
<url>http://www.qt-project.org</url>
$$dependencyList
+ <argumentList>
+ <argument name=\"-capture-puppet-stream\" parameter=\"capture file\">Captures the Qml Puppet stream</argument>
+ </argumentList>
</plugin>
diff --git a/src/plugins/qmldesigner/components/componentcore/componentcore.pri b/src/plugins/qmldesigner/components/componentcore/componentcore.pri
index 2ef8b0911c..725b92415a 100644
--- a/src/plugins/qmldesigner/components/componentcore/componentcore.pri
+++ b/src/plugins/qmldesigner/components/componentcore/componentcore.pri
@@ -1,13 +1,16 @@
VPATH += $$PWD
SOURCES += modelnodecontextmenu.cpp
+SOURCES += designeractionmanagerview.cpp
SOURCES += defaultdesigneraction.cpp
SOURCES += modelnodecontextmenu_helper.cpp
SOURCES += selectioncontext.cpp
SOURCES += designeractionmanager.cpp
SOURCES += modelnodeoperations.cpp
+SOURCES += crumblebar.cpp
HEADERS += modelnodecontextmenu.h
+HEADERS += designeractionmanagerview.h
HEADERS += defaultdesigneraction.h
HEADERS += modelnodecontextmenu_helper.h
HEADERS += selectioncontext.h
@@ -15,3 +18,4 @@ HEADERS += componentcore_constants.h
HEADERS += designeractionmanager.h
HEADERS += modelnodeoperations.h
HEADERS += abstractdesigneraction.h
+HEADERS += crumblebar.h
diff --git a/src/plugins/qmldesigner/components/formeditor/formeditorcrumblebar.cpp b/src/plugins/qmldesigner/components/componentcore/crumblebar.cpp
index d9e22c9bb9..47cbdcdf40 100644
--- a/src/plugins/qmldesigner/components/formeditor/formeditorcrumblebar.cpp
+++ b/src/plugins/qmldesigner/components/componentcore/crumblebar.cpp
@@ -27,16 +27,48 @@
**
****************************************************************************/
-#include "formeditorcrumblebar.h"
+#include "crumblebar.h"
#include "qmldesignerplugin.h"
+#include <nodeabstractproperty.h>
+
#include <QVariant>
#include <QtDebug>
namespace QmlDesigner {
-FormEditorCrumbleBar::FormEditorCrumbleBar(QObject *parent) :
+static DesignDocument *currentDesignDocument()
+{
+ return QmlDesignerPlugin::instance()->documentManager().currentDesignDocument();
+}
+
+static inline QString componentIdForModelNode(const ModelNode &modelNode)
+{
+ if (modelNode.id().isEmpty()) {
+ if (modelNode.hasParentProperty()
+ && modelNode.parentProperty().name() != "data"
+ && modelNode.parentProperty().name() != "children") {
+ return modelNode.parentProperty().name();
+ } else {
+ return modelNode.simplifiedTypeName();
+ }
+ } else {
+ return modelNode.id();
+ }
+}
+
+static CrumbleBarInfo createCrumbleBarInfoFromModelNode(const ModelNode &modelNode)
+{
+ CrumbleBarInfo crumbleBarInfo;
+ crumbleBarInfo.componentId = componentIdForModelNode(modelNode);
+ crumbleBarInfo.fileName = currentDesignDocument()->textEditor()->document()->filePath();
+ crumbleBarInfo.modelNode = modelNode;
+
+ return crumbleBarInfo;
+}
+
+CrumbleBar::CrumbleBar(QObject *parent) :
QObject(parent),
m_isInternalCalled(false),
m_crumblePath(new Utils::CrumblePath)
@@ -45,9 +77,11 @@ FormEditorCrumbleBar::FormEditorCrumbleBar(QObject *parent) :
SIGNAL(elementClicked(QVariant)),
this,
SLOT(onCrumblePathElementClicked(QVariant)));
+
+ updateVisibility();
}
-void FormEditorCrumbleBar::pushFile(const QString &fileName)
+void CrumbleBar::pushFile(const QString &fileName)
{
if (m_isInternalCalled == false) {
crumblePath()->clear();
@@ -65,40 +99,37 @@ void FormEditorCrumbleBar::pushFile(const QString &fileName)
crumblePath()->pushElement(fileName.split("/").last(), QVariant::fromValue(crumbleBarInfo));
m_isInternalCalled = false;
-}
-static DesignDocument *currentDesignDocument()
-{
- return QmlDesignerPlugin::instance()->documentManager().currentDesignDocument();
+ updateVisibility();
}
-void FormEditorCrumbleBar::pushInFileComponent(const QString &componentId)
+void CrumbleBar::pushInFileComponent(const ModelNode &modelNode)
{
- CrumbleBarInfo crumbleBarInfo;
- crumbleBarInfo.componentId = componentId;
- crumbleBarInfo.fileName = currentDesignDocument()->textEditor()->document()->fileName();
+ CrumbleBarInfo crumbleBarInfo = createCrumbleBarInfoFromModelNode(modelNode);
CrumbleBarInfo lastElementCrumbleBarInfo = crumblePath()->dataForLastIndex().value<CrumbleBarInfo>();
if (!lastElementCrumbleBarInfo.componentId.isEmpty())
crumblePath()->popElement();
- crumblePath()->pushElement(componentId, QVariant::fromValue(crumbleBarInfo));
+ crumblePath()->pushElement(crumbleBarInfo.componentId, QVariant::fromValue(crumbleBarInfo));
m_isInternalCalled = false;
+
+ updateVisibility();
}
-void FormEditorCrumbleBar::nextFileIsCalledInternally()
+void CrumbleBar::nextFileIsCalledInternally()
{
m_isInternalCalled = true;
}
-Utils::CrumblePath *FormEditorCrumbleBar::crumblePath()
+Utils::CrumblePath *CrumbleBar::crumblePath()
{
return m_crumblePath;
}
-void FormEditorCrumbleBar::onCrumblePathElementClicked(const QVariant &data)
+void CrumbleBar::onCrumblePathElementClicked(const QVariant &data)
{
CrumbleBarInfo clickedCrumbleBarInfo = data.value<CrumbleBarInfo>();
@@ -111,7 +142,6 @@ void FormEditorCrumbleBar::onCrumblePathElementClicked(const QVariant &data)
if (!crumblePath()->dataForLastIndex().value<CrumbleBarInfo>().componentId.isEmpty())
crumblePath()->popElement();
-
m_isInternalCalled = true;
if (clickedCrumbleBarInfo.componentId.isEmpty()
&& clickedCrumbleBarInfo.fileName == currentDesignDocument()->fileName()) {
@@ -125,9 +155,15 @@ void FormEditorCrumbleBar::onCrumblePathElementClicked(const QVariant &data)
if (!clickedCrumbleBarInfo.componentId.isEmpty()) {
currentDesignDocument()->changeToSubComponent(
currentDesignDocument()->rewriterView()->modelNodeForId(clickedCrumbleBarInfo.componentId));
- pushInFileComponent(clickedCrumbleBarInfo.componentId);
+ //pushInFileComponent(clickedCrumbleBarInfo.componentId);
}
}
+ updateVisibility();
+}
+
+void CrumbleBar::updateVisibility()
+{
+ crumblePath()->setVisible(crumblePath()->length() > 1);
}
bool operator ==(const CrumbleBarInfo &first, const CrumbleBarInfo &second)
diff --git a/src/plugins/qmldesigner/components/formeditor/formeditorcrumblebar.h b/src/plugins/qmldesigner/components/componentcore/crumblebar.h
index bf6edfc91f..632edf3f2d 100644
--- a/src/plugins/qmldesigner/components/formeditor/formeditorcrumblebar.h
+++ b/src/plugins/qmldesigner/components/componentcore/crumblebar.h
@@ -32,19 +32,18 @@
#include <QObject>
#include <utils/crumblepath.h>
+#include <modelnode.h>
namespace QmlDesigner {
-
-
-class FormEditorCrumbleBar : public QObject
+class CrumbleBar : public QObject
{
Q_OBJECT
public:
- explicit FormEditorCrumbleBar(QObject *parent = 0);
+ explicit CrumbleBar(QObject *parent = 0);
void pushFile(const QString &fileName);
- void pushInFileComponent(const QString &componentId);
+ void pushInFileComponent(const ModelNode &modelNode);
void nextFileIsCalledInternally();
@@ -54,6 +53,9 @@ private slots:
void onCrumblePathElementClicked(const QVariant &data);
private:
+ void updateVisibility();
+
+private:
bool m_isInternalCalled;
Utils::CrumblePath *m_crumblePath;
};
@@ -62,6 +64,7 @@ class CrumbleBarInfo {
public:
QString fileName;
QString componentId;
+ ModelNode modelNode;
};
bool operator ==(const CrumbleBarInfo &first, const CrumbleBarInfo &second);
diff --git a/src/plugins/qmldesigner/components/componentcore/designeractionmanager.cpp b/src/plugins/qmldesigner/components/componentcore/designeractionmanager.cpp
index 041bdf5b32..6c276216c2 100644
--- a/src/plugins/qmldesigner/components/componentcore/designeractionmanager.cpp
+++ b/src/plugins/qmldesigner/components/componentcore/designeractionmanager.cpp
@@ -31,6 +31,7 @@
#include "modelnodecontextmenu_helper.h"
#include <nodeproperty.h>
#include <nodemetainfo.h>
+#include "designeractionmanagerview.h"
namespace QmlDesigner {
@@ -42,183 +43,14 @@ static inline QString captionForModelNode(const ModelNode &modelNode)
return modelNode.id();
}
-static inline bool contains(const QmlItemNode &node, const QPoint &position)
+static inline bool contains(const QmlItemNode &node, const QPointF &position)
{
return node.isValid() && node.instanceSceneTransform().mapRect(node.instanceBoundingRect()).contains(position);
}
-namespace Internal {
-
-class DesignerActionManagerView : public QmlModelView
+AbstractView *DesignerActionManager::view()
{
-public:
- DesignerActionManagerView() : QmlModelView(0), m_isInRewriterTransaction(false), m_setupContextDirty(false)
- {}
-
- void modelAttached(Model *model) QTC_OVERRIDE
- {
- QmlModelView::modelAttached(model);
- setupContext();
- }
-
- void modelAboutToBeDetached(Model *model) QTC_OVERRIDE
- {
- QmlModelView::modelAboutToBeDetached(model);
- setupContext();
- }
-
- virtual void nodeCreated(const ModelNode &) QTC_OVERRIDE
- {
- setupContext();
- }
-
- virtual void nodeAboutToBeRemoved(const ModelNode &) QTC_OVERRIDE
- {}
-
- virtual void nodeRemoved(const ModelNode &, const NodeAbstractProperty &, PropertyChangeFlags) QTC_OVERRIDE
- {
- setupContext();
- }
-
- virtual void nodeAboutToBeReparented(const ModelNode &,
- const NodeAbstractProperty &,
- const NodeAbstractProperty &,
- AbstractView::PropertyChangeFlags ) QTC_OVERRIDE
- {
- setupContext();
- }
-
- virtual void nodeReparented(const ModelNode &, const NodeAbstractProperty &,
- const NodeAbstractProperty &,
- AbstractView::PropertyChangeFlags) QTC_OVERRIDE
- {
- setupContext();
- }
-
- virtual void nodeIdChanged(const ModelNode&, const QString&, const QString&) QTC_OVERRIDE
- {}
-
- virtual void propertiesAboutToBeRemoved(const QList<AbstractProperty>&) QTC_OVERRIDE
- {}
-
- virtual void propertiesRemoved(const QList<AbstractProperty>&) QTC_OVERRIDE
- {
- setupContext();
- }
-
- virtual void variantPropertiesChanged(const QList<VariantProperty>&, PropertyChangeFlags) QTC_OVERRIDE
- {}
-
- virtual void bindingPropertiesChanged(const QList<BindingProperty>&, PropertyChangeFlags) QTC_OVERRIDE
- {}
-
- virtual void rootNodeTypeChanged(const QString &, int , int ) QTC_OVERRIDE
- {
- setupContext();
- }
-
- virtual void instancePropertyChange(const QList<QPair<ModelNode, PropertyName> > &) QTC_OVERRIDE
- {}
-
- virtual void instancesCompleted(const QVector<ModelNode> &) QTC_OVERRIDE
- {}
-
- virtual void instanceInformationsChange(const QMultiHash<ModelNode, InformationName> &) QTC_OVERRIDE
- {}
-
- virtual void instancesRenderImageChanged(const QVector<ModelNode> &) QTC_OVERRIDE
- {}
-
- virtual void instancesPreviewImageChanged(const QVector<ModelNode> &) QTC_OVERRIDE
- {}
-
- virtual void instancesChildrenChanged(const QVector<ModelNode> &) QTC_OVERRIDE
- {}
-
- virtual void instancesToken(const QString &, int , const QVector<ModelNode> &) QTC_OVERRIDE
- {}
-
- virtual void nodeSourceChanged(const ModelNode &, const QString &) QTC_OVERRIDE
- {}
-
- virtual void rewriterBeginTransaction() QTC_OVERRIDE
- {
- m_isInRewriterTransaction = true;
- }
-
- virtual void rewriterEndTransaction() QTC_OVERRIDE
- {
- m_isInRewriterTransaction = false;
-
- if (m_setupContextDirty)
- setupContext();
- }
-
- virtual void actualStateChanged(const ModelNode &) QTC_OVERRIDE
- {
- setupContext();
- }
-
- virtual void selectedNodesChanged(const QList<ModelNode> &,
- const QList<ModelNode> &) QTC_OVERRIDE
- {
- setupContext();
- }
-
- virtual void nodeOrderChanged(const NodeListProperty &, const ModelNode &, int ) QTC_OVERRIDE
- {
- setupContext();
- }
-
- virtual void importsChanged(const QList<Import> &, const QList<Import> &) QTC_OVERRIDE
- {
- setupContext();
- }
-
- virtual void scriptFunctionsChanged(const ModelNode &, const QStringList &) QTC_OVERRIDE
- {}
-
- void setDesignerActionList(const QList<AbstractDesignerAction* > &designerActionList)
- {
- m_designerActionList = designerActionList;
- }
-
-protected:
- void setupContext()
- {
- if (m_isInRewriterTransaction) {
- m_setupContextDirty = true;
- return;
- }
- SelectionContext selectionContext(this);
- foreach (AbstractDesignerAction* action, m_designerActionList) {
- action->currentContextChanged(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;
+ return m_designerActionManagerView;
}
class VisiblityModelNodeAction : public ModelNodeAction
@@ -338,10 +170,10 @@ public:
m_menu->addAction(selectionAction);
}
- foreach (const ModelNode &node, m_selectionContext.qmlModelView()->allModelNodes()) {
+ foreach (const ModelNode &node, m_selectionContext.view()->allModelNodes()) {
if (node != m_selectionContext.currentSingleSelectedNode()
&& node != parentNode
- && contains(node, m_selectionContext.scenePos())
+ && contains(node, m_selectionContext.scenePosition())
&& !node.isRootNode()) {
m_selectionContext.setTargetNode(node);
QString what = QString(QT_TRANSLATE_NOOP("QmlDesignerContextMenu", "Select: %1")).arg(captionForModelNode(node));
@@ -413,9 +245,9 @@ bool selectionCanBeLayouted(const SelectionContext &context)
bool hasQtQuickLayoutImport(const SelectionContext &context)
{
- if (context.qmlModelView() && context.qmlModelView()->model()) {
+ if (context.view() && context.view()->model()) {
Import import = Import::createLibraryImport(QLatin1String("QtQuick.Layouts"), QLatin1String("1.0"));
- return context.qmlModelView()->model()->hasImport(import, true, true);
+ return context.view()->model()->hasImport(import, true, true);
}
return false;
@@ -588,23 +420,13 @@ void DesignerActionManager::createDefaultDesignerActions()
(goIntoComponentDisplayName, rootCategory, priorityGoIntoComponent, &goIntoComponent, &selectionIsComponent));
}
-DesignerActionManager *DesignerActionManager::instance()
-{
- if (!m_instance) {
- m_instance = new DesignerActionManager;
- createDefaultDesignerActions();
- }
-
- return m_instance;
-}
-
-void DesignerActionManager::addDesignerActionInternal(AbstractDesignerAction *newAction)
+void DesignerActionManager::addDesignerAction(AbstractDesignerAction *newAction)
{
m_designerActions.append(QSharedPointer<AbstractDesignerAction>(newAction));
- m_view->setDesignerActionList(designerActions());
+ m_designerActionManagerView->setDesignerActionList(designerActions());
}
-QList<AbstractDesignerAction* > DesignerActionManager::factoriesInternal() const
+QList<AbstractDesignerAction* > DesignerActionManager::designerActions() const
{
QList<AbstractDesignerAction* > list;
foreach (const QSharedPointer<AbstractDesignerAction> &pointer, m_designerActions) {
@@ -614,13 +436,13 @@ QList<AbstractDesignerAction* > DesignerActionManager::factoriesInternal() const
return list;
}
-DesignerActionManager::DesignerActionManager() : m_view(new Internal::DesignerActionManagerView)
+DesignerActionManager::DesignerActionManager(DesignerActionManagerView *designerActionManagerView)
+ : m_designerActionManagerView(designerActionManagerView)
{
}
DesignerActionManager::~DesignerActionManager()
{
- delete m_view;
}
} //QmlDesigner
diff --git a/src/plugins/qmldesigner/components/componentcore/designeractionmanager.h b/src/plugins/qmldesigner/components/componentcore/designeractionmanager.h
index 2b4f31ec56..8266cd778a 100644
--- a/src/plugins/qmldesigner/components/componentcore/designeractionmanager.h
+++ b/src/plugins/qmldesigner/components/componentcore/designeractionmanager.h
@@ -32,33 +32,26 @@
#include <qmldesignercorelib_global.h>
#include "abstractdesigneraction.h"
-#include "qmlmodelview.h"
+#include "abstractview.h"
namespace QmlDesigner {
-namespace Internal {
class DesignerActionManagerView;
-}
class QMLDESIGNERCORE_EXPORT DesignerActionManager {
public:
- static void addDesignerAction(AbstractDesignerAction *newAction);
- static QList<AbstractDesignerAction* > designerActions();
+ DesignerActionManager(DesignerActionManagerView *designerActionManagerView);
+ ~DesignerActionManager();
- static void createDefaultDesignerActions();
- static QmlModelView *view();
+ void addDesignerAction(AbstractDesignerAction *newAction);
+ QList<AbstractDesignerAction* > designerActions() const;
-protected:
- static DesignerActionManager *instance();
- void addDesignerActionInternal(AbstractDesignerAction *newAction);
- QList<AbstractDesignerAction* > factoriesInternal() const;
- DesignerActionManager();
- ~DesignerActionManager();
+ void createDefaultDesignerActions();
+ AbstractView *view();
private:
- static DesignerActionManager *m_instance;
QList<QSharedPointer<AbstractDesignerAction> > m_designerActions;
- Internal::DesignerActionManagerView *m_view;
+ DesignerActionManagerView *m_designerActionManagerView;
};
} //QmlDesigner
diff --git a/src/plugins/qmldesigner/components/componentcore/designeractionmanagerview.cpp b/src/plugins/qmldesigner/components/componentcore/designeractionmanagerview.cpp
new file mode 100644
index 0000000000..87cd3969d4
--- /dev/null
+++ b/src/plugins/qmldesigner/components/componentcore/designeractionmanagerview.cpp
@@ -0,0 +1,196 @@
+/****************************************************************************
+**
+** 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 "designeractionmanagerview.h"
+
+#include <selectioncontext.h>
+#include <abstractdesigneraction.h>
+
+namespace QmlDesigner {
+
+DesignerActionManagerView::DesignerActionManagerView()
+ : AbstractView(0),
+ m_designerActionManager(this),
+ m_isInRewriterTransaction(false),
+ m_setupContextDirty(false)
+{
+ m_designerActionManager.createDefaultDesignerActions();
+}
+
+void DesignerActionManagerView::modelAttached(Model *model)
+{
+ AbstractView::modelAttached(model);
+ setupContext();
+}
+
+void DesignerActionManagerView::modelAboutToBeDetached(Model *model)
+{
+ AbstractView::modelAboutToBeDetached(model);
+ setupContext();
+}
+
+void DesignerActionManagerView::nodeCreated(const ModelNode &)
+{
+ setupContext();
+}
+
+void DesignerActionManagerView::nodeAboutToBeRemoved(const ModelNode &)
+{}
+
+void DesignerActionManagerView::nodeRemoved(const ModelNode &, const NodeAbstractProperty &, AbstractView::PropertyChangeFlags)
+{
+ setupContext();
+}
+
+void DesignerActionManagerView::nodeAboutToBeReparented(const ModelNode &, const NodeAbstractProperty &, const NodeAbstractProperty &, AbstractView::PropertyChangeFlags)
+{
+ setupContext();
+}
+
+void DesignerActionManagerView::nodeReparented(const ModelNode &, const NodeAbstractProperty &, const NodeAbstractProperty &, AbstractView::PropertyChangeFlags)
+{
+ setupContext();
+}
+
+void DesignerActionManagerView::nodeIdChanged(const ModelNode &, const QString &, const QString &)
+{}
+
+void DesignerActionManagerView::propertiesAboutToBeRemoved(const QList<AbstractProperty> &)
+{}
+
+void DesignerActionManagerView::propertiesRemoved(const QList<AbstractProperty> &)
+{
+ setupContext();
+}
+
+void DesignerActionManagerView::variantPropertiesChanged(const QList<VariantProperty> &, AbstractView::PropertyChangeFlags)
+{}
+
+void DesignerActionManagerView::bindingPropertiesChanged(const QList<BindingProperty> &, AbstractView::PropertyChangeFlags)
+{}
+
+void DesignerActionManagerView::rootNodeTypeChanged(const QString &, int, int)
+{
+ setupContext();
+}
+
+void DesignerActionManagerView::instancePropertyChange(const QList<QPair<ModelNode, PropertyName> > &)
+{}
+
+void DesignerActionManagerView::instancesCompleted(const QVector<ModelNode> &)
+{}
+
+void DesignerActionManagerView::instanceInformationsChange(const QMultiHash<ModelNode, InformationName> &)
+{}
+
+void DesignerActionManagerView::instancesRenderImageChanged(const QVector<ModelNode> &)
+{}
+
+void DesignerActionManagerView::instancesPreviewImageChanged(const QVector<ModelNode> &)
+{}
+
+void DesignerActionManagerView::instancesChildrenChanged(const QVector<ModelNode> &)
+{}
+
+void DesignerActionManagerView::instancesToken(const QString &, int, const QVector<ModelNode> &)
+{}
+
+void DesignerActionManagerView::nodeSourceChanged(const ModelNode &, const QString &)
+{}
+
+void DesignerActionManagerView::rewriterBeginTransaction()
+{
+ m_isInRewriterTransaction = true;
+}
+
+void DesignerActionManagerView::rewriterEndTransaction()
+{
+ m_isInRewriterTransaction = false;
+
+ if (m_setupContextDirty)
+ setupContext();
+}
+
+void DesignerActionManagerView::currentStateChanged(const ModelNode &)
+{
+ setupContext();
+}
+
+void DesignerActionManagerView::selectedNodesChanged(const QList<ModelNode> &, const QList<ModelNode> &)
+{
+ setupContext();
+}
+
+void DesignerActionManagerView::nodeOrderChanged(const NodeListProperty &, const ModelNode &, int)
+{
+ setupContext();
+}
+
+void DesignerActionManagerView::importsChanged(const QList<Import> &, const QList<Import> &)
+{
+ setupContext();
+}
+
+void DesignerActionManagerView::scriptFunctionsChanged(const ModelNode &, const QStringList &)
+{}
+
+void DesignerActionManagerView::setDesignerActionList(const QList<AbstractDesignerAction *> &designerActionList)
+{
+ m_designerActionList = designerActionList;
+}
+
+void DesignerActionManagerView::signalHandlerPropertiesChanged(const QVector<SignalHandlerProperty> &, AbstractView::PropertyChangeFlags)
+{
+ setupContext();
+}
+
+DesignerActionManager &DesignerActionManagerView::designerActionManager()
+{
+ return m_designerActionManager;
+}
+
+const DesignerActionManager &DesignerActionManagerView::designerActionManager() const
+{
+ return m_designerActionManager;
+}
+
+void DesignerActionManagerView::setupContext()
+{
+ if (m_isInRewriterTransaction) {
+ m_setupContextDirty = true;
+ return;
+ }
+ SelectionContext selectionContext(this);
+ foreach (AbstractDesignerAction* action, m_designerActionList) {
+ action->currentContextChanged(selectionContext);
+ }
+ m_setupContextDirty = false;
+}
+
+} // namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/components/componentcore/designeractionmanagerview.h b/src/plugins/qmldesigner/components/componentcore/designeractionmanagerview.h
new file mode 100644
index 0000000000..dee7021b3c
--- /dev/null
+++ b/src/plugins/qmldesigner/components/componentcore/designeractionmanagerview.h
@@ -0,0 +1,100 @@
+/****************************************************************************
+**
+** 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 QMLDESIGNER_DESIGNERACTIONMANAGERVIEW_H
+#define QMLDESIGNER_DESIGNERACTIONMANAGERVIEW_H
+
+#include <abstractview.h>
+
+#include "designeractionmanager.h"
+
+namespace QmlDesigner {
+
+class AbstractDesignerAction;
+
+class DesignerActionManagerView : public AbstractView
+{
+ Q_OBJECT
+public:
+ DesignerActionManagerView();
+
+ void modelAttached(Model *model);
+ void modelAboutToBeDetached(Model *model);
+ void nodeCreated(const ModelNode &);
+ void nodeAboutToBeRemoved(const ModelNode &);
+ void nodeRemoved(const ModelNode &, const NodeAbstractProperty &, PropertyChangeFlags);
+ void nodeAboutToBeReparented(const ModelNode &,
+ const NodeAbstractProperty &,
+ const NodeAbstractProperty &,
+ AbstractView::PropertyChangeFlags );
+ void nodeReparented(const ModelNode &, const NodeAbstractProperty &,
+ const NodeAbstractProperty &,
+ AbstractView::PropertyChangeFlags);
+ void nodeIdChanged(const ModelNode&, const QString&, const QString&);
+ void propertiesAboutToBeRemoved(const QList<AbstractProperty>&);
+ void propertiesRemoved(const QList<AbstractProperty>&);
+ void variantPropertiesChanged(const QList<VariantProperty>&, PropertyChangeFlags);
+ void bindingPropertiesChanged(const QList<BindingProperty>&, PropertyChangeFlags);
+ void rootNodeTypeChanged(const QString &, int , int );
+ void instancePropertyChange(const QList<QPair<ModelNode, PropertyName> > &);
+ void instancesCompleted(const QVector<ModelNode> &);
+ void instanceInformationsChange(const QMultiHash<ModelNode, InformationName> &);
+ void instancesRenderImageChanged(const QVector<ModelNode> &);
+ void instancesPreviewImageChanged(const QVector<ModelNode> &);
+ void instancesChildrenChanged(const QVector<ModelNode> &);
+ void instancesToken(const QString &, int , const QVector<ModelNode> &);
+ void nodeSourceChanged(const ModelNode &, const QString &);
+ void rewriterBeginTransaction();
+ void rewriterEndTransaction();
+ void currentStateChanged(const ModelNode &);
+ void selectedNodesChanged(const QList<ModelNode> &,
+ const QList<ModelNode> &);
+ void nodeOrderChanged(const NodeListProperty &, const ModelNode &, int );
+ void importsChanged(const QList<Import> &, const QList<Import> &);
+ void scriptFunctionsChanged(const ModelNode &, const QStringList &);
+ void setDesignerActionList(const QList<AbstractDesignerAction* > &designerActionList);
+ void signalHandlerPropertiesChanged(const QVector<SignalHandlerProperty> &/*propertyList*/, PropertyChangeFlags /*propertyChange*/);
+
+ DesignerActionManager &designerActionManager();
+ const DesignerActionManager &designerActionManager() const;
+
+protected:
+ void setupContext();
+
+private:
+ DesignerActionManager m_designerActionManager;
+ QList<AbstractDesignerAction* > m_designerActionList;
+ bool m_isInRewriterTransaction;
+ bool m_setupContextDirty;
+};
+
+
+} // namespace QmlDesigner
+
+#endif // QMLDESIGNER_DESIGNERACTIONMANAGERVIEW_H
diff --git a/src/plugins/qmldesigner/components/componentcore/modelnodecontextmenu.cpp b/src/plugins/qmldesigner/components/componentcore/modelnodecontextmenu.cpp
index f26159ec36..6a8a717ac4 100644
--- a/src/plugins/qmldesigner/components/componentcore/modelnodecontextmenu.cpp
+++ b/src/plugins/qmldesigner/components/componentcore/modelnodecontextmenu.cpp
@@ -30,6 +30,7 @@
#include "modelnodecontextmenu.h"
#include "modelnodecontextmenu_helper.h"
#include "designeractionmanager.h"
+#include <qmldesignerplugin.h>
#include <modelnode.h>
@@ -37,7 +38,7 @@
namespace QmlDesigner {
-ModelNodeContextMenu::ModelNodeContextMenu(QmlModelView *view) :
+ModelNodeContextMenu::ModelNodeContextMenu(AbstractView *view) :
m_selectionContext(view)
{
}
@@ -94,11 +95,11 @@ void ModelNodeContextMenu::execute(const QPoint &position, bool selectionMenuBoo
QMenu* mainMenu = new QMenu();
m_selectionContext.setShowSelectionTools(selectionMenuBool);
- m_selectionContext.setScenePos(m_scenePos);
+ m_selectionContext.setScenePosition(m_scenePos);
QSet<AbstractDesignerAction* > factories =
- QSet<AbstractDesignerAction* >::fromList(DesignerActionManager::designerActions());
+ QSet<AbstractDesignerAction* >::fromList(QmlDesignerPlugin::instance()->designerActionManager().designerActions());
populateMenu(factories, QString(""), mainMenu, m_selectionContext);
@@ -111,7 +112,7 @@ void ModelNodeContextMenu::setScenePos(const QPoint &position)
m_scenePos = position;
}
-void ModelNodeContextMenu::showContextMenu(QmlModelView *view,
+void ModelNodeContextMenu::showContextMenu(AbstractView *view,
const QPoint &globalPosition,
const QPoint &scenePosition,
bool showSelection)
diff --git a/src/plugins/qmldesigner/components/componentcore/modelnodecontextmenu.h b/src/plugins/qmldesigner/components/componentcore/modelnodecontextmenu.h
index 11be0a5173..d13ef732bd 100644
--- a/src/plugins/qmldesigner/components/componentcore/modelnodecontextmenu.h
+++ b/src/plugins/qmldesigner/components/componentcore/modelnodecontextmenu.h
@@ -33,7 +33,7 @@
#include <QPoint>
#include <QCoreApplication>
-#include <qmlmodelview.h>
+#include <abstractview.h>
#include "selectioncontext.h"
namespace QmlDesigner {
@@ -42,11 +42,11 @@ class ModelNodeContextMenu
{
Q_DECLARE_TR_FUNCTIONS(QmlDesigner::ModelNodeContextMenu)
public:
- ModelNodeContextMenu(QmlModelView *view);
+ ModelNodeContextMenu(AbstractView *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);
+ static void showContextMenu(AbstractView *view, const QPoint &globalPosition, const QPoint &scenePosition, bool showSelection);
private:
QPoint m_scenePos;
diff --git a/src/plugins/qmldesigner/components/componentcore/modelnodecontextmenu_helper.cpp b/src/plugins/qmldesigner/components/componentcore/modelnodecontextmenu_helper.cpp
index 3c7d299556..f05fb1db93 100644
--- a/src/plugins/qmldesigner/components/componentcore/modelnodecontextmenu_helper.cpp
+++ b/src/plugins/qmldesigner/components/componentcore/modelnodecontextmenu_helper.cpp
@@ -38,87 +38,6 @@
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<PropertyName, QVariant> &propertyHash)
-{
- if (QmlObjectNode(node).isValid()) {
- foreach (const PropertyName &propertyName, node.propertyNames()) {
- if (node.property(propertyName).isVariantProperty() ||
- (node.property(propertyName).isBindingProperty() &&
- !propertyName.contains("anchors."))) {
- propertyHash.insert(propertyName, QmlObjectNode(node).instanceValue(propertyName));
- }
- }
- }
- QmlItemNode itemNode(node);
- if (itemNode.isValid()) {
- propertyHash.insert("width", itemNode.instanceValue("width"));
- propertyHash.insert("height", itemNode.instanceValue("height"));
- propertyHash.remove("x");
- propertyHash.remove("y");
- propertyHash.remove("rotation");
- propertyHash.remove("opacity");
- }
-}
-
-static inline void applyProperties(ModelNode &node, const QHash<PropertyName, QVariant> &propertyHash)
-{
- QHash<PropertyName, QVariant> auxiliaryData = node.auxiliaryData();
- foreach (const PropertyName &propertyName, auxiliaryData.keys()) {
- node.setAuxiliaryData(propertyName, QVariant());
- }
-
- QHashIterator<PropertyName, QVariant> propertyIterator(propertyHash);
- while (propertyIterator.hasNext()) {
- propertyIterator.next();
- const PropertyName propertyName = propertyIterator.key();
- if (propertyName == "width" || propertyName == "height") {
- node.setAuxiliaryData(propertyIterator.key(), propertyIterator.value());
- } else if (node.property(propertyIterator.key()).isDynamic() &&
- node.property(propertyIterator.key()).dynamicTypeName() == "alias" &&
- node.property(propertyIterator.key()).isBindingProperty()) {
- AbstractProperty targetProperty = node.bindingProperty(propertyIterator.key()).resolveToProperty();
- if (targetProperty.isValid())
- targetProperty.parentModelNode().setAuxiliaryData(targetProperty.name() + "@NodeInstance", propertyIterator.value());
- } else {
- node.setAuxiliaryData(propertyIterator.key() + "@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())
@@ -151,91 +70,6 @@ static inline bool itemsHaveSameParent(const QList<ModelNode> &siblingList)
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<PropertyName, 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<PropertyName, 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)
@@ -265,7 +99,8 @@ bool selectionHasSameParent(const SelectionContext &selectionState)
bool selectionIsComponent(const SelectionContext &selectionState)
{
- return modelNodeIsComponent(selectionState.currentSingleSelectedNode());
+ return selectionState.currentSingleSelectedNode().isValid()
+ && selectionState.currentSingleSelectedNode().isComponent();
}
} //SelectionStateFunctors
diff --git a/src/plugins/qmldesigner/components/componentcore/modelnodecontextmenu_helper.h b/src/plugins/qmldesigner/components/componentcore/modelnodecontextmenu_helper.h
index d25731495a..4fb8afde25 100644
--- a/src/plugins/qmldesigner/components/componentcore/modelnodecontextmenu_helper.h
+++ b/src/plugins/qmldesigner/components/componentcore/modelnodecontextmenu_helper.h
@@ -32,6 +32,7 @@
#include "modelnodeoperations.h"
#include "defaultdesigneraction.h"
+#include "qmlitemnode.h"
#include <QAction>
#include <QMenu>
@@ -95,11 +96,6 @@ bool singleSelectionItemIsNotAnchored(const SelectionContext &selectionState);
} // namespace SelectionStateFunctors
-
-namespace ComponentUtils {
- void goIntoComponent(const ModelNode &modelNode);
-}
-
class ActionTemplate : public DefaultAction
{
diff --git a/src/plugins/qmldesigner/components/componentcore/modelnodeoperations.cpp b/src/plugins/qmldesigner/components/componentcore/modelnodeoperations.cpp
index 931501b4fd..0203f287f6 100644
--- a/src/plugins/qmldesigner/components/componentcore/modelnodeoperations.cpp
+++ b/src/plugins/qmldesigner/components/componentcore/modelnodeoperations.cpp
@@ -39,22 +39,19 @@
#include <variantproperty.h>
#include <rewritingexception.h>
#include <rewritertransaction.h>
+#include <documentmanager.h>
#include <qmlanchors.h>
+#include <limits>
namespace QmlDesigner {
const PropertyName auxDataString("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()) {
+ if (itemNode.isValid() && itemNode.modelNode().hasParentProperty()) {
QList<ModelNode> modelNodes = itemNode.modelNode().parentProperty().parentModelNode().allDirectSubModelNodes();
foreach (const ModelNode &node, modelNodes) {
QmlItemNode childItemNode = node;
@@ -88,47 +85,75 @@ static signed int getMinZValue(const QList<QmlItemNode> &siblingList)
return minimum;
}
-static inline void getWidthHeight(const ModelNode &node, int &width, int &height)
+static inline void reparentTo(const ModelNode &node, const QmlItemNode &parent)
{
- QmlItemNode itemNode(node);
- if (itemNode.isValid()) {
- width = itemNode.instanceValue("width").toInt();
- height = itemNode.instanceValue("height").toInt();
+
+ if (parent.isValid() && node.isValid()) {
+ NodeAbstractProperty parentProperty;
+
+ if (parent.hasDefaultPropertyName())
+ parentProperty = parent.defaultNodeAbstractProperty();
+ else
+ parentProperty = parent.nodeAbstractProperty("data");
+
+ parentProperty.reparentHere(node);
}
}
-static inline bool modelNodesHaveProperty(const QList<ModelNode> &modelNodeList, const PropertyName &propertyName)
+static void reparentToNodeAndRemovePositionForModelNodes(const ModelNode &parentModelNode, const QList<ModelNode> &modelNodeList)
{
- foreach (const ModelNode &modelNode, modelNodeList)
- if (modelNode.hasProperty(propertyName))
- return true;
+ foreach (ModelNode modelNode, modelNodeList) {
+ reparentTo(modelNode, parentModelNode);
+ modelNode.removeProperty("x");
+ modelNode.removeProperty("y");
+ }
+}
+
+static inline QPointF getUpperLeftPosition(const QList<ModelNode> &modelNodeList)
+{
+ QPointF postion(std::numeric_limits<qreal>::max(), std::numeric_limits<qreal>::max());
+ foreach (const ModelNode &modelNode, modelNodeList) {
+ if (QmlItemNode::isValidQmlItemNode(modelNode)) {
+ QmlItemNode qmlIitemNode = QmlItemNode(modelNode);
+ if (qmlIitemNode.instancePosition().x() < postion.x())
+ postion.setX(qmlIitemNode.instancePosition().x());
+ if (qmlIitemNode.instancePosition().y() < postion.y())
+ postion.setY(qmlIitemNode.instancePosition().y());
+ }
+ }
- return false;
+ return postion;
}
+static void setUpperLeftPostionToNode(const ModelNode &layoutNode, const QList<ModelNode> &modelNodeList)
+{
+ QPointF upperLeftPosition = getUpperLeftPosition(modelNodeList);
+ layoutNode.variantProperty("x").setValue(qRound(upperLeftPosition.x()));
+ layoutNode.variantProperty("y") .setValue(qRound(upperLeftPosition.y()));
+}
namespace ModelNodeOperations {
void goIntoComponent(const ModelNode &modelNode)
{
- ComponentUtils::goIntoComponent(modelNode);
+ DocumentManager::goIntoComponent(modelNode);
}
void select(const SelectionContext &selectionState)
{
- if (selectionState.qmlModelView())
- selectionState.qmlModelView()->setSelectedModelNodes(QList<ModelNode>() << selectionState.targetNode());
+ if (selectionState.view())
+ selectionState.view()->setSelectedModelNodes(QList<ModelNode>() << selectionState.targetNode());
}
void deSelect(const SelectionContext &selectionState)
{
- if (selectionState.qmlModelView()) {
- QList<ModelNode> selectedNodes = selectionState.qmlModelView()->selectedModelNodes();
+ if (selectionState.view()) {
+ QList<ModelNode> selectedNodes = selectionState.view()->selectedModelNodes();
foreach (const ModelNode &node, selectionState.selectedModelNodes()) {
if (selectedNodes.contains(node))
selectedNodes.removeAll(node);
}
- selectionState.qmlModelView()->setSelectedModelNodes(selectedNodes);
+ selectionState.view()->setSelectedModelNodes(selectedNodes);
}
}
@@ -147,11 +172,11 @@ void deleteSelection(const SelectionContext &)
void toFront(const SelectionContext &selectionState)
{
- if (!selectionState.qmlModelView())
+ if (!selectionState.view())
return;
try {
- QmlItemNode node = selectionState.selectedModelNodes().first();
+ QmlItemNode node = selectionState.firstSelectedModelNode();
if (node.isValid()) {
signed int maximumZ = getMaxZValue(siblingsForNode(node));
maximumZ++;
@@ -165,10 +190,10 @@ void toFront(const SelectionContext &selectionState)
void toBack(const SelectionContext &selectionState)
{
- if (!selectionState.qmlModelView())
+ if (!selectionState.view())
return;
try {
- QmlItemNode node = selectionState.selectedModelNodes().first();
+ QmlItemNode node = selectionState.firstSelectedModelNode();
if (node.isValid()) {
signed int minimumZ = getMinZValue(siblingsForNode(node));
minimumZ--;
@@ -182,11 +207,11 @@ void toBack(const SelectionContext &selectionState)
void raise(const SelectionContext &selectionState)
{
- if (!selectionState.qmlModelView())
+ if (!selectionState.view())
return;
try {
- RewriterTransaction transaction(selectionState.qmlModelView());
+ RewriterTransaction transaction(selectionState.view());
foreach (ModelNode modelNode, selectionState.selectedModelNodes()) {
QmlItemNode node = modelNode;
if (node.isValid()) {
@@ -203,11 +228,11 @@ void raise(const SelectionContext &selectionState)
void lower(const SelectionContext &selectionState)
{
- if (!selectionState.qmlModelView())
+ if (!selectionState.view())
return;
try {
- RewriterTransaction transaction(selectionState.qmlModelView());
+ RewriterTransaction transaction(selectionState.view());
foreach (ModelNode modelNode, selectionState.selectedModelNodes()) {
QmlItemNode node = modelNode;
if (node.isValid()) {
@@ -235,11 +260,11 @@ void redo(const SelectionContext &)
void setVisible(const SelectionContext &selectionState)
{
- if (!selectionState.qmlModelView())
+ if (!selectionState.view())
return;
try {
- selectionState.selectedModelNodes().first().variantProperty("visible") = selectionState.toggled();
+ selectionState.selectedModelNodes().first().variantProperty("visible").setValue(selectionState.toggled());
} catch (RewritingException &e) { //better save then sorry
QMessageBox::warning(0, "Error", e.description());
}
@@ -247,12 +272,12 @@ void setVisible(const SelectionContext &selectionState)
void setFillWidth(const SelectionContext &selectionState)
{
- if (!selectionState.qmlModelView()
- || selectionState.selectedModelNodes().isEmpty())
+ if (!selectionState.view()
+ || !selectionState.hasSingleSelectedModelNode())
return;
try {
- selectionState.selectedModelNodes().first().variantProperty("Layout.fillWidth") = selectionState.toggled();
+ selectionState.firstSelectedModelNode().variantProperty("Layout.fillWidth").setValue(selectionState.toggled());
} catch (RewritingException &e) { //better save then sorry
QMessageBox::warning(0, "Error", e.description());
}
@@ -260,12 +285,12 @@ void setFillWidth(const SelectionContext &selectionState)
void setFillHeight(const SelectionContext &selectionState)
{
- if (!selectionState.qmlModelView()
- || selectionState.selectedModelNodes().isEmpty())
+ if (!selectionState.view()
+ || !selectionState.hasSingleSelectedModelNode())
return;
try {
- selectionState.selectedModelNodes().first().variantProperty("Layout.fillHeight") = selectionState.toggled();
+ selectionState.firstSelectedModelNode().variantProperty("Layout.fillHeight").setValue(selectionState.toggled());
} catch (RewritingException &e) { //better save then sorry
QMessageBox::warning(0, "Error", e.description());
}
@@ -273,11 +298,11 @@ void setFillHeight(const SelectionContext &selectionState)
void resetSize(const SelectionContext &selectionState)
{
- if (!selectionState.qmlModelView())
+ if (!selectionState.view())
return;
try {
- RewriterTransaction transaction(selectionState.qmlModelView());
+ RewriterTransaction transaction(selectionState.view());
foreach (ModelNode node, selectionState.selectedModelNodes()) {
node.removeProperty("width");
node.removeProperty("height");
@@ -289,11 +314,11 @@ void resetSize(const SelectionContext &selectionState)
void resetPosition(const SelectionContext &selectionState)
{
- if (!selectionState.qmlModelView())
+ if (!selectionState.view())
return;
try {
- RewriterTransaction transaction(selectionState.qmlModelView());
+ RewriterTransaction transaction(selectionState.view());
foreach (ModelNode node, selectionState.selectedModelNodes()) {
node.removeProperty("x");
node.removeProperty("y");
@@ -314,10 +339,10 @@ void setId(const SelectionContext &)
void resetZ(const SelectionContext &selectionState)
{
- if (!selectionState.qmlModelView())
+ if (!selectionState.view())
return;
- RewriterTransaction transaction(selectionState.qmlModelView());
+ RewriterTransaction transaction(selectionState.view());
foreach (ModelNode node, selectionState.selectedModelNodes()) {
node.removeProperty("z");
}
@@ -340,15 +365,15 @@ static inline void backupPropertyAndRemove(ModelNode node, const PropertyName &p
static inline void restoreProperty(ModelNode node, const PropertyName &propertyName)
{
if (node.hasAuxiliaryData(auxDataString + propertyName))
- node.variantProperty(propertyName) = node.auxiliaryData(auxDataString + propertyName);
+ node.variantProperty(propertyName).setValue(node.auxiliaryData(auxDataString + propertyName));
}
void anchorsFill(const SelectionContext &selectionState)
{
- if (!selectionState.qmlModelView())
+ if (!selectionState.view())
return;
- RewriterTransaction transaction(selectionState.qmlModelView());
+ RewriterTransaction transaction(selectionState.view());
ModelNode modelNode = selectionState.currentSingleSelectedNode();
@@ -364,10 +389,10 @@ void anchorsFill(const SelectionContext &selectionState)
void anchorsReset(const SelectionContext &selectionState)
{
- if (!selectionState.qmlModelView())
+ if (!selectionState.view())
return;
- RewriterTransaction transaction(selectionState.qmlModelView());
+ RewriterTransaction transaction(selectionState.view());
ModelNode modelNode = selectionState.currentSingleSelectedNode();
@@ -382,21 +407,7 @@ void anchorsReset(const SelectionContext &selectionState)
}
}
-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("data");
-
- parentProperty.reparentHere(node);
- }
-}
-
+typedef bool (*LessThan)(const ModelNode &node1, const ModelNode &node2);
bool compareByX(const ModelNode &node1, const ModelNode &node2)
{
@@ -430,339 +441,80 @@ bool compareByGrid(const ModelNode &node1, const ModelNode &node2)
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 layoutRowPositioner(const SelectionContext &selectionState)
+static void layoutHelperFunction(const SelectionContext &selectionContext,
+ TypeName layoutType,
+ LessThan lessThan)
{
- if (!selectionState.qmlModelView())
+ if (!selectionContext.view()
+ || !selectionContext.hasSingleSelectedModelNode()
+ || !selectionContext.view()->model()->hasNodeMetaInfo(layoutType))
return;
- NodeMetaInfo rowMetaInfo = selectionState.qmlModelView()->model()->metaInfo("QtQuick.Row");
-
- if (!rowMetaInfo.isValid())
- return;
+ if (QmlItemNode::isValidQmlItemNode(selectionContext.firstSelectedModelNode())) {
+ QmlItemNode qmlItemNode = QmlItemNode(selectionContext.firstSelectedModelNode());
- QList<ModelNode> modelNodeList = selectionState.selectedModelNodes();
+ if (qmlItemNode.hasInstanceParentItem()) {
- ModelNode row;
- {
- RewriterTransaction transaction(selectionState.qmlModelView());
+ ModelNode layoutNode;
+ {
+ RewriterTransaction transaction(selectionContext.view());
- QmlItemNode parent = QmlItemNode(modelNodeList.first()).instanceParent().toQmlItemNode();
- if (!parent.isValid())
- return;
+ QmlItemNode parentNode = qmlItemNode.instanceParentItem();
- qDebug() << parent.modelNode().majorQtQuickVersion();
+ NodeMetaInfo metaInfo = selectionContext.view()->model()->metaInfo(layoutType);
- row = selectionState.qmlModelView()->createModelNode("QtQuick.Row", rowMetaInfo.majorVersion(), rowMetaInfo.minorVersion());
-
- reparentTo(row, parent);
- }
+ layoutNode = selectionContext.view()->createModelNode(layoutType, metaInfo.majorVersion(), metaInfo.minorVersion());
- {
- RewriterTransaction transaction(selectionState.qmlModelView());
+ reparentTo(layoutNode, parentNode);
+ }
- QPoint pos = getUpperLeftPosition(modelNodeList);
- row.variantProperty("x") = pos.x();
- row.variantProperty("y") = pos.y();
+ {
+ RewriterTransaction transaction(selectionContext.view());
- QList<ModelNode> sortedList = modelNodeList;
- qSort(sortedList.begin(), sortedList.end(), compareByX);
+ QList<ModelNode> sortedSelectedNodes = selectionContext.selectedModelNodes();
+ qSort(sortedSelectedNodes.begin(), sortedSelectedNodes.end(), lessThan);
- foreach (ModelNode modelNode, sortedList) {
- reparentTo(modelNode, row);
- modelNode.removeProperty("x");
- modelNode.removeProperty("y");
+ setUpperLeftPostionToNode(layoutNode, sortedSelectedNodes);
+ reparentToNodeAndRemovePositionForModelNodes(layoutNode, sortedSelectedNodes);
+ }
}
}
}
-void layoutColumnPositioner(const SelectionContext &selectionState)
+void layoutRowPositioner(const SelectionContext &selectionContext)
{
- if (!selectionState.qmlModelView())
- return;
-
- NodeMetaInfo columnMetaInfo = selectionState.qmlModelView()->model()->metaInfo("QtQuick.Column");
-
- if (!columnMetaInfo.isValid())
- return;
-
- QList<ModelNode> modelNodeList = selectionState.selectedModelNodes();
-
- ModelNode column;
- {
- RewriterTransaction transaction(selectionState.qmlModelView());
-
- QmlItemNode parent = QmlItemNode(modelNodeList.first()).instanceParent().toQmlItemNode();
- if (!parent.isValid())
- return;
-
- column = selectionState.qmlModelView()->createModelNode("QtQuick.Column", columnMetaInfo.majorVersion(), columnMetaInfo.minorVersion());
-
- reparentTo(column, parent);
- }
-
- {
- RewriterTransaction transaction(selectionState.qmlModelView());
-
- QPoint pos = getUpperLeftPosition(modelNodeList);
- column.variantProperty("x") = pos.x();
- column.variantProperty("y") = pos.y();
-
- QList<ModelNode> sortedList = modelNodeList;
- qSort(sortedList.begin(), sortedList.end(), compareByY);
-
- foreach (ModelNode modelNode, sortedList) {
- reparentTo(modelNode, column);
- modelNode.removeProperty("x");
- modelNode.removeProperty("y");
- }
- }
+ layoutHelperFunction(selectionContext, "QtQuick.Row", compareByX);
}
-void layoutGridPositioner(const SelectionContext &selectionState)
+void layoutColumnPositioner(const SelectionContext &selectionContext)
{
- if (!selectionState.qmlModelView())
- return;
-
- NodeMetaInfo gridMetaInfo = selectionState.qmlModelView()->model()->metaInfo("QtQuick.Grid");
-
- if (!gridMetaInfo.isValid())
- return;
-
- QList<ModelNode> modelNodeList = selectionState.selectedModelNodes();
-
- ModelNode grid;
- {
- RewriterTransaction transaction(selectionState.qmlModelView());
-
- QmlItemNode parent = QmlItemNode(modelNodeList.first()).instanceParent().toQmlItemNode();
- if (!parent.isValid())
- return;
-
- grid = selectionState.qmlModelView()->createModelNode("QtQuick.Grid", gridMetaInfo.majorVersion(), gridMetaInfo.minorVersion());
- grid.variantProperty("columns") = int(sqrt(double(modelNodeList.count())));
-
- reparentTo(grid, parent);
- }
-
- {
- RewriterTransaction transaction(selectionState.qmlModelView());
-
- QPoint pos = getUpperLeftPosition(modelNodeList);
- grid.variantProperty("x") = pos.x();
- grid.variantProperty("y") = pos.y();
-
- QList<ModelNode> sortedList = modelNodeList;
- qSort(sortedList.begin(), sortedList.end(), compareByGrid);
-
- foreach (ModelNode modelNode, sortedList) {
- reparentTo(modelNode, grid);
- modelNode.removeProperty("x");
- modelNode.removeProperty("y");
- }
- }
+ layoutHelperFunction(selectionContext, "QtQuick.Column", compareByY);
}
-void layoutFlowPositioner(const SelectionContext &selectionState)
+void layoutGridPositioner(const SelectionContext &selectionContext)
{
- if (!selectionState.qmlModelView())
- return;
-
- NodeMetaInfo flowMetaInfo = selectionState.qmlModelView()->model()->metaInfo("QtQuick.Flow");
-
- if (!flowMetaInfo.isValid())
- return;
-
- QList<ModelNode> modelNodeList = selectionState.selectedModelNodes();
-
- ModelNode flow;
- {
- RewriterTransaction transaction(selectionState.qmlModelView());
-
- QmlItemNode parent = QmlItemNode(modelNodeList.first()).instanceParent().toQmlItemNode();
- if (!parent.isValid())
- return;
-
- flow = selectionState.qmlModelView()->createModelNode("QtQuick.Flow", flowMetaInfo.majorVersion(), flowMetaInfo.minorVersion());
-
- reparentTo(flow, parent);
- }
-
- {
- RewriterTransaction transaction(selectionState.qmlModelView());
-
- QPoint pos = getUpperLeftPosition(modelNodeList);
- flow.variantProperty("x") = pos.x();
- flow.variantProperty("y") = pos.y();
-
- QList<ModelNode> sortedList = modelNodeList;
- qSort(sortedList.begin(), sortedList.end(), compareByGrid);
-
- foreach (ModelNode modelNode, sortedList) {
- reparentTo(modelNode, flow);
- modelNode.removeProperty("x");
- modelNode.removeProperty("y");
- }
- }
+ layoutHelperFunction(selectionContext, "QtQuick.Grid", compareByGrid);
}
-void layoutRowLayout(const SelectionContext &selectionState)
+void layoutFlowPositioner(const SelectionContext &selectionContext)
{
- if (!selectionState.qmlModelView()
- || selectionState.selectedModelNodes().isEmpty())
- return;
-
- static TypeName rowLayoutType = "QtQuick.Layouts.RowLayout";
-
- if (!selectionState.qmlModelView()->model()->hasNodeMetaInfo(rowLayoutType))
- return;
-
- NodeMetaInfo rowMetaInfo = selectionState.qmlModelView()->model()->metaInfo(rowLayoutType);
-
- QList<ModelNode> selectedNodeList = selectionState.selectedModelNodes();
- QmlItemNode qmlItemNode = QmlItemNode(selectedNodeList.first());
-
- if (qmlItemNode.isValid() && qmlItemNode.hasInstanceParentItem()) {
-
- ModelNode rowNode;
- {
- RewriterTransaction transaction(selectionState.qmlModelView());
-
- QmlItemNode parentNode = qmlItemNode.instanceParentItem();
-
- rowNode = selectionState.qmlModelView()->createModelNode(rowLayoutType, rowMetaInfo.majorVersion(), rowMetaInfo.minorVersion());
-
- reparentTo(rowNode, parentNode);
- }
-
- {
- RewriterTransaction transaction(selectionState.qmlModelView());
-
- QPoint upperLeftPosition = getUpperLeftPosition(selectedNodeList);
- rowNode.variantProperty("x") = upperLeftPosition.x();
- rowNode.variantProperty("y") = upperLeftPosition.y();
-
- QList<ModelNode> sortedSelectedNodes = selectedNodeList;
- qSort(sortedSelectedNodes.begin(), sortedSelectedNodes.end(), compareByX);
-
- foreach (ModelNode selectedNode, sortedSelectedNodes) {
- reparentTo(selectedNode, rowNode);
- selectedNode.removeProperty("x");
- selectedNode.removeProperty("y");
- }
- }
- }
+ layoutHelperFunction(selectionContext, "QtQuick.Flow", compareByGrid);
}
-void layoutColumnLayout(const SelectionContext &selectionState)
+void layoutRowLayout(const SelectionContext &selectionContext)
{
- if (!selectionState.qmlModelView()
- || selectionState.selectedModelNodes().isEmpty())
- return;
-
- static TypeName columnLayoutType = "QtQuick.Layouts.ColumnLayout";
-
- if (!selectionState.qmlModelView()->model()->hasNodeMetaInfo(columnLayoutType))
- return;
-
- NodeMetaInfo columnMetaInfo = selectionState.qmlModelView()->model()->metaInfo(columnLayoutType);
-
- QList<ModelNode> selectedNodeList = selectionState.selectedModelNodes();
- QmlItemNode qmlItemNode = QmlItemNode(selectedNodeList.first());
-
- if (qmlItemNode.isValid() && qmlItemNode.hasInstanceParentItem()) {
-
- ModelNode columnNode;
- {
- RewriterTransaction transaction(selectionState.qmlModelView());
-
- QmlItemNode parentNode = qmlItemNode.instanceParentItem();
-
- columnNode = selectionState.qmlModelView()->createModelNode(columnLayoutType, columnMetaInfo.majorVersion(), columnMetaInfo.minorVersion());
-
- reparentTo(columnNode, parentNode);
- }
-
- {
- RewriterTransaction transaction(selectionState.qmlModelView());
-
- QPoint upperLeftPosition = getUpperLeftPosition(selectedNodeList);
- columnNode.variantProperty("x") = upperLeftPosition.x();
- columnNode.variantProperty("y") = upperLeftPosition.y();
-
- QList<ModelNode> sortedSelectedNodes = selectedNodeList;
- qSort(sortedSelectedNodes.begin(), sortedSelectedNodes.end(), compareByY);
-
- foreach (ModelNode selectedNode, sortedSelectedNodes) {
- reparentTo(selectedNode, columnNode);
- selectedNode.removeProperty("x");
- selectedNode.removeProperty("y");
- }
- }
- }
+ layoutHelperFunction(selectionContext, "QtQuick.Layouts.RowLayout", compareByX);
}
-void layoutGridLayout(const SelectionContext &selectionState)
+void layoutColumnLayout(const SelectionContext &selectionContext)
{
- if (!selectionState.qmlModelView()
- || selectionState.selectedModelNodes().isEmpty())
- return;
-
- static TypeName gridLayoutType = "QtQuick.Layouts.GridLayout";
-
- if (!selectionState.qmlModelView()->model()->hasNodeMetaInfo(gridLayoutType))
- return;
-
- NodeMetaInfo gridMetaInfo = selectionState.qmlModelView()->model()->metaInfo(gridLayoutType);
-
- QList<ModelNode> selectedNodeList = selectionState.selectedModelNodes();
- QmlItemNode qmlItemNode = QmlItemNode(selectedNodeList.first());
-
- if (qmlItemNode.isValid() && qmlItemNode.hasInstanceParentItem()) {
-
- ModelNode gridNode;
- {
- RewriterTransaction transaction(selectionState.qmlModelView());
-
- QmlItemNode parentNode = qmlItemNode.instanceParentItem();
-
- gridNode = selectionState.qmlModelView()->createModelNode(gridLayoutType, gridMetaInfo.majorVersion(), gridMetaInfo.minorVersion());
- gridNode.variantProperty("columns") = int(sqrt(double(selectedNodeList.count())));
-
- reparentTo(gridNode, parentNode);
- }
-
- {
- RewriterTransaction transaction(selectionState.qmlModelView());
-
- QPoint upperLeftPosition = getUpperLeftPosition(selectedNodeList);
- gridNode.variantProperty("x") = upperLeftPosition.x();
- gridNode.variantProperty("y") = upperLeftPosition.y();
-
- QList<ModelNode> sortedSelectedNodes = selectedNodeList;
- qSort(sortedSelectedNodes.begin(), sortedSelectedNodes.end(), compareByGrid);
+ layoutHelperFunction(selectionContext, "QtQuick.Layouts.ColumnLayout", compareByY);
+}
- foreach (ModelNode selectedNode, sortedSelectedNodes) {
- reparentTo(selectedNode, gridNode);
- selectedNode.removeProperty("x");
- selectedNode.removeProperty("y");
- }
- }
- }
+void layoutGridLayout(const SelectionContext &selectionContext)
+{
+ layoutHelperFunction(selectionContext, "QtQuick.Layouts.GridLayout", compareByGrid);
}
} // namespace Mode
diff --git a/src/plugins/qmldesigner/components/componentcore/selectioncontext.cpp b/src/plugins/qmldesigner/components/componentcore/selectioncontext.cpp
index 60ee47798a..5c01a69deb 100644
--- a/src/plugins/qmldesigner/components/componentcore/selectioncontext.cpp
+++ b/src/plugins/qmldesigner/components/componentcore/selectioncontext.cpp
@@ -29,23 +29,21 @@
#include "selectioncontext.h"
+#include <qmlstate.h>
+
namespace QmlDesigner {
SelectionContext::SelectionContext() :
- m_isInBaseState(false),
m_toggled(false)
{
}
-SelectionContext::SelectionContext(QmlModelView *qmlModelView) :
- m_qmlModelView(qmlModelView),
- m_isInBaseState(qmlModelView->currentState().isBaseState()),
+SelectionContext::SelectionContext(AbstractView *view) :
+ m_view(view),
m_toggled(false)
{
- if (qmlModelView && qmlModelView->model())
- m_selectedModelNodes = qmlModelView->selectedModelNodes();
}
void SelectionContext::setTargetNode(const ModelNode &modelNode)
@@ -60,30 +58,37 @@ ModelNode SelectionContext::targetNode() const
bool SelectionContext::singleNodeIsSelected() const
{
- return m_selectedModelNodes.count() == 1;
+ return view()->hasSingleSelectedModelNode();
}
bool SelectionContext::isInBaseState() const
{
- return m_isInBaseState;
+ return view()->currentState().isBaseState();
}
ModelNode SelectionContext::currentSingleSelectedNode() const
{
- if (m_selectedModelNodes.count() != 1)
- return ModelNode();
+ return view()->singleSelectedModelNode();
+}
- return m_selectedModelNodes.first();
+ModelNode SelectionContext::firstSelectedModelNode() const
+{
+ return view()->firstSelectedModelNode();
}
QList<ModelNode> SelectionContext::selectedModelNodes() const
{
- return m_selectedModelNodes;
+ return view()->selectedModelNodes();
+}
+
+bool SelectionContext::hasSingleSelectedModelNode() const
+{
+ return view()->hasSelectedModelNodes();
}
-QmlModelView *SelectionContext::qmlModelView() const
+AbstractView *SelectionContext::view() const
{
- return m_qmlModelView.data();
+ return m_view.data();
}
void SelectionContext::setShowSelectionTools(bool show)
@@ -96,12 +101,12 @@ bool SelectionContext::showSelectionTools() const
return m_showSelectionTools;
}
-void SelectionContext::setScenePos(const QPoint &postition)
+void SelectionContext::setScenePosition(const QPointF &postition)
{
m_scenePosition = postition;
}
-QPoint SelectionContext::scenePos() const
+QPointF SelectionContext::scenePosition() const
{
return m_scenePosition;
}
@@ -118,7 +123,7 @@ bool SelectionContext::toggled() const
bool SelectionContext::isValid() const
{
- return qmlModelView() && qmlModelView()->model() && qmlModelView()->nodeInstanceView();
+ return view() && view()->model();
}
} //QmlDesigner
diff --git a/src/plugins/qmldesigner/components/componentcore/selectioncontext.h b/src/plugins/qmldesigner/components/componentcore/selectioncontext.h
index f8226616ab..e5a4705af4 100644
--- a/src/plugins/qmldesigner/components/componentcore/selectioncontext.h
+++ b/src/plugins/qmldesigner/components/componentcore/selectioncontext.h
@@ -28,7 +28,8 @@
****************************************************************************/
#include <qmldesignercorelib_global.h>
-#include <qmlmodelview.h>
+#include <abstractview.h>
+#include <QPointF>
#ifndef SELECTIONCONTEXT_H
#define SELECTIONCONTEXT_H
@@ -39,7 +40,7 @@ class QMLDESIGNERCORE_EXPORT SelectionContext {
public:
SelectionContext();
- SelectionContext(QmlModelView *qmlModelView);
+ SelectionContext(AbstractView *view);
void setTargetNode(const ModelNode &modelNode);
ModelNode targetNode() const;
@@ -48,15 +49,17 @@ public:
bool isInBaseState() const;
ModelNode currentSingleSelectedNode() const;
+ ModelNode firstSelectedModelNode() const;
QList<ModelNode> selectedModelNodes() const;
+ bool hasSingleSelectedModelNode() const;
- QmlModelView *qmlModelView() const;
+ AbstractView *view() const;
void setShowSelectionTools(bool show);
bool showSelectionTools() const;
- void setScenePos(const QPoint &postition);
- QPoint scenePos() const;
+ void setScenePosition(const QPointF &postition);
+ QPointF scenePosition() const;
void setToggled(bool toggled);
bool toggled() const;
@@ -64,12 +67,10 @@ public:
bool isValid() const;
private:
- QWeakPointer<QmlModelView> m_qmlModelView;
+ QWeakPointer<AbstractView> m_view;
ModelNode m_targetNode;
- bool m_isInBaseState;
- QList<ModelNode> m_selectedModelNodes;
bool m_showSelectionTools;
- QPoint m_scenePosition;
+ QPointF m_scenePosition;
bool m_toggled;
};
diff --git a/src/plugins/qmldesigner/components/debugview/debugview.cpp b/src/plugins/qmldesigner/components/debugview/debugview.cpp
index 7bf56a9d63..2b7823ccbe 100644
--- a/src/plugins/qmldesigner/components/debugview/debugview.cpp
+++ b/src/plugins/qmldesigner/components/debugview/debugview.cpp
@@ -56,7 +56,7 @@ namespace QmlDesigner {
namespace Internal {
-DebugView::DebugView(QObject *parent) : QmlModelView(parent),
+DebugView::DebugView(QObject *parent) : AbstractView(parent),
m_debugViewWidget(new DebugViewWidget)
{
}
@@ -70,13 +70,13 @@ void DebugView::modelAttached(Model *model)
log(tr("Model attached"), tr("FileName %1").arg(model->fileUrl().toLocalFile()));
m_debugViewWidget->setDebugViewEnabled(isDebugViewEnabled());
qDebug() << "enabled: " << isDebugViewEnabled();
- QmlModelView::modelAttached(model);
+ AbstractView::modelAttached(model);
}
void DebugView::modelAboutToBeDetached(Model *model)
{
log(tr("Model detached"), tr("FileName %1").arg(model->fileUrl().toLocalFile()));
- QmlModelView::modelAboutToBeDetached(model);
+ AbstractView::modelAboutToBeDetached(model);
}
void DebugView::importsChanged(const QList<Import> &addedImports, const QList<Import> &removedImports)
@@ -85,12 +85,12 @@ void DebugView::importsChanged(const QList<Import> &addedImports, const QList<Im
QString message;
message += tr("Added imports:") += lineBreak;
foreach (const Import &import, addedImports) {
- message += import.toString() += lineBreak;
+ message += import.toImportString() += lineBreak;
}
message += tr("Removed imports:") += lineBreak;
foreach (const Import &import, removedImports) {
- message += import.toString() += lineBreak;
+ message += import.toImportString() += lineBreak;
}
log(tr("Imports changed:"), message);
@@ -371,6 +371,31 @@ void DebugView::nodeSourceChanged(const ModelNode &modelNode, const QString &new
}
}
+void DebugView::nodeRemoved(const ModelNode &/*removedNode*/, const NodeAbstractProperty &/*parentProperty*/, AbstractView::PropertyChangeFlags /*propertyChange*/)
+{
+
+}
+
+void DebugView::nodeAboutToBeReparented(const ModelNode &/*node*/, const NodeAbstractProperty &/*newPropertyParent*/, const NodeAbstractProperty &/*oldPropertyParent*/, AbstractView::PropertyChangeFlags /*propertyChange*/)
+{
+
+}
+
+void DebugView::instancesToken(const QString &/*tokenName*/, int /*tokenNumber*/, const QVector<ModelNode> &/*nodeVector*/)
+{
+
+}
+
+void DebugView::currentStateChanged(const ModelNode &/*node*/)
+{
+
+}
+
+void DebugView::nodeOrderChanged(const NodeListProperty &/*listProperty*/, const ModelNode &/*movedNode*/, int /*oldIndex*/)
+{
+
+}
+
void DebugView::log(const QString &title, const QString &message, bool highlight)
{
m_debugViewWidget->addLogMessage(title, message, highlight);
diff --git a/src/plugins/qmldesigner/components/debugview/debugview.h b/src/plugins/qmldesigner/components/debugview/debugview.h
index 12687fab8f..88915ce68f 100644
--- a/src/plugins/qmldesigner/components/debugview/debugview.h
+++ b/src/plugins/qmldesigner/components/debugview/debugview.h
@@ -30,7 +30,7 @@
#ifndef DEBUGVIEW_H
#define DEBUGVIEW_H
-#include <qmlmodelview.h>
+#include <abstractview.h>
#include <QPointer>
namespace QmlDesigner {
@@ -39,7 +39,7 @@ namespace Internal {
class DebugViewWidget;
-class DebugView : public QmlModelView
+class DebugView : public AbstractView
{
Q_OBJECT
@@ -87,6 +87,12 @@ public:
void nodeSourceChanged(const ModelNode &modelNode, const QString &newNodeSource) QTC_OVERRIDE;
+ void nodeRemoved(const ModelNode &removedNode, const NodeAbstractProperty &parentProperty, PropertyChangeFlags propertyChange) QTC_OVERRIDE;
+ void nodeAboutToBeReparented(const ModelNode &node, const NodeAbstractProperty &newPropertyParent, const NodeAbstractProperty &oldPropertyParent, PropertyChangeFlags propertyChange) QTC_OVERRIDE;
+ void instancesToken(const QString &tokenName, int tokenNumber, const QVector<ModelNode> &nodeVector) QTC_OVERRIDE;
+ void currentStateChanged(const ModelNode &node) QTC_OVERRIDE;
+ void nodeOrderChanged(const NodeListProperty &listProperty, const ModelNode &movedNode, int oldIndex) QTC_OVERRIDE;
+
protected:
void log(const QString &title, const QString &message, bool highlight = false);
void logInstance(const QString &title, const QString &message, bool highlight = false);
diff --git a/src/plugins/qmldesigner/components/formeditor/abstractformeditortool.cpp b/src/plugins/qmldesigner/components/formeditor/abstractformeditortool.cpp
index 56688e1c53..0f70ca0cd7 100644
--- a/src/plugins/qmldesigner/components/formeditor/abstractformeditortool.cpp
+++ b/src/plugins/qmldesigner/components/formeditor/abstractformeditortool.cpp
@@ -77,6 +77,19 @@ QList<FormEditorItem*> AbstractFormEditorTool::items() const
return m_itemList;
}
+QList<FormEditorItem *> AbstractFormEditorTool::toFormEditorItemList(const QList<QGraphicsItem *> &itemList)
+{
+ QList<FormEditorItem *> formEditorItemList;
+
+ foreach (QGraphicsItem *graphicsItem, itemList) {
+ FormEditorItem *formEditorItem = qgraphicsitem_cast<FormEditorItem*>(graphicsItem);
+ if (formEditorItem)
+ formEditorItemList.append(formEditorItem);
+ }
+
+ return formEditorItemList;
+}
+
bool AbstractFormEditorTool::topItemIsMovable(const QList<QGraphicsItem*> & itemList)
{
QGraphicsItem *firstSelectableItem = topMovableGraphicsItem(itemList);
@@ -84,7 +97,7 @@ bool AbstractFormEditorTool::topItemIsMovable(const QList<QGraphicsItem*> & item
return false;
FormEditorItem *formEditorItem = FormEditorItem::fromQGraphicsItem(firstSelectableItem);
- QList<QmlItemNode> selectedNodes = view()->selectedQmlItemNodes();
+ QList<ModelNode> selectedNodes = view()->selectedModelNodes();
if (formEditorItem != 0
&& selectedNodes.contains(formEditorItem->qmlItemNode()))
@@ -96,15 +109,16 @@ bool AbstractFormEditorTool::topItemIsMovable(const QList<QGraphicsItem*> & item
bool AbstractFormEditorTool::topSelectedItemIsMovable(const QList<QGraphicsItem*> &itemList)
{
- QList<QmlItemNode> selectedNodes = view()->selectedQmlItemNodes();
+ QList<ModelNode> selectedNodes = view()->selectedModelNodes();
foreach (QGraphicsItem *item, itemList) {
FormEditorItem *formEditorItem = FormEditorItem::fromQGraphicsItem(item);
if (formEditorItem
&& selectedNodes.contains(formEditorItem->qmlItemNode())
&& formEditorItem->qmlItemNode().instanceIsMovable()
+ && formEditorItem->qmlItemNode().modelIsMovable()
&& !formEditorItem->qmlItemNode().instanceIsInLayoutable()
- && (formEditorItem->qmlItemNode().hasShowContent()))
+ && (formEditorItem->qmlItemNode().instanceHasShowContent()))
return true;
}
@@ -113,6 +127,7 @@ bool AbstractFormEditorTool::topSelectedItemIsMovable(const QList<QGraphicsItem*
if (formEditorItem
&& formEditorItem->qmlItemNode().isValid()
&& formEditorItem->qmlItemNode().instanceIsMovable()
+ && formEditorItem->qmlItemNode().modelIsMovable()
&& !formEditorItem->qmlItemNode().instanceIsInLayoutable()
&& selectedNodes.contains(formEditorItem->qmlItemNode()))
return true;
@@ -137,12 +152,16 @@ QGraphicsItem *AbstractFormEditorTool::topMovableGraphicsItem(const QList<QGraph
return 0;
}
-FormEditorItem *AbstractFormEditorTool::topMovableFormEditorItem(const QList<QGraphicsItem*> &itemList)
+FormEditorItem *AbstractFormEditorTool::topMovableFormEditorItem(const QList<QGraphicsItem*> &itemList, bool selectOnlyContentItems)
{
foreach (QGraphicsItem *item, itemList) {
FormEditorItem *formEditorItem = FormEditorItem::fromQGraphicsItem(item);
if (formEditorItem
- && (formEditorItem->qmlItemNode().hasShowContent()))
+ && formEditorItem->qmlItemNode().isValid()
+ && !formEditorItem->qmlItemNode().instanceIsInLayoutable()
+ && formEditorItem->qmlItemNode().instanceIsMovable()
+ && formEditorItem->qmlItemNode().modelIsMovable()
+ && (formEditorItem->qmlItemNode().instanceHasShowContent() || !selectOnlyContentItems))
return formEditorItem;
}
@@ -187,14 +206,6 @@ void AbstractFormEditorTool::dragEnterEvent(QGraphicsSceneDragDropEvent * event)
}
}
-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));
-}
-
void AbstractFormEditorTool::mousePressEvent(const QList<QGraphicsItem*> & /*itemList*/, QGraphicsSceneMouseEvent *event)
{
if (event->button() == Qt::RightButton)
@@ -213,8 +224,10 @@ void AbstractFormEditorTool::mouseDoubleClickEvent(const QList<QGraphicsItem*> &
{
if (event->button() == Qt::LeftButton) {
FormEditorItem *formEditorItem = topFormEditorItem(itemList);
- if (formEditorItem)
- view()->changeToCustomTool(formEditorItem->qmlItemNode().modelNode());
+ if (formEditorItem) {
+ view()->setSelectedModelNode(formEditorItem->qmlItemNode().modelNode());
+ view()->changeToCustomTool();
+ }
}
}
diff --git a/src/plugins/qmldesigner/components/formeditor/abstractformeditortool.h b/src/plugins/qmldesigner/components/formeditor/abstractformeditortool.h
index 43c2113709..0ec408738d 100644
--- a/src/plugins/qmldesigner/components/formeditor/abstractformeditortool.h
+++ b/src/plugins/qmldesigner/components/formeditor/abstractformeditortool.h
@@ -89,8 +89,9 @@ public:
void setItems(const QList<FormEditorItem*> &itemList);
QList<FormEditorItem*> items() const;
+ static QList<FormEditorItem*> toFormEditorItemList(const QList<QGraphicsItem*> &itemList);
static QGraphicsItem* topMovableGraphicsItem(const QList<QGraphicsItem*> &itemList);
- static FormEditorItem* topMovableFormEditorItem(const QList<QGraphicsItem*> &itemList);
+ static FormEditorItem* topMovableFormEditorItem(const QList<QGraphicsItem*> &itemList, bool selectOnlyContentItems);
bool topItemIsMovable(const QList<QGraphicsItem*> &itemList);
bool topSelectedItemIsMovable(const QList<QGraphicsItem*> &itemList);
bool topItemIsResizeHandle(const QList<QGraphicsItem*> &itemList);
diff --git a/src/plugins/qmldesigner/components/formeditor/anchorindicator.cpp b/src/plugins/qmldesigner/components/formeditor/anchorindicator.cpp
new file mode 100644
index 0000000000..91ad8bdf67
--- /dev/null
+++ b/src/plugins/qmldesigner/components/formeditor/anchorindicator.cpp
@@ -0,0 +1,178 @@
+/****************************************************************************
+**
+** 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 "anchorindicator.h"
+
+#include "qmlanchors.h"
+#include "anchorindicatorgraphicsitem.h"
+#include <QGraphicsScene>
+#include <QGraphicsPathItem>
+
+namespace QmlDesigner {
+
+AnchorIndicator::AnchorIndicator(LayerItem *layerItem)
+ : m_layerItem(layerItem)
+{
+}
+
+AnchorIndicator::AnchorIndicator()
+{
+}
+
+AnchorIndicator::~AnchorIndicator()
+{
+ clear();
+}
+
+void AnchorIndicator::show()
+{
+ if (m_indicatorTopShape)
+ m_indicatorTopShape->show();
+
+ if (m_indicatorBottomShape)
+ m_indicatorBottomShape->show();
+
+ if (m_indicatorLeftShape)
+ m_indicatorLeftShape->show();
+
+ if (m_indicatorRightShape)
+ m_indicatorRightShape->show();
+}
+
+void AnchorIndicator::hide()
+{
+ if (m_indicatorTopShape)
+ m_indicatorTopShape->hide();
+
+ if (m_indicatorBottomShape)
+ m_indicatorBottomShape->hide();
+
+ if (m_indicatorLeftShape)
+ m_indicatorLeftShape->hide();
+
+ if (m_indicatorRightShape)
+ m_indicatorRightShape->hide();
+}
+
+void AnchorIndicator::clear()
+{
+ delete m_indicatorTopShape;
+ delete m_indicatorBottomShape;
+ delete m_indicatorLeftShape;
+ delete m_indicatorRightShape;
+}
+
+void AnchorIndicator::setItems(const QList<FormEditorItem *> &itemList)
+{
+ clear();
+
+ if (itemList.count() == 1) {
+ m_formEditorItem = itemList.first();
+ QmlItemNode sourceQmlItemNode = m_formEditorItem->qmlItemNode();
+ if (!sourceQmlItemNode.modelNode().isRootNode()) {
+ QmlAnchors qmlAnchors = sourceQmlItemNode.anchors();
+
+ if (qmlAnchors.modelHasAnchor(AnchorLine::Top)) {
+ m_indicatorTopShape = new AnchorIndicatorGraphicsItem(m_layerItem.data());
+ m_indicatorTopShape->updateAnchorIndicator(AnchorLine(sourceQmlItemNode, AnchorLine::Top),
+ qmlAnchors.modelAnchor(AnchorLine::Top));
+ }
+
+ if (qmlAnchors.modelHasAnchor(AnchorLine::Bottom)) {
+ m_indicatorBottomShape = new AnchorIndicatorGraphicsItem(m_layerItem.data());
+ m_indicatorBottomShape->updateAnchorIndicator(AnchorLine(sourceQmlItemNode, AnchorLine::Bottom),
+ qmlAnchors.modelAnchor(AnchorLine::Bottom));
+ }
+
+ if (qmlAnchors.modelHasAnchor(AnchorLine::Left)) {
+ m_indicatorLeftShape = new AnchorIndicatorGraphicsItem(m_layerItem.data());
+ m_indicatorLeftShape->updateAnchorIndicator(AnchorLine(sourceQmlItemNode, AnchorLine::Left),
+ qmlAnchors.modelAnchor(AnchorLine::Left));
+ }
+
+ if (qmlAnchors.modelHasAnchor(AnchorLine::Right)) {
+ m_indicatorRightShape = new AnchorIndicatorGraphicsItem(m_layerItem.data());
+ m_indicatorRightShape->updateAnchorIndicator(AnchorLine(sourceQmlItemNode, AnchorLine::Right),
+ qmlAnchors.modelAnchor(AnchorLine::Right));
+ }
+ }
+ }
+}
+
+void AnchorIndicator::updateItems(const QList<FormEditorItem *> &itemList)
+{
+ foreach (FormEditorItem *formEditorItem, itemList) {
+ if (formEditorItem == m_formEditorItem) {
+ QmlItemNode sourceQmlItemNode = m_formEditorItem->qmlItemNode();
+ if (!sourceQmlItemNode.modelNode().isRootNode()) {
+ QmlAnchors qmlAnchors = formEditorItem->qmlItemNode().anchors();
+
+ if (qmlAnchors.modelHasAnchor(AnchorLine::Top)) {
+ if (m_indicatorTopShape.isNull())
+ m_indicatorTopShape = new AnchorIndicatorGraphicsItem(m_layerItem.data());
+ m_indicatorTopShape->updateAnchorIndicator(AnchorLine(sourceQmlItemNode, AnchorLine::Top),
+ qmlAnchors.modelAnchor(AnchorLine::Top));
+ } else {
+ delete m_indicatorTopShape;
+ }
+
+ if (qmlAnchors.modelHasAnchor(AnchorLine::Bottom)) {
+ if (m_indicatorBottomShape.isNull())
+ m_indicatorBottomShape = new AnchorIndicatorGraphicsItem(m_layerItem.data());
+ m_indicatorBottomShape->updateAnchorIndicator(AnchorLine(sourceQmlItemNode, AnchorLine::Bottom),
+ qmlAnchors.modelAnchor(AnchorLine::Bottom));
+ } else {
+ delete m_indicatorBottomShape;
+ }
+
+ if (qmlAnchors.modelHasAnchor(AnchorLine::Left)) {
+ if (m_indicatorLeftShape.isNull())
+ m_indicatorLeftShape = new AnchorIndicatorGraphicsItem(m_layerItem.data());
+ m_indicatorLeftShape->updateAnchorIndicator(AnchorLine(sourceQmlItemNode, AnchorLine::Left),
+ qmlAnchors.modelAnchor(AnchorLine::Left));
+ } else {
+ delete m_indicatorLeftShape;
+ }
+
+ if (qmlAnchors.modelHasAnchor(AnchorLine::Right)) {
+ if (m_indicatorRightShape.isNull())
+ m_indicatorRightShape = new AnchorIndicatorGraphicsItem(m_layerItem.data());
+ m_indicatorRightShape->updateAnchorIndicator(AnchorLine(sourceQmlItemNode, AnchorLine::Right),
+ qmlAnchors.modelAnchor(AnchorLine::Right));
+ } else {
+ delete m_indicatorRightShape;
+ }
+ }
+
+ return;
+ }
+ }
+}
+
+} // namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/components/formeditor/anchorindicator.h b/src/plugins/qmldesigner/components/formeditor/anchorindicator.h
new file mode 100644
index 0000000000..307fcc3e14
--- /dev/null
+++ b/src/plugins/qmldesigner/components/formeditor/anchorindicator.h
@@ -0,0 +1,70 @@
+/****************************************************************************
+**
+** 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 QMLDESIGNER_ANCHORINDICATOR_H
+#define QMLDESIGNER_ANCHORINDICATOR_H
+
+#include <QPointer>
+#include "layeritem.h"
+#include "formeditoritem.h"
+
+
+namespace QmlDesigner {
+
+class FormEditorItem;
+class AnchorIndicatorGraphicsItem;
+
+class AnchorIndicator
+{
+public:
+ AnchorIndicator(LayerItem *layerItem);
+ AnchorIndicator();
+ ~AnchorIndicator();
+
+ void show();
+ void hide();
+
+ void clear();
+
+ void setItems(const QList<FormEditorItem*> &itemList);
+ void updateItems(const QList<FormEditorItem*> &itemList);
+
+
+private:
+ QPointer<LayerItem> m_layerItem;
+ QPointer<FormEditorItem> m_formEditorItem;
+ QPointer<AnchorIndicatorGraphicsItem> m_indicatorTopShape;
+ QPointer<AnchorIndicatorGraphicsItem> m_indicatorBottomShape;
+ QPointer<AnchorIndicatorGraphicsItem> m_indicatorLeftShape;
+ QPointer<AnchorIndicatorGraphicsItem> m_indicatorRightShape;
+};
+
+} // namespace QmlDesigner
+
+#endif // QMLDESIGNER_ANCHORINDICATOR_H
diff --git a/src/plugins/qmldesigner/components/formeditor/anchorindicatorgraphicsitem.cpp b/src/plugins/qmldesigner/components/formeditor/anchorindicatorgraphicsitem.cpp
new file mode 100644
index 0000000000..5f61d1a81e
--- /dev/null
+++ b/src/plugins/qmldesigner/components/formeditor/anchorindicatorgraphicsitem.cpp
@@ -0,0 +1,262 @@
+/****************************************************************************
+**
+** 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 "anchorindicatorgraphicsitem.h"
+
+#include <QPainter>
+#include <QPainterPath>
+
+namespace QmlDesigner {
+
+AnchorIndicatorGraphicsItem::AnchorIndicatorGraphicsItem(QGraphicsItem *parent) :
+ QGraphicsObject(parent)
+{
+ setZValue(-3);
+}
+
+int startAngleForAnchorLine(const AnchorLine::Type &anchorLineType)
+{
+ switch (anchorLineType) {
+ case AnchorLine::Top:
+ return 0;
+ case AnchorLine::Bottom:
+ return 180 * 16;
+ case AnchorLine::Left:
+ return 90 * 16;
+ case AnchorLine::Right:
+ return 270 * 16;
+ default:
+ return 0;
+ }
+}
+
+void AnchorIndicatorGraphicsItem::paint(QPainter *painter, const QStyleOptionGraphicsItem * /* option */, QWidget * /* widget */)
+{
+ painter->save();
+
+ QPen linePen(QColor(0, 0, 0, 150));
+ linePen.setDashPattern(QVector<double>() << 3. << 2.);
+
+ painter->setPen(linePen);
+
+ painter->drawLine(m_startPoint, m_firstControlPoint);
+ painter->drawLine(m_firstControlPoint, m_secondControlPoint);
+ painter->drawLine(m_secondControlPoint, m_endPoint);
+
+ linePen.setColor(QColor(255, 255, 255, 150));
+ linePen.setDashPattern(QVector<double>() << 2. << 3.);
+ linePen.setDashOffset(2.);
+
+ painter->setPen(linePen);
+
+ painter->drawLine(m_startPoint, m_firstControlPoint);
+ painter->drawLine(m_firstControlPoint, m_secondControlPoint);
+ painter->drawLine(m_secondControlPoint, m_endPoint);
+
+ static QRectF bumpRectangle(0., 0., 8., 8.);
+
+ painter->setPen(QPen(QColor(0, 255 , 0), 2));
+ painter->drawLine(m_sourceAnchorLineFirstPoint, m_sourceAnchorLineSecondPoint);
+
+ bumpRectangle.moveTo(m_startPoint.x() - 4., m_startPoint.y() - 4.);
+ painter->setBrush(painter->pen().color());
+ painter->setRenderHint(QPainter::Antialiasing, true);
+ painter->drawChord(bumpRectangle, startAngleForAnchorLine(m_sourceAnchorLineType), 180 * 16);
+ painter->setRenderHint(QPainter::Antialiasing, false);
+
+ painter->setPen(QPen(QColor(0, 0 , 255), 2));
+ painter->drawLine(m_targetAnchorLineFirstPoint, m_targetAnchorLineSecondPoint);
+
+ bumpRectangle.moveTo(m_endPoint.x() - 4., m_endPoint.y() - 4.);
+ painter->setBrush(painter->pen().color());
+ painter->setRenderHint(QPainter::Antialiasing, true);
+ painter->drawChord(bumpRectangle, startAngleForAnchorLine(m_targetAnchorLineType), 180 * 16);
+ painter->setRenderHint(QPainter::Antialiasing, false);
+
+ painter->restore();
+}
+
+QRectF AnchorIndicatorGraphicsItem::boundingRect() const
+{
+ return m_boundingRect;
+}
+
+static QPointF createParentAnchorPoint(const QmlItemNode &parentQmlItemNode, AnchorLine::Type anchorLineType, const QmlItemNode &childQmlItemNode)
+{
+ QRectF parentBoundingRect = parentQmlItemNode.instanceSceneTransform().mapRect(parentQmlItemNode.instanceBoundingRect().adjusted(0., 0., 1., 1.));
+ QRectF childBoundingRect = childQmlItemNode.instanceSceneTransform().mapRect(childQmlItemNode.instanceBoundingRect().adjusted(0., 0., 1., 1.));
+
+ QPointF anchorPoint;
+
+ switch (anchorLineType) {
+ case AnchorLine::Top:
+ anchorPoint = QPointF(childBoundingRect.center().x(), parentBoundingRect.top());
+ break;
+ case AnchorLine::Bottom:
+ anchorPoint = QPointF(childBoundingRect.center().x(), parentBoundingRect.bottom());
+ break;
+ case AnchorLine::Left:
+ anchorPoint = QPointF(parentBoundingRect.left(), childBoundingRect.center().y());
+ break;
+ case AnchorLine::Right:
+ anchorPoint = QPointF(parentBoundingRect.right(), childBoundingRect.center().y());
+ break;
+ default:
+ break;
+ }
+
+ return anchorPoint;
+}
+
+static QPointF createAnchorPoint(const QmlItemNode &qmlItemNode, AnchorLine::Type anchorLineType)
+{
+ QRectF boundingRect = qmlItemNode.instanceBoundingRect().adjusted(0., 0., 1., 1.);
+
+ QPointF anchorPoint;
+
+ switch (anchorLineType) {
+ case AnchorLine::Top:
+ anchorPoint = QPointF(boundingRect.center().x(), boundingRect.top());
+ break;
+ case AnchorLine::Bottom:
+ anchorPoint = QPointF(boundingRect.center().x(), boundingRect.bottom());
+ break;
+ case AnchorLine::Left:
+ anchorPoint = QPointF(boundingRect.left(), boundingRect.center().y());
+ break;
+ case AnchorLine::Right:
+ anchorPoint = QPointF(boundingRect.right(), boundingRect.center().y());
+ break;
+ default:
+ break;
+ }
+
+ return qmlItemNode.instanceSceneTransform().map(anchorPoint);
+}
+
+static QPointF createControlPoint(const QPointF &firstEditPoint, AnchorLine::Type anchorLineType, const QPointF &secondEditPoint)
+{
+ QPointF controlPoint = firstEditPoint;
+
+ switch (anchorLineType) {
+ case AnchorLine::Top:
+ case AnchorLine::Bottom:
+ controlPoint.ry() += (secondEditPoint.y() - firstEditPoint.y()) / 2.0;
+ break;
+ case AnchorLine::Left:
+ case AnchorLine::Right:
+ controlPoint.rx() += (secondEditPoint.x() - firstEditPoint.x()) / 2.0;
+ break;
+ default:
+ break;
+ }
+
+ return controlPoint;
+}
+
+static void updateAnchorLinePoints(QPointF *firstPoint, QPointF *secondPoint, const AnchorLine &anchorLine)
+{
+ QRectF boundingRectangle = anchorLine.qmlItemNode().instanceBoundingRect().adjusted(0., 0., 1., 1.);
+
+ switch (anchorLine.type()) {
+ case AnchorLine::Top:
+ *firstPoint = boundingRectangle.topLeft();
+ *secondPoint = boundingRectangle.topRight();
+ break;
+ case AnchorLine::Bottom:
+ *firstPoint = boundingRectangle.bottomLeft();
+ *secondPoint = boundingRectangle.bottomRight();
+ break;
+ case AnchorLine::Left:
+ *firstPoint = boundingRectangle.topLeft();
+ *secondPoint = boundingRectangle.bottomLeft();
+ break;
+ case AnchorLine::Right:
+ *firstPoint = boundingRectangle.topRight();
+ *secondPoint = boundingRectangle.bottomRight();
+ break;
+ default:
+ break;
+ }
+
+ *firstPoint = anchorLine.qmlItemNode().instanceSceneTransform().map(*firstPoint);
+ *secondPoint = anchorLine.qmlItemNode().instanceSceneTransform().map(*secondPoint);
+}
+
+void AnchorIndicatorGraphicsItem::updateAnchorIndicator(const AnchorLine &sourceAnchorLine, const AnchorLine targetAnchorLine)
+{
+ m_sourceAnchorLineType = sourceAnchorLine.type();
+ m_targetAnchorLineType = targetAnchorLine.type();
+
+ m_startPoint = createAnchorPoint(sourceAnchorLine.qmlItemNode(), sourceAnchorLine.type());
+
+ if (targetAnchorLine.qmlItemNode() == sourceAnchorLine.qmlItemNode().instanceParentItem())
+ m_endPoint = createParentAnchorPoint(targetAnchorLine.qmlItemNode(), targetAnchorLine.type(), sourceAnchorLine.qmlItemNode());
+ else
+ m_endPoint = createAnchorPoint(targetAnchorLine.qmlItemNode(), targetAnchorLine.type());
+
+ m_firstControlPoint = createControlPoint(m_startPoint, sourceAnchorLine.type(), m_endPoint);
+ m_secondControlPoint = createControlPoint(m_endPoint, targetAnchorLine.type(), m_startPoint);
+
+ updateAnchorLinePoints(&m_sourceAnchorLineFirstPoint, &m_sourceAnchorLineSecondPoint, sourceAnchorLine);
+ updateAnchorLinePoints(&m_targetAnchorLineFirstPoint, &m_targetAnchorLineSecondPoint, targetAnchorLine);
+
+ updateBoundingRect();
+ update();
+}
+
+void AnchorIndicatorGraphicsItem::updateBoundingRect()
+{
+ QPolygonF controlPolygon(QVector<QPointF>()
+ << m_startPoint
+ << m_firstControlPoint
+ << m_secondControlPoint
+ << m_endPoint
+ << m_sourceAnchorLineFirstPoint
+ << m_sourceAnchorLineSecondPoint
+ << m_targetAnchorLineFirstPoint
+ << m_targetAnchorLineSecondPoint
+ );
+
+ m_boundingRect = controlPolygon.boundingRect().adjusted(-10., -10., 10., 10.);
+}
+AnchorLine::Type AnchorIndicatorGraphicsItem::sourceAnchorLineType() const
+{
+ return m_sourceAnchorLineType;
+}
+
+void AnchorIndicatorGraphicsItem::setSourceAnchorLineType(const AnchorLine::Type &sourceAnchorLineType)
+{
+ m_sourceAnchorLineType = sourceAnchorLineType;
+}
+
+
+
+
+} // namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/components/propertyeditor/resetwidget.h b/src/plugins/qmldesigner/components/formeditor/anchorindicatorgraphicsitem.h
index f56f6200d6..75b859a950 100644
--- a/src/plugins/qmldesigner/components/propertyeditor/resetwidget.h
+++ b/src/plugins/qmldesigner/components/formeditor/anchorindicatorgraphicsitem.h
@@ -27,80 +27,47 @@
**
****************************************************************************/
-#ifndef ResetWidget_h
-#define ResetWidget_h
+#ifndef QMLDESIGNER_ANCHORINDICATORGRAPHICSITEM_H
+#define QMLDESIGNER_ANCHORINDICATORGRAPHICSITEM_H
-#include <QGroupBox>
-#include <QPushButton>
+#include <QGraphicsObject>
-QT_BEGIN_NAMESPACE
-class QListWidget;
-class QVBoxLayout;
-class QTableWidget;
-QT_END_NAMESPACE
+#include <qmlanchors.h>
namespace QmlDesigner {
-class ResetWidget : public QGroupBox
+class AnchorIndicatorGraphicsItem : public QGraphicsObject
{
-
Q_OBJECT
-
- Q_PROPERTY(QObject *backendObject READ backendObject WRITE setBackendObject)
-
-public slots:
- void resetView();
-
public:
- ResetWidget(QWidget *parent = 0);
- QObject* backendObject()
- {
- return m_backendObject;
- }
+ explicit AnchorIndicatorGraphicsItem(QGraphicsItem *parent = 0);
- void setBackendObject(QObject* backendObject)
- {
- m_backendObject = backendObject;
- setupView();
- }
- static void registerDeclarativeType();
+ void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
+ QRectF boundingRect() const;
-public slots:
- void buttonPressed(const QString &name);
+ void updateAnchorIndicator(const AnchorLine &sourceAnchorLine, const AnchorLine targetAnchorLine);
+ AnchorLine::Type sourceAnchorLineType() const;
+ void setSourceAnchorLineType(const AnchorLine::Type &sourceAnchorLineType);
-private:
- void setupView();
-
- void addPropertyItem(const QString &name, int row);
-
- QObject* m_backendObject;
- QVBoxLayout *m_vlayout;
- QTableWidget *m_tableWidget;
-
-};
+protected:
+ void updateBoundingRect();
-class ResetWidgetPushButton : public QPushButton
-{
- Q_OBJECT
-
-public slots:
- void myPressed();
- void setName(const QString &name)
- { m_name = name; }
-
-signals:
- void pressed(const QString &name);
-
-public:
- ResetWidgetPushButton(QWidget *parent = 0);
private:
- QString m_name;
-
+ QPointF m_startPoint;
+ QPointF m_firstControlPoint;
+ QPointF m_secondControlPoint;
+ QPointF m_endPoint;
+ QPointF m_sourceAnchorLineFirstPoint;
+ QPointF m_sourceAnchorLineSecondPoint;
+ QPointF m_targetAnchorLineFirstPoint;
+ QPointF m_targetAnchorLineSecondPoint;
+ AnchorLine::Type m_sourceAnchorLineType;
+ AnchorLine::Type m_targetAnchorLineType;
+ QRectF m_boundingRect;
};
-}
-
-#endif //ResetWidget_h
+} // namespace QmlDesigner
+#endif // QMLDESIGNER_ANCHORINDICATORGRAPHICSITEM_H
diff --git a/src/plugins/qmldesigner/components/formeditor/bindingindicator.cpp b/src/plugins/qmldesigner/components/formeditor/bindingindicator.cpp
new file mode 100644
index 0000000000..3753a03959
--- /dev/null
+++ b/src/plugins/qmldesigner/components/formeditor/bindingindicator.cpp
@@ -0,0 +1,191 @@
+/****************************************************************************
+**
+** 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 "bindingindicator.h"
+
+#include "bindingindicatorgraphicsitem.h"
+
+#include <QLineF>
+
+namespace QmlDesigner {
+
+BindingIndicator::BindingIndicator(LayerItem *layerItem)
+ : m_layerItem(layerItem)
+{
+}
+
+BindingIndicator::BindingIndicator()
+{
+}
+
+BindingIndicator::~BindingIndicator()
+{
+ clear();
+}
+
+void BindingIndicator::show()
+{
+ if (m_indicatorTopShape)
+ m_indicatorTopShape->show();
+
+ if (m_indicatorBottomShape)
+ m_indicatorBottomShape->show();
+
+ if (m_indicatorLeftShape)
+ m_indicatorLeftShape->show();
+
+ if (m_indicatorRightShape)
+ m_indicatorRightShape->show();
+}
+
+void BindingIndicator::hide()
+{
+ if (m_indicatorTopShape)
+ m_indicatorTopShape->hide();
+
+ if (m_indicatorBottomShape)
+ m_indicatorBottomShape->hide();
+
+ if (m_indicatorLeftShape)
+ m_indicatorLeftShape->hide();
+
+ if (m_indicatorRightShape)
+ m_indicatorRightShape->hide();
+}
+
+void BindingIndicator::clear()
+{
+ delete m_indicatorTopShape;
+ delete m_indicatorBottomShape;
+ delete m_indicatorLeftShape;
+ delete m_indicatorRightShape;
+}
+
+QLineF topLine(const QmlItemNode &qmlItemNode)
+{
+ QRectF rectangle = qmlItemNode.instanceSceneTransform().mapRect(qmlItemNode.instanceBoundingRect()).adjusted(1, 1, 0, 0);
+
+ return QLineF(rectangle.topLeft(), rectangle.topRight());
+}
+
+QLineF bottomLine(const QmlItemNode &qmlItemNode)
+{
+ QRectF rectangle = qmlItemNode.instanceSceneTransform().mapRect(qmlItemNode.instanceBoundingRect()).adjusted(1, 0, 0, 0);
+
+ return QLineF(rectangle.bottomLeft(), rectangle.bottomRight());
+}
+
+QLineF leftLine(const QmlItemNode &qmlItemNode)
+{
+ QRectF rectangle = qmlItemNode.instanceSceneTransform().mapRect(qmlItemNode.instanceBoundingRect()).adjusted(1, 1, 0, 0);
+
+ return QLineF(rectangle.topLeft(), rectangle.bottomLeft());
+}
+
+QLineF rightLine(const QmlItemNode &qmlItemNode)
+{
+ QRectF rectangle = qmlItemNode.instanceSceneTransform().mapRect(qmlItemNode.instanceBoundingRect()).adjusted(0, 1, 0, 0);
+
+ return QLineF(rectangle.topRight(), rectangle.bottomRight());
+}
+
+void BindingIndicator::setItems(const QList<FormEditorItem *> &itemList)
+{
+ clear();
+
+ if (itemList.count() == 1) {
+ m_formEditorItem = itemList.first();
+ QmlItemNode qmlItemNode = m_formEditorItem->qmlItemNode();
+
+ if (qmlItemNode.hasBindingProperty("x")) {
+ m_indicatorTopShape = new BindingIndicatorGraphicsItem(m_layerItem.data());
+ m_indicatorTopShape->updateBindingIndicator(leftLine(qmlItemNode));
+ }
+
+ if (qmlItemNode.hasBindingProperty("y")) {
+ m_indicatorLeftShape = new BindingIndicatorGraphicsItem(m_layerItem.data());
+ m_indicatorLeftShape->updateBindingIndicator(topLine(qmlItemNode));
+ }
+
+ if (qmlItemNode.hasBindingProperty("width")) {
+ m_indicatorRightShape = new BindingIndicatorGraphicsItem(m_layerItem.data());
+ m_indicatorRightShape->updateBindingIndicator(rightLine(qmlItemNode));
+ }
+
+ if (qmlItemNode.hasBindingProperty("height")) {
+ m_indicatorBottomShape = new BindingIndicatorGraphicsItem(m_layerItem.data());
+ m_indicatorBottomShape->updateBindingIndicator(bottomLine(qmlItemNode));
+ }
+ }
+}
+
+void BindingIndicator::updateItems(const QList<FormEditorItem *> &itemList)
+{
+ foreach (FormEditorItem *formEditorItem, itemList) {
+ if (formEditorItem == m_formEditorItem) {
+ QmlItemNode qmlItemNode = m_formEditorItem->qmlItemNode();
+
+ if (qmlItemNode.hasBindingProperty("x")) {
+ if (m_indicatorTopShape.isNull())
+ m_indicatorTopShape = new BindingIndicatorGraphicsItem(m_layerItem.data());
+ m_indicatorTopShape->updateBindingIndicator(leftLine(qmlItemNode));
+ } else {
+ delete m_indicatorTopShape;
+ }
+
+ if (qmlItemNode.hasBindingProperty("y")) {
+ if (m_indicatorLeftShape.isNull())
+ m_indicatorLeftShape = new BindingIndicatorGraphicsItem(m_layerItem.data());
+ m_indicatorLeftShape->updateBindingIndicator(topLine(qmlItemNode));
+ } else {
+ delete m_indicatorLeftShape;
+ }
+
+ if (qmlItemNode.hasBindingProperty("width")) {
+ if (m_indicatorRightShape.isNull())
+ m_indicatorRightShape = new BindingIndicatorGraphicsItem(m_layerItem.data());
+ m_indicatorRightShape->updateBindingIndicator(rightLine(qmlItemNode));
+ } else {
+ delete m_indicatorRightShape;
+ }
+
+ if (qmlItemNode.hasBindingProperty("height")) {
+ if (m_indicatorBottomShape.isNull())
+ m_indicatorBottomShape = new BindingIndicatorGraphicsItem(m_layerItem.data());
+ m_indicatorBottomShape->updateBindingIndicator(bottomLine(qmlItemNode));
+ } else {
+ delete m_indicatorBottomShape;
+ }
+
+ return;
+ }
+ }
+}
+
+} // namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/components/formeditor/bindingindicator.h b/src/plugins/qmldesigner/components/formeditor/bindingindicator.h
new file mode 100644
index 0000000000..86c728030e
--- /dev/null
+++ b/src/plugins/qmldesigner/components/formeditor/bindingindicator.h
@@ -0,0 +1,68 @@
+/****************************************************************************
+**
+** 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 QMLDESIGNER_BINDINGINDICATOR_H
+#define QMLDESIGNER_BINDINGINDICATOR_H
+
+#include <QPointer>
+#include "layeritem.h"
+#include "formeditoritem.h"
+
+namespace QmlDesigner {
+
+class FormEditorItem;
+class BindingIndicatorGraphicsItem;
+
+class BindingIndicator
+{
+public:
+ BindingIndicator(LayerItem *layerItem);
+ BindingIndicator();
+ ~BindingIndicator();
+
+ void show();
+ void hide();
+
+ void clear();
+
+ void setItems(const QList<FormEditorItem*> &itemList);
+ void updateItems(const QList<FormEditorItem*> &itemList);
+
+private:
+ QPointer<LayerItem> m_layerItem;
+ QPointer<FormEditorItem> m_formEditorItem;
+ QPointer<BindingIndicatorGraphicsItem> m_indicatorTopShape;
+ QPointer<BindingIndicatorGraphicsItem> m_indicatorBottomShape;
+ QPointer<BindingIndicatorGraphicsItem> m_indicatorLeftShape;
+ QPointer<BindingIndicatorGraphicsItem> m_indicatorRightShape;
+};
+
+} // namespace QmlDesigner
+
+#endif // QMLDESIGNER_BINDINGINDICATOR_H
diff --git a/src/plugins/qmldesigner/components/formeditor/bindingindicatorgraphicsitem.cpp b/src/plugins/qmldesigner/components/formeditor/bindingindicatorgraphicsitem.cpp
new file mode 100644
index 0000000000..3876b03602
--- /dev/null
+++ b/src/plugins/qmldesigner/components/formeditor/bindingindicatorgraphicsitem.cpp
@@ -0,0 +1,65 @@
+/****************************************************************************
+**
+** 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 "bindingindicatorgraphicsitem.h"
+
+#include <QPainter>
+
+namespace QmlDesigner {
+
+BindingIndicatorGraphicsItem::BindingIndicatorGraphicsItem(QGraphicsItem *parent) :
+ QGraphicsObject(parent)
+{
+}
+
+void BindingIndicatorGraphicsItem::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/)
+{
+ painter->save();
+ QPen linePen(QColor(255, 0, 0, 255), 2);
+ //linePen.setDashPattern(QVector<double>() << 3. << 2.);
+ painter->setPen(linePen);
+ painter->drawLine(m_bindingLine);
+ painter->restore();
+}
+
+QRectF BindingIndicatorGraphicsItem::boundingRect() const
+{
+ return QRectF(m_bindingLine.x1(),
+ m_bindingLine.y1(),
+ m_bindingLine.x2() - m_bindingLine.x1() + 3,
+ m_bindingLine.y2() - m_bindingLine.y1() + 3);
+}
+
+void BindingIndicatorGraphicsItem::updateBindingIndicator(const QLineF &bindingLine)
+{
+ m_bindingLine = bindingLine;
+ update();
+}
+
+} // namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/components/formeditor/bindingindicatorgraphicsitem.h b/src/plugins/qmldesigner/components/formeditor/bindingindicatorgraphicsitem.h
new file mode 100644
index 0000000000..6e259b70bd
--- /dev/null
+++ b/src/plugins/qmldesigner/components/formeditor/bindingindicatorgraphicsitem.h
@@ -0,0 +1,55 @@
+/****************************************************************************
+**
+** 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 QMLDESIGNER_BINDINGINDICATORGRAPHICSITEM_H
+#define QMLDESIGNER_BINDINGINDICATORGRAPHICSITEM_H
+
+#include <QGraphicsObject>
+
+namespace QmlDesigner {
+
+class BindingIndicatorGraphicsItem : public QGraphicsObject
+{
+ Q_OBJECT
+public:
+ explicit BindingIndicatorGraphicsItem(QGraphicsItem *parent = 0);
+
+ void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
+ QRectF boundingRect() const;
+
+ void updateBindingIndicator(const QLineF &bindingLine);
+
+private:
+ QLineF m_bindingLine;
+
+};
+
+} // namespace QmlDesigner
+
+#endif // QMLDESIGNER_BINDINGINDICATORGRAPHICSITEM_H
diff --git a/src/plugins/qmldesigner/components/formeditor/contentnoteditableindicator.cpp b/src/plugins/qmldesigner/components/formeditor/contentnoteditableindicator.cpp
new file mode 100644
index 0000000000..6763b10f4b
--- /dev/null
+++ b/src/plugins/qmldesigner/components/formeditor/contentnoteditableindicator.cpp
@@ -0,0 +1,106 @@
+/****************************************************************************
+**
+** 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 "contentnoteditableindicator.h"
+#include "nodemetainfo.h"
+
+namespace QmlDesigner {
+
+ContentNotEditableIndicator::ContentNotEditableIndicator(LayerItem *layerItem)
+ : m_layerItem(layerItem)
+{
+
+}
+
+ContentNotEditableIndicator::ContentNotEditableIndicator()
+{
+}
+
+ContentNotEditableIndicator::~ContentNotEditableIndicator()
+{
+ clear();
+}
+
+void ContentNotEditableIndicator::clear()
+{
+ foreach (const EntryPair &entryPair, m_entryList) {
+ delete entryPair.second;
+ entryPair.first->blurContent(false);
+ }
+
+ m_entryList.clear();
+}
+
+bool operator ==(const ContentNotEditableIndicator::EntryPair &firstPair, const ContentNotEditableIndicator::EntryPair &secondPair)
+{
+ return firstPair.first == secondPair.first;
+}
+
+void ContentNotEditableIndicator::setItems(const QList<FormEditorItem*> &itemList)
+{
+ removeEntriesWhichAreNotInTheList(itemList);
+ addAddiationEntries(itemList);
+}
+
+void ContentNotEditableIndicator::addAddiationEntries(const QList<FormEditorItem *> &itemList)
+{
+ foreach (FormEditorItem *formEditorItem, itemList) {
+ if (formEditorItem->qmlItemNode().modelNode().metaInfo().isSubclassOf("QtQuick.Loader", -1, -1)) {
+
+ if (!m_entryList.contains(EntryPair(formEditorItem, 0))) {
+ QGraphicsRectItem *indicatorShape = new QGraphicsRectItem(m_layerItem);
+ QRectF boundingRectangleInSceneSpace = formEditorItem->qmlItemNode().instanceSceneTransform().mapRect(formEditorItem->qmlItemNode().instanceBoundingRect());
+ indicatorShape->setRect(boundingRectangleInSceneSpace);
+ static QBrush brush(QColor(0, 0, 0, 130), Qt::BDiagPattern);
+ indicatorShape->setBrush(brush);
+
+ formEditorItem->blurContent(true);
+
+ m_entryList.append(EntryPair(formEditorItem, indicatorShape));
+ }
+
+ }
+ }
+}
+
+void ContentNotEditableIndicator::removeEntriesWhichAreNotInTheList(const QList<FormEditorItem *> &itemList)
+{
+ QMutableListIterator<EntryPair> entryIterator(m_entryList);
+
+ while (entryIterator.hasNext()) {
+ EntryPair &entryPair = entryIterator.next();
+ if (!itemList.contains(entryPair.first)) {
+ delete entryPair.second;
+ entryPair.first->blurContent(false);
+ entryIterator.remove();
+ }
+ }
+}
+
+} // namespace QmlDesigner
diff --git a/src/plugins/qt4projectmanager/qtuicodemodelsupport.h b/src/plugins/qmldesigner/components/formeditor/contentnoteditableindicator.h
index 58d645ea22..2567bfaab1 100644
--- a/src/plugins/qt4projectmanager/qtuicodemodelsupport.h
+++ b/src/plugins/qmldesigner/components/formeditor/contentnoteditableindicator.h
@@ -27,36 +27,38 @@
**
****************************************************************************/
-#ifndef QTUICODEMODELSUPPORT_H
-#define QTUICODEMODELSUPPORT_H
+#ifndef QMLDESIGNER_CONTENTNOTEDITABLEINDICATOR_H
+#define QMLDESIGNER_CONTENTNOTEDITABLEINDICATOR_H
-#include <cpptools/uicodecompletionsupport.h>
+#include <QPointer>
+#include <QGraphicsRectItem>
+#include "layeritem.h"
+#include "formeditoritem.h"
-namespace CPlusPlus {
-class CppModelManagerInterface;
-}
+namespace QmlDesigner {
-namespace Qt4ProjectManager {
-class Qt4Project;
-namespace Internal {
-
-class Qt4UiCodeModelSupport : public CppTools::UiCodeModelSupport
+class ContentNotEditableIndicator
{
- Q_OBJECT
public:
- Qt4UiCodeModelSupport(CppTools::CppModelManagerInterface *modelmanager,
- Qt4Project *project,
- const QString &sourceFile,
- const QString &uiHeaderFile);
- virtual ~Qt4UiCodeModelSupport();
+ typedef QPair<FormEditorItem*, QGraphicsRectItem *> EntryPair;
+
+ ContentNotEditableIndicator(LayerItem *layerItem);
+ ContentNotEditableIndicator();
+ ~ContentNotEditableIndicator();
+
+ void clear();
+
+ void setItems(const QList<FormEditorItem*> &itemList);
+
protected:
- virtual QString uicCommand() const;
- virtual QStringList environment() const;
+ void addAddiationEntries(const QList<FormEditorItem*> &itemList);
+ void removeEntriesWhichAreNotInTheList(const QList<FormEditorItem*> &itemList);
+
private:
- Qt4Project *m_project;
+ QPointer<LayerItem> m_layerItem;
+ QList<EntryPair> m_entryList;
};
+} // namespace QmlDesigner
-} // Internal
-} // Qt4ProjectManager
-#endif // QTUICODEMODELSUPPORT_H
+#endif // QMLDESIGNER_CONTENTNOTEDITABLEINDICATOR_H
diff --git a/src/plugins/qmldesigner/components/formeditor/dragtool.cpp b/src/plugins/qmldesigner/components/formeditor/dragtool.cpp
index 2e58201661..20c1db6b19 100644
--- a/src/plugins/qmldesigner/components/formeditor/dragtool.cpp
+++ b/src/plugins/qmldesigner/components/formeditor/dragtool.cpp
@@ -152,7 +152,7 @@ void DragTool::createQmlItemNode(const ItemLibraryEntry &itemLibraryEntry, QmlIt
FormEditorItem *parentItem = scene()->itemForQmlItemNode(parentNode);
QPointF pos = parentItem->mapFromScene(scenePos);
- m_dragNode = view()->createQmlItemNode(itemLibraryEntry, pos, parentNode);
+ m_dragNode = QmlItemNode::createQmlItemNode(view(), itemLibraryEntry, pos, parentNode);
Q_ASSERT(m_dragNode.modelNode().isValid());
@@ -171,7 +171,7 @@ void DragTool::createQmlItemNodeFromImage(const QString &imageName, QmlItemNode
FormEditorItem *parentItem = scene()->itemForQmlItemNode(parentNode);
QPointF pos = parentItem->mapFromScene(scenePos);
- m_dragNode = view()->createQmlItemNodeFromImage(imageName, pos, parentNode);
+ m_dragNode = QmlItemNode::createQmlItemNodeFromImage(view(), imageName, pos, parentNode);
QList<QmlItemNode> nodeList;
nodeList.append(m_dragNode);
@@ -285,7 +285,7 @@ void DragTool::dropEvent(QGraphicsSceneDragDropEvent * event)
if (m_dragNode.isValid()) {
QList<QmlItemNode> nodeList;
nodeList.append(m_dragNode);
- view()->setSelectedQmlItemNodes(nodeList);
+ view()->setSelectedModelNodes(toModelNodeList(nodeList));
}
m_dragNode = ModelNode();
view()->changeToSelectionTool();
@@ -345,7 +345,7 @@ void DragTool::dragLeaveEvent(QGraphicsSceneDragDropEvent * event)
QmlDesignerItemLibraryDragAndDrop::CustomDragAndDrop::show();
QList<QmlItemNode> nodeList;
- view()->setSelectedQmlItemNodes(nodeList);
+ view()->setSelectedModelNodes(toModelNodeList(nodeList));
view()->changeToSelectionTool();
}
}
diff --git a/src/plugins/qmldesigner/components/formeditor/formeditor.pri b/src/plugins/qmldesigner/components/formeditor/formeditor.pri
index 0b9d1463fd..8968c2f597 100644
--- a/src/plugins/qmldesigner/components/formeditor/formeditor.pri
+++ b/src/plugins/qmldesigner/components/formeditor/formeditor.pri
@@ -30,8 +30,12 @@ SOURCES += formeditoritem.cpp \
formeditorgraphicsview.cpp \
numberseriesaction.cpp \
lineeditaction.cpp \
- formeditorcrumblebar.cpp \
- abstractcustomtool.cpp
+ abstractcustomtool.cpp \
+ anchorindicator.cpp \
+ anchorindicatorgraphicsitem.cpp \
+ bindingindicator.cpp \
+ bindingindicatorgraphicsitem.cpp \
+ contentnoteditableindicator.cpp
HEADERS += formeditorscene.h \
formeditorwidget.h \
formeditoritem.h \
@@ -63,6 +67,10 @@ HEADERS += formeditorscene.h \
formeditorgraphicsview.h \
numberseriesaction.h \
lineeditaction.h \
- formeditorcrumblebar.h \
- abstractcustomtool.h
+ abstractcustomtool.h \
+ anchorindicator.h \
+ anchorindicatorgraphicsitem.h \
+ bindingindicator.h \
+ bindingindicatorgraphicsitem.h \
+ contentnoteditableindicator.h
RESOURCES += formeditor.qrc
diff --git a/src/plugins/qmldesigner/components/formeditor/formeditoritem.cpp b/src/plugins/qmldesigner/components/formeditor/formeditoritem.cpp
index 8bfcd04206..9ed39b9f63 100644
--- a/src/plugins/qmldesigner/components/formeditor/formeditoritem.cpp
+++ b/src/plugins/qmldesigner/components/formeditor/formeditoritem.cpp
@@ -31,7 +31,7 @@
#include "formeditorscene.h"
#include <modelnode.h>
-
+#include <nodemetainfo.h>
#include <QDebug>
#include <QPainter>
@@ -40,7 +40,6 @@
#include <cmath>
-
namespace QmlDesigner {
@@ -54,6 +53,7 @@ FormEditorItem::FormEditorItem(const QmlItemNode &qmlItemNode, FormEditorScene*
m_qmlItemNode(qmlItemNode),
m_borderWidth(1.0),
m_highlightBoundingRect(false),
+ m_blurContent(false),
m_isContentVisible(true),
m_isFormEditorVisible(true)
{
@@ -92,7 +92,6 @@ void FormEditorItem::updateGeometry()
m_boundingRect = qmlItemNode().instanceBoundingRect().adjusted(0, 0, 1., 1.);
m_paintedBoundingRect = qmlItemNode().instancePaintedBoundingRect().united(m_boundingRect);
setTransform(qmlItemNode().instanceTransformWithContentTransform());
- setTransform(m_attentionTransform, true);
//the property for zValue is called z in QGraphicsObject
if (qmlItemNode().instanceValue("z").isValid())
setZValue(qmlItemNode().instanceValue("z").toDouble());
@@ -104,67 +103,24 @@ void FormEditorItem::updateVisibilty()
// setOpacity(nodeInstance().opacity());
}
-void FormEditorItem::showAttention()
-{
- if (m_attentionTimeLine.isNull()) {
- m_attentionTimeLine = new QTimeLine(500, this);
- m_attentionTimeLine->setCurveShape(QTimeLine::SineCurve);
- connect(m_attentionTimeLine.data(), SIGNAL(valueChanged(qreal)), SLOT(changeAttention(qreal)));
- connect(m_attentionTimeLine.data(), SIGNAL(finished()), m_attentionTimeLine.data(), SLOT(deleteLater()));
-
- m_attentionTimeLine->start();
- }
-}
-
-void FormEditorItem::changeAttention(qreal value)
-{
- if (QGraphicsItem::parentItem() == scene()->formLayerItem()) {
- setAttentionHighlight(value);
- } else {
- setAttentionHighlight(value);
- setAttentionScale(value);
- }
-}
FormEditorView *FormEditorItem::formEditorView() const
{
return scene()->editorView();
}
-void FormEditorItem::setAttentionScale(double sinusScale)
+void FormEditorItem::setHighlightBoundingRect(bool highlight)
{
- if (!qFuzzyIsNull(sinusScale)) {
- double scale = std::sqrt(sinusScale);
- m_attentionTransform.reset();
- QPointF centerPoint(qmlItemNode().instanceBoundingRect().center());
- m_attentionTransform.translate(centerPoint.x(), centerPoint.y());
- m_attentionTransform.scale(scale * 0.15 + 1.0, scale * 0.15 + 1.0);
- m_attentionTransform.translate(-centerPoint.x(), -centerPoint.y());
- m_inverseAttentionTransform = m_attentionTransform.inverted();
- prepareGeometryChange();
- setTransform(qmlItemNode().instanceTransformWithContentTransform());
- setTransform(m_attentionTransform, true);
- } else {
- m_attentionTransform.reset();
- prepareGeometryChange();
- setTransform(qmlItemNode().instanceTransform());
+ if (m_highlightBoundingRect != highlight) {
+ m_highlightBoundingRect = highlight;
+ update();
}
}
-void FormEditorItem::setAttentionHighlight(double value)
+void FormEditorItem::blurContent(bool blurContent)
{
- if (QGraphicsItem::parentItem() == scene()->formLayerItem())
- m_borderWidth = value * 4;
- else
- m_borderWidth = 1. + value * 3;
-
- update();
-}
-
-void FormEditorItem::setHighlightBoundingRect(bool highlight)
-{
- if (m_highlightBoundingRect != highlight) {
- m_highlightBoundingRect = highlight;
+ if (m_blurContent != blurContent) {
+ m_blurContent = blurContent;
update();
}
}
@@ -235,20 +191,23 @@ void FormEditorItem::paintBoundingRect(QPainter *painter) const
QPen pen;
pen.setJoinStyle(Qt::MiterJoin);
- pen.setStyle(Qt::DotLine);
QColor frameColor("#AAAAAA");
if (scene()->showBoundingRects()) {
- if (m_highlightBoundingRect)
+ if (m_highlightBoundingRect) {
pen.setColor(frameColor);
- else
+ } else {
pen.setColor(frameColor.darker(150));
+ pen.setStyle(Qt::DotLine);
+ }
} else {
- if (m_highlightBoundingRect)
+ if (m_highlightBoundingRect) {
pen.setColor(frameColor);
- else
+ } else {
pen.setColor(Qt::transparent);
+ pen.setStyle(Qt::DotLine);
+ }
}
painter->setPen(pen);
@@ -308,6 +267,11 @@ void FormEditorItem::paintPlaceHolderForInvisbleItem(QPainter *painter) const
}
}
+void FormEditorItem::paintComponentContentVisualisation(QPainter *painter, const QRectF &clippinRectangle) const
+{
+ painter->setBrush(QColor(0, 0, 0, 150));
+ painter->fillRect(clippinRectangle, Qt::BDiagPattern);
+}
void FormEditorItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *)
{
@@ -323,12 +287,18 @@ void FormEditorItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *,
if (scene()->showBoundingRects() && m_boundingRect.width() > 15 && m_boundingRect.height() > 15)
paintPlaceHolderForInvisbleItem(painter);
} else {
- qmlItemNode().paintInstance(painter);
+ if (m_blurContent)
+ painter->drawPixmap(boundingRect().topLeft(), qmlItemNode().instanceBlurredRenderPixmap());
+ else
+ painter->drawPixmap(boundingRect().topLeft(), qmlItemNode().instanceRenderPixmap());
}
if (!qmlItemNode().isRootModelNode())
paintBoundingRect(painter);
+// if (qmlItemNode().modelNode().metaInfo().isSubclassOf("QtQuick.Loader", -1, -1))
+// paintComponentContentVisualisation(painter, boundingRect());
+
painter->restore();
}
@@ -410,6 +380,11 @@ QList<FormEditorItem*> FormEditorItem::childFormEditorItems() const
bool FormEditorItem::isContainer() const
{
+ NodeMetaInfo nodeMetaInfo = qmlItemNode().modelNode().metaInfo();
+
+ if (nodeMetaInfo.isValid())
+ return !nodeMetaInfo.defaultPropertyIsComponent();
+
return true;
}
diff --git a/src/plugins/qmldesigner/components/formeditor/formeditoritem.h b/src/plugins/qmldesigner/components/formeditor/formeditoritem.h
index ff133c70d5..ddc5c76b40 100644
--- a/src/plugins/qmldesigner/components/formeditor/formeditoritem.h
+++ b/src/plugins/qmldesigner/components/formeditor/formeditoritem.h
@@ -99,6 +99,7 @@ public:
FormEditorView *formEditorView() const;
void setHighlightBoundingRect(bool highlight);
+ void blurContent(bool blurContent);
void setContentVisible(bool visible);
bool isContentVisible() const;
@@ -110,26 +111,22 @@ protected:
AbstractFormEditorTool* tool() const;
void paintBoundingRect(QPainter *painter) const;
void paintPlaceHolderForInvisbleItem(QPainter *painter) const;
-
-private slots:
- void changeAttention(qreal value);
+ void paintComponentContentVisualisation(QPainter *painter, const QRectF &clippinRectangle) const;
private: // functions
FormEditorItem(const QmlItemNode &qmlItemNode, FormEditorScene* scene);
void setup();
- void setAttentionScale(double scale);
- void setAttentionHighlight(double value);
private: // variables
SnappingLineCreator m_snappingLineCreator;
QmlItemNode m_qmlItemNode;
QWeakPointer<QTimeLine> m_attentionTimeLine;
- QTransform m_attentionTransform; // make item larger in anchor mode
QTransform m_inverseAttentionTransform;
QRectF m_boundingRect;
QRectF m_paintedBoundingRect;
double m_borderWidth;
bool m_highlightBoundingRect;
+ bool m_blurContent;
bool m_isContentVisible;
bool m_isFormEditorVisible;
};
diff --git a/src/plugins/qmldesigner/components/formeditor/formeditorview.cpp b/src/plugins/qmldesigner/components/formeditor/formeditorview.cpp
index b7991dacde..be51e341bc 100644
--- a/src/plugins/qmldesigner/components/formeditor/formeditorview.cpp
+++ b/src/plugins/qmldesigner/components/formeditor/formeditorview.cpp
@@ -53,7 +53,7 @@
namespace QmlDesigner {
FormEditorView::FormEditorView(QObject *parent)
- : QmlModelView(parent),
+ : AbstractView(parent),
m_formEditorWidget(new FormEditorWidget(this)),
m_scene(new FormEditorScene(m_formEditorWidget.data(), this)),
m_moveTool(new MoveTool(this)),
@@ -100,12 +100,12 @@ void FormEditorView::modelAttached(Model *model)
{
Q_ASSERT(model);
- QmlModelView::modelAttached(model);
+ AbstractView::modelAttached(model);
Q_ASSERT(m_scene->formLayerItem());
- if (rootQmlObjectNode().toQmlItemNode().isValid())
- setupFormEditorItemTree(rootQmlObjectNode().toQmlItemNode());
+ if (QmlItemNode::isValidQmlItemNode(rootModelNode()))
+ setupFormEditorItemTree(rootModelNode());
m_formEditorWidget->updateActions();
}
@@ -156,10 +156,9 @@ void FormEditorView::hideNodeFromScene(const QmlItemNode &qmlItemNode)
void FormEditorView::nodeCreated(const ModelNode &createdNode)
{
- QmlModelView::nodeCreated(createdNode);
ModelNode node(createdNode);
//If the node has source for components/custom parsers we ignore it.
- if (QmlItemNode(node).isValid() && node.nodeSourceType() == ModelNode::NodeWithoutSource) //only setup QmlItems
+ if (QmlItemNode::isValidQmlItemNode(node) && node.nodeSourceType() == ModelNode::NodeWithoutSource) //only setup QmlItems
setupFormEditorItemTree(QmlItemNode(node));
}
@@ -178,7 +177,7 @@ void FormEditorView::modelAboutToBeDetached(Model *model)
m_currentTool = m_selectionTool;
- QmlModelView::modelAboutToBeDetached(model);
+ AbstractView::modelAboutToBeDetached(model);
}
void FormEditorView::importsChanged(const QList<Import> &/*addedImports*/, const QList<Import> &/*removedImports*/)
@@ -191,11 +190,9 @@ void FormEditorView::nodeAboutToBeRemoved(const ModelNode &removedNode)
QmlItemNode qmlItemNode(removedNode);
removeNodeFromScene(qmlItemNode);
-
- QmlModelView::nodeAboutToBeRemoved(removedNode);
}
- void FormEditorView::rootNodeTypeChanged(const QString &type, int majorVersion, int minorVersion)
+ void FormEditorView::rootNodeTypeChanged(const QString &/*type*/, int /*majorVersion*/, int /*minorVersion*/)
{
foreach (FormEditorItem *item, m_scene->allFormEditorItems()) {
item->setParentItem(0);
@@ -207,13 +204,11 @@ void FormEditorView::nodeAboutToBeRemoved(const ModelNode &removedNode)
delete item;
}
- QmlModelView::rootNodeTypeChanged(type, majorVersion, minorVersion);
-
QmlItemNode newItemNode(rootModelNode());
if (newItemNode.isValid()) //only setup QmlItems
setupFormEditorItemTree(newItemNode);
- m_currentTool->setItems(scene()->itemsForQmlItemNodes(selectedQmlItemNodes()));
+ m_currentTool->setItems(scene()->itemsForQmlItemNodes(toQmlItemNodeList(selectedModelNodes())));
}
void FormEditorView::propertiesAboutToBeRemoved(const QList<AbstractProperty>& propertyList)
@@ -237,13 +232,11 @@ void FormEditorView::propertiesAboutToBeRemoved(const QList<AbstractProperty>& p
m_currentTool->itemsAboutToRemoved(removedItemList);
}
}
-
- QmlModelView::propertiesAboutToBeRemoved(propertyList);
}
static inline bool hasNodeSourceParent(const ModelNode &node)
{
- if (node.parentProperty().isValid() && node.parentProperty().parentModelNode().isValid()) {
+ if (node.hasParentProperty() && node.parentProperty().parentModelNode().isValid()) {
ModelNode parent = node.parentProperty().parentModelNode();
if (parent.nodeSourceType() != ModelNode::NodeWithoutSource)
return true;
@@ -252,22 +245,18 @@ static inline bool hasNodeSourceParent(const ModelNode &node)
return false;
}
-void FormEditorView::nodeReparented(const ModelNode &node, const NodeAbstractProperty &newPropertyParent, const NodeAbstractProperty &oldPropertyParent, AbstractView::PropertyChangeFlags propertyChange)
+void FormEditorView::nodeReparented(const ModelNode &node, const NodeAbstractProperty &/*newPropertyParent*/, const NodeAbstractProperty &/*oldPropertyParent*/, AbstractView::PropertyChangeFlags /*propertyChange*/)
{
if (hasNodeSourceParent(node))
hideNodeFromScene(node);
-
- QmlModelView::nodeReparented(node, newPropertyParent, oldPropertyParent, propertyChange);
}
-void FormEditorView::variantPropertiesChanged(const QList<VariantProperty>& propertyList, PropertyChangeFlags propertyChange)
+void FormEditorView::variantPropertiesChanged(const QList<VariantProperty> &/*propertyList*/, PropertyChangeFlags /*propertyChange*/)
{
- QmlModelView::variantPropertiesChanged(propertyList, propertyChange);
}
-void FormEditorView::bindingPropertiesChanged(const QList<BindingProperty>& propertyList, PropertyChangeFlags propertyChange)
+void FormEditorView::bindingPropertiesChanged(const QList<BindingProperty> &/*propertyList*/, PropertyChangeFlags /*propertyChange*/)
{
- QmlModelView::bindingPropertiesChanged(propertyList, propertyChange);
}
void FormEditorView::signalHandlerPropertiesChanged(const QVector<SignalHandlerProperty> & /*propertyList*/, AbstractView::PropertyChangeFlags /*propertyChange*/)
@@ -284,9 +273,8 @@ FormEditorWidget *FormEditorView::formEditorWidget()
return m_formEditorWidget.data();
}
-void FormEditorView::nodeIdChanged(const ModelNode& node, const QString& newId, const QString& oldId)
+void FormEditorView::nodeIdChanged(const ModelNode& node, const QString &/*newId*/, const QString &/*oldId*/)
{
- QmlModelView::nodeIdChanged(node, newId, oldId);
QmlItemNode itemNode(node);
if (itemNode.isValid() && node.nodeSourceType() == ModelNode::NodeWithoutSource) {
@@ -296,18 +284,15 @@ void FormEditorView::nodeIdChanged(const ModelNode& node, const QString& newId,
}
void FormEditorView::selectedNodesChanged(const QList<ModelNode> &selectedNodeList,
- const QList<ModelNode> &lastSelectedNodeList)
+ const QList<ModelNode> &/*lastSelectedNodeList*/)
{
- QmlModelView::selectedNodesChanged(selectedNodeList, lastSelectedNodeList);
-
m_currentTool->setItems(scene()->itemsForQmlItemNodes(toQmlItemNodeList(selectedNodeList)));
m_scene->update();
}
-void FormEditorView::scriptFunctionsChanged(const ModelNode &node, const QStringList &scriptFunctionList)
+void FormEditorView::scriptFunctionsChanged(const ModelNode &/*node*/, const QStringList &/*scriptFunctionList*/)
{
- QmlModelView::scriptFunctionsChanged(node, scriptFunctionList);
}
void FormEditorView::propertiesRemoved(const QList<AbstractProperty> &/*propertyList*/)
@@ -331,7 +316,7 @@ bool FormEditorView::changeToMoveTool()
m_currentTool->clear();
m_currentTool = m_moveTool;
m_currentTool->clear();
- m_currentTool->setItems(scene()->itemsForQmlItemNodes(selectedQmlItemNodes()));
+ m_currentTool->setItems(scene()->itemsForQmlItemNodes(toQmlItemNodeList(selectedModelNodes())));
return true;
}
@@ -344,7 +329,7 @@ void FormEditorView::changeToDragTool()
m_currentTool->clear();
m_currentTool = m_dragTool;
m_currentTool->clear();
- m_currentTool->setItems(scene()->itemsForQmlItemNodes(selectedQmlItemNodes()));
+ m_currentTool->setItems(scene()->itemsForQmlItemNodes(toQmlItemNodeList(selectedModelNodes())));
}
@@ -360,7 +345,7 @@ bool FormEditorView::changeToMoveTool(const QPointF &beginPoint)
m_currentTool->clear();
m_currentTool = m_moveTool;
m_currentTool->clear();
- m_currentTool->setItems(scene()->itemsForQmlItemNodes(selectedQmlItemNodes()));
+ m_currentTool->setItems(scene()->itemsForQmlItemNodes(toQmlItemNodeList(selectedModelNodes())));
m_moveTool->beginWithPoint(beginPoint);
return true;
}
@@ -374,7 +359,7 @@ void FormEditorView::changeToSelectionTool()
m_currentTool->clear();
m_currentTool = m_selectionTool;
m_currentTool->clear();
- m_currentTool->setItems(scene()->itemsForQmlItemNodes(selectedQmlItemNodes()));
+ m_currentTool->setItems(scene()->itemsForQmlItemNodes(toQmlItemNodeList(selectedModelNodes())));
}
void FormEditorView::changeToSelectionTool(QGraphicsSceneMouseEvent *event)
@@ -386,7 +371,7 @@ void FormEditorView::changeToSelectionTool(QGraphicsSceneMouseEvent *event)
m_currentTool->clear();
m_currentTool = m_selectionTool;
m_currentTool->clear();
- m_currentTool->setItems(scene()->itemsForQmlItemNodes(selectedQmlItemNodes()));
+ m_currentTool->setItems(scene()->itemsForQmlItemNodes(toQmlItemNodeList(selectedModelNodes())));
m_selectionTool->selectUnderPoint(event);
}
@@ -400,7 +385,7 @@ void FormEditorView::changeToResizeTool()
m_currentTool->clear();
m_currentTool = m_resizeTool;
m_currentTool->clear();
- m_currentTool->setItems(scene()->itemsForQmlItemNodes(selectedQmlItemNodes()));
+ m_currentTool->setItems(scene()->itemsForQmlItemNodes(toQmlItemNodeList(selectedModelNodes())));
}
void FormEditorView::changeToTransformTools()
@@ -413,25 +398,29 @@ void FormEditorView::changeToTransformTools()
changeToSelectionTool();
}
-void FormEditorView::changeToCustomTool(const ModelNode &modelNode)
+void FormEditorView::changeToCustomTool()
{
- int handlingRank = 0;
- AbstractCustomTool *selectedCustomTool;
+ if (hasSelectedModelNodes()) {
+ int handlingRank = 0;
+ AbstractCustomTool *selectedCustomTool;
- foreach (AbstractCustomTool *customTool, m_customToolList) {
- if (customTool->wantHandleItem(modelNode) > handlingRank) {
- handlingRank = customTool->wantHandleItem(modelNode);
- selectedCustomTool = customTool;
- }
+ ModelNode selectedModelNode = selectedModelNodes().first();
- }
+ foreach (AbstractCustomTool *customTool, m_customToolList) {
+ if (customTool->wantHandleItem(selectedModelNode) > handlingRank) {
+ handlingRank = customTool->wantHandleItem(selectedModelNode);
+ selectedCustomTool = customTool;
+ }
- if (handlingRank > 0) {
- m_scene->updateAllFormEditorItems();
- m_currentTool->clear();
- m_currentTool = selectedCustomTool;
- m_currentTool->clear();
- m_currentTool->setItems(scene()->itemsForQmlItemNodes(selectedQmlItemNodes()));
+ }
+
+ if (handlingRank > 0) {
+ m_scene->updateAllFormEditorItems();
+ m_currentTool->clear();
+ m_currentTool = selectedCustomTool;
+ m_currentTool->clear();
+ m_currentTool->setItems(scene()->itemsForQmlItemNodes(toQmlItemNodeList(selectedModelNodes())));
+ }
}
}
@@ -441,7 +430,7 @@ void FormEditorView::changeToCustomTool(AbstractCustomTool *customTool)
m_currentTool->clear();
m_currentTool = customTool;
m_currentTool->clear();
- m_currentTool->setItems(scene()->itemsForQmlItemNodes(selectedQmlItemNodes()));
+ m_currentTool->setItems(scene()->itemsForQmlItemNodes(toQmlItemNodeList(selectedModelNodes())));
}
void FormEditorView::registerTool(AbstractCustomTool *tool)
@@ -467,7 +456,7 @@ void FormEditorView::nodeSlidedToIndex(const NodeListProperty &listProperty, int
void FormEditorView::auxiliaryDataChanged(const ModelNode &node, const PropertyName &name, const QVariant &data)
{
- QmlModelView::auxiliaryDataChanged(node, name, data);
+ AbstractView::auxiliaryDataChanged(node, name, data);
if (name == "invisible" && m_scene->hasItemForQmlItemNode(QmlItemNode(node))) {
FormEditorItem *item(m_scene->itemForQmlItemNode(QmlItemNode(node)));
bool isInvisible = data.toBool();
@@ -606,8 +595,6 @@ void FormEditorView::instancePropertyChange(const QList<QPair<ModelNode, Propert
}
}
}
-
- QmlModelView::instancePropertyChange(propertyList);
}
void FormEditorView::updateGraphicsIndicators()
@@ -623,17 +610,38 @@ void FormEditorView::setSelectOnlyContentItemsAction(bool selectOnlyContentItems
bool FormEditorView::isMoveToolAvailable() const
{
- if (selectedQmlItemNodes().count() == 1)
- return selectedQmlItemNodes().first().instanceIsMovable() &&
- !selectedQmlItemNodes().first().instanceIsInLayoutable();
+ if (hasSingleSelectedModelNode() && QmlItemNode::isValidQmlItemNode(singleSelectedModelNode())) {
+ QmlItemNode selectedQmlItemNode(singleSelectedModelNode());
+ return selectedQmlItemNode.instanceIsMovable()
+ && selectedQmlItemNode.modelIsMovable()
+ && !selectedQmlItemNode.instanceIsInLayoutable();
+ }
+
return true;
}
-void FormEditorView::actualStateChanged(const ModelNode &node)
+void FormEditorView::currentStateChanged(const ModelNode &/*node*/)
+{
+}
+
+void FormEditorView::nodeRemoved(const ModelNode &/*removedNode*/, const NodeAbstractProperty &/*parentProperty*/, AbstractView::PropertyChangeFlags /*propertyChange*/)
+{
+
+}
+
+void FormEditorView::nodeAboutToBeReparented(const ModelNode &/*node*/, const NodeAbstractProperty &/*newPropertyParent*/, const NodeAbstractProperty &/*oldPropertyParent*/, AbstractView::PropertyChangeFlags /*propertyChange*/)
+{
+
+}
+
+void FormEditorView::nodeSourceChanged(const ModelNode &/*modelNode*/, const QString &/*newNodeSource*/)
+{
+
+}
+
+void FormEditorView::nodeOrderChanged(const NodeListProperty &/*listProperty*/, const ModelNode &/*movedNode*/, int /*oldIndex*/)
{
- QmlModelView::actualStateChanged(node);
- QmlModelState newQmlModelState(node);
}
void FormEditorView::reset()
@@ -648,8 +656,8 @@ void FormEditorView::delayedReset()
m_resizeTool->clear();
m_dragTool->clear();
m_scene->clearFormEditorItems();
- if (rootQmlObjectNode().toQmlItemNode().isValid())
- setupFormEditorItemTree(rootQmlObjectNode().toQmlItemNode());
+ if (QmlItemNode::isValidQmlItemNode(rootModelNode()))
+ setupFormEditorItemTree(rootModelNode());
}
diff --git a/src/plugins/qmldesigner/components/formeditor/formeditorview.h b/src/plugins/qmldesigner/components/formeditor/formeditorview.h
index aeaff58c9f..bb5fcc6d87 100644
--- a/src/plugins/qmldesigner/components/formeditor/formeditorview.h
+++ b/src/plugins/qmldesigner/components/formeditor/formeditorview.h
@@ -30,7 +30,7 @@
#ifndef FORMEDITORVIEW_H
#define FORMEDITORVIEW_H
-#include <qmlmodelview.h>
+#include <abstractview.h>
QT_BEGIN_NAMESPACE
class QGraphicsScene;
@@ -57,7 +57,7 @@ class DragTool;
class ItemLibraryEntry;
class QmlItemNode;
-class QMLDESIGNERCORE_EXPORT FormEditorView : public QmlModelView
+class QMLDESIGNERCORE_EXPORT FormEditorView : public AbstractView
{
Q_OBJECT
@@ -100,7 +100,7 @@ public:
void changeToSelectionTool(QGraphicsSceneMouseEvent *event);
void changeToResizeTool();
void changeToTransformTools();
- void changeToCustomTool(const ModelNode &modelNode);
+ void changeToCustomTool();
void changeToCustomTool(AbstractCustomTool *customTool);
void registerTool(AbstractCustomTool *tool);
@@ -123,7 +123,12 @@ public:
double spacing() const;
void deActivateItemCreator();
- void actualStateChanged(const ModelNode &node) QTC_OVERRIDE;
+ void currentStateChanged(const ModelNode &node) QTC_OVERRIDE;
+
+ void nodeRemoved(const ModelNode &removedNode, const NodeAbstractProperty &parentProperty, PropertyChangeFlags propertyChange) QTC_OVERRIDE;
+ void nodeAboutToBeReparented(const ModelNode &node, const NodeAbstractProperty &newPropertyParent, const NodeAbstractProperty &oldPropertyParent, PropertyChangeFlags propertyChange) QTC_OVERRIDE;
+ void nodeSourceChanged(const ModelNode &modelNode, const QString &newNodeSource) QTC_OVERRIDE;
+ void nodeOrderChanged(const NodeListProperty &listProperty, const ModelNode &movedNode, int oldIndex) QTC_OVERRIDE;
protected:
void reset();
diff --git a/src/plugins/qmldesigner/components/formeditor/formeditorwidget.cpp b/src/plugins/qmldesigner/components/formeditor/formeditorwidget.cpp
index f730f7e73d..1c81a28b2a 100644
--- a/src/plugins/qmldesigner/components/formeditor/formeditorwidget.cpp
+++ b/src/plugins/qmldesigner/components/formeditor/formeditorwidget.cpp
@@ -127,13 +127,6 @@ FormEditorWidget::FormEditorWidget(FormEditorView *view)
fillLayout->addWidget(m_toolBox.data());
m_toolBox->setLeftSideActions(upperActions);
- m_graphicsView = new FormEditorGraphicsView(this);
- fillLayout->addWidget(m_graphicsView.data());
-
- m_graphicsView.data()->setStyleSheet(
- QLatin1String(Utils::FileReader::fetchQrc(":/qmldesigner/scrollbar.css")));
-
- QList<QAction*> lowerActions;
m_zoomAction = new ZoomAction(m_toolActionGroup.data());
connect(m_zoomAction.data(), SIGNAL(zoomLevelChanged(double)), SLOT(setZoomLevel(double)));
@@ -149,6 +142,11 @@ FormEditorWidget::FormEditorWidget(FormEditorView *view)
addAction(m_resetAction.data());
upperActions.append(m_resetAction.data());
m_toolBox->addRightSideAction(m_resetAction.data());
+
+ m_graphicsView = new FormEditorGraphicsView(this);
+
+ fillLayout->addWidget(m_graphicsView.data());
+ m_graphicsView.data()->setStyleSheet(QLatin1String(Utils::FileReader::fetchQrc(":/qmldesigner/scrollbar.css")));
}
void FormEditorWidget::changeTransformTool(bool checked)
@@ -180,7 +178,7 @@ void FormEditorWidget::changeRootItemHeight(const QString &heighText)
void FormEditorWidget::resetNodeInstanceView()
{
- m_formEditorView->setCurrentState(m_formEditorView->baseState());
+ m_formEditorView->setCurrentStateNode(m_formEditorView->rootModelNode());
m_formEditorView->emitCustomNotification(QLatin1String("reset QmlPuppet"));
}
@@ -232,11 +230,6 @@ void FormEditorWidget::setFocus()
m_graphicsView->setFocus(Qt::OtherFocusReason);
}
-FormEditorCrumbleBar *FormEditorWidget::formEditorCrumbleBar() const
-{
- return toolBox()->formEditorCrumbleBar();
-}
-
ZoomAction *FormEditorWidget::zoomAction() const
{
return m_zoomAction.data();
diff --git a/src/plugins/qmldesigner/components/formeditor/formeditorwidget.h b/src/plugins/qmldesigner/components/formeditor/formeditorwidget.h
index 7cf54c5c24..53efd906e1 100644
--- a/src/plugins/qmldesigner/components/formeditor/formeditorwidget.h
+++ b/src/plugins/qmldesigner/components/formeditor/formeditorwidget.h
@@ -32,8 +32,6 @@
#include <QWidget>
-#include "formeditorcrumblebar.h"
-
QT_BEGIN_NAMESPACE
class QActionGroup;
QT_END_NAMESPACE
@@ -79,8 +77,6 @@ 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 1888d5ee1b..4ac274afc7 100644
--- a/src/plugins/qmldesigner/components/formeditor/movemanipulator.cpp
+++ b/src/plugins/qmldesigner/components/formeditor/movemanipulator.cpp
@@ -115,7 +115,7 @@ bool MoveManipulator::itemsCanReparented() const
foreach (FormEditorItem* item, m_itemList) {
if (item
&& item->qmlItemNode().isValid()
- && !item->qmlItemNode().canReparent())
+ && !item->qmlItemNode().instanceCanReparent())
return false;
}
@@ -277,7 +277,7 @@ void MoveManipulator::update(const QPointF& updatePoint, Snapper::Snapping useSn
continue;
// don't support anchors for base state because it is not needed by the droptool
- if (stateToBeManipulated == UseActualState) {
+ if (stateToBeManipulated == UseCurrentState) {
QmlAnchors anchors(item->qmlItemNode().anchors());
if (anchors.instanceHasAnchor(AnchorLine::Top))
@@ -298,10 +298,9 @@ void MoveManipulator::update(const QPointF& updatePoint, Snapper::Snapping useSn
if (anchors.instanceHasAnchor(AnchorLine::VerticalCenter))
anchors.setMargin(AnchorLine::VerticalCenter, m_beginVerticalCenterHash.value(item) + offsetVector.y());
- setPosition(item->qmlItemNode(), positionInContainerSpace);
+ item->qmlItemNode().setPosition(positionInContainerSpace);
} else {
- item->qmlItemNode().modelNode().variantProperty("x").setValue(qRound(positionInContainerSpace.x()));
- item->qmlItemNode().modelNode().variantProperty("y").setValue(qRound(positionInContainerSpace.y()));
+ item->qmlItemNode().setPostionInBaseState(positionInContainerSpace);
}
}
}
@@ -347,12 +346,12 @@ void MoveManipulator::reparentTo(FormEditorItem *newParent)
QVector<ModelNode> nodeReparentVector;
NodeAbstractProperty parentProperty;
- QmlItemNode parent(newParent->qmlItemNode());
- if (parent.isValid()) {
- if (parent.hasDefaultProperty())
- parentProperty = parent.nodeAbstractProperty(parent.defaultProperty());
+ QmlItemNode parentItemNode(newParent->qmlItemNode());
+ if (parentItemNode.isValid()) {
+ if (parentItemNode.hasDefaultPropertyName())
+ parentProperty = parentItemNode.defaultNodeAbstractProperty();
else
- parentProperty = parent.nodeAbstractProperty("data");
+ parentProperty = parentItemNode.nodeAbstractProperty("data");
foreach (FormEditorItem* item, m_itemList) {
if (!item || !item->qmlItemNode().isValid())
@@ -415,7 +414,7 @@ void MoveManipulator::moveBy(double deltaX, double deltaY)
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().setPosition(QPointF(item->qmlItemNode().instanceValue("x").toDouble() + deltaX,
item->qmlItemNode().instanceValue("y").toDouble() + deltaY));
}
}
@@ -453,13 +452,4 @@ bool MoveManipulator::isActive() const
return m_isActive;
}
-void MoveManipulator::setPosition(QmlItemNode itemNode, const QPointF &position)
-{
- if (!itemNode.hasBindingProperty("x"))
- itemNode.setVariantProperty("x", qRound(position.x()));
-
- if (!itemNode.hasBindingProperty("y"))
- itemNode.setVariantProperty("y", qRound(position.y()));
-}
-
}
diff --git a/src/plugins/qmldesigner/components/formeditor/movemanipulator.h b/src/plugins/qmldesigner/components/formeditor/movemanipulator.h
index 380f1207f3..98647bb2de 100644
--- a/src/plugins/qmldesigner/components/formeditor/movemanipulator.h
+++ b/src/plugins/qmldesigner/components/formeditor/movemanipulator.h
@@ -50,7 +50,7 @@ class MoveManipulator
{
public:
enum State {
- UseActualState,
+ UseCurrentState,
UseBaseState
};
@@ -62,7 +62,7 @@ public:
void synchronizeParent(const QList<FormEditorItem*> &itemList, const ModelNode &parentNode);
void begin(const QPointF& beginPoint);
- void update(const QPointF& updatePoint, Snapper::Snapping useSnapping, State stateToBeManipulated = UseActualState);
+ void update(const QPointF& updatePoint, Snapper::Snapping useSnapping, State stateToBeManipulated = UseCurrentState);
void reparentTo(FormEditorItem *newParent);
void end();
void end(Snapper::Snapping useSnapping);
@@ -95,8 +95,6 @@ protected:
bool itemsCanReparented() const;
- void setPosition(QmlItemNode itemNode, const QPointF &position);
-
void adjustAnchoringOfItem(FormEditorItem *item);
private:
diff --git a/src/plugins/qmldesigner/components/formeditor/movetool.cpp b/src/plugins/qmldesigner/components/formeditor/movetool.cpp
index 7167b0d3ff..8a6132d406 100644
--- a/src/plugins/qmldesigner/components/formeditor/movetool.cpp
+++ b/src/plugins/qmldesigner/components/formeditor/movetool.cpp
@@ -46,7 +46,10 @@ MoveTool::MoveTool(FormEditorView *editorView)
: AbstractFormEditorTool(editorView),
m_moveManipulator(editorView->scene()->manipulatorLayerItem(), editorView),
m_selectionIndicator(editorView->scene()->manipulatorLayerItem()),
- m_resizeIndicator(editorView->scene()->manipulatorLayerItem())
+ m_resizeIndicator(editorView->scene()->manipulatorLayerItem()),
+ m_anchorIndicator(editorView->scene()->manipulatorLayerItem()),
+ m_bindingIndicator(editorView->scene()->manipulatorLayerItem()),
+ m_contentNotEditableIndicator(editorView->scene()->manipulatorLayerItem())
{
m_selectionIndicator.setCursor(Qt::SizeAllCursor);
}
@@ -63,6 +66,9 @@ void MoveTool::clear()
m_movingItems.clear();
m_selectionIndicator.clear();
m_resizeIndicator.clear();
+ m_anchorIndicator.clear();
+ m_bindingIndicator.clear();
+ m_contentNotEditableIndicator.clear();
AbstractFormEditorTool::clear();
}
@@ -93,10 +99,11 @@ void MoveTool::mouseMoveEvent(const QList<QGraphicsItem*> &itemList,
// m_selectionIndicator.hide();
m_resizeIndicator.hide();
+ m_anchorIndicator.hide();
+ m_bindingIndicator.hide();
FormEditorItem *containerItem = containerFormEditorItem(itemList, m_movingItems);
- if (containerItem
- && view()->currentState().isBaseState()) {
+ if (containerItem && view()->currentState().isBaseState()) {
if (containerItem != m_movingItems.first()->parentItem()
&& event->modifiers().testFlag(Qt::ShiftModifier)) {
m_moveManipulator.reparentTo(containerItem);
@@ -125,6 +132,8 @@ void MoveTool::hoverMoveEvent(const QList<QGraphicsItem*> &itemList,
view()->changeToSelectionTool();
return;
}
+
+ m_contentNotEditableIndicator.setItems(toFormEditorItemList(itemList));
}
void MoveTool::keyPressEvent(QKeyEvent *event)
@@ -151,6 +160,8 @@ void MoveTool::keyPressEvent(QKeyEvent *event)
m_moveManipulator.setItems(movableItems);
// m_selectionIndicator.hide();
m_resizeIndicator.hide();
+ m_anchorIndicator.hide();
+ m_bindingIndicator.hide();
m_moveManipulator.beginRewriterTransaction();
}
@@ -183,6 +194,8 @@ void MoveTool::keyReleaseEvent(QKeyEvent *keyEvent)
m_moveManipulator.clear();
// m_selectionIndicator.show();
m_resizeIndicator.show();
+ m_anchorIndicator.show();
+ m_bindingIndicator.show();
}
}
@@ -207,6 +220,8 @@ void MoveTool::mouseReleaseEvent(const QList<QGraphicsItem*> &itemList,
m_selectionIndicator.show();
m_resizeIndicator.show();
+ m_anchorIndicator.show();
+ m_bindingIndicator.show();
m_movingItems.clear();
}
@@ -228,6 +243,8 @@ void MoveTool::selectedItemsChanged(const QList<FormEditorItem*> &itemList)
{
m_selectionIndicator.setItems(movingItems(itemList));
m_resizeIndicator.setItems(itemList);
+ m_anchorIndicator.setItems(itemList);
+ m_bindingIndicator.setItems(itemList);
updateMoveManipulator();
}
@@ -324,7 +341,8 @@ FormEditorItem* MoveTool::containerFormEditorItem(const QList<QGraphicsItem*> &i
FormEditorItem *formEditorItem = FormEditorItem::fromQGraphicsItem(item);
if (formEditorItem
&& !selectedItemList.contains(formEditorItem)
- && isNotAncestorOfItemInList(formEditorItem, selectedItemList))
+ && isNotAncestorOfItemInList(formEditorItem, selectedItemList)
+ && formEditorItem->isContainer())
return formEditorItem;
}
@@ -339,7 +357,10 @@ QList<FormEditorItem*> movalbeItems(const QList<FormEditorItem*> &itemList)
QMutableListIterator<FormEditorItem*> listIterator(filteredItemList);
while (listIterator.hasNext()) {
FormEditorItem *item = listIterator.next();
- if (!item->qmlItemNode().isValid() || !item->qmlItemNode().instanceIsMovable() || item->qmlItemNode().instanceIsInLayoutable())
+ if (!item->qmlItemNode().isValid()
+ || !item->qmlItemNode().instanceIsMovable()
+ || !item->qmlItemNode().modelIsMovable()
+ || item->qmlItemNode().instanceIsInLayoutable())
listIterator.remove();
}
@@ -376,6 +397,8 @@ void MoveTool::formEditorItemsChanged(const QList<FormEditorItem*> &itemList)
{
m_selectionIndicator.updateItems(itemList);
m_resizeIndicator.updateItems(itemList);
+ m_anchorIndicator.updateItems(itemList);
+ m_bindingIndicator.updateItems(itemList);
}
}
diff --git a/src/plugins/qmldesigner/components/formeditor/movetool.h b/src/plugins/qmldesigner/components/formeditor/movetool.h
index 2611219b60..0b5a9ac2a4 100644
--- a/src/plugins/qmldesigner/components/formeditor/movetool.h
+++ b/src/plugins/qmldesigner/components/formeditor/movetool.h
@@ -34,7 +34,9 @@
#include "movemanipulator.h"
#include "selectionindicator.h"
#include "resizeindicator.h"
-
+#include "anchorindicator.h"
+#include "bindingindicator.h"
+#include "contentnoteditableindicator.h"
namespace QmlDesigner {
@@ -93,6 +95,9 @@ private:
MoveManipulator m_moveManipulator;
SelectionIndicator m_selectionIndicator;
ResizeIndicator m_resizeIndicator;
+ AnchorIndicator m_anchorIndicator;
+ BindingIndicator m_bindingIndicator;
+ ContentNotEditableIndicator m_contentNotEditableIndicator;
QList<FormEditorItem*> m_movingItems;
};
diff --git a/src/plugins/qmldesigner/components/formeditor/resizehandleitem.cpp b/src/plugins/qmldesigner/components/formeditor/resizehandleitem.cpp
index c4a450e52a..dc0fd0e18c 100644
--- a/src/plugins/qmldesigner/components/formeditor/resizehandleitem.cpp
+++ b/src/plugins/qmldesigner/components/formeditor/resizehandleitem.cpp
@@ -29,14 +29,14 @@
#include "resizehandleitem.h"
+#include <QPainter>
+
namespace QmlDesigner {
ResizeHandleItem::ResizeHandleItem(QGraphicsItem *parent, const ResizeController &resizeController)
- : QGraphicsPixmapItem(QPixmap(":/icon/handle/resize_handle.png"), parent),
+ : QGraphicsItem(parent),
m_weakResizeController(resizeController.toWeakResizeController())
{
- setShapeMode(QGraphicsPixmapItem::BoundingRectShape);
- setOffset(-pixmap().rect().center());
setFlag(QGraphicsItem::ItemIsMovable, true);
setFlag(QGraphicsItem::ItemIgnoresTransformations, true);
}
@@ -53,14 +53,20 @@ void ResizeHandleItem::setHandlePosition(const QPointF & globalPosition, const Q
QRectF ResizeHandleItem::boundingRect() const
{
- return QGraphicsPixmapItem::boundingRect().adjusted(-1, -1, 1, 1);
+ return QRectF(- 3., - 3., 7., 7.);
}
-QPainterPath ResizeHandleItem::shape() const
+void ResizeHandleItem::paint(QPainter *painter, const QStyleOptionGraphicsItem * /* option */, QWidget * /* widget */)
{
- return QGraphicsItem::shape();
+ painter->save();
+ painter->setRenderHint(QPainter::Antialiasing, false);
+ painter->setBrush(QColor(255, 255, 255));
+ painter->drawRect(QRectF(-2., -2., 4., 4.));
+
+ painter->restore();
}
+
ResizeController ResizeHandleItem::resizeController() const
{
return ResizeController(m_weakResizeController.toResizeController());
diff --git a/src/plugins/qmldesigner/components/formeditor/resizehandleitem.h b/src/plugins/qmldesigner/components/formeditor/resizehandleitem.h
index 35d68d5e8e..1de9b7ea01 100644
--- a/src/plugins/qmldesigner/components/formeditor/resizehandleitem.h
+++ b/src/plugins/qmldesigner/components/formeditor/resizehandleitem.h
@@ -30,7 +30,7 @@
#ifndef RESIZEHANDLEITEM_H
#define RESIZEHANDLEITEM_H
-#include <QGraphicsPixmapItem>
+#include <QGraphicsItem>
#include <qmldesignercorelib_global.h>
@@ -38,7 +38,7 @@
namespace QmlDesigner {
-class QMLDESIGNERCORE_EXPORT ResizeHandleItem : public QGraphicsPixmapItem
+class QMLDESIGNERCORE_EXPORT ResizeHandleItem : public QGraphicsItem
{
public:
enum
@@ -53,7 +53,7 @@ public:
int type() const;
QRectF boundingRect() const;
- QPainterPath shape() const;
+ void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
ResizeController resizeController() const;
diff --git a/src/plugins/qmldesigner/components/formeditor/resizeindicator.cpp b/src/plugins/qmldesigner/components/formeditor/resizeindicator.cpp
index f21ce88bbb..a1741c8724 100644
--- a/src/plugins/qmldesigner/components/formeditor/resizeindicator.cpp
+++ b/src/plugins/qmldesigner/components/formeditor/resizeindicator.cpp
@@ -66,16 +66,22 @@ void ResizeIndicator::clear()
m_itemControllerHash.clear();
}
+bool itemIsResizable(const QmlItemNode &qmlItemNode)
+{
+ return qmlItemNode.isValid()
+ && qmlItemNode.instanceIsResizable()
+ && qmlItemNode.modelIsMovable()
+ && qmlItemNode.modelIsResizable()
+ && !qmlItemNode.instanceHasRotationTransform()
+ && !qmlItemNode.instanceIsInLayoutable();
+}
+
void ResizeIndicator::setItems(const QList<FormEditorItem*> &itemList)
{
clear();
foreach (FormEditorItem* item, itemList) {
- if (item
- && item->qmlItemNode().isValid()
- && item->qmlItemNode().instanceIsResizable()
- && !item->qmlItemNode().instanceHasRotationTransform()
- && !item->qmlItemNode().instanceIsInLayoutable()) {
+ if (item && itemIsResizable(item->qmlItemNode())) {
ResizeController controller(m_layerItem, item);
m_itemControllerHash.insert(item, controller);
}
@@ -86,12 +92,15 @@ void ResizeIndicator::updateItems(const QList<FormEditorItem*> &itemList)
{
foreach (FormEditorItem* item, itemList) {
if (m_itemControllerHash.contains(item)) {
- if (item->qmlItemNode().instanceHasRotationTransform()) {
+ if (!item || !itemIsResizable(item->qmlItemNode())) {
m_itemControllerHash.take(item);
} else {
ResizeController controller(m_itemControllerHash.value(item));
controller.updatePosition();
}
+ } else if (item && itemIsResizable(item->qmlItemNode())) {
+ ResizeController controller(m_layerItem, item);
+ m_itemControllerHash.insert(item, controller);
}
}
}
diff --git a/src/plugins/qmldesigner/components/formeditor/resizeindicator.h b/src/plugins/qmldesigner/components/formeditor/resizeindicator.h
index 7c234b2679..203ab14e5c 100644
--- a/src/plugins/qmldesigner/components/formeditor/resizeindicator.h
+++ b/src/plugins/qmldesigner/components/formeditor/resizeindicator.h
@@ -30,12 +30,10 @@
#ifndef RESIZEINDICATOR_H
#define RESIZEINDICATOR_H
-#include <QHash>
-#include <QPair>
-
#include "resizecontroller.h"
-class QGraphicsRectItem;
+#include <QHash>
+#include <QPair>
namespace QmlDesigner {
@@ -52,7 +50,7 @@ public:
Left = 8
};
- ResizeIndicator(LayerItem *layerItem);
+ explicit ResizeIndicator(LayerItem *layerItem);
~ResizeIndicator();
void show();
@@ -63,19 +61,12 @@ public:
void setItems(const QList<FormEditorItem*> &itemList);
void updateItems(const QList<FormEditorItem*> &itemList);
-//
-// QPair<FormEditorItem*,Orientation> pick(QGraphicsRectItem* pickedItem) const;
-//
-// void show();
-// void hide();
-
-
-
private:
QHash<FormEditorItem*, ResizeController> m_itemControllerHash;
LayerItem *m_layerItem;
};
-}
+} // namespace QmlDesigner
+
#endif // SCALEINDICATOR_H
diff --git a/src/plugins/qmldesigner/components/formeditor/resizemanipulator.cpp b/src/plugins/qmldesigner/components/formeditor/resizemanipulator.cpp
index e35b2ede56..a872e4b090 100644
--- a/src/plugins/qmldesigner/components/formeditor/resizemanipulator.cpp
+++ b/src/plugins/qmldesigner/components/formeditor/resizemanipulator.cpp
@@ -146,8 +146,7 @@ void ResizeManipulator::update(const QPointF& updatePoint, Snapper::Snapping use
if (boundingRect.height() < minimumHeight)
boundingRect.setHeight(minimumHeight);
- setSize(formEditorItem->qmlItemNode(), boundingRect.size());
-
+ formEditorItem->qmlItemNode().setSize(boundingRect.size());
if (anchors.instanceHasAnchor(AnchorLine::Bottom)) {
anchors.setMargin(AnchorLine::Bottom,
@@ -184,8 +183,8 @@ void ResizeManipulator::update(const QPointF& updatePoint, Snapper::Snapping use
if (boundingRect.height() < minimumHeight)
boundingRect.setTop(boundingRect.top() - minimumHeight + boundingRect.height());
- setSize(formEditorItem->qmlItemNode(), boundingRect.size());
- setPosition(formEditorItem->qmlItemNode(), m_beginToParentTransform.map(boundingRect.topLeft()));
+ formEditorItem->qmlItemNode().setSize(boundingRect.size());
+ formEditorItem->qmlItemNode().setPosition(m_beginToParentTransform.map(boundingRect.topLeft()));
if (anchors.instanceHasAnchor(AnchorLine::Top)) {
@@ -223,8 +222,8 @@ void ResizeManipulator::update(const QPointF& updatePoint, Snapper::Snapping use
if (boundingRect.width() < minimumWidth)
boundingRect.setWidth(minimumWidth);
- setSize(formEditorItem->qmlItemNode(), boundingRect.size());
- setPosition(formEditorItem->qmlItemNode(), m_beginToParentTransform.map(boundingRect.topLeft()));
+ formEditorItem->qmlItemNode().setSize(boundingRect.size());
+ formEditorItem->qmlItemNode().setPosition( m_beginToParentTransform.map(boundingRect.topLeft()));
if (anchors.instanceHasAnchor(AnchorLine::Top)) {
anchors.setMargin(AnchorLine::Top,
@@ -261,8 +260,8 @@ void ResizeManipulator::update(const QPointF& updatePoint, Snapper::Snapping use
if (boundingRect.width() < minimumWidth)
boundingRect.setLeft(boundingRect.left() - minimumWidth + boundingRect.width());
- setSize(formEditorItem->qmlItemNode(), boundingRect.size());
- setPosition(formEditorItem->qmlItemNode(), m_beginToParentTransform.map(boundingRect.topLeft()));
+ formEditorItem->qmlItemNode().setSize(boundingRect.size());
+ formEditorItem->qmlItemNode().setPosition(m_beginToParentTransform.map(boundingRect.topLeft()));
if (anchors.instanceHasAnchor(AnchorLine::Left)) {
anchors.setMargin(AnchorLine::Left,
@@ -290,7 +289,7 @@ void ResizeManipulator::update(const QPointF& updatePoint, Snapper::Snapping use
if (boundingRect.height() < minimumHeight)
boundingRect.setHeight(minimumHeight);
- setSize(formEditorItem->qmlItemNode(), boundingRect.size());
+ formEditorItem->qmlItemNode().setSize(boundingRect.size());
if (anchors.instanceHasAnchor(AnchorLine::Bottom)) {
anchors.setMargin(AnchorLine::Bottom,
@@ -313,8 +312,8 @@ void ResizeManipulator::update(const QPointF& updatePoint, Snapper::Snapping use
if (boundingRect.height() < minimumHeight)
boundingRect.setTop(boundingRect.top() - minimumHeight + boundingRect.height());
- setSize(formEditorItem->qmlItemNode(), boundingRect.size());
- setPosition(formEditorItem->qmlItemNode(), m_beginToParentTransform.map(boundingRect.topLeft()));
+ formEditorItem->qmlItemNode().setSize(boundingRect.size());
+ formEditorItem->qmlItemNode().setPosition(m_beginToParentTransform.map(boundingRect.topLeft()));
if (anchors.instanceHasAnchor(AnchorLine::Top)) {
anchors.setMargin(AnchorLine::Top,
@@ -337,7 +336,7 @@ void ResizeManipulator::update(const QPointF& updatePoint, Snapper::Snapping use
if (boundingRect.width() < minimumWidth)
boundingRect.setWidth(minimumWidth);
- setSize(formEditorItem->qmlItemNode(), boundingRect.size());
+ formEditorItem->qmlItemNode().setSize(boundingRect.size());
if (anchors.instanceHasAnchor(AnchorLine::Right)) {
@@ -361,8 +360,8 @@ void ResizeManipulator::update(const QPointF& updatePoint, Snapper::Snapping use
if (boundingRect.width() < minimumWidth)
boundingRect.setLeft(boundingRect.left() - minimumWidth + boundingRect.width());
- setSize(formEditorItem->qmlItemNode(), boundingRect.size());
- setPosition(formEditorItem->qmlItemNode(), m_beginToParentTransform.map(boundingRect.topLeft()));
+ formEditorItem->qmlItemNode().setSize(boundingRect.size());
+ formEditorItem->qmlItemNode().setPosition(m_beginToParentTransform.map(boundingRect.topLeft()));
if (anchors.instanceHasAnchor(AnchorLine::Left)) {
anchors.setMargin(AnchorLine::Left,
@@ -501,21 +500,4 @@ bool ResizeManipulator::isActive() const
return m_isActive;
}
-void ResizeManipulator::setSize(QmlItemNode itemNode, const QSizeF &size)
-{
- if (!itemNode.hasBindingProperty("width"))
- itemNode.setVariantProperty("width", qRound(size.width()));
-
- if (!itemNode.hasBindingProperty("height"))
- itemNode.setVariantProperty("height", qRound(size.height()));
-}
-
-void ResizeManipulator::setPosition(QmlItemNode itemNode, const QPointF &position)
-{
- if (!itemNode.hasBindingProperty("x"))
- itemNode.setVariantProperty("x", qRound(position.x()));
-
- if (!itemNode.hasBindingProperty("y"))
- itemNode.setVariantProperty("y", qRound(position.y()));
-}
}
diff --git a/src/plugins/qmldesigner/components/formeditor/resizemanipulator.h b/src/plugins/qmldesigner/components/formeditor/resizemanipulator.h
index 2654a36598..c3b274853e 100644
--- a/src/plugins/qmldesigner/components/formeditor/resizemanipulator.h
+++ b/src/plugins/qmldesigner/components/formeditor/resizemanipulator.h
@@ -64,8 +64,6 @@ protected:
bool isInvalidSize(const QSizeF & size);
void deleteSnapLines();
ResizeHandleItem *resizeHandle();
- void setSize(QmlItemNode itemNode, const QSizeF &size);
- void setPosition(QmlItemNode itemNode, const QPointF &position);
private:
Snapper m_snapper;
diff --git a/src/plugins/qmldesigner/components/formeditor/resizetool.cpp b/src/plugins/qmldesigner/components/formeditor/resizetool.cpp
index 78d8f094cd..48f36d6fbd 100644
--- a/src/plugins/qmldesigner/components/formeditor/resizetool.cpp
+++ b/src/plugins/qmldesigner/components/formeditor/resizetool.cpp
@@ -45,6 +45,7 @@ ResizeTool::ResizeTool(FormEditorView *editorView)
: AbstractFormEditorTool(editorView),
m_selectionIndicator(editorView->scene()->manipulatorLayerItem()),
m_resizeIndicator(editorView->scene()->manipulatorLayerItem()),
+ m_anchorIndicator(editorView->scene()->manipulatorLayerItem()),
m_resizeManipulator(editorView->scene()->manipulatorLayerItem(), editorView)
{
}
@@ -66,6 +67,7 @@ void ResizeTool::mousePressEvent(const QList<QGraphicsItem*> &itemList,
m_resizeManipulator.setHandle(resizeHandle);
m_resizeManipulator.begin(event->scenePos());
m_resizeIndicator.hide();
+ m_anchorIndicator.hide();
}
}
@@ -116,6 +118,7 @@ void ResizeTool::mouseReleaseEvent(const QList<QGraphicsItem*> &itemList,
m_selectionIndicator.show();
m_resizeIndicator.show();
+ m_anchorIndicator.show();
m_resizeManipulator.end(generateUseSnapping(event->modifiers()));
}
@@ -176,12 +179,14 @@ void ResizeTool::selectedItemsChanged(const QList<FormEditorItem*> & /*itemList*
{
m_selectionIndicator.setItems(items());
m_resizeIndicator.setItems(items());
+ m_anchorIndicator.setItems(items());
}
void ResizeTool::clear()
{
m_selectionIndicator.clear();
m_resizeIndicator.clear();
+ m_anchorIndicator.clear();
m_resizeManipulator.clear();
}
@@ -189,6 +194,7 @@ void ResizeTool::formEditorItemsChanged(const QList<FormEditorItem*> &itemList)
{
m_selectionIndicator.updateItems(itemList);
m_resizeIndicator.updateItems(itemList);
+ m_anchorIndicator.updateItems(itemList);
}
void ResizeTool::instancesCompleted(const QList<FormEditorItem*> &/*itemList*/)
diff --git a/src/plugins/qmldesigner/components/formeditor/resizetool.h b/src/plugins/qmldesigner/components/formeditor/resizetool.h
index a8d3f9a645..81954b5e67 100644
--- a/src/plugins/qmldesigner/components/formeditor/resizetool.h
+++ b/src/plugins/qmldesigner/components/formeditor/resizetool.h
@@ -33,6 +33,7 @@
#include "abstractformeditortool.h"
#include "selectionindicator.h"
#include "resizeindicator.h"
+#include "anchorindicator.h"
#include "resizemanipulator.h"
@@ -77,6 +78,7 @@ public:
private:
SelectionIndicator m_selectionIndicator;
ResizeIndicator m_resizeIndicator;
+ AnchorIndicator m_anchorIndicator;
ResizeManipulator m_resizeManipulator;
};
diff --git a/src/plugins/qmldesigner/components/formeditor/rubberbandselectionmanipulator.cpp b/src/plugins/qmldesigner/components/formeditor/rubberbandselectionmanipulator.cpp
index 1a33b4e04a..727da8ef84 100644
--- a/src/plugins/qmldesigner/components/formeditor/rubberbandselectionmanipulator.cpp
+++ b/src/plugins/qmldesigner/components/formeditor/rubberbandselectionmanipulator.cpp
@@ -72,7 +72,7 @@ void RubberBandSelectionManipulator::begin(const QPointF& beginPoint)
m_selectionRectangleElement.show();
m_isActive = true;
m_beginFormEditorItem = topFormEditorItem(m_editorView->scene()->items(beginPoint));
- m_oldSelectionList = m_editorView->selectedQmlItemNodes();
+ m_oldSelectionList = toQmlItemNodeList(m_editorView->selectedModelNodes());
}
void RubberBandSelectionManipulator::update(const QPointF& updatePoint)
@@ -103,6 +103,7 @@ void RubberBandSelectionManipulator::select(SelectionType selectionType)
&& formEditorItem->qmlItemNode().isValid()
&& m_beginFormEditorItem->childItems().contains(formEditorItem)
&& formEditorItem->qmlItemNode().instanceIsMovable()
+ && formEditorItem->qmlItemNode().modelIsMovable()
&& !formEditorItem->qmlItemNode().instanceIsInLayoutable())
{
newNodeList.append(formEditorItem->qmlItemNode());
@@ -112,6 +113,7 @@ void RubberBandSelectionManipulator::select(SelectionType selectionType)
if (newNodeList.isEmpty()
&& m_beginFormEditorItem->qmlItemNode().isValid()
&& m_beginFormEditorItem->qmlItemNode().instanceIsMovable()
+ && m_beginFormEditorItem->qmlItemNode().modelIsMovable()
&& !m_beginFormEditorItem->qmlItemNode().instanceIsInLayoutable())
newNodeList.append(m_beginFormEditorItem->qmlItemNode());
@@ -134,7 +136,7 @@ void RubberBandSelectionManipulator::select(SelectionType selectionType)
}
}
- m_editorView->setSelectedQmlItemNodes(nodeList);
+ m_editorView->setSelectedModelNodes(toModelNodeList(nodeList));
}
diff --git a/src/plugins/qmldesigner/components/formeditor/selectiontool.cpp b/src/plugins/qmldesigner/components/formeditor/selectiontool.cpp
index 6df144c783..eb51bb808d 100644
--- a/src/plugins/qmldesigner/components/formeditor/selectiontool.cpp
+++ b/src/plugins/qmldesigner/components/formeditor/selectiontool.cpp
@@ -33,6 +33,7 @@
#include "resizehandleitem.h"
+#include <nodemetainfo.h>
#include <QGraphicsSceneMouseEvent>
#include <QDebug>
@@ -48,6 +49,9 @@ SelectionTool::SelectionTool(FormEditorView *editorView)
m_singleSelectionManipulator(editorView),
m_selectionIndicator(editorView->scene()->manipulatorLayerItem()),
m_resizeIndicator(editorView->scene()->manipulatorLayerItem()),
+ m_anchorIndicator(editorView->scene()->manipulatorLayerItem()),
+ m_bindingIndicator(editorView->scene()->manipulatorLayerItem()),
+ m_contentNotEditableIndicator(editorView->scene()->manipulatorLayerItem()),
m_selectOnlyContentItems(false)
{
m_selectionIndicator.setCursor(Qt::ArrowCursor);
@@ -141,32 +145,19 @@ void SelectionTool::hoverMoveEvent(const QList<QGraphicsItem*> &itemList,
}
}
- FormEditorItem *topSelectableItem = 0;
-
- foreach (QGraphicsItem* item, itemList)
- {
- FormEditorItem *formEditorItem = FormEditorItem::fromQGraphicsItem(item);
-
- if (formEditorItem
- && formEditorItem->qmlItemNode().isValid()
- && !formEditorItem->qmlItemNode().instanceIsInLayoutable()
- && formEditorItem->qmlItemNode().instanceIsMovable()
- && (formEditorItem->qmlItemNode().hasShowContent() || !m_selectOnlyContentItems))
- {
- topSelectableItem = formEditorItem;
- break;
- }
- }
+ FormEditorItem *topSelectableItem = topMovableFormEditorItem(itemList, m_selectOnlyContentItems);
scene()->highlightBoundingRect(topSelectableItem);
+
+ m_contentNotEditableIndicator.setItems(toFormEditorItemList(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()) {
+ } else if (m_rubberbandSelectionManipulator.isActive()) {
QPointF mouseMovementVector = m_rubberbandSelectionManipulator.beginPoint() - event->scenePos();
if (mouseMovementVector.toPoint().manhattanLength() < s_startDragDistance) {
@@ -258,6 +249,8 @@ void SelectionTool::clear()
m_singleSelectionManipulator.clear();
m_selectionIndicator.clear();
m_resizeIndicator.clear();
+ m_anchorIndicator.clear();
+ m_bindingIndicator.clear();
AbstractFormEditorTool::clear();
}
@@ -266,12 +259,16 @@ void SelectionTool::selectedItemsChanged(const QList<FormEditorItem*> &itemList)
{
m_selectionIndicator.setItems(itemList);
m_resizeIndicator.setItems(itemList);
+ m_anchorIndicator.setItems(itemList);
+ m_bindingIndicator.setItems(itemList);
}
void SelectionTool::formEditorItemsChanged(const QList<FormEditorItem*> &itemList)
{
m_selectionIndicator.updateItems(itemList);
m_resizeIndicator.updateItems(itemList);
+ m_anchorIndicator.updateItems(itemList);
+ m_bindingIndicator.updateItems(itemList);
}
void SelectionTool::instancesCompleted(const QList<FormEditorItem*> &/*itemList*/)
diff --git a/src/plugins/qmldesigner/components/formeditor/selectiontool.h b/src/plugins/qmldesigner/components/formeditor/selectiontool.h
index 464630f59e..c97141e540 100644
--- a/src/plugins/qmldesigner/components/formeditor/selectiontool.h
+++ b/src/plugins/qmldesigner/components/formeditor/selectiontool.h
@@ -36,6 +36,9 @@
#include "singleselectionmanipulator.h"
#include "selectionindicator.h"
#include "resizeindicator.h"
+#include "anchorindicator.h"
+#include "bindingindicator.h"
+#include "contentnoteditableindicator.h"
#include <QTime>
@@ -92,6 +95,9 @@ private:
SingleSelectionManipulator m_singleSelectionManipulator;
SelectionIndicator m_selectionIndicator;
ResizeIndicator m_resizeIndicator;
+ AnchorIndicator m_anchorIndicator;
+ BindingIndicator m_bindingIndicator;
+ ContentNotEditableIndicator m_contentNotEditableIndicator;
QTime m_mousePressTimer;
bool m_selectOnlyContentItems;
QCursor m_cursor;
diff --git a/src/plugins/qmldesigner/components/formeditor/singleselectionmanipulator.cpp b/src/plugins/qmldesigner/components/formeditor/singleselectionmanipulator.cpp
index fedccd62e2..86e9d3874a 100644
--- a/src/plugins/qmldesigner/components/formeditor/singleselectionmanipulator.cpp
+++ b/src/plugins/qmldesigner/components/formeditor/singleselectionmanipulator.cpp
@@ -46,7 +46,7 @@ void SingleSelectionManipulator::begin(const QPointF &beginPoint)
{
m_beginPoint = beginPoint;
m_isActive = true;
- m_oldSelectionList = m_editorView->selectedQmlItemNodes();
+ m_oldSelectionList = toQmlItemNodeList(m_editorView->selectedModelNodes());
}
void SingleSelectionManipulator::update(const QPointF &/*updatePoint*/)
@@ -79,7 +79,7 @@ void SingleSelectionManipulator::select(SelectionType selectionType, bool select
if (formEditorItem
&& formEditorItem->qmlItemNode().isValid()
- && (formEditorItem->qmlItemNode().hasShowContent() || !selectOnlyContentItems))
+ && (formEditorItem->qmlItemNode().instanceHasShowContent() || !selectOnlyContentItems))
{
selectedNode = formEditorItem->qmlItemNode();
break;
@@ -113,7 +113,7 @@ void SingleSelectionManipulator::select(SelectionType selectionType, bool select
}
}
- m_editorView->setSelectedQmlItemNodes(nodeList);
+ m_editorView->setSelectedModelNodes(toModelNodeList(nodeList));
}
diff --git a/src/plugins/qmldesigner/components/formeditor/singleselectionmanipulator.h b/src/plugins/qmldesigner/components/formeditor/singleselectionmanipulator.h
index 14369c913d..82556dc72b 100644
--- a/src/plugins/qmldesigner/components/formeditor/singleselectionmanipulator.h
+++ b/src/plugins/qmldesigner/components/formeditor/singleselectionmanipulator.h
@@ -32,6 +32,8 @@
#include "formeditorview.h"
+#include <QPointF>
+
namespace QmlDesigner {
class SingleSelectionManipulator
diff --git a/src/plugins/qmldesigner/components/formeditor/snapper.cpp b/src/plugins/qmldesigner/components/formeditor/snapper.cpp
index f3dff72030..5b81e2ac8e 100644
--- a/src/plugins/qmldesigner/components/formeditor/snapper.cpp
+++ b/src/plugins/qmldesigner/components/formeditor/snapper.cpp
@@ -478,7 +478,7 @@ static QLineF mergedHorizontalLine(const QList<QLineF> &lineList)
}
double y(lineList.first().y1());
- return QLineF(minimumX, y, maximumX, y);;
+ return QLineF(minimumX, y, maximumX, y);
}
static QLineF mergedVerticalLine(const QList<QLineF> &lineList)
@@ -496,7 +496,7 @@ static QLineF mergedVerticalLine(const QList<QLineF> &lineList)
}
double x(lineList.first().x1());
- return QLineF(x, minimumY, x, maximumY);;
+ return QLineF(x, minimumY, x, maximumY);
}
static QList<QLineF> mergedHorizontalLines(const QList<QLineF> &lineList)
diff --git a/src/plugins/qmldesigner/components/formeditor/toolbox.cpp b/src/plugins/qmldesigner/components/formeditor/toolbox.cpp
index 9d010324d1..0afb3aa750 100644
--- a/src/plugins/qmldesigner/components/formeditor/toolbox.cpp
+++ b/src/plugins/qmldesigner/components/formeditor/toolbox.cpp
@@ -39,39 +39,19 @@ namespace QmlDesigner {
ToolBox::ToolBox(QWidget *parentWidget)
: Utils::StyledBar(parentWidget),
m_leftToolBar(new QToolBar("LeftSidebar", this)),
- m_rightToolBar(new QToolBar("RightSidebar", this)),
- m_formEditorCrumbleBar(new FormEditorCrumbleBar(this))
+ m_rightToolBar(new QToolBar("RightSidebar", this))
{
- setMaximumHeight(44);
- setSingleRow(false);
- QFrame *frame = new QFrame(this);
- 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_formEditorCrumbleBar->crumblePath());
- frame->setProperty("panelwidget", true);
- frame->setProperty("panelwidget_singlerow", false);
- QVBoxLayout *verticalLayout = new QVBoxLayout(this);
- verticalLayout->setMargin(0);
- verticalLayout->setSpacing(0);
-
- QHBoxLayout *horizontalLayout = new QHBoxLayout();
- verticalLayout->addLayout(horizontalLayout);
- verticalLayout->addWidget(frame);
- horizontalLayout->setMargin(0);
- horizontalLayout->setSpacing(0);
-
+ setMaximumHeight(22);
m_leftToolBar->setFloatable(true);
m_leftToolBar->setMovable(true);
m_leftToolBar->setOrientation(Qt::Horizontal);
m_leftToolBar->setIconSize(QSize(24, 24));
- QToolBar *stretchToolbar = new QToolBar(this);
+ QHBoxLayout *horizontalLayout = new QHBoxLayout(this);
+ horizontalLayout->setMargin(0);
+ horizontalLayout->setSpacing(0);
- setSingleRow(false);
+ QToolBar *stretchToolbar = new QToolBar(this);
m_leftToolBar->setProperty("panelwidget", true);
m_leftToolBar->setProperty("panelwidget_singlerow", false);
@@ -121,9 +101,4 @@ QList<QAction*> ToolBox::actions() const
return QList<QAction*>() << m_leftToolBar->actions() << m_rightToolBar->actions();
}
-FormEditorCrumbleBar *ToolBox::formEditorCrumbleBar() const
-{
- return m_formEditorCrumbleBar;
-}
-
} // namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/components/formeditor/toolbox.h b/src/plugins/qmldesigner/components/formeditor/toolbox.h
index 8974ae6b71..b58cd0dd80 100644
--- a/src/plugins/qmldesigner/components/formeditor/toolbox.h
+++ b/src/plugins/qmldesigner/components/formeditor/toolbox.h
@@ -30,9 +30,7 @@
#ifndef TOOLBOX_H
#define TOOLBOX_H
-#include "utils/styledbar.h"
-
-#include "formeditorcrumblebar.h"
+#include <utils/styledbar.h>
QT_BEGIN_NAMESPACE
class QToolBar;
@@ -53,12 +51,10 @@ public:
void addLeftSideAction(QAction *action);
void addRightSideAction(QAction *action);
QList<QAction*> actions() const;
- FormEditorCrumbleBar *formEditorCrumbleBar() const;
private:
QToolBar *m_leftToolBar;
QToolBar *m_rightToolBar;
- FormEditorCrumbleBar *m_formEditorCrumbleBar;
};
} // namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/components/importmanager/importlabel.cpp b/src/plugins/qmldesigner/components/importmanager/importlabel.cpp
new file mode 100644
index 0000000000..d93ae20833
--- /dev/null
+++ b/src/plugins/qmldesigner/components/importmanager/importlabel.cpp
@@ -0,0 +1,76 @@
+/****************************************************************************
+**
+** 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 "importlabel.h"
+
+#include <QHBoxLayout>
+#include <QPushButton>
+
+namespace QmlDesigner {
+
+ImportLabel::ImportLabel(QWidget *parent) :
+ QWidget(parent)
+{
+ QHBoxLayout *layout = new QHBoxLayout(this);
+ layout->setContentsMargins(0, 0, 0, 0);
+
+
+ m_removeButton = new QPushButton("X", this);
+ m_removeButton->setFlat(true);
+ m_removeButton->setMaximumWidth(20);
+ m_removeButton->setMaximumHeight(20);
+ m_removeButton->setFocusPolicy(Qt::NoFocus);
+ m_removeButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
+ connect(m_removeButton, SIGNAL(clicked()), this, SLOT(emitRemoveImport()));
+ layout->addWidget(m_removeButton);
+
+ m_importLabel = new QLabel(this);
+ layout->addWidget(m_importLabel);
+
+ setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
+}
+
+void ImportLabel::setImport(const Import &import)
+{
+ m_importLabel->setText(import.toString(false));
+
+ m_import = import;
+}
+
+const Import ImportLabel::import() const
+{
+ return m_import;
+}
+
+void ImportLabel::emitRemoveImport()
+{
+ emit removeImport(m_import);
+}
+
+} // namespace QmlDesigner
diff --git a/src/plugins/cpaster/codepastersettings.h b/src/plugins/qmldesigner/components/importmanager/importlabel.h
index ebc58d45ab..29ff948b7c 100644
--- a/src/plugins/cpaster/codepastersettings.h
+++ b/src/plugins/qmldesigner/components/importmanager/importlabel.h
@@ -27,37 +27,36 @@
**
****************************************************************************/
-#ifndef CODEPASTERSETTINGSPAGE_H
-#define CODEPASTERSETTINGSPAGE_H
+#ifndef IMPORTLABEL_H
+#define IMPORTLABEL_H
-#include <coreplugin/dialogs/ioptionspage.h>
+#include <QLabel>
+#include <QPushButton>
-QT_BEGIN_NAMESPACE
-class QSettings;
-QT_END_NAMESPACE
+#include <import.h>
-namespace CodePaster {
+namespace QmlDesigner {
-class CodePasterSettingsPage : public Core::IOptionsPage
+class ImportLabel : public QWidget
{
Q_OBJECT
-
public:
- CodePasterSettingsPage();
+ explicit ImportLabel(QWidget *parent = 0);
- QWidget *createPage(QWidget *parent);
- void apply();
- void finish() { }
+ void setImport(const Import &import);
+ const Import import() const;
- QString hostName() const;
+signals:
+ void removeImport(const Import &import);
-public slots:
- void serverChanged(const QString &host);
+private slots:
+ void emitRemoveImport();
private:
- QString m_host;
+ Import m_import;
+ QLabel *m_importLabel;
+ QPushButton *m_removeButton;
};
-} // namespace CodePaster
-
-#endif // SETTINGSPAGE_H
+}
+#endif // IMPORTLABEL_H
diff --git a/src/plugins/qmldesigner/components/importmanager/importmanager.pri b/src/plugins/qmldesigner/components/importmanager/importmanager.pri
new file mode 100644
index 0000000000..6f0a672cc3
--- /dev/null
+++ b/src/plugins/qmldesigner/components/importmanager/importmanager.pri
@@ -0,0 +1,11 @@
+VPATH += $$PWD
+
+HEADERS += importmanagerview.h \
+ components/importmanager/importlabel.h
+HEADERS += importswidget.h
+
+SOURCES += importmanagerview.cpp \
+ components/importmanager/importlabel.cpp
+SOURCES += components/importmanager/importswidget.cpp
+
+
diff --git a/src/plugins/qmldesigner/components/importmanager/importmanagerview.cpp b/src/plugins/qmldesigner/components/importmanager/importmanagerview.cpp
new file mode 100644
index 0000000000..576a34f4c9
--- /dev/null
+++ b/src/plugins/qmldesigner/components/importmanager/importmanagerview.cpp
@@ -0,0 +1,257 @@
+/****************************************************************************
+**
+** 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 "importmanagerview.h"
+#include "importswidget.h"
+
+
+namespace QmlDesigner {
+
+ImportManagerView::ImportManagerView(QObject *parent) :
+ AbstractView(parent),
+ m_importsWidget(0)
+
+{
+}
+
+ImportManagerView::~ImportManagerView()
+{
+
+}
+
+bool ImportManagerView::hasWidget() const
+{
+ return true;
+}
+
+WidgetInfo ImportManagerView::widgetInfo()
+{
+ if (m_importsWidget == 0) {
+ m_importsWidget = new ImportsWidget;
+ connect(m_importsWidget, SIGNAL(removeImport(Import)), this, SLOT(removeImport(Import)));
+ connect(m_importsWidget, SIGNAL(addImport(Import)), this, SLOT(addImport(Import)));
+
+ if (model())
+ m_importsWidget->setImports(model()->imports());
+ }
+
+ return createWidgetInfo(m_importsWidget, 0, "ImportManager", WidgetInfo::LeftPane, 1);
+}
+
+void ImportManagerView::modelAttached(Model *model)
+{
+ AbstractView::modelAttached(model);
+
+ if (m_importsWidget) {
+ m_importsWidget->setImports(model->imports());
+ m_importsWidget->setPossibleImports(model->possibleImports());
+ m_importsWidget->setUsedImports(model->usedImports());
+ }
+}
+
+void ImportManagerView::modelAboutToBeDetached(Model *model)
+{
+ if (m_importsWidget) {
+ m_importsWidget->removeImports();
+ m_importsWidget->removePossibleImports();
+ m_importsWidget->removeUsedImports();
+ }
+
+ AbstractView::modelAboutToBeDetached(model);
+}
+
+void ImportManagerView::nodeCreated(const ModelNode &/*createdNode*/)
+{
+ if (m_importsWidget)
+ m_importsWidget->setUsedImports(model()->usedImports());
+}
+
+void ImportManagerView::nodeAboutToBeRemoved(const ModelNode &/*removedNode*/)
+{
+ if (m_importsWidget)
+ m_importsWidget->setUsedImports(model()->usedImports());
+}
+
+void ImportManagerView::nodeRemoved(const ModelNode &/*removedNode*/, const NodeAbstractProperty &/*parentProperty*/, AbstractView::PropertyChangeFlags /*propertyChange*/)
+{
+
+}
+
+void ImportManagerView::nodeAboutToBeReparented(const ModelNode &/*node*/, const NodeAbstractProperty &/*newPropertyParent*/, const NodeAbstractProperty &/*oldPropertyParent*/, AbstractView::PropertyChangeFlags /*propertyChange*/)
+{
+
+}
+
+void ImportManagerView::nodeReparented(const ModelNode &/*node*/, const NodeAbstractProperty &/*newPropertyParent*/, const NodeAbstractProperty &/*oldPropertyParent*/, AbstractView::PropertyChangeFlags /*propertyChange*/)
+{
+
+}
+
+void ImportManagerView::nodeIdChanged(const ModelNode &/*node*/, const QString &/*newId*/, const QString &/*oldId*/)
+{
+
+}
+
+void ImportManagerView::propertiesAboutToBeRemoved(const QList<AbstractProperty> &/*propertyList*/)
+{
+
+}
+
+void ImportManagerView::propertiesRemoved(const QList<AbstractProperty> &/*propertyList*/)
+{
+
+}
+
+void ImportManagerView::variantPropertiesChanged(const QList<VariantProperty> &/*propertyList*/, AbstractView::PropertyChangeFlags /*propertyChange*/)
+{
+
+}
+
+void ImportManagerView::bindingPropertiesChanged(const QList<BindingProperty> &/*propertyList*/, AbstractView::PropertyChangeFlags /*propertyChange*/)
+{
+
+}
+
+void ImportManagerView::signalHandlerPropertiesChanged(const QVector<SignalHandlerProperty> &/*propertyList*/, AbstractView::PropertyChangeFlags /*propertyChange*/)
+{
+
+}
+
+void ImportManagerView::rootNodeTypeChanged(const QString &/*type*/, int /*majorVersion*/, int /*minorVersion*/)
+{
+
+}
+
+void ImportManagerView::instancePropertyChange(const QList<QPair<ModelNode, PropertyName> > &/*propertyList*/)
+{
+
+}
+
+void ImportManagerView::instancesCompleted(const QVector<ModelNode> &/*completedNodeList*/)
+{
+
+}
+
+void ImportManagerView::instanceInformationsChange(const QMultiHash<ModelNode, InformationName> &/*informationChangeHash*/)
+{
+
+}
+
+void ImportManagerView::instancesRenderImageChanged(const QVector<ModelNode> &/*nodeList*/)
+{
+
+}
+
+void ImportManagerView::instancesPreviewImageChanged(const QVector<ModelNode> &/*nodeList*/)
+{
+
+}
+
+void ImportManagerView::instancesChildrenChanged(const QVector<ModelNode> &/*nodeList*/)
+{
+
+}
+
+void ImportManagerView::instancesToken(const QString &/*tokenName*/, int /*tokenNumber*/, const QVector<ModelNode> &/*nodeVector*/)
+{
+
+}
+
+void ImportManagerView::nodeSourceChanged(const ModelNode &/*modelNode*/, const QString &/*newNodeSource*/)
+{
+
+}
+
+void ImportManagerView::rewriterBeginTransaction()
+{
+
+}
+
+void ImportManagerView::rewriterEndTransaction()
+{
+
+}
+
+void ImportManagerView::currentStateChanged(const ModelNode &/*node*/)
+{
+
+}
+
+void ImportManagerView::selectedNodesChanged(const QList<ModelNode> &/*selectedNodeList*/, const QList<ModelNode> &/*lastSelectedNodeList*/)
+{
+
+}
+
+void ImportManagerView::fileUrlChanged(const QUrl &/*oldUrl*/, const QUrl &/*newUrl*/)
+{
+
+}
+
+void ImportManagerView::nodeOrderChanged(const NodeListProperty &/*listProperty*/, const ModelNode &/*movedNode*/, int /*oldIndex*/)
+{
+
+}
+
+void ImportManagerView::importsChanged(const QList<Import> &/*addedImports*/, const QList<Import> &/*removedImports*/)
+{
+ if (m_importsWidget) {
+ m_importsWidget->setImports(model()->imports());
+ m_importsWidget->setPossibleImports(model()->possibleImports());
+ m_importsWidget->setUsedImports(model()->usedImports());
+ }
+}
+
+void ImportManagerView::auxiliaryDataChanged(const ModelNode &/*node*/, const PropertyName &/*name*/, const QVariant &/*data*/)
+{
+
+}
+
+void ImportManagerView::customNotification(const AbstractView * /*view*/, const QString &/*identifier*/, const QList<ModelNode> &/*nodeList*/, const QList<QVariant> &/*data*/)
+{
+
+}
+
+void ImportManagerView::scriptFunctionsChanged(const ModelNode &/*node*/, const QStringList &/*scriptFunctionList*/)
+{
+
+}
+
+void ImportManagerView::removeImport(const Import &import)
+{
+ if (model())
+ model()->changeImports(QList<Import>(), QList<Import>() << import);
+}
+
+void ImportManagerView::addImport(const Import &import)
+{
+ if (model())
+ model()->changeImports(QList<Import>() << import, QList<Import>());
+}
+
+} // namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/components/importmanager/importmanagerview.h b/src/plugins/qmldesigner/components/importmanager/importmanagerview.h
new file mode 100644
index 0000000000..3e8bb196b8
--- /dev/null
+++ b/src/plugins/qmldesigner/components/importmanager/importmanagerview.h
@@ -0,0 +1,106 @@
+/****************************************************************************
+**
+** 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 QMLDESIGNER_IMPORTMANAGERVIEW_H
+#define QMLDESIGNER_IMPORTMANAGERVIEW_H
+
+#include <abstractview.h>
+#include <QWeakPointer>
+
+namespace QmlDesigner {
+
+class ImportsWidget;
+
+class ImportManagerView : public AbstractView
+{
+ Q_OBJECT
+public:
+ explicit ImportManagerView(QObject *parent = 0);
+ ~ImportManagerView();
+
+ bool hasWidget() const;
+ WidgetInfo widgetInfo();
+
+ void modelAttached(Model *model);
+ void modelAboutToBeDetached(Model *model);
+
+ void nodeCreated(const ModelNode &createdNode);
+ void nodeAboutToBeRemoved(const ModelNode &removedNode);
+ void nodeRemoved(const ModelNode &removedNode, const NodeAbstractProperty &parentProperty, PropertyChangeFlags propertyChange);
+ void nodeAboutToBeReparented(const ModelNode &node, const NodeAbstractProperty &newPropertyParent, const NodeAbstractProperty &oldPropertyParent, AbstractView::PropertyChangeFlags propertyChange);
+ void nodeReparented(const ModelNode &node, const NodeAbstractProperty &newPropertyParent, const NodeAbstractProperty &oldPropertyParent, AbstractView::PropertyChangeFlags propertyChange);
+ void nodeIdChanged(const ModelNode& node, const QString& newId, const QString& oldId);
+ void propertiesAboutToBeRemoved(const QList<AbstractProperty>& propertyList);
+ void propertiesRemoved(const QList<AbstractProperty>& propertyList);
+ void variantPropertiesChanged(const QList<VariantProperty>& propertyList, PropertyChangeFlags propertyChange);
+ void bindingPropertiesChanged(const QList<BindingProperty>& propertyList, PropertyChangeFlags propertyChange);
+ void signalHandlerPropertiesChanged(const QVector<SignalHandlerProperty>& propertyList, PropertyChangeFlags propertyChange);
+ void rootNodeTypeChanged(const QString &type, int majorVersion, int minorVersion);
+
+ void instancePropertyChange(const QList<QPair<ModelNode, PropertyName> > &propertyList);
+ void instancesCompleted(const QVector<ModelNode> &completedNodeList);
+ void instanceInformationsChange(const QMultiHash<ModelNode, InformationName> &informationChangeHash);
+ void instancesRenderImageChanged(const QVector<ModelNode> &nodeList);
+ void instancesPreviewImageChanged(const QVector<ModelNode> &nodeList);
+ void instancesChildrenChanged(const QVector<ModelNode> &nodeList);
+ void instancesToken(const QString &tokenName, int tokenNumber, const QVector<ModelNode> &nodeVector);
+
+ void nodeSourceChanged(const ModelNode &modelNode, const QString &newNodeSource);
+
+ void rewriterBeginTransaction();
+ void rewriterEndTransaction();
+
+ void currentStateChanged(const ModelNode &node); // base state is a invalid model node
+
+ void selectedNodesChanged(const QList<ModelNode> &selectedNodeList,
+ const QList<ModelNode> &lastSelectedNodeList);
+
+ void fileUrlChanged(const QUrl &oldUrl, const QUrl &newUrl);
+
+ void nodeOrderChanged(const NodeListProperty &listProperty, const ModelNode &movedNode, int oldIndex);
+
+ void importsChanged(const QList<Import> &addedImports, const QList<Import> &removedImports);
+
+ void auxiliaryDataChanged(const ModelNode &node, const PropertyName &name, const QVariant &data);
+
+ void customNotification(const AbstractView *view, const QString &identifier, const QList<ModelNode> &nodeList, const QList<QVariant> &data);
+
+ void scriptFunctionsChanged(const ModelNode &node, const QStringList &scriptFunctionList);
+
+private slots:
+ void removeImport(const Import &import);
+ void addImport(const Import &import);
+
+private:
+ ImportsWidget *m_importsWidget;
+};
+
+} // namespace QmlDesigner
+
+#endif // QMLDESIGNER_IMPORTMANAGERVIEW_H
diff --git a/src/plugins/qmldesigner/components/importmanager/importswidget.cpp b/src/plugins/qmldesigner/components/importmanager/importswidget.cpp
new file mode 100644
index 0000000000..5a0cd1ca34
--- /dev/null
+++ b/src/plugins/qmldesigner/components/importmanager/importswidget.cpp
@@ -0,0 +1,156 @@
+/****************************************************************************
+**
+** 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 "importswidget.h"
+
+#include <QVBoxLayout>
+#include <QComboBox>
+
+#include "importlabel.h"
+
+namespace QmlDesigner {
+
+ImportsWidget::ImportsWidget(QWidget *parent) :
+ QWidget(parent)
+{
+ setWindowTitle(tr("Import Manager"));
+ m_addImportComboBox = new QComboBox(this);
+ connect(m_addImportComboBox, SIGNAL(activated(int)), this, SLOT(addSelectedImport(int)));
+}
+
+void ImportsWidget::removeImports()
+{
+ qDeleteAll(m_importLabels);
+ m_importLabels.clear();
+ updateLayout();
+}
+
+static bool isImportAlreadyUsed(const Import &import, QList<ImportLabel*> importLabels)
+{
+ foreach (ImportLabel *importLabel, importLabels) {
+ if (importLabel->import() == import)
+ return true;
+ }
+
+ return false;
+}
+
+void ImportsWidget::setPossibleImports(const QList<Import> &possibleImports)
+{
+ m_addImportComboBox->clear();
+ foreach (const Import &possibleImport, possibleImports) {
+ if (!isImportAlreadyUsed(possibleImport, m_importLabels))
+ m_addImportComboBox->addItem(possibleImport.toString(true), QVariant::fromValue(possibleImport));
+ }
+}
+
+void ImportsWidget::removePossibleImports()
+{
+ m_addImportComboBox->clear();
+}
+
+void ImportsWidget::setUsedImports(const QList<Import> &usedImports)
+{
+ foreach (ImportLabel *importLabel, m_importLabels)
+ importLabel->setDisabled(usedImports.contains(importLabel->import()));
+
+}
+
+void ImportsWidget::removeUsedImports()
+{
+ foreach (ImportLabel *importLabel, m_importLabels)
+ importLabel->setEnabled(true);
+}
+
+static bool importLess(const Import &firstImport, const Import &secondImport)
+{
+ if (firstImport.url() == "QtQuick")
+ return true;
+
+ if (secondImport.url() == "QtQuick")
+ return false;
+
+ if (firstImport.isLibraryImport() && secondImport.isFileImport())
+ return true;
+
+ if (firstImport.isFileImport() && secondImport.isLibraryImport())
+ return false;
+
+ if (firstImport.isFileImport() && secondImport.isFileImport())
+ return QString::localeAwareCompare(firstImport.file(), secondImport.file()) < 0;
+
+ if (firstImport.isLibraryImport() && secondImport.isLibraryImport())
+ return QString::localeAwareCompare(firstImport.url(), secondImport.url()) < 0;
+
+ return false;
+}
+
+void ImportsWidget::setImports(const QList<Import> &imports)
+{
+ qDeleteAll(m_importLabels);
+ m_importLabels.clear();
+
+ QList<Import> sortedImports = imports;
+
+ qSort(sortedImports.begin(), sortedImports.end(), importLess);
+
+ foreach (const Import &import, sortedImports) {
+ ImportLabel *importLabel = new ImportLabel(this);
+ importLabel->setImport(import);
+ m_importLabels.append(importLabel);
+ connect(importLabel, SIGNAL(removeImport(Import)), this, SIGNAL(removeImport(Import)));
+ }
+
+ updateLayout();
+}
+
+
+void ImportsWidget::updateLayout()
+{
+ delete layout();
+
+ QVBoxLayout *layout = new QVBoxLayout(this);
+ layout->setSpacing(0);
+
+ layout->addWidget(m_addImportComboBox);
+
+ foreach (ImportLabel *importLabel, m_importLabels)
+ layout->addWidget(importLabel);
+
+ layout->addStretch();
+}
+
+void ImportsWidget::addSelectedImport(int addImportComboBoxIndex)
+{
+ Import selectedImport = m_addImportComboBox->itemData(addImportComboBoxIndex).value<Import>();
+
+ emit addImport(selectedImport);
+}
+
+} // namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/components/propertyeditor/basiclayouts.cpp b/src/plugins/qmldesigner/components/importmanager/importswidget.h
index bce02e81eb..0938cbb13e 100644
--- a/src/plugins/qmldesigner/components/propertyeditor/basiclayouts.cpp
+++ b/src/plugins/qmldesigner/components/importmanager/importswidget.h
@@ -27,52 +27,51 @@
**
****************************************************************************/
-#include "basiclayouts.h"
+#ifndef QMLDESIGNER_IMPORTSWIDGET_H
+#define QMLDESIGNER_IMPORTSWIDGET_H
+#include <import.h>
+
+#include <QWidget>
QT_BEGIN_NAMESPACE
+class QComboBox;
+QT_END_NAMESPACE
-QBoxLayoutObject::QBoxLayoutObject(QObject *parent)
-: QLayoutObject(parent), _layout(0)
-{
-}
+namespace QmlDesigner {
-QBoxLayoutObject::QBoxLayoutObject(QBoxLayout *layout, QObject *parent)
-: QLayoutObject(parent), _layout(layout)
-{
-}
+class ImportLabel;
-QLayout *QBoxLayoutObject::layout() const
+class ImportsWidget : public QWidget
{
- return _layout;
-}
+ Q_OBJECT
+public:
+ explicit ImportsWidget(QWidget *parent = 0);
-void QBoxLayoutObject::addWidget(QWidget *wid)
-{
- _layout->addWidget(wid);
-}
+ void setImports(const QList<Import> &imports);
+ void removeImports();
-void QBoxLayoutObject::clearWidget()
-{
-}
+ void setPossibleImports(const QList<Import> &possibleImports);
+ void removePossibleImports();
-QHBoxLayoutObject::QHBoxLayoutObject(QObject *parent)
-: QBoxLayoutObject(new QHBoxLayout, parent)
-{
-}
+ void setUsedImports(const QList<Import> &possibleImports);
+ void removeUsedImports();
+signals:
+ void removeImport(const Import &import);
+ void addImport(const Import &import);
-QVBoxLayoutObject::QVBoxLayoutObject(QObject *parent)
-: QBoxLayoutObject(new QVBoxLayout, parent)
-{
-}
+protected:
+ void updateLayout();
-QT_END_NAMESPACE
+private slots:
+ void addSelectedImport(int addImportComboBoxIndex);
-void BasicLayouts::registerDeclarativeTypes()
-{
- qmlRegisterType<QBoxLayoutObject>("Bauhaus",1,0,"QBoxLayout");
- qmlRegisterType<QHBoxLayoutObject>("Bauhaus",1,0,"QHBoxLayout");
- qmlRegisterType<QVBoxLayoutObject>("Bauhaus",1,0,"QVBoxLayout");
-}
+private:
+ QList<ImportLabel*> m_importLabels;
+ QComboBox *m_addImportComboBox;
+};
+
+} // namespace QmlDesigner
+#endif // QMLDESIGNER_IMPORTSWIDGET_H
diff --git a/src/plugins/qmldesigner/components/integration/componentview.cpp b/src/plugins/qmldesigner/components/integration/componentview.cpp
index 346d31b7b9..53d82f8adc 100644
--- a/src/plugins/qmldesigner/components/integration/componentview.cpp
+++ b/src/plugins/qmldesigner/components/integration/componentview.cpp
@@ -139,8 +139,9 @@ void ComponentView::searchForComponentAndAddToList(const ModelNode &node)
m_standardItemModel->appendRow(item);
} else {
QString description;
- ModelNode parentNode = node.parentProperty().parentModelNode();
- if (parentNode.isValid()) {
+ if (node.hasParentProperty()) {
+ ModelNode parentNode = node.parentProperty().parentModelNode();
+
if (parentNode.id().isEmpty())
description = parentNode.simplifiedTypeName() + QLatin1Char(' ');
else
@@ -201,7 +202,7 @@ void ComponentView::nodeSourceChanged(const ModelNode &, const QString & /*newNo
void ComponentView::rewriterBeginTransaction() {}
void ComponentView::rewriterEndTransaction() {}
-void ComponentView::actualStateChanged(const ModelNode &/*node*/) {}
+void ComponentView::currentStateChanged(const ModelNode &/*node*/) {}
void ComponentView::selectedNodesChanged(const QList<ModelNode> &/*selectedNodeList*/,
const QList<ModelNode> &/*lastSelectedNodeList*/) {}
diff --git a/src/plugins/qmldesigner/components/integration/componentview.h b/src/plugins/qmldesigner/components/integration/componentview.h
index f3287940aa..3c5f3ab74b 100644
--- a/src/plugins/qmldesigner/components/integration/componentview.h
+++ b/src/plugins/qmldesigner/components/integration/componentview.h
@@ -95,7 +95,7 @@ public:
void rewriterBeginTransaction() QTC_OVERRIDE;
void rewriterEndTransaction() QTC_OVERRIDE;
- void actualStateChanged(const ModelNode &node) QTC_OVERRIDE;
+ void currentStateChanged(const ModelNode &node) QTC_OVERRIDE;
void selectedNodesChanged(const QList<ModelNode> &selectedNodeList,
const QList<ModelNode> &lastSelectedNodeList) QTC_OVERRIDE;
diff --git a/src/plugins/qmldesigner/components/integration/designdocument.cpp b/src/plugins/qmldesigner/components/integration/designdocument.cpp
index 8b480d5747..510022e76b 100644
--- a/src/plugins/qmldesigner/components/integration/designdocument.cpp
+++ b/src/plugins/qmldesigner/components/integration/designdocument.cpp
@@ -29,13 +29,13 @@
#include "designdocument.h"
#include "designdocumentview.h"
+#include "documentmanager.h"
#include <metainfo.h>
#include <qmlobjectnode.h>
#include <rewritingexception.h>
#include <nodelistproperty.h>
#include <variantproperty.h>
-#include <modelnodeoperations.h>
#include <qmldesignerplugin.h>
#include <viewmanager.h>
@@ -70,8 +70,6 @@ namespace QmlDesigner {
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.data()),
m_subComponentManager(new SubComponentManager(m_documentModel.data(), this)),
m_rewriterView (new RewriterView(RewriterView::Amend, m_documentModel.data())),
m_documentLoaded(false),
@@ -85,7 +83,10 @@ DesignDocument::~DesignDocument()
Model *DesignDocument::currentModel() const
{
- return m_currentModel.data();
+ if (m_inFileComponentModel)
+ return m_inFileComponentModel.data();
+
+ return m_documentModel.data();
}
Model *DesignDocument::documentModel() const
@@ -100,7 +101,7 @@ QWidget *DesignDocument::centralWidget() const
QString DesignDocument::pathToQt() const
{
- QtSupport::BaseQtVersion *activeQtVersion = QtSupport::QtVersionManager::instance()->version(m_qtVersionId);
+ QtSupport::BaseQtVersion *activeQtVersion = QtSupport::QtVersionManager::version(m_qtVersionId);
if (activeQtVersion && (activeQtVersion->qtVersion() >= QtSupport::QtVersionNumber(4, 7, 1))
&& (activeQtVersion->type() == QLatin1String(QtSupport::Constants::DESKTOPQT)
|| activeQtVersion->type() == QLatin1String(QtSupport::Constants::SIMULATORQT)))
@@ -153,18 +154,23 @@ bool DesignDocument::loadInFileComponent(const ModelNode &componentNode)
if (!componentNode.isRootNode()) {
//change to subcomponent model
-
- m_inFileComponentTextModifier.reset(createComponentTextModifier(m_documentTextModifier.data(), rewriterView(), componentText, componentNode));
-
- changeToInFileComponentModel();
+ changeToInFileComponentModel(createComponentTextModifier(m_documentTextModifier.data(), rewriterView(), componentText, componentNode));
}
return true;
}
-QmlModelView *DesignDocument::qmlModelView()
+AbstractView *DesignDocument::view()
{
- return viewManager().qmlModelView();
+ return viewManager().nodeInstanceView();
+}
+
+Model* DesignDocument::createInFileComponentModel()
+{
+ Model *model = Model::create("QtQuick.Item", 1, 0);
+ model->setFileUrl(m_documentModel->fileUrl());
+
+ return model;
}
/*!
@@ -177,7 +183,7 @@ QList<RewriterView::Error> DesignDocument::qmlSyntaxErrors() const
bool DesignDocument::hasQmlSyntaxErrors() const
{
- return m_currentModel->rewriterView() && !m_currentModel->rewriterView()->errors().isEmpty();
+ return currentModel()->rewriterView() && !currentModel()->rewriterView()->errors().isEmpty();
}
QString DesignDocument::displayName() const
@@ -212,7 +218,7 @@ void DesignDocument::updateFileName(const QString & /*oldFileName*/, const QStri
QString DesignDocument::fileName() const
{
- return editor()->document()->fileName();
+ return editor()->document()->filePath();
}
int DesignDocument::qtVersionId() const
@@ -227,8 +233,7 @@ bool DesignDocument::isDocumentLoaded() const
void DesignDocument::resetToDocumentModel()
{
- m_currentModel = m_documentModel.data();
- m_rewriterView->setTextModifier(m_documentTextModifier.data());
+ m_inFileComponentModel.reset();
}
void DesignDocument::loadDocument(QPlainTextEdit *edit)
@@ -243,14 +248,13 @@ void DesignDocument::loadDocument(QPlainTextEdit *edit)
this, SIGNAL(dirtyStateChanged(bool)));
m_documentTextModifier.reset(new BaseTextEditModifier(dynamic_cast<TextEditor::BaseTextEditorWidget*>(plainTextEdit())));
+ m_documentModel->setTextModifier(m_documentTextModifier.data());
m_inFileComponentTextModifier.reset();
- //masterModel = Model::create(textModifier, searchPath, errors);
-
updateFileName(QString(), fileName());
- m_subComponentManager->update(QUrl::fromLocalFile(fileName()), m_currentModel->imports());
+ m_subComponentManager->update(QUrl::fromLocalFile(fileName()), currentModel()->imports());
m_documentLoaded = true;
}
@@ -260,95 +264,54 @@ void DesignDocument::changeToDocumentModel()
viewManager().detachRewriterView();
viewManager().detachViewsExceptRewriterAndComponetView();
- m_currentModel = m_documentModel.data();
+ m_inFileComponentModel.reset();
- viewManager().attachRewriterView(m_documentTextModifier.data());
+ viewManager().attachRewriterView();
viewManager().attachViewsExceptRewriterAndComponetView();
}
-void DesignDocument::changeToInFileComponentModel()
+void DesignDocument::changeToInFileComponentModel(ComponentTextModifier *textModifer)
{
+ m_inFileComponentTextModifier.reset(textModifer);
viewManager().detachRewriterView();
viewManager().detachViewsExceptRewriterAndComponetView();
- m_currentModel = m_inFileComponentModel.data();
+ m_inFileComponentModel.reset(createInFileComponentModel());
+ m_inFileComponentModel->setTextModifier(m_inFileComponentTextModifier.data());
- viewManager().attachRewriterView(m_inFileComponentTextModifier.data());
+ viewManager().attachRewriterView();
viewManager().attachViewsExceptRewriterAndComponetView();
}
-void DesignDocument::changeToSubComponentAndPushOnCrumblePath(const ModelNode &componentNode)
+void DesignDocument::changeToSubComponent(const ModelNode &componentNode)
{
if (QmlDesignerPlugin::instance()->currentDesignDocument() != this)
return;
- changeToSubComponent(componentNode);
-
- QmlDesignerPlugin::instance()->viewManager().pushInFileComponentOnCrambleBar(componentNode.id());
-}
-
-void DesignDocument::changeToSubComponent(const ModelNode &componentNode)
-{
- Q_ASSERT(m_documentModel);
- QWeakPointer<Model> oldModel = m_currentModel;
- Q_ASSERT(oldModel.data());
-
- if (m_currentModel.data() == m_inFileComponentModel.data())
+ if (m_inFileComponentModel)
changeToDocumentModel();
bool subComponentLoaded = loadInFileComponent(componentNode);
if (subComponentLoaded)
- activateCurrentModel(m_inFileComponentTextModifier.data());
-
- if (!componentNode.id().isEmpty())
- QmlDesignerPlugin::instance()->viewManager().pushInFileComponentOnCrambleBar(componentNode.id());
-}
-
-void DesignDocument::changeToExternalSubComponent(const QString &fileName)
-{
- Core::EditorManager::openEditor(fileName, Core::Id(), Core::EditorManager::DoNotMakeVisible);
-}
-
-void DesignDocument::goIntoSelectedComponent()
-{
- if (!m_currentModel)
- return;
+ attachRewriterToModel();
- QList<ModelNode> selectedNodes;
- if (rewriterView())
- selectedNodes = qmlModelView()->selectedModelNodes();
-
- if (selectedNodes.count() == 1) {
- viewManager().setComponentNode(selectedNodes.first());
- ModelNodeOperations::goIntoComponent(selectedNodes.first());
- }
+ QmlDesignerPlugin::instance()->viewManager().pushInFileComponentOnCrumbleBar(componentNode);
}
-void DesignDocument::activateCurrentModel(TextModifier *textModifier)
+void DesignDocument::attachRewriterToModel()
{
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);
+ viewManager().attachRewriterView();
Q_ASSERT(m_documentModel);
QApplication::restoreOverrideCursor();
}
-void DesignDocument::activateDocumentModel()
-{
- activateCurrentModel(m_documentTextModifier.data());
-}
-
bool DesignDocument::isUndoAvailable() const
{
-
if (plainTextEdit())
return plainTextEdit()->document()->isUndoAvailable();
return false;
@@ -370,19 +333,19 @@ void DesignDocument::close()
void DesignDocument::updateSubcomponentManager()
{
Q_ASSERT(m_subComponentManager);
- m_subComponentManager->update(QUrl::fromLocalFile(fileName()), m_currentModel->imports());
+ m_subComponentManager->update(QUrl::fromLocalFile(fileName()), currentModel()->imports());
}
void DesignDocument::deleteSelected()
{
- if (!m_currentModel)
+ if (!currentModel())
return;
try {
RewriterTransaction transaction(rewriterView());
- QList<ModelNode> toDelete = qmlModelView()->selectedModelNodes();
+ QList<ModelNode> toDelete = view()->selectedModelNodes();
foreach (ModelNode node, toDelete) {
- if (node.isValid() && !node.isRootNode() && QmlObjectNode(node).isValid())
+ if (node.isValid() && !node.isRootNode() && QmlObjectNode::isValidQmlObjectNode(node))
QmlObjectNode(node).destroy();
}
@@ -401,7 +364,7 @@ void DesignDocument::copySelected()
DesignDocumentView view;
- m_currentModel->attachView(&view);
+ currentModel()->attachView(&view);
if (view.selectedModelNodes().isEmpty())
return;
@@ -421,7 +384,7 @@ void DesignDocument::copySelected()
if (!selectedNode.isValid())
return;
- m_currentModel->detachView(&view);
+ currentModel()->detachView(&view);
copyModel->attachView(&view);
view.replaceModel(selectedNode);
@@ -431,7 +394,7 @@ void DesignDocument::copySelected()
view.toClipboard();
} else { //multi items selected
- m_currentModel->detachView(&view);
+ currentModel()->detachView(&view);
copyModel->attachView(&view);
foreach (ModelNode node, view.rootModelNode().allDirectSubModelNodes()) {
@@ -474,15 +437,15 @@ static void scatterItem(ModelNode pastedNode, const ModelNode targetNode, int of
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);
+ pastedNode.variantProperty("x").setValue(int(x));
+ pastedNode.variantProperty("y").setValue(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);
+ pastedNode.variantProperty("x").setValue(int(x));
+ pastedNode.variantProperty("y").setValue(int(y));
}
}
@@ -510,7 +473,7 @@ void DesignDocument::paste()
if (rootNode.id() == "designer__Selection") {
QList<ModelNode> selectedNodes = rootNode.allDirectSubModelNodes();
pasteModel->detachView(&view);
- m_currentModel->attachView(&view);
+ currentModel()->attachView(&view);
ModelNode targetNode;
@@ -518,7 +481,7 @@ void DesignDocument::paste()
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())
+ if ((view.selectedModelNodes().count() == selectedNodes.count()) && targetNode.isValid() && targetNode.hasParentProperty())
targetNode = targetNode.parentProperty().parentModelNode();
if (!targetNode.isValid())
@@ -555,7 +518,7 @@ void DesignDocument::paste()
RewriterTransaction transaction(rewriterView());
pasteModel->detachView(&view);
- m_currentModel->attachView(&view);
+ currentModel()->attachView(&view);
ModelNode pastedNode(view.insertModel(rootNode));
ModelNode targetNode;
@@ -565,7 +528,7 @@ void DesignDocument::paste()
if (!targetNode.isValid())
targetNode = view.rootModelNode();
- if (targetNode.parentProperty().isValid() &&
+ if (targetNode.hasParentProperty() &&
(pastedNode.simplifiedTypeName() == targetNode.simplifiedTypeName()) &&
(pastedNode.variantProperty("width").value() == targetNode.variantProperty("width").value()) &&
(pastedNode.variantProperty("height").value() == targetNode.variantProperty("height").value()))
@@ -575,7 +538,7 @@ void DesignDocument::paste()
PropertyName defaultProperty(targetNode.metaInfo().defaultPropertyName());
scatterItem(pastedNode, targetNode);
- if (targetNode.nodeListProperty(defaultProperty).isValid())
+ if (targetNode.hasNodeListProperty(defaultProperty))
targetNode.nodeListProperty(defaultProperty).reparentHere(pastedNode);
transaction.commit();
@@ -590,11 +553,11 @@ void DesignDocument::paste()
void DesignDocument::selectAll()
{
- if (!m_currentModel)
+ if (!currentModel())
return;
DesignDocumentView view;
- m_currentModel->attachView(&view);
+ currentModel()->attachView(&view);
QList<ModelNode> allNodesExceptRootNode(view.allModelNodes());
@@ -611,7 +574,7 @@ void DesignDocument::setEditor(Core::IEditor *editor)
{
m_textEditor = editor;
connect(editor->document(),
- SIGNAL(fileNameChanged(QString,QString)),
+ SIGNAL(filePathChanged(QString,QString)),
SLOT(updateFileName(QString,QString)));
updateActiveQtVersion();
@@ -713,7 +676,7 @@ void DesignDocument::updateActiveQtVersion()
QString DesignDocument::contextHelpId() const
{
DesignDocumentView view;
- m_currentModel->attachView(&view);
+ currentModel()->attachView(&view);
QList<ModelNode> nodes = view.selectedModelNodes();
QString helpId;
diff --git a/src/plugins/qmldesigner/components/integration/designdocument.h b/src/plugins/qmldesigner/components/integration/designdocument.h
index 62604686b4..e4178b0328 100644
--- a/src/plugins/qmldesigner/components/integration/designdocument.h
+++ b/src/plugins/qmldesigner/components/integration/designdocument.h
@@ -57,7 +57,7 @@ class TextModifier;
class QmlObjectNode;
class CrumbleBarInfo;
class ViewManager;
-class QmlModelView;
+class AbstractView;
class QMLDESIGNERCORE_EXPORT DesignDocument: public QObject
{
@@ -70,7 +70,7 @@ public:
QString simplfiedDisplayName() const;
void loadDocument(QPlainTextEdit *edit);
- void activateDocumentModel();
+ void attachRewriterToModel();
void close();
void updateSubcomponentManager();
@@ -97,8 +97,6 @@ public:
void resetToDocumentModel();
- void goIntoSelectedComponent();
-
void changeToDocumentModel();
signals:
@@ -119,16 +117,13 @@ public slots:
void undo();
void redo();
void updateActiveQtVersion();
- void changeToSubComponentAndPushOnCrumblePath(const ModelNode &componentNode);
void changeToSubComponent(const ModelNode &componentNode);
- void changeToExternalSubComponent(const QString &m_oldFileName);
private slots:
void updateFileName(const QString &oldFileName, const QString &newFileName);
private: // functions
- void changeToInFileComponentModel();
- void activateCurrentModel(TextModifier *textModifier);
+ void changeToInFileComponentModel(ComponentTextModifier *textModifer);
QWidget *centralWidget() const;
QString pathToQt() const;
@@ -140,13 +135,13 @@ private: // functions
bool loadInFileComponent(const ModelNode &componentNode);
- QmlModelView *qmlModelView();
+ AbstractView *view();
+
+ Model *createInFileComponentModel();
private: // variables
- QScopedPointer<QStackedWidget> m_stackedWidget;
QScopedPointer<Model> m_documentModel;
QScopedPointer<Model> m_inFileComponentModel;
- QWeakPointer<Model> m_currentModel;
QWeakPointer<Core::IEditor> m_textEditor;
QScopedPointer<BaseTextEditModifier> m_documentTextModifier;
QScopedPointer<ComponentTextModifier> m_inFileComponentTextModifier;
diff --git a/src/plugins/qmldesigner/components/integration/designdocumentview.cpp b/src/plugins/qmldesigner/components/integration/designdocumentview.cpp
index 8c44ee8343..6a11cf9360 100644
--- a/src/plugins/qmldesigner/components/integration/designdocumentview.cpp
+++ b/src/plugins/qmldesigner/components/integration/designdocumentview.cpp
@@ -119,7 +119,7 @@ void DesignDocumentView::rewriterEndTransaction()
{
}
-void DesignDocumentView::actualStateChanged(const ModelNode &/*node*/)
+void DesignDocumentView::currentStateChanged(const ModelNode &/*node*/)
{
}
@@ -151,7 +151,7 @@ void DesignDocumentView::toClipboard() const
data->setText(toText());
QStringList imports;
foreach (const Import &import, model()->imports())
- imports.append(import.toString());
+ imports.append(import.toImportString());
data->setData("QmlDesigner::imports", stringListToArray(imports));
clipboard->setMimeData(data);
@@ -208,7 +208,7 @@ void DesignDocumentView::fromText(QString text)
QPlainTextEdit textEdit;
QString imports;
foreach (const Import &import, model()->imports())
- imports += import.toString(true, true) + QLatin1Char('\n');
+ imports += QLatin1String("import ") + import.toString(true) + QLatin1Char(';') + QLatin1Char('\n');
textEdit.setPlainText(imports + text);
NotIndentingTextEditModifier modifier(&textEdit);
diff --git a/src/plugins/qmldesigner/components/integration/designdocumentview.h b/src/plugins/qmldesigner/components/integration/designdocumentview.h
index d2ef379fec..6cd5bf4332 100644
--- a/src/plugins/qmldesigner/components/integration/designdocumentview.h
+++ b/src/plugins/qmldesigner/components/integration/designdocumentview.h
@@ -79,7 +79,7 @@ public:
void rewriterBeginTransaction();
void rewriterEndTransaction();
- void actualStateChanged(const ModelNode &node) QTC_OVERRIDE;
+ void currentStateChanged(const ModelNode &node) QTC_OVERRIDE;
void importsChanged(const QList<Import> &addedImports, const QList<Import> &removedImports) QTC_OVERRIDE;
diff --git a/src/plugins/qmldesigner/components/itemlibrary/customdraganddrop.cpp b/src/plugins/qmldesigner/components/itemlibrary/customdraganddrop.cpp
index f5dc94a079..934d037038 100644
--- a/src/plugins/qmldesigner/components/itemlibrary/customdraganddrop.cpp
+++ b/src/plugins/qmldesigner/components/itemlibrary/customdraganddrop.cpp
@@ -101,8 +101,7 @@ void CustomDragAndDropIcon::mouseMoveEvent(QMouseEvent *event)
resize(m_size);
show();
update();
- }
- else {
+ } else {
move(-1000, -1000); // if no top level widget is found we are out of the main window
}
QWidget* target = QApplication::widgetAt(globalPos - QPoint(2,2)); //-(2, 2) because:
diff --git a/src/plugins/qmldesigner/components/itemlibrary/itemlibrary.pri b/src/plugins/qmldesigner/components/itemlibrary/itemlibrary.pri
index 0a981e9baa..424de58514 100644
--- a/src/plugins/qmldesigner/components/itemlibrary/itemlibrary.pri
+++ b/src/plugins/qmldesigner/components/itemlibrary/itemlibrary.pri
@@ -12,7 +12,3 @@ OTHER_FILES += \
qml/ItemView.qml \
qml/ItemsViewStyle.qml \
qml/ItemsView.qml
-
-greaterThan(QT_MAJOR_VERSION, 4) {
- QT += declarative-private core-private script-private
-}
diff --git a/src/plugins/qmldesigner/components/itemlibrary/itemlibrary.qrc b/src/plugins/qmldesigner/components/itemlibrary/itemlibrary.qrc
index 1343c93988..4869a43d22 100644
--- a/src/plugins/qmldesigner/components/itemlibrary/itemlibrary.qrc
+++ b/src/plugins/qmldesigner/components/itemlibrary/itemlibrary.qrc
@@ -3,7 +3,7 @@
<file>qml/ItemsView.qml</file>
<file>qml/ItemsViewStyle.qml</file>
<file>qml/SectionView.qml</file>
- <file>qml/ItemView.qml</file>
+ <file>qml/SingleItemView.qml</file>
<file>qml/Scrollbar.qml</file>
<file>qml/Selector.qml</file>
diff --git a/src/plugins/qmldesigner/components/itemlibrary/itemlibraryimageprovider.cpp b/src/plugins/qmldesigner/components/itemlibrary/itemlibraryimageprovider.cpp
index 6e3898cabd..6912e09cbb 100644
--- a/src/plugins/qmldesigner/components/itemlibrary/itemlibraryimageprovider.cpp
+++ b/src/plugins/qmldesigner/components/itemlibrary/itemlibraryimageprovider.cpp
@@ -33,7 +33,7 @@ namespace QmlDesigner {
namespace Internal {
ItemLibraryImageProvider::ItemLibraryImageProvider() :
- QDeclarativeImageProvider(QDeclarativeImageProvider::Pixmap)
+ QQuickImageProvider(QQuickImageProvider::Pixmap)
{
}
diff --git a/src/plugins/qmldesigner/components/itemlibrary/itemlibraryimageprovider.h b/src/plugins/qmldesigner/components/itemlibrary/itemlibraryimageprovider.h
index 10e4277b75..ed8f7e57d6 100644
--- a/src/plugins/qmldesigner/components/itemlibrary/itemlibraryimageprovider.h
+++ b/src/plugins/qmldesigner/components/itemlibrary/itemlibraryimageprovider.h
@@ -30,13 +30,13 @@
#ifndef ITEMLIBRARYIMAGEPROVIDER_H
#define ITEMLIBRARYIMAGEPROVIDER_H
-#include <QDeclarativeImageProvider>
+#include <QQuickImageProvider>
namespace QmlDesigner {
namespace Internal {
-class ItemLibraryImageProvider : public QDeclarativeImageProvider
+class ItemLibraryImageProvider : public QQuickImageProvider
{
public:
ItemLibraryImageProvider();
diff --git a/src/plugins/qmldesigner/components/itemlibrary/itemlibrarymodel.cpp b/src/plugins/qmldesigner/components/itemlibrary/itemlibrarymodel.cpp
index 04a5377301..27933db262 100644
--- a/src/plugins/qmldesigner/components/itemlibrary/itemlibrarymodel.cpp
+++ b/src/plugins/qmldesigner/components/itemlibrary/itemlibrarymodel.cpp
@@ -33,11 +33,16 @@
#include <nodemetainfo.h>
#include <QVariant>
+#include <QMetaProperty>
#include <QMimeData>
#include <QPainter>
#include <QPen>
#include <qdebug.h>
+static bool inline registerItemLibrarySortedModel() {
+ qmlRegisterType<QmlDesigner::Internal::ItemLibrarySortedModel>();
+ return true;
+}
namespace QmlDesigner {
@@ -45,31 +50,59 @@ namespace Internal {
static QHash<QString, bool> collapsedStateHash;
-
-template <class T>
-ItemLibrarySortedModel<T>::ItemLibrarySortedModel(QObject *parent) :
- QDeclarativeListModel(parent)
+ItemLibrarySortedModel::ItemLibrarySortedModel(QObject *parent) :
+ QAbstractListModel(parent)
{
}
-
-template <class T>
-ItemLibrarySortedModel<T>::~ItemLibrarySortedModel()
+ItemLibrarySortedModel::~ItemLibrarySortedModel()
{
clearElements();
}
+int ItemLibrarySortedModel::rowCount(const QModelIndex &) const
+{
+ return m_privList.count();
+}
+
+QVariant ItemLibrarySortedModel::data(const QModelIndex &index, int role) const
+{
+ if (!index.isValid() || index.row()+1 > m_privList.count()) {
+ qDebug() << Q_FUNC_INFO << "invalid index requested";
+ return QVariant();
+ }
+
+ if (m_roleNames.contains(role)) {
+ QVariant value = m_privList.at(index.row())->property(m_roleNames.value(role));
+
+ if (ItemLibrarySortedModel* model = qobject_cast<ItemLibrarySortedModel *>(value.value<QObject*>())) {
+ return QVariant::fromValue(model);
+ }
+
+ return m_privList.at(index.row())->property(m_roleNames.value(role));
+ }
+
+ qWarning() << Q_FUNC_INFO << "invalid role requested";
-template <class T>
-void ItemLibrarySortedModel<T>::clearElements()
+ return QVariant();
+}
+
+void ItemLibrarySortedModel::clearElements()
{
+ beginResetModel();
while (m_elementOrder.count() > 0)
removeElement(m_elementOrder.at(0).libId);
+ endResetModel();
}
+static bool compareFunction(QObject *first, QObject *second)
+{
+ static const char sortRoleName[] = "sortingRole";
+
+ return first->property(sortRoleName).toString() < second->property(sortRoleName).toString();
+}
-template <class T>
-void ItemLibrarySortedModel<T>::addElement(T *element, int libId)
+void ItemLibrarySortedModel::addElement(QObject *element, int libId)
{
struct order_struct orderEntry;
orderEntry.libId = libId;
@@ -77,7 +110,7 @@ void ItemLibrarySortedModel<T>::addElement(T *element, int libId)
int pos = 0;
while ((pos < m_elementOrder.count()) &&
- (*(m_elementModels.value(m_elementOrder.at(pos).libId)) < *element))
+ compareFunction(m_elementModels.value(m_elementOrder.at(pos).libId), element))
++pos;
m_elementModels.insert(libId, element);
@@ -86,10 +119,9 @@ void ItemLibrarySortedModel<T>::addElement(T *element, int libId)
setElementVisible(libId, true);
}
-template <class T>
-void ItemLibrarySortedModel<T>::removeElement(int libId)
+void ItemLibrarySortedModel::removeElement(int libId)
{
- T *element = m_elementModels.value(libId);
+ QObject *element = m_elementModels.value(libId);
int pos = findElement(libId);
setElementVisible(libId, false);
@@ -100,49 +132,77 @@ void ItemLibrarySortedModel<T>::removeElement(int libId)
delete element;
}
-
-template <class T>
-bool ItemLibrarySortedModel<T>::elementVisible(int libId) const
+bool ItemLibrarySortedModel::elementVisible(int libId) const
{
int pos = findElement(libId);
return m_elementOrder.at(pos).visible;
}
-
-template <class T>
-bool ItemLibrarySortedModel<T>::setElementVisible(int libId, bool visible)
+bool ItemLibrarySortedModel::setElementVisible(int libId, bool visible)
{
int pos = findElement(libId);
if (m_elementOrder.at(pos).visible == visible)
return false;
int visiblePos = visibleElementPosition(libId);
- if (visible)
- insert(visiblePos, *(m_elementModels.value(libId)));
- else
- remove(visiblePos);
+ if (visible) {
+ privateInsert(visiblePos, (m_elementModels.value(libId)));
+ } else {
+ privateRemove(visiblePos);
+ }
m_elementOrder[pos].visible = visible;
return true;
}
+void ItemLibrarySortedModel::privateInsert(int pos, QObject *element)
+{
+ QObject *object = element;
+
+ for (int i = 0; i < object->metaObject()->propertyCount(); ++i) {
+ QMetaProperty property = object->metaObject()->property(i);
+ addRoleName(property.name());
+ }
+
+ m_privList.insert(pos, element);
+}
+
+void ItemLibrarySortedModel::privateRemove(int pos)
+{
+ m_privList.removeAt(pos);
+}
-template <class T>
-const QMap<int, T *> &ItemLibrarySortedModel<T>::elements() const
+const QMap<int, QObject *> &ItemLibrarySortedModel::elements() const
{
return m_elementModels;
}
+template<typename T>
+const QList<T> ItemLibrarySortedModel::elementsByType() const
+{
+ QList<T> objectList;
+
+ foreach (QObject *item, elements()) {
+ T object = qobject_cast<T>(item);
+ if (object)
+ objectList.append(object);
+ }
-template <class T>
-T *ItemLibrarySortedModel<T>::elementModel(int libId)
+ return objectList;
+}
+
+QObject *ItemLibrarySortedModel::element(int libId)
{
return m_elementModels.value(libId);
}
+template<typename T>
+T ItemLibrarySortedModel::elementByType(int libId)
+{
+ return qobject_cast<T>(element(libId));
+}
-template <class T>
-int ItemLibrarySortedModel<T>::findElement(int libId) const
+int ItemLibrarySortedModel::findElement(int libId) const
{
int i = 0;
QListIterator<struct order_struct> it(m_elementOrder);
@@ -156,8 +216,7 @@ int ItemLibrarySortedModel<T>::findElement(int libId) const
return -1;
}
-template <class T>
-int ItemLibrarySortedModel<T>::visibleElementPosition(int libId) const
+int ItemLibrarySortedModel::visibleElementPosition(int libId) const
{
int i = 0;
QListIterator<struct order_struct> it(m_elementOrder);
@@ -173,26 +232,36 @@ int ItemLibrarySortedModel<T>::visibleElementPosition(int libId) const
return -1;
}
+void ItemLibrarySortedModel::resetModel()
+{
+ beginResetModel();
+ endResetModel();
+}
+void ItemLibrarySortedModel::addRoleName(const QByteArray &roleName)
+{
+ if (m_roleNames.values().contains(roleName)) {
+ return;
+ }
+
+ int key = m_roleNames.count();
+ m_roleNames.insert(key, roleName);
+ setRoleNames(m_roleNames);
+}
-ItemLibraryItemModel::ItemLibraryItemModel(QScriptEngine *scriptEngine, int itemLibId, const QString &itemName)
- : QScriptValue(scriptEngine->newObject()),
- m_scriptEngine(scriptEngine),
+ItemLibraryItemModel::ItemLibraryItemModel(int itemLibId, const QString &itemName, QObject *parent)
+ : QObject(parent),
m_libId(itemLibId),
m_name(itemName),
m_iconSize(64, 64)
{
- QScriptValue pixmapScriptValue(m_scriptEngine->newVariant(QPixmap()));
- setProperty(QLatin1String("itemLibId"), itemLibId);
- setProperty(QLatin1String("itemName"), itemName);
- setProperty(QLatin1String("itemPixmap"), pixmapScriptValue);
}
ItemLibraryItemModel::~ItemLibraryItemModel()
{
- setProperty(QLatin1String("itemPixmap"), QVariant::Invalid);
+
}
@@ -207,45 +276,37 @@ QString ItemLibraryItemModel::itemName() const
return m_name;
}
+QString ItemLibraryItemModel::itemLibraryIconPath() const
+{
+ //Prepend image provider prefix
+ return QLatin1String("image://qmldesigner_itemlibrary/")+ m_iconPath;
+}
+
+QVariant ItemLibraryItemModel::sortingRole() const
+{
+ return itemName();
+}
+
void ItemLibraryItemModel::setItemIconPath(const QString &iconPath)
{
m_iconPath = iconPath;
-
- setProperty(QLatin1String("itemLibraryIconPath"),
- QString(QLatin1String("image://qmldesigner_itemlibrary/") + iconPath));
}
void ItemLibraryItemModel::setItemIconSize(const QSize &itemIconSize)
{
m_iconSize = itemIconSize;
-// qDebug() << "set icon size" << itemIconSize;
setItemIconPath(m_iconPath);
}
-
-bool ItemLibraryItemModel::operator<(const ItemLibraryItemModel &other) const
-{
- return itemName() < other.itemName();
-}
-
-
-
-
-ItemLibrarySectionModel::ItemLibrarySectionModel(QScriptEngine *scriptEngine, int sectionLibId, const QString &sectionName, QObject *parent)
- : QScriptValue(scriptEngine->newObject()),
+ItemLibrarySectionModel::ItemLibrarySectionModel(int sectionLibId, const QString &sectionName, QObject *parent)
+ : QObject(parent),
m_name(sectionName),
+ m_sectionLibId(sectionLibId),
+ m_sectionExpanded(true),
m_sectionEntries(parent)
{
- QScriptValue::setProperty(QLatin1String("sectionLibId"), sectionLibId);
- QScriptValue::setProperty(QLatin1String("sectionName"), sectionName);
- QScriptValue::setProperty(QLatin1String("sectionEntries"),
- scriptEngine->newVariant(QVariant::fromValue(static_cast<QDeclarativeListModel *>(&m_sectionEntries))));
-
- if (collapsedStateHash.contains(sectionName)) {
- QScriptValue::setProperty(QLatin1String("sectionExpanded"), collapsedStateHash.value(sectionName));
- } else {
- QScriptValue::setProperty(QLatin1String("sectionExpanded"), true);
- }
+ if (collapsedStateHash.contains(sectionName))
+ m_sectionExpanded= collapsedStateHash.value(sectionName);
}
@@ -254,6 +315,24 @@ QString ItemLibrarySectionModel::sectionName() const
return m_name;
}
+int ItemLibrarySectionModel::sectionLibId() const
+{
+ return m_sectionLibId;
+}
+
+bool ItemLibrarySectionModel::sectionExpanded() const
+{
+ return m_sectionExpanded;
+}
+
+QVariant ItemLibrarySectionModel::sortingRole() const
+{
+
+ if (sectionName() == QLatin1String("QML Components")) //Qml Components always come first
+ return QVariant(QLatin1String("AA.this_comes_first"));
+
+ return sectionName();
+}
void ItemLibrarySectionModel::addSectionEntry(ItemLibraryItemModel *sectionEntry)
{
@@ -266,6 +345,10 @@ void ItemLibrarySectionModel::removeSectionEntry(int itemLibId)
m_sectionEntries.removeElement(itemLibId);
}
+QObject *ItemLibrarySectionModel::sectionEntries()
+{
+ return &m_sectionEntries;
+}
int ItemLibrarySectionModel::visibleItemIndex(int itemLibId)
{
@@ -285,11 +368,13 @@ bool ItemLibrarySectionModel::updateSectionVisibility(const QString &searchText,
*changed = false;
- QMap<int, ItemLibraryItemModel *>::const_iterator itemIt = m_sectionEntries.elements().constBegin();
+ QMap<int, QObject *>::const_iterator itemIt = m_sectionEntries.elements().constBegin();
while (itemIt != m_sectionEntries.elements().constEnd()) {
- bool itemVisible = itemIt.value()->itemName().toLower().contains(searchText),
- itemChanged = false;
+ bool itemVisible = m_sectionEntries.elementByType<ItemLibraryItemModel*>(
+ itemIt.key())->itemName().toLower().contains(searchText);
+
+ bool itemChanged = false;
itemChanged = m_sectionEntries.setElementVisible(itemIt.key(), itemVisible);
*changed |= itemChanged;
@@ -300,24 +385,21 @@ bool ItemLibrarySectionModel::updateSectionVisibility(const QString &searchText,
++itemIt;
}
+ m_sectionEntries.resetModel();
+
+ emit sectionEntriesChanged();
+
return haveVisibleItems;
}
void ItemLibrarySectionModel::updateItemIconSize(const QSize &itemIconSize)
{
- foreach (ItemLibraryItemModel *item, m_sectionEntries.elements()) {
- item->setItemIconSize(itemIconSize);
+ foreach (ItemLibraryItemModel* itemLibraryItemModel, m_sectionEntries.elementsByType<ItemLibraryItemModel*>()) {
+ itemLibraryItemModel->setItemIconSize(itemIconSize);
}
}
-bool ItemLibrarySectionModel::operator<(const ItemLibrarySectionModel &other) const
-{
- if (sectionName() == QLatin1String("QML Components")) //Qml Components always come first
- return true;
- return sectionName() < other.sectionName();
-}
-
void ItemLibraryModel::setExpanded(bool expanded, const QString &section)
{
if (collapsedStateHash.contains(section))
@@ -327,9 +409,8 @@ void ItemLibraryModel::setExpanded(bool expanded, const QString &section)
collapsedStateHash.insert(section, expanded);
}
-ItemLibraryModel::ItemLibraryModel(QScriptEngine *scriptEngine, QObject *parent)
- : ItemLibrarySortedModel<ItemLibrarySectionModel>(parent),
- m_scriptEngine(scriptEngine),
+ItemLibraryModel::ItemLibraryModel(QObject *parent)
+ : ItemLibrarySortedModel(parent),
m_searchText(""),
m_itemIconSize(64, 64),
m_nextLibId(0)
@@ -365,15 +446,16 @@ void ItemLibraryModel::setItemIconSize(const QSize &itemIconSize)
{
m_itemIconSize = itemIconSize;
- foreach (ItemLibrarySectionModel *section, elements().values())
- section->updateItemIconSize(itemIconSize);
+ foreach (ItemLibrarySectionModel* itemLibrarySectionModel, sections()) {
+ itemLibrarySectionModel->updateItemIconSize(itemIconSize);
+ }
}
int ItemLibraryModel::getItemSectionIndex(int itemLibId)
{
if (m_sections.contains(itemLibId))
- return elementModel(m_sections.value(itemLibId))->visibleItemIndex(itemLibId);
+ return section(m_sections.value(itemLibId))->visibleItemIndex(itemLibId);
else
return -1;
}
@@ -394,7 +476,7 @@ bool ItemLibraryModel::isItemVisible(int itemLibId)
if (!elementVisible(sectionLibId))
return false;
- return elementModel(sectionLibId)->isItemVisible(itemLibId);
+ return section(sectionLibId)->isItemVisible(itemLibId);
}
Import entryToImport(const ItemLibraryEntry &entry)
@@ -439,17 +521,17 @@ void ItemLibraryModel::update(ItemLibraryInfo *itemLibraryInfo, Model *model)
if (sections.contains(itemSectionName)) {
sectionId = sections.value(itemSectionName);
- sectionModel = elementModel(sectionId);
+ sectionModel = section(sectionId);
} else {
sectionId = m_nextLibId++;
- sectionModel = new ItemLibrarySectionModel(m_scriptEngine.data(), sectionId, itemSectionName, this);
+ sectionModel = new ItemLibrarySectionModel(sectionId, itemSectionName, this);
addElement(sectionModel, sectionId);
sections.insert(itemSectionName, sectionId);
}
m_itemInfos.insert(itemId, entry);
- itemModel = new ItemLibraryItemModel(m_scriptEngine.data(), itemId, entry.name());
+ itemModel = new ItemLibraryItemModel(itemId, entry.name(), sectionModel);
// delayed creation of (default) icons
if (entry.iconPath().isEmpty())
@@ -501,15 +583,26 @@ QIcon ItemLibraryModel::getIcon(int libId)
return m_itemInfos.value(libId).icon();
}
+ItemLibrarySectionModel *ItemLibraryModel::section(int libId)
+{
+ return elementByType<ItemLibrarySectionModel*>(libId);
+}
+
+QList<ItemLibrarySectionModel *> ItemLibraryModel::sections() const
+{
+ return elementsByType<ItemLibrarySectionModel*>();
+}
void ItemLibraryModel::updateVisibility()
{
+ beginResetModel();
+ endResetModel();
bool changed = false;
- QMap<int, ItemLibrarySectionModel *>::const_iterator sectionIt = elements().constBegin();
+ QMap<int, QObject *>::const_iterator sectionIt = elements().constBegin();
while (sectionIt != elements().constEnd()) {
+ ItemLibrarySectionModel *sectionModel = section(sectionIt.key());
- ItemLibrarySectionModel *sectionModel = sectionIt.value();
QString sectionSearchText = m_searchText;
if (sectionModel->sectionName().toLower().contains(m_searchText))
@@ -564,6 +657,11 @@ QPixmap ItemLibraryModel::createDragPixmap(int , int )
return QPixmap::fromImage(dragImage);
}
+void registerQmlTypes()
+{
+ registerItemLibrarySortedModel();
+}
+
} // namespace Internal
} // namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/components/itemlibrary/itemlibrarymodel.h b/src/plugins/qmldesigner/components/itemlibrary/itemlibrarymodel.h
index 1aacaa6388..8fe62142db 100644
--- a/src/plugins/qmldesigner/components/itemlibrary/itemlibrarymodel.h
+++ b/src/plugins/qmldesigner/components/itemlibrary/itemlibrarymodel.h
@@ -32,8 +32,8 @@
#include <QMap>
#include <QIcon>
-#include <QScriptEngine>
-#include <private/qdeclarativelistmodel_p.h>
+#include <QAbstractListModel>
+#include <QtQuick>
QT_FORWARD_DECLARE_CLASS(QMimeData)
@@ -45,52 +45,82 @@ class Model;
namespace Internal {
-template <class T>
-class ItemLibrarySortedModel: public QDeclarativeListModel {
+void registerQmlTypes();
+
+class ItemLibrarySortedModel: public QAbstractListModel {
+
+ Q_OBJECT
+
public:
ItemLibrarySortedModel(QObject *parent = 0);
~ItemLibrarySortedModel();
+ int rowCount(const QModelIndex &parent = QModelIndex()) const;
+ QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
+
void clearElements();
- void addElement(T *element, int libId);
+ void addElement(QObject *element, int libId);
void removeElement(int libId);
bool elementVisible(int libId) const;
bool setElementVisible(int libId, bool visible);
- const QMap<int, T *> &elements() const;
+ void privateInsert(int pos, QObject *element);
+ void privateRemove(int pos);
+
+ const QMap<int, QObject *> &elements() const;
+
+ template<typename T>
+ const QList<T> elementsByType() const;
+
+ QObject *element(int libId);
+
+ template<typename T>
+ T elementByType(int libId);
- T *elementModel(int libId);
int findElement(int libId) const;
int visibleElementPosition(int libId) const;
+ void resetModel();
+
private:
+ void addRoleName(const QByteArray &roleName);
+
struct order_struct {
int libId;
bool visible;
};
- QMap<int, T *> m_elementModels;
+ QMap<int, QObject *> m_elementModels;
QList<struct order_struct> m_elementOrder;
+
+ QList<QObject *> m_privList;
+ QHash<int, QByteArray> m_roleNames;
};
+class ItemLibraryItemModel: public QObject {
+
+ Q_OBJECT
+
+ Q_PROPERTY(int itemLibId READ itemLibId FINAL)
+ Q_PROPERTY(QString itemName READ itemName FINAL)
+ Q_PROPERTY(QString itemLibraryIconPath READ itemLibraryIconPath FINAL)
+ Q_PROPERTY(QVariant sortingRole READ sortingRole FINAL)
-class ItemLibraryItemModel: public QScriptValue {
public:
- ItemLibraryItemModel(QScriptEngine *scriptEngine, int itemLibId, const QString &itemName);
+ ItemLibraryItemModel(int itemLibId, const QString &itemName, QObject *parent);
~ItemLibraryItemModel();
int itemLibId() const;
QString itemName() const;
+ QString itemLibraryIconPath() const;
+ QVariant sortingRole() const;
void setItemIconPath(const QString &iconPath);
void setItemIconSize(const QSize &itemIconSize);
- bool operator<(const ItemLibraryItemModel &other) const;
-
private:
- QWeakPointer<QScriptEngine> m_scriptEngine;
int m_libId;
QString m_name;
QString m_iconPath;
@@ -98,14 +128,27 @@ private:
};
-class ItemLibrarySectionModel: public QScriptValue {
+class ItemLibrarySectionModel: public QObject {
+
+ Q_OBJECT
+
+ Q_PROPERTY(QObject* sectionEntries READ sectionEntries NOTIFY sectionEntriesChanged FINAL)
+ Q_PROPERTY(int sectionLibId READ sectionLibId FINAL)
+ Q_PROPERTY(QString sectionName READ sectionName FINAL)
+ Q_PROPERTY(bool sectionExpanded READ sectionExpanded FINAL)
+ Q_PROPERTY(QVariant sortingRole READ sortingRole FINAL)
+
public:
- ItemLibrarySectionModel(QScriptEngine *scriptEngine, int sectionLibId, const QString &sectionName, QObject *parent = 0);
+ ItemLibrarySectionModel(int sectionLibId, const QString &sectionName, QObject *parent = 0);
QString sectionName() const;
+ int sectionLibId() const;
+ bool sectionExpanded() const;
+ QVariant sortingRole() const;
void addSectionEntry(ItemLibraryItemModel *sectionEntry);
void removeSectionEntry(int itemLibId);
+ QObject *sectionEntries();
int visibleItemIndex(int itemLibId);
bool isItemVisible(int itemLibId);
@@ -113,20 +156,24 @@ public:
bool updateSectionVisibility(const QString &searchText, bool *changed);
void updateItemIconSize(const QSize &itemIconSize);
- bool operator<(const ItemLibrarySectionModel &other) const;
+signals:
+ void sectionEntriesChanged();
private:
QString m_name;
- ItemLibrarySortedModel<ItemLibraryItemModel> m_sectionEntries;
+ int m_sectionLibId;
+ bool m_sectionExpanded;
+ ItemLibrarySortedModel m_sectionEntries;
};
-class ItemLibraryModel: public ItemLibrarySortedModel<ItemLibrarySectionModel> {
+class ItemLibraryModel: public ItemLibrarySortedModel {
+
Q_OBJECT
Q_PROPERTY(QString searchText READ searchText WRITE setSearchText NOTIFY searchTextChanged)
public:
- explicit ItemLibraryModel(QScriptEngine *scriptEngine, QObject *parent = 0);
+ explicit ItemLibraryModel(QObject *parent = 0);
~ItemLibraryModel();
QString searchText() const;
@@ -137,6 +184,9 @@ public:
QMimeData *getMimeData(int libId);
QIcon getIcon(int libId);
+ ItemLibrarySectionModel* section(int libId);
+ QList<ItemLibrarySectionModel*> sections() const;
+
public slots:
void setSearchText(const QString &searchText);
void setItemIconSize(const QSize &itemIconSize);
@@ -159,7 +209,6 @@ private:
int getHeight(const ItemLibraryEntry &entry);
QPixmap createDragPixmap(int width, int height);
- QWeakPointer<QScriptEngine> m_scriptEngine;
QMap<int, ItemLibraryEntry> m_itemInfos;
QMap<int, int> m_sections;
@@ -171,5 +220,7 @@ private:
} // namespace Internal
} // namespace QmlDesigner
+QML_DECLARE_TYPE(QmlDesigner::Internal::ItemLibrarySortedModel)
+
#endif // ITEMLIBRARYMODEL_H
diff --git a/src/plugins/qmldesigner/components/itemlibrary/itemlibraryview.cpp b/src/plugins/qmldesigner/components/itemlibrary/itemlibraryview.cpp
index 82ea759fe2..5aef537796 100644
--- a/src/plugins/qmldesigner/components/itemlibrary/itemlibraryview.cpp
+++ b/src/plugins/qmldesigner/components/itemlibrary/itemlibraryview.cpp
@@ -30,10 +30,14 @@
#include "itemlibraryview.h"
#include "itemlibrarywidget.h"
#include <import.h>
+#include <importmanagerview.h>
namespace QmlDesigner {
-ItemLibraryView::ItemLibraryView(QObject* parent) : AbstractView(parent)
+ItemLibraryView::ItemLibraryView(QObject* parent)
+ : AbstractView(parent),
+ m_importManagerView(new ImportManagerView(this))
+
{
}
@@ -50,8 +54,10 @@ bool ItemLibraryView::hasWidget() const
WidgetInfo ItemLibraryView::widgetInfo()
{
- if (m_widget.isNull())
- m_widget = new ItemLibraryWidget;
+ if (m_widget.isNull()) {
+ m_widget = new ItemLibraryWidget;
+ m_widget->setImportsWidget(m_importManagerView->widgetInfo().widget);
+ }
return createWidgetInfo(m_widget.data(),
new WidgetInfo::ToolBarWidgetDefaultFactory<ItemLibraryWidget>(m_widget.data()),
@@ -65,10 +71,13 @@ void ItemLibraryView::modelAttached(Model *model)
AbstractView::modelAttached(model);
m_widget->setModel(model);
updateImports();
+ model->attachView(m_importManagerView);
}
void ItemLibraryView::modelAboutToBeDetached(Model *model)
{
+ model->detachView(m_importManagerView);
+
AbstractView::modelAboutToBeDetached(model);
m_widget->setModel(0);
}
@@ -203,7 +212,7 @@ void ItemLibraryView::rewriterEndTransaction()
{
}
-void ItemLibraryView::actualStateChanged(const ModelNode &/*node*/)
+void ItemLibraryView::currentStateChanged(const ModelNode &/*node*/)
{
}
diff --git a/src/plugins/qmldesigner/components/itemlibrary/itemlibraryview.h b/src/plugins/qmldesigner/components/itemlibrary/itemlibraryview.h
index dc156d61e2..2fc40c4d23 100644
--- a/src/plugins/qmldesigner/components/itemlibrary/itemlibraryview.h
+++ b/src/plugins/qmldesigner/components/itemlibrary/itemlibraryview.h
@@ -38,7 +38,7 @@
namespace QmlDesigner {
class ItemLibraryWidget;
-
+class ImportManagerView;
class ItemLibraryView : public AbstractView
{
@@ -98,7 +98,7 @@ public:
void rewriterBeginTransaction() QTC_OVERRIDE;
void rewriterEndTransaction() QTC_OVERRIDE;
- void actualStateChanged(const ModelNode &node) QTC_OVERRIDE;
+ void currentStateChanged(const ModelNode &node) QTC_OVERRIDE;
void setResourcePath(const QString &resourcePath);
@@ -107,6 +107,7 @@ protected:
private:
QWeakPointer<ItemLibraryWidget> m_widget;
+ ImportManagerView *m_importManagerView;
};
}
diff --git a/src/plugins/qmldesigner/components/itemlibrary/itemlibrarywidget.cpp b/src/plugins/qmldesigner/components/itemlibrary/itemlibrarywidget.cpp
index 9888a566e6..5f39710130 100644
--- a/src/plugins/qmldesigner/components/itemlibrary/itemlibrarywidget.cpp
+++ b/src/plugins/qmldesigner/components/itemlibrary/itemlibrarywidget.cpp
@@ -49,36 +49,29 @@
#include <QMenu>
#include <QApplication>
-#include <QDeclarativeItem>
-#include <private/qdeclarativeengine_p.h>
-
+#include <QQuickItem>
namespace QmlDesigner {
-
-
-
ItemLibraryWidget::ItemLibraryWidget(QWidget *parent) :
QFrame(parent),
m_iconProvider(m_resIconSize),
m_itemIconSize(24, 24),
m_resIconSize(24, 24),
- m_itemsView(new QDeclarativeView(this)),
+ m_itemsView(new QQuickView()),
m_resourcesView(new Internal::ItemLibraryTreeView(this)),
m_filterFlag(QtBasic)
{
+ Internal::registerQmlTypes();
+
setWindowTitle(tr("Library", "Title of library view"));
/* create Items view and its model */
- 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_itemsView->setResizeMode(QQuickView::SizeRootObjectToView);
+ m_itemLibraryModel = new Internal::ItemLibraryModel(this);
m_itemLibraryModel->setItemIconSize(m_itemIconSize);
- QDeclarativeContext *rootContext = m_itemsView->rootContext();
+ QQmlContext *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());
@@ -91,7 +84,7 @@ ItemLibraryWidget::ItemLibraryWidget(QWidget *parent) :
// loading the qml has to come after all needed context properties are set
m_itemsView->setSource(QUrl("qrc:/ItemLibrary/qml/ItemsView.qml"));
- QDeclarativeItem *rootItem = qobject_cast<QDeclarativeItem*>(m_itemsView->rootObject());
+ QQuickItem *rootItem = qobject_cast<QQuickItem*>(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)));
@@ -110,14 +103,17 @@ ItemLibraryWidget::ItemLibraryWidget(QWidget *parent) :
QTabBar *tabBar = new QTabBar(this);
tabBar->addTab(tr("QML Types", "Title of library QML types view"));
tabBar->addTab(tr("Resources", "Title of library resources view"));
+ tabBar->addTab(tr("Imports", "Title of library imports view"));
tabBar->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
-
- 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);
+ connect(tabBar, SIGNAL(currentChanged(int)), this, SLOT(setCurrentIndexOfStackedWidget(int)));
+ connect(tabBar, SIGNAL(currentChanged(int)), this, SLOT(updateSearch()));
+
+ m_filterLineEdit = new Utils::FilterLineEdit(this);
+ m_filterLineEdit->setObjectName(QLatin1String("itemLibrarySearchInput"));
+ m_filterLineEdit->setPlaceholderText(tr("<Filter>", "Library search input hint text"));
+ m_filterLineEdit->setDragEnabled(false);
+ m_filterLineEdit->setMinimumWidth(75);
+ m_filterLineEdit->setTextMargins(0, 0, 20, 0);
QWidget *lineEditFrame = new QWidget(this);
lineEditFrame->setObjectName(QLatin1String("itemLibrarySearchInputFrame"));
QGridLayout *lineEditLayout = new QGridLayout(lineEditFrame);
@@ -125,17 +121,14 @@ 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(m_lineEdit.data(), 1, 1, 1, 1);
+ lineEditLayout->addWidget(m_filterLineEdit.data(), 1, 1, 1, 1);
lineEditLayout->addItem(new QSpacerItem(5, 5, QSizePolicy::Fixed, QSizePolicy::Fixed), 1, 2);
- connect(m_lineEdit.data(), SIGNAL(filterChanged(QString)), this, SLOT(setSearchFilter(QString)));
+ connect(m_filterLineEdit.data(), SIGNAL(filterChanged(QString)), this, SLOT(setSearchFilter(QString)));
+ QWidget *container = createWindowContainer(m_itemsView.data());
m_stackedWidget = new QStackedWidget(this);
- m_stackedWidget->addWidget(m_itemsView.data());
+ m_stackedWidget->addWidget(container);
m_stackedWidget->addWidget(m_resourcesView.data());
- connect(tabBar, SIGNAL(currentChanged(int)),
- m_stackedWidget.data(), SLOT(setCurrentIndex(int)));
- connect(tabBar, SIGNAL(currentChanged(int)),
- this, SLOT(updateSearch()));
QWidget *spacer = new QWidget(this);
spacer->setObjectName(QLatin1String("itemLibrarySearchInputSpacer"));
@@ -154,8 +147,7 @@ ItemLibraryWidget::ItemLibraryWidget(QWidget *parent) :
/* style sheets */
setStyleSheet(QLatin1String(Utils::FileReader::fetchQrc(":/qmldesigner/stylesheet.css")));
- m_resourcesView->setStyleSheet(
- QLatin1String(Utils::FileReader::fetchQrc(":/qmldesigner/scrollbar.css")));
+ m_resourcesView->setStyleSheet(QLatin1String(Utils::FileReader::fetchQrc(":/qmldesigner/scrollbar.css")));
}
void ItemLibraryWidget::setItemLibraryInfo(ItemLibraryInfo *itemLibraryInfo)
@@ -191,6 +183,11 @@ void ItemLibraryWidget::updateImports()
setImportFilter(filter);
}
+void ItemLibraryWidget::setImportsWidget(QWidget *importsWidget)
+{
+ m_stackedWidget->addWidget(importsWidget);
+}
+
QList<QToolButton *> ItemLibraryWidget::createToolBarWidgets()
{
QList<QToolButton *> buttons;
@@ -281,6 +278,16 @@ void ItemLibraryWidget::emitImportChecked()
emit meegoChecked(meegoImport);
}
+void ItemLibraryWidget::setCurrentIndexOfStackedWidget(int index)
+{
+ if (index == 2)
+ m_filterLineEdit->setVisible(false);
+ else
+ m_filterLineEdit->setVisible(true);
+
+ m_stackedWidget->setCurrentIndex(index);
+}
+
void ItemLibraryWidget::setImportFilter(FilterChangeFlag flag)
{
return;
@@ -339,7 +346,7 @@ void ItemLibraryWidget::updateModel()
void ItemLibraryWidget::updateSearch()
{
- setSearchFilter(m_lineEdit->text());
+ setSearchFilter(m_filterLineEdit->text());
}
void ItemLibraryWidget::setResourcePath(const QString &resourcePath)
@@ -361,7 +368,7 @@ void ItemLibraryWidget::startDragAndDrop(int itemLibId)
drag->setPreview(QPixmap::fromImage(image));
drag->setMimeData(mimeData);
- QDeclarativeItem *rootItem = qobject_cast<QDeclarativeItem*>(m_itemsView->rootObject());
+ QQuickItem *rootItem = qobject_cast<QQuickItem*>(m_itemsView->rootObject());
connect(rootItem, SIGNAL(stopDragAndDrop()), drag, SLOT(stopDrag()));
drag->exec();
@@ -372,16 +379,6 @@ void ItemLibraryWidget::showItemInfo(int /*itemLibId*/)
// qDebug() << "showing item info about id" << itemLibId;
}
-void ItemLibraryWidget::wheelEvent(QWheelEvent *event)
-{
- 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 (!m_model)
diff --git a/src/plugins/qmldesigner/components/itemlibrary/itemlibrarywidget.h b/src/plugins/qmldesigner/components/itemlibrary/itemlibrarywidget.h
index 7796a9a9be..0369771d12 100644
--- a/src/plugins/qmldesigner/components/itemlibrary/itemlibrarywidget.h
+++ b/src/plugins/qmldesigner/components/itemlibrary/itemlibrarywidget.h
@@ -38,7 +38,7 @@
#include <QFrame>
#include <QToolButton>
#include <QFileIconProvider>
-#include <QDeclarativeView>
+#include <QQuickView>
QT_BEGIN_NAMESPACE
class QFileSystemModel;
@@ -85,7 +85,9 @@ public:
void updateImports();
-public Q_SLOTS:
+ void setImportsWidget(QWidget *importsWidget);
+
+public slots:
void setSearchFilter(const QString &searchFilter);
void updateModel();
void updateSearch();
@@ -103,7 +105,6 @@ public Q_SLOTS:
void onMeegoChecked(bool b);
protected:
- void wheelEvent(QWheelEvent *event);
void removeImport(const QString &name);
void addImport(const QString &name, const QString &version);
void emitImportChecked();
@@ -115,6 +116,9 @@ signals:
void qtBasicOnlyChecked(bool b);
void meegoChecked(bool b);
+private slots:
+ void setCurrentIndexOfStackedWidget(int index);
+
private:
ItemLibraryFileIconProvider m_iconProvider;
QSize m_itemIconSize;
@@ -126,8 +130,9 @@ private:
QWeakPointer<QFileSystemModel> m_resourcesFileSystemModel;
QWeakPointer<QStackedWidget> m_stackedWidget;
- QWeakPointer<Utils::FilterLineEdit> m_lineEdit;
- QScopedPointer<QDeclarativeView> m_itemsView;
+
+ QWeakPointer<Utils::FilterLineEdit> m_filterLineEdit;
+ QScopedPointer<QQuickView> m_itemsView;
QScopedPointer<Internal::ItemLibraryTreeView> m_resourcesView;
QWeakPointer<Model> m_model;
diff --git a/src/plugins/qmldesigner/components/itemlibrary/qml/ItemsView.qml b/src/plugins/qmldesigner/components/itemlibrary/qml/ItemsView.qml
index 8be1316212..793d7ea7f0 100644
--- a/src/plugins/qmldesigner/components/itemlibrary/qml/ItemsView.qml
+++ b/src/plugins/qmldesigner/components/itemlibrary/qml/ItemsView.qml
@@ -27,7 +27,7 @@
**
****************************************************************************/
-import QtQuick 1.0
+import QtQuick 2.1
/* The view displaying the item grid.
@@ -90,146 +90,147 @@ focus */
onEntered: {
if (!pressed)
stopDragAndDrop()
+ }
+ }
+
+ signal selectionUpdated(int itemSectionIndex)
+
+ property int selectedItemLibId: -1
+ property int selectionSectionLibId: -1
+
+ function setSelection(itemLibId) {
+ selectedItemLibId = itemLibId
+ selectionSectionLibId = itemLibraryModel.getSectionLibId(itemLibId)
+ selectionUpdated(itemLibraryModel.getItemSectionIndex(itemLibId))
+ }
+
+ function unsetSelection() {
+ selectedItemLibId = -1
+ selectionSectionLibId = -1
+ selectionUpdated(-1)
+ }
+
+ Connections {
+ target: itemLibraryModel
+ onVisibilityChanged: {
+ if (itemLibraryModel.isItemVisible(selectedItemLibId))
+ setSelection(selectedItemLibId)
+ else
+ unsetSelection()
+ }
+ }
+
+ /* the following 3 properties are calculated here for performance
+ reasons and then passed to the section views */
+ property int entriesPerRow: Math.max(1, Math.floor((itemsFlickable.width - 2) / style.cellWidth))
+
+ property int cellWidth: Math.floor((itemsFlickable.width - 2) / entriesPerRow)
+ property int cellHeight: style.cellHeight
+
+ Component {
+ id: sectionDelegate
+
+ SectionView {
+ id: section
+
+ entriesPerRow: itemsView.entriesPerRow
+ cellWidth: itemsView.cellWidth
+ cellHeight: itemsView.cellHeight
+
+ width: itemsFlickable.width
+ itemHighlight: selector
+
+ property bool containsSelection: (selectionSectionLibId == sectionLibId)
+
+ onItemSelected: {
+ itemsView.setSelection(itemLibId)
+ itemsView.itemSelected(itemLibId)
+ }
+ onItemDragged: {
+ section.itemSelected(itemLibId)
+ itemsView.itemDragged(itemLibId)
}
+
+ Connections {
+ target: itemsView
+ onExpandAllEntries: section.expand()
+ onSelectionUpdated: {
+ if (containsSelection) {
+ section.setSelection(itemSectionIndex)
+ section.focusSelection(itemsFlickable)
+ } else
+ section.unsetSelection()
+ }
}
- signal selectionUpdated(int itemSectionIndex)
+ Component {
+ id: selector
- property int selectedItemLibId: -1
- property int selectionSectionLibId: -1
+ Selector {
+ x: containsSelection? section.currentItem.x:0
+ y: containsSelection? section.currentItem.y:0
+ width: itemsView.cellWidth
+ height: itemsView.cellHeight
- function setSelection(itemLibId) {
- selectedItemLibId = itemLibId
- selectionSectionLibId = itemLibraryModel.getSectionLibId(itemLibId)
- selectionUpdated(itemLibraryModel.getItemSectionIndex(itemLibId))
+ visible: containsSelection
}
+ }
+ }
+ }
- function unsetSelection() {
- selectedItemLibId = -1
- selectionSectionLibId = -1
- selectionUpdated(-1)
- }
+ Flickable {
+ id: itemsFlickable
- Connections {
- target: itemLibraryModel
- onVisibilityChanged: {
- if (itemLibraryModel.isItemVisible(selectedItemLibId))
- setSelection(selectedItemLibId)
- else
- unsetSelection()
- }
- }
-
- /* the following 3 properties are calculated here for performance
-reasons and then passed to the section views */
- property int entriesPerRow: Math.max(1, Math.floor((itemsFlickable.width - 2) / style.cellWidth))
- property int cellWidth: Math.floor((itemsFlickable.width - 2) / entriesPerRow)
- property int cellHeight: style.cellHeight
-
- Component {
- id: sectionDelegate
-
- SectionView {
- id: section
-
- entriesPerRow: itemsView.entriesPerRow
- cellWidth: itemsView.cellWidth
- cellHeight: itemsView.cellHeight
-
- width: itemsFlickable.width
- itemHighlight: selector
-
- property bool containsSelection: (selectionSectionLibId == sectionLibId)
-
- onItemSelected: {
- itemsView.setSelection(itemLibId)
- itemsView.itemSelected(itemLibId)
- }
- onItemDragged: {
- section.itemSelected(itemLibId)
- itemsView.itemDragged(itemLibId)
- }
-
- Connections {
- target: itemsView
- onExpandAllEntries: section.expand()
- onSelectionUpdated: {
- if (containsSelection) {
- section.setSelection(itemSectionIndex)
- section.focusSelection(itemsFlickable)
- } else
- section.unsetSelection()
- }
- }
-
- Component {
- id: selector
-
- Selector {
- x: containsSelection? section.currentItem.x:0
- y: containsSelection? section.currentItem.y:0
- width: itemsView.cellWidth
- height: itemsView.cellHeight
-
- visible: containsSelection
- }
- }
- }
- }
-
- Flickable {
- id: itemsFlickable
-
- anchors.top: parent.top
- anchors.topMargin: 3
- anchors.bottom: parent.bottom
- anchors.left: parent.left
- anchors.right: scrollbarFrame.left
- boundsBehavior: Flickable.DragOverBounds
-
- interactive: false
- contentHeight: col.height
-
- /* Limit the content position. Without this, resizing would get the
+ anchors.top: parent.top
+ anchors.topMargin: 3
+ anchors.bottom: parent.bottom
+ anchors.left: parent.left
+ anchors.right: scrollbarFrame.left
+ boundsBehavior: Flickable.DragOverBounds
+
+ interactive: false
+ contentHeight: col.height
+
+ /* Limit the content position. Without this, resizing would get the
content position out of scope regarding the scrollbar. */
- function limitContentPos() {
- if (contentY < 0)
- contentY = 0;
- else {
- var maxContentY = Math.max(0, contentHeight - height)
- if (contentY > maxContentY)
- contentY = maxContentY;
- }
- }
- onHeightChanged: limitContentPos()
- onContentHeightChanged: limitContentPos()
-
- Column {
- id: col
-
- Repeater {
- model: itemLibraryModel // to be set in Qml context
- delegate: sectionDelegate
- }
- }
- }
-
- Item {
- id: scrollbarFrame
-
- anchors.top: parent.top
- anchors.topMargin: 2
- anchors.bottom: parent.bottom
- anchors.bottomMargin: 1
- anchors.right: parent.right
- width: (itemsFlickable.contentHeight > itemsFlickable.height)? 11:0
-
- Scrollbar {
- id: scrollbar
- anchors.fill: parent
- anchors.leftMargin: 1
-
- flickable: itemsFlickable
- }
- }
- }
+ function limitContentPos() {
+ if (contentY < 0) {
+ contentY = 0;
+ } else {
+ var maxContentY = Math.max(0, contentHeight - height)
+ if (contentY > maxContentY)
+ contentY = maxContentY;
+ }
+ }
+ onHeightChanged: limitContentPos()
+ onContentHeightChanged: limitContentPos()
+
+ Column {
+ id: col
+
+ Repeater {
+ model: itemLibraryModel // to be set in Qml context
+ delegate: sectionDelegate
+ }
+ }
+ }
+
+ Item {
+ id: scrollbarFrame
+
+ anchors.top: parent.top
+ anchors.topMargin: 2
+ anchors.bottom: parent.bottom
+ anchors.bottomMargin: 1
+ anchors.right: parent.right
+ width: (itemsFlickable.contentHeight > itemsFlickable.height)? 11:0
+
+ Scrollbar {
+ id: scrollbar
+ anchors.fill: parent
+ anchors.leftMargin: 1
+
+ flickable: itemsFlickable
+ }
+ }
+}
diff --git a/src/plugins/qmldesigner/components/itemlibrary/qml/ItemsViewStyle.qml b/src/plugins/qmldesigner/components/itemlibrary/qml/ItemsViewStyle.qml
index 24b613182a..e5f29de94c 100644
--- a/src/plugins/qmldesigner/components/itemlibrary/qml/ItemsViewStyle.qml
+++ b/src/plugins/qmldesigner/components/itemlibrary/qml/ItemsViewStyle.qml
@@ -27,7 +27,7 @@
**
****************************************************************************/
-import QtQuick 1.0
+import QtQuick 2.1
// the style used the items view
diff --git a/src/plugins/qmldesigner/components/itemlibrary/qml/Scrollbar.qml b/src/plugins/qmldesigner/components/itemlibrary/qml/Scrollbar.qml
index 0e1dba8095..33bc50fc80 100644
--- a/src/plugins/qmldesigner/components/itemlibrary/qml/Scrollbar.qml
+++ b/src/plugins/qmldesigner/components/itemlibrary/qml/Scrollbar.qml
@@ -27,7 +27,7 @@
**
****************************************************************************/
-import QtQuick 1.0
+import QtQuick 2.1
// scrollbar for the items view
diff --git a/src/plugins/qmldesigner/components/itemlibrary/qml/SectionView.qml b/src/plugins/qmldesigner/components/itemlibrary/qml/SectionView.qml
index a29cf8997d..5a43d7de75 100644
--- a/src/plugins/qmldesigner/components/itemlibrary/qml/SectionView.qml
+++ b/src/plugins/qmldesigner/components/itemlibrary/qml/SectionView.qml
@@ -27,7 +27,7 @@
**
****************************************************************************/
-import QtQuick 1.0
+import QtQuick 2.1
// view displaying one item library section including its grid
@@ -77,18 +77,18 @@ Column {
var currentItemX = sectionView.x + gridFrame.x + gridView.x + gridView.currentItem.x;
var currentItemY = sectionView.y + gridFrame.y + gridView.y + gridView.currentItem.y
- - gridView.contentY; // workaround: GridView reports wrong contentY
+ - gridView.contentY; // workaround: GridView reports wrong contentY
if (currentItemY < flickable.contentY)
pos = Math.max(0, currentItemY)
- else if ((currentItemY + gridView.currentItem.height) >
- (flickable.contentY + flickable.height - 1))
- pos = Math.min(Math.max(0, flickable.contentHeight - flickable.height),
- currentItemY + gridView.currentItem.height - flickable.height + 1)
+ else if ((currentItemY + gridView.currentItem.height) >
+ (flickable.contentY + flickable.height - 1))
+ pos = Math.min(Math.max(0, flickable.contentHeight - flickable.height),
+ currentItemY + gridView.currentItem.height - flickable.height + 1)
- if (pos >= 0)
- flickable.contentY = pos
+ if (pos >= 0)
+ flickable.contentY = pos
}
// internal
@@ -98,7 +98,7 @@ Column {
Component {
id: itemDelegate
- ItemView {
+ SingleItemView {
id: item
width: cellWidth
@@ -145,6 +145,7 @@ Column {
color: style.sectionTitleTextColor
elide: Text.ElideMiddle
font.bold: true
+ renderType: Text.NativeRendering
}
MouseArea {
id: mouseArea
@@ -168,7 +169,8 @@ Column {
clip: true
width: entriesPerRow * cellWidth + 1
- height: Math.ceil(sectionEntries.count / entriesPerRow) * cellHeight + 1
+ height: gridView.model !== undefined ? Math.ceil(gridView.count / sectionView.entriesPerRow) * cellHeight + 1 : 0
+
anchors.horizontalCenter: parent.horizontalCenter
GridView {
@@ -198,18 +200,18 @@ updated properly under all conditions */
}
states: [
- State {
- name: "shrunk"
- PropertyChanges {
- target: gridFrame
- height: 0
- opacity: 0
- }
- PropertyChanges {
- target: arrow
- rotation: -90
+ State {
+ name: "shrunk"
+ PropertyChanges {
+ target: gridFrame
+ height: 0
+ opacity: 0
+ }
+ PropertyChanges {
+ target: arrow
+ rotation: -90
+ }
}
- }
]
}
diff --git a/src/plugins/qmldesigner/components/itemlibrary/qml/Selector.qml b/src/plugins/qmldesigner/components/itemlibrary/qml/Selector.qml
index a67d4bfb8d..9e6a30e048 100644
--- a/src/plugins/qmldesigner/components/itemlibrary/qml/Selector.qml
+++ b/src/plugins/qmldesigner/components/itemlibrary/qml/Selector.qml
@@ -27,7 +27,7 @@
**
****************************************************************************/
-import QtQuick 1.0
+import QtQuick 2.1
// the coloured selector of the items view
diff --git a/src/plugins/qmldesigner/components/itemlibrary/qml/ItemView.qml b/src/plugins/qmldesigner/components/itemlibrary/qml/SingleItemView.qml
index 659daf66b9..10757c08ba 100644
--- a/src/plugins/qmldesigner/components/itemlibrary/qml/ItemView.qml
+++ b/src/plugins/qmldesigner/components/itemlibrary/qml/SingleItemView.qml
@@ -27,8 +27,7 @@
**
****************************************************************************/
-import QtQuick 1.0
-
+import QtQuick 2.1
// view displaying an item library grid item
Item {
@@ -115,6 +114,7 @@ Item {
horizontalAlignment: "AlignHCenter"
text: itemName // to be set by model
color: style.itemNameTextColor
+ renderType: Text.NativeRendering
}
MouseArea {
diff --git a/src/plugins/qmldesigner/components/navigator/navigatortreemodel.cpp b/src/plugins/qmldesigner/components/navigator/navigatortreemodel.cpp
index e9340401c9..5ceb949caa 100644
--- a/src/plugins/qmldesigner/components/navigator/navigatortreemodel.cpp
+++ b/src/plugins/qmldesigner/components/navigator/navigatortreemodel.cpp
@@ -34,11 +34,12 @@
#include <nodeproperty.h>
#include <variantproperty.h>
#include <metainfo.h>
-#include <qmlmodelview.h>
+#include <abstractview.h>
#include <rewriterview.h>
#include <invalididexception.h>
#include <rewritingexception.h>
#include <modelnodecontextmenu.h>
+#include <qmlitemnode.h>
#include <QMimeData>
#include <QMessageBox>
@@ -47,11 +48,11 @@
static inline void setScenePos(const QmlDesigner::ModelNode &modelNode,const QPointF &pos)
{
- QmlDesigner::QmlItemNode parentNode = modelNode.parentProperty().parentQmlObjectNode().toQmlItemNode();
- if (parentNode.isValid()) {
+ if (modelNode.hasParentProperty() && QmlDesigner::QmlItemNode::isValidQmlItemNode(modelNode.parentProperty().parentModelNode())) {
+ QmlDesigner::QmlItemNode parentNode = modelNode.parentProperty().parentQmlObjectNode().toQmlItemNode();
QPointF localPos = parentNode.instanceSceneTransform().inverted().map(pos);
- modelNode.variantProperty("x") = localPos.toPoint().x();
- modelNode.variantProperty("y") = localPos.toPoint().y();
+ modelNode.variantProperty("x").setValue(localPos.toPoint().x());
+ modelNode.variantProperty("y").setValue(localPos.toPoint().y());
}
}
@@ -149,8 +150,7 @@ bool NavigatorTreeModel::dropMimeData(const QMimeData *data,
return false;
targetIndex -= visibleProperties(parentNode).count();
parentPropertyName = parentNode.metaInfo().defaultPropertyName();
- }
- else {
+ } else {
parentItemIndex = parentIndex.parent();
parentPropertyName = parentIndex.data(Qt::DisplayRole).toByteArray();
}
@@ -295,8 +295,7 @@ void NavigatorTreeModel::updateItemRowOrder(const NodeListProperty &listProperty
parentIdItem = parentRow.idItem;
newRow += visibleProperties(listProperty.parentModelNode()).count();
}
- }
- else {
+ } else {
parentIdItem = itemRow.idItem->parent();
}
Q_ASSERT(parentIdItem);
@@ -382,7 +381,7 @@ NavigatorTreeModel::ItemRow NavigatorTreeModel::itemRowForNode(const ModelNode &
return m_nodeItemHash.value(node);
}
-void NavigatorTreeModel::setView(QmlModelView *view)
+void NavigatorTreeModel::setView(AbstractView *view)
{
m_view = view;
m_hiddenProperties.clear();
diff --git a/src/plugins/qmldesigner/components/navigator/navigatortreemodel.h b/src/plugins/qmldesigner/components/navigator/navigatortreemodel.h
index 3d833f0084..8c53cabfaa 100644
--- a/src/plugins/qmldesigner/components/navigator/navigatortreemodel.h
+++ b/src/plugins/qmldesigner/components/navigator/navigatortreemodel.h
@@ -39,7 +39,7 @@
namespace QmlDesigner {
class Model;
-class QmlModelView;
+class AbstractView;
class ModelNode;
class NavigatorTreeModel : public QStandardItemModel
@@ -95,7 +95,7 @@ public:
int column,
const QModelIndex &parent);
- void setView(QmlModelView *view);
+ void setView(AbstractView *view);
void clearView();
QModelIndex indexForNode(const ModelNode &node) const;
@@ -140,7 +140,7 @@ private:
private:
QHash<ModelNode, ItemRow> m_nodeItemHash;
QHash<uint, ModelNode> m_nodeHash;
- QWeakPointer<QmlModelView> m_view;
+ QWeakPointer<AbstractView> m_view;
bool m_blockItemChangedSignal;
diff --git a/src/plugins/qmldesigner/components/navigator/navigatortreeview.cpp b/src/plugins/qmldesigner/components/navigator/navigatortreeview.cpp
index 497318705d..58cb96790c 100644
--- a/src/plugins/qmldesigner/components/navigator/navigatortreeview.cpp
+++ b/src/plugins/qmldesigner/components/navigator/navigatortreeview.cpp
@@ -145,8 +145,7 @@ public:
if (option->rect.height() == 0) {
if (option->rect.top()>0)
painter->drawLine(rect.topLeft(), rect.topRight());
- }
- else {
+ } else {
highlight.setAlphaF(0.2);
painter->setBrush(highlight);
painter->drawRect(rect.adjusted(0, 0, -1, -1));
@@ -280,8 +279,7 @@ void NameItemDelegate::paint(QPainter *painter,
displayString = fm.elidedText(displayString,Qt::ElideMiddle,option.rect.width()-extraSpace);
displayStringOffset = QPoint(5+pixmapSide,-5);
width = fm.width(displayString);
- }
- else {
+ } else {
displayString = index.data(Qt::DisplayRole).toString();
displayStringOffset = QPoint(0, -2);
}
diff --git a/src/plugins/qmldesigner/components/navigator/navigatorview.cpp b/src/plugins/qmldesigner/components/navigator/navigatorview.cpp
index deec645b3e..d8677f8a04 100644
--- a/src/plugins/qmldesigner/components/navigator/navigatorview.cpp
+++ b/src/plugins/qmldesigner/components/navigator/navigatorview.cpp
@@ -39,21 +39,22 @@
#include <nodelistproperty.h>
#include <variantproperty.h>
#include <QHeaderView>
+#include <qmlitemnode.h>
static inline void setScenePos(const QmlDesigner::ModelNode &modelNode,const QPointF &pos)
{
- QmlDesigner::QmlItemNode parentNode = modelNode.parentProperty().parentQmlObjectNode().toQmlItemNode();
- if (parentNode.isValid()) {
+ if (modelNode.hasParentProperty() && QmlDesigner::QmlItemNode::isValidQmlItemNode(modelNode.parentProperty().parentModelNode())) {
+ QmlDesigner::QmlItemNode parentNode = modelNode.parentProperty().parentQmlObjectNode().toQmlItemNode();
QPointF localPos = parentNode.instanceSceneTransform().inverted().map(pos);
- modelNode.variantProperty("x") = localPos.toPoint().x();
- modelNode.variantProperty("y") = localPos.toPoint().y();
+ modelNode.variantProperty("x").setValue(localPos.toPoint().x());
+ modelNode.variantProperty("y").setValue(localPos.toPoint().y());
}
}
namespace QmlDesigner {
NavigatorView::NavigatorView(QObject* parent) :
- QmlModelView(parent),
+ AbstractView(parent),
m_blockSelectionChangedSignal(false),
m_widget(new NavigatorWidget(this)),
m_treeModel(new NavigatorTreeModel(this))
@@ -114,7 +115,7 @@ WidgetInfo NavigatorView::widgetInfo()
void NavigatorView::modelAttached(Model *model)
{
- QmlModelView::modelAttached(model);
+ AbstractView::modelAttached(model);
m_treeModel->setView(this);
@@ -133,7 +134,7 @@ void NavigatorView::modelAttached(Model *model)
void NavigatorView::modelAboutToBeDetached(Model *model)
{
m_treeModel->clearView();
- QmlModelView::modelAboutToBeDetached(model);
+ AbstractView::modelAboutToBeDetached(model);
}
void NavigatorView::importsChanged(const QList<Import> &/*addedImports*/, const QList<Import> &/*removedImports*/)
@@ -274,10 +275,15 @@ void NavigatorView::rewriterEndTransaction()
{
}
-void NavigatorView::actualStateChanged(const ModelNode &/*node*/)
+void NavigatorView::currentStateChanged(const ModelNode &/*node*/)
{
}
+void NavigatorView::instancesToken(const QString &/*tokenName*/, int /*tokenNumber*/, const QVector<ModelNode> &/*nodeVector*/)
+{
+
+}
+
void NavigatorView::nodeOrderChanged(const NodeListProperty &listProperty, const ModelNode &node, int oldIndex)
{
if (m_treeModel->isInTree(node))
@@ -303,7 +309,7 @@ void NavigatorView::leftButtonClicked()
foreach (const ModelNode &node, selectedModelNodes()) {
if (!node.isRootNode() && !node.parentProperty().parentModelNode().isRootNode()) {
- if (QmlItemNode(node).isValid()) {
+ if (QmlItemNode::isValidQmlItemNode(node)) {
QPointF scenePos = QmlItemNode(node).instanceScenePosition();
node.parentProperty().parentModelNode().parentProperty().reparentHere(node);
if (!scenePos.isNull())
@@ -330,13 +336,16 @@ void NavigatorView::rightButtonClicked()
if (index >= 0) { //for the first node the semantics are not clear enough. Wrapping would be irritating.
ModelNode newParent = node.parentProperty().toNodeListProperty().at(index);
- if (QmlItemNode(node).isValid()) {
+ if (QmlItemNode::isValidQmlItemNode(node)
+ && QmlItemNode::isValidQmlItemNode(newParent)
+ && !newParent.metaInfo().defaultPropertyIsComponent()) {
QPointF scenePos = QmlItemNode(node).instanceScenePosition();
newParent.nodeAbstractProperty(newParent.metaInfo().defaultPropertyName()).reparentHere(node);
if (!scenePos.isNull())
setScenePos(node, scenePos);
} else {
- newParent.nodeAbstractProperty(newParent.metaInfo().defaultPropertyName()).reparentHere(node);
+ if (newParent.metaInfo().isValid() && !newParent.metaInfo().defaultPropertyIsComponent())
+ newParent.nodeAbstractProperty(newParent.metaInfo().defaultPropertyName()).reparentHere(node);
}
}
}
diff --git a/src/plugins/qmldesigner/components/navigator/navigatorview.h b/src/plugins/qmldesigner/components/navigator/navigatorview.h
index 2aa159367f..aede53b67f 100644
--- a/src/plugins/qmldesigner/components/navigator/navigatorview.h
+++ b/src/plugins/qmldesigner/components/navigator/navigatorview.h
@@ -30,7 +30,7 @@
#ifndef NAVIGATORVIEW_H
#define NAVIGATORVIEW_H
-#include <qmlmodelview.h>
+#include <abstractview.h>
#include <QWeakPointer>
@@ -48,7 +48,7 @@ class NavigatorTreeModel;
class IconCheckboxItemDelegate;
class IdItemDelegate;
-class NavigatorView : public QmlModelView
+class NavigatorView : public AbstractView
{
Q_OBJECT
@@ -96,7 +96,9 @@ public:
void rewriterBeginTransaction() QTC_OVERRIDE;
void rewriterEndTransaction() QTC_OVERRIDE;
- void actualStateChanged(const ModelNode &node) QTC_OVERRIDE;
+ void currentStateChanged(const ModelNode &node) QTC_OVERRIDE;
+
+ void instancesToken(const QString &tokenName, int tokenNumber, const QVector<ModelNode> &nodeVector) QTC_OVERRIDE;
private slots:
// void handleChangedItem(QStandardItem * item);
diff --git a/src/plugins/qmldesigner/components/propertyeditor/basiclayouts.h b/src/plugins/qmldesigner/components/propertyeditor/basiclayouts.h
deleted file mode 100644
index d4af8b4524..0000000000
--- a/src/plugins/qmldesigner/components/propertyeditor/basiclayouts.h
+++ /dev/null
@@ -1,177 +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 BASICLAYOUTS_H
-#define BASICLAYOUTS_H
-
-#include <qlayoutobject.h>
-
-QT_BEGIN_NAMESPACE
-
-QT_MODULE(Declarative)
-class QBoxLayoutObject : public QLayoutObject
-{
- Q_OBJECT
-
- Q_PROPERTY(QDeclarativeListProperty<QWidget> children READ children)
-
- Q_PROPERTY(int topMargin READ topMargin WRITE setTopMargin)
- Q_PROPERTY(int bottomMargin READ bottomMargin WRITE setBottomMargin)
- Q_PROPERTY(int leftMargin READ leftMargin WRITE setLeftMargin)
- Q_PROPERTY(int rightMargin READ rightMargin WRITE setRightMargin)
- Q_PROPERTY(int spacing READ spacing WRITE setSpacing)
-
- Q_CLASSINFO("DefaultProperty", "children")
-public:
- QBoxLayoutObject(QObject *parent=0);
- explicit QBoxLayoutObject(QBoxLayout *, QObject *parent=0);
- virtual QLayout *layout() const;
-
- QDeclarativeListProperty<QWidget> children() {
- return QDeclarativeListProperty<QWidget>(this, 0, children_append, 0, 0, children_clear);
- }
-
-private:
- friend class WidgetList;
- void addWidget(QWidget *);
- void clearWidget();
-
- static void children_append(QDeclarativeListProperty<QWidget> *property, QWidget *widget) {
- static_cast<QBoxLayoutObject*>(property->object)->addWidget(widget);
- }
-
- static void children_clear(QDeclarativeListProperty<QWidget> *property) {
- static_cast<QBoxLayoutObject*>(property->object)->clearWidget();
- }
-
- void getMargins()
- {
- _layout->getContentsMargins(&mLeft, &mTop, &mRight, &mBottom);
- }
-
- void setMargins()
- {
- _layout->setContentsMargins(mLeft, mTop, mRight, mBottom);
- }
-
- int topMargin()
- {
- getMargins();
- return mTop;
- }
-
- void setTopMargin(int margin)
- {
- getMargins();
- mTop = margin;
- setMargins();
- }
-
- int bottomMargin()
- {
- getMargins();
- return mBottom;
- }
-
- void setBottomMargin(int margin)
- {
- getMargins();
- mBottom = margin;
- setMargins();
- }
-
- int leftMargin()
- {
- getMargins();
- return mLeft;
- }
-
- void setLeftMargin(int margin)
- {
- getMargins();
- mLeft = margin;
- setMargins();
- }
-
- int rightMargin()
- {
- getMargins();
- return mRight;
- }
-
- void setRightMargin(int margin)
- {
- getMargins();
- mRight = margin;
- setMargins();
- }
-
- int spacing() const
- {
- return _layout->spacing();
- }
-
- void setSpacing(int spacing)
- {
- _layout->setSpacing(spacing);
- }
-
- QBoxLayout *_layout;
-
- int mTop, mLeft, mBottom, mRight;
-
-};
-
-class QHBoxLayoutObject : public QBoxLayoutObject
-{
-Q_OBJECT
-public:
- QHBoxLayoutObject(QObject *parent=0);
-};
-
-class QVBoxLayoutObject : public QBoxLayoutObject
-{
-Q_OBJECT
-public:
- QVBoxLayoutObject(QObject *parent=0);
-};
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QBoxLayoutObject)
-QML_DECLARE_TYPE(QHBoxLayoutObject)
-QML_DECLARE_TYPE(QVBoxLayoutObject)
-
-
-class BasicLayouts {
-public:
- static void registerDeclarativeTypes();
-};
-
-#endif // BASICLAYOUTS_H
diff --git a/src/plugins/qmldesigner/components/propertyeditor/basicwidgets.cpp b/src/plugins/qmldesigner/components/propertyeditor/basicwidgets.cpp
deleted file mode 100644
index ffc61704c9..0000000000
--- a/src/plugins/qmldesigner/components/propertyeditor/basicwidgets.cpp
+++ /dev/null
@@ -1,1460 +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 "basicwidgets.h"
-#include <utils/fileutils.h>
-#include <qlayoutobject.h>
-#include <QDeclarativeContext>
-#include <QDeclarativeComponent>
-#include <QDebug>
-#include <QFile>
-#include <QPixmap>
-#include <QTimeLine>
-#include <QFileInfo>
-#include <QMenu>
-#include <QAction>
-#include <QListView>
-#include <QApplication>
-#include <QGraphicsOpacityEffect>
-#include <QStyleFactory>
-#include <QScopedPointer>
-
-#include <QTextEdit>
-
-
-QT_BEGIN_NAMESPACE
-
-class WindowsStyleSingleton
-{
- public:
- static WindowsStyleSingleton* instance();
- QStyle* style() { return m_style.data(); };
-
- private:
- static WindowsStyleSingleton *m_instance;
-
- QScopedPointer<QStyle> m_style;
-
- WindowsStyleSingleton() : m_style(QStyleFactory::create(QLatin1String("windows"))) {}
- WindowsStyleSingleton( const WindowsStyleSingleton& );
-
- class WindowsWatcher {
- public: ~WindowsWatcher() {
- if ( WindowsStyleSingleton::m_instance != 0 )
- delete WindowsStyleSingleton::m_instance;
- }
- };
- friend class WindowsWatcher;
-};
-
-WindowsStyleSingleton* WindowsStyleSingleton::m_instance = 0;
-
-WindowsStyleSingleton* WindowsStyleSingleton::instance()
-{
- static WindowsWatcher w;
- if ( m_instance == 0 )
- m_instance = new WindowsStyleSingleton();
- return m_instance;
-}
-
-
-class QWidgetDeclarativeUI;
-
-class ResizeEventFilter : public QObject
-{
- Q_OBJECT
-public:
- ResizeEventFilter(QObject *parent) : QObject(parent), m_target(0) { }
-
- void setTarget(QObject *target) { m_target = target; }
- void setDuiTarget(QWidgetDeclarativeUI* dui_target) {m_dui_target = dui_target;}
-
-protected:
- bool eventFilter(QObject *obj, QEvent *event);
-private:
- QObject *m_target;
- QWidgetDeclarativeUI* m_dui_target;
-};
-
-class QWidgetDeclarativeUI : public QObject
-{
- Q_OBJECT
-
- Q_PROPERTY(QDeclarativeListProperty<QObject> children READ children)
- Q_PROPERTY(QLayoutObject *layout READ layout WRITE setLayout)
- Q_PROPERTY(QDeclarativeListProperty<Action> actions READ actions)
- Q_PROPERTY(QFont font READ font WRITE setFont)
-
- Q_PROPERTY(QPoint pos READ pos)
- Q_PROPERTY(QSize size READ size)
-
- Q_PROPERTY(int x READ x WRITE setX NOTIFY xChanged)
- Q_PROPERTY(int y READ y WRITE setY NOTIFY yChanged)
-
- Q_PROPERTY(int globalX READ globalX WRITE setGlobalX)
- Q_PROPERTY(int globalY READ globalY WRITE setGlobalY)
-
- Q_PROPERTY(bool focus READ hasFocus NOTIFY focusChanged)
- Q_PROPERTY(int width READ width WRITE setWidth NOTIFY widthChanged)
- Q_PROPERTY(int height READ height WRITE setHeight NOTIFY heightChanged)
- Q_PROPERTY(qreal opacity READ opacity WRITE setOpacity NOTIFY opacityChanged)
-
- Q_PROPERTY(QUrl styleSheetFile READ styleSheetFile WRITE setStyleSheetFile)
-
- Q_PROPERTY(QColor windowColor READ windowColor WRITE setWindowColor)
- Q_PROPERTY(QColor backgroundColor READ backgroundColor WRITE setBackgroundColor)
- Q_PROPERTY(QColor baseColor READ baseColor WRITE setBaseColor)
- Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor)
- Q_PROPERTY(QColor windowTextColor READ windowTextColor WRITE setWindowTextColor)
- Q_PROPERTY(QColor buttonTextColor READ buttonTextColor WRITE setButtonTextColor)
- Q_PROPERTY(QColor buttonColor READ buttonColor WRITE setButtonColor)
-
- Q_PROPERTY(int fixedWidth READ width WRITE setFixedWidth)
- Q_PROPERTY(int fixedHeight READ height WRITE setFixedHeight)
-
- Q_PROPERTY(bool mouseOver READ mouseOver NOTIFY mouseOverChanged)
-
- Q_PROPERTY(bool visible READ visible WRITE setVisible NOTIFY visibleChanged)
- Q_PROPERTY(bool enabled READ enabled WRITE setEnabled NOTIFY enabledChanged)
-
- Q_CLASSINFO("DefaultProperty", "children")
-
-signals:
- void xChanged();
- void yChanged();
- void widthChanged();
- void heightChanged();
- void focusChanged();
- void mouseOverChanged();
- void opacityChanged();
- void visibleChanged();
- void enabledChanged();
-
-public:
- QWidgetDeclarativeUI(QObject *other) : QObject(other), _layout(0), _graphicsOpacityEffect(0) {
- q = qobject_cast<QWidget*>(other);
- ResizeEventFilter *filter(new ResizeEventFilter(q));
- filter->setTarget(q);
- filter->setDuiTarget(this);
- m_mouseOver = false;
- q->installEventFilter(filter);
- q->setStyle(WindowsStyleSingleton::instance()->style());
- Q_ASSERT(q);
- }
- virtual ~QWidgetDeclarativeUI() {
- }
-
-public:
-
- void setMouseOver(bool _mouseOver)
- {
- m_mouseOver = _mouseOver;
- }
-
- void emitResize()
- {
- emit widthChanged();
- emit heightChanged();
- }
-
- void emitMove()
- {
- emit xChanged();
- emit yChanged();
- }
-
- void emitFocusChanged()
- {
- emit focusChanged();
- }
-
- void emitMouseOverChanged()
- {
- emit mouseOverChanged();
- }
-
-
- void emitVisibleChanged()
- {
- emit visibleChanged();
- }
-
- void emitEnabledChanged()
- {
- emit enabledChanged();
- }
-
- QDeclarativeListProperty<QObject> children() {
- return QDeclarativeListProperty<QObject>(this, 0, children_append, children_count, children_at, children_clear);
- }
-
- QLayoutObject *layout() const { return _layout; }
- void setLayout(QLayoutObject *lo)
- {
- _layout = lo;
- static_cast<QWidget *>(parent())->setLayout(lo->layout());
- }
-
- QFont font() const
- {
- return _font;
- }
-
- void setFont(const QFont &font)
- {
- if (font != _font) {
- _font = font;
- static_cast<QWidget *>(parent())->setFont(_font);
- }
- }
-
- int x() const {
- return q->x();
- }
-
- int globalX() const {
- if (q->parentWidget())
- return q->mapToGlobal(QPoint(x(), 0)).x();
- else
- return x();
- }
-
- bool hasFocus() const {
- return q->hasFocus();
- }
-
- bool mouseOver() const {
- return m_mouseOver;
- }
-
- void setX(int x) {
- q->move(x, y());
- }
-
- void setGlobalX(int newX) {
- if (q->parentWidget())
- setX(q->mapFromGlobal(QPoint(newX, 1)).x());
- else
- setX(newX);
- }
-
- int y() const {
- return q->y();
- }
-
- bool visible() const {
- return q->isVisible();
- }
-
- void setVisible(bool visible) {
- q->setVisible(visible);
- }
-
- bool enabled() const {
- return q->isEnabled();
- }
-
- void setEnabled(bool enabled) {
- q->setEnabled(enabled);
- }
-
- int globalY() const {
- if (q->parentWidget())
- return q->mapToGlobal(QPoint(1,y())).y();
- else return y();
- }
-
- qreal opacity() const {
- if (_graphicsOpacityEffect)
- return _graphicsOpacityEffect->opacity();
- else
- return 1;
- }
-
- void setOpacity(qreal newOpacity) {
- if (newOpacity != opacity()) {
- if (!_graphicsOpacityEffect) {
- _graphicsOpacityEffect = new QGraphicsOpacityEffect(this);
- q->setGraphicsEffect(_graphicsOpacityEffect);
- }
- _graphicsOpacityEffect->setOpacity(newOpacity);
- emit opacityChanged();
- }
- }
-
- void setY(int y) {
- q->move(x(), y);
- }
-
- void setGlobalY(int newY) {
- if (q->parentWidget())
- setY(q->parentWidget()->mapFromGlobal(QPoint(1, newY)).y());
- else
- setY(newY);
- }
-
- int width() const {
- return q->width();
- }
-
- void setWidth(int width) {
- q->resize(width, height());
- }
-
- int height() const {
- return q->height();
- }
-
- void setHeight(int height) {
- q->resize(width(), height);
- }
-
- void setFixedWidth(int width) {
- q->setFixedWidth(width);
- }
-
- void setFixedHeight(int height) {
- q->setFixedHeight(height);
- }
-
- QPoint pos() const {
- return q->pos();
- }
-
- QSize size() const {
- return q->size();
- }
-
- QUrl styleSheetFile() const {
- return _styleSheetFile;
- }
-
- QColor windowColor() const
- { return q->palette().color(QPalette::Window); }
-
- void setWindowColor(const QColor &color)
- {
- QPalette pal = q->palette();
- pal.setColor(QPalette::Window, color);
- q->setPalette(pal);
- }
-
- QColor backgroundColor() const
- { return q->palette().color(QPalette::Background); }
-
- void setBackgroundColor(const QColor &color)
- {
- QPalette pal = q->palette();
- pal.setColor(QPalette::Background, color);
- q->setPalette(pal);
- }
-
- QColor baseColor() const
- { return q->palette().color(QPalette::Base); }
-
- void setBaseColor(const QColor &color)
- {
- QPalette pal = q->palette();
- pal.setColor(QPalette::Base, color);
- q->setPalette(pal);
- }
-
- QColor textColor() const
- { return q->palette().color(QPalette::Text); }
-
- void setTextColor(const QColor &color)
- {
- QPalette pal = q->palette();
- pal.setColor(QPalette::Text, color);
- q->setPalette(pal);
- }
-
- QColor windowTextColor() const
- { return q->palette().color(QPalette::WindowText); }
-
- void setWindowTextColor(const QColor &color)
- {
- QPalette pal = q->palette();
- pal.setColor(QPalette::WindowText, color);
- q->setPalette(pal);
- }
-
- QColor buttonTextColor() const
- { return q->palette().color(QPalette::ButtonText); }
-
- void setButtonTextColor(const QColor &color)
- {
- QPalette pal = q->palette();
- pal.setColor(QPalette::ButtonText, color);
- q->setPalette(pal);
- }
-
- QColor buttonColor() const
- { return q->palette().color(QPalette::Button); }
-
- void setButtonColor(const QColor &color)
- {
- QPalette pal = q->palette();
- pal.setColor(QPalette::Button, color);
- q->setPalette(pal);
- }
-
-
- void setStyleSheetFile(const QUrl &url) {
- _styleSheetFile = url;
- _styleSheetFile.setScheme("file"); //### todo
- QString fileName;
- if (!QFileInfo(_styleSheetFile.toLocalFile()).exists())
- fileName = (QLatin1Char(':') + _styleSheetFile.toLocalFile().split(QLatin1Char(':')).last()); //try if it is a resource
- else
- fileName = (_styleSheetFile.toLocalFile());
- Utils::FileReader reader;
- if (reader.fetch(fileName))
- q->setStyleSheet(QString::fromUtf8(reader.data()));
- else
- qWarning() << QString::fromUtf8("setStyleSheetFile: %1").arg(reader.errorString());
-
- }
-
- QDeclarativeListProperty<Action> actions() {
- return QDeclarativeListProperty<Action>(this, 0, actions_append, actions_count, actions_at, actions_clear);
- }
-
-private:
- QWidget *q;
- QLayoutObject *_layout;
- QFont _font;
- QUrl _styleSheetFile;
- QGraphicsOpacityEffect *_graphicsOpacityEffect;
- bool m_mouseOver;
-
- static void children_append(QDeclarativeListProperty<QObject> *property, QObject *o) {
- QWidgetDeclarativeUI *p = static_cast<QWidgetDeclarativeUI *>(property->object);
- QWidget *q = p->q;
- if (QWidget *w = qobject_cast<QWidget *>(o))
- w->setParent(static_cast<QWidget *>(q));
- else
- o->setParent(q);
- }
-
- static int children_count(QDeclarativeListProperty<QObject> *property) {
- QWidgetDeclarativeUI *p = static_cast<QWidgetDeclarativeUI *>(property->object);
- QWidget *q = p->q;
- return q->children().count();
- }
-
- static QObject * children_at(QDeclarativeListProperty<QObject> *property, int index) {
- QWidgetDeclarativeUI *p = static_cast<QWidgetDeclarativeUI *>(property->object);
- QWidget *q = p->q;
- return q->children().at(index);
- }
-
- static void children_clear(QDeclarativeListProperty<QObject> *property) {
- QWidgetDeclarativeUI *p = static_cast<QWidgetDeclarativeUI *>(property->object);
- QWidget *q = p->q;
- QObjectList c = q->children();
- for (int i = 0; i < c.count(); ++i)
- c.at(i)->setParent(0);
- }
-
- // ### Original had an insert, and removeAt
- static void actions_append(QDeclarativeListProperty<Action> *property, Action *o) {
- QWidgetDeclarativeUI *p = static_cast<QWidgetDeclarativeUI *>(property->object);
- QWidget *w = p->q;
- o->setParent(w);
- w->addAction(o);
- }
-
- static int actions_count(QDeclarativeListProperty<Action> *property) {
- QWidgetDeclarativeUI *p = static_cast<QWidgetDeclarativeUI *>(property->object);
- QWidget *w = p->q;
- return w->actions().count();
- }
- static Action *actions_at(QDeclarativeListProperty<Action> *property, int index) {
- QWidgetDeclarativeUI *p = static_cast<QWidgetDeclarativeUI *>(property->object);
- QWidget *w = p->q;
- return qobject_cast<Action *>(w->actions().at(index));
- }
-
- static void actions_clear(QDeclarativeListProperty<Action> *property) {
- QWidgetDeclarativeUI *p = static_cast<QWidgetDeclarativeUI *>(property->object);
- QWidget *w = p->q;
-
- while (!w->actions().empty())
- w->removeAction(w->actions().first());
- }
-};
-
-bool ResizeEventFilter::eventFilter(QObject *obj, QEvent *event)
-{
- if (event->type() == QEvent::Resize) {
- if (obj
- && obj->isWidgetType()
- && obj == m_target) {
- m_dui_target->emitResize();
- return QObject::eventFilter(obj, event);
- }
- } else if (event->type() == QEvent::Move) {
- if (obj
- && obj->isWidgetType()
- && obj == m_target) {
- m_dui_target->emitMove();
- return QObject::eventFilter(obj, event);
- }
- } else if ((event->type() == QEvent::FocusIn) || (event->type() == QEvent::FocusOut)) {
- if (obj
- && obj->isWidgetType()
- && obj == m_target) {
- m_dui_target->emitFocusChanged();
- return QObject::eventFilter(obj, event);
- }
- } else if ((event->type() == QEvent::Enter) || (event->type() == QEvent::Leave)) {
- if (obj
- && obj->isWidgetType()
- && obj == m_target) {
- m_dui_target->setMouseOver(event->type() == QEvent::Enter);
- m_dui_target->emitMouseOverChanged();
- return QObject::eventFilter(obj, event);
- }
- } else if ((event->type() == QEvent::Show) || (event->type() == QEvent::Hide)) {
- if (obj
- && obj->isWidgetType()
- && obj == m_target) {
- m_dui_target->emitVisibleChanged();
- return QObject::eventFilter(obj, event);
- }
- } else if (event->type() == QEvent::EnabledChange) {
- if (obj
- && obj->isWidgetType()
- && obj == m_target) {
- m_dui_target->emitEnabledChanged();
- return QObject::eventFilter(obj,event);
- }
- }
- return QObject::eventFilter(obj, event);
-}
-
-
-class QTabObject : public QObject
-{
- Q_OBJECT
-
- Q_PROPERTY(QWidget *content READ content WRITE setContent)
- Q_PROPERTY(QString label READ label WRITE setLabel)
- Q_PROPERTY(QIcon icon READ icon WRITE setIcon)
- Q_CLASSINFO("DefaultProperty", "content")
-public:
- QTabObject(QObject *parent = 0) : QObject(parent), _content(0) {}
-
- QWidget *content() const { return _content; }
- void setContent(QWidget *content)
- {
- _content = content;
- }
-
- QString label() const { return _label; }
- void setLabel(const QString &label)
- {
- _label = label;
- }
-
- QIcon icon() const { return _icon; }
- void setIcon(const QIcon &icon)
- {
- _icon = icon;
- }
-
-private:
- QWidget *_content;
- QString _label;
- QIcon _icon;
-};
-
-class QPushButtonDeclarativeUI : public QObject
-{
- Q_OBJECT
-
- Q_PROPERTY(QUrl iconFromFile READ iconFromFile WRITE setIconFromFile)
-public:
- QPushButtonDeclarativeUI(QObject *parent = 0) : QObject(parent)
- {
- pb = qobject_cast<QPushButton*>(parent);
- }
-private:
- QUrl iconFromFile() const
- {
- return _url;
- }
-
- void setIconFromFile(const QUrl &url) {
- _url = url;
-
- QString path;
- if (_url.scheme() == QLatin1String("qrc"))
- path = QLatin1Char(':') + _url.path();
- else
- path = _url.toLocalFile();
-
- QFile file(path);
- if (file.open(QIODevice::ReadOnly)) {
- QPixmap pixmap(path);
- if (pixmap.isNull())
- qWarning() << "setIconFromFile: failed to load" << path;
- pb->setIcon(pixmap);
- } else {
- qWarning() << QString::fromUtf8("setIconFromFile: %1: %2").arg(path, file.errorString());
- }
-
- }
-
- QPushButton *pb;
- QUrl _url;
-};
-
-class ElidingLabel : public QLabel
-{
- Q_OBJECT
-public:
- ElidingLabel(QWidget * parent = 0) : QLabel(parent) {}
-
-protected:
- void paintEvent(QPaintEvent *event)
- {
- QFontMetrics fm(font());
- if (fm.width(text()) > (contentsRect().width() - 8) && text().length() > 4) {
- QPainter p(this);
- 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);
- }
- else
- QLabel::paintEvent(event);
- }
-
-};
-
-
-class QLabelDeclarativeUI : public QObject
-{
- Q_OBJECT
-
- Q_PROPERTY(QUrl iconFromFile READ iconFromFile WRITE setIconFromFile)
-public:
- QLabelDeclarativeUI(QObject *parent = 0) : QObject(parent)
- {
- lb = qobject_cast<ElidingLabel*>(parent);
- }
-private:
- QUrl iconFromFile() const
- {
- return _url;
- }
-
- void setIconFromFile(const QUrl &url) {
- _url = url;
-
- QString path;
- if (_url.scheme() == QLatin1String("qrc"))
- path = QLatin1Char(':') + _url.path();
- else
- path = _url.toLocalFile();
-
- QFile file(path);
- if (file.open(QIODevice::ReadOnly)) {
- QPixmap pixmap(path);
- if (pixmap.isNull())
- qWarning() << "setIconFromFile: failed to load" << path;
- lb->setPixmap(pixmap);
- } else {
- qWarning() << QString::fromUtf8("setIconFromFile: %1: %2").arg(path, file.errorString());
- }
-
- }
-
- ElidingLabel *lb;
- QUrl _url;
-};
-
-class QMenuDeclarativeUI : public QObject
-{
- Q_OBJECT
-
- Q_CLASSINFO("DefaultProperty", "actions")
-
-public:
- QMenuDeclarativeUI(QObject *parent = 0) : QObject(parent)
- {
- menu = qobject_cast<QMenu*>(parent);
- }
-
-private:
- //if not for the at() function, we could use QDeclarativeList instead
-
- QMenu *menu;
-
-};
-
-class QToolButtonDeclarativeUI : public QObject
-{
- Q_OBJECT
-
- Q_PROPERTY(QUrl iconFromFile READ iconFromFile WRITE setIconFromFile)
- Q_PROPERTY(QMenu *menu READ menu WRITE setMenu)
-
-public:
- QToolButtonDeclarativeUI(QObject *parent = 0) : QObject(parent)
- {
- pb = qobject_cast<QToolButton*>(parent);
- }
-private:
-
- QMenu *menu() const { return pb->menu(); }
- void setMenu(QMenu *menu)
- {
- menu->setParent(0);
- pb->setMenu(menu);
- menu->setParent(QApplication::topLevelWidgets().first());
- }
-
- QUrl iconFromFile() const
- {
- return _url;
- }
-
- void setIconFromFile(const QUrl &url) {
- _url = url;
-
- QString path;
- if (_url.scheme() == QLatin1String("qrc"))
- path = QLatin1Char(':') + _url.path();
- else
- path = _url.toLocalFile();
-
- QFile file(path);
- if (file.open(QIODevice::ReadOnly)) {
- QPixmap pixmap(path);
- if (pixmap.isNull())
- qWarning() << "setIconFromFile: failed to load" << path;
- pb->setIcon(pixmap);
- } else {
- qWarning() << QString::fromUtf8("setIconFromFile: %1: %2").arg(path, file.errorString());
- }
-
- }
-
- QToolButton *pb;
- QUrl _url;
-};
-
-class AnimatedToolButton : public QToolButton
-{
-
-Q_OBJECT
-
- Q_PROPERTY(QUrl hoverIconFromFile READ hoverIconFromFile WRITE setHoverIconFromFile)
-
-public:
- AnimatedToolButton( QWidget * parent = 0 ) : QToolButton(parent)
- {}
-
-private:
- QUrl hoverIconFromFile() const
- { return m_hoverIconUrl; }
-
- void setHoverIconFromFile(const QUrl &url)
- { m_hoverIconUrl= url;
- m_hoverIcon = QIcon(m_hoverIconUrl.toLocalFile());
- }
-
- void leaveEvent(QEvent *)
- {
- setIcon(m_icon);
- }
-
- void enterEvent(QEvent *)
- {
- m_icon = icon();
- setIcon(m_hoverIcon);
- }
-
- QUrl m_hoverIconUrl;
- QIcon m_hoverIcon;
- QIcon m_icon;
-
-};
-
-class QComboBoxDeclarativeUI : public QObject
-{
- Q_OBJECT
- Q_PROPERTY(QStringList items READ items WRITE setItems)
- Q_PROPERTY(QString currentText READ currentText WRITE setCurrentText NOTIFY currentTextChanged)
-
-public:
- QComboBoxDeclarativeUI(QObject *parent = 0) : QObject(parent), m_itemsSet(false)
- {
- cb = qobject_cast<QComboBox*>(parent);
- connect(cb, SIGNAL(currentIndexChanged(QString)), this, SLOT(setCurrentText(QString)));
- }
-
- QString currentText() const
- {
- return cb->currentText();
- }
-
-public slots:
- void setCurrentText(const QString &text)
- {
- if (!m_itemsSet)
- return;
- int i = cb->findText(text);
- if (i != -1) {
- cb->setCurrentIndex(i);
- emit currentTextChanged();
- }
- }
-public slots:
- void setCurrentTextSilent(const QString &text)
- {
- if (!m_itemsSet)
- return;
- int i = cb->findText(text);
- if (i != -1) {
- blockSignals(true);
- cb->setCurrentIndex(i);
- blockSignals(false);
- }
- }
-signals:
- void currentTextChanged();
- void itemsChanged();
-
-private:
- void setItems(const QStringList &list)
- {
- _items = list;
- cb->clear();
- blockSignals(true);
- cb->addItems(list);
- m_itemsSet = true;
- blockSignals(false);
- emit itemsChanged();
- }
-
- QStringList items() const
- {
- return _items;
- }
-
- QComboBox *cb;
- QStringList _items;
-
- bool m_itemsSet;
-};
-
-class QScrollAreaDeclarativeUI : public QObject
-{
- Q_OBJECT
- Q_PROPERTY(QWidget *content READ content WRITE setContent)
- Q_CLASSINFO("DefaultProperty", "content")
-
-public:
- QScrollAreaDeclarativeUI(QObject *parent = 0) : QObject(parent), _content(0)
- {
- sa = qobject_cast<QScrollArea*>(parent);
- }
-
-private:
- QWidget *content() const { return _content; }
- void setContent(QWidget *content)
- {
- _content = content;
- sa->setWidget(content);
- sa->verticalScrollBar()->show();
- }
-
- QWidget *_content;
- QScrollArea *sa;
-};
-
-
-class WidgetLoader : public QWidget
-{
- Q_OBJECT
- Q_PROPERTY(QString sourceString READ sourceString WRITE setSourceString NOTIFY sourceChanged)
- Q_PROPERTY(QUrl source READ source WRITE setSource NOTIFY sourceChanged)
- Q_PROPERTY(QUrl baseUrl READ baseUrl WRITE setBaseUrl)
- Q_PROPERTY(QString qmlData READ qmlData WRITE setQmlData NOTIFY qmlDataChanged)
- Q_PROPERTY(QWidget *widget READ widget NOTIFY widgetChanged)
- Q_PROPERTY(QDeclarativeComponent *component READ component NOTIFY sourceChanged)
-
-public:
- WidgetLoader(QWidget * parent = 0) : QWidget(parent), m_source(QUrl()), m_widget(0),
- m_component(0), m_layout(0)
- {
- m_layout = new QVBoxLayout(this);
- m_layout->setContentsMargins(0,0,0,0);
- }
-
- QUrl source() const;
- void setSource(const QUrl &);
- QString qmlData() const;
- void setQmlData(const QString &data);
-
- QString sourceString() const
- { return m_source.toString(); }
- void setSourceString(const QString &url)
- { setSource(QUrl(url)); }
-
- QWidget *widget() const;
- QDeclarativeComponent *component() const
- { return m_component; }
-
- void setBaseUrl(const QUrl &baseUrl);
-
- QUrl baseUrl() const;
-
-signals:
- void widgetChanged();
- void sourceChanged();
- void qmlDataChanged();
-
-private:
- QUrl m_source;
- QUrl m_baseUrl;
- QString m_qmlData;
- QWidget *m_widget;
- QDeclarativeComponent *m_component;
- QVBoxLayout *m_layout;
- QHash<QString, QWidget*> m_cachedWidgets;
-};
-
-QUrl WidgetLoader::source() const
-{
- return m_source;
-}
-
-QUrl WidgetLoader::baseUrl() const
-{
- return m_baseUrl;
-}
-
-void WidgetLoader::setBaseUrl(const QUrl &baseUrl)
-{
- if (m_baseUrl == baseUrl)
- return;
- m_baseUrl = baseUrl;
-}
-
-QString WidgetLoader::qmlData() const
-{
- return m_qmlData;
-}
-
-void WidgetLoader::setQmlData(const QString &data)
-{
- if (m_qmlData == data)
- return;
-
- m_qmlData = data;
-
- setSource(QUrl());
-
- foreach (QWidget *cachedWidget, m_cachedWidgets)
- cachedWidget->hide();
-
- if (m_qmlData.isEmpty()) {
- emit sourceChanged();
- emit widgetChanged();
- return;
- }
-
- if (m_component) {
- delete m_component;
- m_component = 0;
- }
-
- QString stringHash = QString::number(qHash(data));
-
- if (m_cachedWidgets.contains(stringHash)) {
- m_widget = m_cachedWidgets.value(stringHash);
- m_widget->show();
- } else {
- m_component = new QDeclarativeComponent(qmlEngine(this), this);
- m_component->setData (m_qmlData.toUtf8(), m_baseUrl);
- if (m_component) {
- emit sourceChanged();
- emit widgetChanged();
-
- while (m_component->isLoading())
- QApplication::processEvents();
-
- if (!m_component->isReady()) {
- if (!m_component->errors().isEmpty())
- qWarning() << m_component->errors();
- emit sourceChanged();
- return;
- }
-
- QDeclarativeContext *ctxt = new QDeclarativeContext(qmlContext(this));
- ctxt->setContextObject(this);
- QObject *obj = m_component->create(ctxt);
- if (obj) {
- QWidget *widget = qobject_cast<QWidget *>(obj);
- if (widget) {
- m_cachedWidgets.insert(stringHash, widget);
- m_widget = widget;
- m_layout->addWidget(m_widget);
- m_widget->show();
- }
- }
- }
- }
-
-}
-
-void WidgetLoader::setSource(const QUrl &source)
-{
- if (m_source == source)
- return;
-
- setQmlData("");
-
-// QWidget *oldWidget = m_widget;
-
- if (m_widget) {
- //m_widget->deleteLater();
- m_widget->hide();
- m_widget = 0;
- }
-
- foreach (QWidget *cachedWidget, m_cachedWidgets)
- cachedWidget->hide();
-
- m_source = source;
- if (m_source.isEmpty()) {
- emit sourceChanged();
- emit widgetChanged();
- return;
- }
-
- if (m_component) {
- delete m_component;
- m_component = 0;
- }
-
- if (m_cachedWidgets.contains(source.toString())) {
- m_widget = m_cachedWidgets.value(source.toString());
- m_widget->show();
- } else {
- m_component = new QDeclarativeComponent(qmlEngine(this), m_source, this);
-
- if (m_component) {
- emit sourceChanged();
- emit widgetChanged();
-
- while (m_component->isLoading())
- QApplication::processEvents();
-
- if (!m_component->isReady()) {
- if (!m_component->errors().isEmpty())
- qWarning() << m_component->errors();
- emit sourceChanged();
- return;
- }
-
- QDeclarativeContext *ctxt = new QDeclarativeContext(qmlContext(this));
- ctxt->setContextObject(this);
- QObject *obj = m_component->create(ctxt);
- if (obj) {
- QWidget *widget = qobject_cast<QWidget *>(obj);
- if (widget) {
- m_cachedWidgets.insert(source.toString(), widget);
- m_widget = widget;
- m_layout->addWidget(m_widget);
- m_widget->show();
- }
- }
- }
- }
-}
-
-QWidget *WidgetLoader::widget() const
-{
- return m_widget;
-}
-
-class MyGroupBox : public QGroupBox
-{
- Q_OBJECT
-
- Q_PROPERTY(bool animated READ isAnimated)
-
-public:
- MyGroupBox(QWidget * parent = 0) : QGroupBox(parent), m_animated(false), m_firstExpand(true)
- {}
-
-void setPixmap(const QPixmap &pixmap, qreal alpha = 1)
-{ m_pixmap = pixmap; m_alpha = alpha;}
-
-void setAnimated(bool animated)
-{ m_animated = animated; }
-
-void finishFirstExpand()
-{ m_firstExpand = false; }
-
-bool isAnimated()
-{ return m_animated; }
-
-public slots:
- virtual void setVisible ( bool visible );
-
-protected:
- virtual void paintEvent(QPaintEvent * event);
-private:
- qreal m_alpha;
- QPixmap m_pixmap;
- bool m_animated;
- bool m_firstExpand;
-};
-
-void MyGroupBox::paintEvent(QPaintEvent * event)
-{
- QGroupBox::paintEvent(event);
- if (m_animated) {
- QPainter p(this);
- if (!m_pixmap.isNull() && !m_firstExpand) {
- p.setOpacity(m_alpha);
- p.drawPixmap(5, 5, m_pixmap.width(), m_pixmap.height(), m_pixmap);
- }
- }
-}
-
-void MyGroupBox::setVisible ( bool visible )
-{
- if (parentWidget())
- QGroupBox::setVisible(visible);
-}
-
-class QGroupBoxDeclarativeUI : public QObject
-{
- Q_OBJECT
-
- Q_PROPERTY(bool collapsed READ isCollapsed WRITE setCollapsed)
- Q_PROPERTY(bool smooth READ isSmooth WRITE setSmooth)
-public:
- QGroupBoxDeclarativeUI(QObject *parent = 0) : QObject(parent), m_expanded(true)
- {
- gb = qobject_cast<MyGroupBox*>(parent);
- connect(&m_timeLine, SIGNAL (frameChanged(int)), this, SLOT(animate(int)));
- connect(&m_timeLine, SIGNAL(finished()), this, SLOT(finish()));
-
- m_timeLine.setDuration(100);
- m_timeLine.setFrameRange(0, 5);
- m_smooth = true;
- }
-
- bool isCollapsed()
- { return ! m_expanded; }
-
- void setCollapsed(bool collapsed)
- {
- if (collapsed)
- collapse();
- else
- expand();
- }
-
- bool isSmooth()
- { return m_smooth; }
- void setSmooth(bool smooth)
- { m_smooth = smooth; }
-
-public slots:
- void collapse();
- void expand();
-
- void animate(int frame);
- void finish();
-
-private:
- MyGroupBox *gb;
- QTimeLine m_timeLine;
- bool m_expanded;
- int m_oldHeight;
- int m_oldMAxHeight;
- int m_oldMinHeight;
- QPixmap m_contens;
- bool m_smooth;
-
- void hideChildren();
- void showChildren();
-
- void reLayout();
-};
-
-void QGroupBoxDeclarativeUI::reLayout()
-{
- gb->setUpdatesEnabled(false);
- QLayout *layout = gb->parentWidget()->layout();
- QPoint oldPos = gb->pos();
- if (layout) {
- layout->invalidate();
- layout->activate();
- }
- gb->move(oldPos);
- gb->setUpdatesEnabled(true);
- gb->update();
-}
-
-void QGroupBoxDeclarativeUI::finish()
-{
- if (m_expanded) {
- showChildren();
- gb->setUpdatesEnabled(false);
- gb->setMinimumHeight(m_oldMinHeight);
- gb->setMaximumHeight(m_oldMAxHeight);
- gb->setUpdatesEnabled(true);
- //gb->resize(gb->sizeHint());
- gb->finishFirstExpand();
- }
- else {
- gb->setMinimumHeight(30);
- gb->setMaximumHeight(30);
- gb->resize(gb->sizeHint().width(), 30);
- }
- reLayout();
- gb->setAnimated(false);
-}
-
-void QGroupBoxDeclarativeUI::hideChildren()
-{
- if (gb->isVisible()) {
- gb->setMinimumHeight(gb->height());
- foreach (QWidget *widget, gb->findChildren<QWidget*>())
- if (widget->parent() == gb) {
- widget->setProperty("wasVisibleGB", widget->property("visible"));
- widget->hide();
- }
- }
-}
-
-void QGroupBoxDeclarativeUI::showChildren()
-{
- foreach (QWidget *widget, gb->findChildren<QWidget*>()) {
- if (widget->parent() == gb) {
- if (widget->property("wasVisibleGB").toBool())
- widget->show();
- widget->setProperty("wasVisibleGB", QVariant());
- widget->ensurePolished();
- }
- }
- gb->show();
-}
-
-void QGroupBoxDeclarativeUI::collapse()
-{
- m_oldMAxHeight = gb->maximumHeight();
- m_oldHeight = gb->height();
- m_oldMinHeight =gb->minimumHeight();
- if (!m_expanded)
- return;
-
-#if QT_VERSION < 0x050000
- m_contens = QPixmap::grabWidget(gb, 5, 5, gb->width() - 5, gb->height() - 5);
-#else
- m_contens = gb->grab(QRect(5, 5, gb->width() - 5, gb->height() - 5));
-#endif
- gb->setPixmap(m_contens,1);
- hideChildren();
- m_expanded = false;
- gb->setAnimated(true);
- m_timeLine.start();
-}
-
-void QGroupBoxDeclarativeUI::expand()
-{
- if (m_expanded)
- return;
- m_expanded = true;
- gb->setAnimated(true);
- m_timeLine.start();
-}
-
-void QGroupBoxDeclarativeUI::animate(int frame)
-{
- if (!m_smooth)
- return;
- qreal height;
-
- if (m_expanded) {
- height = ((qreal(frame) / 5.0) * qreal(m_oldHeight)) + (30.0 * (1.0 - qreal(frame) / 5.0));
- gb->setPixmap(m_contens, qreal(frame) / 5.0);
- }
- else {
- height = ((qreal(frame) / 5.0) * 30.0) + (qreal(m_oldHeight) * (1.0 - qreal(frame) / 5.0));
- qreal alpha = 0.8 - qreal(frame) / 4.0;
- if (alpha < 0)
- alpha = 0;
- gb->setPixmap(m_contens, alpha);
- }
-
- gb->setMaximumHeight(height);
- gb->setMinimumHeight(height);
- reLayout();
-}
-
-class QTabWidgetDeclarativeUI : public QObject
-{
- Q_OBJECT
-
- Q_PROPERTY(QDeclarativeListProperty<QTabObject> tabs READ tabs)
- Q_CLASSINFO("DefaultProperty", "tabs")
-public:
- QTabWidgetDeclarativeUI(QObject *other) : QObject(other) {}
-
- QDeclarativeListProperty<QTabObject> tabs() {
- return QDeclarativeListProperty<QTabObject>(this, 0, tabs_append, 0, 0, tabs_clear);
- }
-
-private:
- static void tabs_append(QDeclarativeListProperty<QTabObject> *property, QTabObject *o) {
- QTabWidget *tw = static_cast<QTabWidget*>(property->object->parent());
- if (!o->icon().isNull())
- tw->addTab(o->content(), o->icon(), o->label());
- else
- tw->addTab(o->content(), o->label());
- }
-
- static void tabs_clear(QDeclarativeListProperty<QTabObject> *property) {
- QTabWidget *tw = static_cast<QTabWidget*>(property->object->parent());
- tw->clear();
- }
-};
-
-class ExpressionEdit : public QPlainTextEdit
-{
- Q_OBJECT
-public:
- ExpressionEdit(QWidget *parent = 0) : QPlainTextEdit(parent) {}
-signals:
- void returnPressed();
-
-protected:
- void keyPressEvent( QKeyEvent * e );
-};
-
-void ExpressionEdit::keyPressEvent(QKeyEvent * e)
-{
- if ((e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return) && (e->modifiers() == Qt::NoModifier))
- emit returnPressed();
- else
- QPlainTextEdit::keyPressEvent(e);
-}
-
-
-class WidgetFrame : public QFrame
-{
- Q_OBJECT
-public:
- WidgetFrame( QWidget * parent = 0, Qt::WindowFlags f = 0 ) : QFrame(parent, f)
- {}
-};
-
-QT_END_NAMESPACE
-
-QML_DECLARE_TYPE(QTabObject)
-QML_DECLARE_TYPE(MyGroupBox)
-QML_DECLARE_TYPE(WidgetLoader)
-QML_DECLARE_TYPE(WidgetFrame)
-QML_DECLARE_TYPE(AnimatedToolButton)
-
-void BasicWidgets::registerDeclarativeTypes()
-{
- qmlRegisterExtendedType<QWidget,QWidgetDeclarativeUI>("Bauhaus",1,0,"QWidget");
-
- //display
- qmlRegisterType<QProgressBar>("Bauhaus",1,0,"QProgressBar");
- qmlRegisterType<QLCDNumber>("Bauhaus",1,0,"QLCDNumber");
-
- //input
- qmlRegisterType<QLineEdit>("Bauhaus",1,0,"QLineEdit");
- qmlRegisterType<QTextEdit>("Bauhaus",1,0,"QTextEdit");
- qmlRegisterType<ExpressionEdit>("Bauhaus",1,0,"ExpressionEdit");
- qmlRegisterType<QPlainTextEdit>("Bauhaus",1,0,"QPlainTextEdit");
- qmlRegisterType<QSpinBox>("Bauhaus",1,0,"QSpinBox");
- qmlRegisterType<QDoubleSpinBox>("Bauhaus",1,0,"QDoubleSpinBox");
- qmlRegisterType<QSlider>("Bauhaus",1,0,"QSlider");
- qmlRegisterType<QDateTimeEdit>("Bauhaus",1,0,"QDateTimeEdit");
- qmlRegisterType<QDateEdit>("Bauhaus",1,0,"QDateEdit");
- qmlRegisterType<QTimeEdit>("Bauhaus",1,0,"QTimeEdit");
- qmlRegisterType<QFontComboBox>("Bauhaus",1,0,"QFontComboBox");
- qmlRegisterType<QDial>("Bauhaus",1,0,"QDial");
- qmlRegisterType<QScrollBar>("Bauhaus",1,0,"QScrollBar");
- qmlRegisterType<QCalendarWidget>("Bauhaus",1,0,"QCalendarWidget");
-
-
- //qmlRegisterType<>("Bauhaus",1,0,QComboBox,QComboBox); //need a way to populate
- //QML_REGISTER_EXTENDED_TYPE(QComboBox,QComboBox, QComboBox); //need a way to populate
-
- //buttons
- //qmlRegisterType<>("Bauhaus",1,0,QPushButton,QPushButton);
- qmlRegisterType<QCheckBox>("Bauhaus",1,0,"QCheckBox");
- qmlRegisterType<QGroupBox>("Bauhaus",1,0,"QGroupBox");
- qmlRegisterType<Action>("Bauhaus",1,0,"QAction");
- qmlRegisterType<QRadioButton>("Bauhaus",1,0,"QRadioButton");
- qmlRegisterType<FileWidget>("Bauhaus",1,0,"FileWidget");
- qmlRegisterType<LayoutWidget>("Bauhaus",1,0,"LayoutWidget");
-
- //containers
- qmlRegisterType<QFrame>("Bauhaus",1,0,"QFrame");
- qmlRegisterType<WidgetFrame>("Bauhaus",1,0,"WidgetFrame");
- qmlRegisterType<WidgetLoader>("Bauhaus",1,0,"WidgetLoader");
- qmlRegisterType<AnimatedToolButton>("Bauhaus",1,0,"AnimatedToolButton");
- qmlRegisterExtendedType<MyGroupBox,QGroupBoxDeclarativeUI>("Bauhaus",1,0,"QExtGroupBox");
- qmlRegisterExtendedType<QTabWidget,QTabWidgetDeclarativeUI>("Bauhaus",1,0,"QTabWidget");
- qmlRegisterExtendedType<QScrollArea,QScrollAreaDeclarativeUI>("Bauhaus",1,0,"QScrollArea");
- qmlRegisterExtendedType<QPushButton,QPushButtonDeclarativeUI>("Bauhaus",1,0,"QPushButton");
- qmlRegisterExtendedType<ElidingLabel,QLabelDeclarativeUI>("Bauhaus",1,0,"QLabel");
- qmlRegisterExtendedType<QToolButton, QToolButtonDeclarativeUI>("Bauhaus",1,0,"QToolButton");
- qmlRegisterExtendedType<QComboBox, QComboBoxDeclarativeUI>("Bauhaus",1,0,"QComboBox");
- qmlRegisterExtendedType<QMenu, QMenuDeclarativeUI>("Bauhaus",1,0,"QMenu");
- //qmlRegisterType<>("Bauhaus",1,0,BauhausoolBox,BauhausoolBox);
- //qmlRegisterType<>("Bauhaus",1,0,QScrollArea,QScrollArea);
-
- //QML_REGISTER_EXTENDED_TYPE(BauhausColorButton,BauhausColorButton,BauhausColorButtonDeclarativeUI);
-
- //itemviews
- //qmlRegisterType<>("Bauhaus",1,0,QListView,QListView);
- //qmlRegisterType<>("Bauhaus",1,0,BauhausreeView,BauhausreeView);
- //qmlRegisterType<>("Bauhaus",1,0,BauhausableView,BauhausableView);
-
- qmlRegisterType<QTabObject>("Bauhaus",1,0,"QTabObject"); //### with namespacing, this should just be 'Tab'
-}
-
-#include "basicwidgets.moc"
diff --git a/src/plugins/qmldesigner/components/propertyeditor/basicwidgets.h b/src/plugins/qmldesigner/components/propertyeditor/basicwidgets.h
deleted file mode 100644
index b4454acf94..0000000000
--- a/src/plugins/qmldesigner/components/propertyeditor/basicwidgets.h
+++ /dev/null
@@ -1,120 +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 BASICWIDGETS_H
-#define BASICWIDGETS_H
-
-#include <qdeclarative.h>
-#include <QGraphicsView>
-#include <QLabel>
-#include <QPushButton>
-#include <QToolButton>
-#include <QCheckBox>
-#include <QRadioButton>
-#include <QLineEdit>
-#include <QTextEdit>
-#include <QPlainTextEdit>
-#include <QDoubleSpinBox>
-#include <QSlider>
-#include <QDateEdit>
-#include <QTimeEdit>
-#include <QProgressBar>
-#include <QGroupBox>
-#include <QDial>
-#include <QLCDNumber>
-#include <QFontComboBox>
-#include <QScrollBar>
-#include <QCalendarWidget>
-#include <QTabWidget>
-#include <QMenu>
-#include <QAction>
-#include "filewidget.h"
-#include "layoutwidget.h"
-
-QML_DECLARE_TYPE(QWidget)
-
-//display
-QML_DECLARE_TYPE(QLabel)
-QML_DECLARE_TYPE(QProgressBar)
-QML_DECLARE_TYPE(QLCDNumber)
-
-//input
-QML_DECLARE_TYPE(QLineEdit)
-QML_DECLARE_TYPE(QTextEdit)
-QML_DECLARE_TYPE(QPlainTextEdit)
-QML_DECLARE_TYPE(QSpinBox)
-QML_DECLARE_TYPE(QDoubleSpinBox)
-QML_DECLARE_TYPE(QSlider)
-QML_DECLARE_TYPE(QDateTimeEdit)
-QML_DECLARE_TYPE(QDateEdit)
-QML_DECLARE_TYPE(QTimeEdit)
-QML_DECLARE_TYPE(QFontComboBox)
-QML_DECLARE_TYPE(QDial)
-QML_DECLARE_TYPE(QScrollBar)
-QML_DECLARE_TYPE(QCalendarWidget)
-QML_DECLARE_TYPE(QComboBox)
-
-//buttons
-QML_DECLARE_TYPE(QPushButton)
-QML_DECLARE_TYPE(QToolButton)
-QML_DECLARE_TYPE(QCheckBox)
-QML_DECLARE_TYPE(QRadioButton)
-
-//containers
-QML_DECLARE_TYPE(QGroupBox)
-QML_DECLARE_TYPE(QFrame)
-QML_DECLARE_TYPE(QScrollArea)
-QML_DECLARE_TYPE(QTabWidget)
-QML_DECLARE_TYPE(FileWidget)
-QML_DECLARE_TYPE(LayoutWidget)
-
-
-class Action : public QAction {
- Q_OBJECT
-public:
- Action(QObject *parent = 0) : QAction(parent) {}
-};
-
-QML_DECLARE_TYPE(QMenu)
-QML_DECLARE_TYPE(Action)
-
-//QML_DECLARE_TYPE(QToolBox)
-
-//itemviews
-//QML_DECLARE_TYPE(QListView)
-//QML_DECLARE_TYPE(QTreeView)
-//QML_DECLARE_TYPE(QTableView)
-
-//top-level windows?
-class BasicWidgets {
-public:
- static void registerDeclarativeTypes();
-};
-
-#endif // BASICWIDGETS_H
diff --git a/src/plugins/qmldesigner/components/propertyeditor/behaviordialog.cpp b/src/plugins/qmldesigner/components/propertyeditor/behaviordialog.cpp
deleted file mode 100644
index b26f2e9bd9..0000000000
--- a/src/plugins/qmldesigner/components/propertyeditor/behaviordialog.cpp
+++ /dev/null
@@ -1,165 +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 "behaviordialog.h"
-
-#include <abstractview.h>
-#include <nodeproperty.h>
-#include <variantproperty.h>
-#include <bindingproperty.h>
-
-
-namespace QmlDesigner {
-
-void BehaviorDialog::registerDeclarativeType()
-{
- qmlRegisterType<QmlDesigner::BehaviorWidget>("Bauhaus",1,0,"BehaviorWidget");
-}
-
-BehaviorWidget::BehaviorWidget(QWidget *parent) : QPushButton(parent), m_BehaviorDialog(new BehaviorDialog)
-{
- setCheckable(true);
- connect(this, SIGNAL(toggled(bool)), this, SLOT(buttonPressed(bool)));
-}
-
-PropertyEditorNodeWrapper* BehaviorWidget::complexNode() const
-{
- return m_complexNode;
-}
-
-void BehaviorWidget::setComplexNode(PropertyEditorNodeWrapper* complexNode)
-{
- m_complexNode = complexNode;
- m_propertyName = complexNode->propertyName();
- m_modelNode = complexNode->parentModelNode();
-
- if (!modelNode().isValid())
- m_BehaviorDialog->hide();
-
- m_BehaviorDialog->setup(modelNode(), propertyName());
-}
-
-void BehaviorWidget::buttonPressed(bool show)
-{
- if (show) {
- if (m_BehaviorDialog->isVisible()) {
- m_BehaviorDialog->reject();
- } else {
- m_BehaviorDialog->setup(modelNode(), propertyName());
- m_BehaviorDialog->show();
- setChecked(false);
- }
- }
-}
-
-BehaviorDialog::BehaviorDialog(QWidget *parent) : QDialog(parent), m_ui(new Internal::Ui::BehaviorDialog)
-{
- m_ui->setupUi(this);
- setModal(true);
-}
-
- void BehaviorDialog::setup(const ModelNode &node, const PropertyName propertyName)
-{
- m_modelNode = node;
- m_ui->duration->setValue(100);
- m_ui->velocity->setValue(2);
- m_ui->spring->setValue(2);
- m_ui->damping->setValue(2);
- m_ui->stackedWidget->setCurrentIndex(0);
- m_ui->curve->setCurrentIndex(0);
-
- if (m_modelNode.isValid()) {
- m_propertyName = propertyName;
- m_ui->id->setText(m_modelNode.id());
- m_ui->type->setText(m_modelNode.simplifiedTypeName());
- m_ui->propertyName->setText(propertyName);
- if (m_modelNode.hasProperty(m_propertyName) && m_modelNode.property(m_propertyName).isNodeProperty()) {
- NodeProperty nodeProperty(m_modelNode.nodeProperty(m_propertyName));
- if (nodeProperty.modelNode().type() == "Qt/SpringFollow") {
- ModelNode springFollow = nodeProperty.modelNode();
- m_ui->curve->setCurrentIndex(1);
- m_ui->stackedWidget->setCurrentIndex(1);
- if (springFollow.hasProperty("velocity") && springFollow.property("velocity").isVariantProperty())
- m_ui->velocity->setValue(springFollow.variantProperty("velocity").value().toDouble());
- if (springFollow.hasProperty("spring") && springFollow.property("spring").isVariantProperty())
- m_ui->spring->setValue(springFollow.variantProperty("spring").value().toDouble());
- if (springFollow.hasProperty("damping") && springFollow.property("damping").isVariantProperty())
- m_ui->damping->setValue(springFollow.variantProperty("damping").value().toDouble());
- if (springFollow.hasProperty("source") && springFollow.property("source").isVariantProperty())
- m_ui->source->setText(springFollow.variantProperty("source").value().toString());
- } else if (nodeProperty.modelNode().type() == "Qt/Behavior") {
- if (nodeProperty.modelNode().hasProperty("animation") &&
- nodeProperty.modelNode().property("animation").isNodeProperty() &&
- nodeProperty.modelNode().nodeProperty("animation").modelNode().type() == "Qt/NumberAnimation") {
- m_ui->curve->setCurrentIndex(0);
- ModelNode animation = nodeProperty.modelNode().nodeProperty("animation").modelNode();
- if (animation.hasProperty("duration") && animation.property("duration").isVariantProperty())
- m_ui->duration->setValue(animation.variantProperty("duration").value().toInt());
- if (animation.hasProperty("easing") && animation.property("easing").isVariantProperty()) {
- QStringList easingItems;
- for (int i = 0; i < m_ui->curve->count(); i++)
- easingItems.append(m_ui->curve->itemText(i));
- m_ui->curve->setCurrentIndex(easingItems.indexOf(animation.variantProperty("easing").value().toString()));
- }
- }
- }
- }
- }
-}
-
-void BehaviorDialog::accept()
-{
- QDialog::accept();
- if (m_modelNode.hasProperty(m_propertyName))
- m_modelNode.removeProperty(m_propertyName);
- if (m_ui->comboBox->currentIndex() == 0) {
- RewriterTransaction transaction(m_modelNode.view()->beginRewriterTransaction());
- ModelNode Behavior = m_modelNode.view()->createModelNode("Qt/Behavior", 4, 7);
- m_modelNode.nodeProperty(m_propertyName).reparentHere(Behavior);
- ModelNode animation = m_modelNode.view()->createModelNode("Qt/NumberAnimation", 4, 7);
- animation.variantProperty("duration") = m_ui->duration->value();
- animation.variantProperty("easing") = m_ui->curve->currentText();
- Behavior.nodeProperty("animation").reparentHere(animation);
- } else {
- RewriterTransaction transaction(m_modelNode.view()->beginRewriterTransaction());
- ModelNode springFollow = m_modelNode.view()->createModelNode("Qt/SpringFollow", 4, 7);
- m_modelNode.nodeProperty(m_propertyName).reparentHere(springFollow);
- springFollow.variantProperty("velocity") = m_ui->velocity->value();
- springFollow.variantProperty("spring") = m_ui->spring->value();
- springFollow.variantProperty("damping") = m_ui->damping->value();
- springFollow.bindingProperty("source") = m_ui->source->text();
- }
-}
-
-void BehaviorDialog::reject()
-{
- QDialog::reject();
-}
-
-}
diff --git a/src/plugins/qmldesigner/components/propertyeditor/behaviordialog.h b/src/plugins/qmldesigner/components/propertyeditor/behaviordialog.h
deleted file mode 100644
index 26151d8f7e..0000000000
--- a/src/plugins/qmldesigner/components/propertyeditor/behaviordialog.h
+++ /dev/null
@@ -1,95 +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 BEHAVIORDIALOG_H
-#define BEHAVIORDIALOG_H
-
-#include <modelnode.h>
-#include <propertyeditorvalue.h>
-
-#include <QPushButton>
-#include <QDialog>
-#include <QScopedPointer>
-
-#include "ui_behaviordialog.h"
-
-namespace QmlDesigner {
-
-class BehaviorDialog;
-
-class BehaviorWidget : public QPushButton
-{
- Q_PROPERTY(PropertyEditorNodeWrapper* complexNode READ complexNode WRITE setComplexNode)
-
- Q_OBJECT
-
-public:
- explicit BehaviorWidget(QWidget *parent = 0);
-
- ModelNode modelNode() const {return m_modelNode; }
- PropertyName propertyName() const {return m_propertyName; }
-
- PropertyEditorNodeWrapper* complexNode() const;
- void setComplexNode(PropertyEditorNodeWrapper* complexNode);
-
-public slots:
- void buttonPressed(bool);
-
-private:
- ModelNode m_modelNode;
- PropertyName m_propertyName;
- PropertyEditorNodeWrapper* m_complexNode;
- QScopedPointer<BehaviorDialog> m_BehaviorDialog;
-};
-
-class BehaviorDialog : public QDialog
-{
- Q_OBJECT
-public:
- explicit BehaviorDialog(QWidget *parent = 0);
- void setup(const ModelNode &node, const PropertyName propertyName);
-
-public slots:
- virtual void accept();
- virtual void reject();
-
- static void registerDeclarativeType();
-
-private:
- ModelNode m_modelNode;
- PropertyName m_propertyName;
- QScopedPointer<Internal::Ui::BehaviorDialog> m_ui;
-};
-
-
-}
-
-QML_DECLARE_TYPE(QmlDesigner::BehaviorWidget)
-
-#endif// BEHAVIORDIALOG_H
diff --git a/src/plugins/qmldesigner/components/propertyeditor/behaviordialog.ui b/src/plugins/qmldesigner/components/propertyeditor/behaviordialog.ui
deleted file mode 100644
index 2d0d3257d2..0000000000
--- a/src/plugins/qmldesigner/components/propertyeditor/behaviordialog.ui
+++ /dev/null
@@ -1,472 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<ui version="4.0">
- <class>QmlDesigner::Internal::BehaviorDialog</class>
- <widget class="QDialog" name="QmlDesigner::Internal::BehaviorDialog">
- <property name="geometry">
- <rect>
- <x>0</x>
- <y>0</y>
- <width>269</width>
- <height>354</height>
- </rect>
- </property>
- <property name="sizePolicy">
- <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="windowTitle">
- <string>Dialog</string>
- </property>
- <property name="styleSheet">
- <string notr="true">QDialog {
-qlineargradient(spread:pad, x1:0.585, y1:0.0284091, x2:0.517, y2:1, stop:0 rgba(85, 85, 85, 255), stop:1 rgba(173, 173, 173, 255))
-}
-
-</string>
- </property>
- <layout class="QGridLayout" name="gridLayout">
- <item row="0" column="0">
- <widget class="QLabel" name="label">
- <property name="minimumSize">
- <size>
- <width>0</width>
- <height>0</height>
- </size>
- </property>
- <property name="font">
- <font>
- <weight>75</weight>
- <bold>true</bold>
- </font>
- </property>
- <property name="text">
- <string>Type:</string>
- </property>
- </widget>
- </item>
- <item row="0" column="1">
- <widget class="QLineEdit" name="type">
- <property name="readOnly">
- <bool>true</bool>
- </property>
- </widget>
- </item>
- <item row="1" column="0">
- <widget class="QLabel" name="label_3">
- <property name="font">
- <font>
- <weight>75</weight>
- <bold>true</bold>
- </font>
- </property>
- <property name="text">
- <string>ID:</string>
- </property>
- </widget>
- </item>
- <item row="1" column="1">
- <widget class="QLineEdit" name="id">
- <property name="readOnly">
- <bool>true</bool>
- </property>
- </widget>
- </item>
- <item row="2" column="0">
- <widget class="QLabel" name="label_5">
- <property name="font">
- <font>
- <weight>75</weight>
- <bold>true</bold>
- </font>
- </property>
- <property name="text">
- <string>Property name:</string>
- </property>
- </widget>
- </item>
- <item row="2" column="1">
- <widget class="QLineEdit" name="propertyName">
- <property name="readOnly">
- <bool>true</bool>
- </property>
- </widget>
- </item>
- <item row="3" column="0" colspan="2">
- <widget class="QComboBox" name="comboBox">
- <item>
- <property name="text">
- <string>Animation</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string>SpringFollow</string>
- </property>
- </item>
- </widget>
- </item>
- <item row="4" column="0" colspan="2">
- <widget class="QGroupBox" name="groupBox">
- <property name="minimumSize">
- <size>
- <width>0</width>
- <height>120</height>
- </size>
- </property>
- <property name="title">
- <string>Settings</string>
- </property>
- <layout class="QGridLayout" name="gridLayout_4">
- <item row="0" column="0">
- <widget class="QStackedWidget" name="stackedWidget">
- <property name="currentIndex">
- <number>0</number>
- </property>
- <widget class="QWidget" name="page">
- <layout class="QGridLayout" name="gridLayout_2">
- <item row="0" column="0">
- <widget class="QLabel" name="label_7">
- <property name="font">
- <font>
- <weight>75</weight>
- <bold>true</bold>
- </font>
- </property>
- <property name="text">
- <string>Duration:</string>
- </property>
- </widget>
- </item>
- <item row="0" column="1">
- <widget class="QSpinBox" name="duration">
- <property name="maximum">
- <number>10000</number>
- </property>
- <property name="singleStep">
- <number>10</number>
- </property>
- </widget>
- </item>
- <item row="1" column="0">
- <widget class="QLabel" name="label_8">
- <property name="font">
- <font>
- <weight>75</weight>
- <bold>true</bold>
- </font>
- </property>
- <property name="text">
- <string>Curve:</string>
- </property>
- </widget>
- </item>
- <item row="1" column="1">
- <widget class="QComboBox" name="curve">
- <item>
- <property name="text">
- <string>easeNone</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string notr="true">easeInQuad</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string notr="true">easeOutQuad</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string notr="true">easeInOutQuad</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string notr="true">easeOutInQuad</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string notr="true">easeInCubic</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string notr="true">easeOutCubic</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string notr="true">easeInOutCubic</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string notr="true">easeOutInCubic</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string notr="true">easeOutInBounce</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string notr="true">easeInOutBounce</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string notr="true">easeOutBounce</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string notr="true">easeInBounce</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string notr="true">easeOutInBack</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string notr="true">easeInOutBack</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string notr="true">easeOutBack</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string notr="true">easeInBack</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string notr="true">easeOutInElastic</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string notr="true">easeInOutElastic</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string notr="true">easeOutElastic</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string notr="true">easeInElastic</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string notr="true">easeOutInCirc</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string notr="true">easeInOutCirc</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string notr="true">easeOutCirc</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string notr="true">easeInCirc</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string notr="true">easeOutInExpo</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string notr="true">easeInOutExpo</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string notr="true">easeOutExpo</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string notr="true">easeInExpo</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string notr="true">easeOutInSine</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string notr="true">easeInOutSine</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string notr="true">easeOutSine</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string notr="true">easeInSine</string>
- </property>
- </item>
- </widget>
- </item>
- </layout>
- </widget>
- <widget class="QWidget" name="page_2">
- <layout class="QGridLayout" name="gridLayout_3">
- <item row="0" column="0">
- <widget class="QLabel" name="label_2">
- <property name="font">
- <font>
- <weight>75</weight>
- <bold>true</bold>
- </font>
- </property>
- <property name="text">
- <string>Source:</string>
- </property>
- </widget>
- </item>
- <item row="0" column="1">
- <widget class="QLineEdit" name="source"/>
- </item>
- <item row="1" column="0">
- <widget class="QLabel" name="label_9">
- <property name="font">
- <font>
- <weight>75</weight>
- <bold>true</bold>
- </font>
- </property>
- <property name="text">
- <string>Velocity:</string>
- </property>
- </widget>
- </item>
- <item row="1" column="1">
- <widget class="QDoubleSpinBox" name="velocity"/>
- </item>
- <item row="2" column="0">
- <widget class="QLabel" name="label_10">
- <property name="font">
- <font>
- <weight>75</weight>
- <bold>true</bold>
- </font>
- </property>
- <property name="text">
- <string>Spring:</string>
- </property>
- </widget>
- </item>
- <item row="2" column="1">
- <widget class="QDoubleSpinBox" name="spring"/>
- </item>
- <item row="3" column="0">
- <widget class="QLabel" name="label_11">
- <property name="font">
- <font>
- <weight>75</weight>
- <bold>true</bold>
- </font>
- </property>
- <property name="text">
- <string>Damping:</string>
- </property>
- </widget>
- </item>
- <item row="3" column="1">
- <widget class="QDoubleSpinBox" name="damping"/>
- </item>
- </layout>
- </widget>
- </widget>
- </item>
- </layout>
- </widget>
- </item>
- <item row="5" column="0" colspan="2">
- <widget class="QDialogButtonBox" name="ButtonGroup">
- <property name="orientation">
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="standardButtons">
- <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
- </property>
- </widget>
- </item>
- </layout>
- </widget>
- <resources/>
- <connections>
- <connection>
- <sender>ButtonGroup</sender>
- <signal>accepted()</signal>
- <receiver>QmlDesigner::Internal::BehaviorDialog</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>ButtonGroup</sender>
- <signal>rejected()</signal>
- <receiver>QmlDesigner::Internal::BehaviorDialog</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>
- <connection>
- <sender>comboBox</sender>
- <signal>currentIndexChanged(int)</signal>
- <receiver>stackedWidget</receiver>
- <slot>setCurrentIndex(int)</slot>
- <hints>
- <hint type="sourcelabel">
- <x>52</x>
- <y>106</y>
- </hint>
- <hint type="destinationlabel">
- <x>121</x>
- <y>191</y>
- </hint>
- </hints>
- </connection>
- </connections>
-</ui>
diff --git a/src/plugins/qmldesigner/components/propertyeditor/declarativewidgetview.cpp b/src/plugins/qmldesigner/components/propertyeditor/declarativewidgetview.cpp
deleted file mode 100644
index 9db2ce5ac6..0000000000
--- a/src/plugins/qmldesigner/components/propertyeditor/declarativewidgetview.cpp
+++ /dev/null
@@ -1,144 +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 "declarativewidgetview.h"
-
-#include <QDeclarativeItem>
-#include <QDeclarativeEngine>
-#include <QDeclarativeContext>
-
-namespace QmlDesigner {
-
-void DeclarativeWidgetView::execute()
-{
- 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)
-{
-}
-
-QUrl DeclarativeWidgetView::source() const
-{
- return m_source;
-}
-
-void DeclarativeWidgetView::setSource(const QUrl& url)
-{
- m_source = url;
- execute();
-}
-
-QDeclarativeEngine* DeclarativeWidgetView::engine()
-{
- return &m_engine;
-}
-
-QWidget *DeclarativeWidgetView::rootWidget() const
-{
- return m_root.data();
-}
-
-QDeclarativeContext* DeclarativeWidgetView::rootContext()
-{
- return m_engine.rootContext();
-}
-
-DeclarativeWidgetView::Status DeclarativeWidgetView::status() const
-{
- if (!m_component)
- return DeclarativeWidgetView::Null;
-
- return DeclarativeWidgetView::Status(m_component->status());
-}
-
-
-void DeclarativeWidgetView::continueExecute()
-{
-
- disconnect(m_component.data(), SIGNAL(statusChanged(QDeclarativeComponent::Status)), this, SLOT(continueExecute()));
-
- if (m_component->isError()) {
- QList<QDeclarativeError> errorList = m_component->errors();
- foreach (const QDeclarativeError &error, errorList) {
- qWarning() << error;
- }
- emit statusChanged(status());
- return;
- }
-
- QObject *obj = m_component->create();
-
- if (m_component->isError()) {
- QList<QDeclarativeError> errorList = m_component->errors();
- foreach (const QDeclarativeError &error, errorList) {
- qWarning() << error;
- }
- emit statusChanged(status());
- return;
- }
-
- setRootWidget(qobject_cast<QWidget *>(obj));
- emit statusChanged(status());
-}
-
-void DeclarativeWidgetView::setRootWidget(QWidget *widget)
-{
- if (m_root.data() == widget)
- return;
-
- window()->setAttribute(Qt::WA_OpaquePaintEvent, false);
- window()->setAttribute(Qt::WA_NoSystemBackground, false);
- widget->setParent(this);
- if (isVisible())
- widget->setVisible(true);
- resize(widget->size());
- m_root.reset(widget);
-
- if (m_root) {
- QSize initialSize = m_root->size();
- if (initialSize != size())
- resize(initialSize);
- }
-}
-
-} //QmlDesigner
diff --git a/src/plugins/qmldesigner/components/propertyeditor/designerpropertymap.h b/src/plugins/qmldesigner/components/propertyeditor/designerpropertymap.h
index 3cace3d004..ebdfcf3225 100644
--- a/src/plugins/qmldesigner/components/propertyeditor/designerpropertymap.h
+++ b/src/plugins/qmldesigner/components/propertyeditor/designerpropertymap.h
@@ -30,13 +30,13 @@
#ifndef DESIGNERPROPERTYMAP_H
#define DESIGNERPROPERTYMAP_H
-#include <QDeclarativePropertyMap>
-#include <qdeclarative.h>
+#include <QQmlPropertyMap>
+#include <QtQml>
namespace QmlDesigner {
template <class DefaultType>
-class DesignerPropertyMap : public QDeclarativePropertyMap
+class DesignerPropertyMap : public QQmlPropertyMap
{
public:
@@ -50,7 +50,7 @@ private:
};
template <class DefaultType>
-DesignerPropertyMap<DefaultType>::DesignerPropertyMap(QObject *parent) : QDeclarativePropertyMap(parent), m_defaultValue(this)
+DesignerPropertyMap<DefaultType>::DesignerPropertyMap(QObject *parent) : QQmlPropertyMap(parent), m_defaultValue(this)
{
}
@@ -58,7 +58,7 @@ template <class DefaultType>
QVariant DesignerPropertyMap<DefaultType>::value(const QString &key) const
{
if (contains(key))
- return QDeclarativePropertyMap::value(key);
+ return QQmlPropertyMap::value(key);
return QVariant(&m_defaultValue);
}
diff --git a/src/plugins/qmldesigner/components/propertyeditor/gradientlineqmladaptor.cpp b/src/plugins/qmldesigner/components/propertyeditor/gradientlineqmladaptor.cpp
index b2a9f180d7..cfd9812baf 100644
--- a/src/plugins/qmldesigner/components/propertyeditor/gradientlineqmladaptor.cpp
+++ b/src/plugins/qmldesigner/components/propertyeditor/gradientlineqmladaptor.cpp
@@ -128,7 +128,7 @@ void GradientLineQmlAdaptor::writeGradient()
modelNode.removeProperty(gradientName().toUtf8());
}
- ModelNode gradientNode= modelNode.view()->createModelNode("QtQuick.Gradient", modelNode.majorQtQuickVersion(), 0);
+ ModelNode gradientNode= modelNode.view()->createModelNode("QtQuick.Gradient", modelNode.view()->majorQtQuickVersion(), 0);
modelNode.nodeProperty(gradientName().toUtf8()).reparentHere(gradientNode);
RewriterTransaction transaction = m_itemNode.modelNode().view()->beginRewriterTransaction();
@@ -137,9 +137,9 @@ void GradientLineQmlAdaptor::writeGradient()
gradientNode.setId(oldId);
for (int i = 0;i < stops.size(); i++) {
- 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);
+ ModelNode gradientStopNode = modelNode.view()->createModelNode("QtQuick.GradientStop", modelNode.view()->majorQtQuickVersion(), 0);
+ gradientStopNode.variantProperty("position").setValue(roundReal(stops.at(i).first));
+ gradientStopNode.variantProperty("color").setValue(normalizeColor(stops.at(i).second));
gradientNode.nodeListProperty("stops").reparentHere(gradientStopNode);
}
} else { //state
diff --git a/src/plugins/qmldesigner/components/propertyeditor/layoutwidget.cpp b/src/plugins/qmldesigner/components/propertyeditor/layoutwidget.cpp
deleted file mode 100644
index 163ff72bcd..0000000000
--- a/src/plugins/qmldesigner/components/propertyeditor/layoutwidget.cpp
+++ /dev/null
@@ -1,106 +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 "layoutwidget.h"
-#include <QGridLayout>
-#include <QFile>
-#include <QDebug>
-
-QT_BEGIN_NAMESPACE
-
-
-LayoutWidget::LayoutWidget(QWidget *parent) : QFrame(parent)
-{
- QSizePolicy policy(QSizePolicy::Expanding, QSizePolicy::Expanding);
-
- QGridLayout *grid = new QGridLayout(this);
- setLayout(grid);
- grid->setContentsMargins(0,0,0,0);
- grid->setSpacing(4);
-
- m_topButton = new QPushButton(this);
- m_topButton->setCheckable(true);
- m_topButton->setSizePolicy(policy);
-
- grid->addWidget(m_topButton, 0, 2, 2, 1, Qt::AlignHCenter);
-
- m_bottomButton = new QPushButton(this);
- m_bottomButton->setCheckable(true);
-
- m_bottomButton->setSizePolicy(policy);
-
- grid->addWidget(m_bottomButton, 3, 2, 2, 1, Qt::AlignHCenter);
-
- m_leftButton = new QPushButton(this);
- m_leftButton->setCheckable(true);
- m_leftButton->setSizePolicy(policy);
-
-
- grid->addWidget(m_leftButton, 2, 0, 1, 2, Qt::AlignVCenter);
-
- m_rightButton = new QPushButton(this);
- m_rightButton->setCheckable(true);
- m_rightButton->setSizePolicy(policy);
-
- grid->addWidget(m_rightButton, 2, 3, 1, 2, Qt::AlignVCenter);
-
-
- m_middleButton = new QPushButton(this);
-
- grid->addWidget(m_middleButton, 2, 2, 1, 1, Qt::AlignCenter);
-
- connect(m_topButton, SIGNAL(toggled(bool)), this, SLOT(setTopAnchor(bool)));
- connect(m_bottomButton, SIGNAL(toggled(bool)), this, SLOT(setBottomAnchor(bool)));
- connect(m_leftButton, SIGNAL(toggled(bool)), this, SLOT(setLeftAnchor(bool)));
- connect(m_rightButton, SIGNAL(toggled(bool)), this, SLOT(setRightAnchor(bool)));
-
- connect(m_middleButton, SIGNAL(pressed()), this, SIGNAL(fill()));
-}
-
-LayoutWidget::~LayoutWidget()
-{
-}
-
- void LayoutWidget::setIcon(QPushButton *button, QUrl url)
- {
- if (url.scheme() == QLatin1String("file")) {
- QFile file(url.toLocalFile());
- if (file.open(QIODevice::ReadOnly)) {
- QPixmap pixmap(url.toLocalFile());
- button->setIcon(pixmap);
- } else {
- qWarning() << QString::fromUtf8("setIconFromFile: %1: %2").arg(
- file.fileName(), file.errorString());
- }
- }
- }
-
-QT_END_NAMESPACE
-
-
diff --git a/src/plugins/qmldesigner/components/propertyeditor/layoutwidget.h b/src/plugins/qmldesigner/components/propertyeditor/layoutwidget.h
deleted file mode 100644
index 10288c4ea2..0000000000
--- a/src/plugins/qmldesigner/components/propertyeditor/layoutwidget.h
+++ /dev/null
@@ -1,136 +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 LAYOUTWIDGET_H
-#define LAYOUTWIDGET_H
-
-#include <QFrame>
-#include <QPushButton>
-#include <QUrl>
-
-QT_BEGIN_NAMESPACE
-
-class LayoutWidget : public QFrame
-{
- Q_OBJECT
-
- Q_PROPERTY(bool leftAnchor READ leftAnchor WRITE setLeftAnchor NOTIFY leftAnchorChanged)
- Q_PROPERTY(bool rightAnchor READ rightAnchor WRITE setRightAnchor NOTIFY rightAnchorChanged)
- Q_PROPERTY(bool bottomAnchor READ bottomAnchor WRITE setBottomAnchor NOTIFY bottomAnchorChanged)
- Q_PROPERTY(bool topAnchor READ topAnchor WRITE setTopAnchor NOTIFY topAnchorChanged)
-
- Q_PROPERTY(QUrl leftButtonIcon READ icon WRITE setLeftButtonIcon)
- Q_PROPERTY(QUrl rightButtonIcon READ icon WRITE setRightButtonIcon)
- Q_PROPERTY(QUrl topButtonIcon READ icon WRITE setTopButtonIcon)
- Q_PROPERTY(QUrl bottomButtonIcon READ icon WRITE setBottomButtonIcon)
-
-public:
-
- void setLeftButtonIcon(const QUrl &url)
- { setIcon(m_leftButton, url); }
-
- void setRightButtonIcon(const QUrl &url)
- { setIcon(m_rightButton, url); }
-
- void setTopButtonIcon(const QUrl &url)
- { setIcon(m_topButton, url); }
-
- void setBottomButtonIcon(const QUrl &url)
- { setIcon(m_bottomButton, url); }
-
- QUrl icon() const {return QUrl(); }
-
- LayoutWidget(QWidget *parent = 0);
- ~LayoutWidget();
-
- bool leftAnchor() const { return m_leftAnchor; }
- bool rightAnchor() const { return m_rightAnchor; }
- bool topAnchor() const { return m_topAnchor; }
- bool bottomAnchor() const { return m_bottomAnchor; }
-
-public slots:
- void setLeftAnchor(bool anchor)
- {
- if (anchor == m_leftAnchor)
- return;
- m_leftAnchor = anchor;
- m_leftButton->setChecked(anchor);
- emit leftAnchorChanged();
- }
-
- void setRightAnchor(bool anchor)
- {
- if (anchor == m_rightAnchor)
- return;
- m_rightAnchor = anchor;
- m_rightButton->setChecked(anchor);
- emit rightAnchorChanged();
- }
-
- void setTopAnchor(bool anchor)
- {
- if (anchor == m_topAnchor)
- return;
- m_topAnchor = anchor;
- m_topButton->setChecked(anchor);
- emit topAnchorChanged();
- }
-
- void setBottomAnchor(bool anchor)
- {
- if (anchor == m_bottomAnchor)
- return;
- m_bottomAnchor = anchor;
- m_bottomButton->setChecked(anchor);
- emit bottomAnchorChanged();
- }
-
-signals:
- //void colorChanged(const QColor &color);
- void fill();
- void topAnchorChanged();
- void bottomAnchorChanged();
- void leftAnchorChanged();
- void rightAnchorChanged();
-
-private:
- void setIcon(QPushButton *button, QUrl url);
- bool m_leftAnchor, m_rightAnchor, m_topAnchor, m_bottomAnchor;
- QPushButton *m_leftButton;
- QPushButton *m_rightButton;
- QPushButton *m_topButton;
- QPushButton *m_bottomButton;
- QPushButton *m_middleButton;
-};
-
-QT_END_NAMESPACE
-
-#endif
-
diff --git a/src/plugins/qmldesigner/components/propertyeditor/propertyeditor.cpp b/src/plugins/qmldesigner/components/propertyeditor/propertyeditor.cpp
deleted file mode 100644
index 3b3281fcad..0000000000
--- a/src/plugins/qmldesigner/components/propertyeditor/propertyeditor.cpp
+++ /dev/null
@@ -1,1124 +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 "propertyeditor.h"
-
-#include <qmldesignerconstants.h>
-
-#include <nodemetainfo.h>
-
-#include <invalididexception.h>
-#include <rewritingexception.h>
-#include <variantproperty.h>
-
-#include <bindingproperty.h>
-
-#include <nodeabstractproperty.h>
-#include <rewriterview.h>
-
-#include "propertyeditorvalue.h"
-#include "basiclayouts.h"
-#include "basicwidgets.h"
-#include "resetwidget.h"
-#include "qlayoutobject.h"
-#include <qmleditorwidgets/colorwidgets.h>
-#include "gradientlineqmladaptor.h"
-#include "behaviordialog.h"
-#include "fontwidget.h"
-#include "siblingcombobox.h"
-#include "propertyeditortransaction.h"
-#include "originwidget.h"
-
-#include <qmljs/qmljssimplereader.h>
-#include <utils/fileutils.h>
-
-#include <QCoreApplication>
-#include <QDir>
-#include <QFileSystemWatcher>
-#include <QFileInfo>
-#include <QDebug>
-#include <QTimer>
-#include <QDeclarativeContext>
-#include <QShortcut>
-#include <QMessageBox>
-#include <QApplication>
-
-#ifdef Q_OS_WIN
-#include <utils/winutils.h>
-#endif
-
-enum {
- debug = false
-};
-
-const int collapseButtonOffset = 114;
-
-namespace QmlDesigner {
-
-const char resourcePropertyEditorPath[] = ":/propertyeditor";
-
-static QString applicationDirPath()
-{
-#ifdef Q_OS_WIN
- // normalize paths so QML doesn't freak out if it's wrongly capitalized on Windows
- return Utils::normalizePathName(QCoreApplication::applicationDirPath());
-#else
- return QCoreApplication::applicationDirPath();
-#endif
-}
-
-#ifdef Q_OS_MAC
-# define SHARE_PATH "/../Resources/qmldesigner"
-#else
-# define SHARE_PATH "/../share/qtcreator/qmldesigner"
-#endif
-
-static inline QString sharedDirPath()
-{
- QString appPath = applicationDirPath();
-
- 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)
- return *(QObject **)v.constData();
-
- 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())
-{
- Q_ASSERT(QFileInfo(":/images/button_normal.png").exists());
-
- 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);
- ctxt->setContextObject(m_contextObject.data());
-
- connect(&m_backendValuesPropertyMap, SIGNAL(valueChanged(QString,QVariant)), propertyEditor, SLOT(changeValue(QString)));
-}
-
-PropertyEditor::NodeType::~NodeType()
-{
-}
-
-void setupPropertyEditorValue(const PropertyName &name, QDeclarativePropertyMap *propertyMap, PropertyEditor *propertyEditor, const QString &type)
-{
- QmlDesigner::PropertyName propertyName(name);
- propertyName.replace('.', '_');
- PropertyEditorValue *valueObject = qobject_cast<PropertyEditorValue*>(variantToQObject(propertyMap->value(propertyName)));
- if (!valueObject) {
- valueObject = new PropertyEditorValue(propertyMap);
- QObject::connect(valueObject, SIGNAL(valueChanged(QString,QVariant)), propertyMap, SIGNAL(valueChanged(QString,QVariant)));
- QObject::connect(valueObject, SIGNAL(expressionChanged(QString)), propertyEditor, SLOT(changeExpression(QString)));
- propertyMap->insert(QString::fromUtf8(propertyName), QVariant::fromValue(valueObject));
- }
- valueObject->setName(propertyName);
- if (type == "QColor")
- valueObject->setValue(QVariant("#000000"));
- else
- valueObject->setValue(QVariant(1));
-
-}
-
-void createPropertyEditorValue(const QmlObjectNode &fxObjectNode, const PropertyName &name, const QVariant &value, QDeclarativePropertyMap *propertyMap, PropertyEditor *propertyEditor)
-{
- PropertyName propertyName(name);
- propertyName.replace('.', '_');
- PropertyEditorValue *valueObject = qobject_cast<PropertyEditorValue*>(variantToQObject(propertyMap->value(propertyName)));
- if (!valueObject) {
- valueObject = new PropertyEditorValue(propertyMap);
- QObject::connect(valueObject, SIGNAL(valueChanged(QString,QVariant)), propertyMap, SIGNAL(valueChanged(QString,QVariant)));
- QObject::connect(valueObject, SIGNAL(expressionChanged(QString)), propertyEditor, SLOT(changeExpression(QString)));
- propertyMap->insert(QString::fromUtf8(propertyName), QVariant::fromValue(valueObject));
- }
- valueObject->setName(name);
- valueObject->setModelNode(fxObjectNode);
-
- if (fxObjectNode.propertyAffectedByCurrentState(name) && !(fxObjectNode.modelNode().property(name).isBindingProperty()))
- valueObject->setValue(fxObjectNode.modelValue(name));
-
- else
- valueObject->setValue(value);
-
- if (propertyName != "id" &&
- fxObjectNode.currentState().isBaseState() &&
- fxObjectNode.modelNode().property(propertyName).isBindingProperty()) {
- valueObject->setExpression(fxObjectNode.modelNode().bindingProperty(propertyName).expression());
- } else {
- valueObject->setExpression(fxObjectNode.instanceValue(name).toString());
- }
-}
-
-void PropertyEditor::NodeType::setValue(const QmlObjectNode & fxObjectNode, const PropertyName &name, const QVariant &value)
-{
- PropertyName propertyName = name;
- propertyName.replace('.', '_');
- PropertyEditorValue *propertyValue = qobject_cast<PropertyEditorValue*>(variantToQObject(m_backendValuesPropertyMap.value(propertyName)));
- if (propertyValue) {
- propertyValue->setValue(value);
- if (!fxObjectNode.hasBindingProperty(name))
- propertyValue->setExpression(value.toString());
- else
- propertyValue->setExpression(fxObjectNode.expression(name));
- }
-}
-
-void PropertyEditor::NodeType::setup(const QmlObjectNode &fxObjectNode, const QString &stateName, const QUrl &qmlSpecificsFile, PropertyEditor *propertyEditor)
-{
- if (!fxObjectNode.isValid())
- return;
-
- QDeclarativeContext *ctxt = m_view->rootContext();
-
- if (fxObjectNode.isValid()) {
- foreach (const PropertyName &propertyName, fxObjectNode.modelNode().metaInfo().propertyNames())
- createPropertyEditorValue(fxObjectNode, propertyName, fxObjectNode.instanceValue(propertyName), &m_backendValuesPropertyMap, propertyEditor);
-
- // className
- PropertyEditorValue *valueObject = qobject_cast<PropertyEditorValue*>(variantToQObject(m_backendValuesPropertyMap.value("className")));
- if (!valueObject)
- valueObject = new PropertyEditorValue(&m_backendValuesPropertyMap);
- valueObject->setName("className");
- valueObject->setModelNode(fxObjectNode.modelNode());
- valueObject->setValue(fxObjectNode.modelNode().simplifiedTypeName());
- QObject::connect(valueObject, SIGNAL(valueChanged(QString,QVariant)), &m_backendValuesPropertyMap, SIGNAL(valueChanged(QString,QVariant)));
- m_backendValuesPropertyMap.insert("className", QVariant::fromValue(valueObject));
-
- // id
- valueObject = qobject_cast<PropertyEditorValue*>(variantToQObject(m_backendValuesPropertyMap.value("id")));
- if (!valueObject)
- valueObject = new PropertyEditorValue(&m_backendValuesPropertyMap);
- valueObject->setName("id");
- valueObject->setValue(fxObjectNode.id());
- QObject::connect(valueObject, SIGNAL(valueChanged(QString,QVariant)), &m_backendValuesPropertyMap, SIGNAL(valueChanged(QString,QVariant)));
- m_backendValuesPropertyMap.insert("id", QVariant::fromValue(valueObject));
-
- // anchors
- 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;
- ctxt->setContextProperty("propertyCount", QVariant(fxObjectNode.modelNode().properties().count()));
-
- m_contextObject->setIsBaseState(fxObjectNode.isInBaseState());
- m_contextObject->setSelectionChanged(false);
-
- m_contextObject->setSelectionChanged(false);
-
- NodeMetaInfo metaInfo = fxObjectNode.modelNode().metaInfo();
-
- if (metaInfo.isValid()) {
- m_contextObject->setMajorVersion(metaInfo.majorVersion());
- m_contextObject->setMinorVersion(metaInfo.minorVersion());
- } else {
- m_contextObject->setMajorVersion(-1);
- m_contextObject->setMinorVersion(-1);
- }
-
- } else {
- qWarning() << "PropertyEditor: invalid node for setup";
- }
-}
-
-void PropertyEditor::NodeType::initialSetup(const TypeName &typeName, const QUrl &qmlSpecificsFile, PropertyEditor *propertyEditor)
-{
- QDeclarativeContext *ctxt = m_view->rootContext();
-
- NodeMetaInfo metaInfo = propertyEditor->model()->metaInfo(typeName, 4, 7);
-
- foreach (const PropertyName &propertyName, metaInfo.propertyNames())
- setupPropertyEditorValue(propertyName, &m_backendValuesPropertyMap, propertyEditor, metaInfo.propertyTypeName(propertyName));
-
- PropertyEditorValue *valueObject = qobject_cast<PropertyEditorValue*>(variantToQObject(m_backendValuesPropertyMap.value("className")));
- if (!valueObject)
- valueObject = new PropertyEditorValue(&m_backendValuesPropertyMap);
- valueObject->setName("className");
-
- valueObject->setValue(typeName);
- QObject::connect(valueObject, SIGNAL(valueChanged(QString,QVariant)), &m_backendValuesPropertyMap, SIGNAL(valueChanged(QString,QVariant)));
- m_backendValuesPropertyMap.insert("className", QVariant::fromValue(valueObject));
-
- // id
- valueObject = qobject_cast<PropertyEditorValue*>(variantToQObject(m_backendValuesPropertyMap.value("id")));
- if (!valueObject)
- valueObject = new PropertyEditorValue(&m_backendValuesPropertyMap);
- valueObject->setName("id");
- valueObject->setValue("id");
- QObject::connect(valueObject, SIGNAL(valueChanged(QString,QVariant)), &m_backendValuesPropertyMap, SIGNAL(valueChanged(QString,QVariant)));
- m_backendValuesPropertyMap.insert("id", QVariant::fromValue(valueObject));
-
- ctxt->setContextProperty("anchorBackend", &m_backendAnchorBinding);
- ctxt->setContextProperty("transaction", m_propertyEditorTransaction.data());
-
- m_contextObject->setSpecificsUrl(qmlSpecificsFile);
-
- m_contextObject->setStateName(QLatin1String("basestate"));
-
- m_contextObject->setIsBaseState(true);
-
- m_contextObject->setSpecificQmlData(QLatin1String(""));
-
- m_contextObject->setGlobalBaseUrl(QUrl());
-}
-
-PropertyEditor::PropertyEditor(QWidget *parent) :
- QmlModelView(parent),
- m_parent(parent),
- m_updateShortcut(0),
- m_timerId(0),
- m_stackedWidget(new StackedWidget(parent)),
- m_currentType(0),
- m_locked(false),
- m_setupCompleted(false),
- m_singleShotTimer(new QTimer(this))
-{
- m_updateShortcut = new QShortcut(QKeySequence("F3"), m_stackedWidget);
- connect(m_updateShortcut, SIGNAL(activated()), this, SLOT(reloadQml()));
-
- m_stackedWidget->setStyleSheet(
- QLatin1String(Utils::FileReader::fetchQrc(":/qmldesigner/stylesheet.css")));
- m_stackedWidget->setMinimumWidth(320);
- m_stackedWidget->move(0, 0);
- connect(m_stackedWidget, SIGNAL(resized()), this, SLOT(updateSize()));
-
- m_stackedWidget->insertWidget(0, new QWidget(m_stackedWidget));
-
-
- static bool declarativeTypesRegistered = false;
- if (!declarativeTypesRegistered) {
- declarativeTypesRegistered = true;
- BasicWidgets::registerDeclarativeTypes();
- BasicLayouts::registerDeclarativeTypes();
- ResetWidget::registerDeclarativeType();
- QLayoutObject::registerDeclarativeType();
- QmlEditorWidgets::ColorWidgets::registerDeclarativeTypes();
- BehaviorDialog::registerDeclarativeType();
- PropertyEditorValue::registerDeclarativeTypes();
- FontWidget::registerDeclarativeTypes();
- SiblingComboBox::registerDeclarativeTypes();
- OriginWidget::registerDeclarativeType();
- GradientLineQmlAdaptor::registerDeclarativeType();
- }
- setQmlDir(sharedDirPath() + QLatin1String("/propertyeditor"));
- m_stackedWidget->setWindowTitle(tr("Properties"));
-}
-
-PropertyEditor::~PropertyEditor()
-{
- qDeleteAll(m_typeHash);
-}
-
-static inline QString fixTypeNameForPanes(const QString &typeName)
-{
- QString fixedTypeName = typeName;
- fixedTypeName.replace('.', '/');
- return fixedTypeName;
-}
-
-void PropertyEditor::setupPane(const TypeName &typeName)
-{
- NodeMetaInfo metaInfo = model()->metaInfo(typeName);
-
- QUrl qmlFile = fileToUrl(locateQmlFile(metaInfo, QLatin1String("Qt/ItemPane.qml")));
- QUrl qmlSpecificsFile;
-
- qmlSpecificsFile = fileToUrl(locateQmlFile(metaInfo, fixTypeNameForPanes(typeName) + "Specifics.qml"));
- NodeType *type = m_typeHash.value(qmlFile.toString());
-
- if (!type) {
- type = new NodeType(this);
-
- QDeclarativeContext *ctxt = type->m_view->rootContext();
- ctxt->setContextProperty("finishedNotify", QVariant(false) );
- type->initialSetup(typeName, qmlSpecificsFile, this);
- type->m_view->setSource(qmlFile);
- ctxt->setContextProperty("finishedNotify", QVariant(true) );
-
- m_stackedWidget->addWidget(type->m_view);
- m_typeHash.insert(qmlFile.toString(), type);
- } else {
- QDeclarativeContext *ctxt = type->m_view->rootContext();
- ctxt->setContextProperty("finishedNotify", QVariant(false) );
-
- type->initialSetup(typeName, qmlSpecificsFile, this);
- ctxt->setContextProperty("finishedNotify", QVariant(true) );
- }
-}
-
-void PropertyEditor::changeValue(const QString &name)
-{
- PropertyName propertyName = name.toUtf8();
-
- if (propertyName.isNull())
- return;
-
- if (m_locked)
- return;
-
- if (propertyName == "type")
- return;
-
- if (!m_selectedNode.isValid())
- return;
-
- if (propertyName == "id") {
- PropertyEditorValue *value = qobject_cast<PropertyEditorValue*>(variantToQObject(m_currentType->m_backendValuesPropertyMap.value(propertyName)));
- const QString newId = value->value().toString();
-
- if (newId == m_selectedNode.id())
- return;
-
- if (m_selectedNode.isValidId(newId) && !modelNodeForId(newId).isValid() ) {
- if (m_selectedNode.id().isEmpty() || newId.isEmpty()) { //no id
- try {
- m_selectedNode.setId(newId);
- } catch (InvalidIdException &e) { //better save then sorry
- m_locked = true;
- value->setValue(m_selectedNode.id());
- m_locked = false;
- QMessageBox::warning(0, tr("Invalid Id"), e.description());
- }
- } else { //there is already an id, so we refactor
- if (rewriterView())
- rewriterView()->renameId(m_selectedNode.id(), newId);
- }
- } else {
- m_locked = true;
- value->setValue(m_selectedNode.id());
- m_locked = false;
- if (!m_selectedNode.isValidId(newId))
- QMessageBox::warning(0, tr("Invalid Id"), tr("%1 is an invalid id").arg(newId));
- else
- QMessageBox::warning(0, tr("Invalid Id"), tr("%1 already exists").arg(newId));
- }
- return;
- }
-
- //.replace(QLatin1Char('.'), QLatin1Char('_'))
- PropertyName underscoreName(propertyName);
- underscoreName.replace('.', '_');
- PropertyEditorValue *value = qobject_cast<PropertyEditorValue*>(variantToQObject(m_currentType->m_backendValuesPropertyMap.value(underscoreName)));
-
- if (value ==0)
- return;
-
- QmlObjectNode fxObjectNode(m_selectedNode);
-
- QVariant castedValue;
-
- if (fxObjectNode.modelNode().metaInfo().isValid() && fxObjectNode.modelNode().metaInfo().hasProperty(propertyName)) {
- castedValue = fxObjectNode.modelNode().metaInfo().propertyCastedValue(propertyName, value->value());
- } else {
- qWarning() << "PropertyEditor:" <<propertyName << "cannot be casted (metainfo)";
- return ;
- }
-
- if (value->value().isValid() && !castedValue.isValid()) {
- qWarning() << "PropertyEditor:" << propertyName << "not properly casted (metainfo)";
- return ;
- }
-
- if (fxObjectNode.modelNode().metaInfo().isValid() && fxObjectNode.modelNode().metaInfo().hasProperty(propertyName))
- if (fxObjectNode.modelNode().metaInfo().propertyTypeName(propertyName) == "QUrl"
- || fxObjectNode.modelNode().metaInfo().propertyTypeName(propertyName) == "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));
- }
- }
-
- if (castedValue.type() == QVariant::Color) {
- QColor color = castedValue.value<QColor>();
- QColor newColor = QColor(color.name());
- newColor.setAlpha(color.alpha());
- castedValue = QVariant(newColor);
- }
-
- try {
- if (!value->value().isValid()) { //reset
- fxObjectNode.removeVariantProperty(propertyName);
- } else {
- if (castedValue.isValid() && !castedValue.isNull()) {
- m_locked = true;
- fxObjectNode.setVariantProperty(propertyName, castedValue);
- m_locked = false;
- }
- }
- }
- catch (RewritingException &e) {
- QMessageBox::warning(0, "Error", e.description());
- }
-}
-
-void PropertyEditor::changeExpression(const QString &propertyName)
-{
- PropertyName name = propertyName.toUtf8();
-
- if (name.isNull())
- return;
-
- if (m_locked)
- return;
-
- RewriterTransaction transaction = beginRewriterTransaction();
-
- try {
- PropertyName underscoreName(name);
- underscoreName.replace('.', '_');
-
- QmlObjectNode fxObjectNode(m_selectedNode);
- PropertyEditorValue *value = qobject_cast<PropertyEditorValue*>(variantToQObject(m_currentType->m_backendValuesPropertyMap.value(underscoreName)));
-
- if (fxObjectNode.modelNode().metaInfo().isValid() && fxObjectNode.modelNode().metaInfo().hasProperty(name)) {
- if (fxObjectNode.modelNode().metaInfo().propertyTypeName(name) == "QColor") {
- if (QColor(value->expression().remove('"')).isValid()) {
- fxObjectNode.setVariantProperty(name, QColor(value->expression().remove('"')));
- transaction.commit(); //committing in the try block
- return;
- }
- } else if (fxObjectNode.modelNode().metaInfo().propertyTypeName(name) == "bool") {
- if (value->expression().compare("false", Qt::CaseInsensitive) == 0 || value->expression().compare("true", Qt::CaseInsensitive) == 0) {
- if (value->expression().compare("true", Qt::CaseInsensitive) == 0)
- fxObjectNode.setVariantProperty(name, true);
- else
- fxObjectNode.setVariantProperty(name, false);
- transaction.commit(); //committing in the try block
- return;
- }
- } else if (fxObjectNode.modelNode().metaInfo().propertyTypeName(name) == "int") {
- bool ok;
- int intValue = value->expression().toInt(&ok);
- if (ok) {
- fxObjectNode.setVariantProperty(name, intValue);
- transaction.commit(); //committing in the try block
- return;
- }
- } else if (fxObjectNode.modelNode().metaInfo().propertyTypeName(name) == "qreal") {
- bool ok;
- qreal realValue = value->expression().toFloat(&ok);
- if (ok) {
- fxObjectNode.setVariantProperty(name, realValue);
- transaction.commit(); //committing in the try block
- return;
- }
- }
- }
-
- if (!value) {
- qWarning() << "PropertyEditor::changeExpression no value for " << underscoreName;
- return;
- }
-
- if (value->expression().isEmpty())
- return;
-
- if (fxObjectNode.expression(name) != value->expression() || !fxObjectNode.propertyAffectedByCurrentState(name))
- fxObjectNode.setBindingProperty(name, value->expression());
-
- transaction.commit(); //committing in the try block
- }
-
- catch (RewritingException &e) {
- QMessageBox::warning(0, "Error", e.description());
- }
-}
-
-void PropertyEditor::updateSize()
-{
- if (!m_currentType)
- return;
- QWidget* frame = m_currentType->m_view->findChild<QWidget*>("propertyEditorFrame");
- if (frame)
- frame->resize(m_stackedWidget->size());
-}
-
-void PropertyEditor::setupPanes()
-{
- QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
- setupPane("QtQuick.Rectangle");
- setupPane("QtQuick.Text");
- resetView();
- m_setupCompleted = true;
- QApplication::restoreOverrideCursor();
-}
-
-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()));
-}
-
-void PropertyEditor::delayedResetView()
-{
- if (m_timerId == 0)
- m_timerId = startTimer(100);
-}
-
-void PropertyEditor::timerEvent(QTimerEvent *timerEvent)
-{
- if (m_timerId == timerEvent->timerId())
- resetView();
-}
-
-QString templateGeneration(NodeMetaInfo type, NodeMetaInfo superType, const QmlObjectNode &objectNode)
-{
- 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(QString::fromUtf8(objectNode.modelNode().simplifiedTypeName()));
- qmlTemplate += QLatin1String("layout: VerticalLayout {\n");
-
- QList<PropertyName> orderedList = type.propertyNames();
- qSort(orderedList);
-
- bool emptyTemplate = true;
-
- foreach (const PropertyName &name, orderedList) {
-
- if (name.startsWith("__"))
- continue; //private API
- PropertyName properName = name;
-
- properName.replace('.', '_');
-
- 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) && !name.contains(".")) {
- 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(QString::fromUtf8(name)).arg(QString::fromUtf8(properName));
- emptyTemplate = false;
- } else {
- qWarning().nospace() << "template definition source file not found:" << fileName;
- }
- }
- }
- }
- qmlTemplate += QLatin1String("}\n"); //VerticalLayout
- qmlTemplate += QLatin1String("}\n"); //GroupBox
-
- if (emptyTemplate)
- return QString();
-
- return qmlTemplate;
-}
-
-void PropertyEditor::resetView()
-{
- if (model() == 0)
- return;
-
- m_locked = true;
-
- if (debug)
- qDebug() << "________________ RELOADING PROPERTY EDITOR QML _______________________";
-
- if (m_timerId)
- killTimer(m_timerId);
-
- if (m_selectedNode.isValid() && model() != m_selectedNode.model())
- m_selectedNode = ModelNode();
-
- TypeName specificsClassName;
- QUrl qmlFile(qmlForNode(m_selectedNode, specificsClassName));
- QUrl qmlSpecificsFile;
-
- TypeName diffClassName;
- if (m_selectedNode.isValid()) {
- diffClassName = m_selectedNode.metaInfo().typeName();
- QList<NodeMetaInfo> hierarchy;
- hierarchy << m_selectedNode.metaInfo();
- hierarchy << m_selectedNode.metaInfo().superClasses();
-
- foreach (const NodeMetaInfo &info, hierarchy) {
- if (QFileInfo(fileFromUrl(qmlSpecificsFile)).exists())
- break;
- qmlSpecificsFile = fileToUrl(locateQmlFile(info, fixTypeNameForPanes(info.typeName()) + "Specifics.qml"));
- diffClassName = info.typeName();
- }
- }
-
- if (!QFileInfo(fileFromUrl(qmlSpecificsFile)).exists())
- diffClassName = specificsClassName;
-
- QString specificQmlData;
-
- if (m_selectedNode.isValid() && m_selectedNode.metaInfo().isValid() && diffClassName != m_selectedNode.type()) {
- //do magic !!
- specificQmlData = templateGeneration(m_selectedNode.metaInfo(), model()->metaInfo(diffClassName), m_selectedNode);
- }
-
- NodeType *type = m_typeHash.value(qmlFile.toString());
-
- if (!type) {
- type = new NodeType(this);
-
- m_stackedWidget->addWidget(type->m_view);
- m_typeHash.insert(qmlFile.toString(), type);
-
- QmlObjectNode fxObjectNode;
- if (m_selectedNode.isValid()) {
- fxObjectNode = QmlObjectNode(m_selectedNode);
- Q_ASSERT(fxObjectNode.isValid());
- }
- QDeclarativeContext *ctxt = type->m_view->rootContext();
- type->setup(fxObjectNode, currentState().name(), qmlSpecificsFile, this);
- 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 qmlObjectNode;
- if (m_selectedNode.isValid())
- qmlObjectNode = QmlObjectNode(m_selectedNode);
- QDeclarativeContext *ctxt = type->m_view->rootContext();
-
- ctxt->setContextProperty("finishedNotify", QVariant(false));
- if (specificQmlData.isEmpty())
- type->m_contextObject->setSpecificQmlData(specificQmlData);
- QString currentStateName = currentState().isValid() ? currentState().name() : QLatin1String("invalid state");
- type->setup(qmlObjectNode, currentStateName, qmlSpecificsFile, this);
- type->m_contextObject->setGlobalBaseUrl(qmlFile);
- type->m_contextObject->setSpecificQmlData(specificQmlData);
- }
-
- m_stackedWidget->setCurrentWidget(type->m_view);
-
-
- QDeclarativeContext *ctxt = type->m_view->rootContext();
- ctxt->setContextProperty("finishedNotify", QVariant(true));
- /*ctxt->setContextProperty("selectionChanged", QVariant(false));
- ctxt->setContextProperty("selectionChanged", QVariant(true));
- ctxt->setContextProperty("selectionChanged", QVariant(false));*/
- type->m_contextObject->triggerSelectionChanged();
-
- m_currentType = type;
-
- m_locked = false;
-
- if (m_timerId)
- m_timerId = 0;
-
- updateSize();
-}
-
-void PropertyEditor::selectedNodesChanged(const QList<ModelNode> &selectedNodeList,
- const QList<ModelNode> &lastSelectedNodeList)
-{
- Q_UNUSED(lastSelectedNodeList);
-
- if (selectedNodeList.isEmpty() || selectedNodeList.count() > 1)
- select(ModelNode());
- else if (m_selectedNode != selectedNodeList.first())
- select(selectedNodeList.first());
-}
-
-void PropertyEditor::nodeAboutToBeRemoved(const ModelNode &removedNode)
-{
- QmlModelView::nodeAboutToBeRemoved(removedNode);
- if (m_selectedNode.isValid() && removedNode.isValid() && m_selectedNode == removedNode)
- select(m_selectedNode.parentProperty().parentModelNode());
-}
-
-void PropertyEditor::modelAttached(Model *model)
-{
- QmlModelView::modelAttached(model);
-
- if (debug)
- qDebug() << Q_FUNC_INFO;
-
- m_locked = true;
-
- resetView();
- if (!m_setupCompleted) {
- m_singleShotTimer->setSingleShot(true);
- m_singleShotTimer->setInterval(100);
- connect(m_singleShotTimer, SIGNAL(timeout()), this, SLOT(setupPanes()));
- m_singleShotTimer->start();
- }
-
- m_locked = false;
-}
-
-void PropertyEditor::modelAboutToBeDetached(Model *model)
-{
- QmlModelView::modelAboutToBeDetached(model);
- m_currentType->m_propertyEditorTransaction->end();
-
- resetView();
-}
-
-
-void PropertyEditor::propertiesRemoved(const QList<AbstractProperty>& propertyList)
-{
- QmlModelView::propertiesRemoved(propertyList);
-
- if (!m_selectedNode.isValid())
- return;
-
- if (!QmlObjectNode(m_selectedNode).isValid())
- return;
-
- foreach (const AbstractProperty &property, propertyList) {
- ModelNode node(property.parentModelNode());
- if (node == m_selectedNode || QmlObjectNode(m_selectedNode).propertyChangeForCurrentState() == node) {
- setValue(m_selectedNode, property.name(), QmlObjectNode(m_selectedNode).instanceValue(property.name()));
- if (property.name().contains("anchor"))
- m_currentType->m_backendAnchorBinding.invalidate(m_selectedNode);
- }
- }
-}
-
-
-void PropertyEditor::variantPropertiesChanged(const QList<VariantProperty>& propertyList, PropertyChangeFlags propertyChange)
-{
-
- QmlModelView::variantPropertiesChanged(propertyList, propertyChange);
-
- if (!m_selectedNode.isValid())
- return;
-
- if (!QmlObjectNode(m_selectedNode).isValid())
- return;
-
- foreach (const VariantProperty &property, propertyList) {
- ModelNode node(property.parentModelNode());
-
- if (node == m_selectedNode || QmlObjectNode(m_selectedNode).propertyChangeForCurrentState() == node) {
- if ( QmlObjectNode(m_selectedNode).modelNode().property(property.name()).isBindingProperty())
- setValue(m_selectedNode, property.name(), QmlObjectNode(m_selectedNode).instanceValue(property.name()));
- else
- setValue(m_selectedNode, property.name(), QmlObjectNode(m_selectedNode).modelValue(property.name()));
- }
- }
-}
-
-void PropertyEditor::bindingPropertiesChanged(const QList<BindingProperty>& propertyList, PropertyChangeFlags propertyChange)
-{
- QmlModelView::bindingPropertiesChanged(propertyList, propertyChange);
-
- if (!m_selectedNode.isValid())
- return;
-
- if (!QmlObjectNode(m_selectedNode).isValid())
- return;
-
- foreach (const BindingProperty &property, propertyList) {
- ModelNode node(property.parentModelNode());
-
- if (node == m_selectedNode || QmlObjectNode(m_selectedNode).propertyChangeForCurrentState() == node) {
- if (property.name().contains("anchor"))
- m_currentType->m_backendAnchorBinding.invalidate(m_selectedNode);
- if ( QmlObjectNode(m_selectedNode).modelNode().property(property.name()).isBindingProperty())
- setValue(m_selectedNode, property.name(), QmlObjectNode(m_selectedNode).instanceValue(property.name()));
- else
- setValue(m_selectedNode, property.name(), QmlObjectNode(m_selectedNode).modelValue(property.name()));
- }
- }
-}
-
-void PropertyEditor::signalHandlerPropertiesChanged(const QVector<SignalHandlerProperty> & /*propertyList*/,
- AbstractView::PropertyChangeFlags /*propertyChange*/)
-{
-}
-
-
-void PropertyEditor::instanceInformationsChange(const QMultiHash<ModelNode, InformationName> &informationChangeHash)
-{
- if (!m_selectedNode.isValid())
- return;
-
- m_locked = true;
- QList<InformationName> informationNameList = informationChangeHash.values(m_selectedNode);
- if (informationNameList.contains(Anchor)
- || informationNameList.contains(HasAnchor))
- m_currentType->m_backendAnchorBinding.setup(QmlItemNode(m_selectedNode));
- m_locked = false;
-}
-
-void PropertyEditor::nodeIdChanged(const ModelNode& node, const QString& newId, const QString& oldId)
-{
- QmlModelView::nodeIdChanged(node, newId, oldId);
-
- if (!m_selectedNode.isValid())
- return;
-
- if (!QmlObjectNode(m_selectedNode).isValid())
- return;
-
- if (node == m_selectedNode) {
-
- if (m_currentType)
- setValue(node, "id", newId);
- }
-}
-
-void PropertyEditor::scriptFunctionsChanged(const ModelNode &node, const QStringList &scriptFunctionList)
-{
- QmlModelView::scriptFunctionsChanged(node, scriptFunctionList);
-}
-
-void PropertyEditor::select(const ModelNode &node)
-{
- if (QmlObjectNode(node).isValid())
- m_selectedNode = node;
- else
- m_selectedNode = ModelNode();
-
- delayedResetView();
-}
-
-bool PropertyEditor::hasWidget() const
-{
- return true;
-}
-
-WidgetInfo PropertyEditor::widgetInfo()
-{
- return createWidgetInfo(m_stackedWidget, 0, QLatin1String("Properties"), WidgetInfo::RightPane, 0);
-}
-
-void PropertyEditor::actualStateChanged(const ModelNode &node)
-{
- QmlModelView::actualStateChanged(node);
- QmlModelState newQmlModelState(node);
- Q_ASSERT(newQmlModelState.isValid());
- if (debug)
- qDebug() << Q_FUNC_INFO << newQmlModelState.name();
- delayedResetView();
-}
-
-void PropertyEditor::instancePropertyChange(const QList<QPair<ModelNode, PropertyName> > &propertyList)
-{
- if (!m_selectedNode.isValid())
- return;
- m_locked = true;
-
- typedef QPair<ModelNode, PropertyName> ModelNodePropertyPair;
- foreach (const ModelNodePropertyPair &propertyPair, propertyList) {
- const ModelNode modelNode = propertyPair.first;
- const QmlObjectNode qmlObjectNode(modelNode);
- const PropertyName propertyName = propertyPair.second;
-
- if (qmlObjectNode.isValid() && m_currentType && modelNode == m_selectedNode && qmlObjectNode.currentState().isValid()) {
- const AbstractProperty property = modelNode.property(propertyName);
- if (modelNode == m_selectedNode || qmlObjectNode.propertyChangeForCurrentState() == qmlObjectNode) {
- if ( !modelNode.hasProperty(propertyName) || modelNode.property(property.name()).isBindingProperty() )
- setValue(modelNode, property.name(), qmlObjectNode.instanceValue(property.name()));
- else
- setValue(modelNode, property.name(), qmlObjectNode.modelValue(property.name()));
- }
- }
-
- }
-
- m_locked = false;
-
-}
-
-void PropertyEditor::setValue(const QmlObjectNode &fxObjectNode, const PropertyName &name, const QVariant &value)
-{
- m_locked = true;
- m_currentType->setValue(fxObjectNode, name, value);
- m_locked = false;
-}
-
-void PropertyEditor::reloadQml()
-{
- m_typeHash.clear();
- while (QWidget *widget = m_stackedWidget->widget(0)) {
- m_stackedWidget->removeWidget(widget);
- delete widget;
- }
- m_currentType = 0;
-
- delayedResetView();
-}
-
-QString PropertyEditor::qmlFileName(const NodeMetaInfo &nodeInfo) const
-{
- if (nodeInfo.typeName().split('.').last() == "QDeclarativeItem")
- return "QtQuick/ItemPane.qml";
- const QString fixedTypeName = fixTypeNameForPanes(nodeInfo.typeName());
- return fixedTypeName + QLatin1String("Pane.qml");
-}
-
-QUrl PropertyEditor::fileToUrl(const QString &filePath) const {
- QUrl fileUrl;
-
- if (filePath.isEmpty())
- return fileUrl;
-
- if (filePath.startsWith(QLatin1Char(':'))) {
- fileUrl.setScheme("qrc");
- QString path = filePath;
- path.remove(0, 1); // remove trailing ':'
- fileUrl.setPath(path);
- } else {
- fileUrl = QUrl::fromLocalFile(filePath);
- }
-
- return fileUrl;
-}
-
-QString PropertyEditor::fileFromUrl(const QUrl &url) const
-{
- if (url.scheme() == QLatin1String("qrc")) {
- const QString &path = url.path();
- return QLatin1String(":") + path;
- }
-
- return url.toLocalFile();
-}
-
-QUrl PropertyEditor::qmlForNode(const ModelNode &modelNode, TypeName &className) const
-{
- if (modelNode.isValid()) {
- QList<NodeMetaInfo> hierarchy;
- hierarchy.append(modelNode.metaInfo());
- hierarchy.append(modelNode.metaInfo().superClasses());
-
- foreach (const NodeMetaInfo &info, hierarchy) {
- QUrl fileUrl = fileToUrl(locateQmlFile(info, qmlFileName(info)));
- if (fileUrl.isValid()) {
- className = info.typeName();
- return fileUrl;
- }
- }
- }
- return fileToUrl(QDir(m_qmlDir).filePath("QtQuick/emptyPane.qml"));
-}
-
-QString PropertyEditor::locateQmlFile(const NodeMetaInfo &info, const QString &relativePath) const
-{
- QDir fileSystemDir(m_qmlDir);
- static QDir resourcesDir(resourcePropertyEditorPath);
- QDir importDir(info.importDirectoryPath() + QLatin1String(Constants::QML_DESIGNER_SUBFOLDER));
-
- const QString versionString = QLatin1String("_") + QString::number(info.majorVersion())
- + QLatin1String("_")
- + QString::number(info.minorVersion());
-
- QString relativePathWithoutEnding = relativePath;
- relativePathWithoutEnding.chop(4);
- const QString relativePathWithVersion = relativePathWithoutEnding + versionString + QLatin1String(".qml");
-
- //Check for qml files with versions first
- const QString withoutDirWithVersion = relativePathWithVersion.split(QLatin1String("/")).last();
- if (importDir.exists(relativePathWithVersion))
- return importDir.absoluteFilePath(relativePathWithVersion);
- if (importDir.exists(withoutDirWithVersion)) //Since we are in a subfolder of the import we do not require the directory
- return importDir.absoluteFilePath(withoutDirWithVersion);
- if (fileSystemDir.exists(relativePathWithVersion))
- return fileSystemDir.absoluteFilePath(relativePathWithVersion);
- if (resourcesDir.exists(relativePathWithVersion))
- return resourcesDir.absoluteFilePath(relativePathWithVersion);
-
- const QString withoutDir = relativePath.split(QLatin1String("/")).last();
- if (importDir.exists(relativePath))
- return importDir.absoluteFilePath(relativePath);
- if (importDir.exists(withoutDir)) //Since we are in a subfolder of the import we do not require the directory
- return importDir.absoluteFilePath(withoutDir);
- if (fileSystemDir.exists(relativePath))
- return fileSystemDir.absoluteFilePath(relativePath);
- if (resourcesDir.exists(relativePath))
- return resourcesDir.absoluteFilePath(relativePath);
-
- return QString();
-}
-
-
-} //QmlDesigner
-
diff --git a/src/plugins/qmldesigner/components/propertyeditor/propertyeditor.pri b/src/plugins/qmldesigner/components/propertyeditor/propertyeditor.pri
index 85f2b39e57..61874b4252 100644
--- a/src/plugins/qmldesigner/components/propertyeditor/propertyeditor.pri
+++ b/src/plugins/qmldesigner/components/propertyeditor/propertyeditor.pri
@@ -1,13 +1,7 @@
VPATH += $$PWD
-SOURCES += propertyeditor.cpp \
+SOURCES += propertyeditorview.cpp \
qmlanchorbindingproxy.cpp \
- resetwidget.cpp \
- qlayoutobject.cpp \
- basiclayouts.cpp \
- basicwidgets.cpp \
- behaviordialog.cpp \
- layoutwidget.cpp \
filewidget.cpp \
propertyeditorvalue.cpp \
fontwidget.cpp \
@@ -15,17 +9,13 @@ SOURCES += propertyeditor.cpp \
siblingcombobox.cpp \
propertyeditortransaction.cpp \
propertyeditorcontextobject.cpp \
- declarativewidgetview.cpp \
- gradientlineqmladaptor.cpp
+ quick2propertyeditorview.cpp \
+ gradientlineqmladaptor.cpp \
+ propertyeditorqmlbackend.cpp \
+ propertyeditorwidget.cpp
-HEADERS += propertyeditor.h \
+HEADERS += propertyeditorview.h \
qmlanchorbindingproxy.h \
- resetwidget.h \
- qlayoutobject.h \
- basiclayouts.h \
- basicwidgets.h \
- behaviordialog.h \
- layoutwidget.h \
filewidget.h \
propertyeditorvalue.h \
fontwidget.h \
@@ -34,10 +24,11 @@ HEADERS += propertyeditor.h \
propertyeditortransaction.h \
designerpropertymap.h \
propertyeditorcontextobject.h \
- declarativewidgetview.h \
- gradientlineqmladaptor.h
+ quick2propertyeditorview.h \
+ gradientlineqmladaptor.h \
+ propertyeditorqmlbackend.h \
+ propertyeditorwidget.h
-QT += declarative
+QT += qml quick
RESOURCES += propertyeditor.qrc
-FORMS += behaviordialog.ui
diff --git a/src/plugins/qmldesigner/components/propertyeditor/propertyeditorcontextobject.cpp b/src/plugins/qmldesigner/components/propertyeditor/propertyeditorcontextobject.cpp
index ce6b27bafa..51d4517476 100644
--- a/src/plugins/qmldesigner/components/propertyeditor/propertyeditorcontextobject.cpp
+++ b/src/plugins/qmldesigner/components/propertyeditor/propertyeditorcontextobject.cpp
@@ -42,7 +42,6 @@ PropertyEditorContextObject::PropertyEditorContextObject(QObject *parent) :
}
-
int PropertyEditorContextObject::majorVersion() const
{
return m_majorVersion;
diff --git a/src/plugins/qmldesigner/components/propertyeditor/propertyeditorcontextobject.h b/src/plugins/qmldesigner/components/propertyeditor/propertyeditorcontextobject.h
index 407d823ea6..96f43da3ca 100644
--- a/src/plugins/qmldesigner/components/propertyeditor/propertyeditorcontextobject.h
+++ b/src/plugins/qmldesigner/components/propertyeditor/propertyeditorcontextobject.h
@@ -32,7 +32,7 @@
#include <QObject>
#include <QUrl>
-#include <QDeclarativePropertyMap>
+#include <QQmlPropertyMap>
#include <QColor>
namespace QmlDesigner {
@@ -53,7 +53,7 @@ class PropertyEditorContextObject : public QObject
Q_PROPERTY(int majorVersion READ majorVersion WRITE setMajorVersion NOTIFY majorVersionChanged)
Q_PROPERTY(int minorVersion READ minorVersion WRITE setMinorVersion NOTIFY minorVersionChanged)
- Q_PROPERTY(QDeclarativePropertyMap* backendValues READ backendValues WRITE setBackendValues NOTIFY backendValuesChanged)
+ Q_PROPERTY(QQmlPropertyMap* backendValues READ backendValues WRITE setBackendValues NOTIFY backendValuesChanged)
public:
PropertyEditorContextObject(QObject *parent = 0);
@@ -66,7 +66,7 @@ public:
bool isBaseState() const { return m_isBaseState; }
bool selectionChanged() const { return m_selectionChanged; }
- QDeclarativePropertyMap* backendValues() const { return m_backendValues; }
+ QQmlPropertyMap* backendValues() const { return m_backendValues; }
Q_INVOKABLE QString convertColorToString(const QColor &color) { return color.name(); }
@@ -141,7 +141,7 @@ public slots:
emit selectionChangedChanged();
}
- void setBackendValues(QDeclarativePropertyMap* newBackendValues)
+ void setBackendValues(QQmlPropertyMap* newBackendValues)
{
if (newBackendValues == m_backendValues)
return;
@@ -165,7 +165,7 @@ private:
bool m_isBaseState;
bool m_selectionChanged;
- QDeclarativePropertyMap* m_backendValues;
+ QQmlPropertyMap* m_backendValues;
int m_majorVersion;
int m_minorVersion;
diff --git a/src/plugins/qmldesigner/components/propertyeditor/propertyeditorqmlbackend.cpp b/src/plugins/qmldesigner/components/propertyeditor/propertyeditorqmlbackend.cpp
new file mode 100644
index 0000000000..37fa5bc6df
--- /dev/null
+++ b/src/plugins/qmldesigner/components/propertyeditor/propertyeditorqmlbackend.cpp
@@ -0,0 +1,513 @@
+/****************************************************************************
+**
+** 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 "propertyeditorqmlbackend.h"
+
+#include "propertyeditorvalue.h"
+#include "propertyeditortransaction.h"
+#include <qmldesignerconstants.h>
+
+#include <qmlobjectnode.h>
+#include <nodemetainfo.h>
+#include <variantproperty.h>
+#include <bindingproperty.h>
+
+#include <QApplication>
+#include <QDir>
+#include <QFileInfo>
+
+#include <qmljs/qmljssimplereader.h>
+
+#ifdef Q_OS_WIN
+#include <utils/winutils.h>
+#endif
+
+enum {
+ debug = false
+};
+
+const char propertyEditorPath[] = "/propertyEditorQmlSources";
+const char resourcePropertyEditorPath[] = ":/propertyEditorQmlSources";
+
+static QmlJS::SimpleReaderNode::Ptr s_templateConfiguration = QmlJS::SimpleReaderNode::Ptr();
+
+static inline QString propertyTemplatesPath()
+{
+ return QmlDesigner::PropertyEditorQmlBackend::propertyEditorResourcesPath() + QLatin1String("/PropertyTemplates/");
+}
+
+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;
+}
+
+static QObject *variantToQObject(const QVariant &value)
+{
+ if (value.userType() == QMetaType::QObjectStar || value.userType() > QMetaType::User)
+ return *(QObject **)value.constData();
+
+ return 0;
+}
+
+static QString applicationDirPath()
+{
+#ifdef Q_OS_WIN
+ // normalize paths so QML doesn't freak out if it's wrongly capitalized on Windows
+ return Utils::normalizePathName(QCoreApplication::applicationDirPath());
+#else
+ return QCoreApplication::applicationDirPath();
+#endif
+}
+
+#ifdef Q_OS_MAC
+# define SHARE_PATH "/../Resources/qmldesigner"
+#else
+# define SHARE_PATH "/../share/qtcreator/qmldesigner"
+#endif
+
+static inline QString sharedDirPath()
+{
+ QString appPath = applicationDirPath();
+
+ return QFileInfo(appPath + SHARE_PATH).absoluteFilePath();
+}
+
+namespace QmlDesigner {
+
+PropertyEditorQmlBackend::PropertyEditorQmlBackend(PropertyEditorView *propertyEditor) :
+ m_view(new Quick2PropertyEditorView), m_propertyEditorTransaction(new PropertyEditorTransaction(propertyEditor)), m_dummyPropertyEditorValue(new PropertyEditorValue()),
+ m_contextObject(new PropertyEditorContextObject())
+{
+ Q_ASSERT(QFileInfo(":/images/button_normal.png").exists());
+
+ m_view->engine()->setOutputWarningsToStandardError(debug);
+ m_view->engine()->addImportPath(propertyEditorResourcesPath());
+ m_dummyPropertyEditorValue->setValue("#000000");
+ context()->setContextProperty("dummyBackendValue", m_dummyPropertyEditorValue.data());
+ m_contextObject->setBackendValues(&m_backendValuesPropertyMap);
+ context()->setContextObject(m_contextObject.data());
+
+ QObject::connect(&m_backendValuesPropertyMap, SIGNAL(valueChanged(QString,QVariant)), propertyEditor, SLOT(changeValue(QString)));
+}
+
+PropertyEditorQmlBackend::~PropertyEditorQmlBackend()
+{
+}
+
+void PropertyEditorQmlBackend::setupPropertyEditorValue(const PropertyName &name, PropertyEditorView *propertyEditor, const QString &type)
+{
+ QmlDesigner::PropertyName propertyName(name);
+ propertyName.replace('.', '_');
+ PropertyEditorValue *valueObject = qobject_cast<PropertyEditorValue*>(variantToQObject(backendValuesPropertyMap().value(propertyName)));
+ if (!valueObject) {
+ valueObject = new PropertyEditorValue(&backendValuesPropertyMap());
+ QObject::connect(valueObject, SIGNAL(valueChanged(QString,QVariant)), &backendValuesPropertyMap(), SIGNAL(valueChanged(QString,QVariant)));
+ QObject::connect(valueObject, SIGNAL(expressionChanged(QString)), propertyEditor, SLOT(changeExpression(QString)));
+ backendValuesPropertyMap().insert(QString::fromUtf8(propertyName), QVariant::fromValue(valueObject));
+ }
+ valueObject->setName(propertyName);
+ if (type == "QColor")
+ valueObject->setValue(QVariant("#000000"));
+ else
+ valueObject->setValue(QVariant(1));
+
+}
+
+void PropertyEditorQmlBackend::createPropertyEditorValue(const QmlObjectNode &qmlObjectNode,
+ const PropertyName &name,
+ const QVariant &value,
+ PropertyEditorView *propertyEditor)
+{
+ PropertyName propertyName(name);
+ propertyName.replace('.', '_');
+ PropertyEditorValue *valueObject = qobject_cast<PropertyEditorValue*>(variantToQObject(backendValuesPropertyMap().value(propertyName)));
+ if (!valueObject) {
+ valueObject = new PropertyEditorValue(&backendValuesPropertyMap());
+ QObject::connect(valueObject, SIGNAL(valueChanged(QString,QVariant)), &backendValuesPropertyMap(), SIGNAL(valueChanged(QString,QVariant)));
+ QObject::connect(valueObject, SIGNAL(expressionChanged(QString)), propertyEditor, SLOT(changeExpression(QString)));
+ backendValuesPropertyMap().insert(QString::fromUtf8(propertyName), QVariant::fromValue(valueObject));
+ }
+ valueObject->setName(name);
+ valueObject->setModelNode(qmlObjectNode);
+
+ if (qmlObjectNode.propertyAffectedByCurrentState(name) && !(qmlObjectNode.modelNode().property(name).isBindingProperty()))
+ valueObject->setValue(qmlObjectNode.modelValue(name));
+
+ else
+ valueObject->setValue(value);
+
+ if (propertyName != "id" &&
+ qmlObjectNode.currentState().isBaseState() &&
+ qmlObjectNode.modelNode().property(propertyName).isBindingProperty()) {
+ valueObject->setExpression(qmlObjectNode.modelNode().bindingProperty(propertyName).expression());
+ } else {
+ valueObject->setExpression(qmlObjectNode.instanceValue(name).toString());
+ }
+}
+
+void PropertyEditorQmlBackend::setValue(const QmlObjectNode & qmlObjectNode, const PropertyName &name, const QVariant &value)
+{
+ PropertyName propertyName = name;
+ propertyName.replace('.', '_');
+ PropertyEditorValue *propertyValue = qobject_cast<PropertyEditorValue*>(variantToQObject(m_backendValuesPropertyMap.value(propertyName)));
+ if (propertyValue) {
+ propertyValue->setValue(value);
+ if (!qmlObjectNode.hasBindingProperty(name))
+ propertyValue->setExpression(value.toString());
+ else
+ propertyValue->setExpression(qmlObjectNode.expression(name));
+ }
+}
+
+
+QQmlContext *PropertyEditorQmlBackend::context() {
+ return m_view->rootContext();
+}
+
+PropertyEditorContextObject* PropertyEditorQmlBackend::contextObject() {
+ return m_contextObject.data();
+}
+
+QWidget *PropertyEditorQmlBackend::widget() {
+ return m_view;
+}
+
+void PropertyEditorQmlBackend::setSource(const QUrl& url) {
+ m_view->setSource(url);
+}
+
+Internal::QmlAnchorBindingProxy &PropertyEditorQmlBackend::backendAnchorBinding() {
+ return m_backendAnchorBinding;
+}
+
+DesignerPropertyMap<PropertyEditorValue> &PropertyEditorQmlBackend::backendValuesPropertyMap() {
+ return m_backendValuesPropertyMap;
+}
+
+PropertyEditorTransaction *PropertyEditorQmlBackend::propertyEditorTransaction() {
+ return m_propertyEditorTransaction.data();
+}
+
+PropertyEditorValue *PropertyEditorQmlBackend::propertyValueForName(const QString &propertyName)
+{
+ return qobject_cast<PropertyEditorValue*>(variantToQObject(backendValuesPropertyMap().value(propertyName)));
+}
+
+void PropertyEditorQmlBackend::setup(const QmlObjectNode &qmlObjectNode, const QString &stateName, const QUrl &qmlSpecificsFile, PropertyEditorView *propertyEditor)
+{
+ if (!qmlObjectNode.isValid())
+ return;
+
+ if (qmlObjectNode.isValid()) {
+ foreach (const PropertyName &propertyName, qmlObjectNode.modelNode().metaInfo().propertyNames())
+ createPropertyEditorValue(qmlObjectNode, propertyName, qmlObjectNode.instanceValue(propertyName), propertyEditor);
+
+ // className
+ PropertyEditorValue *valueObject = qobject_cast<PropertyEditorValue*>(variantToQObject(m_backendValuesPropertyMap.value("className")));
+ if (!valueObject)
+ valueObject = new PropertyEditorValue(&m_backendValuesPropertyMap);
+ valueObject->setName("className");
+ valueObject->setModelNode(qmlObjectNode.modelNode());
+ valueObject->setValue(qmlObjectNode.modelNode().simplifiedTypeName());
+ QObject::connect(valueObject, SIGNAL(valueChanged(QString,QVariant)), &m_backendValuesPropertyMap, SIGNAL(valueChanged(QString,QVariant)));
+ m_backendValuesPropertyMap.insert("className", QVariant::fromValue(valueObject));
+
+ // id
+ valueObject = qobject_cast<PropertyEditorValue*>(variantToQObject(m_backendValuesPropertyMap.value("id")));
+ if (!valueObject)
+ valueObject = new PropertyEditorValue(&m_backendValuesPropertyMap);
+ valueObject->setName("id");
+ valueObject->setValue(qmlObjectNode.id());
+ QObject::connect(valueObject, SIGNAL(valueChanged(QString,QVariant)), &m_backendValuesPropertyMap, SIGNAL(valueChanged(QString,QVariant)));
+ m_backendValuesPropertyMap.insert("id", QVariant::fromValue(valueObject));
+
+ // anchors
+ m_backendAnchorBinding.setup(QmlItemNode(qmlObjectNode.modelNode()));
+
+ context()->setContextProperty("anchorBackend", &m_backendAnchorBinding);
+
+ context()->setContextProperty("transaction", m_propertyEditorTransaction.data());
+
+ contextObject()->setSpecificsUrl(qmlSpecificsFile);
+
+ contextObject()->setStateName(stateName);
+ if (!qmlObjectNode.isValid())
+ return;
+ context()->setContextProperty("propertyCount", QVariant(qmlObjectNode.modelNode().properties().count()));
+
+ contextObject()->setIsBaseState(qmlObjectNode.isInBaseState());
+ contextObject()->setSelectionChanged(false);
+
+ contextObject()->setSelectionChanged(false);
+
+ NodeMetaInfo metaInfo = qmlObjectNode.modelNode().metaInfo();
+
+ if (metaInfo.isValid()) {
+ contextObject()->setMajorVersion(metaInfo.majorVersion());
+ contextObject()->setMinorVersion(metaInfo.minorVersion());
+ } else {
+ contextObject()->setMajorVersion(-1);
+ contextObject()->setMinorVersion(-1);
+ }
+
+ } else {
+ qWarning() << "PropertyEditor: invalid node for setup";
+ }
+}
+
+void PropertyEditorQmlBackend::initialSetup(const TypeName &typeName, const QUrl &qmlSpecificsFile, PropertyEditorView *propertyEditor)
+{
+ NodeMetaInfo metaInfo = propertyEditor->model()->metaInfo(typeName, 4, 7);
+
+ foreach (const PropertyName &propertyName, metaInfo.propertyNames())
+ setupPropertyEditorValue(propertyName, propertyEditor, metaInfo.propertyTypeName(propertyName));
+
+ PropertyEditorValue *valueObject = qobject_cast<PropertyEditorValue*>(variantToQObject(m_backendValuesPropertyMap.value("className")));
+ if (!valueObject)
+ valueObject = new PropertyEditorValue(&m_backendValuesPropertyMap);
+ valueObject->setName("className");
+
+ valueObject->setValue(typeName);
+ QObject::connect(valueObject, SIGNAL(valueChanged(QString,QVariant)), &m_backendValuesPropertyMap, SIGNAL(valueChanged(QString,QVariant)));
+ m_backendValuesPropertyMap.insert("className", QVariant::fromValue(valueObject));
+
+ // id
+ valueObject = qobject_cast<PropertyEditorValue*>(variantToQObject(m_backendValuesPropertyMap.value("id")));
+ if (!valueObject)
+ valueObject = new PropertyEditorValue(&m_backendValuesPropertyMap);
+ valueObject->setName("id");
+ valueObject->setValue("id");
+ QObject::connect(valueObject, SIGNAL(valueChanged(QString,QVariant)), &m_backendValuesPropertyMap, SIGNAL(valueChanged(QString,QVariant)));
+ m_backendValuesPropertyMap.insert("id", QVariant::fromValue(valueObject));
+
+ context()->setContextProperty("anchorBackend", &m_backendAnchorBinding);
+ context()->setContextProperty("transaction", m_propertyEditorTransaction.data());
+
+ contextObject()->setSpecificsUrl(qmlSpecificsFile);
+
+ contextObject()->setStateName(QLatin1String("basestate"));
+
+ contextObject()->setIsBaseState(true);
+
+ contextObject()->setSpecificQmlData(QLatin1String(""));
+
+ contextObject()->setGlobalBaseUrl(QUrl());
+}
+
+QString PropertyEditorQmlBackend::propertyEditorResourcesPath() {
+ return sharedDirPath() + QLatin1String(propertyEditorPath);
+}
+
+QString PropertyEditorQmlBackend::templateGeneration(NodeMetaInfo type,
+ NodeMetaInfo superType,
+ const QmlObjectNode &objectNode)
+{
+ 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(QString::fromUtf8(objectNode.modelNode().simplifiedTypeName()));
+ qmlTemplate += QLatin1String("layout: VerticalLayout {\n");
+
+ QList<PropertyName> orderedList = type.propertyNames();
+ qSort(orderedList);
+
+ bool emptyTemplate = true;
+
+ foreach (const PropertyName &name, orderedList) {
+
+ if (name.startsWith("__"))
+ continue; //private API
+ PropertyName properName = name;
+
+ properName.replace('.', '_');
+
+ 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) && !name.contains(".")) {
+ 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(QString::fromUtf8(name)).arg(QString::fromUtf8(properName));
+ emptyTemplate = false;
+ } else {
+ qWarning().nospace() << "template definition source file not found:" << fileName;
+ }
+ }
+ }
+ }
+ qmlTemplate += QLatin1String("}\n"); //VerticalLayout
+ qmlTemplate += QLatin1String("}\n"); //GroupBox
+
+ if (emptyTemplate)
+ return QString();
+
+ return qmlTemplate;
+}
+
+QUrl PropertyEditorQmlBackend::getQmlFileUrl(const QString &relativeTypeName, const NodeMetaInfo &info)
+{
+ return fileToUrl(locateQmlFile(info, fixTypeNameForPanes(relativeTypeName) + QLatin1String(".qml")));
+}
+
+QString PropertyEditorQmlBackend::fixTypeNameForPanes(const QString &typeName)
+{
+ QString fixedTypeName = typeName;
+ fixedTypeName.replace('.', '/');
+ return fixedTypeName;
+}
+
+QString PropertyEditorQmlBackend::qmlFileName(const NodeMetaInfo &nodeInfo)
+{
+ if (nodeInfo.typeName().split('.').last() == "QDeclarativeItem")
+ return "QtQuick/ItemPane.qml";
+ const QString fixedTypeName = fixTypeNameForPanes(nodeInfo.typeName());
+ return fixedTypeName + QLatin1String("Pane.qml");
+}
+
+QUrl PropertyEditorQmlBackend::fileToUrl(const QString &filePath) {
+ QUrl fileUrl;
+
+ if (filePath.isEmpty())
+ return fileUrl;
+
+ if (filePath.startsWith(QLatin1Char(':'))) {
+ fileUrl.setScheme("qrc");
+ QString path = filePath;
+ path.remove(0, 1); // remove trailing ':'
+ fileUrl.setPath(path);
+ } else {
+ fileUrl = QUrl::fromLocalFile(filePath);
+ }
+
+ return fileUrl;
+}
+
+QString PropertyEditorQmlBackend::fileFromUrl(const QUrl &url)
+{
+ if (url.scheme() == QLatin1String("qrc")) {
+ const QString &path = url.path();
+ return QLatin1String(":") + path;
+ }
+
+ return url.toLocalFile();
+}
+
+bool PropertyEditorQmlBackend::checkIfUrlExists(const QUrl &url)
+{
+ return (QFileInfo(fileFromUrl(url)).exists());
+}
+
+QUrl PropertyEditorQmlBackend::getQmlUrlForModelNode(const ModelNode &modelNode, TypeName &className)
+{
+ if (modelNode.isValid()) {
+ QList<NodeMetaInfo> hierarchy;
+ hierarchy.append(modelNode.metaInfo());
+ hierarchy.append(modelNode.metaInfo().superClasses());
+
+ foreach (const NodeMetaInfo &info, hierarchy) {
+ QUrl fileUrl = fileToUrl(locateQmlFile(info, qmlFileName(info)));
+ if (fileUrl.isValid()) {
+ className = info.typeName();
+ return fileUrl;
+ }
+ }
+ }
+ return fileToUrl(QDir(propertyEditorResourcesPath()).filePath("QtQuick/emptyPane.qml"));
+}
+
+QString PropertyEditorQmlBackend::locateQmlFile(const NodeMetaInfo &info, const QString &relativePath)
+{
+ QDir fileSystemDir(PropertyEditorQmlBackend::propertyEditorResourcesPath());
+
+ static QDir resourcesDir(resourcePropertyEditorPath);
+ QDir importDir(info.importDirectoryPath() + QLatin1String(Constants::QML_DESIGNER_SUBFOLDER));
+
+ const QString versionString = QLatin1String("_") + QString::number(info.majorVersion())
+ + QLatin1String("_")
+ + QString::number(info.minorVersion());
+
+ QString relativePathWithoutEnding = relativePath;
+ relativePathWithoutEnding.chop(4);
+ const QString relativePathWithVersion = relativePathWithoutEnding + versionString + QLatin1String(".qml");
+
+ //Check for qml files with versions first
+ const QString withoutDirWithVersion = relativePathWithVersion.split(QLatin1String("/")).last();
+ if (importDir.exists(relativePathWithVersion))
+ return importDir.absoluteFilePath(relativePathWithVersion);
+ if (importDir.exists(withoutDirWithVersion)) //Since we are in a subfolder of the import we do not require the directory
+ return importDir.absoluteFilePath(withoutDirWithVersion);
+ if (fileSystemDir.exists(relativePathWithVersion))
+ return fileSystemDir.absoluteFilePath(relativePathWithVersion);
+ if (resourcesDir.exists(relativePathWithVersion))
+ return resourcesDir.absoluteFilePath(relativePathWithVersion);
+
+ const QString withoutDir = relativePath.split(QLatin1String("/")).last();
+ if (importDir.exists(relativePath))
+ return importDir.absoluteFilePath(relativePath);
+ if (importDir.exists(withoutDir)) //Since we are in a subfolder of the import we do not require the directory
+ return importDir.absoluteFilePath(withoutDir);
+ if (fileSystemDir.exists(relativePath))
+ return fileSystemDir.absoluteFilePath(relativePath);
+ if (resourcesDir.exists(relativePath))
+ return resourcesDir.absoluteFilePath(relativePath);
+
+ return QString();
+}
+
+
+} //QmlDesigner
diff --git a/src/plugins/qmldesigner/components/propertyeditor/propertyeditorqmlbackend.h b/src/plugins/qmldesigner/components/propertyeditor/propertyeditorqmlbackend.h
new file mode 100644
index 0000000000..844915bad9
--- /dev/null
+++ b/src/plugins/qmldesigner/components/propertyeditor/propertyeditorqmlbackend.h
@@ -0,0 +1,99 @@
+/****************************************************************************
+**
+** 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 PROPERTYEDITORQMLBACKEND_H
+#define PROPERTYEDITORQMLBACKEND_H
+
+#include "qmlanchorbindingproxy.h"
+#include "designerpropertymap.h"
+#include "propertyeditorvalue.h"
+#include "propertyeditorcontextobject.h"
+#include "quick2propertyeditorview.h"
+
+#include <nodemetainfo.h>
+
+class PropertyEditorValue;
+
+namespace QmlDesigner {
+
+class PropertyEditorTransaction;
+class PropertyEditorView;
+
+class PropertyEditorQmlBackend {
+public:
+ PropertyEditorQmlBackend(PropertyEditorView *propertyEditor);
+ ~PropertyEditorQmlBackend();
+
+ void setup(const QmlObjectNode &fxObjectNode, const QString &stateName, const QUrl &qmlSpecificsFile, PropertyEditorView *propertyEditor);
+ void initialSetup(const TypeName &typeName, const QUrl &qmlSpecificsFile, PropertyEditorView *propertyEditor);
+ void setValue(const QmlObjectNode &fxObjectNode, const PropertyName &name, const QVariant &value);
+
+ QQmlContext *context();
+ PropertyEditorContextObject* contextObject();
+ QWidget *widget();
+ void setSource(const QUrl& url);
+ Internal::QmlAnchorBindingProxy &backendAnchorBinding();
+ DesignerPropertyMap<PropertyEditorValue> &backendValuesPropertyMap();
+ PropertyEditorTransaction *propertyEditorTransaction();
+
+ PropertyEditorValue *propertyValueForName(const QString &propertyName);
+
+ static QString propertyEditorResourcesPath();
+ static QString templateGeneration(NodeMetaInfo type, NodeMetaInfo superType,
+ const QmlObjectNode &objectNode);
+
+ static QUrl getQmlFileUrl(const QString &relativeTypeName, const NodeMetaInfo &info = NodeMetaInfo());
+ static QUrl getQmlUrlForModelNode(const ModelNode &modelNode, TypeName &className);
+
+ static bool checkIfUrlExists(const QUrl &url);
+
+private:
+ void createPropertyEditorValue(const QmlObjectNode &qmlObjectNode,
+ const PropertyName &name, const QVariant &value,
+ PropertyEditorView *propertyEditor);
+ void setupPropertyEditorValue(const PropertyName &name, PropertyEditorView *propertyEditor, const QString &type);
+
+ static QString qmlFileName(const NodeMetaInfo &nodeInfo);
+ static QUrl fileToUrl(const QString &filePath);
+ static QString fileFromUrl(const QUrl &url);
+ static QString locateQmlFile(const NodeMetaInfo &info, const QString &relativePath);
+ static QString fixTypeNameForPanes(const QString &typeName);
+
+private:
+ Quick2PropertyEditorView *m_view;
+ Internal::QmlAnchorBindingProxy m_backendAnchorBinding;
+ DesignerPropertyMap<PropertyEditorValue> m_backendValuesPropertyMap;
+ QScopedPointer<PropertyEditorTransaction> m_propertyEditorTransaction;
+ QScopedPointer<PropertyEditorValue> m_dummyPropertyEditorValue;
+ QScopedPointer<PropertyEditorContextObject> m_contextObject;
+};
+
+} //QmlDesigner
+
+#endif //PROPERTYEDITORQMLBACKEND_H
diff --git a/src/plugins/qmldesigner/components/propertyeditor/propertyeditortransaction.cpp b/src/plugins/qmldesigner/components/propertyeditor/propertyeditortransaction.cpp
index 6b5b32c950..11ebf55777 100644
--- a/src/plugins/qmldesigner/components/propertyeditor/propertyeditortransaction.cpp
+++ b/src/plugins/qmldesigner/components/propertyeditor/propertyeditortransaction.cpp
@@ -34,7 +34,7 @@
namespace QmlDesigner {
-PropertyEditorTransaction::PropertyEditorTransaction(QmlDesigner::PropertyEditor *propertyEditor) : QObject(propertyEditor), m_propertyEditor(propertyEditor), m_timerId(-1)
+PropertyEditorTransaction::PropertyEditorTransaction(QmlDesigner::PropertyEditorView *propertyEditor) : QObject(propertyEditor), m_propertyEditor(propertyEditor), m_timerId(-1)
{
}
diff --git a/src/plugins/qmldesigner/components/propertyeditor/propertyeditortransaction.h b/src/plugins/qmldesigner/components/propertyeditor/propertyeditortransaction.h
index ef54a8f810..5eb8c1d3cf 100644
--- a/src/plugins/qmldesigner/components/propertyeditor/propertyeditortransaction.h
+++ b/src/plugins/qmldesigner/components/propertyeditor/propertyeditortransaction.h
@@ -30,7 +30,7 @@
#ifndef PROPERTYEDITORTRANSACTION_H
#define PROPERTYEDITORTRANSACTION_H
-#include "propertyeditor.h"
+#include "propertyeditorview.h"
namespace QmlDesigner {
@@ -38,7 +38,7 @@ class PropertyEditorTransaction : public QObject
{
Q_OBJECT
public:
- PropertyEditorTransaction(QmlDesigner::PropertyEditor *propertyEditor);
+ PropertyEditorTransaction(QmlDesigner::PropertyEditorView *propertyEditor);
public slots:
void start();
@@ -47,7 +47,7 @@ protected:
void timerEvent(QTimerEvent *event);
private:
- QmlDesigner::PropertyEditor *m_propertyEditor;
+ QmlDesigner::PropertyEditorView *m_propertyEditor;
QmlDesigner::RewriterTransaction m_rewriterTransaction;
int m_timerId;
};
diff --git a/src/plugins/qmldesigner/components/propertyeditor/propertyeditorvalue.cpp b/src/plugins/qmldesigner/components/propertyeditor/propertyeditorvalue.cpp
index 27d3853330..80a7a4029f 100644
--- a/src/plugins/qmldesigner/components/propertyeditor/propertyeditorvalue.cpp
+++ b/src/plugins/qmldesigner/components/propertyeditor/propertyeditorvalue.cpp
@@ -266,7 +266,7 @@ void PropertyEditorValue::registerDeclarativeTypes()
{
qmlRegisterType<PropertyEditorValue>("Bauhaus",1,0,"PropertyEditorValue");
qmlRegisterType<PropertyEditorNodeWrapper>("Bauhaus",1,0,"PropertyEditorNodeWrapper");
- qmlRegisterType<QDeclarativePropertyMap>("Bauhaus",1,0,"QDeclarativePropertyMap");
+ qmlRegisterType<QQmlPropertyMap>("Bauhaus",1,0,"QQmlPropertyMap");
}
PropertyEditorNodeWrapper::PropertyEditorNodeWrapper(PropertyEditorValue* parent) : QObject(parent), m_valuesPropertyMap(this)
@@ -306,7 +306,7 @@ QmlDesigner::PropertyName PropertyEditorNodeWrapper::propertyName() const
return m_editorValue->name();
}
-QDeclarativePropertyMap* PropertyEditorNodeWrapper::properties()
+QQmlPropertyMap *PropertyEditorNodeWrapper::properties()
{
return &m_valuesPropertyMap;
}
@@ -356,14 +356,14 @@ void PropertyEditorNodeWrapper::changeValue(const QString &propertyName)
if (name.isNull())
return;
if (m_modelNode.isValid()) {
- QmlDesigner::QmlObjectNode fxObjectNode(m_modelNode);
+ QmlDesigner::QmlObjectNode qmlObjectNode(m_modelNode);
PropertyEditorValue *valueObject = qvariant_cast<PropertyEditorValue *>(m_valuesPropertyMap.value(name));
if (valueObject->value().isValid())
- fxObjectNode.setVariantProperty(name, valueObject->value());
+ qmlObjectNode.setVariantProperty(name, valueObject->value());
else
- fxObjectNode.removeVariantProperty(name);
+ qmlObjectNode.removeProperty(name);
}
}
@@ -372,17 +372,17 @@ void PropertyEditorNodeWrapper::setup()
Q_ASSERT(m_editorValue);
Q_ASSERT(m_editorValue->modelNode().isValid());
if ((m_editorValue->modelNode().isValid() && m_modelNode.isValid())) {
- QmlDesigner::QmlObjectNode fxObjectNode(m_modelNode);
+ QmlDesigner::QmlObjectNode qmlObjectNode(m_modelNode);
foreach ( const QString &propertyName, m_valuesPropertyMap.keys())
m_valuesPropertyMap.clear(propertyName);
foreach (QObject *object, m_valuesPropertyMap.children())
delete object;
foreach (const QmlDesigner::PropertyName &propertyName, m_modelNode.metaInfo().propertyNames()) {
- if (fxObjectNode.isValid()) {
+ if (qmlObjectNode.isValid()) {
PropertyEditorValue *valueObject = new PropertyEditorValue(&m_valuesPropertyMap);
valueObject->setName(propertyName);
- valueObject->setValue(fxObjectNode.instanceValue(propertyName));
+ valueObject->setValue(qmlObjectNode.instanceValue(propertyName));
connect(valueObject, SIGNAL(valueChanged(QString,QVariant)), &m_valuesPropertyMap, SIGNAL(valueChanged(QString,QVariant)));
m_valuesPropertyMap.insert(propertyName, QVariant::fromValue(valueObject));
}
diff --git a/src/plugins/qmldesigner/components/propertyeditor/propertyeditorvalue.h b/src/plugins/qmldesigner/components/propertyeditor/propertyeditorvalue.h
index 9f485cc8a6..17c51944ca 100644
--- a/src/plugins/qmldesigner/components/propertyeditor/propertyeditorvalue.h
+++ b/src/plugins/qmldesigner/components/propertyeditor/propertyeditorvalue.h
@@ -33,8 +33,8 @@
#include <qmldesignercorelib_global.h>
#include <QObject>
-#include <QDeclarativePropertyMap>
-#include <qdeclarative.h>
+#include <QQmlPropertyMap>
+#include <QtQml>
#include <modelnode.h>
class PropertyEditorValue;
@@ -43,7 +43,7 @@ class PropertyEditorNodeWrapper : public QObject {
Q_OBJECT
Q_PROPERTY(bool exists READ exists NOTIFY existsChanged)
- Q_PROPERTY(QDeclarativePropertyMap* properties READ properties NOTIFY propertiesChanged)
+ Q_PROPERTY(QQmlPropertyMap* properties READ properties NOTIFY propertiesChanged)
Q_PROPERTY(QString type READ type NOTIFY typeChanged)
public:
@@ -51,7 +51,7 @@ public:
PropertyEditorNodeWrapper(PropertyEditorValue* parent);
bool exists();
QString type();
- QDeclarativePropertyMap* properties();
+ QQmlPropertyMap* properties();
QmlDesigner::ModelNode parentModelNode() const;
QmlDesigner::PropertyName propertyName() const;
@@ -70,7 +70,7 @@ private:
void setup();
QmlDesigner::ModelNode m_modelNode;
- QDeclarativePropertyMap m_valuesPropertyMap;
+ QQmlPropertyMap m_valuesPropertyMap;
PropertyEditorValue* m_editorValue;
};
@@ -152,7 +152,7 @@ private: //variables
QML_DECLARE_TYPE(PropertyEditorValue)
QML_DECLARE_TYPE(PropertyEditorNodeWrapper)
-QML_DECLARE_TYPE(QDeclarativePropertyMap)
+QML_DECLARE_TYPE(QQmlPropertyMap)
#endif // PROPERTYEDITORVALUE_H
diff --git a/src/plugins/qmldesigner/components/propertyeditor/propertyeditorview.cpp b/src/plugins/qmldesigner/components/propertyeditor/propertyeditorview.cpp
new file mode 100644
index 0000000000..594f5265e9
--- /dev/null
+++ b/src/plugins/qmldesigner/components/propertyeditor/propertyeditorview.cpp
@@ -0,0 +1,751 @@
+/****************************************************************************
+**
+** 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 "propertyeditorview.h"
+
+#include "propertyeditorqmlbackend.h"
+#include "propertyeditorvalue.h"
+#include "propertyeditortransaction.h"
+
+#include <qmldesignerconstants.h>
+#include <nodemetainfo.h>
+
+#include <invalididexception.h>
+#include <rewritingexception.h>
+#include <variantproperty.h>
+
+#include <bindingproperty.h>
+
+#include <nodeabstractproperty.h>
+#include <rewriterview.h>
+
+#include <utils/fileutils.h>
+
+#include <QCoreApplication>
+#include <QDir>
+#include <QFileSystemWatcher>
+#include <QFileInfo>
+#include <QDebug>
+#include <QTimer>
+#include <QShortcut>
+#include <QMessageBox>
+#include <QApplication>
+
+enum {
+ debug = false
+};
+
+namespace QmlDesigner {
+
+PropertyEditorView::PropertyEditorView(QWidget *parent) :
+ AbstractView(parent),
+ m_parent(parent),
+ m_updateShortcut(0),
+ m_timerId(0),
+ m_stackedWidget(new PropertyEditorWidget(parent)),
+ m_qmlBackEndForCurrentType(0),
+ m_locked(false),
+ m_setupCompleted(false),
+ m_singleShotTimer(new QTimer(this))
+{
+ m_updateShortcut = new QShortcut(QKeySequence("F3"), m_stackedWidget);
+ connect(m_updateShortcut, SIGNAL(activated()), this, SLOT(reloadQml()));
+
+ m_stackedWidget->setStyleSheet(
+ QLatin1String(Utils::FileReader::fetchQrc(":/qmldesigner/stylesheet.css")));
+ m_stackedWidget->setMinimumWidth(320);
+ m_stackedWidget->move(0, 0);
+ connect(m_stackedWidget, SIGNAL(resized()), this, SLOT(updateSize()));
+
+ m_stackedWidget->insertWidget(0, new QWidget(m_stackedWidget));
+
+ Quick2PropertyEditorView::registerQmlTypes();
+ setQmlDir(PropertyEditorQmlBackend::propertyEditorResourcesPath());
+ m_stackedWidget->setWindowTitle(tr("Properties"));
+}
+
+PropertyEditorView::~PropertyEditorView()
+{
+ qDeleteAll(m_qmlBackendHash);
+}
+
+void PropertyEditorView::setupPane(const TypeName &typeName)
+{
+ NodeMetaInfo metaInfo = model()->metaInfo(typeName);
+
+ QUrl qmlFile = PropertyEditorQmlBackend::getQmlFileUrl(QLatin1String("Qt/ItemPane"), metaInfo);
+ QUrl qmlSpecificsFile;
+
+ qmlSpecificsFile = PropertyEditorQmlBackend::getQmlFileUrl(typeName + "Specifics", metaInfo);
+
+ PropertyEditorQmlBackend *qmlBackend = m_qmlBackendHash.value(qmlFile.toString());
+
+ if (!qmlBackend) {
+ qmlBackend = new PropertyEditorQmlBackend(this);
+
+ qmlBackend->context()->setContextProperty("finishedNotify", QVariant(false) );
+ qmlBackend->initialSetup(typeName, qmlSpecificsFile, this);
+ qmlBackend->setSource(qmlFile);
+ qmlBackend->context()->setContextProperty("finishedNotify", QVariant(true) );
+
+ m_stackedWidget->addWidget(qmlBackend->widget());
+ m_qmlBackendHash.insert(qmlFile.toString(), qmlBackend);
+ } else {
+ qmlBackend->context()->setContextProperty("finishedNotify", QVariant(false) );
+
+ qmlBackend->initialSetup(typeName, qmlSpecificsFile, this);
+ qmlBackend->context()->setContextProperty("finishedNotify", QVariant(true) );
+ }
+}
+
+void PropertyEditorView::changeValue(const QString &name)
+{
+ PropertyName propertyName = name.toUtf8();
+
+ if (propertyName.isNull())
+ return;
+
+ if (m_locked)
+ return;
+
+ if (propertyName == "type")
+ return;
+
+ if (!m_selectedNode.isValid())
+ return;
+
+ if (propertyName == "id") {
+ PropertyEditorValue *value = m_qmlBackEndForCurrentType->propertyValueForName(propertyName);
+ const QString newId = value->value().toString();
+
+ if (newId == m_selectedNode.id())
+ return;
+
+ if (m_selectedNode.isValidId(newId) && !modelNodeForId(newId).isValid() ) {
+ if (m_selectedNode.id().isEmpty() || newId.isEmpty()) { //no id
+ try {
+ m_selectedNode.setId(newId);
+ } catch (InvalidIdException &e) { //better save then sorry
+ m_locked = true;
+ value->setValue(m_selectedNode.id());
+ m_locked = false;
+ QMessageBox::warning(0, tr("Invalid Id"), e.description());
+ }
+ } else { //there is already an id, so we refactor
+ if (rewriterView())
+ rewriterView()->renameId(m_selectedNode.id(), newId);
+ }
+ } else {
+ m_locked = true;
+ value->setValue(m_selectedNode.id());
+ m_locked = false;
+ if (!m_selectedNode.isValidId(newId))
+ QMessageBox::warning(0, tr("Invalid Id"), tr("%1 is an invalid id").arg(newId));
+ else
+ QMessageBox::warning(0, tr("Invalid Id"), tr("%1 already exists").arg(newId));
+ }
+ return;
+ }
+
+ //.replace(QLatin1Char('.'), QLatin1Char('_'))
+ PropertyName underscoreName(propertyName);
+ underscoreName.replace('.', '_');
+ PropertyEditorValue *value = m_qmlBackEndForCurrentType->propertyValueForName(underscoreName);
+
+ if (value ==0)
+ return;
+
+ QmlObjectNode qmlObjectNode(m_selectedNode);
+
+ QVariant castedValue;
+
+ if (qmlObjectNode.modelNode().metaInfo().isValid() && qmlObjectNode.modelNode().metaInfo().hasProperty(propertyName)) {
+ castedValue = qmlObjectNode.modelNode().metaInfo().propertyCastedValue(propertyName, value->value());
+ } else {
+ qWarning() << "PropertyEditor:" <<propertyName << "cannot be casted (metainfo)";
+ return ;
+ }
+
+ if (value->value().isValid() && !castedValue.isValid()) {
+ qWarning() << "PropertyEditor:" << propertyName << "not properly casted (metainfo)";
+ return ;
+ }
+
+ if (qmlObjectNode.modelNode().metaInfo().isValid() && qmlObjectNode.modelNode().metaInfo().hasProperty(propertyName))
+ if (qmlObjectNode.modelNode().metaInfo().propertyTypeName(propertyName) == "QUrl"
+ || qmlObjectNode.modelNode().metaInfo().propertyTypeName(propertyName) == "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));
+ }
+ }
+
+ if (castedValue.type() == QVariant::Color) {
+ QColor color = castedValue.value<QColor>();
+ QColor newColor = QColor(color.name());
+ newColor.setAlpha(color.alpha());
+ castedValue = QVariant(newColor);
+ }
+
+ try {
+ if (!value->value().isValid()) { //reset
+ qmlObjectNode.removeProperty(propertyName);
+ } else {
+ if (castedValue.isValid() && !castedValue.isNull()) {
+ m_locked = true;
+ qmlObjectNode.setVariantProperty(propertyName, castedValue);
+ m_locked = false;
+ }
+ }
+ }
+ catch (RewritingException &e) {
+ QMessageBox::warning(0, "Error", e.description());
+ }
+}
+
+void PropertyEditorView::changeExpression(const QString &propertyName)
+{
+ PropertyName name = propertyName.toUtf8();
+
+ if (name.isNull())
+ return;
+
+ if (m_locked)
+ return;
+
+ RewriterTransaction transaction = beginRewriterTransaction();
+
+ try {
+ PropertyName underscoreName(name);
+ underscoreName.replace('.', '_');
+
+ QmlObjectNode qmlObjectNode(m_selectedNode);
+ PropertyEditorValue *value = m_qmlBackEndForCurrentType->propertyValueForName(underscoreName);
+
+ if (qmlObjectNode.modelNode().metaInfo().isValid() && qmlObjectNode.modelNode().metaInfo().hasProperty(name)) {
+ if (qmlObjectNode.modelNode().metaInfo().propertyTypeName(name) == "QColor") {
+ if (QColor(value->expression().remove('"')).isValid()) {
+ qmlObjectNode.setVariantProperty(name, QColor(value->expression().remove('"')));
+ transaction.commit(); //committing in the try block
+ return;
+ }
+ } else if (qmlObjectNode.modelNode().metaInfo().propertyTypeName(name) == "bool") {
+ if (value->expression().compare("false", Qt::CaseInsensitive) == 0 || value->expression().compare("true", Qt::CaseInsensitive) == 0) {
+ if (value->expression().compare("true", Qt::CaseInsensitive) == 0)
+ qmlObjectNode.setVariantProperty(name, true);
+ else
+ qmlObjectNode.setVariantProperty(name, false);
+ transaction.commit(); //committing in the try block
+ return;
+ }
+ } else if (qmlObjectNode.modelNode().metaInfo().propertyTypeName(name) == "int") {
+ bool ok;
+ int intValue = value->expression().toInt(&ok);
+ if (ok) {
+ qmlObjectNode.setVariantProperty(name, intValue);
+ transaction.commit(); //committing in the try block
+ return;
+ }
+ } else if (qmlObjectNode.modelNode().metaInfo().propertyTypeName(name) == "qreal") {
+ bool ok;
+ qreal realValue = value->expression().toFloat(&ok);
+ if (ok) {
+ qmlObjectNode.setVariantProperty(name, realValue);
+ transaction.commit(); //committing in the try block
+ return;
+ }
+ }
+ }
+
+ if (!value) {
+ qWarning() << "PropertyEditor::changeExpression no value for " << underscoreName;
+ return;
+ }
+
+ if (value->expression().isEmpty())
+ return;
+
+ if (qmlObjectNode.expression(name) != value->expression() || !qmlObjectNode.propertyAffectedByCurrentState(name))
+ qmlObjectNode.setBindingProperty(name, value->expression());
+
+ transaction.commit(); //committing in the try block
+ }
+
+ catch (RewritingException &e) {
+ QMessageBox::warning(0, "Error", e.description());
+ }
+}
+
+void PropertyEditorView::updateSize()
+{
+ if (!m_qmlBackEndForCurrentType)
+ return;
+ QWidget* frame = m_qmlBackEndForCurrentType->widget()->findChild<QWidget*>("propertyEditorFrame");
+ if (frame)
+ frame->resize(m_stackedWidget->size());
+}
+
+void PropertyEditorView::setupPanes()
+{
+ QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+ setupPane("QtQuick.Item");
+ resetView();
+ m_setupCompleted = true;
+ QApplication::restoreOverrideCursor();
+}
+
+void PropertyEditorView::setQmlDir(const QString &qmlDir)
+{
+ m_qmlDir = qmlDir;
+
+
+ QFileSystemWatcher *watcher = new QFileSystemWatcher(this);
+ watcher->addPath(m_qmlDir);
+ connect(watcher, SIGNAL(directoryChanged(QString)), this, SLOT(reloadQml()));
+}
+
+void PropertyEditorView::delayedResetView()
+{
+ if (m_timerId == 0)
+ m_timerId = startTimer(100);
+}
+
+void PropertyEditorView::timerEvent(QTimerEvent *timerEvent)
+{
+ if (m_timerId == timerEvent->timerId())
+ resetView();
+}
+
+void PropertyEditorView::resetView()
+{
+ if (model() == 0)
+ return;
+
+ m_locked = true;
+
+ if (debug)
+ qDebug() << "________________ RELOADING PROPERTY EDITOR QML _______________________";
+
+ if (m_timerId)
+ killTimer(m_timerId);
+
+ if (m_selectedNode.isValid() && model() != m_selectedNode.model())
+ m_selectedNode = ModelNode();
+
+ setupQmlBackend();
+
+ m_locked = false;
+
+ if (m_timerId)
+ m_timerId = 0;
+
+ updateSize();
+}
+
+
+void PropertyEditorView::setupQmlBackend()
+{
+ TypeName specificsClassName;
+ QUrl qmlFile(PropertyEditorQmlBackend::getQmlUrlForModelNode(m_selectedNode, specificsClassName));
+ QUrl qmlSpecificsFile;
+
+ TypeName diffClassName;
+ if (m_selectedNode.isValid()) {
+ diffClassName = m_selectedNode.metaInfo().typeName();
+ QList<NodeMetaInfo> hierarchy;
+ hierarchy << m_selectedNode.metaInfo();
+ hierarchy << m_selectedNode.metaInfo().superClasses();
+
+ foreach (const NodeMetaInfo &metaInfo, hierarchy) {
+ if (PropertyEditorQmlBackend::checkIfUrlExists(qmlSpecificsFile))
+ break;
+ qmlSpecificsFile = PropertyEditorQmlBackend::getQmlFileUrl(metaInfo.typeName() + QLatin1String("Specifics"), metaInfo);
+ diffClassName = metaInfo.typeName();
+ }
+ }
+
+ if (!PropertyEditorQmlBackend::checkIfUrlExists(qmlSpecificsFile))
+ diffClassName = specificsClassName;
+
+ QString specificQmlData;
+
+ if (m_selectedNode.isValid() && m_selectedNode.metaInfo().isValid() && diffClassName != m_selectedNode.type()) {
+ specificQmlData = PropertyEditorQmlBackend::templateGeneration(m_selectedNode.metaInfo(), model()->metaInfo(diffClassName), m_selectedNode);
+ }
+
+ PropertyEditorQmlBackend *currentQmlBackend = m_qmlBackendHash.value(qmlFile.toString());
+
+ QString currentStateName = currentState().isBaseState() ? currentState().name() : QLatin1String("invalid state");
+
+ if (!currentQmlBackend) {
+ currentQmlBackend = new PropertyEditorQmlBackend(this);
+
+ m_stackedWidget->addWidget(currentQmlBackend->widget());
+ m_qmlBackendHash.insert(qmlFile.toString(), currentQmlBackend);
+
+ QmlObjectNode qmlObjectNode;
+ if (m_selectedNode.isValid()) {
+ qmlObjectNode = QmlObjectNode(m_selectedNode);
+ Q_ASSERT(qmlObjectNode.isValid());
+ }
+ currentQmlBackend->setup(qmlObjectNode, currentStateName, qmlSpecificsFile, this);
+ currentQmlBackend->context()->setContextProperty("finishedNotify", QVariant(false));
+ if (specificQmlData.isEmpty())
+ currentQmlBackend->contextObject()->setSpecificQmlData(specificQmlData);
+
+ currentQmlBackend->contextObject()->setGlobalBaseUrl(qmlFile);
+ currentQmlBackend->contextObject()->setSpecificQmlData(specificQmlData);
+ currentQmlBackend->setSource(qmlFile);
+ currentQmlBackend->context()->setContextProperty("finishedNotify", QVariant(true));
+ } else {
+ QmlObjectNode qmlObjectNode;
+ if (m_selectedNode.isValid())
+ qmlObjectNode = QmlObjectNode(m_selectedNode);
+
+ currentQmlBackend->context()->setContextProperty("finishedNotify", QVariant(false));
+ if (specificQmlData.isEmpty())
+ currentQmlBackend->contextObject()->setSpecificQmlData(specificQmlData);
+ currentQmlBackend->setup(qmlObjectNode, currentStateName, qmlSpecificsFile, this);
+ currentQmlBackend->contextObject()->setGlobalBaseUrl(qmlFile);
+ currentQmlBackend->contextObject()->setSpecificQmlData(specificQmlData);
+ }
+
+ m_stackedWidget->setCurrentWidget(currentQmlBackend->widget());
+
+ currentQmlBackend->context()->setContextProperty("finishedNotify", QVariant(true));
+
+ currentQmlBackend->contextObject()->triggerSelectionChanged();
+
+ m_qmlBackEndForCurrentType = currentQmlBackend;
+
+}
+
+void PropertyEditorView::selectedNodesChanged(const QList<ModelNode> &selectedNodeList,
+ const QList<ModelNode> &lastSelectedNodeList)
+{
+ Q_UNUSED(lastSelectedNodeList);
+
+ if (selectedNodeList.isEmpty() || selectedNodeList.count() > 1)
+ select(ModelNode());
+ else if (m_selectedNode != selectedNodeList.first())
+ select(selectedNodeList.first());
+}
+
+void PropertyEditorView::nodeAboutToBeRemoved(const ModelNode &removedNode)
+{
+ if (m_selectedNode.isValid() && removedNode.isValid() && m_selectedNode == removedNode)
+ select(m_selectedNode.parentProperty().parentModelNode());
+}
+
+void PropertyEditorView::modelAttached(Model *model)
+{
+ AbstractView::modelAttached(model);
+
+ if (debug)
+ qDebug() << Q_FUNC_INFO;
+
+ m_locked = true;
+
+ resetView();
+ if (!m_setupCompleted) {
+ m_singleShotTimer->setSingleShot(true);
+ m_singleShotTimer->setInterval(100);
+ connect(m_singleShotTimer, SIGNAL(timeout()), this, SLOT(setupPanes()));
+ m_singleShotTimer->start();
+ }
+
+ m_locked = false;
+}
+
+void PropertyEditorView::modelAboutToBeDetached(Model *model)
+{
+ AbstractView::modelAboutToBeDetached(model);
+ m_qmlBackEndForCurrentType->propertyEditorTransaction()->end();
+
+ resetView();
+}
+
+void PropertyEditorView::propertiesRemoved(const QList<AbstractProperty>& propertyList)
+{
+ if (!m_selectedNode.isValid())
+ return;
+
+ if (!QmlObjectNode(m_selectedNode).isValid())
+ return;
+
+ foreach (const AbstractProperty &property, propertyList) {
+ ModelNode node(property.parentModelNode());
+ if (node == m_selectedNode || QmlObjectNode(m_selectedNode).propertyChangeForCurrentState() == node) {
+ setValue(m_selectedNode, property.name(), QmlObjectNode(m_selectedNode).instanceValue(property.name()));
+ if (property.name().contains("anchor"))
+ m_qmlBackEndForCurrentType->backendAnchorBinding().invalidate(m_selectedNode);
+ }
+ }
+}
+
+void PropertyEditorView::variantPropertiesChanged(const QList<VariantProperty>& propertyList, PropertyChangeFlags /*propertyChange*/)
+{
+
+ if (!m_selectedNode.isValid())
+ return;
+
+ if (!QmlObjectNode(m_selectedNode).isValid())
+ return;
+
+ foreach (const VariantProperty &property, propertyList) {
+ ModelNode node(property.parentModelNode());
+
+ if (node == m_selectedNode || QmlObjectNode(m_selectedNode).propertyChangeForCurrentState() == node) {
+ if ( QmlObjectNode(m_selectedNode).modelNode().property(property.name()).isBindingProperty())
+ setValue(m_selectedNode, property.name(), QmlObjectNode(m_selectedNode).instanceValue(property.name()));
+ else
+ setValue(m_selectedNode, property.name(), QmlObjectNode(m_selectedNode).modelValue(property.name()));
+ }
+ }
+}
+
+void PropertyEditorView::bindingPropertiesChanged(const QList<BindingProperty>& propertyList, PropertyChangeFlags /*propertyChange*/)
+{
+ if (!m_selectedNode.isValid())
+ return;
+
+ if (!QmlObjectNode(m_selectedNode).isValid())
+ return;
+
+ foreach (const BindingProperty &property, propertyList) {
+ ModelNode node(property.parentModelNode());
+
+ if (node == m_selectedNode || QmlObjectNode(m_selectedNode).propertyChangeForCurrentState() == node) {
+ if (property.name().contains("anchor"))
+ m_qmlBackEndForCurrentType->backendAnchorBinding().invalidate(m_selectedNode);
+ if ( QmlObjectNode(m_selectedNode).modelNode().property(property.name()).isBindingProperty())
+ setValue(m_selectedNode, property.name(), QmlObjectNode(m_selectedNode).instanceValue(property.name()));
+ else
+ setValue(m_selectedNode, property.name(), QmlObjectNode(m_selectedNode).modelValue(property.name()));
+ }
+ }
+}
+
+void PropertyEditorView::signalHandlerPropertiesChanged(const QVector<SignalHandlerProperty> & /*propertyList*/,
+ AbstractView::PropertyChangeFlags /*propertyChange*/)
+{
+}
+
+void PropertyEditorView::instanceInformationsChange(const QMultiHash<ModelNode, InformationName> &informationChangeHash)
+{
+ if (!m_selectedNode.isValid())
+ return;
+
+ m_locked = true;
+ QList<InformationName> informationNameList = informationChangeHash.values(m_selectedNode);
+ if (informationNameList.contains(Anchor)
+ || informationNameList.contains(HasAnchor))
+ m_qmlBackEndForCurrentType->backendAnchorBinding().setup(QmlItemNode(m_selectedNode));
+ m_locked = false;
+}
+
+void PropertyEditorView::nodeIdChanged(const ModelNode& node, const QString& newId, const QString& /*oldId*/)
+{
+ if (!m_selectedNode.isValid())
+ return;
+
+ if (!QmlObjectNode(m_selectedNode).isValid())
+ return;
+
+ if (node == m_selectedNode) {
+
+ if (m_qmlBackEndForCurrentType)
+ setValue(node, "id", newId);
+ }
+}
+
+void PropertyEditorView::scriptFunctionsChanged(const ModelNode &/*node*/, const QStringList &/*scriptFunctionList*/)
+{
+}
+
+void PropertyEditorView::select(const ModelNode &node)
+{
+ if (QmlObjectNode(node).isValid())
+ m_selectedNode = node;
+ else
+ m_selectedNode = ModelNode();
+
+ delayedResetView();
+}
+
+bool PropertyEditorView::hasWidget() const
+{
+ return true;
+}
+
+WidgetInfo PropertyEditorView::widgetInfo()
+{
+ return createWidgetInfo(m_stackedWidget, 0, QLatin1String("Properties"), WidgetInfo::RightPane, 0);
+}
+
+void PropertyEditorView::currentStateChanged(const ModelNode &node)
+{
+ QmlModelState newQmlModelState(node);
+ Q_ASSERT(newQmlModelState.isValid());
+ if (debug)
+ qDebug() << Q_FUNC_INFO << newQmlModelState.name();
+ delayedResetView();
+}
+
+void PropertyEditorView::instancePropertyChange(const QList<QPair<ModelNode, PropertyName> > &propertyList)
+{
+ if (!m_selectedNode.isValid())
+ return;
+ m_locked = true;
+
+ typedef QPair<ModelNode, PropertyName> ModelNodePropertyPair;
+ foreach (const ModelNodePropertyPair &propertyPair, propertyList) {
+ const ModelNode modelNode = propertyPair.first;
+ const QmlObjectNode qmlObjectNode(modelNode);
+ const PropertyName propertyName = propertyPair.second;
+
+ if (qmlObjectNode.isValid() && m_qmlBackEndForCurrentType && modelNode == m_selectedNode && qmlObjectNode.currentState().isValid()) {
+ const AbstractProperty property = modelNode.property(propertyName);
+ if (modelNode == m_selectedNode || qmlObjectNode.propertyChangeForCurrentState() == qmlObjectNode) {
+ if ( !modelNode.hasProperty(propertyName) || modelNode.property(property.name()).isBindingProperty() )
+ setValue(modelNode, property.name(), qmlObjectNode.instanceValue(property.name()));
+ else
+ setValue(modelNode, property.name(), qmlObjectNode.modelValue(property.name()));
+ }
+ }
+
+ }
+
+ m_locked = false;
+
+}
+
+void PropertyEditorView::nodeCreated(const ModelNode &/*createdNode*/)
+{
+
+}
+
+void PropertyEditorView::nodeRemoved(const ModelNode &/*removedNode*/, const NodeAbstractProperty &/*parentProperty*/, AbstractView::PropertyChangeFlags /*propertyChange*/)
+{
+
+}
+
+void PropertyEditorView::nodeAboutToBeReparented(const ModelNode &/*node*/, const NodeAbstractProperty &/*newPropertyParent*/, const NodeAbstractProperty &/*oldPropertyParent*/, AbstractView::PropertyChangeFlags /*propertyChange*/)
+{
+
+}
+
+void PropertyEditorView::nodeReparented(const ModelNode &/*node*/, const NodeAbstractProperty &/*newPropertyParent*/, const NodeAbstractProperty &/*oldPropertyParent*/, AbstractView::PropertyChangeFlags /*propertyChange*/)
+{
+
+}
+
+void PropertyEditorView::propertiesAboutToBeRemoved(const QList<AbstractProperty> &/*propertyList*/)
+{
+
+}
+
+void PropertyEditorView::rootNodeTypeChanged(const QString &/*type*/, int /*majorVersion*/, int /*minorVersion*/)
+{
+ // TODO: we should react to this case
+}
+
+void PropertyEditorView::instancesCompleted(const QVector<ModelNode> &/*completedNodeList*/)
+{
+
+}
+
+void PropertyEditorView::instancesRenderImageChanged(const QVector<ModelNode> &/*nodeList*/)
+{
+
+}
+
+void PropertyEditorView::instancesPreviewImageChanged(const QVector<ModelNode> &/*nodeList*/)
+{
+
+}
+
+void PropertyEditorView::instancesChildrenChanged(const QVector<ModelNode> &/*nodeList*/)
+{
+
+}
+
+void PropertyEditorView::instancesToken(const QString &/*tokenName*/, int /*tokenNumber*/, const QVector<ModelNode> &/*nodeVector*/)
+{
+
+}
+
+void PropertyEditorView::nodeSourceChanged(const ModelNode &/*modelNode*/, const QString &/*newNodeSource*/)
+{
+
+}
+
+void PropertyEditorView::rewriterBeginTransaction()
+{
+
+}
+
+void PropertyEditorView::rewriterEndTransaction()
+{
+
+}
+
+void PropertyEditorView::nodeOrderChanged(const NodeListProperty &/*listProperty*/, const ModelNode &/*movedNode*/, int /*oldIndex*/)
+{
+
+}
+
+void PropertyEditorView::importsChanged(const QList<Import> &/*addedImports*/, const QList<Import> &/*removedImports*/)
+{
+
+}
+
+void PropertyEditorView::setValue(const QmlObjectNode &qmlObjectNode, const PropertyName &name, const QVariant &value)
+{
+ m_locked = true;
+ m_qmlBackEndForCurrentType->setValue(qmlObjectNode, name, value);
+ m_locked = false;
+}
+
+void PropertyEditorView::reloadQml()
+{
+ m_qmlBackendHash.clear();
+ while (QWidget *widget = m_stackedWidget->widget(0)) {
+ m_stackedWidget->removeWidget(widget);
+ delete widget;
+ }
+ m_qmlBackEndForCurrentType = 0;
+
+ delayedResetView();
+}
+
+
+} //QmlDesigner
+
diff --git a/src/plugins/qmldesigner/components/propertyeditor/propertyeditor.h b/src/plugins/qmldesigner/components/propertyeditor/propertyeditorview.h
index b590eb24b1..e2ec57e667 100644
--- a/src/plugins/qmldesigner/components/propertyeditor/propertyeditor.h
+++ b/src/plugins/qmldesigner/components/propertyeditor/propertyeditorview.h
@@ -27,19 +27,14 @@
**
****************************************************************************/
-#ifndef PROPERTYEDITOR_H
-#define PROPERTYEDITOR_H
+#ifndef PROPERTYEDITORVIEW_H
+#define PROPERTYEDITORVIEW_H
-#include <qmlmodelview.h>
-#include <declarativewidgetview.h>
+#include <abstractview.h>
#include <QHash>
-#include <QStackedWidget>
#include <QTimer>
-#include "qmlanchorbindingproxy.h"
-#include "designerpropertymap.h"
-#include "propertyeditorvalue.h"
-#include "propertyeditorcontextobject.h"
+#include "propertyeditorwidget.h"
QT_BEGIN_NAMESPACE
class QShortcut;
@@ -47,38 +42,21 @@ class QStackedWidget;
class QTimer;
QT_END_NAMESPACE
-class PropertyEditorValue;
-
namespace QmlDesigner {
class PropertyEditorTransaction;
class CollapseButton;
-class StackedWidget;
+class PropertyEditorWidget;
+class PropertyEditorView;
+class PropertyEditorQmlBackend;
-class PropertyEditor: public QmlModelView
+class PropertyEditorView: public AbstractView
{
Q_OBJECT
- class NodeType {
- public:
- NodeType(PropertyEditor *propertyEditor);
- ~NodeType();
-
- void setup(const QmlObjectNode &fxObjectNode, const QString &stateName, const QUrl &qmlSpecificsFile, PropertyEditor *propertyEditor);
- void initialSetup(const TypeName &typeName, const QUrl &qmlSpecificsFile, PropertyEditor *propertyEditor);
- void setValue(const QmlObjectNode &fxObjectNode, const PropertyName &name, const QVariant &value);
-
- DeclarativeWidgetView *m_view;
- Internal::QmlAnchorBindingProxy m_backendAnchorBinding;
- DesignerPropertyMap<PropertyEditorValue> m_backendValuesPropertyMap;
- QScopedPointer<PropertyEditorTransaction> m_propertyEditorTransaction;
- QScopedPointer<PropertyEditorValue> m_dummyPropertyEditorValue;
- QScopedPointer<PropertyEditorContextObject> m_contextObject;
- };
-
public:
- PropertyEditor(QWidget *parent = 0);
- ~PropertyEditor();
+ PropertyEditorView(QWidget *parent = 0);
+ ~PropertyEditorView();
void setQmlDir(const QString &qmlDirPath);
@@ -107,9 +85,26 @@ public:
void scriptFunctionsChanged(const ModelNode &node, const QStringList &scriptFunctionList) QTC_OVERRIDE;
void resetView();
- void actualStateChanged(const ModelNode &node) QTC_OVERRIDE;
+ void currentStateChanged(const ModelNode &node) QTC_OVERRIDE;
void instancePropertyChange(const QList<QPair<ModelNode, PropertyName> > &propertyList) QTC_OVERRIDE;
+ void nodeCreated(const ModelNode &createdNode) QTC_OVERRIDE;
+ void nodeRemoved(const ModelNode &removedNode, const NodeAbstractProperty &parentProperty, PropertyChangeFlags propertyChange) QTC_OVERRIDE;
+ void nodeAboutToBeReparented(const ModelNode &node, const NodeAbstractProperty &newPropertyParent, const NodeAbstractProperty &oldPropertyParent, PropertyChangeFlags propertyChange) QTC_OVERRIDE;
+ void nodeReparented(const ModelNode &node, const NodeAbstractProperty &newPropertyParent, const NodeAbstractProperty &oldPropertyParent, PropertyChangeFlags propertyChange) QTC_OVERRIDE;
+ void propertiesAboutToBeRemoved(const QList<AbstractProperty> &propertyList) QTC_OVERRIDE;
+ void rootNodeTypeChanged(const QString &type, int majorVersion, int minorVersion) QTC_OVERRIDE;
+ void instancesCompleted(const QVector<ModelNode> &completedNodeList) QTC_OVERRIDE;
+ void instancesRenderImageChanged(const QVector<ModelNode> &nodeList) QTC_OVERRIDE;
+ void instancesPreviewImageChanged(const QVector<ModelNode> &nodeList) QTC_OVERRIDE;
+ void instancesChildrenChanged(const QVector<ModelNode> &nodeList) QTC_OVERRIDE;
+ void instancesToken(const QString &tokenName, int tokenNumber, const QVector<ModelNode> &nodeVector) QTC_OVERRIDE;
+ void nodeSourceChanged(const ModelNode &modelNode, const QString &newNodeSource) QTC_OVERRIDE;
+ void rewriterBeginTransaction() QTC_OVERRIDE;
+ void rewriterEndTransaction() QTC_OVERRIDE;
+ void nodeOrderChanged(const NodeListProperty &listProperty, const ModelNode &movedNode, int oldIndex) QTC_OVERRIDE;
+ void importsChanged(const QList<Import> &addedImports, const QList<Import> &removedImports) QTC_OVERRIDE;
+
protected:
void timerEvent(QTimerEvent *event);
void setupPane(const TypeName &typeName);
@@ -123,47 +118,26 @@ private slots:
void setupPanes();
private: //functions
- QString qmlFileName(const NodeMetaInfo &nodeInfo) const;
- QUrl fileToUrl(const QString &filePath) const;
- QString fileFromUrl(const QUrl &url) const;
- QUrl qmlForNode(const ModelNode &modelNode, TypeName &className) const;
- QString locateQmlFile(const NodeMetaInfo &info, const QString &relativePath) const;
+
void select(const ModelNode& node);
void delayedResetView();
-
+ void setupQmlBackend();
private: //variables
ModelNode m_selectedNode;
QWidget *m_parent;
QShortcut *m_updateShortcut;
int m_timerId;
- StackedWidget* m_stackedWidget;
+ PropertyEditorWidget* m_stackedWidget;
QString m_qmlDir;
- QHash<QString, NodeType *> m_typeHash;
- NodeType *m_currentType;
+ QHash<QString, PropertyEditorQmlBackend *> m_qmlBackendHash;
+ PropertyEditorQmlBackend *m_qmlBackEndForCurrentType;
bool m_locked;
bool m_setupCompleted;
QTimer *m_singleShotTimer;
};
+} //QmlDesigner
-class StackedWidget : public QStackedWidget
-{
-Q_OBJECT
-
-public:
- StackedWidget(QWidget *parent = 0) : QStackedWidget(parent) {}
-
-signals:
- void resized();
-protected:
- void resizeEvent(QResizeEvent * event)
- {
- QStackedWidget::resizeEvent(event);
- emit resized();
- }
-};
-}
-
-#endif // PROPERTYEDITOR_H
+#endif // PROPERTYEDITORVIEW_H
diff --git a/src/plugins/cpptools/cppcompletionsupport.cpp b/src/plugins/qmldesigner/components/propertyeditor/propertyeditorwidget.cpp
index 12665cb6b4..919766d3bf 100644
--- a/src/plugins/cpptools/cppcompletionsupport.cpp
+++ b/src/plugins/qmldesigner/components/propertyeditor/propertyeditorwidget.cpp
@@ -27,16 +27,19 @@
**
****************************************************************************/
-#include "cppcompletionsupport.h"
+#include "propertyeditorwidget.h"
-using namespace CppTools;
-CppCompletionSupport::CppCompletionSupport(TextEditor::ITextEditor *editor)
- : m_editor(editor)
+namespace QmlDesigner {
+
+PropertyEditorWidget::PropertyEditorWidget(QWidget *parent) : QStackedWidget(parent)
{
- Q_ASSERT(editor);
}
-CppCompletionSupport::~CppCompletionSupport()
+void PropertyEditorWidget::resizeEvent(QResizeEvent * event)
{
+ QStackedWidget::resizeEvent(event);
+ emit resized();
+}
+
}
diff --git a/src/plugins/glsleditor/glsleditor_global.h b/src/plugins/qmldesigner/components/propertyeditor/propertyeditorwidget.h
index 94f7a89652..d34e1951fc 100644
--- a/src/plugins/glsleditor/glsleditor_global.h
+++ b/src/plugins/qmldesigner/components/propertyeditor/propertyeditorwidget.h
@@ -27,15 +27,28 @@
**
****************************************************************************/
-#ifndef GLSLEDITOR_GLOBAL_H
-#define GLSLEDITOR_GLOBAL_H
+#ifndef PROPERTYEDITORWIDGET_H
+#define PROPERTYEDITORWIDGET_H
-#include <QtGlobal>
+#include <QStackedWidget>
-#if defined(GLSLEDITOR_LIBRARY)
-# define GLSLEDITOR_EXPORT Q_DECL_EXPORT
-#else
-# define GLSLEDITOR_EXPORT Q_DECL_IMPORT
-#endif
+namespace QmlDesigner {
-#endif // GLSLEDITOR_GLOBAL_H
+class PropertyEditorWidget : public QStackedWidget
+{
+
+Q_OBJECT
+
+public:
+ PropertyEditorWidget(QWidget *parent = 0);
+
+signals:
+ void resized();
+
+protected:
+ void resizeEvent(QResizeEvent * event);
+};
+
+} //QmlDesigner
+
+#endif //PROPERTYEDITORWIDGET_H
diff --git a/src/plugins/qmldesigner/components/propertyeditor/qmlanchorbindingproxy.cpp b/src/plugins/qmldesigner/components/propertyeditor/qmlanchorbindingproxy.cpp
index e4de93c15d..5375d03a0a 100644
--- a/src/plugins/qmldesigner/components/propertyeditor/qmlanchorbindingproxy.cpp
+++ b/src/plugins/qmldesigner/components/propertyeditor/qmlanchorbindingproxy.cpp
@@ -58,7 +58,7 @@ static inline void backupPropertyAndRemove(ModelNode node, const PropertyName &p
static inline void restoreProperty(ModelNode node, const PropertyName &propertyName)
{
if (node.hasAuxiliaryData(auxDataString + propertyName))
- node.variantProperty(propertyName) = node.auxiliaryData(auxDataString + propertyName);
+ node.variantProperty(propertyName).setValue(node.auxiliaryData(auxDataString + propertyName));
}
namespace Internal {
@@ -74,42 +74,46 @@ QmlAnchorBindingProxy::~QmlAnchorBindingProxy()
void QmlAnchorBindingProxy::setup(const QmlItemNode &fxItemNode)
{
- m_fxItemNode = fxItemNode;
+ m_qmlItemNode = fxItemNode;
- m_verticalTarget = m_horizontalTarget = m_topTarget = m_bottomTarget = m_leftTarget = m_rightTarget = m_fxItemNode.modelNode().parentProperty().parentModelNode();
+ if (m_qmlItemNode.modelNode().hasParentProperty()) {
+ setDefaultAnchorTarget(m_qmlItemNode.modelNode().parentProperty().parentModelNode());
+ } else {
+ setDefaultAnchorTarget(ModelNode());
+ }
if (topAnchored()) {
- ModelNode targetNode = m_fxItemNode.anchors().instanceAnchor(AnchorLine::Top).qmlItemNode();
+ ModelNode targetNode = m_qmlItemNode.anchors().instanceAnchor(AnchorLine::Top).qmlItemNode();
if (targetNode.isValid())
m_topTarget = targetNode;
}
if (bottomAnchored()) {
- ModelNode targetNode = m_fxItemNode.anchors().instanceAnchor(AnchorLine::Bottom).qmlItemNode();
+ ModelNode targetNode = m_qmlItemNode.anchors().instanceAnchor(AnchorLine::Bottom).qmlItemNode();
if (targetNode.isValid())
m_bottomTarget = targetNode;
}
if (leftAnchored()) {
- ModelNode targetNode = m_fxItemNode.anchors().instanceAnchor(AnchorLine::Left).qmlItemNode();
+ ModelNode targetNode = m_qmlItemNode.anchors().instanceAnchor(AnchorLine::Left).qmlItemNode();
if (targetNode.isValid())
m_leftTarget = targetNode;
}
if (rightAnchored()) {
- ModelNode targetNode = m_fxItemNode.anchors().instanceAnchor(AnchorLine::Right).qmlItemNode();
+ ModelNode targetNode = m_qmlItemNode.anchors().instanceAnchor(AnchorLine::Right).qmlItemNode();
if (targetNode.isValid())
m_rightTarget = targetNode;
}
if (verticalCentered()) {
- ModelNode targetNode = m_fxItemNode.anchors().instanceAnchor(AnchorLine::VerticalCenter).qmlItemNode();
+ ModelNode targetNode = m_qmlItemNode.anchors().instanceAnchor(AnchorLine::VerticalCenter).qmlItemNode();
if (targetNode.isValid())
m_verticalTarget = targetNode;
}
if (horizontalCentered()) {
- ModelNode targetNode = m_fxItemNode.anchors().instanceAnchor(AnchorLine::HorizontalCenter).qmlItemNode();
+ ModelNode targetNode = m_qmlItemNode.anchors().instanceAnchor(AnchorLine::HorizontalCenter).qmlItemNode();
if (targetNode.isValid())
m_horizontalTarget = targetNode;
}
@@ -124,7 +128,7 @@ void QmlAnchorBindingProxy::setup(const QmlItemNode &fxItemNode)
emit centeredVChanged();
emit anchorsChanged();
- if (m_fxItemNode.hasNodeParent()) {
+ if (m_qmlItemNode.hasNodeParent()) {
emit itemNodeChanged();
emit topTargetChanged();
emit bottomTargetChanged();
@@ -140,42 +144,42 @@ void QmlAnchorBindingProxy::invalidate(const QmlItemNode &fxItemNode)
if (m_locked)
return;
- m_fxItemNode = fxItemNode;
+ m_qmlItemNode = fxItemNode;
- m_verticalTarget = m_horizontalTarget = m_topTarget = m_bottomTarget = m_leftTarget = m_rightTarget = m_fxItemNode.modelNode().parentProperty().parentModelNode();
+ m_verticalTarget = m_horizontalTarget = m_topTarget = m_bottomTarget = m_leftTarget = m_rightTarget = m_qmlItemNode.modelNode().parentProperty().parentModelNode();
if (topAnchored()) {
- ModelNode targetNode = m_fxItemNode.anchors().instanceAnchor(AnchorLine::Top).qmlItemNode();
+ ModelNode targetNode = m_qmlItemNode.anchors().instanceAnchor(AnchorLine::Top).qmlItemNode();
if (targetNode.isValid())
m_topTarget = targetNode;
}
if (bottomAnchored()) {
- ModelNode targetNode = m_fxItemNode.anchors().instanceAnchor(AnchorLine::Bottom).qmlItemNode();
+ ModelNode targetNode = m_qmlItemNode.anchors().instanceAnchor(AnchorLine::Bottom).qmlItemNode();
if (targetNode.isValid())
m_bottomTarget = targetNode;
}
if (leftAnchored()) {
- ModelNode targetNode = m_fxItemNode.anchors().instanceAnchor(AnchorLine::Left).qmlItemNode();
+ ModelNode targetNode = m_qmlItemNode.anchors().instanceAnchor(AnchorLine::Left).qmlItemNode();
if (targetNode.isValid())
m_leftTarget = targetNode;
}
if (rightAnchored()) {
- ModelNode targetNode = m_fxItemNode.anchors().instanceAnchor(AnchorLine::Right).qmlItemNode();
+ ModelNode targetNode = m_qmlItemNode.anchors().instanceAnchor(AnchorLine::Right).qmlItemNode();
if (targetNode.isValid())
m_rightTarget = targetNode;
}
if (verticalCentered()) {
- ModelNode targetNode = m_fxItemNode.anchors().instanceAnchor(AnchorLine::VerticalCenter).qmlItemNode();
+ ModelNode targetNode = m_qmlItemNode.anchors().instanceAnchor(AnchorLine::VerticalCenter).qmlItemNode();
if (targetNode.isValid())
m_verticalTarget = targetNode;
}
if (horizontalCentered()) {
- ModelNode targetNode = m_fxItemNode.anchors().instanceAnchor(AnchorLine::HorizontalCenter).qmlItemNode();
+ ModelNode targetNode = m_qmlItemNode.anchors().instanceAnchor(AnchorLine::HorizontalCenter).qmlItemNode();
if (targetNode.isValid())
m_horizontalTarget = targetNode;
}
@@ -188,7 +192,7 @@ void QmlAnchorBindingProxy::invalidate(const QmlItemNode &fxItemNode)
emit centeredVChanged();
emit anchorsChanged();
- if (m_fxItemNode.hasNodeParent()) {
+ if (m_qmlItemNode.hasNodeParent()) {
emit itemNodeChanged();
emit topTargetChanged();
emit bottomTargetChanged();
@@ -201,41 +205,41 @@ void QmlAnchorBindingProxy::invalidate(const QmlItemNode &fxItemNode)
bool QmlAnchorBindingProxy::hasParent()
{
- return m_fxItemNode.isValid() && m_fxItemNode.hasNodeParent();
+ return m_qmlItemNode.isValid() && m_qmlItemNode.hasNodeParent();
}
bool QmlAnchorBindingProxy::isFilled()
{
- return m_fxItemNode.isValid() && hasAnchors() && topAnchored() && bottomAnchored() && leftAnchored() && rightAnchored()
- && (m_fxItemNode.instanceValue("anchors.topMargin").toInt() == 0)
- && (m_fxItemNode.instanceValue("anchors.bottomMargin").toInt() == 0)
- && (m_fxItemNode.instanceValue("anchors.leftMargin").toInt() == 0)
- && (m_fxItemNode.instanceValue("anchors.rightMargin").toInt() == 0);
+ return m_qmlItemNode.isValid() && hasAnchors() && topAnchored() && bottomAnchored() && leftAnchored() && rightAnchored()
+ && (m_qmlItemNode.instanceValue("anchors.topMargin").toInt() == 0)
+ && (m_qmlItemNode.instanceValue("anchors.bottomMargin").toInt() == 0)
+ && (m_qmlItemNode.instanceValue("anchors.leftMargin").toInt() == 0)
+ && (m_qmlItemNode.instanceValue("anchors.rightMargin").toInt() == 0);
}
bool QmlAnchorBindingProxy::topAnchored()
{
- return m_fxItemNode.isValid() && m_fxItemNode.anchors().instanceHasAnchor(AnchorLine::Top);
+ return m_qmlItemNode.isValid() && m_qmlItemNode.anchors().instanceHasAnchor(AnchorLine::Top);
}
bool QmlAnchorBindingProxy::bottomAnchored()
{
- return m_fxItemNode.isValid() && m_fxItemNode.anchors().instanceHasAnchor(AnchorLine::Bottom);
+ return m_qmlItemNode.isValid() && m_qmlItemNode.anchors().instanceHasAnchor(AnchorLine::Bottom);
}
bool QmlAnchorBindingProxy::leftAnchored()
{
- return m_fxItemNode.isValid() && m_fxItemNode.anchors().instanceHasAnchor(AnchorLine::Left);
+ return m_qmlItemNode.isValid() && m_qmlItemNode.anchors().instanceHasAnchor(AnchorLine::Left);
}
bool QmlAnchorBindingProxy::rightAnchored()
{
- return m_fxItemNode.isValid() && m_fxItemNode.anchors().instanceHasAnchor(AnchorLine::Right);
+ return m_qmlItemNode.isValid() && m_qmlItemNode.anchors().instanceHasAnchor(AnchorLine::Right);
}
bool QmlAnchorBindingProxy::hasAnchors()
{
- return m_fxItemNode.isValid() && m_fxItemNode.anchors().instanceHasAnchors();
+ return m_qmlItemNode.isValid() && m_qmlItemNode.anchors().instanceHasAnchors();
}
@@ -246,7 +250,7 @@ void QmlAnchorBindingProxy::setTopTarget(const QVariant &target)
if (newTarget == m_topTarget)
return;
- RewriterTransaction transaction = m_fxItemNode.modelNode().view()->beginRewriterTransaction();
+ RewriterTransaction transaction = m_qmlItemNode.modelNode().view()->beginRewriterTransaction();
m_topTarget = newTarget;
calcTopMargin();
@@ -262,7 +266,7 @@ void QmlAnchorBindingProxy::setBottomTarget(const QVariant &target)
if (newTarget == m_bottomTarget)
return;
- RewriterTransaction transaction = m_fxItemNode.modelNode().view()->beginRewriterTransaction();
+ RewriterTransaction transaction = m_qmlItemNode.modelNode().view()->beginRewriterTransaction();
m_bottomTarget = newTarget;
calcBottomMargin();
@@ -277,7 +281,7 @@ void QmlAnchorBindingProxy::setLeftTarget(const QVariant &target)
if (newTarget == m_leftTarget)
return;
- RewriterTransaction transaction = m_fxItemNode.modelNode().view()->beginRewriterTransaction();
+ RewriterTransaction transaction = m_qmlItemNode.modelNode().view()->beginRewriterTransaction();
m_leftTarget = newTarget;
calcLeftMargin();
@@ -292,7 +296,7 @@ void QmlAnchorBindingProxy::setRightTarget(const QVariant &target)
if (newTarget == m_rightTarget)
return;
- RewriterTransaction transaction = m_fxItemNode.modelNode().view()->beginRewriterTransaction();
+ RewriterTransaction transaction = m_qmlItemNode.modelNode().view()->beginRewriterTransaction();
m_rightTarget = newTarget;
calcRightMargin();
@@ -307,10 +311,10 @@ void QmlAnchorBindingProxy::setVerticalTarget(const QVariant &target)
if (newTarget == m_verticalTarget)
return;
- RewriterTransaction transaction = m_fxItemNode.modelNode().view()->beginRewriterTransaction();
+ RewriterTransaction transaction = m_qmlItemNode.modelNode().view()->beginRewriterTransaction();
m_verticalTarget = newTarget;
- m_fxItemNode.anchors().setAnchor(AnchorLine::VerticalCenter, m_verticalTarget, AnchorLine::VerticalCenter);
+ m_qmlItemNode.anchors().setAnchor(AnchorLine::VerticalCenter, m_verticalTarget, AnchorLine::VerticalCenter);
emit verticalTargetChanged();
}
@@ -322,19 +326,19 @@ void QmlAnchorBindingProxy::setHorizontalTarget(const QVariant &target)
if (newTarget == m_horizontalTarget)
return;
- RewriterTransaction transaction = m_fxItemNode.modelNode().view()->beginRewriterTransaction();
+ RewriterTransaction transaction = m_qmlItemNode.modelNode().view()->beginRewriterTransaction();
m_horizontalTarget = newTarget;
- m_fxItemNode.anchors().setAnchor(AnchorLine::HorizontalCenter, m_horizontalTarget, AnchorLine::HorizontalCenter);
+ m_qmlItemNode.anchors().setAnchor(AnchorLine::HorizontalCenter, m_horizontalTarget, AnchorLine::HorizontalCenter);
emit horizontalTargetChanged();
}
void QmlAnchorBindingProxy::resetLayout() {
- RewriterTransaction transaction = m_fxItemNode.modelNode().view()->beginRewriterTransaction();
+ RewriterTransaction transaction = m_qmlItemNode.modelNode().view()->beginRewriterTransaction();
- m_fxItemNode.anchors().removeAnchors();
- m_fxItemNode.anchors().removeMargins();
+ m_qmlItemNode.anchors().removeAnchors();
+ m_qmlItemNode.anchors().removeMargins();
restoreProperty(modelNode(), "x");
restoreProperty(modelNode(), "y");
@@ -350,13 +354,13 @@ void QmlAnchorBindingProxy::resetLayout() {
void QmlAnchorBindingProxy::setBottomAnchor(bool anchor)
{
- if (!m_fxItemNode.hasNodeParent())
+ if (!m_qmlItemNode.hasNodeParent())
return;
if (bottomAnchored() == anchor)
return;
- RewriterTransaction transaction = m_fxItemNode.modelNode().view()->beginRewriterTransaction();
+ RewriterTransaction transaction = m_qmlItemNode.modelNode().view()->beginRewriterTransaction();
if (!anchor) {
removeBottomAnchor();
@@ -373,13 +377,13 @@ void QmlAnchorBindingProxy::setBottomAnchor(bool anchor)
void QmlAnchorBindingProxy::setLeftAnchor(bool anchor)
{
- if (!m_fxItemNode.hasNodeParent())
+ if (!m_qmlItemNode.hasNodeParent())
return;
if (leftAnchored() == anchor)
return;
- RewriterTransaction transaction = m_fxItemNode.modelNode().view()->beginRewriterTransaction();
+ RewriterTransaction transaction = m_qmlItemNode.modelNode().view()->beginRewriterTransaction();
if (!anchor) {
removeLeftAnchor();
@@ -397,13 +401,13 @@ void QmlAnchorBindingProxy::setLeftAnchor(bool anchor)
void QmlAnchorBindingProxy::setRightAnchor(bool anchor)
{
- if (!m_fxItemNode.hasNodeParent())
+ if (!m_qmlItemNode.hasNodeParent())
return;
if (rightAnchored() == anchor)
return;
- RewriterTransaction transaction = m_fxItemNode.modelNode().view()->beginRewriterTransaction();
+ RewriterTransaction transaction = m_qmlItemNode.modelNode().view()->beginRewriterTransaction();
if (!anchor) {
removeRightAnchor();
@@ -418,10 +422,10 @@ void QmlAnchorBindingProxy::setRightAnchor(bool anchor)
}
QRectF QmlAnchorBindingProxy::parentBoundingBox()
{
- if (m_fxItemNode.hasInstanceParent()) {
- if (m_fxItemNode.instanceParent().toQmlItemNode().instanceContentItemBoundingRect().isValid())
- return m_fxItemNode.instanceParent().toQmlItemNode().instanceContentItemBoundingRect();
- return m_fxItemNode.instanceParent().toQmlItemNode().instanceBoundingRect();
+ if (m_qmlItemNode.hasInstanceParent()) {
+ if (m_qmlItemNode.instanceParentItem().instanceContentItemBoundingRect().isValid())
+ return m_qmlItemNode.instanceParentItem().instanceContentItemBoundingRect();
+ return m_qmlItemNode.instanceParentItem().instanceBoundingRect();
}
return QRect();
@@ -430,28 +434,28 @@ void QmlAnchorBindingProxy::setRightAnchor(bool anchor)
QRectF QmlAnchorBindingProxy::boundingBox(QmlItemNode node)
{
if (node.isValid())
- return node.instanceTransform().mapRect(node.instanceBoundingRect());
+ return node.instanceTransformWithContentTransform().mapRect(node.instanceBoundingRect());
return QRect();
}
QRectF QmlAnchorBindingProxy::transformedBoundingBox()
{
- return m_fxItemNode.instanceTransformWithContentTransform().mapRect(m_fxItemNode.instanceBoundingRect());
+ return m_qmlItemNode.instanceTransformWithContentTransform().mapRect(m_qmlItemNode.instanceBoundingRect());
}
void QmlAnchorBindingProxy::calcTopMargin()
{
m_locked = true;
- if (m_topTarget.modelNode() == m_fxItemNode.modelNode().parentProperty().parentModelNode()) {
+ if (m_topTarget.modelNode() == m_qmlItemNode.modelNode().parentProperty().parentModelNode()) {
qreal topMargin = transformedBoundingBox().top() - parentBoundingBox().top();
- m_fxItemNode.anchors().setMargin( AnchorLine::Top, topMargin);
- m_fxItemNode.anchors().setAnchor(AnchorLine::Top, m_topTarget, AnchorLine::Top);
+ m_qmlItemNode.anchors().setMargin( AnchorLine::Top, topMargin);
+ m_qmlItemNode.anchors().setAnchor(AnchorLine::Top, m_topTarget, AnchorLine::Top);
} else {
- qreal topMargin = boundingBox(m_fxItemNode).top() - boundingBox(m_topTarget).bottom();
- m_fxItemNode.anchors().setMargin( AnchorLine::Top, topMargin);
- m_fxItemNode.anchors().setAnchor(AnchorLine::Top, m_topTarget, AnchorLine::Bottom);
+ qreal topMargin = boundingBox(m_qmlItemNode).top() - boundingBox(m_topTarget).bottom();
+ m_qmlItemNode.anchors().setMargin( AnchorLine::Top, topMargin);
+ m_qmlItemNode.anchors().setAnchor(AnchorLine::Top, m_topTarget, AnchorLine::Bottom);
}
m_locked = false;
@@ -461,14 +465,14 @@ void QmlAnchorBindingProxy::calcBottomMargin()
{
m_locked = true;
- if (m_bottomTarget.modelNode() == m_fxItemNode.modelNode().parentProperty().parentModelNode()) {
+ if (m_bottomTarget.modelNode() == m_qmlItemNode.modelNode().parentProperty().parentModelNode()) {
qreal bottomMargin = parentBoundingBox().bottom() - transformedBoundingBox().bottom();
- m_fxItemNode.anchors().setMargin( AnchorLine::Bottom, bottomMargin);
- m_fxItemNode.anchors().setAnchor(AnchorLine::Bottom, m_bottomTarget, AnchorLine::Bottom);
+ m_qmlItemNode.anchors().setMargin( AnchorLine::Bottom, bottomMargin);
+ m_qmlItemNode.anchors().setAnchor(AnchorLine::Bottom, m_bottomTarget, AnchorLine::Bottom);
} else {
- qreal bottomMargin = boundingBox(m_bottomTarget).top()- boundingBox(m_fxItemNode).bottom();
- m_fxItemNode.anchors().setMargin( AnchorLine::Bottom, bottomMargin);
- m_fxItemNode.anchors().setAnchor(AnchorLine::Bottom, m_bottomTarget, AnchorLine::Top);
+ qreal bottomMargin = boundingBox(m_bottomTarget).top()- boundingBox(m_qmlItemNode).bottom();
+ m_qmlItemNode.anchors().setMargin( AnchorLine::Bottom, bottomMargin);
+ m_qmlItemNode.anchors().setAnchor(AnchorLine::Bottom, m_bottomTarget, AnchorLine::Top);
}
m_locked = false;
@@ -478,14 +482,14 @@ void QmlAnchorBindingProxy::calcLeftMargin()
{
m_locked = true;
- if (m_leftTarget.modelNode() == m_fxItemNode.modelNode().parentProperty().parentModelNode()) {
+ if (m_leftTarget.modelNode() == m_qmlItemNode.modelNode().parentProperty().parentModelNode()) {
qreal leftMargin = transformedBoundingBox().left() - parentBoundingBox().left();
- m_fxItemNode.anchors().setMargin(AnchorLine::Left, leftMargin);
- m_fxItemNode.anchors().setAnchor(AnchorLine::Left, m_leftTarget, AnchorLine::Left);
+ m_qmlItemNode.anchors().setMargin(AnchorLine::Left, leftMargin);
+ m_qmlItemNode.anchors().setAnchor(AnchorLine::Left, m_leftTarget, AnchorLine::Left);
} else {
- qreal leftMargin = boundingBox(m_fxItemNode).left() - boundingBox(m_leftTarget).right();
- m_fxItemNode.anchors().setMargin( AnchorLine::Left, leftMargin);
- m_fxItemNode.anchors().setAnchor(AnchorLine::Left, m_leftTarget, AnchorLine::Right);
+ qreal leftMargin = boundingBox(m_qmlItemNode).left() - boundingBox(m_leftTarget).right();
+ m_qmlItemNode.anchors().setMargin( AnchorLine::Left, leftMargin);
+ m_qmlItemNode.anchors().setAnchor(AnchorLine::Left, m_leftTarget, AnchorLine::Right);
}
m_locked = false;
@@ -495,14 +499,14 @@ void QmlAnchorBindingProxy::calcRightMargin()
{
m_locked = true;
- if (m_rightTarget.modelNode() == m_fxItemNode.modelNode().parentProperty().parentModelNode()) {
+ if (m_rightTarget.modelNode() == m_qmlItemNode.modelNode().parentProperty().parentModelNode()) {
qreal rightMargin = parentBoundingBox().right() - transformedBoundingBox().right();
- m_fxItemNode.anchors().setMargin( AnchorLine::Right, rightMargin);
- m_fxItemNode.anchors().setAnchor(AnchorLine::Right, m_rightTarget, AnchorLine::Right);
+ m_qmlItemNode.anchors().setMargin( AnchorLine::Right, rightMargin);
+ m_qmlItemNode.anchors().setAnchor(AnchorLine::Right, m_rightTarget, AnchorLine::Right);
} else {
- qreal rightMargin = boundingBox(m_rightTarget).left() - boundingBox(m_fxItemNode).right();
- m_fxItemNode.anchors().setMargin( AnchorLine::Right, rightMargin);
- m_fxItemNode.anchors().setAnchor(AnchorLine::Right, m_rightTarget, AnchorLine::Left);
+ qreal rightMargin = boundingBox(m_rightTarget).left() - boundingBox(m_qmlItemNode).right();
+ m_qmlItemNode.anchors().setMargin( AnchorLine::Right, rightMargin);
+ m_qmlItemNode.anchors().setAnchor(AnchorLine::Right, m_rightTarget, AnchorLine::Left);
}
m_locked = false;
@@ -510,18 +514,18 @@ void QmlAnchorBindingProxy::calcRightMargin()
ModelNode QmlAnchorBindingProxy::modelNode() const
{
- return m_fxItemNode.modelNode();
+ return m_qmlItemNode.modelNode();
}
void QmlAnchorBindingProxy::setTopAnchor(bool anchor)
{
- if (!m_fxItemNode.hasNodeParent())
+ if (!m_qmlItemNode.hasNodeParent())
return ;
if (topAnchored() == anchor)
return;
- RewriterTransaction transaction = m_fxItemNode.modelNode().view()->beginRewriterTransaction();
+ RewriterTransaction transaction = m_qmlItemNode.modelNode().view()->beginRewriterTransaction();
if (!anchor) {
removeTopAnchor();
@@ -537,10 +541,10 @@ void QmlAnchorBindingProxy::setTopAnchor(bool anchor)
}
void QmlAnchorBindingProxy::removeTopAnchor() {
- RewriterTransaction transaction = m_fxItemNode.modelNode().view()->beginRewriterTransaction();
+ RewriterTransaction transaction = m_qmlItemNode.modelNode().view()->beginRewriterTransaction();
- m_fxItemNode.anchors().removeAnchor(AnchorLine::Top);
- m_fxItemNode.anchors().removeMargin(AnchorLine::Top);
+ m_qmlItemNode.anchors().removeAnchor(AnchorLine::Top);
+ m_qmlItemNode.anchors().removeMargin(AnchorLine::Top);
restoreProperty(modelNode(), "y");
restoreProperty(modelNode(), "height");
@@ -548,37 +552,37 @@ void QmlAnchorBindingProxy::removeTopAnchor() {
}
void QmlAnchorBindingProxy::removeBottomAnchor() {
- RewriterTransaction transaction = m_fxItemNode.modelNode().view()->beginRewriterTransaction();
+ RewriterTransaction transaction = m_qmlItemNode.modelNode().view()->beginRewriterTransaction();
- m_fxItemNode.anchors().removeAnchor(AnchorLine::Bottom);
- m_fxItemNode.anchors().removeMargin(AnchorLine::Bottom);
+ m_qmlItemNode.anchors().removeAnchor(AnchorLine::Bottom);
+ m_qmlItemNode.anchors().removeMargin(AnchorLine::Bottom);
restoreProperty(modelNode(), "height");
}
void QmlAnchorBindingProxy::removeLeftAnchor() {
- RewriterTransaction transaction = m_fxItemNode.modelNode().view()->beginRewriterTransaction();
+ RewriterTransaction transaction = m_qmlItemNode.modelNode().view()->beginRewriterTransaction();
- m_fxItemNode.anchors().removeAnchor(AnchorLine::Left);
- m_fxItemNode.anchors().removeMargin(AnchorLine::Left);
+ m_qmlItemNode.anchors().removeAnchor(AnchorLine::Left);
+ m_qmlItemNode.anchors().removeMargin(AnchorLine::Left);
restoreProperty(modelNode(), "x");
restoreProperty(modelNode(), "width");
}
void QmlAnchorBindingProxy::removeRightAnchor() {
- RewriterTransaction transaction = m_fxItemNode.modelNode().view()->beginRewriterTransaction();
+ RewriterTransaction transaction = m_qmlItemNode.modelNode().view()->beginRewriterTransaction();
- m_fxItemNode.anchors().removeAnchor(AnchorLine::Right);
- m_fxItemNode.anchors().removeMargin(AnchorLine::Right);
+ m_qmlItemNode.anchors().removeAnchor(AnchorLine::Right);
+ m_qmlItemNode.anchors().removeMargin(AnchorLine::Right);
restoreProperty(modelNode(), "width");
}
void QmlAnchorBindingProxy::setVerticalCentered(bool centered)
{
- if (!m_fxItemNode.hasNodeParent())
+ if (!m_qmlItemNode.hasNodeParent())
return ;
if (verticalCentered() == centered)
@@ -586,13 +590,13 @@ void QmlAnchorBindingProxy::setVerticalCentered(bool centered)
m_locked = true;
- RewriterTransaction transaction = m_fxItemNode.modelNode().view()->beginRewriterTransaction();
+ RewriterTransaction transaction = m_qmlItemNode.modelNode().view()->beginRewriterTransaction();
if (!centered) {
- m_fxItemNode.anchors().removeAnchor(AnchorLine::VerticalCenter);
- m_fxItemNode.anchors().removeMargin(AnchorLine::VerticalCenter);
+ m_qmlItemNode.anchors().removeAnchor(AnchorLine::VerticalCenter);
+ m_qmlItemNode.anchors().removeMargin(AnchorLine::VerticalCenter);
} else {
- m_fxItemNode.anchors().setAnchor(AnchorLine::VerticalCenter, m_fxItemNode.modelNode().parentProperty().parentModelNode(), AnchorLine::VerticalCenter);
+ m_qmlItemNode.anchors().setAnchor(AnchorLine::VerticalCenter, m_qmlItemNode.modelNode().parentProperty().parentModelNode(), AnchorLine::VerticalCenter);
}
m_locked = false;
@@ -602,7 +606,7 @@ void QmlAnchorBindingProxy::setVerticalCentered(bool centered)
void QmlAnchorBindingProxy::setHorizontalCentered(bool centered)
{
- if (!m_fxItemNode.hasNodeParent())
+ if (!m_qmlItemNode.hasNodeParent())
return ;
if (horizontalCentered() == centered)
@@ -610,13 +614,13 @@ void QmlAnchorBindingProxy::setHorizontalCentered(bool centered)
m_locked = true;
- RewriterTransaction transaction = m_fxItemNode.modelNode().view()->beginRewriterTransaction();
+ RewriterTransaction transaction = m_qmlItemNode.modelNode().view()->beginRewriterTransaction();
if (!centered) {
- m_fxItemNode.anchors().removeAnchor(AnchorLine::HorizontalCenter);
- m_fxItemNode.anchors().removeMargin(AnchorLine::HorizontalCenter);
+ m_qmlItemNode.anchors().removeAnchor(AnchorLine::HorizontalCenter);
+ m_qmlItemNode.anchors().removeMargin(AnchorLine::HorizontalCenter);
} else {
- m_fxItemNode.anchors().setAnchor(AnchorLine::HorizontalCenter, m_fxItemNode.modelNode().parentProperty().parentModelNode(), AnchorLine::HorizontalCenter);
+ m_qmlItemNode.anchors().setAnchor(AnchorLine::HorizontalCenter, m_qmlItemNode.modelNode().parentProperty().parentModelNode(), AnchorLine::HorizontalCenter);
}
m_locked = false;
@@ -626,18 +630,18 @@ void QmlAnchorBindingProxy::setHorizontalCentered(bool centered)
bool QmlAnchorBindingProxy::verticalCentered()
{
- return m_fxItemNode.isValid() && m_fxItemNode.anchors().instanceHasAnchor(AnchorLine::VerticalCenter);
+ return m_qmlItemNode.isValid() && m_qmlItemNode.anchors().instanceHasAnchor(AnchorLine::VerticalCenter);
}
bool QmlAnchorBindingProxy::horizontalCentered()
{
- return m_fxItemNode.isValid() && m_fxItemNode.anchors().instanceHasAnchor(AnchorLine::HorizontalCenter);
+ return m_qmlItemNode.isValid() && m_qmlItemNode.anchors().instanceHasAnchor(AnchorLine::HorizontalCenter);
}
void QmlAnchorBindingProxy::fill()
{
- RewriterTransaction transaction = m_fxItemNode.modelNode().view()->beginRewriterTransaction();
+ RewriterTransaction transaction = m_qmlItemNode.modelNode().view()->beginRewriterTransaction();
backupPropertyAndRemove(modelNode(), "x");
@@ -645,15 +649,15 @@ void QmlAnchorBindingProxy::fill()
backupPropertyAndRemove(modelNode(), "width");
backupPropertyAndRemove(modelNode(), "height");
- m_fxItemNode.anchors().fill();
+ m_qmlItemNode.anchors().fill();
setHorizontalCentered(false);
setVerticalCentered(false);
- m_fxItemNode.anchors().removeMargin(AnchorLine::Right);
- m_fxItemNode.anchors().removeMargin(AnchorLine::Left);
- m_fxItemNode.anchors().removeMargin(AnchorLine::Top);
- m_fxItemNode.anchors().removeMargin(AnchorLine::Bottom);
+ m_qmlItemNode.anchors().removeMargin(AnchorLine::Right);
+ m_qmlItemNode.anchors().removeMargin(AnchorLine::Left);
+ m_qmlItemNode.anchors().removeMargin(AnchorLine::Top);
+ m_qmlItemNode.anchors().removeMargin(AnchorLine::Bottom);
emit topAnchorChanged();
emit bottomAnchorChanged();
@@ -662,6 +666,16 @@ void QmlAnchorBindingProxy::fill()
emit anchorsChanged();
}
+void QmlAnchorBindingProxy::setDefaultAnchorTarget(const ModelNode &modelNode)
+{
+ m_verticalTarget = modelNode;
+ m_horizontalTarget = modelNode;
+ m_topTarget = modelNode;
+ m_bottomTarget = modelNode;
+ m_leftTarget = modelNode;
+ m_rightTarget = modelNode;
+}
+
} // namespace Internal
} // namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/components/propertyeditor/qmlanchorbindingproxy.h b/src/plugins/qmldesigner/components/propertyeditor/qmlanchorbindingproxy.h
index fe7567c290..619fcf0c5c 100644
--- a/src/plugins/qmldesigner/components/propertyeditor/qmlanchorbindingproxy.h
+++ b/src/plugins/qmldesigner/components/propertyeditor/qmlanchorbindingproxy.h
@@ -92,7 +92,7 @@ public:
bool horizontalCentered();
bool verticalCentered();
- QVariant itemNode() const { return QVariant::fromValue(m_fxItemNode.modelNode()); }
+ QVariant itemNode() const { return QVariant::fromValue(m_qmlItemNode.modelNode()); }
QVariant topTarget() const { return QVariant::fromValue(m_topTarget.modelNode()); }
QVariant bottomTarget() const { return QVariant::fromValue(m_bottomTarget.modelNode()); }
@@ -143,7 +143,7 @@ signals:
void horizontalTargetChanged();
private:
-
+ void setDefaultAnchorTarget(const ModelNode &modelNode);
void calcTopMargin();
void calcBottomMargin();
void calcLeftMargin();
@@ -151,7 +151,7 @@ private:
ModelNode modelNode() const;
- QmlItemNode m_fxItemNode;
+ QmlItemNode m_qmlItemNode;
QRectF parentBoundingBox();
diff --git a/src/plugins/qmldesigner/components/propertyeditor/quick2propertyeditorview.cpp b/src/plugins/qmldesigner/components/propertyeditor/quick2propertyeditorview.cpp
new file mode 100644
index 0000000000..4184dc1bc6
--- /dev/null
+++ b/src/plugins/qmldesigner/components/propertyeditor/quick2propertyeditorview.cpp
@@ -0,0 +1,112 @@
+/****************************************************************************
+**
+** 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 "quick2propertyeditorview.h"
+
+#include "propertyeditorvalue.h"
+
+#include <QVBoxLayout>
+
+namespace QmlDesigner {
+
+void Quick2PropertyEditorView::execute()
+{
+ m_view.setSource(m_source);
+
+ if (!m_source.isEmpty()) {
+ m_view.setSource(m_source);
+ connect(&m_view, SIGNAL(statusChanged(QQuickView::Status)), this, SLOT(continueExecute()));
+ }
+}
+
+Quick2PropertyEditorView::Quick2PropertyEditorView(QWidget *parent) :
+ QWidget(parent)
+{
+ m_containerWidget = createWindowContainer(&m_view);
+
+ QVBoxLayout *layout = new QVBoxLayout(this);
+ setLayout(layout);
+ layout->addWidget(m_containerWidget);
+ layout->setMargin(0);
+ m_view.setResizeMode(QQuickView::SizeRootObjectToView);
+}
+
+QUrl Quick2PropertyEditorView::source() const
+{
+ return m_source;
+}
+
+void Quick2PropertyEditorView::setSource(const QUrl& url)
+{
+ m_source = url;
+ execute();
+}
+
+QQmlEngine* Quick2PropertyEditorView::engine()
+{
+ return m_view.engine();
+}
+
+QQmlContext* Quick2PropertyEditorView::rootContext()
+{
+ return engine()->rootContext();
+}
+
+Quick2PropertyEditorView::Status Quick2PropertyEditorView::status() const
+{
+ return Quick2PropertyEditorView::Status(m_view.status());
+}
+
+
+void Quick2PropertyEditorView::continueExecute()
+{
+ disconnect(&m_view, SIGNAL(statusChanged(QQuickView::Status)), this, SLOT(continueExecute()));
+
+ if (!m_view.errors().isEmpty()) {
+ QList<QQmlError> errorList = m_view.errors();
+ foreach (const QQmlError &error, errorList) {
+ qWarning() << error;
+ }
+ emit statusChanged(status());
+ return;
+ }
+
+ emit statusChanged(status());
+}
+
+void Quick2PropertyEditorView::registerQmlTypes()
+{
+ static bool declarativeTypesRegistered = false;
+ if (!declarativeTypesRegistered) {
+ declarativeTypesRegistered = true;
+ PropertyEditorValue::registerDeclarativeTypes();
+ }
+}
+
+} //QmlDesigner
diff --git a/src/plugins/qmldesigner/components/propertyeditor/declarativewidgetview.h b/src/plugins/qmldesigner/components/propertyeditor/quick2propertyeditorview.h
index 626814244d..d1e916df58 100644
--- a/src/plugins/qmldesigner/components/propertyeditor/declarativewidgetview.h
+++ b/src/plugins/qmldesigner/components/propertyeditor/quick2propertyeditorview.h
@@ -27,58 +27,58 @@
**
****************************************************************************/
-#ifndef DECLARATIVEWIDGETVIEW_H
-#define DECLARATIVEWIDGETVIEW_H
+#ifndef QUICK2PROERTYEDITORVIEW_H
+#define QUICK2PROERTYEDITORVIEW_H
#include <QWidget>
#include <QUrl>
-#include <QDeclarativeEngine>
+#include <QQuickView>
+#include <QQmlEngine>
+#include <QQmlContext>
QT_BEGIN_NAMESPACE
-class QDeclarativeContext;
-class QDeclarativeError;
-class QDeclarativeComponent;
+class QQmlError;
+class QQmlComponent;
QT_END_NAMESPACE
namespace QmlDesigner {
-class DeclarativeWidgetView : public QWidget
+class Quick2PropertyEditorView : public QWidget
{
Q_OBJECT
Q_PROPERTY(QUrl source READ source WRITE setSource DESIGNABLE true)
public:
- explicit DeclarativeWidgetView(QWidget *parent = 0);
+ explicit Quick2PropertyEditorView(QWidget *parent = 0);
QUrl source() const;
void setSource(const QUrl&);
- QDeclarativeEngine* engine();
- QDeclarativeContext* rootContext();
-
- QWidget *rootWidget() const;
+ QQmlEngine* engine();
+ QQmlContext* rootContext();
enum Status { Null, Ready, Loading, Error };
Status status() const;
+ static void registerQmlTypes();
+
signals:
- void statusChanged(DeclarativeWidgetView::Status);
+ void statusChanged(Quick2PropertyEditorView::Status);
protected:
- void setRootWidget(QWidget *);
void execute();
private Q_SLOTS:
void continueExecute();
private:
- QScopedPointer<QWidget> m_root;
+ QWidget *m_containerWidget;
QUrl m_source;
- QDeclarativeEngine m_engine;
- QWeakPointer<QDeclarativeComponent> m_component;
+ QQuickView m_view;
+ QWeakPointer<QQmlComponent> m_component;
};
} //QmlDesigner
-#endif // DECLARATIVEWIDGETVIEW_H
+#endif // QUICK2PROERTYEDITORVIEW_H
diff --git a/src/plugins/qmldesigner/components/propertyeditor/resetwidget.cpp b/src/plugins/qmldesigner/components/propertyeditor/resetwidget.cpp
deleted file mode 100644
index f53658ba4c..0000000000
--- a/src/plugins/qmldesigner/components/propertyeditor/resetwidget.cpp
+++ /dev/null
@@ -1,130 +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 "resetwidget.h"
-#include "qdeclarative.h"
-#include <QVBoxLayout>
-#include <QTableWidget>
-#include <QHeaderView>
-#include <QPushButton>
-
-#include <QDebug>
-#include <QApplication>
-
-QML_DECLARE_TYPE(QmlDesigner::ResetWidget)
-
-namespace QmlDesigner {
-
-
-ResetWidget::ResetWidget(QWidget *parent) : QGroupBox(parent), m_backendObject(0)
-{
- m_vlayout = new QVBoxLayout(this);
- m_vlayout->setContentsMargins(2,2,2,2);
-
- QPushButton *b = new QPushButton(this);
- b->setText(tr("Reset All Properties"));
- m_vlayout->addWidget(b);
-
- setLayout(m_vlayout);
-}
-
-void ResetWidget::registerDeclarativeType()
-{
- qmlRegisterType<QmlDesigner::ResetWidget>("Bauhaus", 1, 0, "ResetWidget");
-}
-
-void ResetWidget::resetView()
-{
- m_tableWidget->clear();
- delete m_tableWidget;
- setupView();
-}
-
-void ResetWidget::setupView()
-{
- m_tableWidget = new QTableWidget(this);
- m_vlayout->addWidget(m_tableWidget);
-
- m_tableWidget->setAlternatingRowColors(true);
- m_tableWidget->horizontalHeader()->hide();
- m_tableWidget->verticalHeader()->hide();
- m_tableWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
- m_tableWidget->setShowGrid(false);
- m_tableWidget->setSortingEnabled(true);
- m_tableWidget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
-
- const QMetaObject *metaObject = m_backendObject->metaObject();
- int count = metaObject->propertyCount();
-
- m_tableWidget->setColumnCount(3);
- m_tableWidget->setRowCount(count);
- for (int i=0;i<count;i++) {
- QMetaProperty metaProperty = metaObject->property(i);
- addPropertyItem(metaProperty.name(), i);
- }
- m_tableWidget->resizeRowsToContents();
- m_tableWidget->resizeColumnsToContents();
- m_tableWidget->sortItems(0);
- m_tableWidget->setColumnWidth(2, 40);
- parentWidget()->resize(parentWidget()->width(), count * 28);
- qApp->processEvents();
-
-}
-
-void ResetWidget::addPropertyItem(const QString &name, int row)
-{
- QTableWidgetItem *newItem = new QTableWidgetItem(name);
- m_tableWidget->setItem(row, 0, newItem);
- ResetWidgetPushButton *b = new ResetWidgetPushButton(m_tableWidget);
- b->setName(name);
- b->setText("reset");
- connect(b, SIGNAL(pressed(QString)), this, SLOT(buttonPressed(QString)));
- b->setMaximumHeight(15);
- b->setMinimumHeight(10);
- m_tableWidget->setCellWidget(row, 2, b);
-}
-
-void ResetWidget::buttonPressed(const QString &)
-{
-}
-
-ResetWidgetPushButton::ResetWidgetPushButton(QWidget *parent) : QPushButton(parent)
-{
- connect(this, SIGNAL(pressed()), this, SLOT(myPressed()));
-}
-
-void ResetWidgetPushButton::myPressed()
-{
- emit pressed(m_name);
-}
-
-
-}
-
diff --git a/src/plugins/qmldesigner/components/stateseditor/HorizontalScrollBar.qml b/src/plugins/qmldesigner/components/stateseditor/HorizontalScrollBar.qml
index a9fce48fda..a1077e7ead 100644
--- a/src/plugins/qmldesigner/components/stateseditor/HorizontalScrollBar.qml
+++ b/src/plugins/qmldesigner/components/stateseditor/HorizontalScrollBar.qml
@@ -27,7 +27,7 @@
**
****************************************************************************/
-import QtQuick 1.0
+import QtQuick 2.1
Item {
property variant flickable: this;
diff --git a/src/plugins/qmldesigner/components/stateseditor/stateseditor.pri b/src/plugins/qmldesigner/components/stateseditor/stateseditor.pri
index da160d20f2..185c6f2ede 100644
--- a/src/plugins/qmldesigner/components/stateseditor/stateseditor.pri
+++ b/src/plugins/qmldesigner/components/stateseditor/stateseditor.pri
@@ -1,3 +1,5 @@
+QT *= qml quick
+
VPATH += $$PWD
SOURCES += stateseditorwidget.cpp \
diff --git a/src/plugins/qmldesigner/components/stateseditor/stateseditorimageprovider.cpp b/src/plugins/qmldesigner/components/stateseditor/stateseditorimageprovider.cpp
index 3b0216ea67..9988e7ba74 100644
--- a/src/plugins/qmldesigner/components/stateseditor/stateseditorimageprovider.cpp
+++ b/src/plugins/qmldesigner/components/stateseditor/stateseditorimageprovider.cpp
@@ -36,7 +36,7 @@ namespace QmlDesigner {
namespace Internal {
StatesEditorImageProvider::StatesEditorImageProvider()
- : QDeclarativeImageProvider(QDeclarativeImageProvider::Image)
+ : QQuickImageProvider(QQuickImageProvider::Image)
{
}
diff --git a/src/plugins/qmldesigner/components/stateseditor/stateseditorimageprovider.h b/src/plugins/qmldesigner/components/stateseditor/stateseditorimageprovider.h
index 13b3c6b966..2af03fbf7a 100644
--- a/src/plugins/qmldesigner/components/stateseditor/stateseditorimageprovider.h
+++ b/src/plugins/qmldesigner/components/stateseditor/stateseditorimageprovider.h
@@ -32,7 +32,7 @@
#include"abstractview.h"
-#include <QDeclarativeImageProvider>
+#include <QQuickImageProvider>
#include <QWeakPointer>
namespace QmlDesigner {
@@ -40,7 +40,7 @@ namespace Internal {
class StatesEditorView;
-class StatesEditorImageProvider : public QDeclarativeImageProvider
+class StatesEditorImageProvider : public QQuickImageProvider
{
public:
StatesEditorImageProvider();
diff --git a/src/plugins/qmldesigner/components/stateseditor/stateseditorview.cpp b/src/plugins/qmldesigner/components/stateseditor/stateseditorview.cpp
index 664b212378..677d79d20f 100644
--- a/src/plugins/qmldesigner/components/stateseditor/stateseditorview.cpp
+++ b/src/plugins/qmldesigner/components/stateseditor/stateseditorview.cpp
@@ -41,6 +41,8 @@
#include <variantproperty.h>
#include <nodelistproperty.h>
+#include <qmlitemnode.h>
+
namespace QmlDesigner {
/**
@@ -48,20 +50,92 @@ namespace QmlDesigner {
the current state is the base state, we render the base state + all other states.
*/
StatesEditorView::StatesEditorView(QObject *parent) :
- QmlModelView(parent),
+ AbstractView(parent),
m_statesEditorModel(new StatesEditorModel(this)),
- m_statesEditorWidget(new StatesEditorWidget(this, m_statesEditorModel.data())),
m_lastIndex(-1)
{
Q_ASSERT(m_statesEditorModel);
// base state
}
+StatesEditorView::~StatesEditorView()
+{
+ delete m_statesEditorWidget.data();
+}
+
WidgetInfo StatesEditorView::widgetInfo()
{
+ if (!m_statesEditorWidget)
+ m_statesEditorWidget = new StatesEditorWidget(this, m_statesEditorModel.data());
+
return createWidgetInfo(m_statesEditorWidget.data(), 0, "StatesEditor", WidgetInfo::TopPane, 0, tr("States Editor"));
}
+void StatesEditorView::nodeCreated(const ModelNode &/*createdNode*/)
+{
+
+}
+
+void StatesEditorView::propertiesAboutToBeRemoved(const QList<AbstractProperty> &/*propertyList*/)
+{
+
+}
+
+void StatesEditorView::rootNodeTypeChanged(const QString &/*type*/, int /*majorVersion*/, int /*minorVersion*/)
+{
+ checkForApplicationWindow();
+}
+
+void StatesEditorView::instancePropertyChange(const QList<QPair<ModelNode, PropertyName> > &/*propertyList*/)
+{
+
+}
+
+void StatesEditorView::instancesCompleted(const QVector<ModelNode> &/*completedNodeList*/)
+{
+
+}
+
+void StatesEditorView::instanceInformationsChange(const QMultiHash<ModelNode, InformationName> &/*informationChangeHash*/)
+{
+
+}
+
+void StatesEditorView::instancesRenderImageChanged(const QVector<ModelNode> &/*nodeList*/)
+{
+
+}
+
+void StatesEditorView::instancesChildrenChanged(const QVector<ModelNode> &/*nodeList*/)
+{
+
+}
+
+void StatesEditorView::instancesToken(const QString &/*tokenName*/, int /*tokenNumber*/, const QVector<ModelNode> &/*nodeVector*/)
+{
+
+}
+
+void StatesEditorView::nodeSourceChanged(const ModelNode &/*modelNode*/, const QString &/*newNodeSource*/)
+{
+
+}
+
+void StatesEditorView::rewriterBeginTransaction()
+{
+
+}
+
+void StatesEditorView::rewriterEndTransaction()
+{
+
+}
+
+void StatesEditorView::importsChanged(const QList<Import> &/*addedImports*/, const QList<Import> &/*removedImports*/)
+{
+
+}
+
void StatesEditorView::removeState(int nodeId)
{
try {
@@ -115,7 +189,7 @@ void StatesEditorView::createNewState()
void StatesEditorView::addState()
{
// can happen when root node is e.g. a ListModel
- if (!rootQmlItemNode().isValid())
+ if (!QmlItemNode::isValidQmlItemNode(rootModelNode()))
return;
QStringList modelStateNames = rootStateGroup().names();
@@ -178,6 +252,31 @@ void StatesEditorView::duplicateCurrentState()
setCurrentState(newState);
}
+void StatesEditorView::checkForApplicationWindow()
+{
+ if (m_statesEditorWidget)
+ m_statesEditorWidget->showAddNewStatesButton(!rootModelNode().metaInfo().isSubclassOf("QtQuick.Controls.ApplicationWindow", -1, -1));
+}
+
+void StatesEditorView::setCurrentState(const QmlModelState &state)
+{
+ if (!model() && !state.isValid())
+ return;
+
+ if (currentStateNode() != state.modelNode())
+ setCurrentStateNode(state.modelNode());
+}
+
+QmlModelState StatesEditorView::baseState() const
+{
+ return QmlModelState::createBaseState(this);
+}
+
+QmlModelStateGroup StatesEditorView::rootStateGroup() const
+{
+ return QmlModelStateGroup(rootModelNode());
+}
+
bool StatesEditorView::validStateName(const QString &name) const
{
if (name == tr("base state"))
@@ -215,21 +314,23 @@ void StatesEditorView::renameState(int nodeId, const QString &newName)
void StatesEditorView::modelAttached(Model *model)
{
- if (model == QmlModelView::model())
+ if (model == AbstractView::model())
return;
Q_ASSERT(model);
- QmlModelView::modelAttached(model);
+ AbstractView::modelAttached(model);
if (m_statesEditorWidget)
m_statesEditorWidget->setNodeInstanceView(nodeInstanceView());
+ checkForApplicationWindow();
+
resetModel();
}
void StatesEditorView::modelAboutToBeDetached(Model *model)
{
- QmlModelView::modelAboutToBeDetached(model);
+ AbstractView::modelAboutToBeDetached(model);
resetModel();
}
@@ -292,7 +393,7 @@ void StatesEditorView::nodeOrderChanged(const NodeListProperty &listProperty, co
resetModel();
}
-void StatesEditorView::actualStateChanged(const ModelNode &node)
+void StatesEditorView::currentStateChanged(const ModelNode &node)
{
QmlModelState newQmlModelState(node);
@@ -300,11 +401,13 @@ void StatesEditorView::actualStateChanged(const ModelNode &node)
m_statesEditorWidget->setCurrentStateInternalId(0);
else
m_statesEditorWidget->setCurrentStateInternalId(newQmlModelState.modelNode().internalId());
- QmlModelView::actualStateChanged(node);
}
void StatesEditorView::instancesPreviewImageChanged(const QVector<ModelNode> &nodeList)
{
+ if (!model())
+ return;
+
int minimumIndex = 10000;
int maximumIndex = -1;
foreach (const ModelNode &node, nodeList) {
@@ -324,10 +427,8 @@ void StatesEditorView::instancesPreviewImageChanged(const QVector<ModelNode> &no
m_statesEditorModel->updateState(minimumIndex, maximumIndex);
}
-void StatesEditorView::scriptFunctionsChanged(const ModelNode &node, const QStringList &scriptFunctionList)
+void StatesEditorView::scriptFunctionsChanged(const ModelNode &/*node*/, const QStringList &/*scriptFunctionList*/)
{
-
- QmlModelView::scriptFunctionsChanged(node, scriptFunctionList);
}
void StatesEditorView::nodeIdChanged(const ModelNode &/*node*/, const QString &/*newId*/, const QString &/*oldId*/)
diff --git a/src/plugins/qmldesigner/components/stateseditor/stateseditorview.h b/src/plugins/qmldesigner/components/stateseditor/stateseditorview.h
index 369353f3e3..9dc83d08bd 100644
--- a/src/plugins/qmldesigner/components/stateseditor/stateseditorview.h
+++ b/src/plugins/qmldesigner/components/stateseditor/stateseditorview.h
@@ -30,7 +30,9 @@
#ifndef STATESEDITORVIEW_H
#define STATESEDITORVIEW_H
-#include <qmlmodelview.h>
+#include <abstractview.h>
+
+#include <qmlstate.h>
namespace QmlDesigner {
@@ -38,15 +40,19 @@ namespace QmlDesigner {
class StatesEditorModel;
class StatesEditorWidget;
-class StatesEditorView : public QmlModelView {
+class StatesEditorView : public AbstractView {
Q_OBJECT
public:
explicit StatesEditorView(QObject *parent = 0);
+ ~StatesEditorView();
void renameState(int nodeId,const QString &newName);
bool validStateName(const QString &name) const;
QString currentStateName() const;
+ void setCurrentState(const QmlModelState &state);
+ QmlModelState baseState() const;
+ QmlModelStateGroup rootStateGroup() const;
// AbstractView
void modelAttached(Model *model) QTC_OVERRIDE;
@@ -70,8 +76,8 @@ public:
void nodeOrderChanged(const NodeListProperty &listProperty, const ModelNode &movedNode, int oldIndex) QTC_OVERRIDE;
- // QmlModelView
- void actualStateChanged(const ModelNode &node) QTC_OVERRIDE;
+ // AbstractView
+ void currentStateChanged(const ModelNode &node) QTC_OVERRIDE;
void scriptFunctionsChanged(const ModelNode &node, const QStringList &scriptFunctionList) QTC_OVERRIDE;
void nodeIdChanged(const ModelNode &node, const QString &newId, const QString &oldId) QTC_OVERRIDE;
@@ -83,6 +89,19 @@ public:
WidgetInfo widgetInfo() QTC_OVERRIDE;
+ void nodeCreated(const ModelNode &createdNode) QTC_OVERRIDE;
+ void propertiesAboutToBeRemoved(const QList<AbstractProperty> &propertyList) QTC_OVERRIDE;
+ void rootNodeTypeChanged(const QString &type, int majorVersion, int minorVersion) QTC_OVERRIDE;
+ void instancePropertyChange(const QList<QPair<ModelNode, PropertyName> > &propertyList) QTC_OVERRIDE;
+ void instancesCompleted(const QVector<ModelNode> &completedNodeList) QTC_OVERRIDE;
+ void instanceInformationsChange(const QMultiHash<ModelNode, InformationName> &informationChangeHash) QTC_OVERRIDE;
+ void instancesRenderImageChanged(const QVector<ModelNode> &nodeList) QTC_OVERRIDE;
+ void instancesChildrenChanged(const QVector<ModelNode> &nodeList) QTC_OVERRIDE;
+ void instancesToken(const QString &tokenName, int tokenNumber, const QVector<ModelNode> &nodeVector) QTC_OVERRIDE;
+ void nodeSourceChanged(const ModelNode &modelNode, const QString &newNodeSource) QTC_OVERRIDE;
+ void rewriterBeginTransaction() QTC_OVERRIDE;
+ void rewriterEndTransaction() QTC_OVERRIDE;
+ void importsChanged(const QList<Import> &addedImports, const QList<Import> &removedImports) QTC_OVERRIDE;
public slots:
void synchonizeCurrentStateFromWidget();
@@ -94,6 +113,7 @@ private:
void resetModel();
void addState();
void duplicateCurrentState();
+ void checkForApplicationWindow();
private:
QWeakPointer<StatesEditorModel> m_statesEditorModel;
diff --git a/src/plugins/qmldesigner/components/stateseditor/stateseditorwidget.cpp b/src/plugins/qmldesigner/components/stateseditor/stateseditorwidget.cpp
index c885392462..e089c620ce 100644
--- a/src/plugins/qmldesigner/components/stateseditor/stateseditorwidget.cpp
+++ b/src/plugins/qmldesigner/components/stateseditor/stateseditorwidget.cpp
@@ -38,10 +38,10 @@
#include <QBoxLayout>
-#include <QDeclarativeView>
-#include <QDeclarativeContext>
-#include <QDeclarativeEngine>
-#include <QDeclarativeItem>
+#include <QQuickView>
+#include <QQmlContext>
+#include <QQmlEngine>
+#include <QQuickItem>
enum {
debug = false
@@ -51,15 +51,15 @@ namespace QmlDesigner {
int StatesEditorWidget::currentStateInternalId() const
{
- Q_ASSERT(m_declarativeView->rootObject());
- Q_ASSERT(m_declarativeView->rootObject()->property("currentStateInternalId").isValid());
+ Q_ASSERT(m_quickView->rootObject());
+ Q_ASSERT(m_quickView->rootObject()->property("currentStateInternalId").isValid());
- return m_declarativeView->rootObject()->property("currentStateInternalId").toInt();
+ return m_quickView->rootObject()->property("currentStateInternalId").toInt();
}
void StatesEditorWidget::setCurrentStateInternalId(int internalId)
{
- m_declarativeView->rootObject()->setProperty("currentStateInternalId", internalId);
+ m_quickView->rootObject()->setProperty("currentStateInternalId", internalId);
}
void StatesEditorWidget::setNodeInstanceView(NodeInstanceView *nodeInstanceView)
@@ -67,48 +67,58 @@ void StatesEditorWidget::setNodeInstanceView(NodeInstanceView *nodeInstanceView)
m_imageProvider->setNodeInstanceView(nodeInstanceView);
}
+void StatesEditorWidget::showAddNewStatesButton(bool showAddNewStatesButton)
+{
+ m_quickView->rootContext()->setContextProperty("canAddNewStates", showAddNewStatesButton);
+}
+
StatesEditorWidget::StatesEditorWidget(StatesEditorView *statesEditorView, StatesEditorModel *statesEditorModel):
QWidget(),
- m_declarativeView(new QDeclarativeView(this)),
+ m_quickView(new QQuickView()),
m_statesEditorView(statesEditorView),
m_imageProvider(0)
{
m_imageProvider = new Internal::StatesEditorImageProvider;
m_imageProvider->setNodeInstanceView(statesEditorView->nodeInstanceView());
- m_declarativeView->engine()->addImageProvider(
+ m_quickView->engine()->addImageProvider(
QLatin1String("qmldesigner_stateseditor"), m_imageProvider);
- m_declarativeView->setAcceptDrops(false);
+ //m_quickView->setAcceptDrops(false);
QVBoxLayout *layout = new QVBoxLayout(this);
setMinimumHeight(160);
layout->setMargin(0);
layout->setSpacing(0);
- layout->addWidget(m_declarativeView.data());
+ QWidget *container = createWindowContainer(m_quickView.data());
+ layout->addWidget(container);
- m_declarativeView->setResizeMode(QDeclarativeView::SizeRootObjectToView);
+ m_quickView->setResizeMode(QQuickView::SizeRootObjectToView);
- m_declarativeView->rootContext()->setContextProperty(QLatin1String("statesEditorModel"), statesEditorModel);
+ m_quickView->rootContext()->setContextProperty(QLatin1String("statesEditorModel"), statesEditorModel);
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());
- m_declarativeView->rootContext()->setContextProperty(QLatin1String("highlightColor"), highlightColor);
+ m_quickView->rootContext()->setContextProperty(QLatin1String("highlightColor"), highlightColor);
+
+ m_quickView->rootContext()->setContextProperty("canAddNewStates", true);
// Work around ASSERT in the internal QGraphicsScene that happens when
// the scene is created + items set dirty in one event loop run (BAUHAUS-459)
//QApplication::processEvents();
- m_declarativeView->setSource(QUrl("qrc:/stateseditor/stateslist.qml"));
+ m_quickView->setSource(QUrl("qrc:/stateseditor/stateslist.qml"));
- if (!m_declarativeView->rootObject())
+ if (!m_quickView->rootObject())
throw InvalidQmlSourceException(__LINE__, __FUNCTION__, __FILE__);
- m_declarativeView->setFocusPolicy(Qt::ClickFocus);
- QApplication::sendEvent(m_declarativeView->scene(), new QEvent(QEvent::WindowActivate));
- connect(m_declarativeView->rootObject(), SIGNAL(currentStateInternalIdChanged()), statesEditorView, SLOT(synchonizeCurrentStateFromWidget()));
- connect(m_declarativeView->rootObject(), SIGNAL(createNewState()), statesEditorView, SLOT(createNewState()));
- connect(m_declarativeView->rootObject(), SIGNAL(deleteState(int)), statesEditorView, SLOT(removeState(int)));
+ QEvent event(QEvent::WindowActivate);
+ QApplication::sendEvent(m_quickView.data(), &event);
+
+
+ connect(m_quickView->rootObject(), SIGNAL(currentStateInternalIdChanged()), statesEditorView, SLOT(synchonizeCurrentStateFromWidget()));
+ connect(m_quickView->rootObject(), SIGNAL(createNewState()), statesEditorView, SLOT(createNewState()));
+ connect(m_quickView->rootObject(), SIGNAL(deleteState(int)), statesEditorView, SLOT(removeState(int)));
setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred));
diff --git a/src/plugins/qmldesigner/components/stateseditor/stateseditorwidget.h b/src/plugins/qmldesigner/components/stateseditor/stateseditorwidget.h
index 8973b9c4a6..f81b39a70d 100644
--- a/src/plugins/qmldesigner/components/stateseditor/stateseditorwidget.h
+++ b/src/plugins/qmldesigner/components/stateseditor/stateseditorwidget.h
@@ -33,7 +33,7 @@
#include <QWidget>
QT_BEGIN_NAMESPACE
-class QDeclarativeView;
+class QQuickView;
QT_END_NAMESPACE
namespace QmlDesigner {
@@ -62,8 +62,10 @@ public:
void setCurrentStateInternalId(int internalId);
void setNodeInstanceView(NodeInstanceView *nodeInstanceView);
+ void showAddNewStatesButton(bool showAddNewStatesButton);
+
private:
- QWeakPointer<QDeclarativeView> m_declarativeView;
+ QWeakPointer<QQuickView> m_quickView;
QWeakPointer<StatesEditorView> m_statesEditorView;
Internal::StatesEditorImageProvider *m_imageProvider;
};
diff --git a/src/plugins/qmldesigner/components/stateseditor/stateslist.qml b/src/plugins/qmldesigner/components/stateseditor/stateslist.qml
index 6a9ec04ee3..0fedbefd0c 100644
--- a/src/plugins/qmldesigner/components/stateseditor/stateslist.qml
+++ b/src/plugins/qmldesigner/components/stateseditor/stateslist.qml
@@ -27,7 +27,7 @@
**
****************************************************************************/
-import QtQuick 1.0
+import QtQuick 2.1
Rectangle {
id: root
@@ -85,6 +85,7 @@ Rectangle {
id: newStateBoxLoader;
width:132
height:listViewRow.height
+ visible: canAddNewStates
Loader {
sourceComponent: addState;
// make it square
@@ -208,6 +209,7 @@ Rectangle {
width:parent.width
elide:Qt.ElideMiddle
horizontalAlignment:Qt.AlignHCenter
+ renderType: Text.NativeRendering
}
Rectangle {
id: textFrame
@@ -259,10 +261,12 @@ Rectangle {
text:stateNameInput.text
visible:false
id:textMetric
+ renderType: Text.NativeRendering
}
Text {
visible:false
id:cursorMetric
+ renderType: Text.NativeRendering
}
@@ -278,6 +282,7 @@ Rectangle {
text:stateName
width:Math.max(textMetric.width+4, parent.width)
onCursorPositionChanged: updateScroll();
+ renderType: Text.NativeRendering
function updateScroll() {
cursorMetric.text=text.substring(0,cursorPosition);
var cM = cursorPosition>0?cursorMetric.width:0;
diff --git a/src/plugins/qmldesigner/componentsplugin/components.metainfo b/src/plugins/qmldesigner/componentsplugin/components.metainfo
index b73172380a..af484dda6b 100644
--- a/src/plugins/qmldesigner/componentsplugin/components.metainfo
+++ b/src/plugins/qmldesigner/componentsplugin/components.metainfo
@@ -354,4 +354,20 @@ MetaInfo {
}
}
+ Type {
+ name: "QtQuick.Controls.SplitView"
+ icon: ":/qtquickplugin/images/item-icon16.png"
+
+ ItemLibraryEntry {
+ name: "SplitView"
+ category: "Qt Quick - Layouts"
+ libraryIcon: ":/qtquickplugin/images/item-icon.png"
+ version: "1.0"
+ requiredImport: "QtQuick.Controls"
+
+ Property { name: "width"; type: "int"; value: 100; }
+ Property { name: "height"; type: "int"; value: 100; }
+ }
+ }
+
}
diff --git a/src/plugins/qmldesigner/designercore/designercore-lib.pri b/src/plugins/qmldesigner/designercore/designercore-lib.pri
index 41f7d00982..686867037e 100644
--- a/src/plugins/qmldesigner/designercore/designercore-lib.pri
+++ b/src/plugins/qmldesigner/designercore/designercore-lib.pri
@@ -60,7 +60,6 @@ SOURCES += $$PWD/model/abstractview.cpp \
$$PWD/model/plaintexteditmodifier.cpp \
$$PWD/model/componenttextmodifier.cpp \
$$PWD/model/textmodifier.cpp \
- $$PWD/model/qmlmodelview.cpp \
$$PWD/model/qmlitemnode.cpp \
$$PWD/model/qmlstate.cpp \
$$PWD/model/qmlchangeset.cpp \
@@ -129,7 +128,6 @@ HEADERS += $$PWD/include/qmldesignercorelib_global.h \
$$PWD/include/textmodifier.h \
$$PWD/model/modeltotextmerger.h \
$$PWD/model/texttomodelmerger.h \
- $$PWD/include/qmlmodelview.h \
$$PWD/include/qmlitemnode.h \
$$PWD/include/qmlstate.h \
$$PWD/include/qmlchangeset.h \
diff --git a/src/plugins/qmldesigner/designercore/filemanager/changeimportsvisitor.cpp b/src/plugins/qmldesigner/designercore/filemanager/changeimportsvisitor.cpp
index 6d533f8fd5..d80dd87fcd 100644
--- a/src/plugins/qmldesigner/designercore/filemanager/changeimportsvisitor.cpp
+++ b/src/plugins/qmldesigner/designercore/filemanager/changeimportsvisitor.cpp
@@ -61,9 +61,9 @@ bool ChangeImportsVisitor::add(QmlJS::AST::UiProgram *ast, const Import &import)
if (!c.isSpace() && c != QLatin1Char(';'))
break;
}
- replace(insertionPoint+1, 0, QLatin1String("\n") + import.toString(false));
+ replace(insertionPoint+1, 0, QLatin1String("\n") + import.toImportString());
} else {
- replace(0, 0, import.toString(false) + QLatin1String("\n\n"));
+ replace(0, 0, import.toImportString() + QLatin1String("\n\n"));
}
setDidRewriting(true);
@@ -79,8 +79,8 @@ bool ChangeImportsVisitor::remove(QmlJS::AST::UiProgram *ast, const Import &impo
for (UiImportList *iter = ast->imports; iter; iter = iter->next) {
if (equals(iter->import, import)) {
- int start = iter->firstSourceLocation().begin();
- int end = iter->lastSourceLocation().end();
+ int start = iter->import->firstSourceLocation().begin();
+ int end = iter->import->lastSourceLocation().end();
includeSurroundingWhitespace(start, end);
replace(start, end - start, QString());
setDidRewriting(true);
diff --git a/src/plugins/qmldesigner/designercore/filemanager/changepropertyvisitor.cpp b/src/plugins/qmldesigner/designercore/filemanager/changepropertyvisitor.cpp
index d03203d036..602888566c 100644
--- a/src/plugins/qmldesigner/designercore/filemanager/changepropertyvisitor.cpp
+++ b/src/plugins/qmldesigner/designercore/filemanager/changepropertyvisitor.cpp
@@ -115,9 +115,8 @@ void ChangePropertyVisitor::replaceInMembers(UiObjectInitializer *initializer,
}
break;
- }
// for grouped properties:
- else if (!prefix.isEmpty()) {
+ } else if (!prefix.isEmpty()) {
if (UiObjectDefinition *def = cast<UiObjectDefinition *>(member)) {
if (toString(def->qualifiedTypeNameId) == prefix)
replaceInMembers(def->initializer, suffix);
diff --git a/src/plugins/qmldesigner/designercore/filemanager/removepropertyvisitor.cpp b/src/plugins/qmldesigner/designercore/filemanager/removepropertyvisitor.cpp
index e1ab75919d..94af7278d6 100644
--- a/src/plugins/qmldesigner/designercore/filemanager/removepropertyvisitor.cpp
+++ b/src/plugins/qmldesigner/designercore/filemanager/removepropertyvisitor.cpp
@@ -83,10 +83,10 @@ 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()) {
+ } else if (!prefix.isEmpty()) {
if (UiObjectDefinition *def = cast<UiObjectDefinition *>(member)) {
if (toString(def->qualifiedTypeNameId) == prefix)
removeGroupedProperty(def);
diff --git a/src/plugins/qmldesigner/designercore/include/abstractview.h b/src/plugins/qmldesigner/designercore/include/abstractview.h
index 2411be2a36..bb28457338 100644
--- a/src/plugins/qmldesigner/designercore/include/abstractview.h
+++ b/src/plugins/qmldesigner/designercore/include/abstractview.h
@@ -55,9 +55,9 @@ namespace QmlDesigner {
namespace QmlDesigner {
-class QmlModelView;
class NodeInstanceView;
class RewriterView;
+class QmlModelState;
class WidgetInfo {
@@ -146,14 +146,20 @@ public:
ModelNode rootModelNode();
void setSelectedModelNodes(const QList<ModelNode> &selectedNodeList);
+ void setSelectedModelNode(const ModelNode &modelNode);
void selectModelNode(const ModelNode &node);
void deselectModelNode(const ModelNode &node);
void clearSelectedModelNodes();
+ bool hasSelectedModelNodes() const;
+ bool hasSingleSelectedModelNode() const;
QList<ModelNode> selectedModelNodes() const;
+ ModelNode firstSelectedModelNode() const;
+ ModelNode singleSelectedModelNode() const;
ModelNode modelNodeForId(const QString &id);
bool hasId(const QString &id) const;
+ QString generateNewId(const QString prefixName) const;
ModelNode modelNodeForInternalId(qint32 internalId);
bool hasModelNodeForInternalId(qint32 internalId) const;
@@ -205,7 +211,7 @@ public:
virtual void rewriterBeginTransaction() = 0;
virtual void rewriterEndTransaction() = 0;
- virtual void actualStateChanged(const ModelNode &node) = 0; // base state is a invalid model node
+ virtual void currentStateChanged(const ModelNode &node) = 0; // base state is a invalid model node
virtual void selectedNodesChanged(const QList<ModelNode> &selectedNodeList,
const QList<ModelNode> &lastSelectedNodeList) = 0;
@@ -222,15 +228,17 @@ public:
virtual void scriptFunctionsChanged(const ModelNode &node, const QStringList &scriptFunctionList) = 0;
- QmlModelView *toQmlModelView();
void changeRootNodeType(const TypeName &type, int majorVersion, int minorVersion);
NodeInstanceView *nodeInstanceView() const;
RewriterView *rewriterView() const;
- void setAcutalStateNode(const ModelNode &node);
- ModelNode actualStateNode() const;
+ void setCurrentStateNode(const ModelNode &node);
+ ModelNode currentStateNode() const;
+ QmlModelState currentState() const;
+
+ int majorQtQuickVersion() const;
void resetView();
diff --git a/src/plugins/qmldesigner/designercore/include/anchorline.h b/src/plugins/qmldesigner/designercore/include/anchorline.h
deleted file mode 100644
index ace7dc8582..0000000000
--- a/src/plugins/qmldesigner/designercore/include/anchorline.h
+++ /dev/null
@@ -1,118 +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 ANCHORLINE_H
-#define ANCHORLINE_H
-
-#include <QMetaType>
-#include <QSharedPointer>
-#include <QWeakPointer>
-#include <QVariant>
-
-#include "corelib_global.h"
-
-namespace QmlDesigner {
-
-namespace Internal {
- class ModelPrivate;
- class InternalNode;
- typedef QSharedPointer<InternalNode> InternalNodePointer;
- typedef QWeakPointer<InternalNode> InternalNodeWeakPointer;
-
- class InternalNodeAnchors;
-
- class InternalNodeState;
- typedef QSharedPointer<InternalNodeState> InternalNodeStatePointer;
- typedef QWeakPointer<InternalNodeState> InternalNodeStateWeakPointer;
-
- class TextToModelMerger;
-}
-
-class NodeAnchors;
-class ModelNode;
-class NodeState;
-class Model;
-
-class CORESHARED_EXPORT AnchorLine
-{
-public:
- friend class NodeAnchors;
- friend class Internal::InternalNodeAnchors;
- friend class Internal::ModelPrivate;
- friend class Internal::TextToModelMerger;
-
- enum Type {
- Invalid = 0x0,
- NoAnchor = Invalid,
- Left = 0x01,
- Right = 0x02,
- Top = 0x04,
- Bottom = 0x08,
- HorizontalCenter = 0x10,
- VerticalCenter = 0x20,
- Baseline = 0x40,
-
- HorizontalMask = Left | Right | HorizontalCenter,
- VerticalMask = Top | Bottom | VerticalCenter | Baseline,
- AllMask = VerticalMask | HorizontalMask
- };
-
- AnchorLine();
- AnchorLine(const NodeState &nodeState, Type type);
- ~AnchorLine();
- AnchorLine(const AnchorLine &other);
- AnchorLine &operator =(const AnchorLine &AnchorLine);
-
- ModelNode modelNode() const;
- Type type() const;
- bool isValid() const;
-
- QVariant toVariant() const;
-
-protected:
- Internal::InternalNodeStatePointer internalNodeState() const;
- Internal::InternalNodePointer internalNode() const;
-
-private:
- AnchorLine(const Internal::InternalNodeStatePointer &internalNodeState,
- const Internal::InternalNodePointer &internalNode,
- Model* model,
- Type type);
-
- Internal::InternalNodeStateWeakPointer m_internalNodeState;
- Internal::InternalNodeWeakPointer m_internalNode;
- QWeakPointer<Model> m_model;
- Type m_anchorType;
-};
-
-} // namespace QmlDesigner
-
-Q_DECLARE_METATYPE(QmlDesigner::AnchorLine);
-
-#endif // ANCHORLINE_H
diff --git a/src/plugins/qmldesigner/designercore/include/bindingproperty.h b/src/plugins/qmldesigner/designercore/include/bindingproperty.h
index b6c8e6dbcd..63d7013ce8 100644
--- a/src/plugins/qmldesigner/designercore/include/bindingproperty.h
+++ b/src/plugins/qmldesigner/designercore/include/bindingproperty.h
@@ -44,7 +44,6 @@ class QMLDESIGNERCORE_EXPORT BindingProperty : public QmlDesigner::AbstractPrope
public:
void setExpression(const QString &expression);
QString expression() const;
- BindingProperty& operator= (const QString &expression);
BindingProperty();
BindingProperty(const BindingProperty &property, AbstractView *view);
diff --git a/src/plugins/qmldesigner/designercore/include/import.h b/src/plugins/qmldesigner/designercore/include/import.h
index 29a6e04fc1..b226f77095 100644
--- a/src/plugins/qmldesigner/designercore/include/import.h
+++ b/src/plugins/qmldesigner/designercore/include/import.h
@@ -32,6 +32,7 @@
#include <QString>
#include <QStringList>
+#include <QMetaType>
#include "qmldesignercorelib_global.h"
@@ -40,6 +41,8 @@ namespace QmlDesigner {
class QMLDESIGNERCORE_EXPORT Import
{
public:
+ Import();
+
static Import createLibraryImport(const QString &url, const QString &version = QString(), const QString &alias = QString(), const QStringList &importPaths = QStringList());
static Import createFileImport(const QString &file, const QString &version = QString(), const QString &alias = QString(), const QStringList &importPaths = QStringList());
static Import empty();
@@ -56,9 +59,11 @@ public:
QString alias() const { return m_alias; }
QStringList importPaths() const { return m_importPathList; }
- QString toString(bool addSemicolon = false, bool skipAlias = false) const;
+ QString toString(bool skipAlias = false) const;
+ QString toImportString() const;
bool operator==(const Import &other) const;
+ bool isSameModule(const Import &other) const;
private:
Import(const QString &url, const QString &file, const QString &version, const QString &alias, const QStringList &importPaths);
@@ -75,4 +80,6 @@ QMLDESIGNERCORE_EXPORT uint qHash(const Import &import);
} // namespace QmlDesigner
+Q_DECLARE_METATYPE(QmlDesigner::Import)
+
#endif // IMPORT_H
diff --git a/src/plugins/qmldesigner/designercore/include/itemlibraryinfo.h b/src/plugins/qmldesigner/designercore/include/itemlibraryinfo.h
index 4374aa0030..6218a04c42 100644
--- a/src/plugins/qmldesigner/designercore/include/itemlibraryinfo.h
+++ b/src/plugins/qmldesigner/designercore/include/itemlibraryinfo.h
@@ -69,7 +69,7 @@ public:
int minorVersion() const;
QString category() const;
QIcon dragIcon() const;
- QString qml() const;
+ QString qmlPath() const;
QString qmlSource() const;
QString requiredImport() const;
bool forceImport() const;
@@ -89,7 +89,7 @@ public:
void setDragIcon(const QIcon &icon);
void setIcon(const QIcon &icon);
void setCategory(const QString &category);
- void setQml(const QString &qml);
+ void setQmlPath(const QString &qml);
void setRequiredImport(const QString &requiredImport);
void setForceImport(bool b);
private:
diff --git a/src/plugins/qmldesigner/designercore/include/model.h b/src/plugins/qmldesigner/designercore/include/model.h
index e799907a19..8e4334d87c 100644
--- a/src/plugins/qmldesigner/designercore/include/model.h
+++ b/src/plugins/qmldesigner/designercore/include/model.h
@@ -58,6 +58,7 @@ class NodeAnchors;
class AbstractProperty;
class RewriterView;
class NodeInstanceView;
+class TextModifier;
typedef QList<QPair<PropertyName, QVariant> > PropertyListType;
@@ -95,6 +96,8 @@ public:
// Imports:
QList<Import> imports() const;
+ QList<Import> possibleImports() const;
+ QList<Import> usedImports() 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);
@@ -107,6 +110,9 @@ public:
Model *metaInfoProxyModel();
+ TextModifier *textModifier() const;
+ void setTextModifier(TextModifier *textModifier);
+
protected:
Model();
diff --git a/src/plugins/qmldesigner/designercore/include/modelnode.h b/src/plugins/qmldesigner/designercore/include/modelnode.h
index 491fecc600..922d785b5b 100644
--- a/src/plugins/qmldesigner/designercore/include/modelnode.h
+++ b/src/plugins/qmldesigner/designercore/include/modelnode.h
@@ -90,7 +90,7 @@ public:
};
ModelNode();
- ModelNode(const Internal::InternalNodePointer &internalNode, Model *model, AbstractView *view);
+ ModelNode(const Internal::InternalNodePointer &internalNode, Model *model, const AbstractView *view);
ModelNode(const ModelNode modelNode, AbstractView *view);
ModelNode(const ModelNode &other);
~ModelNode();
@@ -100,7 +100,6 @@ public:
TypeName simplifiedTypeName() const;
int minorVersion() const;
int majorVersion() const;
- int majorQtQuickVersion() const;
bool isValid() const;
bool isInHierarchy() const;
@@ -124,6 +123,7 @@ public:
NodeListProperty nodeListProperty(const PropertyName &name) const;
NodeProperty nodeProperty(const PropertyName &name) const;
NodeAbstractProperty nodeAbstractProperty(const PropertyName &name) const;
+ NodeAbstractProperty defaultNodeAbstractProperty() const;
void removeProperty(const PropertyName &name); //### also implement in AbstractProperty
QList<AbstractProperty> properties() const;
@@ -139,10 +139,10 @@ public:
bool hasVariantProperty(const PropertyName &name) const;
bool hasBindingProperty(const PropertyName &name) const;
bool hasNodeAbstracProperty(const PropertyName &name) const;
+ bool hasDefaultNodeAbstracProperty() const;
bool hasNodeProperty(const PropertyName &name) const;
bool hasNodeListProperty(const PropertyName &name) const;
-
void setScriptFunctions(const QStringList &scriptFunctionList);
QStringList scriptFunctions() const;
@@ -158,6 +158,7 @@ public:
AbstractView *view() const;
const NodeMetaInfo metaInfo() const;
+ bool hasMetaInfo() const;
bool isSelected() const;
bool isRootNode() const;
@@ -183,9 +184,11 @@ public:
NodeSourceType nodeSourceType() const;
+ bool isComponent() const;
+
private: // functions
Internal::InternalNodePointer internalNode() const;
- QString generateNewId() const;
+
private: // variables
Internal::InternalNodePointer m_internalNode;
diff --git a/src/plugins/qmldesigner/designercore/include/nodeinstance.h b/src/plugins/qmldesigner/designercore/include/nodeinstance.h
index 2f21d5cd1e..d0a53513c6 100644
--- a/src/plugins/qmldesigner/designercore/include/nodeinstance.h
+++ b/src/plugins/qmldesigner/designercore/include/nodeinstance.h
@@ -73,7 +73,9 @@ public:
QPointF position() const;
QSizeF size() const;
int penWidth() const;
- void paint(QPainter *painter);
+
+ QPixmap renderPixmap() const;
+ QPixmap blurredRenderPixmap() const;
QVariant property(const PropertyName &name) const;
bool hasBindingForProperty(const PropertyName &name) const;
@@ -84,7 +86,6 @@ public:
qint32 parentId() const;
qint32 instanceId() const;
- QPixmap renderPixmap() const;
protected:
void setProperty(const PropertyName &name, const QVariant &value);
diff --git a/src/plugins/qmldesigner/designercore/include/nodeinstanceview.h b/src/plugins/qmldesigner/designercore/include/nodeinstanceview.h
index 2b7ef3180c..ca7dbd2b38 100644
--- a/src/plugins/qmldesigner/designercore/include/nodeinstanceview.h
+++ b/src/plugins/qmldesigner/designercore/include/nodeinstanceview.h
@@ -119,11 +119,11 @@ public:
void rewriterBeginTransaction() QTC_OVERRIDE;
void rewriterEndTransaction() QTC_OVERRIDE;
- void actualStateChanged(const ModelNode &node);
+ void currentStateChanged(const ModelNode &node);
QList<NodeInstance> instances() const;
- NodeInstance instanceForNode(const ModelNode &node) const ;
- bool hasInstanceForNode(const ModelNode &node) const;
+ NodeInstance instanceForModelNode(const ModelNode &node) const ;
+ bool hasInstanceForModelNode(const ModelNode &node) const;
NodeInstance instanceForId(qint32 id);
bool hasInstanceForId(qint32 id);
diff --git a/src/plugins/qmldesigner/designercore/include/nodelistproperty.h b/src/plugins/qmldesigner/designercore/include/nodelistproperty.h
index b410484e9c..4158db7d10 100644
--- a/src/plugins/qmldesigner/designercore/include/nodelistproperty.h
+++ b/src/plugins/qmldesigner/designercore/include/nodelistproperty.h
@@ -51,8 +51,6 @@ class QMLDESIGNERCORE_EXPORT NodeListProperty : public NodeAbstractProperty
friend class QmlDesigner::AbstractProperty;
friend class QmlDesigner::Internal::ModelPrivate;
public:
- NodeListProperty& operator= (const QVariant &value);
-
NodeListProperty();
NodeListProperty(const NodeListProperty &nodeListProperty, AbstractView *view);
const QList<ModelNode> toModelNodeList() const;
diff --git a/src/plugins/qmldesigner/designercore/include/nodemetainfo.h b/src/plugins/qmldesigner/designercore/include/nodemetainfo.h
index c06b72a212..4bac4ce831 100644
--- a/src/plugins/qmldesigner/designercore/include/nodemetainfo.h
+++ b/src/plugins/qmldesigner/designercore/include/nodemetainfo.h
@@ -86,6 +86,8 @@ public:
QList<NodeMetaInfo> superClasses() const;
NodeMetaInfo directSuperClass() const;
+ bool defaultPropertyIsComponent() const;
+
TypeName typeName() const;
int majorVersion() const;
int minorVersion() const;
@@ -99,6 +101,7 @@ public:
bool isSubclassOf(const TypeName &type, int majorVersion, int minorVersio) const;
bool isLayoutable() const;
+ bool isView() const;
QString importDirectoryPath() const;
diff --git a/src/plugins/qmldesigner/designercore/include/qmlanchors.h b/src/plugins/qmldesigner/designercore/include/qmlanchors.h
index 51be41c875..5e9af6e51b 100644
--- a/src/plugins/qmldesigner/designercore/include/qmlanchors.h
+++ b/src/plugins/qmldesigner/designercore/include/qmlanchors.h
@@ -115,6 +115,10 @@ public:
QmlItemNode qmlItemNode() const;
+ bool modelHasAnchors() const;
+ bool modelHasAnchor(AnchorLine::Type sourceAnchorLineType) const;
+ AnchorLine modelAnchor(AnchorLine::Type sourceAnchorLineType) const;
+
private:
QmlItemNode m_qmlItemNode;
diff --git a/src/plugins/qmldesigner/designercore/include/qmlchangeset.h b/src/plugins/qmldesigner/designercore/include/qmlchangeset.h
index 9ba55974f9..417a75d805 100644
--- a/src/plugins/qmldesigner/designercore/include/qmlchangeset.h
+++ b/src/plugins/qmldesigner/designercore/include/qmlchangeset.h
@@ -44,6 +44,7 @@ public:
ModelNode target() const;
void setTarget(const ModelNode &target);
bool isValid() const;
+ static bool isValidQmlModelStateOperation(const ModelNode &modelNode);
};
@@ -53,6 +54,7 @@ public:
QmlPropertyChanges() : QmlModelStateOperation() {}
QmlPropertyChanges(const ModelNode &modelNode) : QmlModelStateOperation(modelNode) {}
bool isValid() const;
+ static bool isValidQmlPropertyChanges(const ModelNode &modelNode);
void removeProperty(const PropertyName &name);
};
diff --git a/src/plugins/qmldesigner/designercore/include/qmlitemnode.h b/src/plugins/qmldesigner/designercore/include/qmlitemnode.h
index cebb50b590..65ed735e99 100644
--- a/src/plugins/qmldesigner/designercore/include/qmlitemnode.h
+++ b/src/plugins/qmldesigner/designercore/include/qmlitemnode.h
@@ -43,6 +43,7 @@ namespace QmlDesigner {
class QmlModelStateGroup;
class QmlAnchors;
+class ItemLibraryEntry;
class QMLDESIGNERCORE_EXPORT QmlItemNode : public QmlObjectNode
{
@@ -51,23 +52,32 @@ public:
QmlItemNode() : QmlObjectNode() {}
QmlItemNode(const ModelNode &modelNode) : QmlObjectNode(modelNode) {}
bool isValid() const;
+ static bool isValidQmlItemNode(const ModelNode &modelNode);
bool isRootNode() const;
static bool isItemOrWindow(const ModelNode &modelNode);
+ static QmlItemNode createQmlItemNode(AbstractView *view,
+ const ItemLibraryEntry &itemLibraryEntry,
+ const QPointF &position,
+ QmlItemNode parentQmlItemNode);
+ static QmlItemNode createQmlItemNodeFromImage(AbstractView *view,
+ const QString &imageName,
+ const QPointF &position,
+ QmlItemNode parentQmlItemNode);
+
QmlModelStateGroup states() const;
QList<QmlItemNode> children() const;
QList<QmlObjectNode> resources() const;
- QList<QmlObjectNode> defaultPropertyChildren() const;
QList<QmlObjectNode> allDirectSubNodes() const;
QmlAnchors anchors() const;
bool hasChildren() const;
bool hasResources() const;
bool instanceHasAnchors() const;
- bool hasShowContent() const;
+ bool instanceHasShowContent() const;
- bool canReparent() const;
+ bool instanceCanReparent() const;
bool instanceIsAnchoredBySibling() const;
bool instanceIsAnchoredByChildren() const;
bool instanceIsMovable() const;
@@ -75,6 +85,9 @@ public:
bool instanceIsInLayoutable() const;
bool instanceHasRotationTransform() const;
+ bool modelIsMovable() const;
+ bool modelIsResizable() const;
+
QRectF instanceBoundingRect() const;
QRectF instancePaintedBoundingRect() const;
QRectF instanceContentItemBoundingRect() const;
@@ -89,18 +102,19 @@ public:
int instancePenWidth() const;
bool instanceIsRenderPixmapNull() const;
-
- void paintInstance(QPainter *painter);
-
- void selectNode();
- void deselectNode();
- bool isSelected() const;
+ QPixmap instanceRenderPixmap() const;
+ QPixmap instanceBlurredRenderPixmap() const;
TypeName simplifiedTypeName() const;
const QList<QmlItemNode> allDirectSubModelNodes() const;
const QList<QmlItemNode> allSubModelNodes() const;
bool hasAnySubModelNodes() const;
+
+ void setPosition(const QPointF &position);
+ void setPostionInBaseState(const QPointF &position);
+
+ void setSize(const QSizeF &size);
};
QMLDESIGNERCORE_EXPORT uint qHash(const QmlItemNode &node);
@@ -108,7 +122,7 @@ QMLDESIGNERCORE_EXPORT uint qHash(const QmlItemNode &node);
class QMLDESIGNERCORE_EXPORT QmlModelStateGroup
{
friend class QmlItemNode;
- friend class QmlModelView;
+ friend class StatesEditorView;
public:
diff --git a/src/plugins/qmldesigner/designercore/include/qmlmodelnodefacade.h b/src/plugins/qmldesigner/designercore/include/qmlmodelnodefacade.h
index 6c40a452b0..c3ef444ea8 100644
--- a/src/plugins/qmldesigner/designercore/include/qmlmodelnodefacade.h
+++ b/src/plugins/qmldesigner/designercore/include/qmlmodelnodefacade.h
@@ -35,19 +35,24 @@
namespace QmlDesigner {
-class QmlModelView;
+class AbstractView;
+class NodeInstanceView;
class QMLDESIGNERCORE_EXPORT QmlModelNodeFacade
{
public:
- operator ModelNode() const { return m_modelNode; }
- ModelNode modelNode() const { return m_modelNode; }
+ operator ModelNode() const;
+ ModelNode modelNode();
+ const ModelNode modelNode() const;
+ static bool isValidQmlModelNodeFacade(const ModelNode &modelNode);
virtual bool isValid() const;
virtual ~QmlModelNodeFacade();
QmlModelNodeFacade();
+ AbstractView *view() const;
+ static NodeInstanceView *nodeInstanceView();
+
bool isRootNode() const;
- QmlModelView* qmlModelView() const;
protected:
QmlModelNodeFacade(const ModelNode &modelNode);
diff --git a/src/plugins/qmldesigner/designercore/include/qmlmodelview.h b/src/plugins/qmldesigner/designercore/include/qmlmodelview.h
deleted file mode 100644
index 08e56e8535..0000000000
--- a/src/plugins/qmldesigner/designercore/include/qmlmodelview.h
+++ /dev/null
@@ -1,139 +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 QMLMODELVIEW_H
-#define QMLMODELVIEW_H
-
-#include <qmldesignercorelib_global.h>
-#include <abstractview.h>
-#include "qmlitemnode.h"
-#include "qmlstate.h"
-#include "nodeinstanceview.h"
-
-
-namespace QmlDesigner {
-
-class ItemLibraryEntry;
-
-class QMLDESIGNERCORE_EXPORT QmlModelView : public AbstractView
-{
- Q_OBJECT
- friend class QmlObjectNode;
- friend class QmlModelNodeFacade;
-
-public:
- QmlModelView(QObject *parent) ;
-
- void setCurrentState(const QmlModelState &state);
- QmlModelState currentState() const;
-
- QmlModelState baseState() const;
- QmlModelStateGroup rootStateGroup() const;
-
- QmlObjectNode createQmlObjectNode(const TypeName &typeString,
- int majorVersion,
- int minorVersion,
- const PropertyListType &propertyList = PropertyListType());
-
- QmlItemNode createQmlItemNode(const TypeName &typeString,
- int majorVersion,
- 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);
-
- QmlObjectNode rootQmlObjectNode() const;
- QmlItemNode rootQmlItemNode() const;
-
-
- void setSelectedQmlObjectNodes(const QList<QmlObjectNode> &selectedNodeList);
- void setSelectedQmlItemNodes(const QList<QmlItemNode> &selectedNodeList);
- void selectQmlObjectNode(const QmlObjectNode &node);
- void deselectQmlObjectNode(const QmlObjectNode &node);
-
- QList<QmlObjectNode> selectedQmlObjectNodes() const;
- QList<QmlItemNode> selectedQmlItemNodes() const;
-
- QmlObjectNode fxObjectNodeForId(const QString &id);
-
- void modelAttached(Model *model) QTC_OVERRIDE;
- void modelAboutToBeDetached(Model *model) QTC_OVERRIDE;
-
- void instancePropertyChange(const QList<QPair<ModelNode, PropertyName> > &propertyList) QTC_OVERRIDE;
- void instancesCompleted(const QVector<ModelNode> &completedNodeList) QTC_OVERRIDE;
- void instanceInformationsChange(const QMultiHash<ModelNode, InformationName> &informationChangeHash) QTC_OVERRIDE;
- void instancesRenderImageChanged(const QVector<ModelNode> &nodeList) QTC_OVERRIDE;
- void instancesPreviewImageChanged(const QVector<ModelNode> &nodeList) QTC_OVERRIDE;
- void instancesChildrenChanged(const QVector<ModelNode> &nodeList) QTC_OVERRIDE;
- void instancesToken(const QString &tokenName, int tokenNumber, const QVector<ModelNode> &nodeVector);
-
- void rewriterBeginTransaction() QTC_OVERRIDE;
- void rewriterEndTransaction() QTC_OVERRIDE;
-
- void actualStateChanged(const ModelNode &node);
-
- void nodeCreated(const ModelNode &createdNode) QTC_OVERRIDE;
- void nodeRemoved(const ModelNode &removedNode, const NodeAbstractProperty &parentProperty, PropertyChangeFlags propertyChange) QTC_OVERRIDE;
- void nodeAboutToBeReparented(const ModelNode &node, const NodeAbstractProperty &newPropertyParent,
- const NodeAbstractProperty &oldPropertyParent,
- AbstractView::PropertyChangeFlags propertyChange) QTC_OVERRIDE;
- void nodeReparented(const ModelNode &node, const NodeAbstractProperty &newPropertyParent,
- const NodeAbstractProperty &oldPropertyParent,
- AbstractView::PropertyChangeFlags propertyChange) QTC_OVERRIDE;
- void propertiesAboutToBeRemoved(const QList<AbstractProperty> &propertyList) QTC_OVERRIDE;
- void rootNodeTypeChanged(const QString &type, int majorVersion, int minorVersion) QTC_OVERRIDE;
- void nodeOrderChanged(const NodeListProperty &listProperty, const ModelNode &movedNode, int oldIndex) QTC_OVERRIDE;
- void nodeAboutToBeRemoved(const ModelNode &removedNode) QTC_OVERRIDE;
- void nodeIdChanged(const ModelNode& node, const QString& newId, const QString& oldId) QTC_OVERRIDE;
- void propertiesRemoved(const QList<AbstractProperty>& propertyList) QTC_OVERRIDE;
- void variantPropertiesChanged(const QList<VariantProperty>& propertyList, PropertyChangeFlags propertyChange) QTC_OVERRIDE;
- void bindingPropertiesChanged(const QList<BindingProperty>& propertyList, PropertyChangeFlags propertyChange) QTC_OVERRIDE;
- void signalHandlerPropertiesChanged(const QVector<SignalHandlerProperty>& propertyList,PropertyChangeFlags propertyChange) QTC_OVERRIDE;
- void scriptFunctionsChanged(const ModelNode &node, const QStringList &scriptFunctionList) QTC_OVERRIDE;
- void selectedNodesChanged(const QList<ModelNode> &selectedNodeList, const QList<ModelNode> &lastSelectedNodeList) QTC_OVERRIDE;
-
- void importsChanged(const QList<Import> &addedImports, const QList<Import> &removedImports) QTC_OVERRIDE;
- void nodeSourceChanged(const ModelNode &modelNode, const QString &newNodeSource) QTC_OVERRIDE;
-
-protected:
- NodeInstance instanceForModelNode(const ModelNode &modelNode);
- bool hasInstanceForModelNode(const ModelNode &modelNode);
-
- void activateState(const QmlModelState &state);
-
-private:
- QmlModelState m_state;
-};
-
-} //QmlDesigner
-
-#endif // QMLMODELVIEW_H
diff --git a/src/plugins/qmldesigner/designercore/include/qmlobjectnode.h b/src/plugins/qmldesigner/designercore/include/qmlobjectnode.h
index 092b19f6c0..af472e3a7c 100644
--- a/src/plugins/qmldesigner/designercore/include/qmlobjectnode.h
+++ b/src/plugins/qmldesigner/designercore/include/qmlobjectnode.h
@@ -45,8 +45,11 @@ class QmlPropertyChanges;
class QMLDESIGNERCORE_EXPORT QmlObjectNode : public QmlModelNodeFacade
{
public:
- QmlObjectNode() : QmlModelNodeFacade() {}
- QmlObjectNode(const ModelNode &modelNode) : QmlModelNodeFacade(modelNode) {}
+ QmlObjectNode();
+ QmlObjectNode(const ModelNode &modelNode);
+
+ static bool isValidQmlObjectNode(const ModelNode &modelNode);
+ bool isValid() const;
bool hasNodeParent() const;
bool hasInstanceParent() const;
@@ -63,6 +66,7 @@ public:
void setVariantProperty(const PropertyName &name, const QVariant &value);
void setBindingProperty(const PropertyName &name, const QString &expression);
NodeAbstractProperty nodeAbstractProperty(const PropertyName &name) const;
+ NodeAbstractProperty defaultNodeAbstractProperty() const;
NodeProperty nodeProperty(const PropertyName &name) const;
NodeListProperty nodeListProperty(const PropertyName &name) const;
@@ -80,7 +84,7 @@ public:
bool isInBaseState() const;
QmlPropertyChanges propertyChangeForCurrentState() const;
- virtual bool canReparent() const;
+ virtual bool instanceCanReparent() const;
bool isRootModelNode() const;
@@ -89,7 +93,7 @@ public:
QList<QmlModelState> allAffectingStates() const;
QList<QmlModelStateOperation> allAffectingStatesOperations() const;
- void removeVariantProperty(const PropertyName &name);
+ void removeProperty(const PropertyName &name);
void setParent(QmlObjectNode newParent);
@@ -97,8 +101,8 @@ public:
bool isAncestorOf(const QmlObjectNode &objectNode) const;
- bool hasDefaultProperty() const;
- PropertyName defaultProperty() const;
+ bool hasDefaultPropertyName() const;
+ PropertyName defaultPropertyName() const;
static QVariant instanceValue(const ModelNode &modelNode, const PropertyName &name);
diff --git a/src/plugins/qmldesigner/designercore/include/qmlstate.h b/src/plugins/qmldesigner/designercore/include/qmlstate.h
index 84e358b042..197e9cb635 100644
--- a/src/plugins/qmldesigner/designercore/include/qmlstate.h
+++ b/src/plugins/qmldesigner/designercore/include/qmlstate.h
@@ -36,13 +36,13 @@
namespace QmlDesigner {
-class QmlModelView;
-class QmlModelStateGroup;
+class AbstractViewAbstractVieweGroup;
class QmlObjectNode;
+class QmlModelStateGroup;
class QMLDESIGNERCORE_EXPORT QmlModelState : public QmlModelNodeFacade
{
- friend class QmlModelView;
+ friend class StatesEditorView;
public:
QmlModelState();
@@ -64,15 +64,19 @@ public:
QString name() const;
void setName(const QString &name);
bool isValid() const;
+ static bool isValidQmlModelState(const ModelNode &modelNode);
void destroy();
bool isBaseState() const;
+ static bool isBaseState(const ModelNode &modelNode);
QmlModelState duplicate(const QString &name) const;
QmlModelStateGroup stateGroup() const;
+ static ModelNode createQmlState(AbstractView *view, const PropertyListType &propertyList);
+
protected:
void addChangeSetIfNotExists(const ModelNode &node);
- static QmlModelState createBaseState(const QmlModelView *view);
+ static QmlModelState createBaseState(const AbstractView *view);
};
diff --git a/src/plugins/qmldesigner/designercore/include/rewriterview.h b/src/plugins/qmldesigner/designercore/include/rewriterview.h
index 0ad4428f8e..33f5c2fe8b 100644
--- a/src/plugins/qmldesigner/designercore/include/rewriterview.h
+++ b/src/plugins/qmldesigner/designercore/include/rewriterview.h
@@ -151,7 +151,7 @@ public:
void rewriterBeginTransaction() QTC_OVERRIDE;
void rewriterEndTransaction() QTC_OVERRIDE;
- void actualStateChanged(const ModelNode &node) QTC_OVERRIDE;
+ void currentStateChanged(const ModelNode &node) QTC_OVERRIDE;
void importsChanged(const QList<Import> &addedImports, const QList<Import> &removedImports) QTC_OVERRIDE;
diff --git a/src/plugins/qmldesigner/designercore/include/signalhandlerproperty.h b/src/plugins/qmldesigner/designercore/include/signalhandlerproperty.h
index 649e9846fc..4f81d45df6 100644
--- a/src/plugins/qmldesigner/designercore/include/signalhandlerproperty.h
+++ b/src/plugins/qmldesigner/designercore/include/signalhandlerproperty.h
@@ -44,7 +44,6 @@ class QMLDESIGNERCORE_EXPORT SignalHandlerProperty : public QmlDesigner::Abstrac
public:
void setSource(const QString &source);
QString source() const;
- SignalHandlerProperty& operator= (const QString &source);
SignalHandlerProperty();
SignalHandlerProperty(const SignalHandlerProperty &property, AbstractView *view);
diff --git a/src/plugins/qmldesigner/designercore/include/variantproperty.h b/src/plugins/qmldesigner/designercore/include/variantproperty.h
index f507f45214..79a19515f5 100644
--- a/src/plugins/qmldesigner/designercore/include/variantproperty.h
+++ b/src/plugins/qmldesigner/designercore/include/variantproperty.h
@@ -54,7 +54,6 @@ class QMLDESIGNERCORE_EXPORT VariantProperty : public AbstractProperty
public:
void setValue(const QVariant &value);
QVariant value() const;
- VariantProperty& operator= (const QVariant &value);
void setDynamicTypeNameAndValue(const TypeName &type, const QVariant &value);
diff --git a/src/plugins/qmldesigner/designercore/include/viewmanager.h b/src/plugins/qmldesigner/designercore/include/viewmanager.h
index 70f353a80b..fb2e7b71c0 100644
--- a/src/plugins/qmldesigner/designercore/include/viewmanager.h
+++ b/src/plugins/qmldesigner/designercore/include/viewmanager.h
@@ -38,9 +38,12 @@
#include <navigatorview.h>
#include <stateseditorview.h>
#include <formeditorview.h>
-#include <propertyeditor.h>
+#include <propertyeditorview.h>
#include <componentview.h>
#include <debugview.h>
+#include <importmanagerview.h>
+#include <designeractionmanagerview.h>
+#include <QWidgetAction>
namespace QmlDesigner {
@@ -56,7 +59,7 @@ public:
ViewManager();
~ViewManager();
- void attachRewriterView(TextModifier *textModifier);
+ void attachRewriterView();
void detachRewriterView();
void attachComponentView();
@@ -79,12 +82,16 @@ public:
void disableWidgets();
void enableWidgets();
- void pushFileOnCrambleBar(const QString &fileName);
- void pushInFileComponentOnCrambleBar(const QString &componentId);
+ void pushFileOnCrumbleBar(const QString &fileName);
+ void pushInFileComponentOnCrumbleBar(const ModelNode &modelNode);
void nextFileIsCalledInternally();
- //used by DesignDocument ### find a better solution
- QmlModelView *qmlModelView();
+ NodeInstanceView *nodeInstanceView();
+
+ QWidgetAction *componentViewAction();
+
+ DesignerActionManager &designerActionManager();
+ const DesignerActionManager &designerActionManager() const;
private: // functions
Q_DISABLE_COPY(ViewManager)
@@ -109,9 +116,10 @@ private: // variables
FormEditorView m_formEditorView;
ItemLibraryView m_itemLibraryView;
NavigatorView m_navigatorView;
- PropertyEditor m_propertyEditorView;
+ PropertyEditorView m_propertyEditorView;
StatesEditorView m_statesEditorView;
NodeInstanceView m_nodeInstanceView;
+ DesignerActionManagerView m_designerActionManagerView;
QList<QWeakPointer<AbstractView> > m_additionalViews;
};
diff --git a/src/plugins/qmldesigner/designercore/instances/nodeinstance.cpp b/src/plugins/qmldesigner/designercore/instances/nodeinstance.cpp
index efc4ad080b..9ee8f86be4 100644
--- a/src/plugins/qmldesigner/designercore/instances/nodeinstance.cpp
+++ b/src/plugins/qmldesigner/designercore/instances/nodeinstance.cpp
@@ -34,6 +34,10 @@
#include <QDebug>
+QT_BEGIN_NAMESPACE
+void qt_blurImage(QPainter *painter, QImage &blurImage, qreal radius, bool quality, bool alphaOnly, int transposed = 0);
+QT_END_NAMESPACE
+
namespace QmlDesigner {
class ProxyNodeInstanceData
@@ -75,6 +79,8 @@ public:
QHash<PropertyName, TypeName> instanceTypes;
QPixmap renderPixmap;
+ QPixmap blurredRenderPixmap;
+
QHash<PropertyName, QPair<PropertyName, qint32> > anchors;
};
@@ -256,12 +262,6 @@ int NodeInstance::penWidth() const
return 1;
}
-void NodeInstance::paint(QPainter *painter)
-{
- if (isValid() && !d->renderPixmap.isNull())
- painter->drawPixmap(boundingRect().topLeft(), d->renderPixmap);
-}
-
QVariant NodeInstance::property(const PropertyName &name) const
{
if (isValid())
@@ -320,10 +320,24 @@ QPixmap NodeInstance::renderPixmap() const
return d->renderPixmap;
}
+QPixmap NodeInstance::blurredRenderPixmap() const
+{
+ if (d->blurredRenderPixmap.isNull()) {
+ d->blurredRenderPixmap = QPixmap(d->renderPixmap.size());
+ QPainter blurPainter(&d->blurredRenderPixmap);
+ QImage renderImage = d->renderPixmap.toImage();
+ qt_blurImage(&blurPainter, renderImage, 8.0, false, false);
+ }
+
+ return d->blurredRenderPixmap;
+}
+
void NodeInstance::setRenderPixmap(const QImage &image)
{
- if (!image.isNull())
+ if (!image.isNull()) {
d->renderPixmap = QPixmap::fromImage(image);
+ d->blurredRenderPixmap = QPixmap();
+ }
}
void NodeInstance::setParentId(qint32 instanceId)
diff --git a/src/plugins/qmldesigner/designercore/instances/nodeinstanceserverproxy.cpp b/src/plugins/qmldesigner/designercore/instances/nodeinstanceserverproxy.cpp
index f366abbb01..c3aed237bf 100644
--- a/src/plugins/qmldesigner/designercore/instances/nodeinstanceserverproxy.cpp
+++ b/src/plugins/qmldesigner/designercore/instances/nodeinstanceserverproxy.cpp
@@ -38,6 +38,7 @@
#include <QDir>
#include <QTimer>
#include <QTextStream>
+#include <QMessageBox>
#include "createinstancescommand.h"
#include "createscenecommand.h"
@@ -144,14 +145,17 @@ NodeInstanceServerProxy::NodeInstanceServerProxy(NodeInstanceView *nodeInstanceV
} else {
applicationPath = macOSBundlePath(applicationPath);
applicationPath += QLatin1Char('/') + qmlPuppetApplicationName();
+#ifdef QT_NO_DEBUG // to prevent of choosing the wrong puppet in debug
if (!QFileInfo(applicationPath).exists()) { //No qmlpuppet in Qt
//We have to find out how to give not too intrusive feedback
applicationPath = QCoreApplication::applicationDirPath();
applicationPath = macOSBundlePath(applicationPath);
applicationPath += QLatin1Char('/') + qmlPuppetApplicationName();
}
+#endif
}
+
QByteArray envImportPath = qgetenv("QTCREATOR_QMLPUPPET_PATH");
if (!envImportPath.isEmpty())
applicationPath = envImportPath;
@@ -169,8 +173,10 @@ NodeInstanceServerProxy::NodeInstanceServerProxy(NodeInstanceView *nodeInstanceV
connect(m_qmlPuppetEditorProcess.data(), SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(processFinished(int,QProcess::ExitStatus)));
connect(QCoreApplication::instance(), SIGNAL(aboutToQuit()), m_qmlPuppetEditorProcess.data(), SLOT(kill()));
bool fowardQmlpuppetOutput = !qgetenv("FORWARD_QMLPUPPET_OUTPUT").isEmpty();
- if (fowardQmlpuppetOutput)
- m_qmlPuppetEditorProcess->setProcessChannelMode(QProcess::ForwardedChannels);
+ if (fowardQmlpuppetOutput) {
+ m_qmlPuppetEditorProcess->setProcessChannelMode(QProcess::MergedChannels);
+ connect(m_qmlPuppetEditorProcess.data(), SIGNAL(readyRead()), this, SLOT(printEditorProcessOutput()));
+ }
m_qmlPuppetEditorProcess->start(applicationPath, QStringList() << socketToken << "editormode" << "-graphicssystem raster");
if (runModus == NormalModus) {
@@ -179,8 +185,10 @@ NodeInstanceServerProxy::NodeInstanceServerProxy(NodeInstanceView *nodeInstanceV
m_qmlPuppetPreviewProcess->setObjectName("PreviewProcess");
connect(m_qmlPuppetPreviewProcess.data(), SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(processFinished(int,QProcess::ExitStatus)));
connect(QCoreApplication::instance(), SIGNAL(aboutToQuit()), m_qmlPuppetPreviewProcess.data(), SLOT(kill()));
- if (fowardQmlpuppetOutput)
- m_qmlPuppetPreviewProcess->setProcessChannelMode(QProcess::ForwardedChannels);
+ if (fowardQmlpuppetOutput) {
+ m_qmlPuppetPreviewProcess->setProcessChannelMode(QProcess::MergedChannels);
+ connect(m_qmlPuppetPreviewProcess.data(), SIGNAL(readyRead()), this, SLOT(printPreviewProcessOutput()));
+ }
m_qmlPuppetPreviewProcess->start(applicationPath, QStringList() << socketToken << "previewmode" << "-graphicssystem raster");
m_qmlPuppetRenderProcess = new QProcess;
@@ -188,8 +196,10 @@ NodeInstanceServerProxy::NodeInstanceServerProxy(NodeInstanceView *nodeInstanceV
m_qmlPuppetRenderProcess->setObjectName("RenderProcess");
connect(m_qmlPuppetRenderProcess.data(), SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(processFinished(int,QProcess::ExitStatus)));
connect(QCoreApplication::instance(), SIGNAL(aboutToQuit()), m_qmlPuppetRenderProcess.data(), SLOT(kill()));
- if (fowardQmlpuppetOutput)
- m_qmlPuppetRenderProcess->setProcessChannelMode(QProcess::ForwardedChannels);
+ if (fowardQmlpuppetOutput) {
+ m_qmlPuppetRenderProcess->setProcessChannelMode(QProcess::MergedChannels);
+ connect(m_qmlPuppetRenderProcess.data(), SIGNAL(readyRead()), this, SLOT(printRenderProcessOutput()));
+ }
m_qmlPuppetRenderProcess->start(applicationPath, QStringList() << socketToken << "rendermode" << "-graphicssystem raster");
}
@@ -240,6 +250,13 @@ NodeInstanceServerProxy::NodeInstanceServerProxy(NodeInstanceView *nodeInstanceV
} else {
QMessageBox::warning(0, tr("Cannot Find QML Puppet Executable"), missingQmlPuppetErrorMessage(applicationPath));
}
+
+ int indexOfCapturePuppetStream = QCoreApplication::arguments().indexOf("-capture-puppet-stream");
+ if (indexOfCapturePuppetStream > 0) {
+ m_captureFileForTest.setFileName(QCoreApplication::arguments().at(indexOfCapturePuppetStream + 1));
+ bool isOpen = m_captureFileForTest.open(QIODevice::WriteOnly);
+ qDebug() << "file is open: " << isOpen;
+ }
}
NodeInstanceServerProxy::~NodeInstanceServerProxy()
@@ -280,23 +297,23 @@ void NodeInstanceServerProxy::dispatchCommand(const QVariant &command)
static const int tokenCommandType = QMetaType::type("TokenCommand");
static const int debugOutputCommandType = QMetaType::type("DebugOutputCommand");
- if (command.userType() == informationChangedCommandType)
+ if (command.userType() == informationChangedCommandType) {
nodeInstanceClient()->informationChanged(command.value<InformationChangedCommand>());
- else if (command.userType() == valuesChangedCommandType)
+ } else if (command.userType() == valuesChangedCommandType) {
nodeInstanceClient()->valuesChanged(command.value<ValuesChangedCommand>());
- else if (command.userType() == pixmapChangedCommandType)
+ } else if (command.userType() == pixmapChangedCommandType) {
nodeInstanceClient()->pixmapChanged(command.value<PixmapChangedCommand>());
- else if (command.userType() == childrenChangedCommandType)
+ } else if (command.userType() == childrenChangedCommandType) {
nodeInstanceClient()->childrenChanged(command.value<ChildrenChangedCommand>());
- else if (command.userType() == statePreviewImageChangedCommandType)
+ } else if (command.userType() == statePreviewImageChangedCommandType) {
nodeInstanceClient()->statePreviewImagesChanged(command.value<StatePreviewImageChangedCommand>());
- else if (command.userType() == componentCompletedCommandType)
+ } else if (command.userType() == componentCompletedCommandType) {
nodeInstanceClient()->componentCompleted(command.value<ComponentCompletedCommand>());
- else if (command.userType() == tokenCommandType)
+ } else if (command.userType() == tokenCommandType) {
nodeInstanceClient()->token(command.value<TokenCommand>());
- else if (command.userType() == debugOutputCommandType)
+ } else if (command.userType() == debugOutputCommandType) {
nodeInstanceClient()->debugOutput(command.value<DebugOutputCommand>());
- else if (command.userType() == synchronizeCommandType) {
+ } else if (command.userType() == synchronizeCommandType) {
SynchronizeCommand synchronizeCommand = command.value<SynchronizeCommand>();
m_synchronizeId = synchronizeCommand.synchronizeId();
} else
@@ -333,9 +350,9 @@ QString NodeInstanceServerProxy::missingQmlPuppetErrorMessage(const QString &app
return message;
}
-static void writeCommandToSocket(const QVariant &command, QLocalSocket *socket, unsigned int commandCounter)
+static void writeCommandToIODecive(const QVariant &command, QIODevice *ioDevice, unsigned int commandCounter)
{
- if (socket) {
+ if (ioDevice) {
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_8);
@@ -345,22 +362,29 @@ static void writeCommandToSocket(const QVariant &command, QLocalSocket *socket,
out.device()->seek(0);
out << quint32(block.size() - sizeof(quint32));
- socket->write(block);
+ ioDevice->write(block);
}
}
void NodeInstanceServerProxy::writeCommand(const QVariant &command)
{
- writeCommandToSocket(command, m_firstSocket.data(), m_writeCommandCounter);
- writeCommandToSocket(command, m_secondSocket.data(), m_writeCommandCounter);
- writeCommandToSocket(command, m_thirdSocket.data(), m_writeCommandCounter);
+ writeCommandToIODecive(command, m_firstSocket.data(), m_writeCommandCounter);
+ writeCommandToIODecive(command, m_secondSocket.data(), m_writeCommandCounter);
+ writeCommandToIODecive(command, m_thirdSocket.data(), m_writeCommandCounter);
+
+ if (m_captureFileForTest.isWritable()) {
+ qDebug() << "Write strean to file: " << m_captureFileForTest.fileName();
+ writeCommandToIODecive(command, &m_captureFileForTest, m_writeCommandCounter);
+ qDebug() << "\twrite file: " << m_captureFileForTest.pos();
+ }
+
m_writeCommandCounter++;
if (m_runModus == TestModus) {
static int synchronizeId = 0;
synchronizeId++;
SynchronizeCommand synchronizeCommand(synchronizeId);
- writeCommandToSocket(QVariant::fromValue(synchronizeCommand), m_firstSocket.data(), m_writeCommandCounter);
+ writeCommandToIODecive(QVariant::fromValue(synchronizeCommand), m_firstSocket.data(), m_writeCommandCounter);
m_writeCommandCounter++;
while (m_firstSocket->waitForReadyRead(100)) {
@@ -375,6 +399,14 @@ void NodeInstanceServerProxy::processFinished(int /*exitCode*/, QProcess::ExitSt
{
qDebug() << "Process finished:" << sender();
+ if (m_captureFileForTest.isOpen()) {
+ m_captureFileForTest.close();
+ m_captureFileForTest.remove();
+ QMessageBox::warning(0, tr("QML Puppet Crashed"), tr("Your are recording a Puppet stream and the puppet crashed. "
+ "It is recommended to reopen the QML Designer and start again."));
+ }
+
+
writeCommand(QVariant::fromValue(EndPuppetCommand()));
if (m_firstSocket)
@@ -500,6 +532,37 @@ void NodeInstanceServerProxy::readThirdDataStream()
}
}
+void NodeInstanceServerProxy::printEditorProcessOutput()
+{
+ while (m_qmlPuppetEditorProcess->canReadLine()) {
+ QByteArray line = m_qmlPuppetEditorProcess->readLine();
+ line.chop(1);
+ qDebug().nospace() << "Editor Puppet: " << qPrintable(line);
+ }
+ qDebug() << "\n";
+}
+
+void NodeInstanceServerProxy::printPreviewProcessOutput()
+{
+ while (m_qmlPuppetPreviewProcess->canReadLine()) {
+ QByteArray line = m_qmlPuppetPreviewProcess->readLine();
+ line.chop(1);
+ qDebug().nospace() << "Preview Puppet: " << qPrintable(line);
+ }
+ qDebug() << "\n";
+}
+
+void NodeInstanceServerProxy::printRenderProcessOutput()
+{
+ while (m_qmlPuppetRenderProcess->canReadLine()) {
+ QByteArray line = m_qmlPuppetRenderProcess->readLine();
+ line.chop(1);
+ qDebug().nospace() << "Render Puppet: " << qPrintable(line);
+ }
+
+ qDebug() << "\n";
+}
+
QString NodeInstanceServerProxy::qmlPuppetApplicationName() const
{
if (hasQtQuick2(m_nodeInstanceView.data()))
diff --git a/src/plugins/qmldesigner/designercore/instances/nodeinstanceserverproxy.h b/src/plugins/qmldesigner/designercore/instances/nodeinstanceserverproxy.h
index d68ff85aac..1f2d092d78 100644
--- a/src/plugins/qmldesigner/designercore/instances/nodeinstanceserverproxy.h
+++ b/src/plugins/qmldesigner/designercore/instances/nodeinstanceserverproxy.h
@@ -34,6 +34,7 @@
#include <QWeakPointer>
#include <QProcess>
+#include <QFile>
QT_BEGIN_NAMESPACE
class QLocalServer;
@@ -75,6 +76,8 @@ protected:
void dispatchCommand(const QVariant &command);
NodeInstanceClientInterface *nodeInstanceClient() const;
QString missingQmlPuppetErrorMessage(const QString &applicationPath) const;
+ QString qmlPuppetApplicationName() const;
+ QString macOSBundlePath(const QString &path) const;
signals:
void processCrashed();
@@ -85,10 +88,11 @@ private slots:
void readSecondDataStream();
void readThirdDataStream();
+ void printEditorProcessOutput();
+ void printPreviewProcessOutput();
+ void printRenderProcessOutput();
private:
- QString qmlPuppetApplicationName() const;
- QString macOSBundlePath(const QString &path) const;
-
+ QFile m_captureFileForTest;
QWeakPointer<QLocalServer> m_localServer;
QWeakPointer<QLocalSocket> m_firstSocket;
QWeakPointer<QLocalSocket> m_secondSocket;
diff --git a/src/plugins/qmldesigner/designercore/instances/nodeinstanceview.cpp b/src/plugins/qmldesigner/designercore/instances/nodeinstanceview.cpp
index 53dcfd23d7..97f5feb73d 100644
--- a/src/plugins/qmldesigner/designercore/instances/nodeinstanceview.cpp
+++ b/src/plugins/qmldesigner/designercore/instances/nodeinstanceview.cpp
@@ -155,9 +155,9 @@ void NodeInstanceView::modelAttached(Model *model)
if (!isSkippedRootNode(rootModelNode()))
nodeInstanceServer()->createScene(createCreateSceneCommand());
- ModelNode stateNode = actualStateNode();
+ ModelNode stateNode = currentStateNode();
if (stateNode.isValid() && stateNode.metaInfo().isSubclassOf("QtQuick.State", 1, 0)) {
- NodeInstance newStateInstance = instanceForNode(stateNode);
+ NodeInstance newStateInstance = instanceForModelNode(stateNode);
activateState(newStateInstance);
}
@@ -199,9 +199,9 @@ void NodeInstanceView::restartProcess()
if (!isSkippedRootNode(rootModelNode()))
nodeInstanceServer()->createScene(createCreateSceneCommand());
- ModelNode stateNode = actualStateNode();
+ ModelNode stateNode = currentStateNode();
if (stateNode.isValid() && stateNode.metaInfo().isSubclassOf("QtQuick.State", 1, 0)) {
- NodeInstance newStateInstance = instanceForNode(stateNode);
+ NodeInstance newStateInstance = instanceForModelNode(stateNode);
activateState(newStateInstance);
}
}
@@ -330,11 +330,11 @@ void NodeInstanceView::propertiesRemoved(const QList<AbstractProperty>& /*proper
void NodeInstanceView::removeInstanceAndSubInstances(const ModelNode &node)
{
foreach (const ModelNode &subNode, node.allSubModelNodes()) {
- if (hasInstanceForNode(subNode))
+ if (hasInstanceForModelNode(subNode))
removeInstanceNodeRelationship(subNode);
}
- if (hasInstanceForNode(node))
+ if (hasInstanceForModelNode(node))
removeInstanceNodeRelationship(node);
}
@@ -394,8 +394,8 @@ void NodeInstanceView::fileUrlChanged(const QUrl &/*oldUrl*/, const QUrl &newUrl
void NodeInstanceView::nodeIdChanged(const ModelNode& node, const QString& /*newId*/, const QString& /*oldId*/)
{
- if (hasInstanceForNode(node)) {
- NodeInstance instance = instanceForNode(node);
+ if (hasInstanceForModelNode(node)) {
+ NodeInstance instance = instanceForModelNode(node);
nodeInstanceServer()->changeIds(createChangeIdsCommand(QList<NodeInstance>() << instance));
}
}
@@ -407,13 +407,13 @@ void NodeInstanceView::nodeOrderChanged(const NodeListProperty & listProperty,
PropertyName propertyName = listProperty.name();
qint32 containerInstanceId = -1;
ModelNode containerNode = listProperty.parentModelNode();
- if (hasInstanceForNode(containerNode))
- containerInstanceId = instanceForNode(containerNode).instanceId();
+ if (hasInstanceForModelNode(containerNode))
+ containerInstanceId = instanceForModelNode(containerNode).instanceId();
foreach (const ModelNode &node, listProperty.toModelNodeList()) {
qint32 instanceId = -1;
- if (hasInstanceForNode(node)) {
- instanceId = instanceForNode(node).instanceId();
+ if (hasInstanceForModelNode(node)) {
+ instanceId = instanceForModelNode(node).instanceId();
ReparentContainer container(instanceId, containerInstanceId, propertyName, containerInstanceId, propertyName);
containerList.append(container);
}
@@ -482,8 +482,8 @@ void NodeInstanceView::instancesToken(const QString &/*tokenName*/, int /*tokenN
void NodeInstanceView::auxiliaryDataChanged(const ModelNode &node, const PropertyName &name, const QVariant &data)
{
if ((node.isRootNode() && (name == "width" || name == "height")) || name.endsWith(PropertyName("@NodeInstance"))) {
- if (hasInstanceForNode(node)) {
- NodeInstance instance = instanceForNode(node);
+ if (hasInstanceForModelNode(node)) {
+ NodeInstance instance = instanceForModelNode(node);
QVariant value = data;
if (value.isValid()) {
PropertyValueContainer container(instance.instanceId(), name, value, TypeName());
@@ -512,8 +512,8 @@ void NodeInstanceView::customNotification(const AbstractView *view, const QStrin
void NodeInstanceView::nodeSourceChanged(const ModelNode &node, const QString & newNodeSource)
{
- if (hasInstanceForNode(node)) {
- NodeInstance instance = instanceForNode(node);
+ if (hasInstanceForModelNode(node)) {
+ NodeInstance instance = instanceForModelNode(node);
ChangeNodeSourceCommand changeNodeSourceCommand(instance.instanceId(), newNodeSource);
nodeInstanceServer()->changeNodeSource(changeNodeSourceCommand);
}
@@ -529,9 +529,9 @@ void NodeInstanceView::rewriterEndTransaction()
}
-void NodeInstanceView::actualStateChanged(const ModelNode &node)
+void NodeInstanceView::currentStateChanged(const ModelNode &node)
{
- NodeInstance newStateInstance = instanceForNode(node);
+ NodeInstance newStateInstance = instanceForModelNode(node);
if (newStateInstance.isValid() && node.metaInfo().isSubclassOf("QtQuick.State", 1, 0))
nodeInstanceView()->activateState(newStateInstance);
@@ -567,7 +567,7 @@ QList<NodeInstance> NodeInstanceView::instances() const
\sa NodeInstance
*/
-NodeInstance NodeInstanceView::instanceForNode(const ModelNode &node) const
+NodeInstance NodeInstanceView::instanceForModelNode(const ModelNode &node) const
{
Q_ASSERT(node.isValid());
Q_ASSERT(m_nodeInstanceHash.contains(node));
@@ -575,7 +575,7 @@ NodeInstance NodeInstanceView::instanceForNode(const ModelNode &node) const
return m_nodeInstanceHash.value(node);
}
-bool NodeInstanceView::hasInstanceForNode(const ModelNode &node) const
+bool NodeInstanceView::hasInstanceForModelNode(const ModelNode &node) const
{
return m_nodeInstanceHash.contains(node);
}
@@ -647,7 +647,7 @@ void NodeInstanceView::insertInstanceRelationships(const NodeInstance &instance)
void NodeInstanceView::removeInstanceNodeRelationship(const ModelNode &node)
{
Q_ASSERT(m_nodeInstanceHash.contains(node));
- NodeInstance instance = instanceForNode(node);
+ NodeInstance instance = instanceForModelNode(node);
m_nodeInstanceHash.remove(node);
instance.makeInvalid();
}
@@ -748,8 +748,8 @@ CreateSceneCommand NodeInstanceView::createCreateSceneCommand()
foreach (const ModelNode &node, nodeList) {
variantPropertyList.append(node.variantProperties());
bindingPropertyList.append(node.bindingProperties());
- if (node.isValid() && hasInstanceForNode(node)) {
- NodeInstance instance = instanceForNode(node);
+ if (node.isValid() && hasInstanceForModelNode(node)) {
+ NodeInstance instance = instanceForModelNode(node);
QHashIterator<PropertyName, QVariant> auxiliaryIterator(node.auxiliaryData());
while (auxiliaryIterator.hasNext()) {
auxiliaryIterator.next();
@@ -785,7 +785,7 @@ CreateSceneCommand NodeInstanceView::createCreateSceneCommand()
foreach (const NodeInstance &instance, instanceList) {
if (instance.modelNode().hasParentProperty()) {
NodeAbstractProperty parentProperty = instance.modelNode().parentProperty();
- ReparentContainer container(instance.instanceId(), -1, PropertyName(), instanceForNode(parentProperty.parentModelNode()).instanceId(), parentProperty.name());
+ ReparentContainer container(instance.instanceId(), -1, PropertyName(), instanceForModelNode(parentProperty.parentModelNode()).instanceId(), parentProperty.name());
reparentContainerList.append(container);
}
}
@@ -802,8 +802,8 @@ CreateSceneCommand NodeInstanceView::createCreateSceneCommand()
QVector<PropertyValueContainer> valueContainerList;
foreach (const VariantProperty &property, variantPropertyList) {
ModelNode node = property.parentModelNode();
- if (node.isValid() && hasInstanceForNode(node)) {
- NodeInstance instance = instanceForNode(node);
+ if (node.isValid() && hasInstanceForModelNode(node)) {
+ NodeInstance instance = instanceForModelNode(node);
PropertyValueContainer container(instance.instanceId(), property.name(), property.value(), property.dynamicTypeName());
valueContainerList.append(container);
}
@@ -812,8 +812,8 @@ CreateSceneCommand NodeInstanceView::createCreateSceneCommand()
QVector<PropertyBindingContainer> bindingContainerList;
foreach (const BindingProperty &property, bindingPropertyList) {
ModelNode node = property.parentModelNode();
- if (node.isValid() && hasInstanceForNode(node)) {
- NodeInstance instance = instanceForNode(node);
+ if (node.isValid() && hasInstanceForModelNode(node)) {
+ NodeInstance instance = instanceForModelNode(node);
PropertyBindingContainer container(instance.instanceId(), property.name(), property.expression(), property.dynamicTypeName());
bindingContainerList.append(container);
}
@@ -884,7 +884,7 @@ ReparentInstancesCommand NodeInstanceView::createReparentInstancesCommand(const
foreach (const NodeInstance &instance, instanceList) {
if (instance.modelNode().hasParentProperty()) {
NodeAbstractProperty parentProperty = instance.modelNode().parentProperty();
- ReparentContainer container(instance.instanceId(), -1, PropertyName(), instanceForNode(parentProperty.parentModelNode()).instanceId(), parentProperty.name());
+ ReparentContainer container(instance.instanceId(), -1, PropertyName(), instanceForModelNode(parentProperty.parentModelNode()).instanceId(), parentProperty.name());
containerList.append(container);
}
}
@@ -899,15 +899,15 @@ ReparentInstancesCommand NodeInstanceView::createReparentInstancesCommand(const
qint32 newParentInstanceId = -1;
qint32 oldParentInstanceId = -1;
- if (newPropertyParent.isValid() && hasInstanceForNode(newPropertyParent.parentModelNode()))
- newParentInstanceId = instanceForNode(newPropertyParent.parentModelNode()).instanceId();
+ if (newPropertyParent.isValid() && hasInstanceForModelNode(newPropertyParent.parentModelNode()))
+ newParentInstanceId = instanceForModelNode(newPropertyParent.parentModelNode()).instanceId();
- if (oldPropertyParent.isValid() && hasInstanceForNode(oldPropertyParent.parentModelNode()))
- oldParentInstanceId = instanceForNode(oldPropertyParent.parentModelNode()).instanceId();
+ if (oldPropertyParent.isValid() && hasInstanceForModelNode(oldPropertyParent.parentModelNode()))
+ oldParentInstanceId = instanceForModelNode(oldPropertyParent.parentModelNode()).instanceId();
- ReparentContainer container(instanceForNode(node).instanceId(), oldParentInstanceId, oldPropertyParent.name(), newParentInstanceId, newPropertyParent.name());
+ ReparentContainer container(instanceForModelNode(node).instanceId(), oldParentInstanceId, oldPropertyParent.name(), newParentInstanceId, newPropertyParent.name());
containerList.append(container);
@@ -925,8 +925,8 @@ ChangeValuesCommand NodeInstanceView::createChangeValueCommand(const QList<Varia
foreach (const VariantProperty &property, propertyList) {
ModelNode node = property.parentModelNode();
- if (node.isValid() && hasInstanceForNode(node)) {
- NodeInstance instance = instanceForNode(node);
+ if (node.isValid() && hasInstanceForModelNode(node)) {
+ NodeInstance instance = instanceForModelNode(node);
PropertyValueContainer container(instance.instanceId(), property.name(), property.value(), property.dynamicTypeName());
containerList.append(container);
}
@@ -942,8 +942,8 @@ ChangeBindingsCommand NodeInstanceView::createChangeBindingCommand(const QList<B
foreach (const BindingProperty &property, propertyList) {
ModelNode node = property.parentModelNode();
- if (node.isValid() && hasInstanceForNode(node)) {
- NodeInstance instance = instanceForNode(node);
+ if (node.isValid() && hasInstanceForModelNode(node)) {
+ NodeInstance instance = instanceForModelNode(node);
PropertyBindingContainer container(instance.instanceId(), property.name(), property.expression(), property.dynamicTypeName());
containerList.append(container);
}
@@ -973,8 +973,8 @@ RemoveInstancesCommand NodeInstanceView::createRemoveInstancesCommand(const QLis
{
QVector<qint32> idList;
foreach (const ModelNode &node, nodeList) {
- if (node.isValid() && hasInstanceForNode(node)) {
- NodeInstance instance = instanceForNode(node);
+ if (node.isValid() && hasInstanceForModelNode(node)) {
+ NodeInstance instance = instanceForModelNode(node);
if (instance.instanceId() >= 0)
idList.append(instance.instanceId());
@@ -988,8 +988,8 @@ RemoveInstancesCommand NodeInstanceView::createRemoveInstancesCommand(const Mode
{
QVector<qint32> idList;
- if (node.isValid() && hasInstanceForNode(node))
- idList.append(instanceForNode(node).instanceId());
+ if (node.isValid() && hasInstanceForModelNode(node))
+ idList.append(instanceForModelNode(node).instanceId());
return RemoveInstancesCommand(idList);
}
@@ -1000,8 +1000,8 @@ RemovePropertiesCommand NodeInstanceView::createRemovePropertiesCommand(const QL
foreach (const AbstractProperty &property, propertyList) {
ModelNode node = property.parentModelNode();
- if (node.isValid() && hasInstanceForNode(node)) {
- NodeInstance instance = instanceForNode(node);
+ if (node.isValid() && hasInstanceForModelNode(node)) {
+ NodeInstance instance = instanceForModelNode(node);
PropertyAbstractContainer container(instance.instanceId(), property.name(), property.dynamicTypeName());
containerList.append(container);
}
diff --git a/src/plugins/qmldesigner/designercore/metainfo/itemlibraryinfo.cpp b/src/plugins/qmldesigner/designercore/metainfo/itemlibraryinfo.cpp
index 023590bd0c..c59e554cf8 100644
--- a/src/plugins/qmldesigner/designercore/metainfo/itemlibraryinfo.cpp
+++ b/src/plugins/qmldesigner/designercore/metainfo/itemlibraryinfo.cpp
@@ -121,7 +121,7 @@ TypeName ItemLibraryEntry::typeName() const
return m_data->typeName;
}
-QString ItemLibraryEntry::qml() const
+QString ItemLibraryEntry::qmlPath() const
{
return m_data->qml;
}
@@ -199,7 +199,7 @@ static QString getSourceForUrl(const QString &fileURl)
}
}
-void ItemLibraryEntry::setQml(const QString &qml)
+void ItemLibraryEntry::setQmlPath(const QString &qml)
{
m_data->qml = qml;
diff --git a/src/plugins/qmldesigner/designercore/metainfo/metainfo.cpp b/src/plugins/qmldesigner/designercore/metainfo/metainfo.cpp
index 35c06b7a0f..cefc0b9987 100644
--- a/src/plugins/qmldesigner/designercore/metainfo/metainfo.cpp
+++ b/src/plugins/qmldesigner/designercore/metainfo/metainfo.cpp
@@ -89,22 +89,6 @@ void MetaInfoPrivate::initialize()
m_isInitialized = true;
}
-QString static inline stripPrefix(const QString &typeName)
-{
- QStringList list = typeName.split('.');
- if (list.count() == 2)
- return list.last();
- return typeName;
-}
-
-static inline bool isDepricatedQtType(const QString &typeName)
-{
- if (typeName.length() < 8)
- return false;
-
- return typeName.contains("Qt.");
-}
-
void MetaInfoPrivate::parseItemLibraryDescriptions()
{
Internal::WidgetPluginManager pluginManager;
diff --git a/src/plugins/qmldesigner/designercore/metainfo/metainforeader.cpp b/src/plugins/qmldesigner/designercore/metainfo/metainforeader.cpp
index f697b3127c..7bb5224cde 100644
--- a/src/plugins/qmldesigner/designercore/metainfo/metainforeader.cpp
+++ b/src/plugins/qmldesigner/designercore/metainfo/metainforeader.cpp
@@ -252,7 +252,7 @@ void MetaInfoReader::readPropertyProperty(const QString &name, const QVariant &v
void MetaInfoReader::readQmlSourceProperty(const QString &name, const QVariant &value)
{
if (name == QLatin1String("source")) {
- m_currentEntry.setQml(absoluteFilePathForDocument(value.toString()));
+ m_currentEntry.setQmlPath(absoluteFilePathForDocument(value.toString()));
} else {
addError(tr("Unknown property for QmlSource %1").arg(name), currentSourceLocation());
setParserState(Error);
diff --git a/src/plugins/qmldesigner/designercore/metainfo/nodemetainfo.cpp b/src/plugins/qmldesigner/designercore/metainfo/nodemetainfo.cpp
index a10bfdd988..70f6863259 100644
--- a/src/plugins/qmldesigner/designercore/metainfo/nodemetainfo.cpp
+++ b/src/plugins/qmldesigner/designercore/metainfo/nodemetainfo.cpp
@@ -1221,6 +1221,14 @@ NodeMetaInfo NodeMetaInfo::directSuperClass() const
return NodeMetaInfo();
}
+bool NodeMetaInfo::defaultPropertyIsComponent() const
+{
+ if (hasDefaultProperty())
+ return propertyTypeName(defaultPropertyName()) == "Component";
+
+ return false;
+}
+
TypeName NodeMetaInfo::typeName() const
{
return m_privateData->qualfiedTypeName();
@@ -1307,4 +1315,12 @@ bool NodeMetaInfo::isLayoutable() const
return isSubclassOf("QtQuick.Positioner", -1, -1) || isSubclassOf("QtQuick.Layouts.Layout", -1, -1);
}
+bool NodeMetaInfo::isView() const
+{
+ return isValid() &&
+ (isSubclassOf("QtQuick.ListView", -1, -1) ||
+ isSubclassOf("QtQuick.GridView", -1, -1) ||
+ isSubclassOf("QtQuick.PathView", -1, -1));
+}
+
} // namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/designercore/metainfo/subcomponentmanager.cpp b/src/plugins/qmldesigner/designercore/metainfo/subcomponentmanager.cpp
index 97a466441b..69191cbe9e 100644
--- a/src/plugins/qmldesigner/designercore/metainfo/subcomponentmanager.cpp
+++ b/src/plugins/qmldesigner/designercore/metainfo/subcomponentmanager.cpp
@@ -228,6 +228,8 @@ void SubComponentManager::parseDirectories()
void SubComponentManager::parseDirectory(const QString &canonicalDirPath, bool addToLibrary, const TypeName& qualification)
{
+ if (!model()->rewriterView())
+ return;
QDir designerDir(canonicalDirPath + Constants::QML_DESIGNER_SUBFOLDER);
if (designerDir.exists()) {
@@ -360,14 +362,6 @@ void SubComponentManager::unregisterQmlFile(const QFileInfo &fileInfo, const QSt
componentName = qualifier + '.' + componentName;
}
-static inline bool isDepricatedQtType(const QString &typeName)
-{
- if (typeName.length() < 8)
- return false;
-
- return typeName.contains("Qt.");
-}
-
void SubComponentManager::registerQmlFile(const QFileInfo &fileInfo, const QString &qualifier,
bool addToLibrary)
diff --git a/src/plugins/qmldesigner/designercore/model/abstractview.cpp b/src/plugins/qmldesigner/designercore/model/abstractview.cpp
index d56a8a4dbf..ccfa498dd6 100644
--- a/src/plugins/qmldesigner/designercore/model/abstractview.cpp
+++ b/src/plugins/qmldesigner/designercore/model/abstractview.cpp
@@ -32,7 +32,8 @@
#include "model.h"
#include "model_p.h"
#include "internalnode_p.h"
-#include <qmlmodelview.h>
+#include "nodeinstanceview.h"
+#include <qmlstate.h>
namespace QmlDesigner {
@@ -269,6 +270,11 @@ void AbstractView::setSelectedModelNodes(const QList<ModelNode> &selectedNodeLis
model()->d->setSelectedNodes(toInternalNodeList(selectedNodeList));
}
+void AbstractView::setSelectedModelNode(const ModelNode &modelNode)
+{
+ setSelectedModelNodes(QList<ModelNode>() << modelNode);
+}
+
/*!
Clears the selection.
*/
@@ -277,6 +283,16 @@ void AbstractView::clearSelectedModelNodes()
model()->d->clearSelectedNodes();
}
+bool AbstractView::hasSelectedModelNodes() const
+{
+ return !model()->d->selectedNodes().isEmpty();
+}
+
+bool AbstractView::hasSingleSelectedModelNode() const
+{
+ return model()->d->selectedNodes().count() == 1;
+}
+
/*!
Sets the list of nodes to the actual selected nodes. Returns a list of the
selected nodes.
@@ -286,6 +302,22 @@ QList<ModelNode> AbstractView::selectedModelNodes() const
return toModelNodeList(model()->d->selectedNodes());
}
+ModelNode AbstractView::firstSelectedModelNode() const
+{
+ if (hasSelectedModelNodes())
+ return ModelNode(model()->d->selectedNodes().first(), model(), this);
+
+ return ModelNode();
+}
+
+ModelNode AbstractView::singleSelectedModelNode() const
+{
+ if (hasSingleSelectedModelNode())
+ return ModelNode(model()->d->selectedNodes().first(), model(), this);
+
+ return ModelNode();
+}
+
/*!
Adds \a node to the selection list.
*/
@@ -312,6 +344,31 @@ bool AbstractView::hasId(const QString &id) const
return model()->d->hasId(id);
}
+QString firstCharToLower(const QString string)
+{
+ QString resultString = string;
+
+ if (!resultString.isEmpty())
+ resultString[0] = resultString.at(0).toLower();
+
+ return resultString;
+}
+
+QString AbstractView::generateNewId(const QString prefixName) const
+{
+ int counter = 1;
+
+ QString newId = QString("%1%2").arg(firstCharToLower(prefixName)).arg(counter);
+ newId.remove(QRegExp(QLatin1String("[^a-zA-Z0-9_]")));
+
+ while (hasId(newId)) {
+ counter += 1;
+ newId = QString("%1%2").arg(firstCharToLower(prefixName)).arg(counter);
+ }
+
+ return newId;
+}
+
ModelNode AbstractView::modelNodeForInternalId(qint32 internalId)
{
return ModelNode(model()->d->nodeForInternalId(internalId), model(), this);
@@ -322,11 +379,6 @@ bool AbstractView::hasModelNodeForInternalId(qint32 internalId) const
return model()->d->hasNodeForInternalId(internalId);
}
-QmlModelView *AbstractView::toQmlModelView()
-{
- return qobject_cast<QmlModelView*>(this);
-}
-
NodeInstanceView *AbstractView::nodeInstanceView() const
{
if (model())
@@ -443,11 +495,11 @@ void AbstractView::emitRewriterEndTransaction()
model()->d->notifyRewriterEndTransaction();
}
-void AbstractView::setAcutalStateNode(const ModelNode &node)
+void AbstractView::setCurrentStateNode(const ModelNode &node)
{
Internal::WriteLocker locker(m_model.data());
if (model())
- model()->d->notifyActualStateChanged(node);
+ model()->d->notifyCurrentStateChanged(node);
}
void AbstractView::changeRootNodeType(const TypeName &type, int majorVersion, int minorVersion)
@@ -457,12 +509,56 @@ void AbstractView::changeRootNodeType(const TypeName &type, int majorVersion, in
m_model.data()->d->changeRootNodeType(type, majorVersion, minorVersion);
}
-ModelNode AbstractView::actualStateNode() const
+ModelNode AbstractView::currentStateNode() const
{
if (model())
- return ModelNode(m_model.data()->d->actualStateNode(), m_model.data(), const_cast<AbstractView*>(this));
+ return ModelNode(m_model.data()->d->currentStateNode(), m_model.data(), const_cast<AbstractView*>(this));
return ModelNode();
}
+QmlModelState AbstractView::currentState() const
+{
+ return QmlModelState(currentStateNode());
+}
+
+static int getMajorVersionFromImport(const Model *model)
+{
+ foreach (const Import &import, model->imports()) {
+ if (import.isLibraryImport() && import.url() == QLatin1String("QtQuick")) {
+ const QString versionString = import.version();
+ if (versionString.contains(QLatin1String("."))) {
+ const QString majorVersionString = versionString.split(QLatin1String(".")).first();
+ return majorVersionString.toInt();
+ }
+ }
+ }
+
+ return -1;
+}
+
+static int getMajorVersionFromNode(const ModelNode &modelNode)
+{
+ if (modelNode.metaInfo().isValid()) {
+ if (modelNode.type() == "QtQuick.QtObject" || modelNode.type() == "QtQuick.Item")
+ return modelNode.majorVersion();
+
+ foreach (const NodeMetaInfo &superClass, modelNode.metaInfo().superClasses()) {
+ if (modelNode.type() == "QtQuick.QtObject" || modelNode.type() == "QtQuick.Item")
+ return superClass.majorVersion();
+ }
+ }
+
+ return 1; //default
+}
+
+int AbstractView::majorQtQuickVersion() const
+{
+ int majorVersionFromImport = getMajorVersionFromImport(model());
+ if (majorVersionFromImport >= 0)
+ return majorVersionFromImport;
+
+ return getMajorVersionFromNode(rootModelNode());
+}
+
} // namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/designercore/model/anchorline.cpp b/src/plugins/qmldesigner/designercore/model/anchorline.cpp
deleted file mode 100644
index 2563647436..0000000000
--- a/src/plugins/qmldesigner/designercore/model/anchorline.cpp
+++ /dev/null
@@ -1,129 +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 "anchorline.h"
-#include "model.h"
-#include "internalnode_p.h"
-#include "modelnode.h"
-
-namespace QmlDesigner {
-
-AnchorLine::AnchorLine()
- : m_anchorType(Invalid)
-{
-}
-
-AnchorLine::AnchorLine(const Internal::InternalNodeStatePointer &internalNodeState,
- const Internal::InternalNodePointer &internalNode,
- Model* model,
- Type type)
- : m_internalNodeState(internalNodeState),
- m_internalNode(internalNode),
- m_model(model),
- m_anchorType(type)
-{
-}
-
-AnchorLine::AnchorLine(const NodeState &nodeState,
- Type type)
- : m_internalNodeState(nodeState.internalNodeState()),
- m_internalNode(nodeState.internalNode()),
- m_model(nodeState.model()),
- m_anchorType(type)
-{
-
-}
-
-AnchorLine::~AnchorLine()
-{
-}
-
-AnchorLine::AnchorLine(const AnchorLine &other)
- : m_internalNodeState(other.m_internalNodeState),
- m_internalNode(other.m_internalNode),
- m_model(other.m_model),
- m_anchorType(other.m_anchorType)
-{
-}
-
-AnchorLine &AnchorLine::operator =(const AnchorLine &other)
-{
- m_internalNodeState = other.m_internalNodeState;
- m_internalNode = other.m_internalNode;
- m_model = other.m_model;
- m_anchorType = other.m_anchorType;
-
- return *this;
-}
-
-ModelNode AnchorLine::modelNode() const
-{
- if (m_internalNode.isNull() || m_internalNodeState.isNull() || m_model.isNull())
- return ModelNode();
- return ModelNode(m_internalNode, m_model.data());
-}
-
-
-AnchorLine::Type AnchorLine::type() const
-{
- return m_anchorType;
-}
-
-bool AnchorLine::isValid() const
-{
- return m_anchorType != Invalid &&
- !m_model.isNull() &&
- !m_internalNode.isNull() &&
- !m_internalNodeState.isNull() &&
- m_internalNode.toStrongRef()->isValid() &&
- m_internalNodeState.toStrongRef()->isValid();
-}
-
-QVariant AnchorLine::toVariant() const
-{
- return QVariant::fromValue(*this);
-}
-
-Internal::InternalNodeStatePointer AnchorLine::internalNodeState() const
-{
- if (m_internalNodeState.isNull())
- return Internal::InternalNodeStatePointer(new Internal::InternalNodeState);
-
- return m_internalNodeState.toStrongRef();
-}
-
-Internal::InternalNodePointer AnchorLine::internalNode() const
-{
- if (m_internalNode.isNull())
- return Internal::InternalNodePointer(new Internal::InternalNode);
-
- return m_internalNode.toStrongRef();
-}
-
-} // namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/designercore/model/bindingproperty.cpp b/src/plugins/qmldesigner/designercore/model/bindingproperty.cpp
index 7ccd6a9bc1..ce511950a5 100644
--- a/src/plugins/qmldesigner/designercore/model/bindingproperty.cpp
+++ b/src/plugins/qmldesigner/designercore/model/bindingproperty.cpp
@@ -93,13 +93,6 @@ QString BindingProperty::expression() const
return QString();
}
-BindingProperty& BindingProperty::operator= (const QString &expression)
-{
- setExpression(expression);
-
- return *this;
-}
-
static ModelNode resolveBinding(const QString &binding, ModelNode currentNode, AbstractView* view)
{
int i = 0;
@@ -112,13 +105,13 @@ static ModelNode resolveBinding(const QString &binding, ModelNode currentNode, A
else
return ModelNode(); //binding not valid
} else if (currentNode.hasProperty(element.toUtf8())) {
- if (currentNode.property(element.toUtf8()).isNodeProperty()) {
+ if (currentNode.property(element.toUtf8()).isNodeProperty())
currentNode = currentNode.nodeProperty(element.toUtf8()).modelNode();
- } else {
+ else if (view->hasId(element))
currentNode = view->modelNodeForId(element); //id
- if (!currentNode.isValid())
- return ModelNode(); //binding not valid
- }
+ else
+ return ModelNode(); //binding not valid
+
} else {
currentNode = view->modelNodeForId(element); //id
}
@@ -192,9 +185,8 @@ QList<ModelNode> BindingProperty::resolveToModelNodeList() const
string.remove(0, 1);
QStringList simplifiedList = commaSeparatedSimplifiedStringList(string);
foreach (const QString &nodeId, simplifiedList) {
- ModelNode modelNode = view()->modelNodeForId(nodeId);
- if (modelNode.isValid())
- returnList.append(modelNode);
+ if (view()->hasId(nodeId))
+ returnList.append(view()->modelNodeForId(nodeId));
}
}
return returnList;
diff --git a/src/plugins/qmldesigner/designercore/model/import.cpp b/src/plugins/qmldesigner/designercore/model/import.cpp
index c49800123f..b2a46ea264 100644
--- a/src/plugins/qmldesigner/designercore/model/import.cpp
+++ b/src/plugins/qmldesigner/designercore/model/import.cpp
@@ -33,6 +33,10 @@
namespace QmlDesigner {
+Import::Import()
+{
+}
+
Import Import::createLibraryImport(const QString &url, const QString &version, const QString &alias, const QStringList &importPaths)
{
return Import(url, QString(), version, alias, importPaths);
@@ -48,6 +52,15 @@ Import Import::empty()
return Import(QString(), QString(), QString(), QString(), QStringList());
}
+QString Import::toImportString() const
+{
+ QString result = QLatin1String("import ");
+
+ result += toString(false);
+
+ return result;
+}
+
Import::Import(const QString &url, const QString &file, const QString &version, const QString &alias, const QStringList &importPaths):
m_url(url),
m_file(file),
@@ -57,9 +70,9 @@ Import::Import(const QString &url, const QString &file, const QString &version,
{
}
-QString Import::toString(bool addSemicolon, bool skipAlias) const
+QString Import::toString(bool skipAlias) const
{
- QString result = QLatin1String("import ");
+ QString result;
if (isFileImport())
result += '"' + file() + '"';
@@ -74,9 +87,6 @@ QString Import::toString(bool addSemicolon, bool skipAlias) const
if (hasAlias() && !skipAlias)
result += " as " + alias();
- if (addSemicolon)
- result += ';';
-
return result;
}
@@ -85,6 +95,14 @@ bool Import::operator==(const Import &other) const
return url() == other.url() && file() == other.file() && version() == other.version() && alias() == other.alias();
}
+bool Import::isSameModule(const Import &other) const
+{
+ if (isLibraryImport())
+ return url() == other.url();
+ else
+ return file() == other.file();
+}
+
uint qHash(const Import &import)
{
return ::qHash(import.url()) ^ ::qHash(import.file()) ^ ::qHash(import.version()) ^ ::qHash(import.alias());
diff --git a/src/plugins/qmldesigner/designercore/model/internalnode.cpp b/src/plugins/qmldesigner/designercore/model/internalnode.cpp
index 8e6bac99c1..1271a69fb4 100644
--- a/src/plugins/qmldesigner/designercore/model/internalnode.cpp
+++ b/src/plugins/qmldesigner/designercore/model/internalnode.cpp
@@ -174,6 +174,11 @@ void InternalNode::setAuxiliaryData(const PropertyName &name, const QVariant &da
m_auxiliaryDataHash.insert(name, data);
}
+void InternalNode::removeAuxiliaryData(const PropertyName &name)
+{
+ m_auxiliaryDataHash.remove(name);
+}
+
bool InternalNode::hasAuxiliaryData(const PropertyName &name) const
{
return m_auxiliaryDataHash.contains(name);
diff --git a/src/plugins/qmldesigner/designercore/model/internalnode_p.h b/src/plugins/qmldesigner/designercore/model/internalnode_p.h
index 37c249f47b..a3242bbe98 100644
--- a/src/plugins/qmldesigner/designercore/model/internalnode_p.h
+++ b/src/plugins/qmldesigner/designercore/model/internalnode_p.h
@@ -89,6 +89,7 @@ public:
QVariant auxiliaryData(const PropertyName &name) const;
void setAuxiliaryData(const PropertyName &name, const QVariant &data);
+ void removeAuxiliaryData(const PropertyName &name);
bool hasAuxiliaryData(const PropertyName &name) const;
QHash<PropertyName, QVariant> auxiliaryData() const;
diff --git a/src/plugins/qmldesigner/designercore/model/model.cpp b/src/plugins/qmldesigner/designercore/model/model.cpp
index b35d0a5e2d..cc4a79e77f 100644
--- a/src/plugins/qmldesigner/designercore/model/model.cpp
+++ b/src/plugins/qmldesigner/designercore/model/model.cpp
@@ -57,6 +57,7 @@
#include "rewriterview.h"
#include "rewritingexception.h"
#include "invalididexception.h"
+#include "textmodifier.h"
/*!
\defgroup CoreModel
@@ -83,7 +84,7 @@ ModelPrivate::ModelPrivate(Model *model) :
m_internalIdCounter(1)
{
m_rootInternalNode = createNode("QtQuick.Item", 1, 0, PropertyListType(), PropertyListType(), QString(), ModelNode::NodeWithoutSource,true);
- m_acutalStateNode = m_rootInternalNode;
+ m_currentStateNode = m_rootInternalNode;
}
ModelPrivate::~ModelPrivate()
@@ -227,38 +228,38 @@ InternalNode::Pointer ModelPrivate::createNode(const TypeName &typeName,
return newInternalNodePointer;
}
-void ModelPrivate::removeNodeFromModel(const InternalNodePointer &node)
+void ModelPrivate::removeNodeFromModel(const InternalNodePointer &internalNodePointer)
{
- Q_ASSERT(!node.isNull());
+ Q_ASSERT(!internalNodePointer.isNull());
- node->resetParentProperty();
+ internalNodePointer->resetParentProperty();
- if (!node->id().isEmpty())
- m_idNodeHash.remove(node->id());
- node->setValid(false);
- m_nodeSet.remove(node);
- m_internalIdNodeHash.remove(node->internalId());
+ if (!internalNodePointer->id().isEmpty())
+ m_idNodeHash.remove(internalNodePointer->id());
+ internalNodePointer->setValid(false);
+ m_nodeSet.remove(internalNodePointer);
+ m_internalIdNodeHash.remove(internalNodePointer->internalId());
}
-void ModelPrivate::removeAllSubNodes(const InternalNode::Pointer &node)
+void ModelPrivate::removeAllSubNodes(const InternalNode::Pointer &internalNodePointer)
{
- foreach (const InternalNodePointer &subNode, node->allSubNodes()) {
+ foreach (const InternalNodePointer &subNode, internalNodePointer->allSubNodes()) {
removeNodeFromModel(subNode);
}
}
-void ModelPrivate::removeNode(const InternalNode::Pointer &node)
+void ModelPrivate::removeNode(const InternalNode::Pointer &internalNodePointer)
{
- Q_ASSERT(!node.isNull());
+ Q_ASSERT(!internalNodePointer.isNull());
AbstractView::PropertyChangeFlags propertyChangeFlags = AbstractView::NoAdditionalChanges;
- notifyNodeAboutToBeRemoved(node);
+ notifyNodeAboutToBeRemoved(internalNodePointer);
- InternalNodeAbstractProperty::Pointer oldParentProperty(node->parentProperty());
+ InternalNodeAbstractProperty::Pointer oldParentProperty(internalNodePointer->parentProperty());
- removeAllSubNodes(node);
- removeNodeFromModel(node);
+ removeAllSubNodes(internalNodePointer);
+ removeNodeFromModel(internalNodePointer);
InternalNode::Pointer parentNode;
PropertyName parentPropertyName;
@@ -273,7 +274,7 @@ void ModelPrivate::removeNode(const InternalNode::Pointer &node)
propertyChangeFlags |= AbstractView::EmptyPropertiesRemoved;
}
- notifyNodeRemoved(node, parentNode, parentPropertyName, propertyChangeFlags);
+ notifyNodeRemoved(internalNodePointer, parentNode, parentPropertyName, propertyChangeFlags);
}
InternalNode::Pointer ModelPrivate::rootNode() const
@@ -573,16 +574,16 @@ void ModelPrivate::notifyInstancesChildrenChanged(const QVector<ModelNode> &node
resetModelByRewriter(description);
}
-void ModelPrivate::notifyActualStateChanged(const ModelNode &node)
+void ModelPrivate::notifyCurrentStateChanged(const ModelNode &node)
{
bool resetModel = false;
QString description;
- m_acutalStateNode = node.internalNode();
+ m_currentStateNode = node.internalNode();
try {
if (rewriterView())
- rewriterView()->actualStateChanged(ModelNode(node.internalNode(), model(), rewriterView()));
+ rewriterView()->currentStateChanged(ModelNode(node.internalNode(), model(), rewriterView()));
} catch (RewritingException &e) {
description = e.description();
resetModel = true;
@@ -590,11 +591,11 @@ void ModelPrivate::notifyActualStateChanged(const ModelNode &node)
foreach (const QWeakPointer<AbstractView> &view, m_viewList) {
Q_ASSERT(view != 0);
- view->actualStateChanged(ModelNode(node.internalNode(), model(), view.data()));
+ view->currentStateChanged(ModelNode(node.internalNode(), model(), view.data()));
}
if (nodeInstanceView())
- nodeInstanceView()->actualStateChanged(ModelNode(node.internalNode(), model(), nodeInstanceView()));
+ nodeInstanceView()->currentStateChanged(ModelNode(node.internalNode(), model(), nodeInstanceView()));
if (resetModel)
resetModelByRewriter(description);
@@ -756,8 +757,6 @@ void ModelPrivate::notifyPropertiesAboutToBeRemoved(const QList<InternalProperty
bool resetModel = false;
QString description;
-
-
try {
if (rewriterView()) {
QList<AbstractProperty> propertyList;
@@ -804,7 +803,11 @@ void ModelPrivate::notifyPropertiesAboutToBeRemoved(const QList<InternalProperty
void ModelPrivate::setAuxiliaryData(const InternalNode::Pointer& node, const PropertyName &name, const QVariant &data)
{
- node->setAuxiliaryData(name, data);
+ if (data.isValid())
+ node->setAuxiliaryData(name, data);
+ else
+ node->removeAuxiliaryData(name);
+
notifyAuxiliaryDataChanged(node, name,data);
}
@@ -819,6 +822,8 @@ void ModelPrivate::resetModelByRewriter(const QString &description)
void ModelPrivate::attachView(AbstractView *view)
{
+ Q_ASSERT(view);
+
if (m_viewList.contains(view))
return;
@@ -866,15 +871,15 @@ void ModelPrivate::notifyNodeCreated(const InternalNode::Pointer &newInternalNod
resetModelByRewriter(description);
}
-void ModelPrivate::notifyNodeAboutToBeRemoved(const InternalNode::Pointer &nodePointer)
+void ModelPrivate::notifyNodeAboutToBeRemoved(const InternalNode::Pointer &internalNodePointer)
{
bool resetModel = false;
QString description;
try {
if (rewriterView()) {
- ModelNode node(nodePointer, model(), rewriterView());
- rewriterView()->nodeAboutToBeRemoved(node);
+ ModelNode modelNode(internalNodePointer, model(), rewriterView());
+ rewriterView()->nodeAboutToBeRemoved(modelNode);
}
} catch (RewritingException &e) {
description = e.description();
@@ -883,29 +888,32 @@ void ModelPrivate::notifyNodeAboutToBeRemoved(const InternalNode::Pointer &nodeP
foreach (const QWeakPointer<AbstractView> &view, m_viewList) {
Q_ASSERT(view != 0);
- ModelNode node(nodePointer, model(), view.data());
- view->nodeAboutToBeRemoved(node);
+ ModelNode modelNode(internalNodePointer, model(), view.data());
+ view->nodeAboutToBeRemoved(modelNode);
}
if (nodeInstanceView()) {
- ModelNode node(nodePointer, model(), nodeInstanceView());
- nodeInstanceView()->nodeAboutToBeRemoved(node);
+ ModelNode modelNode(internalNodePointer, model(), nodeInstanceView());
+ nodeInstanceView()->nodeAboutToBeRemoved(modelNode);
}
if (resetModel)
resetModelByRewriter(description);
}
-void ModelPrivate::notifyNodeRemoved(const InternalNodePointer &nodePointer, const InternalNodePointer &parentNodePointer, const PropertyName &parentPropertyName, AbstractView::PropertyChangeFlags propertyChange)
+void ModelPrivate::notifyNodeRemoved(const InternalNodePointer &internalNodePointer,
+ const InternalNodePointer &parentNodePointer,
+ const PropertyName &parentPropertyName,
+ AbstractView::PropertyChangeFlags propertyChange)
{
bool resetModel = false;
QString description;
try {
if (rewriterView()) {
- ModelNode node(nodePointer, model(), rewriterView());
+ ModelNode modelNode(internalNodePointer, model(), rewriterView());
NodeAbstractProperty parentProperty(parentPropertyName, parentNodePointer, model(), rewriterView());
- rewriterView()->nodeRemoved(node, parentProperty, propertyChange);
+ rewriterView()->nodeRemoved(modelNode, parentProperty, propertyChange);
}
} catch (RewritingException &e) {
description = e.description();
@@ -913,16 +921,16 @@ void ModelPrivate::notifyNodeRemoved(const InternalNodePointer &nodePointer, con
}
if (nodeInstanceView()) {
- ModelNode node(nodePointer, model(), nodeInstanceView());
+ ModelNode modelNode(internalNodePointer, model(), nodeInstanceView());
NodeAbstractProperty parentProperty(parentPropertyName, parentNodePointer, model(), nodeInstanceView());
- nodeInstanceView()->nodeRemoved(node, parentProperty, propertyChange);
+ nodeInstanceView()->nodeRemoved(modelNode, parentProperty, propertyChange);
}
foreach (const QWeakPointer<AbstractView> &view, m_viewList) {
Q_ASSERT(view != 0);
- ModelNode node(nodePointer, model(), view.data());
+ ModelNode modelNode(internalNodePointer, model(), view.data());
NodeAbstractProperty parentProperty(parentPropertyName, parentNodePointer, model(), view.data());
- view->nodeRemoved(node, parentProperty, propertyChange);
+ view->nodeRemoved(modelNode, parentProperty, propertyChange);
}
@@ -930,15 +938,15 @@ void ModelPrivate::notifyNodeRemoved(const InternalNodePointer &nodePointer, con
resetModelByRewriter(description);
}
-void ModelPrivate::notifyNodeIdChanged(const InternalNode::Pointer& nodePointer, const QString& newId, const QString& oldId)
+void ModelPrivate::notifyNodeIdChanged(const InternalNode::Pointer& internalNodePointer, const QString& newId, const QString& oldId)
{
bool resetModel = false;
QString description;
try {
if (rewriterView()) {
- ModelNode node(nodePointer, model(), rewriterView());
- rewriterView()->nodeIdChanged(node, newId, oldId);
+ ModelNode modelNode(internalNodePointer, model(), rewriterView());
+ rewriterView()->nodeIdChanged(modelNode, newId, oldId);
}
} catch (RewritingException &e) {
description = e.description();
@@ -947,20 +955,21 @@ void ModelPrivate::notifyNodeIdChanged(const InternalNode::Pointer& nodePointer,
foreach (const QWeakPointer<AbstractView> &view, m_viewList) {
Q_ASSERT(view != 0);
- ModelNode node(nodePointer, model(), view.data());
- view->nodeIdChanged(node, newId, oldId);
+ ModelNode modelNode(internalNodePointer, model(), view.data());
+ view->nodeIdChanged(modelNode, newId, oldId);
}
if (nodeInstanceView()) {
- ModelNode node(nodePointer, model(), nodeInstanceView());
- nodeInstanceView()->nodeIdChanged(node, newId, oldId);
+ ModelNode modelNode(internalNodePointer, model(), nodeInstanceView());
+ nodeInstanceView()->nodeIdChanged(modelNode, newId, oldId);
}
if (resetModel)
resetModelByRewriter(description);
}
-void ModelPrivate::notifyBindingPropertiesChanged(const QList<InternalBindingPropertyPointer> &internalBropertyList, AbstractView::PropertyChangeFlags propertyChange)
+void ModelPrivate::notifyBindingPropertiesChanged(const QList<InternalBindingPropertyPointer> &internalPropertyList,
+ AbstractView::PropertyChangeFlags propertyChange)
{
bool resetModel = false;
QString description;
@@ -968,7 +977,7 @@ void ModelPrivate::notifyBindingPropertiesChanged(const QList<InternalBindingPro
try {
if (rewriterView()) {
QList<BindingProperty> propertyList;
- foreach (const InternalBindingPropertyPointer &bindingProperty, internalBropertyList) {
+ foreach (const InternalBindingPropertyPointer &bindingProperty, internalPropertyList) {
propertyList.append(BindingProperty(bindingProperty->name(), bindingProperty->propertyOwner(), model(), rewriterView()));
}
rewriterView()->bindingPropertiesChanged(propertyList, propertyChange);
@@ -981,7 +990,7 @@ void ModelPrivate::notifyBindingPropertiesChanged(const QList<InternalBindingPro
foreach (const QWeakPointer<AbstractView> &view, m_viewList) {
Q_ASSERT(view != 0);
QList<BindingProperty> propertyList;
- foreach (const InternalBindingPropertyPointer &bindingProperty, internalBropertyList) {
+ foreach (const InternalBindingPropertyPointer &bindingProperty, internalPropertyList) {
propertyList.append(BindingProperty(bindingProperty->name(), bindingProperty->propertyOwner(), model(), view.data()));
}
view->bindingPropertiesChanged(propertyList, propertyChange);
@@ -990,7 +999,7 @@ void ModelPrivate::notifyBindingPropertiesChanged(const QList<InternalBindingPro
if (nodeInstanceView()) {
QList<BindingProperty> propertyList;
- foreach (const InternalBindingPropertyPointer &bindingProperty, internalBropertyList) {
+ foreach (const InternalBindingPropertyPointer &bindingProperty, internalPropertyList) {
propertyList.append(BindingProperty(bindingProperty->name(), bindingProperty->propertyOwner(), model(), nodeInstanceView()));
}
nodeInstanceView()->bindingPropertiesChanged(propertyList, propertyChange);
@@ -1000,7 +1009,8 @@ void ModelPrivate::notifyBindingPropertiesChanged(const QList<InternalBindingPro
resetModelByRewriter(description);
}
-void ModelPrivate::notifySignalHandlerPropertiesChanged(const QVector<InternalSignalHandlerPropertyPointer> &internalPropertyList, AbstractView::PropertyChangeFlags propertyChange)
+void ModelPrivate::notifySignalHandlerPropertiesChanged(const QVector<InternalSignalHandlerPropertyPointer> &internalPropertyList,
+ AbstractView::PropertyChangeFlags propertyChange)
{
bool resetModel = false;
QString description;
@@ -1073,7 +1083,9 @@ void ModelPrivate::notifyScriptFunctionsChanged(const InternalNodePointer &inter
}
-void ModelPrivate::notifyVariantPropertiesChanged(const InternalNodePointer &internalNodePointer, const PropertyNameList &propertyNameList, AbstractView::PropertyChangeFlags propertyChange)
+void ModelPrivate::notifyVariantPropertiesChanged(const InternalNodePointer &internalNodePointer,
+ const PropertyNameList &propertyNameList,
+ AbstractView::PropertyChangeFlags propertyChange)
{
bool resetModel = false;
QString description;
@@ -1102,7 +1114,7 @@ void ModelPrivate::notifyVariantPropertiesChanged(const InternalNodePointer &int
VariantProperty property(propertyName, internalNodePointer, model(), view.data());
propertyList.append(property);
}
- ModelNode node(internalNodePointer, model(), view.data());
+
view->variantPropertiesChanged(propertyList, propertyChange);
}
@@ -1124,7 +1136,11 @@ void ModelPrivate::notifyVariantPropertiesChanged(const InternalNodePointer &int
resetModelByRewriter(description);
}
-void ModelPrivate::notifyNodeAboutToBeReparent(const InternalNodePointer &internalNodePointer, const InternalNodeAbstractPropertyPointer &newPropertyParent, const InternalNodePointer &oldParent, const PropertyName &oldPropertyName, AbstractView::PropertyChangeFlags propertyChange)
+void ModelPrivate::notifyNodeAboutToBeReparent(const InternalNodePointer &internalNodePointer,
+ const InternalNodeAbstractPropertyPointer &newPropertyParent,
+ const InternalNodePointer &oldParent,
+ const PropertyName &oldPropertyName,
+ AbstractView::PropertyChangeFlags propertyChange)
{
bool resetModel = false;
QString description;
@@ -1139,8 +1155,8 @@ void ModelPrivate::notifyNodeAboutToBeReparent(const InternalNodePointer &intern
if (!newPropertyParent.isNull())
newProperty = NodeAbstractProperty(newPropertyParent, model(), rewriterView());
- ModelNode node(internalNodePointer, model(), rewriterView());
- rewriterView()->nodeAboutToBeReparented(node, newProperty, oldProperty, propertyChange);
+ ModelNode modelNode(internalNodePointer, model(), rewriterView());
+ rewriterView()->nodeAboutToBeReparented(modelNode, newProperty, oldProperty, propertyChange);
}
} catch (RewritingException &e) {
description = e.description();
@@ -1157,9 +1173,9 @@ void ModelPrivate::notifyNodeAboutToBeReparent(const InternalNodePointer &intern
if (!newPropertyParent.isNull())
newProperty = NodeAbstractProperty(newPropertyParent, model(), view.data());
- ModelNode node(internalNodePointer, model(), view.data());
+ ModelNode modelNode(internalNodePointer, model(), view.data());
- view->nodeAboutToBeReparented(node, newProperty, oldProperty, propertyChange);
+ view->nodeAboutToBeReparented(modelNode, newProperty, oldProperty, propertyChange);
}
@@ -1172,8 +1188,8 @@ void ModelPrivate::notifyNodeAboutToBeReparent(const InternalNodePointer &intern
if (!newPropertyParent.isNull())
newProperty = NodeAbstractProperty(newPropertyParent, model(), nodeInstanceView());
- ModelNode node(internalNodePointer, model(), nodeInstanceView());
- nodeInstanceView()->nodeAboutToBeReparented(node, newProperty, oldProperty, propertyChange);
+ ModelNode modelNode(internalNodePointer, model(), nodeInstanceView());
+ nodeInstanceView()->nodeAboutToBeReparented(modelNode, newProperty, oldProperty, propertyChange);
}
if (resetModel)
@@ -1181,7 +1197,11 @@ void ModelPrivate::notifyNodeAboutToBeReparent(const InternalNodePointer &intern
}
-void ModelPrivate::notifyNodeReparent(const InternalNode::Pointer &internalNodePointer, const InternalNodeAbstractProperty::Pointer &newPropertyParent, const InternalNodePointer &oldParent, const PropertyName &oldPropertyName, AbstractView::PropertyChangeFlags propertyChange)
+void ModelPrivate::notifyNodeReparent(const InternalNode::Pointer &internalNodePointer,
+ const InternalNodeAbstractProperty::Pointer &newPropertyParent,
+ const InternalNodePointer &oldParent,
+ const PropertyName &oldPropertyName,
+ AbstractView::PropertyChangeFlags propertyChange)
{
bool resetModel = false;
QString description;
@@ -1214,9 +1234,9 @@ void ModelPrivate::notifyNodeReparent(const InternalNode::Pointer &internalNodeP
if (!newPropertyParent.isNull())
newProperty = NodeAbstractProperty(newPropertyParent, model(), view.data());
- ModelNode node(internalNodePointer, model(), view.data());
+ ModelNode modelNode(internalNodePointer, model(), view.data());
- view->nodeReparented(node, newProperty, oldProperty, propertyChange);
+ view->nodeReparented(modelNode, newProperty, oldProperty, propertyChange);
}
@@ -1229,8 +1249,8 @@ void ModelPrivate::notifyNodeReparent(const InternalNode::Pointer &internalNodeP
if (!newPropertyParent.isNull())
newProperty = NodeAbstractProperty(newPropertyParent, model(), nodeInstanceView());
- ModelNode node(internalNodePointer, model(), nodeInstanceView());
- nodeInstanceView()->nodeReparented(node, newProperty, oldProperty, propertyChange);
+ ModelNode modelNode(internalNodePointer, model(), nodeInstanceView());
+ nodeInstanceView()->nodeReparented(modelNode, newProperty, oldProperty, propertyChange);
}
if (resetModel)
@@ -1284,12 +1304,12 @@ void ModelPrivate::setSelectedNodes(const QList<InternalNode::Pointer> &selected
sortedSelectedList = sortedSelectedList.toSet().toList();
qSort(sortedSelectedList);
- if (sortedSelectedList == m_selectedNodeList)
+ if (sortedSelectedList == m_selectedInternalNodeList)
return;
- const QList<InternalNode::Pointer> lastSelectedNodeList = m_selectedNodeList;
- m_selectedNodeList = sortedSelectedList;
+ const QList<InternalNode::Pointer> lastSelectedNodeList = m_selectedInternalNodeList;
+ m_selectedInternalNodeList = sortedSelectedList;
changeSelectedNodes(sortedSelectedList, lastSelectedNodeList);
}
@@ -1297,42 +1317,42 @@ void ModelPrivate::setSelectedNodes(const QList<InternalNode::Pointer> &selected
void ModelPrivate::clearSelectedNodes()
{
- const QList<InternalNode::Pointer> lastSelectedNodeList = m_selectedNodeList;
- m_selectedNodeList.clear();
- changeSelectedNodes(m_selectedNodeList, lastSelectedNodeList);
+ const QList<InternalNode::Pointer> lastSelectedNodeList = m_selectedInternalNodeList;
+ m_selectedInternalNodeList.clear();
+ changeSelectedNodes(m_selectedInternalNodeList, lastSelectedNodeList);
}
-QList<ModelNode> ModelPrivate::toModelNodeList(const QList<InternalNode::Pointer> &nodeList, AbstractView *view) const
+QList<ModelNode> ModelPrivate::toModelNodeList(const QList<InternalNode::Pointer> &internalNodeList, AbstractView *view) const
{
QList<ModelNode> newNodeList;
- foreach (const Internal::InternalNode::Pointer &node, nodeList)
+ foreach (const Internal::InternalNode::Pointer &node, internalNodeList)
newNodeList.append(ModelNode(node, model(), view));
return newNodeList;
}
-QVector<ModelNode> ModelPrivate::toModelNodeVector(const QVector<InternalNode::Pointer> &nodeVector, AbstractView *view) const
+QVector<ModelNode> ModelPrivate::toModelNodeVector(const QVector<InternalNode::Pointer> &internalNodeVector, AbstractView *view) const
{
QVector<ModelNode> newNodeVector;
- foreach (const Internal::InternalNode::Pointer &node, nodeVector)
+ foreach (const Internal::InternalNode::Pointer &node, internalNodeVector)
newNodeVector.append(ModelNode(node, model(), view));
return newNodeVector;
}
-QList<Internal::InternalNode::Pointer> ModelPrivate::toInternalNodeList(const QList<ModelNode> &nodeList) const
+QList<Internal::InternalNode::Pointer> ModelPrivate::toInternalNodeList(const QList<ModelNode> &internalNodeList) const
{
QList<Internal::InternalNode::Pointer> newNodeList;
- foreach (const ModelNode &node, nodeList)
+ foreach (const ModelNode &node, internalNodeList)
newNodeList.append(node.internalNode());
return newNodeList;
}
-QVector<Internal::InternalNode::Pointer> ModelPrivate::toInternalNodeVector(const QVector<ModelNode> &nodeVector) const
+QVector<Internal::InternalNode::Pointer> ModelPrivate::toInternalNodeVector(const QVector<ModelNode> &internalNodeVector) const
{
QVector<Internal::InternalNode::Pointer> newNodeVector;
- foreach (const ModelNode &node, nodeVector)
+ foreach (const ModelNode &node, internalNodeVector)
newNodeVector.append(node.internalNode());
return newNodeVector;
@@ -1349,28 +1369,28 @@ void ModelPrivate::changeSelectedNodes(const QList<InternalNode::Pointer> &newSe
QList<InternalNode::Pointer> ModelPrivate::selectedNodes() const
{
- foreach (const InternalNode::Pointer &node, m_selectedNodeList) {
+ foreach (const InternalNode::Pointer &node, m_selectedInternalNodeList) {
if (!node->isValid())
throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);
}
- return m_selectedNodeList;
+ return m_selectedInternalNodeList;
}
-void ModelPrivate::selectNode(const InternalNode::Pointer &node)
+void ModelPrivate::selectNode(const InternalNode::Pointer &internalNodePointer)
{
- if (selectedNodes().contains(node))
+ if (selectedNodes().contains(internalNodePointer))
return;
QList<InternalNode::Pointer> selectedNodeList(selectedNodes());
- selectedNodeList += node;
+ selectedNodeList += internalNodePointer;
setSelectedNodes(selectedNodeList);
}
-void ModelPrivate::deselectNode(const InternalNode::Pointer &node)
+void ModelPrivate::deselectNode(const InternalNode::Pointer &internalNodePointer)
{
QList<InternalNode::Pointer> selectedNodeList(selectedNodes());
- bool isRemoved = selectedNodeList.removeOne(node);
+ bool isRemoved = selectedNodeList.removeOne(internalNodePointer);
if (!isRemoved)
return;
@@ -1410,71 +1430,77 @@ void ModelPrivate::removeProperty(const InternalProperty::Pointer &property)
notifyPropertiesRemoved(propertyPairList);
}
-void ModelPrivate::setBindingProperty(const InternalNode::Pointer &internalNode, const PropertyName &name, const QString &expression)
+void ModelPrivate::setBindingProperty(const InternalNode::Pointer &internalNodePointer, const PropertyName &name, const QString &expression)
{
AbstractView::PropertyChangeFlags propertyChange = AbstractView::NoAdditionalChanges;
- if (!internalNode->hasProperty(name)) {
- internalNode->addBindingProperty(name);
+ if (!internalNodePointer->hasProperty(name)) {
+ internalNodePointer->addBindingProperty(name);
propertyChange = AbstractView::PropertiesAdded;
}
- InternalBindingProperty::Pointer bindingProperty = internalNode->bindingProperty(name);
+ InternalBindingProperty::Pointer bindingProperty = internalNodePointer->bindingProperty(name);
bindingProperty->setExpression(expression);
notifyBindingPropertiesChanged(QList<InternalBindingPropertyPointer>() << bindingProperty, propertyChange);
}
-void ModelPrivate::setSignalHandlerProperty(const InternalNodePointer &internalNode, const PropertyName &name, const QString &source)
+void ModelPrivate::setSignalHandlerProperty(const InternalNodePointer &internalNodePointer, const PropertyName &name, const QString &source)
{
AbstractView::PropertyChangeFlags propertyChange = AbstractView::NoAdditionalChanges;
- if (!internalNode->hasProperty(name)) {
- internalNode->addSignalHandlerProperty(name);
+ if (!internalNodePointer->hasProperty(name)) {
+ internalNodePointer->addSignalHandlerProperty(name);
propertyChange = AbstractView::PropertiesAdded;
}
- InternalSignalHandlerProperty::Pointer signalHandlerProperty = internalNode->signalHandlerProperty(name);
+ InternalSignalHandlerProperty::Pointer signalHandlerProperty = internalNodePointer->signalHandlerProperty(name);
signalHandlerProperty->setSource(source);
notifySignalHandlerPropertiesChanged(QVector<InternalSignalHandlerPropertyPointer>() << signalHandlerProperty, propertyChange);
}
-void ModelPrivate::setVariantProperty(const InternalNode::Pointer &internalNode, const PropertyName &name, const QVariant &value)
+void ModelPrivate::setVariantProperty(const InternalNode::Pointer &internalNodePointer, const PropertyName &name, const QVariant &value)
{
AbstractView::PropertyChangeFlags propertyChange = AbstractView::NoAdditionalChanges;
- if (!internalNode->hasProperty(name)) {
- internalNode->addVariantProperty(name);
+ if (!internalNodePointer->hasProperty(name)) {
+ internalNodePointer->addVariantProperty(name);
propertyChange = AbstractView::PropertiesAdded;
}
- internalNode->variantProperty(name)->setValue(value);
- internalNode->variantProperty(name)->resetDynamicTypeName();
- notifyVariantPropertiesChanged(internalNode, PropertyNameList() << name, propertyChange);
+ internalNodePointer->variantProperty(name)->setValue(value);
+ internalNodePointer->variantProperty(name)->resetDynamicTypeName();
+ notifyVariantPropertiesChanged(internalNodePointer, PropertyNameList() << name, propertyChange);
}
-void ModelPrivate::setDynamicVariantProperty(const InternalNodePointer &internalNode, const PropertyName &name, const TypeName &dynamicPropertyType, const QVariant &value)
+void ModelPrivate::setDynamicVariantProperty(const InternalNodePointer &internalNodePointer,
+ const PropertyName &name,
+ const TypeName &dynamicPropertyType,
+ const QVariant &value)
{
AbstractView::PropertyChangeFlags propertyChange = AbstractView::NoAdditionalChanges;
- if (!internalNode->hasProperty(name)) {
- internalNode->addVariantProperty(name);
+ if (!internalNodePointer->hasProperty(name)) {
+ internalNodePointer->addVariantProperty(name);
propertyChange = AbstractView::PropertiesAdded;
}
- internalNode->variantProperty(name)->setDynamicValue(dynamicPropertyType, value);
- notifyVariantPropertiesChanged(internalNode, PropertyNameList() << name, propertyChange);
+ internalNodePointer->variantProperty(name)->setDynamicValue(dynamicPropertyType, value);
+ notifyVariantPropertiesChanged(internalNodePointer, PropertyNameList() << name, propertyChange);
}
-void ModelPrivate::setDynamicBindingProperty(const InternalNodePointer &internalNode, const PropertyName &name, const TypeName &dynamicPropertyType, const QString &expression)
+void ModelPrivate::setDynamicBindingProperty(const InternalNodePointer &internalNodePointer,
+ const PropertyName &name,
+ const TypeName &dynamicPropertyType,
+ const QString &expression)
{
AbstractView::PropertyChangeFlags propertyChange = AbstractView::NoAdditionalChanges;
- if (!internalNode->hasProperty(name)) {
- internalNode->addBindingProperty(name);
+ if (!internalNodePointer->hasProperty(name)) {
+ internalNodePointer->addBindingProperty(name);
propertyChange = AbstractView::PropertiesAdded;
}
- InternalBindingProperty::Pointer bindingProperty = internalNode->bindingProperty(name);
+ InternalBindingProperty::Pointer bindingProperty = internalNodePointer->bindingProperty(name);
bindingProperty->setDynamicExpression(dynamicPropertyType, expression);
notifyBindingPropertiesChanged(QList<InternalBindingPropertyPointer>() << bindingProperty, propertyChange);
}
-void ModelPrivate::reparentNode(const InternalNode::Pointer &newParentNode, const PropertyName &name, const InternalNode::Pointer &node, bool list)
+void ModelPrivate::reparentNode(const InternalNode::Pointer &newParentNode, const PropertyName &name, const InternalNode::Pointer &internalNodePointer, bool list)
{
AbstractView::PropertyChangeFlags propertyChange = AbstractView::NoAdditionalChanges;
if (!newParentNode->hasProperty(name)) {
@@ -1485,21 +1511,21 @@ void ModelPrivate::reparentNode(const InternalNode::Pointer &newParentNode, cons
propertyChange |= AbstractView::PropertiesAdded;
}
- InternalNodeAbstractProperty::Pointer oldParentProperty(node->parentProperty());
+ InternalNodeAbstractProperty::Pointer oldParentProperty(internalNodePointer->parentProperty());
InternalNode::Pointer oldParentNode;
PropertyName oldParentPropertyName;
if (oldParentProperty && oldParentProperty->isValid()) {
- oldParentNode = node->parentProperty()->propertyOwner();
- oldParentPropertyName = node->parentProperty()->name();
+ oldParentNode = internalNodePointer->parentProperty()->propertyOwner();
+ oldParentPropertyName = internalNodePointer->parentProperty()->name();
}
InternalNodeAbstractProperty::Pointer newParentProperty(newParentNode->nodeAbstractProperty(name));
Q_ASSERT(!newParentProperty.isNull());
- notifyNodeAboutToBeReparent(node, newParentProperty, oldParentNode, oldParentPropertyName, propertyChange);
+ notifyNodeAboutToBeReparent(internalNodePointer, newParentProperty, oldParentNode, oldParentPropertyName, propertyChange);
if (newParentProperty)
- node->setParentProperty(newParentProperty);
+ internalNodePointer->setParentProperty(newParentProperty);
if (oldParentProperty && oldParentProperty->isValid() && oldParentProperty->isEmpty()) {
@@ -1508,22 +1534,22 @@ void ModelPrivate::reparentNode(const InternalNode::Pointer &newParentNode, cons
propertyChange |= AbstractView::EmptyPropertiesRemoved;
}
- notifyNodeReparent(node, newParentProperty, oldParentNode, oldParentPropertyName, propertyChange);
+ notifyNodeReparent(internalNodePointer, newParentProperty, oldParentNode, oldParentPropertyName, propertyChange);
}
-void ModelPrivate::clearParent(const InternalNodePointer &node)
+void ModelPrivate::clearParent(const InternalNodePointer &internalNodePointer)
{
- InternalNodeAbstractProperty::Pointer oldParentProperty(node->parentProperty());
+ InternalNodeAbstractProperty::Pointer oldParentProperty(internalNodePointer->parentProperty());
InternalNode::Pointer oldParentNode;
PropertyName oldParentPropertyName;
if (oldParentProperty->isValid()) {
- oldParentNode = node->parentProperty()->propertyOwner();
- oldParentPropertyName = node->parentProperty()->name();
+ oldParentNode = internalNodePointer->parentProperty()->propertyOwner();
+ oldParentPropertyName = internalNodePointer->parentProperty()->name();
}
- node->resetParentProperty();
- notifyNodeReparent(node, InternalNodeAbstractProperty::Pointer(), oldParentNode, oldParentPropertyName, AbstractView::NoAdditionalChanges);
+ internalNodePointer->resetParentProperty();
+ notifyNodeReparent(internalNodePointer, InternalNodeAbstractProperty::Pointer(), oldParentNode, oldParentPropertyName, AbstractView::NoAdditionalChanges);
}
void ModelPrivate::changeRootNodeType(const TypeName &type, int majorVersion, int minorVersion)
@@ -1535,17 +1561,17 @@ void ModelPrivate::changeRootNodeType(const TypeName &type, int majorVersion, in
notifyRootNodeTypeChanged(type, majorVersion, minorVersion);
}
-void ModelPrivate::setScriptFunctions(const InternalNode::Pointer &internalNode, const QStringList &scriptFunctionList)
+void ModelPrivate::setScriptFunctions(const InternalNode::Pointer &internalNodePointer, const QStringList &scriptFunctionList)
{
- internalNode->setScriptFunctions(scriptFunctionList);
+ internalNodePointer->setScriptFunctions(scriptFunctionList);
- notifyScriptFunctionsChanged(internalNode, scriptFunctionList);
+ notifyScriptFunctionsChanged(internalNodePointer, scriptFunctionList);
}
-void ModelPrivate::setNodeSource(const InternalNodePointer &internalNode, const QString &nodeSource)
+void ModelPrivate::setNodeSource(const InternalNodePointer &internalNodePointer, const QString &nodeSource)
{
- internalNode->setNodeSource(nodeSource);
- notifyNodeSourceChanged(internalNode, nodeSource);
+ internalNodePointer->setNodeSource(nodeSource);
+ notifyNodeSourceChanged(internalNodePointer, nodeSource);
}
void ModelPrivate::changeNodeOrder(const InternalNode::Pointer &internalParentNode, const PropertyName &listPropertyName, int from, int to)
@@ -1640,9 +1666,9 @@ bool ModelPrivate::isWriteLocked() const
return m_writeLock;
}
-InternalNode::Pointer ModelPrivate::actualStateNode() const
+InternalNode::Pointer ModelPrivate::currentStateNode() const
{
- return m_acutalStateNode;
+ return m_currentStateNode;
}
@@ -1703,6 +1729,27 @@ QList<Import> Model::imports() const
return d->imports();
}
+QList<Import> Model::possibleImports() const
+{
+ QList<Import> possibleImportList;
+
+ possibleImportList.append(Import::createLibraryImport("QtQuick", "2.1"));
+ possibleImportList.append(Import::createLibraryImport("QtQuick.Controls", "1.0"));
+ possibleImportList.append(Import::createLibraryImport("QtQuick.Layouts", "1.0"));
+ possibleImportList.append(Import::createLibraryImport("QtQuick.Window", "2.0"));
+
+ return possibleImportList;
+}
+
+QList<Import> Model::usedImports() const
+{
+ QList<Import> usedImportList;
+
+ usedImportList.append(Import::createLibraryImport("QtQuick"));
+
+ return usedImportList;
+}
+
void Model::changeImports(const QList<Import> &importsToBeAdded, const QList<Import> &importsToBeRemoved)
{
d->changeImports(importsToBeAdded, importsToBeRemoved);
@@ -1798,6 +1845,16 @@ Model *Model::metaInfoProxyModel()
return this;
}
+TextModifier *Model::textModifier() const
+{
+ return d->m_textModifier.data();
+}
+
+void Model::setTextModifier(TextModifier *textModifier)
+{
+ d->m_textModifier = textModifier;
+}
+
#if 0
/*!
\brief Creates a new empty model
diff --git a/src/plugins/qmldesigner/designercore/model/model_p.h b/src/plugins/qmldesigner/designercore/model/model_p.h
index ae0f156eb5..7dcc150491 100644
--- a/src/plugins/qmldesigner/designercore/model/model_p.h
+++ b/src/plugins/qmldesigner/designercore/model/model_p.h
@@ -132,13 +132,13 @@ public:
void notifyNodeCreated(const InternalNodePointer &newInternalNodePointer);
void notifyNodeAboutToBeReparent(const InternalNodePointer &internalNodePointer, const InternalNodeAbstractPropertyPointer &newPropertyParent, const InternalNodePointer &oldParent, const PropertyName &oldPropertyName, AbstractView::PropertyChangeFlags propertyChange);
void notifyNodeReparent(const InternalNodePointer &internalNodePointer, const InternalNodeAbstractPropertyPointer &newPropertyParent, const InternalNodePointer &oldParent, const PropertyName &oldPropertyName, AbstractView::PropertyChangeFlags propertyChange);
- void notifyNodeAboutToBeRemoved(const InternalNodePointer &nodePointer);
- void notifyNodeRemoved(const InternalNodePointer &nodePointer, const InternalNodePointer &parentNodePointer, const PropertyName &parentPropertyName, AbstractView::PropertyChangeFlags propertyChange);
- void notifyNodeIdChanged(const InternalNodePointer& nodePointer, const QString& newId, const QString& oldId);
+ void notifyNodeAboutToBeRemoved(const InternalNodePointer &internalNodePointer);
+ void notifyNodeRemoved(const InternalNodePointer &internalNodePointer, const InternalNodePointer &parentNodePointer, const PropertyName &parentPropertyName, AbstractView::PropertyChangeFlags propertyChange);
+ void notifyNodeIdChanged(const InternalNodePointer& internalNodePointer, const QString& newId, const QString& oldId);
void notifyPropertiesRemoved(const QList<PropertyPair> &propertyList);
- void notifyPropertiesAboutToBeRemoved(const QList<InternalPropertyPointer> &propertyList);
- void notifyBindingPropertiesChanged(const QList<InternalBindingPropertyPointer> &propertyList, AbstractView::PropertyChangeFlags propertyChange);
+ void notifyPropertiesAboutToBeRemoved(const QList<InternalPropertyPointer> &internalPropertyList);
+ void notifyBindingPropertiesChanged(const QList<InternalBindingPropertyPointer> &internalPropertyList, AbstractView::PropertyChangeFlags propertyChange);
void notifySignalHandlerPropertiesChanged(const QVector<InternalSignalHandlerPropertyPointer> &propertyList, AbstractView::PropertyChangeFlags propertyChange);
void notifyVariantPropertiesChanged(const InternalNodePointer &internalNodePointer, const PropertyNameList &propertyNameList, AbstractView::PropertyChangeFlags propertyChange);
void notifyScriptFunctionsChanged(const InternalNodePointer &internalNodePointer, const QStringList &scriptFunctionList);
@@ -158,7 +158,7 @@ public:
void notifyInstancesChildrenChanged(const QVector<ModelNode> &nodeList);
void notifyInstanceToken(const QString &token, int number, const QVector<ModelNode> &nodeVector);
- void notifyActualStateChanged(const ModelNode &node);
+ void notifyCurrentStateChanged(const ModelNode &node);
void notifyRewriterBeginTransaction();
void notifyRewriterEndTransaction();
@@ -166,8 +166,8 @@ public:
void setSelectedNodes(const QList<InternalNodePointer> &selectedNodeList);
void clearSelectedNodes();
QList<InternalNodePointer> selectedNodes() const;
- void selectNode(const InternalNodePointer &node);
- void deselectNode(const InternalNodePointer &node);
+ void selectNode(const InternalNodePointer &internalNodePointer);
+ void deselectNode(const InternalNodePointer &internalNodePointer);
void changeSelectedNodes(const QList<InternalNodePointer> &newSelectedsNodeList,
const QList<InternalNodePointer> &oldSelectedsNodeList);
@@ -189,15 +189,15 @@ public:
void setPropertyValue(const InternalNodePointer &node,const PropertyName &name, const QVariant &value);
void removeProperty(const InternalPropertyPointer &property);
- void setBindingProperty(const InternalNodePointer &internalNode, const PropertyName &name, const QString &expression);
- void setSignalHandlerProperty(const InternalNodePointer &internalNode, const PropertyName &name, const QString &source);
- void setVariantProperty(const InternalNodePointer &internalNode, const PropertyName &name, const QVariant &value);
- void setDynamicVariantProperty(const InternalNodePointer &internalNode, const PropertyName &name, const TypeName &propertyType, const QVariant &value);
- void setDynamicBindingProperty(const InternalNodePointer &internalNode, const PropertyName &name, const TypeName &dynamicPropertyType, const QString &expression);
- void reparentNode(const InternalNodePointer &internalNode, const PropertyName &name, const InternalNodePointer &internalNodeToBeAppended, bool list = true);
+ void setBindingProperty(const InternalNodePointer &internalNodePointer, const PropertyName &name, const QString &expression);
+ void setSignalHandlerProperty(const InternalNodePointer &internalNodePointer, const PropertyName &name, const QString &source);
+ void setVariantProperty(const InternalNodePointer &internalNodePointer, const PropertyName &name, const QVariant &value);
+ void setDynamicVariantProperty(const InternalNodePointer &internalNodePointer, const PropertyName &name, const TypeName &propertyType, const QVariant &value);
+ void setDynamicBindingProperty(const InternalNodePointer &internalNodePointer, const PropertyName &name, const TypeName &dynamicPropertyType, const QString &expression);
+ void reparentNode(const InternalNodePointer &internalNodePointer, const PropertyName &name, const InternalNodePointer &internalNodeToBeAppended, bool list = true);
void changeNodeOrder(const InternalNodePointer &internalParentNode, const PropertyName &listPropertyName, int from, int to);
void checkPropertyName(const QString &propertyName);
- void clearParent(const InternalNodePointer &internalNode);
+ void clearParent(const InternalNodePointer &internalNodePointer);
void changeRootNodeType(const TypeName &type, int majorVersion, int minorVersion);
void setScriptFunctions(const InternalNodePointer &internalNode, const QStringList &scriptFunctionList);
void setNodeSource(const InternalNodePointer &internalNode, const QString &nodeSource);
@@ -221,31 +221,32 @@ public:
void setNodeInstanceView(NodeInstanceView *nodeInstanceView);
NodeInstanceView *nodeInstanceView() const;
- InternalNodePointer actualStateNode() const;
+ InternalNodePointer currentStateNode() const;
private: //functions
void removePropertyWithoutNotification(const InternalPropertyPointer &property);
- void removeAllSubNodes(const InternalNodePointer &node);
- void removeNodeFromModel(const InternalNodePointer &node);
- QList<InternalNodePointer> toInternalNodeList(const QList<ModelNode> &nodeList) const;
- QList<ModelNode> toModelNodeList(const QList<InternalNodePointer> &nodeList, AbstractView *view) const;
- QVector<ModelNode> toModelNodeVector(const QVector<InternalNodePointer> &nodeVector, AbstractView *view) const;
- QVector<InternalNodePointer> toInternalNodeVector(const QVector<ModelNode> &nodeVector) const;
+ void removeAllSubNodes(const InternalNodePointer &internalNodePointer);
+ void removeNodeFromModel(const InternalNodePointer &internalNodePointer);
+ QList<InternalNodePointer> toInternalNodeList(const QList<ModelNode> &internalNodeList) const;
+ QList<ModelNode> toModelNodeList(const QList<InternalNodePointer> &internalNodeList, AbstractView *view) const;
+ QVector<ModelNode> toModelNodeVector(const QVector<InternalNodePointer> &internalNodeVector, AbstractView *view) const;
+ QVector<InternalNodePointer> toInternalNodeVector(const QVector<ModelNode> &internalNodeVector) const;
private:
Model *m_q;
MetaInfo m_metaInfo;
QList<Import> m_imports;
QList<QWeakPointer<AbstractView> > m_viewList;
- QList<InternalNodePointer> m_selectedNodeList;
+ QList<InternalNodePointer> m_selectedInternalNodeList;
QHash<QString,InternalNodePointer> m_idNodeHash;
QHash<qint32, InternalNodePointer> m_internalIdNodeHash;
QSet<InternalNodePointer> m_nodeSet;
- InternalNodePointer m_acutalStateNode;
+ InternalNodePointer m_currentStateNode;
InternalNodePointer m_rootInternalNode;
QUrl m_fileUrl;
QWeakPointer<RewriterView> m_rewriterView;
QWeakPointer<NodeInstanceView> m_nodeInstanceView;
+ QWeakPointer<TextModifier> m_textModifier;
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 ba919e70ef..1a73394c21 100644
--- a/src/plugins/qmldesigner/designercore/model/modelmerger.cpp
+++ b/src/plugins/qmldesigner/designercore/model/modelmerger.cpp
@@ -60,7 +60,7 @@ static QString fixExpression(const QString &expression, const QHash<QString, QSt
static void syncVariantProperties(ModelNode &outputNode, const ModelNode &inputNode)
{
foreach (const VariantProperty &variantProperty, inputNode.variantProperties()) {
- outputNode.variantProperty(variantProperty.name()) = variantProperty.value();
+ outputNode.variantProperty(variantProperty.name()).setValue(variantProperty.value());
}
}
diff --git a/src/plugins/qmldesigner/designercore/model/modelnode.cpp b/src/plugins/qmldesigner/designercore/model/modelnode.cpp
index 54191a62a1..7925ee468e 100644
--- a/src/plugins/qmldesigner/designercore/model/modelnode.cpp
+++ b/src/plugins/qmldesigner/designercore/model/modelnode.cpp
@@ -38,6 +38,7 @@
#include "invalidargumentexception.h"
#include "invalididexception.h"
#include "invalidmodelnodeexception.h"
+#include "invalidpropertyexception.h"
#include "model_p.h"
#include "variantproperty.h"
#include "bindingproperty.h"
@@ -77,10 +78,10 @@ All the manipulation functions are generating undo commands internally.
/*! \brief internal constructor
*/
-ModelNode::ModelNode(const InternalNodePointer &internalNode, Model *model, AbstractView *view):
+ModelNode::ModelNode(const InternalNodePointer &internalNode, Model *model, const AbstractView *view):
m_internalNode(internalNode),
m_model(model),
- m_view(view)
+ m_view(const_cast<AbstractView*>(view))
{
Q_ASSERT(!m_model || m_view);
}
@@ -125,19 +126,6 @@ ModelNode::~ModelNode()
{
}
-QString ModelNode::generateNewId() const
-{
- int counter = 1;
- QString newId = QString("%1%2").arg(QString::fromUtf8(simplifiedTypeName()).toLower()).arg(counter);
-
- while (view()->hasId(newId)) {
- counter += 1;
- newId = QString("%1%2").arg(QString::fromUtf8(simplifiedTypeName()).toLower()).arg(counter);
- }
-
- return newId;
-}
-
/*! \brief returns the name of node which is a short cut to a property like objectName
\return name of the node
*/
@@ -152,7 +140,7 @@ QString ModelNode::id() const
QString ModelNode::validId()
{
if (id().isEmpty())
- setId(generateNewId());
+ setId(view()->generateNewId(QString::fromUtf8(simplifiedTypeName())));
return id();
}
@@ -232,54 +220,6 @@ int ModelNode::majorVersion() const
return m_internalNode->majorVersion();
}
-int getMajorVersionFromImport(Model *model)
-{
- foreach (const Import &import, model->imports()) {
- if (import.isLibraryImport() && import.url() == QLatin1String("QtQuick")) {
- const QString versionString = import.version();
- if (versionString.contains(QLatin1String("."))) {
- const QString majorVersionString = versionString.split(QLatin1String(".")).first();
- return majorVersionString.toInt();
- }
- }
- }
-
- return -1;
-}
-
-int getMajorVersionFromNode(const ModelNode &modelNode)
-{
- if (modelNode.metaInfo().isValid()) {
- if (modelNode.type() == "QtQuick.QtObject" || modelNode.type() == "QtQuick.Item")
- return modelNode.majorVersion();
-
- foreach (const NodeMetaInfo &superClass, modelNode.metaInfo().superClasses()) {
- if (modelNode.type() == "QtQuick.QtObject" || modelNode.type() == "QtQuick.Item")
- return superClass.majorVersion();
- }
- }
-
- return 1; //default
-}
-
-/*! \brief major number of the QtQuick version used
-\return major number of QtQuickVersion
-*/
-int ModelNode::majorQtQuickVersion() const
-{
- if (!isValid()) {
- Q_ASSERT_X(isValid(), Q_FUNC_INFO, "model node is invalid");
- throw InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);
- }
-
- int majorVersionFromImport = getMajorVersionFromImport(model());
- if (majorVersionFromImport >= 0)
- return majorVersionFromImport;
-
- return getMajorVersionFromNode(*this);
-}
-
-
/*! \return the short-hand type name of the node. */
TypeName ModelNode::simplifiedTypeName() const
{
@@ -338,8 +278,11 @@ NodeAbstractProperty ModelNode::parentProperty() const
Q_ASSERT_X(isValid(), Q_FUNC_INFO, "model node is invalid");
throw InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);
}
- if (m_internalNode->parentProperty().isNull())
- return NodeAbstractProperty();
+
+ if (m_internalNode->parentProperty().isNull()) {
+ Q_ASSERT_X(m_internalNode->parentProperty(), Q_FUNC_INFO, "parentProperty is invalid");
+ throw InvalidPropertyException(__LINE__, __FUNCTION__, __FILE__, "parent");
+ }
return NodeAbstractProperty(m_internalNode->parentProperty()->name(), m_internalNode->parentProperty()->propertyOwner(), m_model.data(), view());
}
@@ -475,7 +418,12 @@ NodeAbstractProperty ModelNode::nodeAbstractProperty(const PropertyName &name) c
if (!isValid())
throw InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);
- return NodeAbstractProperty(name, m_internalNode, model(), view());
+ return NodeAbstractProperty(name, m_internalNode, model(), view());
+}
+
+NodeAbstractProperty ModelNode::defaultNodeAbstractProperty() const
+{
+ return nodeAbstractProperty(metaInfo().defaultPropertyName());
}
@@ -785,6 +733,16 @@ const NodeMetaInfo ModelNode::metaInfo() const
return NodeMetaInfo(model()->metaInfoProxyModel(), type(), majorVersion(), minorVersion());
}
+bool ModelNode::hasMetaInfo() const
+{
+ if (!isValid()) {
+ Q_ASSERT_X(isValid(), Q_FUNC_INFO, "model node is invalid");
+ throw InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);
+ }
+
+ return model()->hasNodeMetaInfo(type(), majorVersion(), minorVersion());
+}
+
/*! \brief has a node the selection of the model
\return true if the node his selection
*/
@@ -849,6 +807,11 @@ bool ModelNode::hasNodeAbstracProperty(const PropertyName &name) const
return hasProperty(name) && internalNode()->property(name)->isNodeAbstractProperty();
}
+bool ModelNode::hasDefaultNodeAbstracProperty() const
+{
+ return hasProperty(metaInfo().defaultPropertyName()) && internalNode()->property(metaInfo().defaultPropertyName())->isNodeAbstractProperty();
+}
+
bool ModelNode::hasNodeProperty(const PropertyName &name) const
{
return hasProperty(name) && internalNode()->property(name)->isNodeProperty();
@@ -1025,4 +988,26 @@ ModelNode::NodeSourceType ModelNode::nodeSourceType() const
}
+bool ModelNode::isComponent() const
+{
+ if (!isValid())
+ throw InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);
+
+ if (metaInfo().isFileComponent())
+ return true;
+
+ if (nodeSourceType() == ModelNode::NodeWithComponentSource)
+ return true;
+
+ if (metaInfo().isView() && hasNodeProperty("delegate")) {
+ if (nodeProperty("delegate").modelNode().metaInfo().isFileComponent())
+ return true;
+
+ if (nodeProperty("delegate").modelNode().nodeSourceType() == ModelNode::NodeWithComponentSource)
+ return true;
+ }
+
+ return false;
+}
+
}
diff --git a/src/plugins/qmldesigner/designercore/model/nodeabstractproperty.cpp b/src/plugins/qmldesigner/designercore/model/nodeabstractproperty.cpp
index dbe3a96a81..4dc5fc6e7c 100644
--- a/src/plugins/qmldesigner/designercore/model/nodeabstractproperty.cpp
+++ b/src/plugins/qmldesigner/designercore/model/nodeabstractproperty.cpp
@@ -65,7 +65,7 @@ void NodeAbstractProperty::reparentHere(const ModelNode &modelNode)
void NodeAbstractProperty::reparentHere(const ModelNode &modelNode, bool isNodeList)
{
- if (modelNode.parentProperty() == *this)
+ if (modelNode.hasParentProperty() && modelNode.parentProperty() == *this)
return;
Internal::WriteLocker locker(model());
if (!isValid())
diff --git a/src/plugins/qmldesigner/designercore/model/nodelistproperty.cpp b/src/plugins/qmldesigner/designercore/model/nodelistproperty.cpp
index 9f5ff031d3..61fd8ad7c3 100644
--- a/src/plugins/qmldesigner/designercore/model/nodelistproperty.cpp
+++ b/src/plugins/qmldesigner/designercore/model/nodelistproperty.cpp
@@ -84,17 +84,15 @@ const QList<ModelNode> NodeListProperty::toModelNodeList() const
const QList<QmlObjectNode> NodeListProperty::toQmlObjectNodeList() const
{
- QmlModelView *fxView = view()->toQmlModelView();
-
- if (fxView == 0)
+ if (model()->nodeInstanceView())
return QList<QmlObjectNode>();
- QList<QmlObjectNode> fxObjectNodeList;
+ QList<QmlObjectNode> qmlObjectNodeList;
foreach (const ModelNode &modelNode, toModelNodeList())
- fxObjectNodeList.append(QmlObjectNode(modelNode));
+ qmlObjectNodeList.append(QmlObjectNode(modelNode));
- return fxObjectNodeList;
+ return qmlObjectNodeList;
}
void NodeListProperty::slide(int from, int to) const
diff --git a/src/plugins/qmldesigner/designercore/model/qmlanchors.cpp b/src/plugins/qmldesigner/designercore/model/qmlanchors.cpp
index 73c392b85c..9284c907f7 100644
--- a/src/plugins/qmldesigner/designercore/model/qmlanchors.cpp
+++ b/src/plugins/qmldesigner/designercore/model/qmlanchors.cpp
@@ -31,7 +31,7 @@
#include "bindingproperty.h"
#include "nodeabstractproperty.h"
#include "rewritertransaction.h"
-#include "qmlmodelview.h"
+#include "nodeinstanceview.h"
namespace QmlDesigner {
@@ -119,6 +119,54 @@ QmlItemNode QmlAnchors::qmlItemNode() const
return m_qmlItemNode;
}
+bool QmlAnchors::modelHasAnchors() const
+{
+ return modelHasAnchor(AnchorLine::Left)
+ || modelHasAnchor(AnchorLine::Right)
+ || modelHasAnchor(AnchorLine::Top)
+ || modelHasAnchor(AnchorLine::Bottom)
+ || modelHasAnchor(AnchorLine::HorizontalCenter)
+ || modelHasAnchor(AnchorLine::VerticalCenter)
+ || modelHasAnchor(AnchorLine::Baseline);
+}
+
+bool QmlAnchors::modelHasAnchor(AnchorLine::Type sourceAnchorLineType) const
+{
+ const PropertyName propertyName = anchorPropertyName(sourceAnchorLineType);
+
+ if (sourceAnchorLineType & AnchorLine::Fill)
+ return qmlItemNode().modelNode().hasBindingProperty(propertyName) || qmlItemNode().modelNode().hasBindingProperty("anchors.fill");
+
+ if (sourceAnchorLineType & AnchorLine::Center)
+ return qmlItemNode().modelNode().hasBindingProperty(propertyName) || qmlItemNode().modelNode().hasBindingProperty("anchors.centerIn");
+
+ return qmlItemNode().modelNode().hasBindingProperty(anchorPropertyName(sourceAnchorLineType));
+}
+
+AnchorLine QmlAnchors::modelAnchor(AnchorLine::Type sourceAnchorLineType) const
+{
+ QPair<PropertyName, ModelNode> targetAnchorLinePair;
+ if (sourceAnchorLineType & AnchorLine::Fill && qmlItemNode().modelNode().hasBindingProperty("anchors.fill")) {
+ targetAnchorLinePair.second = qmlItemNode().modelNode().bindingProperty("anchors.fill").resolveToModelNode();
+ targetAnchorLinePair.first = lineTypeToString(sourceAnchorLineType);
+ } else if (sourceAnchorLineType & AnchorLine::Center && qmlItemNode().modelNode().hasBindingProperty("anchors.centerIn")) {
+ targetAnchorLinePair.second = qmlItemNode().modelNode().bindingProperty("anchors.centerIn").resolveToModelNode();
+ targetAnchorLinePair.first = lineTypeToString(sourceAnchorLineType);
+ } else {
+ AbstractProperty binding = qmlItemNode().modelNode().bindingProperty(anchorPropertyName(sourceAnchorLineType)).resolveToProperty();
+ targetAnchorLinePair.first = binding.name();
+ targetAnchorLinePair.second = binding.parentModelNode();
+ }
+
+ AnchorLine::Type targetAnchorLine = propertyNameToLineType(targetAnchorLinePair.first);
+
+ if (targetAnchorLine == AnchorLine::Invalid )
+ return AnchorLine();
+
+
+ return AnchorLine(QmlItemNode(targetAnchorLinePair.second), targetAnchorLine);
+}
+
bool QmlAnchors::isValid() const
{
return m_qmlItemNode.isValid();
@@ -128,7 +176,7 @@ void QmlAnchors::setAnchor(AnchorLine::Type sourceAnchorLine,
const QmlItemNode &targetQmlItemNode,
AnchorLine::Type targetAnchorLine)
{
- RewriterTransaction transaction = qmlItemNode().qmlModelView()->beginRewriterTransaction();
+ RewriterTransaction transaction = qmlItemNode().view()->beginRewriterTransaction();
if (qmlItemNode().isInBaseState()) {
if ((qmlItemNode().nodeInstance().hasAnchor("anchors.fill") && (sourceAnchorLine & AnchorLine::Fill))
|| ((qmlItemNode().nodeInstance().hasAnchor("anchors.centerIn") && (sourceAnchorLine & AnchorLine::Center)))) {
@@ -136,7 +184,8 @@ void QmlAnchors::setAnchor(AnchorLine::Type sourceAnchorLine,
}
const PropertyName propertyName = anchorPropertyName(sourceAnchorLine);
- QString targetExpression = targetQmlItemNode.modelNode().validId();
+ ModelNode targetModelNode = targetQmlItemNode.modelNode();
+ QString targetExpression = targetModelNode.validId();
if (targetQmlItemNode.modelNode() == qmlItemNode().modelNode().parentProperty().parentModelNode())
targetExpression = "parent";
if (sourceAnchorLine != AnchorLine::Center && sourceAnchorLine != AnchorLine::Fill)
@@ -276,12 +325,12 @@ AnchorLine QmlAnchors::instanceAnchor(AnchorLine::Type sourceAnchorLine) const
if (targetAnchorLinePair.second < 0) //there might be no node instance for the parent
return AnchorLine();
- return AnchorLine(QmlItemNode(qmlItemNode().nodeForInstance(qmlItemNode().qmlModelView()->nodeInstanceView()->instanceForId(targetAnchorLinePair.second))), targetAnchorLine);
+ return AnchorLine(QmlItemNode(qmlItemNode().nodeForInstance(qmlItemNode().nodeInstanceView()->instanceForId(targetAnchorLinePair.second))), targetAnchorLine);
}
void QmlAnchors::removeAnchor(AnchorLine::Type sourceAnchorLine)
{
- RewriterTransaction transaction = qmlItemNode().qmlModelView()->beginRewriterTransaction();
+ RewriterTransaction transaction = qmlItemNode().view()->beginRewriterTransaction();
if (qmlItemNode().isInBaseState()) {
const PropertyName propertyName = anchorPropertyName(sourceAnchorLine);
if (qmlItemNode().nodeInstance().hasAnchor("anchors.fill") && (sourceAnchorLine & AnchorLine::Fill)) {
@@ -303,7 +352,7 @@ void QmlAnchors::removeAnchor(AnchorLine::Type sourceAnchorLine)
void QmlAnchors::removeAnchors()
{
- RewriterTransaction transaction = qmlItemNode().qmlModelView()->beginRewriterTransaction();
+ RewriterTransaction transaction = qmlItemNode().view()->beginRewriterTransaction();
if (qmlItemNode().nodeInstance().hasAnchor("anchors.fill"))
qmlItemNode().modelNode().removeProperty("anchors.fill");
if (qmlItemNode().nodeInstance().hasAnchor("anchors.centerIn"))
@@ -491,7 +540,7 @@ void QmlAnchors::removeMargin(AnchorLine::Type sourceAnchorLineType)
void QmlAnchors::removeMargins()
{
- RewriterTransaction transaction = qmlItemNode().qmlModelView()->beginRewriterTransaction();
+ RewriterTransaction transaction = qmlItemNode().view()->beginRewriterTransaction();
removeMargin(AnchorLine::Left);
removeMargin(AnchorLine::Right);
removeMargin(AnchorLine::Top);
diff --git a/src/plugins/qmldesigner/designercore/model/qmlchangeset.cpp b/src/plugins/qmldesigner/designercore/model/qmlchangeset.cpp
index aec42974ba..2602e96bbb 100644
--- a/src/plugins/qmldesigner/designercore/model/qmlchangeset.cpp
+++ b/src/plugins/qmldesigner/designercore/model/qmlchangeset.cpp
@@ -30,7 +30,7 @@
#include "qmlchangeset.h"
#include "bindingproperty.h"
#include "variantproperty.h"
-#include "qmlmodelview.h"
+#include "abstractview.h"
#include <metainfo.h>
namespace QmlDesigner {
@@ -50,19 +50,29 @@ void QmlModelStateOperation::setTarget(const ModelNode &target)
bool QmlPropertyChanges::isValid() const
{
- return QmlModelNodeFacade::isValid() && modelNode().metaInfo().isSubclassOf("QtQuick.PropertyChanges", -1, -1);
+ return isValidQmlPropertyChanges(modelNode());
+}
+
+bool QmlPropertyChanges::isValidQmlPropertyChanges(const ModelNode &modelNode)
+{
+ return isValidQmlModelNodeFacade(modelNode) && modelNode.metaInfo().isSubclassOf("QtQuick.PropertyChanges", -1, -1);
}
bool QmlModelStateOperation::isValid() const
{
- return QmlModelNodeFacade::isValid() && (
- modelNode().metaInfo().isSubclassOf("<cpp>.QDeclarative1StateOperation", -1, -1)
- || modelNode().metaInfo().isSubclassOf("<cpp>.QQuickStateOperation", -1, -1));
+ return isValidQmlModelStateOperation(modelNode());
+}
+
+bool QmlModelStateOperation::isValidQmlModelStateOperation(const ModelNode &modelNode)
+{
+ return isValidQmlModelNodeFacade(modelNode)
+ && (modelNode.metaInfo().isSubclassOf("<cpp>.QDeclarative1StateOperation", -1, -1)
+ || modelNode.metaInfo().isSubclassOf("<cpp>.QQuickStateOperation", -1, -1));
}
void QmlPropertyChanges::removeProperty(const PropertyName &name)
{
- RewriterTransaction transaction(qmlModelView()->beginRewriterTransaction());
+ RewriterTransaction transaction(view()->beginRewriterTransaction());
if (name == "name")
return;
modelNode().removeProperty(name);
diff --git a/src/plugins/qmldesigner/designercore/model/qmlitemnode.cpp b/src/plugins/qmldesigner/designercore/model/qmlitemnode.cpp
index 0da7a5445c..17da2a3bea 100644
--- a/src/plugins/qmldesigner/designercore/model/qmlitemnode.cpp
+++ b/src/plugins/qmldesigner/designercore/model/qmlitemnode.cpp
@@ -31,9 +31,21 @@
#include <metainfo.h>
#include "qmlchangeset.h"
#include "nodelistproperty.h"
+#include "variantproperty.h"
#include "qmlanchors.h"
#include "invalidmodelnodeexception.h"
-#include "qmlmodelview.h"
+#include "itemlibraryinfo.h"
+
+#include "plaintexteditmodifier.h"
+#include "rewriterview.h"
+#include "modelmerger.h"
+#include "rewritingexception.h"
+
+#include <QMessageBox>
+#include <QUrl>
+#include <QPlainTextEdit>
+#include <QFileInfo>
+#include <QDir>
namespace QmlDesigner {
@@ -48,9 +60,189 @@ bool QmlItemNode::isItemOrWindow(const ModelNode &modelNode)
return false;
}
+static QmlItemNode createQmlItemNodeFromSource(AbstractView *view, const QString &source, const QPointF &position)
+{
+ QScopedPointer<Model> inputModel(Model::create("QtQuick.Item", 1, 0, view->model()));
+ inputModel->setFileUrl(view->model()->fileUrl());
+ QPlainTextEdit textEdit;
+
+ textEdit.setPlainText(source);
+ NotIndentingTextEditModifier modifier(&textEdit);
+
+ QScopedPointer<RewriterView> rewriterView(new RewriterView(RewriterView::Amend, 0));
+ rewriterView->setCheckSemanticErrors(false);
+ rewriterView->setTextModifier(&modifier);
+ inputModel->setRewriterView(rewriterView.data());
+
+ if (rewriterView->errors().isEmpty() && rewriterView->rootModelNode().isValid()) {
+ ModelNode rootModelNode = rewriterView->rootModelNode();
+ inputModel->detachView(rewriterView.data());
+
+ rootModelNode.variantProperty("x").setValue(qRound(position.x()));
+ rootModelNode.variantProperty("y").setValue(qRound(position.y()));
+
+ ModelMerger merger(view);
+ return merger.insertModel(rootModelNode);
+ }
+
+ return QmlItemNode();
+}
+
+
+QmlItemNode QmlItemNode::createQmlItemNode(AbstractView *view, const ItemLibraryEntry &itemLibraryEntry, const QPointF &position, QmlItemNode parentQmlItemNode)
+{
+ if (!parentQmlItemNode.isValid())
+ parentQmlItemNode = QmlItemNode(view->rootModelNode());
+
+ Q_ASSERT(parentQmlItemNode.isValid());
+
+ QmlItemNode newQmlItemNode;
+
+ try {
+ RewriterTransaction transaction = view->beginRewriterTransaction();
+
+ NodeMetaInfo metaInfo = view->model()->metaInfo(itemLibraryEntry.typeName());
+
+ int minorVersion = metaInfo.minorVersion();
+ int majorVersion = metaInfo.majorVersion();
+
+ if (itemLibraryEntry.typeName().contains('.')) {
+
+ const QString newImportUrl = itemLibraryEntry.requiredImport();
+
+ if (!itemLibraryEntry.requiredImport().isEmpty()) {
+ 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);
+
+ foreach (const Import &import, view->model()->imports()) {
+ if (import.isLibraryImport()
+ && import.url() == newImport.url()
+ && import.version() == newImport.version()) {
+ // reuse this import
+ newImport = import;
+ break;
+ }
+ }
+
+ if (!view->model()->hasImport(newImport, true, true))
+ view->model()->changeImports(QList<Import>() << newImport, QList<Import>());
+ }
+ }
+
+ if (itemLibraryEntry.qmlSource().isEmpty()) {
+ QList<QPair<PropertyName, QVariant> > propertyPairList;
+ propertyPairList.append(qMakePair(PropertyName("x"), QVariant(qRound(position.x()))));
+ propertyPairList.append(qMakePair(PropertyName("y"), QVariant(qRound(position.y()))));
+
+ foreach (const PropertyContainer &property, itemLibraryEntry.properties())
+ propertyPairList.append(qMakePair(property.name(), property.value()));
+
+ newQmlItemNode = QmlItemNode(view->createModelNode(itemLibraryEntry.typeName(), majorVersion, minorVersion, propertyPairList));
+ } else {
+ newQmlItemNode = createQmlItemNodeFromSource(view, itemLibraryEntry.qmlSource(), position);
+ }
+
+ if (parentQmlItemNode.hasDefaultPropertyName())
+ parentQmlItemNode.nodeAbstractProperty(parentQmlItemNode.defaultPropertyName()).reparentHere(newQmlItemNode);
+
+ if (!newQmlItemNode.isValid())
+ return newQmlItemNode;
+
+ newQmlItemNode.setId(view->generateNewId(itemLibraryEntry.name()));
+
+ if (!view->currentState().isBaseState()) {
+ newQmlItemNode.modelNode().variantProperty("opacity").setValue(0);
+ newQmlItemNode.setVariantProperty("opacity", 1);
+ }
+
+ Q_ASSERT(newQmlItemNode.isValid());
+ }
+ catch (RewritingException &e) {
+ QMessageBox::warning(0, "Error", e.description());
+ }
+
+ Q_ASSERT(newQmlItemNode.isValid());
+
+ return newQmlItemNode;
+}
+
+static void checkImageImport(AbstractView *view)
+{
+ const QString newImportUrl = QLatin1String("QtQuick");
+ const QString newImportVersion = QLatin1String("1.1");
+ Import newImport = Import::createLibraryImport(newImportUrl, newImportVersion);
+
+ foreach (const Import &import, view->model()->imports()) {
+ if (import.isLibraryImport()
+ && import.url() == newImport.url()) {
+ // reuse this import
+ newImport = import;
+ break;
+ }
+ }
+
+ if (!view->model()->hasImport(newImport, true, true))
+ view->model()->changeImports(QList<Import>() << newImport, QList<Import>());
+}
+
+QmlItemNode QmlItemNode::createQmlItemNodeFromImage(AbstractView *view, const QString &imageName, const QPointF &position, QmlItemNode parentQmlItemNode)
+{
+ QmlItemNode newQmlItemNode;
+ if (!parentQmlItemNode.isValid())
+ parentQmlItemNode = QmlItemNode(view->rootModelNode());
+
+ if (parentQmlItemNode.isValid()) {
+ RewriterTransaction transaction = view->beginRewriterTransaction();
+
+ checkImageImport(view);
+
+ if (view->model()->hasNodeMetaInfo("QtQuick.Image")) {
+ NodeMetaInfo metaInfo = view->model()->metaInfo("QtQuick.Image");
+ QList<QPair<PropertyName, QVariant> > propertyPairList;
+ propertyPairList.append(qMakePair(PropertyName("x"), QVariant(qRound(position.x()))));
+ propertyPairList.append(qMakePair(PropertyName("y"), QVariant(qRound(position.y()))));
+
+ QString relativeImageName = imageName;
+
+ //use relative path
+ if (QFileInfo(view->model()->fileUrl().toLocalFile()).exists()) {
+ QDir fileDir(QFileInfo(view->model()->fileUrl().toLocalFile()).absolutePath());
+ relativeImageName = fileDir.relativeFilePath(imageName);
+ propertyPairList.append(qMakePair(PropertyName("source"), QVariant(relativeImageName)));
+ }
+
+ newQmlItemNode = QmlItemNode(view->createModelNode("QtQuick.Image", metaInfo.majorVersion(), metaInfo.minorVersion(), propertyPairList));
+ parentQmlItemNode.defaultNodeAbstractProperty().reparentHere(newQmlItemNode);
+
+ newQmlItemNode.setId(view->generateNewId("image"));
+
+ if (!view->currentState().isBaseState()) {
+ newQmlItemNode.modelNode().variantProperty("opacity").setValue(0);
+ newQmlItemNode.setVariantProperty("opacity", 1);
+ }
+
+ Q_ASSERT(newQmlItemNode.isValid());
+ }
+ Q_ASSERT(newQmlItemNode.isValid());
+ }
+
+
+ return newQmlItemNode;
+}
+
bool QmlItemNode::isValid() const
{
- return QmlModelNodeFacade::isValid() && modelNode().metaInfo().isValid() && isItemOrWindow(modelNode());
+ return isValidQmlItemNode(modelNode());
+}
+
+bool QmlItemNode::isValidQmlItemNode(const ModelNode &modelNode)
+{
+ return isValidQmlObjectNode(modelNode) && modelNode.metaInfo().isValid() && isItemOrWindow(modelNode);
}
bool QmlItemNode::isRootNode() const
@@ -67,7 +259,7 @@ QStringList QmlModelStateGroup::names() const
if (modelNode().property("states").isNodeListProperty()) {
foreach (const ModelNode &node, modelNode().nodeListProperty("states").toModelNodeList()) {
- if (QmlModelState(node).isValid())
+ if (QmlModelState::isValidQmlModelState(node))
returnList.append(QmlModelState(node).name());
}
}
@@ -88,81 +280,47 @@ QmlModelStateGroup QmlItemNode::states() const
QList<QmlItemNode> QmlItemNode::children() const
{
- QList<QmlItemNode> returnList;
+ QList<ModelNode> childrenList;
if (isValid()) {
- QList<ModelNode> modelNodeList;
-
- if (modelNode().hasProperty("children")) {
- if (modelNode().property("children").isNodeListProperty())
- modelNodeList.append(modelNode().nodeListProperty("children").toModelNodeList());
- }
-
- if (modelNode().hasProperty("data")) {
- if (modelNode().property("data").isNodeListProperty())
- modelNodeList.append(modelNode().nodeListProperty("data").toModelNodeList());
- }
+ if (modelNode().hasNodeListProperty("children"))
+ childrenList.append(modelNode().nodeListProperty("children").toModelNodeList());
- foreach (const ModelNode &modelNode, modelNodeList) {
- if (QmlItemNode(modelNode).isValid()) //if ModelNode is FxItem
- returnList.append(modelNode);
+ if (modelNode().hasNodeListProperty("data")) {
+ foreach (const ModelNode &node, modelNode().nodeListProperty("data").toModelNodeList()) {
+ if (QmlItemNode::isValidQmlItemNode(node))
+ childrenList.append(node);
+ }
}
}
- return returnList;
+
+ return toQmlItemNodeList(childrenList);
}
QList<QmlObjectNode> QmlItemNode::resources() const
{
- QList<QmlObjectNode> returnList;
+ QList<ModelNode> resourcesList;
if (isValid()) {
- QList<ModelNode> modelNodeList;
- if (modelNode().hasProperty("resources")) {
- if (modelNode().property("resources").isNodeListProperty())
- modelNodeList.append(modelNode().nodeListProperty("resources").toModelNodeList());
- }
- if (modelNode().hasProperty("data")) {
- if (modelNode().property("data").isNodeListProperty())
- modelNodeList.append(modelNode().nodeListProperty("data").toModelNodeList());
- }
+ if (modelNode().hasNodeListProperty("resources"))
+ resourcesList.append(modelNode().nodeListProperty("resources").toModelNodeList());
- foreach (const ModelNode &node, modelNodeList) {
- if (!QmlObjectNode(node).isValid()) //if ModelNode is no FxItem
- returnList.append(node);
+ if (modelNode().hasNodeListProperty("data")) {
+ foreach (const ModelNode &node, modelNode().nodeListProperty("data").toModelNodeList()) {
+ if (!QmlItemNode::isValidQmlItemNode(node))
+ resourcesList.append(node);
+ }
}
}
- return returnList;
-}
-QList<QmlObjectNode> QmlItemNode::defaultPropertyChildren() const
-{
- QList<QmlObjectNode> returnList;
- if (isValid()) {
- QList<ModelNode> modelNodeList;
- if (modelNode().property(defaultProperty()).isNodeListProperty())
- modelNodeList.append(modelNode().nodeListProperty(defaultProperty()).toModelNodeList());
-
- foreach (const ModelNode &node, modelNodeList) {
- if (!QmlObjectNode(node).isValid()) //if ModelNode is no FxItem
- returnList.append(node);
- }
- }
- return returnList;
+ return toQmlObjectNodeList(resourcesList);
}
QList<QmlObjectNode> QmlItemNode::allDirectSubNodes() const
{
- QList<QmlObjectNode> returnList;
- if (isValid()) {
- QList<ModelNode> modelNodeList = modelNode().allDirectSubModelNodes();
-
- foreach (const ModelNode &node, modelNodeList) {
- returnList.append(node);
- }
- }
- return returnList;
+ return toQmlObjectNodeList(modelNode().allDirectSubModelNodes());
}
QmlAnchors QmlItemNode::anchors() const
@@ -172,11 +330,17 @@ QmlAnchors QmlItemNode::anchors() const
bool QmlItemNode::hasChildren() const
{
+ if (modelNode().hasNodeListProperty("children"))
+ return true;
+
return !children().isEmpty();
}
bool QmlItemNode::hasResources() const
{
+ if (modelNode().hasNodeListProperty("resources"))
+ return true;
+
return !resources().isEmpty();
}
@@ -185,14 +349,14 @@ bool QmlItemNode::instanceHasAnchors() const
return anchors().instanceHasAnchors();
}
-bool QmlItemNode::hasShowContent() const
+bool QmlItemNode::instanceHasShowContent() const
{
return nodeInstance().hasContent();
}
-bool QmlItemNode::canReparent() const
+bool QmlItemNode::instanceCanReparent() const
{
- return QmlObjectNode::canReparent() && !anchors().instanceHasAnchors() && !instanceIsAnchoredBySibling();
+ return QmlObjectNode::instanceCanReparent() && !anchors().instanceHasAnchors() && !instanceIsAnchoredBySibling();
}
bool QmlItemNode::instanceIsAnchoredBySibling() const
@@ -225,6 +389,29 @@ bool QmlItemNode::instanceHasRotationTransform() const
return nodeInstance().transform().type() > QTransform::TxScale;
}
+bool itemIsMovable(const ModelNode &modelNode)
+{
+ if (modelNode.metaInfo().isSubclassOf("QtQuick.Controls.Tab", -1, -1))
+ return false;
+
+ return true;
+}
+
+
+bool QmlItemNode::modelIsMovable() const
+{
+ return !modelNode().hasBindingProperty("x")
+ && !modelNode().hasBindingProperty("y")
+ && itemIsMovable(modelNode());
+}
+
+bool QmlItemNode::modelIsResizable() const
+{
+ return !modelNode().hasBindingProperty("width")
+ && !modelNode().hasBindingProperty("height")
+ && itemIsMovable(modelNode());
+}
+
QRectF QmlItemNode::instanceBoundingRect() const
{
return QRectF(QPointF(0, 0), nodeInstance().size());
@@ -267,11 +454,10 @@ QTransform QmlItemNode::instanceSceneContentItemTransform() const
QPointF QmlItemNode::instanceScenePosition() const
{
- QmlItemNode parentNode = instanceParent().toQmlItemNode();
- if (!parentNode.isValid())
- parentNode = modelNode().parentProperty().parentQmlObjectNode().toQmlItemNode();
- if (parentNode.isValid())
- return parentNode.instanceSceneTransform().map(nodeInstance().position());
+ if (hasInstanceParentItem())
+ return instanceParentItem().instanceSceneTransform().map(nodeInstance().position());
+ else if (modelNode().hasParentProperty() && QmlItemNode::isValidQmlItemNode(modelNode().parentProperty().parentModelNode()))
+ return QmlItemNode(modelNode().parentProperty().parentModelNode()).instanceSceneTransform().map(nodeInstance().position());
return QPointF();
}
@@ -296,25 +482,14 @@ bool QmlItemNode::instanceIsRenderPixmapNull() const
return nodeInstance().renderPixmap().isNull();
}
-void QmlItemNode::paintInstance(QPainter *painter)
-{
- if (nodeInstance().isValid())
- nodeInstance().paint(painter);
-}
-
-void QmlItemNode::selectNode()
+QPixmap QmlItemNode::instanceRenderPixmap() const
{
- modelNode().selectNode();
+ return nodeInstance().renderPixmap();
}
-void QmlItemNode::deselectNode()
+QPixmap QmlItemNode::instanceBlurredRenderPixmap() const
{
- modelNode().deselectNode();
-}
-
-bool QmlItemNode::isSelected() const
-{
- return modelNode().isSelected();
+ return nodeInstance().blurredRenderPixmap();
}
QList<QmlModelState> QmlModelStateGroup::allStates() const
@@ -326,8 +501,8 @@ QList<QmlModelState> QmlModelStateGroup::allStates() const
if (modelNode().property("states").isNodeListProperty()) {
foreach (const ModelNode &node, modelNode().nodeListProperty("states").toModelNodeList()) {
- if (QmlModelState(node).isValid())
- returnList.append(QmlModelState(node));
+ if (QmlModelState::isValidQmlModelState(node))
+ returnList.append(node);
}
}
return returnList;
@@ -352,7 +527,7 @@ QmlModelState QmlModelStateGroup::addState(const QString &name)
PropertyListType propertyList;
propertyList.append(qMakePair(PropertyName("name"), QVariant(name)));
- ModelNode newState = QmlObjectNode(modelNode()).qmlModelView()->createQmlState(propertyList);
+ ModelNode newState = QmlModelState::createQmlState(modelNode().view(), propertyList);
modelNode().nodeListProperty("states").reparentHere(newState);
return newState;
@@ -396,9 +571,8 @@ QList<QmlItemNode> toQmlItemNodeList(const QList<ModelNode> &modelNodeList)
QList<QmlItemNode> qmlItemNodeList;
foreach (const ModelNode &modelNode, modelNodeList) {
- QmlItemNode itemNode(modelNode);
- if (itemNode.isValid())
- qmlItemNodeList.append(itemNode);
+ if (QmlItemNode::isValidQmlItemNode(modelNode))
+ qmlItemNodeList.append(modelNode);
}
return qmlItemNodeList;
@@ -419,4 +593,28 @@ bool QmlItemNode::hasAnySubModelNodes() const
return modelNode().hasAnySubModelNodes();
}
+void QmlItemNode::setPosition(const QPointF &position)
+{
+ if (!hasBindingProperty("x"))
+ setVariantProperty("x", qRound(position.x()));
+
+ if (!hasBindingProperty("y"))
+ setVariantProperty("y", qRound(position.y()));
+}
+
+void QmlItemNode::setPostionInBaseState(const QPointF &position)
+{
+ modelNode().variantProperty("x").setValue(qRound(position.x()));
+ modelNode().variantProperty("y").setValue(qRound(position.y()));
+}
+
+void QmlItemNode::setSize(const QSizeF &size)
+{
+ if (!hasBindingProperty("width"))
+ setVariantProperty("width", qRound(size.width()));
+
+ if (!hasBindingProperty("height"))
+ setVariantProperty("height", qRound(size.height()));
+}
+
} //QmlDesigner
diff --git a/src/plugins/qmldesigner/designercore/model/qmlmodelnodefacade.cpp b/src/plugins/qmldesigner/designercore/model/qmlmodelnodefacade.cpp
index f48e83f8a5..44a3601ecb 100644
--- a/src/plugins/qmldesigner/designercore/model/qmlmodelnodefacade.cpp
+++ b/src/plugins/qmldesigner/designercore/model/qmlmodelnodefacade.cpp
@@ -28,13 +28,27 @@
****************************************************************************/
#include "qmlmodelnodefacade.h"
-#include "qmlmodelview.h"
-#include <QDebug>
+#include "nodeinstanceview.h"
+#include <qmldesignerplugin.h>
+
namespace QmlDesigner {
QmlModelNodeFacade::QmlModelNodeFacade() : m_modelNode(ModelNode())
{}
+AbstractView *QmlModelNodeFacade::view() const
+{
+ if (modelNode().isValid())
+ return modelNode().view();
+ else
+ return 0;
+}
+
+NodeInstanceView *QmlModelNodeFacade::nodeInstanceView()
+{
+ return QmlDesignerPlugin::instance()->viewManager().nodeInstanceView();
+}
+
QmlModelNodeFacade::QmlModelNodeFacade(const ModelNode &modelNode) : m_modelNode(modelNode)
{}
@@ -42,14 +56,32 @@ QmlModelNodeFacade::QmlModelNodeFacade(const ModelNode &modelNode) : m_modelNode
QmlModelNodeFacade::~QmlModelNodeFacade()
{}
+QmlModelNodeFacade::operator ModelNode() const
+{
+ return m_modelNode;
+}
+
+ModelNode QmlModelNodeFacade::modelNode()
+{
+ return m_modelNode;
+}
+
+const ModelNode QmlModelNodeFacade::modelNode() const
+{
+ return m_modelNode;
+}
+
bool QmlModelNodeFacade::isValid() const
{
- return modelNode().isValid() && qmlModelView() && qmlModelView()->nodeInstanceView() && qmlModelView()->hasInstanceForModelNode(modelNode()) && qmlModelView()->instanceForModelNode(modelNode()).isValid();
+ return isValidQmlModelNodeFacade(m_modelNode);
}
-QmlModelView* QmlModelNodeFacade::qmlModelView() const
+bool QmlModelNodeFacade::isValidQmlModelNodeFacade(const ModelNode &modelNode)
{
- return modelNode().view()->toQmlModelView();
+ return modelNode.isValid()
+ && nodeInstanceView()
+ && nodeInstanceView()->hasInstanceForModelNode(modelNode)
+ && nodeInstanceView()->instanceForModelNode(modelNode).isValid();
}
bool QmlModelNodeFacade::isRootNode() const
diff --git a/src/plugins/qmldesigner/designercore/model/qmlmodelview.cpp b/src/plugins/qmldesigner/designercore/model/qmlmodelview.cpp
deleted file mode 100644
index d49078aec5..0000000000
--- a/src/plugins/qmldesigner/designercore/model/qmlmodelview.cpp
+++ /dev/null
@@ -1,449 +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 "qmlmodelview.h"
-#include "qmlobjectnode.h"
-#include "qmlitemnode.h"
-#include "itemlibraryinfo.h"
-#include "mathutils.h"
-#include "invalididexception.h"
-#include <QDir>
-#include <QFileInfo>
-#include <QDebug>
-#include <QMessageBox>
-#include <QPlainTextEdit>
-#include <utils/fileutils.h>
-#include "nodeabstractproperty.h"
-#include "variantproperty.h"
-#include "rewritingexception.h"
-#include "rewriterview.h"
-#include "plaintexteditmodifier.h"
-#include "modelmerger.h"
-#include "nodemetainfo.h"
-
-#include <utils/qtcassert.h>
-
-namespace QmlDesigner {
-
-QmlModelView::QmlModelView(QObject *parent)
- : AbstractView(parent)
-{
-}
-
-void QmlModelView::setCurrentState(const QmlModelState &state)
-{
- if (!state.isValid())
- return;
-
- if (!model())
- return;
-
- if (actualStateNode() != state.modelNode())
- setAcutalStateNode(state.modelNode());
-}
-
-QmlModelState QmlModelView::currentState() const
-{
- return QmlModelState(actualStateNode());
-}
-
-QmlModelState QmlModelView::baseState() const
-{
- return QmlModelState::createBaseState(this);
-}
-
-QmlModelStateGroup QmlModelView::rootStateGroup() const
-{
- return QmlModelStateGroup(rootModelNode());
-}
-
-QmlObjectNode QmlModelView::createQmlObjectNode(const TypeName &typeString,
- int majorVersion,
- int minorVersion,
- const PropertyListType &propertyList)
-{
- return QmlObjectNode(createModelNode(typeString, majorVersion, minorVersion, propertyList));
-}
-
-QmlItemNode QmlModelView::createQmlItemNode(const TypeName &typeString,
- int majorVersion,
- int minorVersion,
- const PropertyListType &propertyList)
-{
- return createQmlObjectNode(typeString, majorVersion, minorVersion, propertyList).toQmlItemNode();
-}
-
-QmlItemNode QmlModelView::createQmlItemNodeFromImage(const QString &imageName, const QPointF &position, QmlItemNode parentNode)
-{
- if (!parentNode.isValid())
- parentNode = rootQmlItemNode();
-
- if (!parentNode.isValid())
- return QmlItemNode();
-
- QmlItemNode newNode;
- RewriterTransaction transaction = beginRewriterTransaction();
- {
- const QString newImportUrl = QLatin1String("QtQuick");
- const QString newImportVersion = QLatin1String("1.1");
- Import newImport = Import::createLibraryImport(newImportUrl, newImportVersion);
-
- foreach (const Import &import, model()->imports()) {
- if (import.isLibraryImport()
- && import.url() == newImport.url()) {
- // reuse this import
- newImport = import;
- break;
- }
- }
-
- if (!model()->hasImport(newImport, true, true))
- model()->changeImports(QList<Import>() << newImport, QList<Import>());
-
- QList<QPair<PropertyName, QVariant> > propertyPairList;
- propertyPairList.append(qMakePair(PropertyName("x"), QVariant( round(position.x(), 4))));
- propertyPairList.append(qMakePair(PropertyName("y"), QVariant( round(position.y(), 4))));
-
- QString relativeImageName = imageName;
-
- //use relative path
- if (QFileInfo(model()->fileUrl().toLocalFile()).exists()) {
- QDir fileDir(QFileInfo(model()->fileUrl().toLocalFile()).absolutePath());
- relativeImageName = fileDir.relativeFilePath(imageName);
- }
-
- propertyPairList.append(qMakePair(PropertyName("source"), QVariant(relativeImageName)));
- NodeMetaInfo metaInfo = model()->metaInfo("QtQuick.Image");
- if (metaInfo.isValid()) {
- int minorVersion = metaInfo.minorVersion();
- int majorVersion = metaInfo.majorVersion();
- newNode = createQmlItemNode("QtQuick.Image", majorVersion, minorVersion, propertyPairList);
- parentNode.nodeAbstractProperty("data").reparentHere(newNode);
- }
-
- Q_ASSERT(newNode.isValid());
-
- QString id;
- int i = 1;
- QString name("image");
- name.remove(QLatin1Char(' '));
- do {
- id = name + QString::number(i);
- i++;
- } while (hasId(id)); //If the name already exists count upwards
-
- newNode.setId(id);
- if (!currentState().isBaseState()) {
- newNode.modelNode().variantProperty("opacity") = 0;
- newNode.setVariantProperty("opacity", 1);
- }
-
- Q_ASSERT(newNode.isValid());
- }
-
- Q_ASSERT(newNode.isValid());
-
- return newNode;
-}
-
-QmlItemNode QmlModelView::createQmlItemNode(const ItemLibraryEntry &itemLibraryEntry, const QPointF &position, QmlItemNode parentNode)
-{
- if (!parentNode.isValid())
- parentNode = rootQmlItemNode();
-
- Q_ASSERT(parentNode.isValid());
-
- QmlItemNode newNode;
-
- 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();
-
- if (!itemLibraryEntry.requiredImport().isEmpty()) {
- 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);
-
- foreach (const Import &import, model()->imports()) {
- if (import.isLibraryImport()
- && import.url() == newImport.url()
- && import.version() == newImport.version()) {
- // reuse this import
- newImport = import;
- break;
- }
- }
-
- if (!model()->hasImport(newImport, true, true))
- model()->changeImports(QList<Import>() << newImport, QList<Import>());
- }
- }
-
- QList<QPair<PropertyName, QVariant> > propertyPairList;
- propertyPairList.append(qMakePair(PropertyName("x"), QVariant(round(position.x(), 4))));
- propertyPairList.append(qMakePair(PropertyName("y"), QVariant(round(position.y(), 4))));
-
- if (itemLibraryEntry.qml().isEmpty()) {
- foreach (const PropertyContainer &property, itemLibraryEntry.properties())
- propertyPairList.append(qMakePair(property.name(), property.value()));
-
- newNode = createQmlItemNode(itemLibraryEntry.typeName(), majorVersion, minorVersion, propertyPairList);
- } else {
- QScopedPointer<Model> inputModel(Model::create("QtQuick.Rectangle", 1, 0, model()));
- inputModel->setFileUrl(model()->fileUrl());
- QPlainTextEdit textEdit;
-
-
- textEdit.setPlainText(itemLibraryEntry.qmlSource());
- NotIndentingTextEditModifier modifier(&textEdit);
-
- QScopedPointer<RewriterView> rewriterView(new RewriterView(RewriterView::Amend, 0));
- rewriterView->setCheckSemanticErrors(false);
- rewriterView->setTextModifier(&modifier);
- inputModel->setRewriterView(rewriterView.data());
-
- if (rewriterView->errors().isEmpty() && rewriterView->rootModelNode().isValid()) {
- ModelNode rootModelNode = rewriterView->rootModelNode();
- inputModel->detachView(rewriterView.data());
-
- rootModelNode.variantProperty("x") = propertyPairList.first().second;
- rootModelNode.variantProperty("y") = propertyPairList.at(1).second;
-
- ModelMerger merger(this);
- newNode = merger.insertModel(rootModelNode);
- }
- }
-
- if (parentNode.hasDefaultProperty())
- parentNode.nodeAbstractProperty(parentNode.defaultProperty()).reparentHere(newNode);
-
- if (!newNode.isValid())
- return newNode;
-
- QString id;
- int i = 1;
- QString name(itemLibraryEntry.name().toLower());
- //remove forbidden characters
- name.replace(QRegExp(QLatin1String("[^a-zA-Z0-9_]")), QLatin1String("_"));
- do {
- id = name + QString::number(i);
- i++;
- } while (hasId(id)); //If the name already exists count upwards
-
- newNode.setId(id);
-
- if (!currentState().isBaseState()) {
- newNode.modelNode().variantProperty("opacity") = 0;
- newNode.setVariantProperty("opacity", 1);
- }
-
- Q_ASSERT(newNode.isValid());
- }
- catch (RewritingException &e) {
- QMessageBox::warning(0, "Error", e.description());
- }
- catch (InvalidIdException &e) {
- // should never happen
- QMessageBox::warning(0, tr("Invalid Id"), e.description());
- }
-
- Q_ASSERT(newNode.isValid());
-
- return newNode;
-}
-
-QmlObjectNode QmlModelView::rootQmlObjectNode() const
-{
- return QmlObjectNode(rootModelNode());
-}
-
-QmlItemNode QmlModelView::rootQmlItemNode() const
-{
- return rootQmlObjectNode().toQmlItemNode();
-}
-
-void QmlModelView::setSelectedQmlObjectNodes(const QList<QmlObjectNode> &selectedNodeList)
-{
- setSelectedModelNodes(QmlDesigner::toModelNodeList(selectedNodeList));
-}
-
-void QmlModelView::selectQmlObjectNode(const QmlObjectNode &node)
-{
- selectModelNode(node.modelNode());
-}
-
-void QmlModelView::deselectQmlObjectNode(const QmlObjectNode &node)
-{
- deselectModelNode(node.modelNode());
-}
-
-QList<QmlObjectNode> QmlModelView::selectedQmlObjectNodes() const
-{
- return toQmlObjectNodeList(selectedModelNodes());
-}
-
-QList<QmlItemNode> QmlModelView::selectedQmlItemNodes() const
-{
- return toQmlItemNodeList(selectedModelNodes());
-}
-
-void QmlModelView::setSelectedQmlItemNodes(const QList<QmlItemNode> &selectedNodeList)
-{
- return setSelectedModelNodes(QmlDesigner::toModelNodeList(selectedNodeList));
-}
-
-QmlObjectNode QmlModelView::fxObjectNodeForId(const QString &id)
-{
- return QmlObjectNode(modelNodeForId(id));
-}
-
-NodeInstance QmlModelView::instanceForModelNode(const ModelNode &modelNode)
-{
- return nodeInstanceView()->instanceForNode(modelNode);
-}
-
-bool QmlModelView::hasInstanceForModelNode(const ModelNode &modelNode)
-{
- return nodeInstanceView() && nodeInstanceView()->hasInstanceForNode(modelNode);
-}
-
-void QmlModelView::modelAttached(Model *model)
-{
- AbstractView::modelAttached(model);
-}
-
-void QmlModelView::modelAboutToBeDetached(Model *model)
-{
- AbstractView::modelAboutToBeDetached(model);
-}
-
-void QmlModelView::nodeOrderChanged(const NodeListProperty &/*listProperty*/, const ModelNode &/*movedNode*/, int /*oldIndex*/)
-{
-
-}
-
-void QmlModelView::nodeCreated(const ModelNode &/*createdNode*/) {}
-void QmlModelView::nodeAboutToBeRemoved(const ModelNode &/*removedNode*/) {}
-void QmlModelView::nodeRemoved(const ModelNode &/*removedNode*/, const NodeAbstractProperty &/*parentProperty*/, PropertyChangeFlags /*propertyChange*/) {}
-void QmlModelView::nodeAboutToBeReparented(const ModelNode &/*node*/, const NodeAbstractProperty &/*newPropertyParent*/, const NodeAbstractProperty &/*oldPropertyParent*/, AbstractView::PropertyChangeFlags /*propertyChange*/) {}
-void QmlModelView::nodeReparented(const ModelNode &/*node*/, const NodeAbstractProperty &/*newPropertyParent*/, const NodeAbstractProperty &/*oldPropertyParent*/, AbstractView::PropertyChangeFlags /*propertyChange*/) {}
-void QmlModelView::nodeIdChanged(const ModelNode& /*node*/, const QString& /*newId*/, const QString& /*oldId*/) {}
-void QmlModelView::propertiesAboutToBeRemoved(const QList<AbstractProperty>& /*propertyList*/) {}
-void QmlModelView::propertiesRemoved(const QList<AbstractProperty>& /*propertyList*/) {}
-void QmlModelView::variantPropertiesChanged(const QList<VariantProperty>& /*propertyList*/, PropertyChangeFlags /*propertyChange*/) {}
-void QmlModelView::bindingPropertiesChanged(const QList<BindingProperty>& /*propertyList*/, PropertyChangeFlags /*propertyChange*/) {}
-void QmlModelView::signalHandlerPropertiesChanged(const QVector<SignalHandlerProperty> & /*propertyList*/, AbstractView::PropertyChangeFlags /*propertyChange*/) {}
-void QmlModelView::rootNodeTypeChanged(const QString &/*type*/, int, int /*minorVersion*/) {}
-void QmlModelView::scriptFunctionsChanged(const ModelNode &/*node*/, const QStringList &/*scriptFunctionList*/) {}
-void QmlModelView::selectedNodesChanged(const QList<ModelNode> &/*selectedNodeList*/, const QList<ModelNode> &/*lastSelectedNodeList*/) {}
-
-
-void QmlModelView::instancesCompleted(const QVector<ModelNode> &/*completedNodeList*/)
-{
-}
-
-void QmlModelView::instanceInformationsChange(const QMultiHash<ModelNode, InformationName> &/*informationChangeHash*/)
-{
-
-}
-
-void QmlModelView::instancesRenderImageChanged(const QVector<ModelNode> &/*nodeList*/)
-{
-
-}
-
-void QmlModelView::instancesPreviewImageChanged(const QVector<ModelNode> &/*nodeList*/)
-{
-
-}
-
-void QmlModelView::instancesChildrenChanged(const QVector<ModelNode> &/*nodeList*/)
-{
-
-}
-
-void QmlModelView::importsChanged(const QList<Import> &/*addedImports*/, const QList<Import> &/*removedImports*/)
-{
-
-}
-
-void QmlModelView::instancesToken(const QString &/*tokenName*/, int /*tokenNumber*/, const QVector<ModelNode> &/*nodeVector*/)
-{
-
-}
-
-void QmlModelView::nodeSourceChanged(const ModelNode &, const QString & /*newNodeSource*/)
-{
-
-}
-
-void QmlModelView::rewriterBeginTransaction()
-{
-
-}
-
-void QmlModelView::rewriterEndTransaction()
-{
-
-}
-
-void QmlModelView::actualStateChanged(const ModelNode & /*node*/)
-{
-
-}
-
-void QmlModelView::instancePropertyChange(const QList<QPair<ModelNode, PropertyName> > & /*propertyList*/)
-{
-}
-
-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 ee8f30a823..83379fad59 100644
--- a/src/plugins/qmldesigner/designercore/model/qmlobjectnode.cpp
+++ b/src/plugins/qmldesigner/designercore/model/qmlobjectnode.cpp
@@ -33,11 +33,12 @@
#include "variantproperty.h"
#include "nodeproperty.h"
#include <invalidmodelnodeexception.h>
-#include "qmlmodelview.h"
+#include "abstractview.h"
#include "nodeinstance.h"
#include "nodemetainfo.h"
#include "bindingproperty.h"
#include "nodelistproperty.h"
+#include "nodeinstanceview.h"
namespace QmlDesigner {
@@ -53,7 +54,7 @@ void QmlObjectNode::setVariantProperty(const PropertyName &name, const QVariant
QmlPropertyChanges changeSet(currentState().propertyChanges(modelNode()));
Q_ASSERT(changeSet.isValid());
- changeSet.modelNode().variantProperty(name) = value;
+ changeSet.modelNode().variantProperty(name).setValue(value);
}
}
@@ -63,20 +64,20 @@ void QmlObjectNode::setBindingProperty(const PropertyName &name, const QString &
throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);
if (isInBaseState()) {
- modelNode().bindingProperty(name) = expression; //basestate
+ modelNode().bindingProperty(name).setExpression(expression); //basestate
} else {
modelNode().validId();
QmlPropertyChanges changeSet(currentState().propertyChanges(modelNode()));
Q_ASSERT(changeSet.isValid());
- changeSet.modelNode().bindingProperty(name) = expression;
+ changeSet.modelNode().bindingProperty(name).setExpression(expression);
}
}
QmlModelState QmlObjectNode::currentState() const
{
if (isValid())
- return qmlModelView()->currentState();
+ return QmlModelState(view()->currentStateNode());
else
return QmlModelState();
}
@@ -128,7 +129,12 @@ bool QmlObjectNode::hasBindingProperty(const PropertyName &name) const
NodeAbstractProperty QmlObjectNode::nodeAbstractProperty(const PropertyName &name) const
{
- return modelNode().nodeAbstractProperty(name);
+ return modelNode().nodeAbstractProperty(name);
+}
+
+NodeAbstractProperty QmlObjectNode::defaultNodeAbstractProperty() const
+{
+ return modelNode().defaultNodeAbstractProperty();
}
NodeProperty QmlObjectNode::nodeProperty(const PropertyName &name) const
@@ -229,7 +235,7 @@ bool QmlObjectNode::isInBaseState() const
return currentState().isBaseState();
}
-bool QmlObjectNode::canReparent() const
+bool QmlObjectNode::instanceCanReparent() const
{
return isInBaseState();
}
@@ -251,7 +257,7 @@ QmlPropertyChanges QmlObjectNode::propertyChangeForCurrentState() const
static void removeStateOperationsForChildren(const QmlObjectNode &node)
{
if (node.isValid()) {
- foreach (const QmlModelStateOperation &stateOperation, node.allAffectingStatesOperations()) {
+ foreach (QmlModelStateOperation stateOperation, node.allAffectingStatesOperations()) {
stateOperation.modelNode().destroy(); //remove of belonging StatesOperations
}
@@ -272,7 +278,7 @@ void QmlObjectNode::destroy()
if (!isValid())
throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);
- foreach (const QmlModelStateOperation &stateOperation, allAffectingStatesOperations()) {
+ foreach (QmlModelStateOperation stateOperation, allAffectingStatesOperations()) {
stateOperation.modelNode().destroy(); //remove of belonging StatesOperations
}
removeStateOperationsForChildren(modelNode());
@@ -315,22 +321,20 @@ QList<QmlModelStateOperation> QmlObjectNode::allAffectingStatesOperations() cons
return returnList;
}
-static QList<QmlItemNode> allFxItemsRecursive(const QmlItemNode &fxNode)
+static QList<QmlItemNode> allQmlItemsRecursive(const QmlItemNode &qmlItemNode)
{
- QList<QmlItemNode> returnList;
+ QList<QmlItemNode> qmlItemNodeList;
- if (fxNode.isValid()) {
- returnList.append(fxNode);
- QList<QmlItemNode> allChildNodes;
- foreach (const ModelNode &node, fxNode.modelNode().allDirectSubModelNodes()) {
- if (QmlItemNode(node).isValid())
- allChildNodes.append(node);
- }
- foreach (const QmlItemNode &node, allChildNodes) {
- returnList.append(allFxItemsRecursive(node));
+ if (qmlItemNode.isValid()) {
+ qmlItemNodeList.append(qmlItemNode);
+
+ foreach (const ModelNode &modelNode, qmlItemNode.modelNode().allDirectSubModelNodes()) {
+ if (QmlItemNode::isValidQmlItemNode(modelNode))
+ qmlItemNodeList.append(allQmlItemsRecursive(modelNode));
}
}
- return returnList;
+
+ return qmlItemNodeList;
}
QList<QmlModelState> QmlObjectNode::allDefinedStates() const
@@ -340,14 +344,12 @@ QList<QmlModelState> QmlObjectNode::allDefinedStates() const
QList<QmlModelState> returnList;
- QList<QmlItemNode> allFxItems;
-
- QmlItemNode rootNode(qmlModelView()->rootModelNode());
+ QList<QmlItemNode> allQmlItems;
- if (rootNode.isValid())
- allFxItems.append(allFxItemsRecursive(rootNode));
+ if (QmlItemNode::isValidQmlItemNode(view()->rootModelNode()))
+ allQmlItems.append(allQmlItemsRecursive(view()->rootModelNode()));
- foreach (const QmlItemNode &item, allFxItems) {
+ foreach (const QmlItemNode &item, allQmlItems) {
returnList.append(item.states().allStates());
}
@@ -360,7 +362,7 @@ QList<QmlModelState> QmlObjectNode::allDefinedStates() const
model.
*/
-void QmlObjectNode::removeVariantProperty(const PropertyName &name)
+void QmlObjectNode::removeProperty(const PropertyName &name)
{
if (!isValid())
throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);
@@ -374,12 +376,12 @@ void QmlObjectNode::removeVariantProperty(const PropertyName &name)
}
}
-QList<ModelNode> toModelNodeList(const QList<QmlObjectNode> &fxObjectNodeList)
+QList<ModelNode> toModelNodeList(const QList<QmlObjectNode> &qmlObjectNodeList)
{
QList<ModelNode> modelNodeList;
- foreach (const QmlObjectNode &fxObjectNode, fxObjectNodeList)
- modelNodeList.append(fxObjectNode.modelNode());
+ foreach (const QmlObjectNode &qmlObjectNode, qmlObjectNodeList)
+ modelNodeList.append(qmlObjectNode.modelNode());
return modelNodeList;
}
@@ -389,9 +391,8 @@ QList<QmlObjectNode> toQmlObjectNodeList(const QList<ModelNode> &modelNodeList)
QList<QmlObjectNode> qmlObjectNodeList;
foreach (const ModelNode &modelNode, modelNodeList) {
- QmlObjectNode objectNode(modelNode);
- if (objectNode.isValid())
- qmlObjectNodeList.append(objectNode);
+ if (QmlObjectNode::isValidQmlObjectNode(modelNode))
+ qmlObjectNodeList.append(modelNode);
}
return qmlObjectNodeList;
@@ -404,11 +405,8 @@ bool QmlObjectNode::isAncestorOf(const QmlObjectNode &objectNode) const
QVariant QmlObjectNode::instanceValue(const ModelNode &modelNode, const PropertyName &name)
{
- QmlModelView *modelView = qobject_cast<QmlModelView*>(modelNode.view());
- if (!modelView)
- throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);
- Q_ASSERT(modelView->hasInstanceForModelNode(modelNode));
- return modelView->instanceForModelNode(modelNode).property(name);
+ Q_ASSERT(modelNode.view()->nodeInstanceView()->hasInstanceForModelNode(modelNode));
+ return modelNode.view()->nodeInstanceView()->instanceForModelNode(modelNode).property(name);
}
QString QmlObjectNode::generateTranslatableText(const QString &text)
@@ -423,26 +421,42 @@ TypeName QmlObjectNode::instanceType(const PropertyName &name) const
bool QmlObjectNode::instanceHasBinding(const PropertyName &name) const
{
- QmlModelView *modelView = qobject_cast<QmlModelView*>(modelNode().view());
- if (!modelView)
- throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);
-
return nodeInstance().hasBindingForProperty(name);
}
NodeInstance QmlObjectNode::nodeInstance() const
{
- return qmlModelView()->nodeInstanceView()->instanceForNode(modelNode());
+ return nodeInstanceView()->instanceForModelNode(modelNode());
}
QmlObjectNode QmlObjectNode::nodeForInstance(const NodeInstance &instance) const
{
- return QmlObjectNode(ModelNode(instance.modelNode(), qmlModelView()));
+ return QmlObjectNode(ModelNode(instance.modelNode(), view()));
}
QmlItemNode QmlObjectNode::itemForInstance(const NodeInstance &instance) const
{
- return QmlItemNode(ModelNode(instance.modelNode(), qmlModelView()));
+ return QmlItemNode(ModelNode(instance.modelNode(), view()));
+}
+
+QmlObjectNode::QmlObjectNode()
+ : QmlModelNodeFacade()
+{
+}
+
+QmlObjectNode::QmlObjectNode(const ModelNode &modelNode)
+ : QmlModelNodeFacade(modelNode)
+{
+}
+
+bool QmlObjectNode::isValidQmlObjectNode(const ModelNode &modelNode)
+{
+ return isValidQmlModelNodeFacade(modelNode);
+}
+
+bool QmlObjectNode::isValid() const
+{
+ return isValidQmlObjectNode(modelNode());
}
bool QmlObjectNode::hasNodeParent() const
@@ -452,14 +466,14 @@ bool QmlObjectNode::hasNodeParent() const
bool QmlObjectNode::hasInstanceParent() const
{
- return nodeInstance().parentId() >= 0 && qmlModelView()->nodeInstanceView()->hasInstanceForId(nodeInstance().parentId());
+ return nodeInstance().parentId() >= 0 && nodeInstanceView()->hasInstanceForId(nodeInstance().parentId());
}
bool QmlObjectNode::hasInstanceParentItem() const
{
return nodeInstance().parentId() >= 0
- && qmlModelView()->nodeInstanceView()->hasInstanceForId(nodeInstance().parentId())
- && QmlItemNode::isItemOrWindow(qmlModelView()->modelNodeForInternalId(nodeInstance().parentId()));
+ && nodeInstanceView()->hasInstanceForId(nodeInstance().parentId())
+ && QmlItemNode::isItemOrWindow(view()->modelNodeForInternalId(nodeInstance().parentId()));
}
@@ -471,7 +485,7 @@ void QmlObjectNode::setParentProperty(const NodeAbstractProperty &parentProeprty
QmlObjectNode QmlObjectNode::instanceParent() const
{
if (hasInstanceParent())
- return nodeForInstance(qmlModelView()->nodeInstanceView()->instanceForId(nodeInstance().parentId()));
+ return nodeForInstance(nodeInstanceView()->instanceForId(nodeInstance().parentId()));
return QmlObjectNode();
}
@@ -479,7 +493,7 @@ QmlObjectNode QmlObjectNode::instanceParent() const
QmlItemNode QmlObjectNode::instanceParentItem() const
{
if (hasInstanceParentItem())
- return itemForInstance(qmlModelView()->nodeInstanceView()->instanceForId(nodeInstance().parentId()));
+ return itemForInstance(nodeInstanceView()->instanceForId(nodeInstance().parentId()));
return QmlItemNode();
}
@@ -499,20 +513,20 @@ QString QmlObjectNode::validId()
return modelNode().validId();
}
-bool QmlObjectNode::hasDefaultProperty() const
+bool QmlObjectNode::hasDefaultPropertyName() const
{
return modelNode().metaInfo().hasDefaultProperty();
}
-PropertyName QmlObjectNode::defaultProperty() const
+PropertyName QmlObjectNode::defaultPropertyName() const
{
return modelNode().metaInfo().defaultPropertyName();
}
void QmlObjectNode::setParent(QmlObjectNode newParent)
{
- if (newParent.hasDefaultProperty())
- newParent.modelNode().nodeAbstractProperty(newParent.defaultProperty()).reparentHere(modelNode());
+ if (newParent.hasDefaultPropertyName())
+ newParent.modelNode().defaultNodeAbstractProperty().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 44909ab520..b2bd156ef9 100644
--- a/src/plugins/qmldesigner/designercore/model/qmlstate.cpp
+++ b/src/plugins/qmldesigner/designercore/model/qmlstate.cpp
@@ -28,13 +28,16 @@
****************************************************************************/
#include "qmlstate.h"
-#include "qmlmodelview.h"
+#include "abstractview.h"
#include <nodelistproperty.h>
#include <variantproperty.h>
#include <metainfo.h>
#include <invalidmodelnodeexception.h>
#include "bindingproperty.h"
+#include "qmlchangeset.h"
+#include "qmlitemnode.h"
+#include <utils/qtcassert.h>
namespace QmlDesigner {
@@ -50,91 +53,73 @@ QmlModelState::QmlModelState(const ModelNode &modelNode)
QmlPropertyChanges QmlModelState::propertyChanges(const ModelNode &node)
{
- //### exception if not valid
-
- if (isBaseState())
- return QmlPropertyChanges();
-
- addChangeSetIfNotExists(node);
- foreach (const ModelNode &childNode, modelNode().nodeListProperty("changes").toModelNodeList()) {
- //### exception if not valid QmlModelStateOperation
- if (QmlPropertyChanges(childNode).target().isValid() && QmlPropertyChanges(childNode).target() == node && QmlPropertyChanges(childNode).isValid())
- return QmlPropertyChanges(childNode); //### exception if not valid(childNode);
+ if (!isBaseState()) {
+ addChangeSetIfNotExists(node);
+ foreach (const ModelNode &childNode, modelNode().nodeListProperty("changes").toModelNodeList()) {
+ //### exception if not valid QmlModelStateOperation
+ if (QmlPropertyChanges::isValidQmlPropertyChanges(childNode)
+ && QmlPropertyChanges(childNode).target().isValid()
+ && QmlPropertyChanges(childNode).target() == node)
+ return QmlPropertyChanges(childNode); //### exception if not valid(childNode);
+ }
}
+
return QmlPropertyChanges(); //not found
}
QList<QmlModelStateOperation> QmlModelState::stateOperations(const ModelNode &node) const
{
QList<QmlModelStateOperation> returnList;
- //### exception if not valid
- if (isBaseState())
- return returnList;
-
- if (!modelNode().hasProperty("changes"))
- return returnList;
-
- Q_ASSERT(modelNode().property("changes").isNodeListProperty());
-
- foreach (const ModelNode &childNode, modelNode().nodeListProperty("changes").toModelNodeList()) {
- QmlModelStateOperation stateOperation(childNode);
- if (stateOperation.isValid()) {
- ModelNode targetNode = stateOperation.target();
- if (targetNode.isValid()
- && targetNode == node)
- returnList.append(stateOperation); //### exception if not valid(childNode);
+ if (!isBaseState() && modelNode().hasNodeListProperty("changes")) {
+ foreach (const ModelNode &childNode, modelNode().nodeListProperty("changes").toModelNodeList()) {
+ if (QmlModelStateOperation::isValidQmlModelStateOperation(childNode)) {
+ QmlModelStateOperation stateOperation(childNode);
+ ModelNode targetNode = stateOperation.target();
+ if (targetNode.isValid() && targetNode == node)
+ returnList.append(stateOperation); //### exception if not valid(childNode);
+ }
}
}
+
return returnList; //not found
}
QList<QmlPropertyChanges> QmlModelState::propertyChanges() const
{
- //### exception if not valid
QList<QmlPropertyChanges> returnList;
- if (isBaseState())
- return returnList;
-
- if (!modelNode().hasProperty("changes"))
- return returnList;
-
- Q_ASSERT(modelNode().property("changes").isNodeListProperty());
-
- foreach (const ModelNode &childNode, modelNode().nodeListProperty("changes").toModelNodeList()) {
- //### exception if not valid QmlModelStateOperation
- if (QmlPropertyChanges(childNode).isValid())
- returnList.append(QmlPropertyChanges(childNode));
+ if (!isBaseState() && modelNode().hasNodeListProperty("changes")) {
+ foreach (const ModelNode &childNode, modelNode().nodeListProperty("changes").toModelNodeList()) {
+ //### exception if not valid QmlModelStateOperation
+ if (QmlPropertyChanges::isValidQmlPropertyChanges(childNode))
+ returnList.append(QmlPropertyChanges(childNode));
+ }
}
+
return returnList;
}
bool QmlModelState::hasPropertyChanges(const ModelNode &node) const
{
- //### exception if not valid
-
- if (isBaseState())
- return false;
-
- foreach (const QmlPropertyChanges &changeSet, propertyChanges()) {
- if (changeSet.target().isValid() && changeSet.target() == node)
- return true;
+ if (!isBaseState() && modelNode().hasNodeListProperty("changes")) {
+ foreach (const QmlPropertyChanges &changeSet, propertyChanges()) {
+ if (changeSet.target().isValid() && changeSet.target() == node)
+ return true;
+ }
}
+
return false;
}
bool QmlModelState::hasStateOperation(const ModelNode &node) const
{
- //### exception if not valid
-
- if (isBaseState())
- return false;
-
- foreach (const QmlModelStateOperation &stateOperation, stateOperations()) {
- if (stateOperation.target() == node)
- return true;
+ if (!isBaseState()) {
+ foreach (const QmlModelStateOperation &stateOperation, stateOperations()) {
+ if (stateOperation.target() == node)
+ return true;
+ }
}
return false;
}
@@ -144,19 +129,14 @@ QList<QmlModelStateOperation> QmlModelState::stateOperations() const
//### exception if not valid
QList<QmlModelStateOperation> returnList;
- if (isBaseState())
- return returnList;
-
- if (!modelNode().hasProperty("changes"))
- return returnList;
-
- Q_ASSERT(modelNode().property("changes").isNodeListProperty());
-
- foreach (const ModelNode &childNode, modelNode().nodeListProperty("changes").toModelNodeList()) {
- //### exception if not valid QmlModelStateOperation
- if (QmlModelStateOperation(childNode).isValid())
- returnList.append(QmlModelStateOperation(childNode));
+ if (!isBaseState() && modelNode().hasNodeListProperty("changes")) {
+ foreach (const ModelNode &childNode, modelNode().nodeListProperty("changes").toModelNodeList()) {
+ //### exception if not valid QmlModelStateOperation
+ if (QmlModelStateOperation::isValidQmlModelStateOperation(childNode))
+ returnList.append(QmlModelStateOperation(childNode));
+ }
}
+
return returnList;
}
@@ -168,24 +148,21 @@ QList<QmlModelStateOperation> QmlModelState::stateOperations() const
void QmlModelState::addChangeSetIfNotExists(const ModelNode &node)
{
- //### exception if not valid
-
if (!isValid())
throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);
- if (hasPropertyChanges(node))
- return; //changeSet already there
+ if (!hasPropertyChanges(node)) {
+ ModelNode newChangeSet;
+ if (view()->majorQtQuickVersion() > 1)
+ newChangeSet = modelNode().view()->createModelNode("QtQuick.PropertyChanges", 2, 0);
+ else
+ 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);
+ modelNode().nodeListProperty("changes").reparentHere(newChangeSet);
- QmlPropertyChanges(newChangeSet).setTarget(node);
- Q_ASSERT(QmlPropertyChanges(newChangeSet).isValid());
+ QmlPropertyChanges(newChangeSet).setTarget(node);
+ Q_ASSERT(QmlPropertyChanges::isValidQmlPropertyChanges(newChangeSet));
+ }
}
void QmlModelState::removePropertyChanges(const ModelNode &node)
@@ -195,12 +172,11 @@ void QmlModelState::removePropertyChanges(const ModelNode &node)
if (!isValid())
throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);
- if (isBaseState())
- return;
-
- QmlPropertyChanges theChangeSet(propertyChanges(node));
- if (theChangeSet.isValid())
- theChangeSet.modelNode().destroy();
+ if (!isBaseState()) {
+ QmlPropertyChanges changeSet(propertyChanges(node));
+ if (changeSet.isValid())
+ changeSet.modelNode().destroy();
+ }
}
@@ -221,11 +197,11 @@ QList<QmlObjectNode> QmlModelState::allAffectedNodes() const
QList<QmlObjectNode> returnList;
foreach (const ModelNode &childNode, modelNode().nodeListProperty("changes").toModelNodeList()) {
- //### exception if not valid QmlModelStateOperation
- if (QmlModelStateOperation(childNode).isValid() &&
+ if (QmlModelStateOperation::isValidQmlModelStateOperation(childNode) &&
!returnList.contains(QmlModelStateOperation(childNode).target()))
returnList.append(QmlModelStateOperation(childNode).target());
}
+
return returnList;
}
@@ -245,9 +221,14 @@ void QmlModelState::setName(const QString &name)
bool QmlModelState::isValid() const
{
- return QmlModelNodeFacade::isValid() &&
- modelNode().metaInfo().isValid() &&
- (modelNode().metaInfo().isSubclassOf("QtQuick.State", -1, -1) || isBaseState());
+ return isValidQmlModelState(modelNode());
+}
+
+bool QmlModelState::isValidQmlModelState(const ModelNode &modelNode)
+{
+ return isValidQmlModelNodeFacade(modelNode)
+ && modelNode.metaInfo().isValid()
+ && (modelNode.metaInfo().isSubclassOf("QtQuick.State", -1, -1) || isBaseState(modelNode));
}
/**
@@ -265,7 +246,12 @@ void QmlModelState::destroy()
bool QmlModelState::isBaseState() const
{
- return !modelNode().isValid() || modelNode().isRootNode();
+ return isBaseState(modelNode());
+}
+
+bool QmlModelState::isBaseState(const ModelNode &modelNode)
+{
+ return !modelNode.isValid() || modelNode.isRootNode();
}
QmlModelState QmlModelState::duplicate(const QString &name) const
@@ -273,21 +259,19 @@ QmlModelState QmlModelState::duplicate(const QString &name) const
if (!isValid())
throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);
- QmlItemNode parentNode(modelNode().parentProperty().parentModelNode());
- if (!parentNode.isValid())
+ if (!QmlItemNode::isValidQmlItemNode(modelNode().parentProperty().parentModelNode()))
throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);
// QmlModelState newState(stateGroup().addState(name));
PropertyListType propertyList;
propertyList.append(qMakePair(PropertyName("name"), QVariant(name)));
- QmlModelState newState ( qmlModelView()->createQmlState(propertyList) );
-
+ QmlModelState newState(createQmlState(view(), propertyList));
foreach (const ModelNode &childNode, modelNode().nodeListProperty("changes").toModelNodeList()) {
- ModelNode newModelNode(qmlModelView()->createModelNode(childNode.type(), childNode.majorVersion(), childNode.minorVersion()));
+ ModelNode newModelNode(view()->createModelNode(childNode.type(), childNode.majorVersion(), childNode.minorVersion()));
foreach (const BindingProperty &bindingProperty, childNode.bindingProperties())
newModelNode.bindingProperty(bindingProperty.name()).setExpression(bindingProperty.expression());
foreach (const VariantProperty &variantProperty, childNode.variantProperties())
- newModelNode.variantProperty(variantProperty.name()) = variantProperty.value();
+ newModelNode.variantProperty(variantProperty.name()).setValue(variantProperty.value());
newState.modelNode().nodeListProperty("changes").reparentHere(newModelNode);
}
@@ -302,11 +286,21 @@ QmlModelStateGroup QmlModelState::stateGroup() const
return parentNode.states();
}
-QmlModelState QmlModelState::createBaseState(const QmlModelView *view)
+ModelNode QmlModelState::createQmlState(AbstractView *view, const PropertyListType &propertyList)
+{
+ QTC_CHECK(view->majorQtQuickVersion() < 3);
+
+ if (view->majorQtQuickVersion() > 1)
+ return view->createModelNode("QtQuick.State", 2, 0, propertyList);
+ else
+ return view->createModelNode("QtQuick.State", 1, 0, propertyList);
+}
+
+QmlModelState QmlModelState::createBaseState(const AbstractView *view)
{
- QmlModelState fxState(view->rootModelNode());
+ QmlModelState qmlModelState(view->rootModelNode());
- return fxState;
+ return qmlModelState;
}
} // QmlDesigner
diff --git a/src/plugins/qmldesigner/designercore/model/rewriteaction.cpp b/src/plugins/qmldesigner/designercore/model/rewriteaction.cpp
index 264ca7ea93..a8a7ba3a0c 100644
--- a/src/plugins/qmldesigner/designercore/model/rewriteaction.cpp
+++ b/src/plugins/qmldesigner/designercore/model/rewriteaction.cpp
@@ -358,7 +358,7 @@ bool AddImportRewriteAction::execute(QmlDesigner::QmlRefactoring &refactoring,
if (!result)
qDebug() << "*** AddImportRewriteAction::execute failed in changeImports ("
- << m_import.toString()
+ << m_import.toImportString()
<< ") **"
<< info();
return result;
@@ -376,7 +376,7 @@ bool RemoveImportRewriteAction::execute(QmlDesigner::QmlRefactoring &refactoring
if (!result)
qDebug() << "*** RemoveImportRewriteAction::execute failed in changeImports ("
- << m_import.toString()
+ << m_import.toImportString()
<< ") **"
<< info();
return result;
diff --git a/src/plugins/qmldesigner/designercore/model/rewriteactioncompressor.cpp b/src/plugins/qmldesigner/designercore/model/rewriteactioncompressor.cpp
index c33a1ae62e..0223d5d86a 100644
--- a/src/plugins/qmldesigner/designercore/model/rewriteactioncompressor.cpp
+++ b/src/plugins/qmldesigner/designercore/model/rewriteactioncompressor.cpp
@@ -38,17 +38,17 @@
using namespace QmlDesigner;
using namespace QmlDesigner::Internal;
-static bool nodeOrParentInSet(const ModelNode &node, const QSet<ModelNode> &nodeSet)
+static bool nodeOrParentInSet(const ModelNode &modelNode, const QSet<ModelNode> &nodeSet)
{
- ModelNode n = node;
- while (n.isValid()) {
- if (nodeSet.contains(n))
+ ModelNode currentModelnode = modelNode;
+ while (currentModelnode.isValid()) {
+ if (nodeSet.contains(currentModelnode))
return true;
- if (!n.hasParentProperty())
+ if (!currentModelnode.hasParentProperty())
return false;
- n = n.parentProperty().parentModelNode();
+ currentModelnode = currentModelnode.parentProperty().parentModelNode();
}
return false;
diff --git a/src/plugins/qmldesigner/designercore/model/rewriterview.cpp b/src/plugins/qmldesigner/designercore/model/rewriterview.cpp
index 5e84c216fb..28289f605f 100644
--- a/src/plugins/qmldesigner/designercore/model/rewriterview.cpp
+++ b/src/plugins/qmldesigner/designercore/model/rewriterview.cpp
@@ -149,6 +149,9 @@ Internal::TextToModelMerger *RewriterView::textToModelMerger() const
void RewriterView::modelAttached(Model *model)
{
+ if (model && model->textModifier())
+ setTextModifier(model->textModifier());
+
AbstractView::modelAttached(model);
ModelAmender differenceHandler(m_textToModelMerger.data());
@@ -439,7 +442,7 @@ void RewriterView::rewriterEndTransaction()
}
}
-void RewriterView::actualStateChanged(const ModelNode & /*node*/)
+void RewriterView::currentStateChanged(const ModelNode & /*node*/)
{
}
@@ -483,12 +486,14 @@ QString RewriterView::textModifierContent() const
void RewriterView::reactivateTextMofifierChangeSignals()
{
- textModifier()->reactivateChangeSignals();
+ if (textModifier())
+ textModifier()->reactivateChangeSignals();
}
void RewriterView::deactivateTextMofifierChangeSignals()
{
- textModifier()->deactivateChangeSignals();
+ if (textModifier())
+ textModifier()->deactivateChangeSignals();
}
void RewriterView::applyModificationGroupChanges()
diff --git a/src/plugins/qmldesigner/designercore/model/signalhandlerproperty.cpp b/src/plugins/qmldesigner/designercore/model/signalhandlerproperty.cpp
index 56f538f027..528df5ad74 100644
--- a/src/plugins/qmldesigner/designercore/model/signalhandlerproperty.cpp
+++ b/src/plugins/qmldesigner/designercore/model/signalhandlerproperty.cpp
@@ -89,11 +89,4 @@ QString SignalHandlerProperty::source() const
return QString();
}
-SignalHandlerProperty& SignalHandlerProperty::operator= (const QString &source)
-{
- setSource(source);
-
- return *this;
-}
-
} // namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/designercore/model/texttomodelmerger.cpp b/src/plugins/qmldesigner/designercore/model/texttomodelmerger.cpp
index 8948278ec2..29cf46d84c 100644
--- a/src/plugins/qmldesigner/designercore/model/texttomodelmerger.cpp
+++ b/src/plugins/qmldesigner/designercore/model/texttomodelmerger.cpp
@@ -49,6 +49,8 @@
#include <qmljs/qmljsmodelmanagerinterface.h>
#include <qmljs/qmljsqrcparser.h>
+#include <utils/qtcassert.h>
+
#include <QSet>
#include <QDir>
@@ -111,11 +113,6 @@ static inline unsigned char convertHex(ushort c)
return (c - 'A' + 10);
}
-static inline unsigned char convertHex(ushort c1, ushort c2)
-{
- return ((convertHex(c1) << 4) + convertHex(c2));
-}
-
QChar convertUnicode(ushort c1, ushort c2,
ushort c3, ushort c4)
{
@@ -901,7 +898,7 @@ void TextToModelMerger::syncNode(ModelNode &modelNode,
}
}
- bool isImplicitComponent = modelNode.parentProperty().isValid() && propertyIsComponentType(modelNode.parentProperty(), typeName, modelNode.model());
+ bool isImplicitComponent = modelNode.hasParentProperty() && propertyIsComponentType(modelNode.parentProperty(), typeName, modelNode.model());
if (modelNode.type() != typeName //If there is no valid parentProperty //the node has just been created. The type is correct then.
@@ -992,7 +989,7 @@ void TextToModelMerger::syncNode(ModelNode &modelNode,
if (property->name.isEmpty() || property->memberType.isEmpty())
continue; // better safe than sorry.
- const QString &astName = property->name.toString();
+ const QStringRef astName = property->name;
QString astValue;
if (property->statement)
astValue = textAt(context->doc(),
@@ -1393,13 +1390,13 @@ void ModelValidator::variantValuesDiffer(VariantProperty &modelProperty, const Q
Q_UNUSED(qmlVariantValue)
Q_UNUSED(dynamicTypeName)
- Q_ASSERT(modelProperty.isDynamic() == !dynamicTypeName.isEmpty());
+ QTC_ASSERT(modelProperty.isDynamic() == !dynamicTypeName.isEmpty(), return);
if (modelProperty.isDynamic()) {
- Q_ASSERT(modelProperty.dynamicTypeName() == dynamicTypeName);
+ QTC_ASSERT(modelProperty.dynamicTypeName() == dynamicTypeName, return);
}
- Q_ASSERT(equals(modelProperty.value(), qmlVariantValue));
- Q_ASSERT(0);
+ QTC_ASSERT(equals(modelProperty.value(), qmlVariantValue), return);
+ QTC_ASSERT(0, return);
}
void ModelValidator::shouldBeVariantProperty(AbstractProperty &modelProperty, const QVariant &/*qmlVariantValue*/, const TypeName &/*dynamicTypeName*/)
@@ -1452,10 +1449,10 @@ void ModelValidator::typeDiffers(bool /*isRootNode*/,
Q_UNUSED(minorVersion)
Q_UNUSED(majorVersion)
- Q_ASSERT(modelNode.type() == typeName);
- Q_ASSERT(modelNode.majorVersion() == majorVersion);
- Q_ASSERT(modelNode.minorVersion() == minorVersion);
- Q_ASSERT(0);
+ QTC_ASSERT(modelNode.type() == typeName, return);
+ QTC_ASSERT(modelNode.majorVersion() == majorVersion, return);
+ QTC_ASSERT(modelNode.minorVersion() == minorVersion, return);
+ QTC_ASSERT(0, return);
}
void ModelValidator::propertyAbsentFromQml(AbstractProperty &modelProperty)
@@ -1471,8 +1468,8 @@ void ModelValidator::idsDiffer(ModelNode &modelNode, const QString &qmlId)
Q_UNUSED(modelNode)
Q_UNUSED(qmlId)
- Q_ASSERT(modelNode.id() == qmlId);
- Q_ASSERT(0);
+ QTC_ASSERT(modelNode.id() == qmlId, return);
+ QTC_ASSERT(0, return);
}
void ModelAmender::modelMissesImport(const QmlDesigner::Import &import)
@@ -1656,7 +1653,7 @@ void ModelAmender::typeDiffers(bool isRootNode,
QmlJS::AST::UiObjectMember *astNode,
ReadingContext *context)
{
- const bool propertyTakesComponent = propertyIsComponentType(modelNode.parentProperty(), typeName, modelNode.model());
+ const bool propertyTakesComponent = modelNode.hasParentProperty() && propertyIsComponentType(modelNode.parentProperty(), typeName, modelNode.model());
if (isRootNode) {
modelNode.view()->changeRootNodeType(typeName, majorVersion, minorVersion);
diff --git a/src/plugins/qmldesigner/designercore/model/variantproperty.cpp b/src/plugins/qmldesigner/designercore/model/variantproperty.cpp
index 614a5f8050..40423adf95 100644
--- a/src/plugins/qmldesigner/designercore/model/variantproperty.cpp
+++ b/src/plugins/qmldesigner/designercore/model/variantproperty.cpp
@@ -89,13 +89,6 @@ QVariant VariantProperty::value() const
return QVariant();
}
-VariantProperty& VariantProperty::operator= (const QVariant &value)
-{
- setValue(value);
-
- return *this;
-}
-
void VariantProperty::setDynamicTypeNameAndValue(const TypeName &type, const QVariant &value)
{
Internal::WriteLocker locker(model());
diff --git a/src/plugins/qmldesigner/designercore/model/viewmanager.cpp b/src/plugins/qmldesigner/designercore/model/viewmanager.cpp
index 6205f0a2c7..6ed7323f2c 100644
--- a/src/plugins/qmldesigner/designercore/model/viewmanager.cpp
+++ b/src/plugins/qmldesigner/designercore/model/viewmanager.cpp
@@ -1,9 +1,8 @@
#include "viewmanager.h"
#include "componentaction.h"
-#include "formeditorwidget.h"
-#include "toolbox.h"
-#include "designeractionmanager.h"
+#include "designmodewidget.h"
+#include "crumblebar.h"
#include <qmldesigner/qmldesignerplugin.h>
@@ -12,11 +11,13 @@
namespace QmlDesigner {
+
+static CrumbleBar *crumbleBar() {
+ return QmlDesignerPlugin::instance()->mainWidget()->crumbleBar();
+}
+
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
}
ViewManager::~ViewManager()
@@ -32,7 +33,7 @@ DesignDocument *ViewManager::currentDesignDocument() const
QString ViewManager::pathToQt() const
{
- QtSupport::BaseQtVersion *activeQtVersion = QtSupport::QtVersionManager::instance()->version(currentDesignDocument()->qtVersionId());
+ QtSupport::BaseQtVersion *activeQtVersion = QtSupport::QtVersionManager::version(currentDesignDocument()->qtVersionId());
if (activeQtVersion && (activeQtVersion->qtVersion() >= QtSupport::QtVersionNumber(4, 7, 1))
&& (activeQtVersion->type() == QLatin1String(QtSupport::Constants::DESKTOPQT)
|| activeQtVersion->type() == QLatin1String(QtSupport::Constants::SIMULATORQT)))
@@ -47,12 +48,11 @@ void ViewManager::attachNodeInstanceView()
currentModel()->setNodeInstanceView(&m_nodeInstanceView);
}
-void ViewManager::attachRewriterView(TextModifier *textModifier)
+void ViewManager::attachRewriterView()
{
if (currentDesignDocument()->rewriterView()) {
- currentDesignDocument()->rewriterView()->setTextModifier(textModifier);
- currentDesignDocument()->rewriterView()->reactivateTextMofifierChangeSignals();
currentModel()->setRewriterView(currentDesignDocument()->rewriterView());
+ currentDesignDocument()->rewriterView()->reactivateTextMofifierChangeSignals();
}
}
@@ -97,14 +97,16 @@ void ViewManager::detachViewsExceptRewriterAndComponetView()
{
switchStateEditorViewToBaseState();
detachAdditionalViews();
- currentModel()->detachView(DesignerActionManager::view());
+ currentModel()->detachView(&m_designerActionManagerView);
currentModel()->detachView(&m_formEditorView);
currentModel()->detachView(&m_navigatorView);
currentModel()->detachView(&m_itemLibraryView);
currentModel()->detachView(&m_statesEditorView);
currentModel()->detachView(&m_propertyEditorView);
+
if (m_debugView.isAttached())
currentModel()->detachView(&m_debugView);
+
currentModel()->setNodeInstanceView(0);
}
@@ -142,13 +144,14 @@ void ViewManager::attachViewsExceptRewriterAndComponetView()
{
if (QmlDesignerPlugin::instance()->settings().enableDebugView)
currentModel()->attachView(&m_debugView);
+
attachNodeInstanceView();
currentModel()->attachView(&m_formEditorView);
currentModel()->attachView(&m_navigatorView);
attachItemLibraryView();
currentModel()->attachView(&m_statesEditorView);
currentModel()->attachView(&m_propertyEditorView);
- currentModel()->attachView(DesignerActionManager::view());
+ currentModel()->attachView(&m_designerActionManagerView);
attachAdditionalViews();
switchStateEditorViewToSavedState();
}
@@ -207,26 +210,40 @@ void ViewManager::enableWidgets()
widgetInfo.widget->setEnabled(true);
}
-void ViewManager::pushFileOnCrambleBar(const QString &fileName)
+void ViewManager::pushFileOnCrumbleBar(const QString &fileName)
{
- m_formEditorView.formEditorWidget()->formEditorCrumbleBar()->pushFile(fileName);
+ crumbleBar()->pushFile(fileName);
}
-void ViewManager::pushInFileComponentOnCrambleBar(const QString &componentId)
-
+void ViewManager::pushInFileComponentOnCrumbleBar(const ModelNode &modelNode)
{
- m_formEditorView.formEditorWidget()->formEditorCrumbleBar()->pushInFileComponent(componentId);
+ crumbleBar()->pushInFileComponent(modelNode);
}
void ViewManager::nextFileIsCalledInternally()
{
- m_formEditorView.formEditorWidget()->formEditorCrumbleBar()->nextFileIsCalledInternally();
+ crumbleBar()->nextFileIsCalledInternally();
+}
+
+NodeInstanceView *ViewManager::nodeInstanceView()
+{
+ return &m_nodeInstanceView;
+}
+
+QWidgetAction *ViewManager::componentViewAction()
+{
+ return m_componentView.action();
}
- QmlModelView *ViewManager::qmlModelView()
- {
- return &m_formEditorView;
- }
+DesignerActionManager &ViewManager::designerActionManager()
+{
+ return m_designerActionManagerView.designerActionManager();
+}
+
+const DesignerActionManager &ViewManager::designerActionManager() const
+{
+ return m_designerActionManagerView.designerActionManager();
+}
Model *ViewManager::currentModel() const
{
diff --git a/src/plugins/qmldesigner/designmodewidget.cpp b/src/plugins/qmldesigner/designmodewidget.cpp
index b8df512dc7..9a163ff649 100644
--- a/src/plugins/qmldesigner/designmodewidget.cpp
+++ b/src/plugins/qmldesigner/designmodewidget.cpp
@@ -30,6 +30,7 @@
#include "designmodewidget.h"
#include "styledoutputpaneplaceholder.h"
#include "qmldesignerplugin.h"
+#include "crumblebar.h"
#include <rewriterview.h>
#include <itemlibrarywidget.h>
@@ -51,6 +52,7 @@
#include <QToolButton>
#include <QLabel>
#include <QTabWidget>
+#include <QToolBar>
using Core::MiniSplitter;
using Core::IEditor;
@@ -170,6 +172,10 @@ void DocumentWarningWidget::goToError()
DesignModeWidget::DesignModeWidget(QWidget *parent) :
QWidget(parent),
m_mainSplitter(0),
+ m_toolBar(Core::EditorManager::createToolBar(this)),
+ m_crumbleBar(new CrumbleBar(this)),
+ m_outputPanePlaceholder(0),
+ m_outputPlaceholderSplitter(0),
m_isDisabled(false),
m_showSidebars(true),
m_initStatus(NotInitialized),
@@ -177,8 +183,6 @@ DesignModeWidget::DesignModeWidget(QWidget *parent) :
m_navigatorHistoryCounter(-1),
m_keepNavigatorHistory(false)
{
- m_outputPlaceholderSplitter = new Core::MiniSplitter;
- m_outputPanePlaceholder = new StyledOutputpanePlaceHolder(Core::DesignMode::instance(), m_outputPlaceholderSplitter);
}
DesignModeWidget::~DesignModeWidget()
@@ -332,7 +336,10 @@ void DesignModeWidget::setup()
}
- m_toolBar = Core::EditorManager::createToolBar(this);
+ QToolBar *toolBar = new QToolBar(m_toolBar);
+
+ toolBar->addAction(viewManager().componentViewAction());
+ m_toolBar->addCenterToolBar(toolBar);
m_mainSplitter = new MiniSplitter(this);
m_mainSplitter->setObjectName("mainSplitter");
@@ -488,7 +495,7 @@ void DesignModeWidget::resizeEvent(QResizeEvent *event)
void DesignModeWidget::setupNavigatorHistory(Core::IEditor *editor)
{
if (!m_keepNavigatorHistory)
- addNavigatorHistoryEntry(editor->document()->fileName());
+ addNavigatorHistoryEntry(editor->document()->filePath());
const bool canGoBack = m_navigatorHistoryCounter > 0;
const bool canGoForward = m_navigatorHistoryCounter < (m_navigatorHistory.size() - 1);
@@ -524,8 +531,9 @@ QWidget *DesignModeWidget::createCenterWidget()
QVBoxLayout *rightLayout = new QVBoxLayout(centerWidget);
rightLayout->setMargin(0);
rightLayout->setSpacing(0);
- rightLayout->addWidget(m_toolBar);
+ rightLayout->addWidget(m_toolBar);
+ rightLayout->addWidget(createCrumbleBarFrame());
//### we now own these here
QList<WidgetInfo> topWidgetInfos;
@@ -546,6 +554,9 @@ QWidget *DesignModeWidget::createCenterWidget()
}
// editor and output panes
+ m_outputPlaceholderSplitter = new Core::MiniSplitter;
+ m_outputPanePlaceholder = new StyledOutputpanePlaceHolder(Core::DesignMode::instance(), m_outputPlaceholderSplitter);
+
if (centralWidgetInfos.count() == 1)
m_outputPlaceholderSplitter->addWidget(centralWidgetInfos.first().widget);
else
@@ -561,6 +572,22 @@ QWidget *DesignModeWidget::createCenterWidget()
return centerWidget;
}
+QWidget *DesignModeWidget::createCrumbleBarFrame()
+{
+ QFrame *frame = new QFrame(this);
+ 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_crumbleBar->crumblePath());
+ frame->setProperty("panelwidget", true);
+ frame->setProperty("panelwidget_singlerow", false);
+
+ return frame;
+}
+
void DesignModeWidget::showErrorMessage(const QList<RewriterView::Error> &errors)
{
Q_ASSERT(!errors.isEmpty());
@@ -569,6 +596,11 @@ void DesignModeWidget::showErrorMessage(const QList<RewriterView::Error> &errors
m_warningWidget->move(width() / 2, height() / 2);
}
+CrumbleBar *DesignModeWidget::crumbleBar() const
+{
+ return m_crumbleBar;
+}
+
QString DesignModeWidget::contextHelpId() const
{
if (currentDesignDocument())
diff --git a/src/plugins/qmldesigner/designmodewidget.h b/src/plugins/qmldesigner/designmodewidget.h
index 58142ab8c3..73e29f202d 100644
--- a/src/plugins/qmldesigner/designmodewidget.h
+++ b/src/plugins/qmldesigner/designmodewidget.h
@@ -35,7 +35,6 @@
#include <designdocument.h>
#include <modelnode.h>
-#include <propertyeditor.h>
#include <QWidget>
#include <QLabel>
@@ -51,7 +50,6 @@ QT_END_NAMESPACE
namespace Core {
class SideBar;
class SideBarItem;
- class OpenEditorsModel;
class EditorToolBar;
class OutputPanePlaceHolder;
}
@@ -59,6 +57,7 @@ namespace Core {
namespace QmlDesigner {
class ItemLibraryWidget;
+class CrumbleBar;
namespace Internal {
@@ -111,6 +110,8 @@ public:
void disableWidgets();
void showErrorMessage(const QList<RewriterView::Error> &errors);
+ CrumbleBar* crumbleBar() const;
+
public slots:
void updateErrorStatus(const QList<RewriterView::Error> &errors);
void restoreDefaultView();
@@ -140,12 +141,14 @@ private: // functions
QmlDesigner::ModelNode nodeForPosition(int cursorPos) const;
void addNavigatorHistoryEntry(const QString &fileName);
QWidget *createCenterWidget();
+ QWidget *createCrumbleBarFrame();
private: // variables
QSplitter *m_mainSplitter;
QScopedPointer<Core::SideBar> m_leftSideBar;
QScopedPointer<Core::SideBar> m_rightSideBar;
Core::EditorToolBar *m_toolBar;
+ CrumbleBar *m_crumbleBar;
Core::OutputPanePlaceHolder *m_outputPanePlaceholder;
Core::MiniSplitter *m_outputPlaceholderSplitter;
bool m_isDisabled;
diff --git a/src/plugins/qmldesigner/documentmanager.cpp b/src/plugins/qmldesigner/documentmanager.cpp
index b69d9adafa..faad001b4d 100644
--- a/src/plugins/qmldesigner/documentmanager.cpp
+++ b/src/plugins/qmldesigner/documentmanager.cpp
@@ -28,9 +28,142 @@
****************************************************************************/
#include "documentmanager.h"
+#include "qmldesignerplugin.h"
+
+#include <modelnode.h>
+#include <qmlitemnode.h>
+#include <nodemetainfo.h>
+#include <nodeproperty.h>
+#include <bindingproperty.h>
namespace QmlDesigner {
+static inline DesignDocument* currentDesignDocument()
+{
+ return QmlDesignerPlugin::instance()->documentManager().currentDesignDocument();
+}
+
+static inline void getProperties(const ModelNode node, QHash<PropertyName, QVariant> &propertyHash)
+{
+ if (QmlObjectNode::isValidQmlObjectNode(node)) {
+ foreach (const AbstractProperty &abstractProperty, node.properties()) {
+ if (abstractProperty.isVariantProperty()
+ || (abstractProperty.isBindingProperty()
+ && !abstractProperty.name().contains("anchors.")))
+ propertyHash.insert(abstractProperty.name(), QmlObjectNode(node).instanceValue(abstractProperty.name()));
+ }
+
+ if (QmlItemNode::isValidQmlItemNode(node)) {
+ QmlItemNode itemNode(node);
+
+ propertyHash.insert("width", itemNode.instanceValue("width"));
+ propertyHash.insert("height", itemNode.instanceValue("height"));
+ propertyHash.remove("x");
+ propertyHash.remove("y");
+ propertyHash.remove("rotation");
+ propertyHash.remove("opacity");
+ }
+ }
+}
+
+static inline void applyProperties(ModelNode &node, const QHash<PropertyName, QVariant> &propertyHash)
+{
+ QHash<PropertyName, QVariant> auxiliaryData = node.auxiliaryData();
+
+ foreach (const PropertyName &propertyName, auxiliaryData.keys()) {
+ if (node.hasAuxiliaryData(propertyName))
+ node.setAuxiliaryData(propertyName, QVariant());
+ }
+
+ QHashIterator<PropertyName, QVariant> propertyIterator(propertyHash);
+ while (propertyIterator.hasNext()) {
+ propertyIterator.next();
+ const PropertyName propertyName = propertyIterator.key();
+ if (propertyName == "width" || propertyName == "height") {
+ node.setAuxiliaryData(propertyIterator.key(), propertyIterator.value());
+ } else if (node.property(propertyIterator.key()).isDynamic() &&
+ node.property(propertyIterator.key()).dynamicTypeName() == "alias" &&
+ node.property(propertyIterator.key()).isBindingProperty()) {
+ AbstractProperty targetProperty = node.bindingProperty(propertyIterator.key()).resolveToProperty();
+ if (targetProperty.isValid())
+ targetProperty.parentModelNode().setAuxiliaryData(targetProperty.name() + "@NodeInstance", propertyIterator.value());
+ } else {
+ node.setAuxiliaryData(propertyIterator.key() + "@NodeInstance", propertyIterator.value());
+ }
+ }
+}
+
+static inline void openFileForComponent(const ModelNode &node)
+{
+ QmlDesignerPlugin::instance()->viewManager().nextFileIsCalledInternally();
+
+ //int width = 0;
+ //int height = 0;
+ QHash<PropertyName, QVariant> propertyHash;
+ if (node.metaInfo().isFileComponent()) {
+ //getWidthHeight(node, width, height);
+ getProperties(node, propertyHash);
+ Core::EditorManager::openEditor(node.metaInfo().componentFileName(), Core::Id(), Core::EditorManager::DoNotMakeVisible);
+ } else if (node.metaInfo().isView() &&
+ node.hasNodeProperty("delegate") &&
+ node.nodeProperty("delegate").modelNode().metaInfo().isFileComponent()) {
+ //getWidthHeight(node, width, height);
+ getProperties(node, propertyHash);
+ Core::EditorManager::openEditor(node.nodeProperty("delegate").modelNode().metaInfo().componentFileName(),
+ Core::Id(), Core::EditorManager::DoNotMakeVisible);
+ }
+ 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<PropertyName, QVariant> propertyHash;
+
+ if (node.nodeSourceType() == ModelNode::NodeWithComponentSource) {
+ //getWidthHeight(node, width, height);
+ getProperties(node, propertyHash);
+ currentDesignDocument()->changeToSubComponent(node);
+ } else if (node.metaInfo().isView()
+ && node.hasNodeProperty("delegate")
+ && 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);
+}
+
+static inline bool isFileComponent(const ModelNode &node)
+{
+ if (!node.isValid() || !node.metaInfo().isValid())
+ return false;
+
+ if (node.metaInfo().isFileComponent())
+ return true;
+
+ if (node.metaInfo().isView() &&
+ node.hasNodeProperty("delegate")) {
+ if (node.nodeProperty("delegate").modelNode().metaInfo().isFileComponent())
+ return true;
+ }
+
+ return false;
+}
+
DocumentManager::DocumentManager()
: QObject()
{
@@ -73,4 +206,16 @@ void DocumentManager::removeEditors(QList<Core::IEditor *> editors)
delete m_designDocumentHash.take(editor).data();
}
+void DocumentManager::goIntoComponent(const ModelNode &modelNode)
+{
+ if (modelNode.isValid() && modelNode.isComponent()) {
+ QmlDesignerPlugin::instance()->viewManager().setComponentNode(modelNode);
+ if (isFileComponent(modelNode))
+ openFileForComponent(modelNode);
+ else
+ openInlineComponent(modelNode);
+ }
+}
+
+
} // namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/documentmanager.h b/src/plugins/qmldesigner/documentmanager.h
index 39ea23d96a..5c45d05523 100644
--- a/src/plugins/qmldesigner/documentmanager.h
+++ b/src/plugins/qmldesigner/documentmanager.h
@@ -42,7 +42,7 @@ class IEditor;
namespace QmlDesigner {
-class DocumentManager : public QObject
+class QMLDESIGNERCORE_EXPORT DocumentManager : public QObject
{
Q_OBJECT
public:
@@ -55,6 +55,8 @@ public:
void removeEditors(QList<Core::IEditor*> editors);
+ static void goIntoComponent(const ModelNode &modelNode);
+
private:
QHash<Core::IEditor *,QWeakPointer<DesignDocument> > m_designDocumentHash;
QWeakPointer<DesignDocument> m_currentDesignDocument;
diff --git a/src/plugins/qmldesigner/qmldesigner_dependencies.pri b/src/plugins/qmldesigner/qmldesigner_dependencies.pri
index 654b5cb1c6..7dac1977a0 100644
--- a/src/plugins/qmldesigner/qmldesigner_dependencies.pri
+++ b/src/plugins/qmldesigner/qmldesigner_dependencies.pri
@@ -15,6 +15,7 @@ INCLUDEPATH *= \
$$PWD/designercore \
$$PWD/designercore/include \
$$PWD/components/componentcore \
+ $$PWD/components/importmanager \
$$PWD/components/formeditor \
$$PWD/components/itemlibrary \
$$PWD/components/navigator \
diff --git a/src/plugins/qmldesigner/qmldesignerconstants.h b/src/plugins/qmldesigner/qmldesignerconstants.h
index 366eef4449..8e5bdf4e0d 100644
--- a/src/plugins/qmldesigner/qmldesignerconstants.h
+++ b/src/plugins/qmldesigner/qmldesignerconstants.h
@@ -33,7 +33,7 @@
namespace QmlDesigner {
namespace Constants {
-const char DELETE[] = "QmlDesigner.Delete";
+const char C_DELETE[] = "QmlDesigner.Delete";
// Context
const char C_QMLDESIGNER[] = "QmlDesigner::QmlDesignerMain";
diff --git a/src/plugins/qmldesigner/qmldesignerplugin.cpp b/src/plugins/qmldesigner/qmldesignerplugin.cpp
index 94bc843fe2..d9e93b3029 100644
--- a/src/plugins/qmldesigner/qmldesignerplugin.cpp
+++ b/src/plugins/qmldesigner/qmldesignerplugin.cpp
@@ -41,6 +41,7 @@
#include <coreplugin/designmode.h>
#include <coreplugin/icore.h>
#include <coreplugin/modemanager.h>
+#include <extensionsystem/pluginspec.h>
#include <projectexplorer/projectexplorerconstants.h>
@@ -151,12 +152,12 @@ void QmlDesignerPlugin::createDesignModeWidget()
m_shortCutManager.registerActions(qmlDesignerMainContext, qmlDesignerFormEditorContext, qmlDesignerNavigatorContext);
- connect(Core::ICore::editorManager(),
+ connect(Core::EditorManager::instance(),
SIGNAL(currentEditorChanged(Core::IEditor*)),
this,
SLOT(onCurrentEditorChanged(Core::IEditor*)));
- connect(Core::ICore::editorManager(),
+ connect(Core::EditorManager::instance(),
SIGNAL(editorsClosed(QList<Core::IEditor*>)),
this,
SLOT(onTextEditorsClosed(QList<Core::IEditor*>)));
@@ -188,7 +189,7 @@ void QmlDesignerPlugin::showDesigner()
if (m_documentManager.hasCurrentDesignDocument()) {
activateAutoSynchronization();
m_shortCutManager.updateActions(currentDesignDocument()->textEditor());
- m_viewManager.pushFileOnCrambleBar(m_documentManager.currentDesignDocument()->fileName());
+ m_viewManager.pushFileOnCrumbleBar(m_documentManager.currentDesignDocument()->fileName());
}
m_shortCutManager.updateUndoActions(currentDesignDocument());
@@ -196,7 +197,8 @@ void QmlDesignerPlugin::showDesigner()
void QmlDesignerPlugin::hideDesigner()
{
- if (currentDesignDocument()->currentModel()
+ if (currentDesignDocument()
+ && currentDesignDocument()->currentModel()
&& !currentDesignDocument()->hasQmlSyntaxErrors())
jumpTextCursorToSelectedModelNode();
@@ -230,7 +232,7 @@ void QmlDesignerPlugin::changeEditor()
if (m_documentManager.hasCurrentDesignDocument()) {
activateAutoSynchronization();
- m_viewManager.pushFileOnCrambleBar(m_documentManager.currentDesignDocument()->fileName());
+ m_viewManager.pushFileOnCrumbleBar(m_documentManager.currentDesignDocument()->fileName());
}
m_shortCutManager.updateUndoActions(currentDesignDocument());
@@ -273,7 +275,7 @@ void QmlDesignerPlugin::activateAutoSynchronization()
currentDesignDocument()->loadDocument(currentDesignDocument()->plainTextEdit());
}
- currentDesignDocument()->activateDocumentModel();
+ currentDesignDocument()->attachRewriterToModel();
resetModelSelection();
@@ -417,6 +419,16 @@ const ViewManager &QmlDesignerPlugin::viewManager() const
return m_viewManager;
}
+DesignerActionManager &QmlDesignerPlugin::designerActionManager()
+{
+ return m_viewManager.designerActionManager();
+}
+
+const DesignerActionManager &QmlDesignerPlugin::designerActionManager() const
+{
+ return m_viewManager.designerActionManager();
+}
+
void QmlDesignerPlugin::switchTextDesign()
{
if (Core::ModeManager::currentMode()->id() == Core::Constants::MODE_EDIT) {
diff --git a/src/plugins/qmldesigner/qmldesignerplugin.h b/src/plugins/qmldesigner/qmldesignerplugin.h
index 9ed708e55d..36a72d971d 100644
--- a/src/plugins/qmldesigner/qmldesignerplugin.h
+++ b/src/plugins/qmldesigner/qmldesignerplugin.h
@@ -39,6 +39,7 @@
#include "documentmanager.h"
#include "viewmanager.h"
#include "shortcutmanager.h"
+#include <designeractionmanager.h>
#include <QStringList>
@@ -82,6 +83,9 @@ public:
ViewManager &viewManager();
const ViewManager &viewManager() const;
+ DesignerActionManager &designerActionManager();
+ const DesignerActionManager &designerActionManager() const;
+
DesignerSettings settings();
void setSettings(const DesignerSettings &s);
diff --git a/src/plugins/qmldesigner/qmldesignerplugin.pro b/src/plugins/qmldesigner/qmldesignerplugin.pro
index 401c51d722..c5026818da 100644
--- a/src/plugins/qmldesigner/qmldesignerplugin.pro
+++ b/src/plugins/qmldesigner/qmldesignerplugin.pro
@@ -16,6 +16,7 @@ include(components/pluginmanager/pluginmanager.pri)
include(components/stateseditor/stateseditor.pri)
include(components/resources/resources.pri)
include(components/debugview/debugview.pri)
+include(components/importmanager/importmanager.pri)
include(qmldesignerplugin.pri)
DEFINES -= QT_NO_CAST_FROM_ASCII
diff --git a/src/plugins/qmldesigner/shortcutmanager.cpp b/src/plugins/qmldesigner/shortcutmanager.cpp
index 1a56e4f22a..4f3b9c0604 100644
--- a/src/plugins/qmldesigner/shortcutmanager.cpp
+++ b/src/plugins/qmldesigner/shortcutmanager.cpp
@@ -3,7 +3,7 @@
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/icore.h>
-#include <coreplugin/editormanager/openeditorsmodel.h>
+#include <coreplugin/editormanager/documentmodel.h>
#include <coreplugin/coreconstants.h>
#include <utils/hostosinfo.h>
@@ -78,28 +78,29 @@ void ShortCutManager::registerActions(const Core::Context &qmlDesignerMainContex
SLOT(toggleRightSidebar()));
// Revert to saved
+ QObject *em = Core::EditorManager::instance();
Core::ActionManager::registerAction(&m_revertToSavedAction,Core::Constants::REVERTTOSAVED, qmlDesignerMainContext);
- connect(&m_revertToSavedAction, SIGNAL(triggered()), Core::ICore::editorManager(), SLOT(revertToSaved()));
+ connect(&m_revertToSavedAction, SIGNAL(triggered()), em, SLOT(revertToSaved()));
//Save
Core::ActionManager::registerAction(&m_saveAction, Core::Constants::SAVE, qmlDesignerMainContext);
- connect(&m_saveAction, SIGNAL(triggered()), Core::ICore::editorManager(), SLOT(saveDocument()));
+ connect(&m_saveAction, SIGNAL(triggered()), em, SLOT(saveDocument()));
//Save As
Core::ActionManager::registerAction(&m_saveAsAction, Core::Constants::SAVEAS, qmlDesignerMainContext);
- connect(&m_saveAsAction, SIGNAL(triggered()), Core::ICore::editorManager(), SLOT(saveDocumentAs()));
+ connect(&m_saveAsAction, SIGNAL(triggered()), em, SLOT(saveDocumentAs()));
//Close Editor
Core::ActionManager::registerAction(&m_closeCurrentEditorAction, Core::Constants::CLOSE, qmlDesignerMainContext);
- connect(&m_closeCurrentEditorAction, SIGNAL(triggered()), Core::ICore::editorManager(), SLOT(closeEditor()));
+ connect(&m_closeCurrentEditorAction, SIGNAL(triggered()), em, SLOT(closeEditor()));
//Close All
Core::ActionManager::registerAction(&m_closeAllEditorsAction, Core::Constants::CLOSEALL, qmlDesignerMainContext);
- connect(&m_closeAllEditorsAction, SIGNAL(triggered()), Core::ICore::editorManager(), SLOT(closeAllEditors()));
+ connect(&m_closeAllEditorsAction, SIGNAL(triggered()), em, 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()));
+ connect(&m_closeOtherEditorsAction, SIGNAL(triggered()), em, SLOT(closeOtherEditors()));
// Undo / Redo
Core::ActionManager::registerAction(&m_undoAction, Core::Constants::UNDO, qmlDesignerMainContext);
@@ -114,8 +115,8 @@ void ShortCutManager::registerActions(const Core::Context &qmlDesignerMainContex
//Edit Menu
- command = Core::ActionManager::registerAction(&m_deleteAction, QmlDesigner::Constants::DELETE, qmlDesignerFormEditorContext);
- command = Core::ActionManager::registerAction(&m_deleteAction, QmlDesigner::Constants::DELETE, qmlDesignerNavigatorContext);
+ command = Core::ActionManager::registerAction(&m_deleteAction, QmlDesigner::Constants::C_DELETE, qmlDesignerFormEditorContext);
+ command = Core::ActionManager::registerAction(&m_deleteAction, QmlDesigner::Constants::C_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);
@@ -172,28 +173,17 @@ void ShortCutManager::registerActions(const Core::Context &qmlDesignerMainContex
void ShortCutManager::updateActions(Core::IEditor* currentEditor)
{
- 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();
- }
- }
+ int openedCount = Core::EditorManager::documentModel()->documentCount();
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()->filePath().isEmpty()
&& currentEditor->document()->isModified());
QString quotedName;
- if (!fileName.isEmpty())
- quotedName = '"' + fileName + '"';
+ if (currentEditor)
+ quotedName = '"' + currentEditor->document()->displayName() + '"';
m_saveAsAction.setText(tr("Save %1 As...").arg(quotedName));
m_saveAction.setText(tr("&Save %1").arg(quotedName));
@@ -315,8 +305,12 @@ void ShortCutManager::redoAvailable(bool isAvailable)
void ShortCutManager::goIntoComponent()
{
- if (currentDesignDocument())
- currentDesignDocument()->goIntoSelectedComponent();
+ if (currentDesignDocument()
+ && currentDesignDocument()->currentModel()
+ && currentDesignDocument()->rewriterView()
+ && currentDesignDocument()->rewriterView()->hasSingleSelectedModelNode()) {
+ DocumentManager::goIntoComponent(currentDesignDocument()->rewriterView()->singleSelectedModelNode());
+ }
}
} // namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/styledoutputpaneplaceholder.cpp b/src/plugins/qmldesigner/styledoutputpaneplaceholder.cpp
index b1169edfc1..540f122049 100644
--- a/src/plugins/qmldesigner/styledoutputpaneplaceholder.cpp
+++ b/src/plugins/qmldesigner/styledoutputpaneplaceholder.cpp
@@ -33,9 +33,12 @@
#include <QChildEvent>
#include <QTabWidget>
-#include <QDebug>
-StyledOutputpanePlaceHolder::StyledOutputpanePlaceHolder(Core::IMode *mode, QSplitter *parent) : Core::OutputPanePlaceHolder(mode, parent)
+namespace QmlDesigner {
+namespace Internal {
+
+StyledOutputpanePlaceHolder::StyledOutputpanePlaceHolder(Core::IMode *mode, QSplitter *parent)
+ : Core::OutputPanePlaceHolder(mode, parent)
{
QByteArray sheet = Utils::FileReader::fetchQrc(":/qmldesigner/outputpane-style.css");
sheet += Utils::FileReader::fetchQrc(":/qmldesigner/scrollbar.css");
@@ -65,3 +68,6 @@ void StyledOutputpanePlaceHolder::childEvent(QChildEvent *event)
}
}
}
+
+} // namespace Internal
+} // namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/styledoutputpaneplaceholder.h b/src/plugins/qmldesigner/styledoutputpaneplaceholder.h
index 5a694ccc8d..1aa773074a 100644
--- a/src/plugins/qmldesigner/styledoutputpaneplaceholder.h
+++ b/src/plugins/qmldesigner/styledoutputpaneplaceholder.h
@@ -32,7 +32,8 @@
#include <coreplugin/outputpane.h>
-QT_FORWARD_DECLARE_CLASS(QChildEvent)
+namespace QmlDesigner {
+namespace Internal {
class StyledOutputpanePlaceHolder : public Core::OutputPanePlaceHolder
{
@@ -41,9 +42,12 @@ public:
protected:
void childEvent(QChildEvent *event);
+
private:
QString m_customStylesheet;
-
};
+} // namespace Internal
+} // namespace QmlDesigner
+
#endif // STYLEDOUTPUTPANEPLACEHOLDER_H
diff --git a/src/plugins/qmljseditor/QmlJSEditor.pluginspec.in b/src/plugins/qmljseditor/QmlJSEditor.pluginspec.in
index 991ba2cdb8..2138608d82 100644
--- a/src/plugins/qmljseditor/QmlJSEditor.pluginspec.in
+++ b/src/plugins/qmljseditor/QmlJSEditor.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"QmlJSEditor\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"QmlJSEditor\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/qmljseditor/jsfilewizard.cpp b/src/plugins/qmljseditor/jsfilewizard.cpp
index 19243618eb..9c790743b6 100644
--- a/src/plugins/qmljseditor/jsfilewizard.cpp
+++ b/src/plugins/qmljseditor/jsfilewizard.cpp
@@ -88,17 +88,10 @@ public:
using namespace QmlJSEditor;
-JsFileWizard::JsFileWizard(const BaseFileWizardParameters &parameters,
- QObject *parent):
- Core::BaseFileWizard(parameters, parent)
+JsFileWizard::JsFileWizard()
{
}
-Core::FeatureSet JsFileWizard::requiredFeatures() const
-{
- return Core::FeatureSet();
-}
-
Core::GeneratedFiles JsFileWizard::generateFiles(const QWizard *w,
QString * /*errorMessage*/) const
{
diff --git a/src/plugins/qmljseditor/jsfilewizard.h b/src/plugins/qmljseditor/jsfilewizard.h
index c80b70e94a..4d4cc7a140 100644
--- a/src/plugins/qmljseditor/jsfilewizard.h
+++ b/src/plugins/qmljseditor/jsfilewizard.h
@@ -39,21 +39,15 @@ class JsFileWizard: public Core::BaseFileWizard
Q_OBJECT
public:
- typedef Core::BaseFileWizardParameters BaseFileWizardParameters;
+ JsFileWizard();
- explicit JsFileWizard(const BaseFileWizardParameters &parameters,
- QObject *parent = 0);
-
- virtual Core::FeatureSet requiredFeatures() const;
-
-protected:
+private:
QString fileContents(const QString &baseName, bool statelessLibrary) const;
- virtual QWizard *createWizardDialog(QWidget *parent,
+ QWizard *createWizardDialog(QWidget *parent,
const Core::WizardDialogParameters &wizardDialogParameters) const;
- virtual Core::GeneratedFiles generateFiles(const QWizard *w,
- QString *errorMessage) const;
+ Core::GeneratedFiles generateFiles(const QWizard *w, QString *errorMessage) const;
};
} // namespace QmlJSEditor
diff --git a/src/plugins/qmljseditor/qmlfilewizard.cpp b/src/plugins/qmljseditor/qmlfilewizard.cpp
index 00ab5862d0..e35c30048b 100644
--- a/src/plugins/qmljseditor/qmlfilewizard.cpp
+++ b/src/plugins/qmljseditor/qmlfilewizard.cpp
@@ -37,9 +37,7 @@
using namespace QmlJSEditor;
-QmlFileWizard::QmlFileWizard(const BaseFileWizardParameters &parameters,
- QObject *parent):
- Core::StandardFileWizard(parameters, parent)
+QmlFileWizard::QmlFileWizard()
{
}
@@ -62,7 +60,7 @@ QString QmlFileWizard::fileContents(const QString &) const
QString contents;
QTextStream str(&contents);
- if (baseFileWizardParameters().id() == QLatin1String(Constants::WIZARD_QML1FILE))
+ if (id() == QLatin1String(Constants::WIZARD_QML1FILE))
str << QLatin1String("import QtQuick 1.1\n");
else
str << QLatin1String("import QtQuick 2.0\n");
diff --git a/src/plugins/qmljseditor/qmlfilewizard.h b/src/plugins/qmljseditor/qmlfilewizard.h
index 168e79c4bd..a476db3f97 100644
--- a/src/plugins/qmljseditor/qmlfilewizard.h
+++ b/src/plugins/qmljseditor/qmlfilewizard.h
@@ -39,15 +39,11 @@ class QmlFileWizard: public Core::StandardFileWizard
Q_OBJECT
public:
- typedef Core::BaseFileWizardParameters BaseFileWizardParameters;
+ QmlFileWizard();
- explicit QmlFileWizard(const BaseFileWizardParameters &parameters,
- QObject *parent = 0);
-
-protected:
+private:
QString fileContents(const QString &baseName) const;
-protected:
Core::GeneratedFiles generateFilesFromPath(const QString &path,
const QString &fileName,
QString *errorMessage) const;
diff --git a/src/plugins/qmljseditor/qmljscompletionassist.cpp b/src/plugins/qmljseditor/qmljscompletionassist.cpp
index 8cb43496e8..65a80f6d29 100644
--- a/src/plugins/qmljseditor/qmljscompletionassist.cpp
+++ b/src/plugins/qmljseditor/qmljscompletionassist.cpp
@@ -286,9 +286,8 @@ private:
{
if (! value)
return;
- else if (const ObjectValue *object = value->asObjectValue()) {
+ if (const ObjectValue *object = value->asObjectValue())
processProperties(object);
- }
}
void processProperties(const ObjectValue *object)
@@ -365,9 +364,8 @@ void QmlJSAssistProposalItem::applyContextualContent(TextEditor::BaseTextEditor
QString content = text();
int cursorOffset = 0;
- const CompletionSettings &completionSettings =
- TextEditorSettings::instance()->completionSettings();
- const bool autoInsertBrackets = completionSettings.m_autoInsertBrackets;
+ const bool autoInsertBrackets =
+ TextEditorSettings::completionSettings().m_autoInsertBrackets;
if (autoInsertBrackets && data().canConvert<CompleteFunctionCall>()) {
CompleteFunctionCall function = data().value<CompleteFunctionCall>();
@@ -1025,7 +1023,7 @@ void QmlJSAssistProposalModel::filter(const QString &prefix)
m_currentItems = newCurrentItems;
}
-void QmlJSAssistProposalModel::sort()
+void QmlJSAssistProposalModel::sort(const QString &)
{
qSort(currentItems().first, currentItems().second, QmlJSLessThan());
}
diff --git a/src/plugins/qmljseditor/qmljscompletionassist.h b/src/plugins/qmljseditor/qmljscompletionassist.h
index 04fa64cd45..a8437211e3 100644
--- a/src/plugins/qmljseditor/qmljscompletionassist.h
+++ b/src/plugins/qmljseditor/qmljscompletionassist.h
@@ -70,13 +70,15 @@ public:
{}
virtual void filter(const QString &prefix);
- virtual void sort();
+ virtual void sort(const QString &prefix);
virtual bool keepPerfectMatch(TextEditor::AssistReason reason) const;
};
class QmlJSCompletionAssistProvider : public TextEditor::CompletionAssistProvider
{
+ Q_OBJECT
+
public:
virtual bool supportsEditor(const Core::Id &editorId) const;
virtual TextEditor::IAssistProcessor *createProcessor() const;
diff --git a/src/plugins/qmljseditor/qmljscomponentfromobjectdef.cpp b/src/plugins/qmljseditor/qmljscomponentfromobjectdef.cpp
index 63702d918f..266ba57241 100644
--- a/src/plugins/qmljseditor/qmljscomponentfromobjectdef.cpp
+++ b/src/plugins/qmljseditor/qmljscomponentfromobjectdef.cpp
@@ -108,7 +108,7 @@ public:
if (!refactoring.createFile(newFileName, txt))
return;
- Core::IVersionControl *versionControl = Core::ICore::vcsManager()->findVersionControlForDirectory(path);
+ Core::IVersionControl *versionControl = Core::VcsManager::findVersionControlForDirectory(path);
if (versionControl
&& versionControl->supportsOperation(Core::IVersionControl::AddOperation)) {
const QMessageBox::StandardButton button =
diff --git a/src/plugins/qmljseditor/qmljseditor.cpp b/src/plugins/qmljseditor/qmljseditor.cpp
index e1cb96f90e..f54d440834 100644
--- a/src/plugins/qmljseditor/qmljseditor.cpp
+++ b/src/plugins/qmljseditor/qmljseditor.cpp
@@ -93,6 +93,7 @@ enum {
UPDATE_OUTLINE_INTERVAL = 500 // msecs after new semantic info has been arrived / cursor has moved
};
+using namespace Core;
using namespace QmlJS;
using namespace QmlJS::AST;
using namespace QmlJSTools;
@@ -578,7 +579,7 @@ QModelIndex QmlJSTextEditorWidget::outlineModelIndex()
return m_outlineModelIndex;
}
-Core::IEditor *QmlJSEditor::duplicate(QWidget *parent)
+IEditor *QmlJSEditor::duplicate(QWidget *parent)
{
QmlJSTextEditorWidget *newEditor = new QmlJSTextEditorWidget(parent);
newEditor->duplicateFrom(editorWidget());
@@ -586,15 +587,15 @@ Core::IEditor *QmlJSEditor::duplicate(QWidget *parent)
return newEditor->editor();
}
-Core::Id QmlJSEditor::id() const
+Id QmlJSEditor::id() const
{
- return Core::Id(Constants::C_QMLJSEDITOR_ID);
+ return Constants::C_QMLJSEDITOR_ID;
}
bool QmlJSEditor::open(QString *errorString, const QString &fileName, const QString &realFileName)
{
bool b = TextEditor::BaseTextEditor::open(errorString, fileName, realFileName);
- editorWidget()->setMimeType(Core::ICore::mimeDatabase()->findByFile(QFileInfo(fileName)).type());
+ editorWidget()->setMimeType(MimeDatabase::findByFile(QFileInfo(fileName)).type());
return b;
}
@@ -607,7 +608,7 @@ void QmlJSTextEditorWidget::reparseDocumentNow()
{
m_updateDocumentTimer->stop();
- const QString fileName = editorDocument()->fileName();
+ const QString fileName = editorDocument()->filePath();
m_modelManager->updateSourceFiles(QStringList() << fileName, false);
}
@@ -649,7 +650,7 @@ static void appendExtraSelectionsForMessages(
void QmlJSTextEditorWidget::onDocumentUpdated(QmlJS::Document::Ptr doc)
{
- if (editorDocument()->fileName() != doc->fileName())
+ if (editorDocument()->filePath() != doc->fileName())
return;
if (doc->editorRevision() != editorRevision()) {
@@ -681,7 +682,7 @@ void QmlJSTextEditorWidget::onDocumentUpdated(QmlJS::Document::Ptr doc)
void QmlJSTextEditorWidget::modificationChanged(bool changed)
{
if (!changed && m_modelManager)
- m_modelManager->fileChangedOnDisk(editorDocument()->fileName());
+ m_modelManager->fileChangedOnDisk(editorDocument()->filePath());
}
void QmlJSTextEditorWidget::jumpToOutlineElement(int /*index*/)
@@ -692,9 +693,8 @@ void QmlJSTextEditorWidget::jumpToOutlineElement(int /*index*/)
if (!location.isValid())
return;
- Core::EditorManager *editorManager = Core::EditorManager::instance();
- editorManager->cutForwardNavigationHistory();
- editorManager->addCurrentPositionToNavigationHistory();
+ EditorManager::cutForwardNavigationHistory();
+ EditorManager::addCurrentPositionToNavigationHistory();
QTextCursor cursor = textCursor();
cursor.setPosition(location.offset);
@@ -980,12 +980,6 @@ void QmlJSTextEditorWidget::updateFileName()
void QmlJSTextEditorWidget::setFontSettings(const TextEditor::FontSettings &fs)
{
TextEditor::BaseTextEditorWidget::setFontSettings(fs);
- Highlighter *highlighter = qobject_cast<Highlighter*>(baseTextDocument()->syntaxHighlighter());
- if (!highlighter)
- return;
-
- highlighter->setFormats(fs.toTextCharFormats(highlighterFormatCategories()));
- highlighter->rehighlight();
m_occurrencesFormat = fs.toTextCharFormat(TextEditor::C_OCCURRENCES);
m_occurrencesUnusedFormat = fs.toTextCharFormat(TextEditor::C_OCCURRENCES_UNUSED);
@@ -1152,12 +1146,12 @@ TextEditor::BaseTextEditorWidget::Link QmlJSTextEditorWidget::findLinkAt(const Q
void QmlJSTextEditorWidget::findUsages()
{
- m_findReferences->findUsages(editorDocument()->fileName(), textCursor().position());
+ m_findReferences->findUsages(editorDocument()->filePath(), textCursor().position());
}
void QmlJSTextEditorWidget::renameUsages()
{
- m_findReferences->renameUsages(editorDocument()->fileName(), textCursor().position());
+ m_findReferences->renameUsages(editorDocument()->filePath(), textCursor().position());
}
void QmlJSTextEditorWidget::showContextPane()
@@ -1214,7 +1208,7 @@ void QmlJSTextEditorWidget::contextMenuEvent(QContextMenuEvent *e)
refactoringMenu->setEnabled(!refactoringMenu->isEmpty());
- if (Core::ActionContainer *mcontext = Core::ActionManager::actionContainer(Constants::M_CONTEXT)) {
+ if (ActionContainer *mcontext = ActionManager::actionContainer(Constants::M_CONTEXT)) {
QMenu *contextMenu = mcontext->menu();
foreach (QAction *action, contextMenu->actions()) {
menu->addAction(action);
@@ -1300,7 +1294,7 @@ void QmlJSTextEditorWidget::updateSemanticInfo()
return;
// Save time by not doing it for non-active editors.
- if (Core::EditorManager::currentEditor() != editor())
+ if (EditorManager::currentEditor() != editor())
return;
m_updateSemanticInfoTimer->start();
@@ -1349,7 +1343,7 @@ void QmlJSTextEditorWidget::acceptNewSemanticInfo(const SemanticInfo &semanticIn
// update outline
m_updateOutlineTimer->start();
- if (Core::EditorManager::currentEditor() == editor())
+ if (EditorManager::currentEditor() == editor())
m_semanticHighlighter->rerun(m_semanticInfo);
emit semanticInfoUpdated();
@@ -1429,7 +1423,7 @@ TextEditor::IAssistInterface *QmlJSTextEditorWidget::createAssistInterface(
if (assistKind == TextEditor::Completion) {
return new QmlJSCompletionAssistInterface(document(),
position(),
- editor()->document()->fileName(),
+ editor()->document()->filePath(),
reason,
m_semanticInfo);
} else if (assistKind == TextEditor::QuickFix) {
diff --git a/src/plugins/qmljseditor/qmljseditor.pro b/src/plugins/qmljseditor/qmljseditor.pro
index 9a40aa33ea..6d80ea429c 100644
--- a/src/plugins/qmljseditor/qmljseditor.pro
+++ b/src/plugins/qmljseditor/qmljseditor.pro
@@ -13,6 +13,7 @@ HEADERS += \
qmlexpressionundercursor.h \
qmlfilewizard.h \
qmljshighlighter.h \
+ qmljshighlighterfactory.h \
qmljshoverhandler.h \
qmljspreviewrunner.h \
qmljscomponentfromobjectdef.h \
@@ -43,6 +44,7 @@ SOURCES += \
qmlexpressionundercursor.cpp \
qmlfilewizard.cpp \
qmljshighlighter.cpp \
+ qmljshighlighterfactory.cpp \
qmljshoverhandler.cpp \
qmljspreviewrunner.cpp \
qmljscomponentfromobjectdef.cpp \
diff --git a/src/plugins/qmljseditor/qmljseditor.qbs b/src/plugins/qmljseditor/qmljseditor.qbs
index 72c9294c14..5f460b0ce1 100644
--- a/src/plugins/qmljseditor/qmljseditor.qbs
+++ b/src/plugins/qmljseditor/qmljseditor.qbs
@@ -47,6 +47,8 @@ QtcPlugin {
"qmljsfindreferences.h",
"qmljshighlighter.cpp",
"qmljshighlighter.h",
+ "qmljshighlighterfactory.cpp",
+ "qmljshighlighterfactory.h",
"qmljshoverhandler.cpp",
"qmljshoverhandler.h",
"qmljsoutline.cpp",
diff --git a/src/plugins/qmljseditor/qmljseditoreditable.cpp b/src/plugins/qmljseditor/qmljseditoreditable.cpp
index 0bbe3fd243..f30b3426f5 100644
--- a/src/plugins/qmljseditor/qmljseditoreditable.cpp
+++ b/src/plugins/qmljseditor/qmljseditoreditable.cpp
@@ -30,6 +30,7 @@
#include "qmljseditoreditable.h"
#include "qmljseditor.h"
#include "qmljseditorconstants.h"
+#include "qmljscompletionassist.h"
#include <qmljstools/qmljstoolsconstants.h>
#include <texteditor/texteditorconstants.h>
@@ -41,6 +42,8 @@
#include <coreplugin/modemanager.h>
#include <coreplugin/coreconstants.h>
+#include <extensionsystem/pluginmanager.h>
+
namespace QmlJSEditor {
QmlJSEditor::QmlJSEditor(QmlJSTextEditorWidget *editor)
@@ -60,16 +63,14 @@ bool QmlJSEditor::isDesignModePreferred() const
return false;
}
-void QmlJSEditor::setTextCodec(QTextCodec *codec, TextCodecReason reason)
+const Utils::CommentDefinition *QmlJSEditor::commentDefinition() const
{
- if (reason != TextCodecOtherReason) // qml is defined to be utf8
- return;
- editorWidget()->setTextCodec(codec);
+ return &m_commentDefinition;
}
-const Utils::CommentDefinition *QmlJSEditor::commentDefinition() const
+TextEditor::CompletionAssistProvider *QmlJSEditor::completionAssistProvider()
{
- return &m_commentDefinition;
+ return ExtensionSystem::PluginManager::getObject<Internal::QmlJSCompletionAssistProvider>();
}
} // namespace QmlJSEditor
diff --git a/src/plugins/qmljseditor/qmljseditoreditable.h b/src/plugins/qmljseditor/qmljseditoreditable.h
index 7490e87177..874e2cf4cf 100644
--- a/src/plugins/qmljseditor/qmljseditoreditable.h
+++ b/src/plugins/qmljseditor/qmljseditoreditable.h
@@ -47,12 +47,12 @@ public:
bool duplicateSupported() const { return true; }
Core::IEditor *duplicate(QWidget *parent);
Core::Id id() const;
- bool isTemporary() const { return false; }
bool open(QString *errorString, const QString &fileName, const QString &realFileName);
bool isDesignModePreferred() const;
- void setTextCodec(QTextCodec *codec, TextCodecReason = TextCodecOtherReason);
const Utils::CommentDefinition *commentDefinition() const;
+
+ TextEditor::CompletionAssistProvider *completionAssistProvider();
private:
Utils::CommentDefinition m_commentDefinition;
};
diff --git a/src/plugins/qmljseditor/qmljseditorfactory.cpp b/src/plugins/qmljseditor/qmljseditorfactory.cpp
index 56f8066170..4a2efa6053 100644
--- a/src/plugins/qmljseditor/qmljseditorfactory.cpp
+++ b/src/plugins/qmljseditor/qmljseditorfactory.cpp
@@ -35,19 +35,7 @@
#include <qmljstools/qmljstoolsconstants.h>
-#include <extensionsystem/pluginmanager.h>
-#include <extensionsystem/pluginspec.h>
-
-#include <coreplugin/icore.h>
-#include <coreplugin/infobar.h>
-#include <coreplugin/editormanager/editormanager.h>
-
#include <QCoreApplication>
-#include <QFileInfo>
-#include <QDebug>
-#include <QSettings>
-#include <QMessageBox>
-#include <QPushButton>
namespace QmlJSEditor {
namespace Internal {
@@ -55,24 +43,15 @@ namespace Internal {
QmlJSEditorFactory::QmlJSEditorFactory(QObject *parent)
: Core::IEditorFactory(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)
- ;
-}
-
-Core::Id QmlJSEditorFactory::id() const
-{
- return Core::Id(Constants::C_QMLJSEDITOR_ID);
-}
+ setId(Constants::C_QMLJSEDITOR_ID);
+ setDisplayName(qApp->translate("OpenWith::Editors", Constants::C_QMLJSEDITOR_DISPLAY_NAME));
-QString QmlJSEditorFactory::displayName() const
-{
- return qApp->translate("OpenWith::Editors", Constants::C_QMLJSEDITOR_DISPLAY_NAME);
+ addMimeType(QmlJSTools::Constants::QML_MIMETYPE);
+ addMimeType(QmlJSTools::Constants::QMLPROJECT_MIMETYPE);
+ addMimeType(QmlJSTools::Constants::QBS_MIMETYPE);
+ addMimeType(QmlJSTools::Constants::QMLTYPES_MIMETYPE);
+ addMimeType(QmlJSTools::Constants::JS_MIMETYPE);
+ addMimeType(QmlJSTools::Constants::JSON_MIMETYPE);
}
Core::IEditor *QmlJSEditorFactory::createEditor(QWidget *parent)
@@ -82,10 +61,5 @@ Core::IEditor *QmlJSEditorFactory::createEditor(QWidget *parent)
return rc->editor();
}
-QStringList QmlJSEditorFactory::mimeTypes() const
-{
- return m_mimeTypes;
-}
-
} // namespace Internal
} // namespace QmlJSEditor
diff --git a/src/plugins/qmljseditor/qmljseditorfactory.h b/src/plugins/qmljseditor/qmljseditorfactory.h
index ed91e33cd2..79d4b3cada 100644
--- a/src/plugins/qmljseditor/qmljseditorfactory.h
+++ b/src/plugins/qmljseditor/qmljseditorfactory.h
@@ -32,8 +32,6 @@
#include <coreplugin/editormanager/ieditorfactory.h>
-#include <QStringList>
-
namespace QmlJSEditor {
namespace Internal {
@@ -44,14 +42,7 @@ class QmlJSEditorFactory : public Core::IEditorFactory
public:
QmlJSEditorFactory(QObject *parent);
- // IEditorFactory
- QStringList mimeTypes() const;
- Core::Id id() const;
- QString displayName() const;
Core::IEditor *createEditor(QWidget *parent);
-
-private:
- QStringList m_mimeTypes;
};
} // namespace Internal
diff --git a/src/plugins/qmljseditor/qmljseditorplugin.cpp b/src/plugins/qmljseditor/qmljseditorplugin.cpp
index bf3de64696..0bc0ffdba0 100644
--- a/src/plugins/qmljseditor/qmljseditorplugin.cpp
+++ b/src/plugins/qmljseditor/qmljseditorplugin.cpp
@@ -43,6 +43,7 @@
#include "quicktoolbarsettingspage.h"
#include "qmljscompletionassist.h"
#include "qmljsquickfixassist.h"
+#include "qmljshighlighterfactory.h"
#include <qmljs/qmljsicons.h>
#include <qmljs/qmljsmodelmanagerinterface.h>
@@ -51,8 +52,8 @@
#include <qmldesigner/qmldesignerconstants.h>
-#include <coreplugin/icore.h>
#include <coreplugin/coreconstants.h>
+#include <coreplugin/icore.h>
#include <coreplugin/id.h>
#include <coreplugin/fileiconprovider.h>
#include <coreplugin/actionmanager/actionmanager.h>
@@ -60,7 +61,6 @@
#include <coreplugin/actionmanager/command.h>
#include <coreplugin/editormanager/editormanager.h>
#include <projectexplorer/taskhub.h>
-#include <projectexplorer/projectexplorer.h>
#include <texteditor/texteditorconstants.h>
#include <texteditor/texteditorsettings.h>
#include <texteditor/textfilewizard.h>
@@ -79,6 +79,7 @@
using namespace QmlJSEditor::Constants;
using namespace ProjectExplorer;
+using namespace Core;
enum {
QUICKFIX_INTERVAL = 20
@@ -99,8 +100,8 @@ QmlJSEditorPlugin::QmlJSEditorPlugin() :
m_reformatFileAction(0),
m_currentEditor(0),
m_jsonManager(new Utils::JsonSchemaManager(
- QStringList() << Core::ICore::instance()->userResourcePath() + QLatin1String("/json/")
- << Core::ICore::instance()->resourcePath() + QLatin1String("/json/")))
+ QStringList() << Core::ICore::userResourcePath() + QLatin1String("/json/")
+ << Core::ICore::resourcePath() + QLatin1String("/json/")))
{
m_instance = this;
}
@@ -116,6 +117,7 @@ bool QmlJSEditorPlugin::initialize(const QStringList & /*arguments*/, QString *e
{
m_modelManager = QmlJS::ModelManagerInterface::instance();
addAutoReleasedObject(new QmlJSSnippetProvider);
+ addAutoReleasedObject(new QmlJSHighlighterFactory);
// QML task updating manager
m_qmlTaskManager = new QmlTaskManager;
@@ -136,30 +138,32 @@ bool QmlJSEditorPlugin::initialize(const QStringList & /*arguments*/, QString *e
m_editor = new QmlJSEditorFactory(this);
addObject(m_editor);
- QObject *core = Core::ICore::instance();
- Core::BaseFileWizardParameters qml1WizardParameters(Core::IWizard::FileWizard);
- qml1WizardParameters.setCategory(QLatin1String(Core::Constants::WIZARD_CATEGORY_QT));
- qml1WizardParameters.setDisplayCategory(QCoreApplication::translate("QmlJsEditor", Core::Constants::WIZARD_TR_CATEGORY_QT));
- qml1WizardParameters.setDescription(tr("Creates a QML file with boilerplate code, starting with \"import QtQuick 1.1\"."));
- qml1WizardParameters.setDisplayName(tr("QML File (Qt Quick 1)"));
- qml1WizardParameters.setId(QLatin1String(Constants::WIZARD_QML1FILE));
- addAutoReleasedObject(new QmlFileWizard(qml1WizardParameters, core));
-
- Core::BaseFileWizardParameters qml2WizardParameters(Core::IWizard::FileWizard);
- qml2WizardParameters.setCategory(QLatin1String(Core::Constants::WIZARD_CATEGORY_QT));
- qml2WizardParameters.setDisplayCategory(QCoreApplication::translate("QmlJsEditor", Core::Constants::WIZARD_TR_CATEGORY_QT));
- qml2WizardParameters.setDescription(tr("Creates a QML file with boilerplate code, starting with \"import QtQuick 2.0\"."));
- qml2WizardParameters.setDisplayName(tr("QML File (Qt Quick 2)"));
- qml2WizardParameters.setId(QLatin1String(Constants::WIZARD_QML2FILE));
- addAutoReleasedObject(new QmlFileWizard(qml2WizardParameters, core));
-
- Core::BaseFileWizardParameters jsWizardParameters(Core::IWizard::FileWizard);
- jsWizardParameters.setCategory(QLatin1String(Core::Constants::WIZARD_CATEGORY_QT));
- jsWizardParameters.setDisplayCategory(QCoreApplication::translate("QmlJsEditor", Core::Constants::WIZARD_TR_CATEGORY_QT));
- jsWizardParameters.setDescription(tr("Creates a JavaScript file."));
- jsWizardParameters.setDisplayName(tr("JS File"));
- jsWizardParameters.setId(QLatin1String("Z.Js"));
- addAutoReleasedObject(new JsFileWizard(jsWizardParameters, core));
+ IWizard *wizard = new QmlFileWizard;
+ wizard->setWizardKind(Core::IWizard::FileWizard);
+ wizard->setCategory(QLatin1String(Core::Constants::WIZARD_CATEGORY_QT));
+ wizard->setDisplayCategory(QCoreApplication::translate("QmlJsEditor", Core::Constants::WIZARD_TR_CATEGORY_QT));
+ wizard->setDescription(tr("Creates a QML file with boilerplate code, starting with \"import QtQuick 1.1\"."));
+ wizard->setDisplayName(tr("QML File (Qt Quick 1)"));
+ wizard->setId(QLatin1String(Constants::WIZARD_QML1FILE));
+ addAutoReleasedObject(wizard);
+
+ wizard = new QmlFileWizard;
+ wizard->setWizardKind(Core::IWizard::FileWizard);
+ wizard->setCategory(QLatin1String(Core::Constants::WIZARD_CATEGORY_QT));
+ wizard->setDisplayCategory(QCoreApplication::translate("QmlJsEditor", Core::Constants::WIZARD_TR_CATEGORY_QT));
+ wizard->setDescription(tr("Creates a QML file with boilerplate code, starting with \"import QtQuick 2.0\"."));
+ wizard->setDisplayName(tr("QML File (Qt Quick 2)"));
+ wizard->setId(QLatin1String(Constants::WIZARD_QML2FILE));
+ addAutoReleasedObject(wizard);
+
+ wizard = new JsFileWizard;
+ wizard->setWizardKind(Core::IWizard::FileWizard);
+ wizard->setCategory(QLatin1String(Core::Constants::WIZARD_CATEGORY_QT));
+ wizard->setDisplayCategory(QCoreApplication::translate("QmlJsEditor", Core::Constants::WIZARD_TR_CATEGORY_QT));
+ wizard->setDescription(tr("Creates a JavaScript file."));
+ wizard->setDisplayName(tr("JS File"));
+ wizard->setId(QLatin1String("Z.Js"));
+ addAutoReleasedObject(wizard);
m_actionHandler = new TextEditor::TextEditorActionHandler(Constants::C_QMLJSEDITOR_ID,
TextEditor::TextEditorActionHandler::Format
@@ -231,8 +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")), QLatin1String("qml"));
+ Core::FileIconProvider::registerIconOverlayForSuffix(":/qmljseditor/images/qmlfile.png", "qml");
registerQuickFixes(this);
@@ -241,16 +244,15 @@ bool QmlJSEditorPlugin::initialize(const QStringList & /*arguments*/, QString *e
addAutoReleasedObject(new QuickToolBar);
addAutoReleasedObject(new Internal::QuickToolBarSettingsPage);
- connect(Core::ICore::editorManager(), SIGNAL(currentEditorChanged(Core::IEditor*)), SLOT(currentEditorChanged(Core::IEditor*)));
+ connect(Core::EditorManager::instance(), SIGNAL(currentEditorChanged(Core::IEditor*)), SLOT(currentEditorChanged(Core::IEditor*)));
return true;
}
void QmlJSEditorPlugin::extensionsInitialized()
{
- TaskHub *taskHub = ProjectExplorerPlugin::instance()->taskHub();
- taskHub->addCategory(Constants::TASK_CATEGORY_QML, tr("QML"));
- taskHub->addCategory(Constants::TASK_CATEGORY_QML_ANALYSIS, tr("QML Analysis"), false);
+ TaskHub::addCategory(Constants::TASK_CATEGORY_QML, tr("QML"));
+ TaskHub::addCategory(Constants::TASK_CATEGORY_QML_ANALYSIS, tr("QML Analysis"), false);
}
ExtensionSystem::IPlugin::ShutdownFlag QmlJSEditorPlugin::aboutToShutdown()
@@ -267,7 +269,7 @@ void QmlJSEditorPlugin::initializeEditor(QmlJSTextEditorWidget *editor)
m_actionHandler->setupActions(editor);
editor->setLanguageSettingsId(QmlJSTools::Constants::QML_JS_SETTINGS_ID);
- TextEditor::TextEditorSettings::instance()->initializeEditor(editor);
+ TextEditor::TextEditorSettings::initializeEditor(editor);
}
Utils::JsonSchemaManager *QmlJSEditorPlugin::jsonManager() const
@@ -348,9 +350,8 @@ void QmlJSEditorPlugin::currentEditorChanged(Core::IEditor *editor)
void QmlJSEditorPlugin::runSemanticScan()
{
m_qmlTaskManager->updateSemanticMessagesNow();
- TaskHub *hub = ProjectExplorerPlugin::instance()->taskHub();
- hub->setCategoryVisibility(Constants::TASK_CATEGORY_QML_ANALYSIS, true);
- hub->requestPopup();
+ TaskHub::setCategoryVisibility(Constants::TASK_CATEGORY_QML_ANALYSIS, true);
+ TaskHub::requestPopup();
}
void QmlJSEditorPlugin::checkCurrentEditorSemanticInfoUpToDate()
diff --git a/src/plugins/qmljseditor/qmljsfindreferences.cpp b/src/plugins/qmljseditor/qmljsfindreferences.cpp
index af0d7b461b..11e22d5028 100644
--- a/src/plugins/qmljseditor/qmljsfindreferences.cpp
+++ b/src/plugins/qmljseditor/qmljsfindreferences.cpp
@@ -62,6 +62,7 @@
#include <functional>
+using namespace Core;
using namespace QmlJS;
using namespace QmlJS::AST;
using namespace QmlJSEditor;
@@ -937,12 +938,11 @@ void FindReferences::displayResults(int first, int last)
this, SLOT(openEditor(Find::SearchResultItem)));
connect(m_currentSearch, SIGNAL(cancelled()), this, SLOT(cancel()));
connect(m_currentSearch, SIGNAL(paused(bool)), this, SLOT(setPaused(bool)));
- Find::SearchResultWindow::instance()->popup(Core::IOutputPane::Flags(Core::IOutputPane::ModeSwitch | Core::IOutputPane::WithFocus));
+ Find::SearchResultWindow::instance()->popup(IOutputPane::Flags(IOutputPane::ModeSwitch | IOutputPane::WithFocus));
- Core::ProgressManager *progressManager = Core::ICore::progressManager();
- Core::FutureProgress *progress = progressManager->addTask(
+ FutureProgress *progress = ProgressManager::addTask(
m_watcher.future(), tr("Searching"),
- QLatin1String(QmlJSEditor::Constants::TASK_SEARCH));
+ QmlJSEditor::Constants::TASK_SEARCH);
connect(progress, SIGNAL(clicked()), m_currentSearch, SLOT(popup()));
++first;
@@ -984,10 +984,10 @@ void FindReferences::setPaused(bool paused)
void FindReferences::openEditor(const Find::SearchResultItem &item)
{
if (item.path.size() > 0) {
- Core::EditorManager::openEditorAt(QDir::fromNativeSeparators(item.path.first()),
+ EditorManager::openEditorAt(QDir::fromNativeSeparators(item.path.first()),
item.lineNumber, item.textMarkPos);
} else {
- Core::EditorManager::openEditor(QDir::fromNativeSeparators(item.text));
+ EditorManager::openEditor(QDir::fromNativeSeparators(item.text));
}
}
@@ -998,9 +998,9 @@ void FindReferences::onReplaceButtonClicked(const QString &text, const QList<Fin
// files that are opened in an editor are changed, but not saved
QStringList changedOnDisk;
QStringList changedUnsavedEditors;
- Core::EditorManager *editorManager = Core::EditorManager::instance();
+ DocumentModel *documentModel = EditorManager::documentModel();
foreach (const QString &fileName, fileNames) {
- if (editorManager->editorsForFileName(fileName).isEmpty())
+ if (documentModel->documentForFilePath(fileName))
changedOnDisk += fileName;
else
changedUnsavedEditors += fileName;
diff --git a/src/plugins/qmljseditor/qmljsfindreferences.h b/src/plugins/qmljseditor/qmljsfindreferences.h
index 779724e603..587ea58ab7 100644
--- a/src/plugins/qmljseditor/qmljsfindreferences.h
+++ b/src/plugins/qmljseditor/qmljsfindreferences.h
@@ -41,8 +41,8 @@
QT_FORWARD_DECLARE_CLASS(QTimer)
namespace Find {
- struct SearchResultItem;
- class SearchResult;
+class SearchResultItem;
+class SearchResult;
} // namespace Find
namespace QmlJSEditor {
diff --git a/src/plugins/qmljseditor/qmljshighlighter.cpp b/src/plugins/qmljseditor/qmljshighlighter.cpp
index f10332d659..fae399cc43 100644
--- a/src/plugins/qmljseditor/qmljshighlighter.cpp
+++ b/src/plugins/qmljseditor/qmljshighlighter.cpp
@@ -41,11 +41,22 @@ using namespace QmlJS;
Highlighter::Highlighter(QTextDocument *parent)
: TextEditor::SyntaxHighlighter(parent),
m_qmlEnabled(true),
+ m_braceDepth(0),
+ m_foldingIndent(0),
m_inMultilineComment(false)
{
m_currentBlockParentheses.reserve(20);
- m_braceDepth = 0;
- m_foldingIndent = 0;
+ static QVector<TextEditor::TextStyle> categories;
+ if (categories.isEmpty()) {
+ categories << TextEditor::C_NUMBER
+ << TextEditor::C_STRING
+ << TextEditor::C_TYPE
+ << TextEditor::C_KEYWORD
+ << TextEditor::C_FIELD
+ << TextEditor::C_COMMENT
+ << TextEditor::C_VISUAL_WHITESPACE;
+ }
+ setTextFormatCategories(categories);
}
Highlighter::~Highlighter()
@@ -62,12 +73,6 @@ void Highlighter::setQmlEnabled(bool qmlEnabled)
m_qmlEnabled = qmlEnabled;
}
-void Highlighter::setFormats(const QVector<QTextCharFormat> &formats)
-{
- QTC_ASSERT(formats.size() == NumFormats, return);
- qCopy(formats.begin(), formats.end(), m_formats);
-}
-
void Highlighter::highlightBlock(const QString &text)
{
const QList<Token> tokens = m_scanner(text, onBlockStart());
@@ -78,11 +83,11 @@ void Highlighter::highlightBlock(const QString &text)
switch (token.kind) {
case Token::Keyword:
- setFormat(token.offset, token.length, m_formats[KeywordFormat]);
+ setFormat(token.offset, token.length, formatForCategory(KeywordFormat));
break;
case Token::String:
- setFormat(token.offset, token.length, m_formats[StringFormat]);
+ setFormat(token.offset, token.length, formatForCategory(StringFormat));
break;
case Token::Comment:
@@ -95,11 +100,11 @@ void Highlighter::highlightBlock(const QString &text)
onOpeningParenthesis(QLatin1Char('+'), token.offset, index == 0);
m_inMultilineComment = true;
}
- setFormat(token.offset, token.length, m_formats[CommentFormat]);
+ setFormat(token.offset, token.length, formatForCategory(CommentFormat));
break;
case Token::RegExp:
- setFormat(token.offset, token.length, m_formats[StringFormat]);
+ setFormat(token.offset, token.length, formatForCategory(StringFormat));
break;
case Token::LeftParenthesis:
@@ -136,7 +141,7 @@ void Highlighter::highlightBlock(const QString &text)
// check the previous token
if (index == 0 || tokens.at(index - 1).isNot(Token::Dot)) {
if (index + 1 == tokens.size() || tokens.at(index + 1).isNot(Token::Colon)) {
- setFormat(token.offset, token.length, m_formats[KeywordFormat]);
+ setFormat(token.offset, token.length, formatForCategory(KeywordFormat));
break;
}
}
@@ -144,7 +149,7 @@ void Highlighter::highlightBlock(const QString &text)
const Token &previousToken = tokens.at(index - 1);
if (previousToken.is(Token::Identifier) && text.at(previousToken.offset) == QLatin1Char('p')
&& text.midRef(previousToken.offset, previousToken.length) == QLatin1String("property")) {
- setFormat(token.offset, token.length, m_formats[KeywordFormat]);
+ setFormat(token.offset, token.length, formatForCategory(KeywordFormat));
break;
}
}
@@ -163,7 +168,7 @@ void Highlighter::highlightBlock(const QString &text)
int previousTokenEnd = 0;
for (int index = 0; index < tokens.size(); ++index) {
const Token &token = tokens.at(index);
- setFormat(previousTokenEnd, token.begin() - previousTokenEnd, m_formats[VisualWhitespace]);
+ setFormat(previousTokenEnd, token.begin() - previousTokenEnd, formatForCategory(VisualWhitespace));
switch (token.kind) {
case Token::Comment:
@@ -177,7 +182,7 @@ void Highlighter::highlightBlock(const QString &text)
do {
++i;
} while (i < e && text.at(i).isSpace());
- setFormat(start, i - start, m_formats[VisualWhitespace]);
+ setFormat(start, i - start, formatForCategory(VisualWhitespace));
} else {
++i;
}
@@ -191,7 +196,7 @@ void Highlighter::highlightBlock(const QString &text)
previousTokenEnd = token.end();
}
- setFormat(previousTokenEnd, text.length() - previousTokenEnd, m_formats[VisualWhitespace]);
+ setFormat(previousTokenEnd, text.length() - previousTokenEnd, formatForCategory(VisualWhitespace));
setCurrentBlockState(m_scanner.state());
onBlockEnd(m_scanner.state());
diff --git a/src/plugins/qmljseditor/qmljshighlighter.h b/src/plugins/qmljseditor/qmljshighlighter.h
index badcfc05f4..b81f168721 100644
--- a/src/plugins/qmljseditor/qmljshighlighter.h
+++ b/src/plugins/qmljseditor/qmljshighlighter.h
@@ -34,13 +34,8 @@
#include <qmljs/qmljsscanner.h>
-#include <QVector>
-#include <QSet>
-#include <QSyntaxHighlighter>
-
#include <texteditor/basetextdocumentlayout.h>
#include <texteditor/syntaxhighlighter.h>
-#include <texteditor/texteditorconstants.h>
namespace QmlJSEditor {
@@ -65,7 +60,6 @@ public:
bool isQmlEnabled() const;
void setQmlEnabled(bool duiEnabled);
- void setFormats(const QVector<QTextCharFormat> &formats);
protected:
virtual void highlightBlock(const QString &text);
@@ -92,8 +86,6 @@ private:
QmlJS::Scanner m_scanner;
Parentheses m_currentBlockParentheses;
-
- QTextCharFormat m_formats[NumFormats];
};
} // namespace QmlJSEditor
diff --git a/src/plugins/qmljseditor/qmljshighlighterfactory.cpp b/src/plugins/qmljseditor/qmljshighlighterfactory.cpp
new file mode 100644
index 0000000000..576d419f30
--- /dev/null
+++ b/src/plugins/qmljseditor/qmljshighlighterfactory.cpp
@@ -0,0 +1,51 @@
+/****************************************************************************
+**
+** 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 "qmljshighlighterfactory.h"
+#include "qmljseditorconstants.h"
+#include "qmljshighlighter.h"
+#include <qmljstools/qmljstoolsconstants.h>
+
+using namespace QmlJSEditor::Internal;
+
+QmlJSHighlighterFactory::QmlJSHighlighterFactory()
+{
+ setId(Constants::C_QMLJSEDITOR_ID);
+ addMimeType(QmlJSTools::Constants::QML_MIMETYPE);
+ addMimeType(QmlJSTools::Constants::QMLPROJECT_MIMETYPE);
+ addMimeType(QmlJSTools::Constants::QBS_MIMETYPE);
+ addMimeType(QmlJSTools::Constants::QMLTYPES_MIMETYPE);
+ addMimeType(QmlJSTools::Constants::JS_MIMETYPE);
+ addMimeType(QmlJSTools::Constants::JSON_MIMETYPE);
+}
+
+TextEditor::SyntaxHighlighter *QmlJSHighlighterFactory::createHighlighter() const
+{
+ return new Highlighter;
+}
diff --git a/src/plugins/qmljseditor/qmljshighlighterfactory.h b/src/plugins/qmljseditor/qmljshighlighterfactory.h
new file mode 100644
index 0000000000..ab768f8a0d
--- /dev/null
+++ b/src/plugins/qmljseditor/qmljshighlighterfactory.h
@@ -0,0 +1,51 @@
+/****************************************************************************
+**
+** 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 QMLJSHIGHLIGHTERFACTORY_H
+#define QMLJSHIGHLIGHTERFACTORY_H
+
+#include <texteditor/ihighlighterfactory.h>
+
+namespace QmlJSEditor {
+namespace Internal {
+
+class QmlJSHighlighterFactory : public TextEditor::IHighlighterFactory
+{
+ Q_OBJECT
+
+public:
+ QmlJSHighlighterFactory();
+
+ virtual TextEditor::SyntaxHighlighter *createHighlighter() const;
+};
+
+} // namespace Internal
+} // namespace QmlJSEditor
+
+#endif // QMLJSHIGHLIGHTERFACTORY_H
diff --git a/src/plugins/qmljseditor/qmljshoverhandler.cpp b/src/plugins/qmljseditor/qmljshoverhandler.cpp
index 6f91d6b0f3..472cff9c26 100644
--- a/src/plugins/qmljseditor/qmljshoverhandler.cpp
+++ b/src/plugins/qmljseditor/qmljshoverhandler.cpp
@@ -160,21 +160,21 @@ bool HoverHandler::setQmlTypeHelp(const ScopeChain &scopeChain, const Document::
helpIdPieces.prepend(moduleName);
helpIdPieces.prepend(QLatin1String("QML"));
helpId = helpIdPieces.join(QLatin1String("."));
- if (!Core::HelpManager::instance()->linksForIdentifier(helpId).isEmpty())
+ if (!HelpManager::linksForIdentifier(helpId).isEmpty())
break;
if (helpIdPieces.size() > 3) {
QString lm = helpIdPieces.value(2);
helpIdPieces.removeAt(2);
helpId = helpIdPieces.join(QLatin1String("."));
- if (!Core::HelpManager::instance()->linksForIdentifier(helpId).isEmpty())
+ if (!HelpManager::linksForIdentifier(helpId).isEmpty())
break;
helpIdPieces.replace(1, lm);
- if (!Core::HelpManager::instance()->linksForIdentifier(helpId).isEmpty())
+ if (!HelpManager::linksForIdentifier(helpId).isEmpty())
break;
}
helpIdPieces.removeAt(1);
helpId = helpIdPieces.join(QLatin1String("."));
- if (!Core::HelpManager::instance()->linksForIdentifier(helpId).isEmpty())
+ if (!HelpManager::linksForIdentifier(helpId).isEmpty())
break;
return false;
} while (0);
@@ -378,18 +378,11 @@ void HoverHandler::reset()
void HoverHandler::operateTooltip(TextEditor::ITextEditor *editor, const QPoint &point)
{
if (toolTip().isEmpty())
- Utils::ToolTip::instance()->hide();
- else {
- if (m_colorTip.isValid()) {
- Utils::ToolTip::instance()->show(point,
- Utils::ColorContent(m_colorTip),
- editor->widget());
- } else {
- Utils::ToolTip::instance()->show(point,
- Utils::TextContent(toolTip()),
- editor->widget());
- }
- }
+ Utils::ToolTip::hide();
+ else if (m_colorTip.isValid())
+ Utils::ToolTip::show(point, Utils::ColorContent(m_colorTip), editor->widget());
+ else
+ Utils::ToolTip::show(point, Utils::TextContent(toolTip()), editor->widget());
}
void HoverHandler::prettyPrintTooltip(const QmlJS::Value *value,
@@ -490,13 +483,13 @@ bool HoverHandler::setQmlHelpItem(const ScopeChain &scopeChain,
do {
helpId = QLatin1String("QML.") + moduleName + QLatin1Char('.') + className
+ QLatin1String("::") + name;
- if (!Core::HelpManager::instance()->linksForIdentifier(helpId).isEmpty())
+ if (!HelpManager::linksForIdentifier(helpId).isEmpty())
break;
helpId = QLatin1String("QML.") + className + QLatin1String("::") + name;
- if (!Core::HelpManager::instance()->linksForIdentifier(helpId).isEmpty())
+ if (!HelpManager::linksForIdentifier(helpId).isEmpty())
break;
helpId = className + QLatin1String("::") + name;
- if (!Core::HelpManager::instance()->linksForIdentifier(helpId).isEmpty())
+ if (!HelpManager::linksForIdentifier(helpId).isEmpty())
break;
helpId.clear();
} while (0);
diff --git a/src/plugins/qmljseditor/qmljsoutline.cpp b/src/plugins/qmljseditor/qmljsoutline.cpp
index 544f5419c7..d9d49853a2 100644
--- a/src/plugins/qmljseditor/qmljsoutline.cpp
+++ b/src/plugins/qmljseditor/qmljsoutline.cpp
@@ -217,9 +217,8 @@ void QmlJSOutlineWidget::updateTextCursor(const QModelIndex &index)
if (location.offset >= textLength)
return;
- Core::EditorManager *editorManager = Core::EditorManager::instance();
- editorManager->cutForwardNavigationHistory();
- editorManager->addCurrentPositionToNavigationHistory();
+ Core::EditorManager::cutForwardNavigationHistory();
+ Core::EditorManager::addCurrentPositionToNavigationHistory();
QTextCursor textCursor = m_editor->textCursor();
m_blockCursorSync = true;
diff --git a/src/plugins/qmljseditor/qmljsquickfix.cpp b/src/plugins/qmljseditor/qmljsquickfix.cpp
index 12828c7325..c05a090d6e 100644
--- a/src/plugins/qmljseditor/qmljsquickfix.cpp
+++ b/src/plugins/qmljseditor/qmljsquickfix.cpp
@@ -30,13 +30,13 @@
#include "qmljsquickfix.h"
#include "qmljscomponentfromobjectdef.h"
#include "qmljseditor.h"
-#include "qmljs/parser/qmljsast_p.h"
#include "qmljsquickfixassist.h"
#include <extensionsystem/iplugin.h>
#include <extensionsystem/pluginmanager.h>
#include <qmljs/qmljsmodelmanagerinterface.h>
+#include <qmljs/parser/qmljsast_p.h>
#include <QDebug>
diff --git a/src/plugins/qmljseditor/qmljsquickfixassist.cpp b/src/plugins/qmljseditor/qmljsquickfixassist.cpp
index 28757dafa5..fef38fadd4 100644
--- a/src/plugins/qmljseditor/qmljsquickfixassist.cpp
+++ b/src/plugins/qmljseditor/qmljsquickfixassist.cpp
@@ -48,7 +48,7 @@ using namespace Internal;
QmlJSQuickFixAssistInterface::QmlJSQuickFixAssistInterface(QmlJSTextEditorWidget *editor,
TextEditor::AssistReason reason)
: DefaultAssistInterface(editor->document(), editor->position(),
- editor->editorDocument()->fileName(), reason)
+ editor->editorDocument()->filePath(), reason)
, m_editor(editor)
, m_semanticInfo(editor->semanticInfo())
, m_currentFile(QmlJSRefactoringChanges::file(m_editor, m_semanticInfo.document))
diff --git a/src/plugins/qmljseditor/qmljssnippetprovider.cpp b/src/plugins/qmljseditor/qmljssnippetprovider.cpp
index 5253a12be5..026fef6199 100644
--- a/src/plugins/qmljseditor/qmljssnippetprovider.cpp
+++ b/src/plugins/qmljseditor/qmljssnippetprovider.cpp
@@ -34,7 +34,6 @@
#include "qmljseditorconstants.h"
#include <texteditor/texteditorsettings.h>
-#include <texteditor/fontsettings.h>
#include <texteditor/texteditorconstants.h>
#include <texteditor/snippets/snippeteditor.h>
@@ -65,10 +64,7 @@ QString QmlJSSnippetProvider::displayName() const
void QmlJSSnippetProvider::decorateEditor(TextEditor::SnippetEditorWidget *editor) const
{
- Highlighter *highlighter = new Highlighter;
- const TextEditor::FontSettings &fs = TextEditor::TextEditorSettings::instance()->fontSettings();
- highlighter->setFormats(fs.toTextCharFormats(QmlJSTextEditorWidget::highlighterFormatCategories()));
- editor->setSyntaxHighlighter(highlighter);
+ editor->setSyntaxHighlighter(new Highlighter);
editor->setIndenter(new Indenter);
editor->setAutoCompleter(new AutoCompleter);
}
diff --git a/src/plugins/qmljseditor/qmltaskmanager.cpp b/src/plugins/qmljseditor/qmltaskmanager.cpp
index 88efb0cb73..42f78bec19 100644
--- a/src/plugins/qmljseditor/qmltaskmanager.cpp
+++ b/src/plugins/qmljseditor/qmltaskmanager.cpp
@@ -51,11 +51,8 @@ namespace Internal {
QmlTaskManager::QmlTaskManager(QObject *parent) :
QObject(parent),
- m_taskHub(0),
m_updatingSemantic(false)
{
- m_taskHub = ProjectExplorer::ProjectExplorerPlugin::instance()->taskHub();
-
// displaying results incrementally leads to flickering
// connect(&m_messageCollector, SIGNAL(resultsReadyAt(int,int)),
// SLOT(displayResults(int,int)));
@@ -195,7 +192,7 @@ void QmlTaskManager::insertTask(const ProjectExplorer::Task &task)
QList<ProjectExplorer::Task> tasks = m_docsWithTasks.value(task.file.toString());
tasks.append(task);
m_docsWithTasks.insert(task.file.toString(), tasks);
- m_taskHub->addTask(task);
+ ProjectExplorer::TaskHub::addTask(task);
}
void QmlTaskManager::removeTasksForFile(const QString &fileName)
@@ -203,16 +200,16 @@ void QmlTaskManager::removeTasksForFile(const QString &fileName)
if (m_docsWithTasks.contains(fileName)) {
const QList<ProjectExplorer::Task> tasks = m_docsWithTasks.value(fileName);
foreach (const ProjectExplorer::Task &task, tasks)
- m_taskHub->removeTask(task);
+ ProjectExplorer::TaskHub::removeTask(task);
m_docsWithTasks.remove(fileName);
}
}
void QmlTaskManager::removeAllTasks(bool clearSemantic)
{
- m_taskHub->clearTasks(Constants::TASK_CATEGORY_QML);
+ ProjectExplorer::TaskHub::clearTasks(Constants::TASK_CATEGORY_QML);
if (clearSemantic)
- m_taskHub->clearTasks(Constants::TASK_CATEGORY_QML_ANALYSIS);
+ ProjectExplorer::TaskHub::clearTasks(Constants::TASK_CATEGORY_QML_ANALYSIS);
m_docsWithTasks.clear();
}
diff --git a/src/plugins/qmljseditor/qmltaskmanager.h b/src/plugins/qmljseditor/qmltaskmanager.h
index a03f193593..986a2e65f3 100644
--- a/src/plugins/qmljseditor/qmltaskmanager.h
+++ b/src/plugins/qmljseditor/qmltaskmanager.h
@@ -89,7 +89,6 @@ private:
bool updateSemantic);
private:
- ProjectExplorer::TaskHub *m_taskHub;
QHash<QString, QList<ProjectExplorer::Task> > m_docsWithTasks;
QFutureWatcher<FileErrorMessages> m_messageCollector;
QTimer m_updateDelay;
diff --git a/src/plugins/qmljseditor/quicktoolbar.cpp b/src/plugins/qmljseditor/quicktoolbar.cpp
index b3923574a4..f084a3020d 100644
--- a/src/plugins/qmljseditor/quicktoolbar.cpp
+++ b/src/plugins/qmljseditor/quicktoolbar.cpp
@@ -55,13 +55,6 @@ using namespace QmlEditorWidgets;
namespace QmlJSEditor {
-static inline QString textAt(const Document* doc,
- const SourceLocation &from,
- const SourceLocation &to)
-{
- return doc->source().mid(from.offset, to.end() - from.begin());
-}
-
static inline const ObjectValue * getPropertyChangesTarget(Node *node, const ScopeChain &scopeChain)
{
UiObjectInitializer *initializer = initializerOfObject(node);
diff --git a/src/plugins/qmljstools/QmlJSTools.pluginspec.in b/src/plugins/qmljstools/QmlJSTools.pluginspec.in
index 668476ff07..9e74e4fc1f 100644
--- a/src/plugins/qmljstools/QmlJSTools.pluginspec.in
+++ b/src/plugins/qmljstools/QmlJSTools.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"QmlJSTools\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"QmlJSTools\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/qmljstools/qmlconsoleitemmodel.h b/src/plugins/qmljstools/qmlconsoleitemmodel.h
index 4caf2409a4..87740971d7 100644
--- a/src/plugins/qmljstools/qmlconsoleitemmodel.h
+++ b/src/plugins/qmljstools/qmlconsoleitemmodel.h
@@ -58,8 +58,6 @@ public:
bool appendMessage(QmlJS::ConsoleItem::ItemType itemType, const QString &message,
int position = -1);
- QAbstractItemModel *model() { return this; }
-
int rowCount(const QModelIndex &parent = QModelIndex()) const;
int sizeOfFile(const QFont &font);
diff --git a/src/plugins/qmljstools/qmlconsoleview.cpp b/src/plugins/qmljstools/qmlconsoleview.cpp
index 872b4ae867..f74e858cd9 100644
--- a/src/plugins/qmljstools/qmlconsoleview.cpp
+++ b/src/plugins/qmljstools/qmlconsoleview.cpp
@@ -107,9 +107,9 @@ QmlConsoleView::QmlConsoleView(QWidget *parent) :
if (Utils::HostOsInfo::isAnyUnixHost() && !Utils::HostOsInfo::isMacHost()
&& baseName == QLatin1String("windows")) {
// Sometimes we get the standard windows 95 style as a fallback
- if (QStyleFactory::keys().contains(QLatin1String("Fusion")))
+ if (QStyleFactory::keys().contains(QLatin1String("Fusion"))) {
baseName = QLatin1String("fusion"); // Qt5
- else { // Qt4
+ } else { // Qt4
// e.g. if we are running on a KDE4 desktop
QByteArray desktopEnvironment = qgetenv("DESKTOP_SESSION");
if (desktopEnvironment == "kde")
diff --git a/src/plugins/qmljstools/qmljscodestylesettingspage.cpp b/src/plugins/qmljstools/qmljscodestylesettingspage.cpp
index bb1fbe755b..b0dcc8a60d 100644
--- a/src/plugins/qmljstools/qmljscodestylesettingspage.cpp
+++ b/src/plugins/qmljstools/qmljscodestylesettingspage.cpp
@@ -70,9 +70,8 @@ QmlJSCodeStylePreferencesWidget::QmlJSCodeStylePreferencesWidget(QWidget *parent
}
}
- TextEditor::TextEditorSettings *textEditorSettings = TextEditorSettings::instance();
- decorateEditor(textEditorSettings->fontSettings());
- connect(textEditorSettings, SIGNAL(fontSettingsChanged(TextEditor::FontSettings)),
+ decorateEditor(TextEditorSettings::fontSettings());
+ connect(TextEditorSettings::instance(), SIGNAL(fontSettingsChanged(TextEditor::FontSettings)),
this, SLOT(decorateEditor(TextEditor::FontSettings)));
setVisualizeWhitespace(true);
@@ -142,7 +141,7 @@ void QmlJSCodeStylePreferencesWidget::updatePreview()
const TextEditor::TabSettings &ts = m_preferences
? m_preferences->currentTabSettings()
- : TextEditorSettings::instance()->codeStyle()->tabSettings();
+ : TextEditorSettings::codeStyle()->tabSettings();
m_ui->previewTextEdit->setTabSettings(ts);
CreatorCodeFormatter formatter(ts);
formatter.invalidateCache(doc);
@@ -181,8 +180,7 @@ QWidget *QmlJSCodeStyleSettingsPage::createPage(QWidget *parent)
m_pageTabPreferences->setTabSettings(originalTabPreferences->tabSettings());
m_pageTabPreferences->setCurrentDelegate(originalTabPreferences->currentDelegate());
m_pageTabPreferences->setId(originalTabPreferences->id());
- TextEditorSettings *settings = TextEditorSettings::instance();
- m_widget = new CodeStyleEditor(settings->codeStyleFactory(QmlJSTools::Constants::QML_JS_SETTINGS_ID),
+ m_widget = new CodeStyleEditor(TextEditorSettings::codeStyleFactory(QmlJSTools::Constants::QML_JS_SETTINGS_ID),
m_pageTabPreferences, parent);
return m_widget;
diff --git a/src/plugins/qmljstools/qmljsfindexportedcpptypes.cpp b/src/plugins/qmljstools/qmljsfindexportedcpptypes.cpp
index 74078654db..0d2bd263f5 100644
--- a/src/plugins/qmljstools/qmljsfindexportedcpptypes.cpp
+++ b/src/plugins/qmljstools/qmljsfindexportedcpptypes.cpp
@@ -309,9 +309,8 @@ protected:
if (QString::fromUtf8(id->chars(), id->size()) != QLatin1String("QVariant"))
return ast;
return call->expression_list->value;
- }
// QVariant::fromValue(foo) -> foo
- else if (QualifiedNameAST *q = idExp->name->asQualifiedName()) {
+ } else if (QualifiedNameAST *q = idExp->name->asQualifiedName()) {
SimpleNameAST *simpleRhsName = q->unqualified_name->asSimpleName();
if (!simpleRhsName
|| !q->nested_name_specifier_list
diff --git a/src/plugins/qmljstools/qmljsfunctionfilter.cpp b/src/plugins/qmljstools/qmljsfunctionfilter.cpp
index 33c1eb9356..89b6c6e903 100644
--- a/src/plugins/qmljstools/qmljsfunctionfilter.cpp
+++ b/src/plugins/qmljstools/qmljsfunctionfilter.cpp
@@ -72,6 +72,7 @@ QList<Locator::FilterEntry> FunctionFilter::matchesFor(QFutureInterface<Locator:
if (!regexp.isValid())
return goodEntries;
bool hasWildcard = (entry.contains(asterisk) || entry.contains(QLatin1Char('?')));
+ const Qt::CaseSensitivity caseSensitivityForPrefix = caseSensitivity(entry);
QHashIterator<QString, QList<LocatorData::Entry> > it(m_data->entries());
while (it.hasNext()) {
@@ -91,7 +92,7 @@ QList<Locator::FilterEntry> FunctionFilter::matchesFor(QFutureInterface<Locator:
Locator::FilterEntry filterEntry(this, info.displayName, id/*, info.icon*/);
filterEntry.extraInfo = info.extraInfo;
- if (info.symbolName.startsWith(entry))
+ if (info.symbolName.startsWith(entry, caseSensitivityForPrefix))
betterEntries.append(filterEntry);
else
goodEntries.append(filterEntry);
diff --git a/src/plugins/qmljstools/qmljsmodelmanager.cpp b/src/plugins/qmljstools/qmljsmodelmanager.cpp
index d9e187d57e..a0bdef083c 100644
--- a/src/plugins/qmljstools/qmljsmodelmanager.cpp
+++ b/src/plugins/qmljstools/qmljsmodelmanager.cpp
@@ -39,7 +39,7 @@
#include <coreplugin/messagemanager.h>
#include <cpptools/cppmodelmanagerinterface.h>
#include <qmljs/qmljsbind.h>
-#include <texteditor/basetexteditor.h>
+#include <texteditor/basetextdocument.h>
#include <projectexplorer/buildconfiguration.h>
#include <projectexplorer/project.h>
#include <projectexplorer/projectexplorer.h>
@@ -55,6 +55,7 @@
#include <QFile>
#include <QFileInfo>
#include <utils/runextensions.h>
+#include <QTextDocument>
#include <QTextStream>
#include <QTimer>
#include <QRegExp>
@@ -62,6 +63,7 @@
#include <QDebug>
+using namespace Core;
using namespace QmlJS;
using namespace QmlJSTools;
using namespace QmlJSTools::Internal;
@@ -73,28 +75,26 @@ ModelManagerInterface::ProjectInfo QmlJSTools::defaultProjectInfoForProject(
ModelManagerInterface::ProjectInfo projectInfo(project);
ProjectExplorer::Target *activeTarget = 0;
if (project) {
- Core::MimeDatabase *db = Core::ICore::mimeDatabase();
- QList<Core::MimeGlobPattern> globs;
- QList<Core::MimeType> mimeTypes = db->mimeTypes();
- foreach (const Core::MimeType &mimeType, mimeTypes)
+ QList<MimeGlobPattern> globs;
+ foreach (const MimeType &mimeType, MimeDatabase::mimeTypes())
if (mimeType.type() == QLatin1String(Constants::QML_MIMETYPE)
|| mimeType.subClassesOf().contains(QLatin1String(Constants::QML_MIMETYPE)))
globs << mimeType.globPatterns();
if (globs.isEmpty()) {
- globs.append(Core::MimeGlobPattern(QLatin1String("*.qbs")));
- globs.append(Core::MimeGlobPattern(QLatin1String("*.qml")));
- globs.append(Core::MimeGlobPattern(QLatin1String("*.qmltypes")));
- globs.append(Core::MimeGlobPattern(QLatin1String("*.qmlproject")));
+ globs.append(MimeGlobPattern(QLatin1String("*.qbs")));
+ globs.append(MimeGlobPattern(QLatin1String("*.qml")));
+ globs.append(MimeGlobPattern(QLatin1String("*.qmltypes")));
+ globs.append(MimeGlobPattern(QLatin1String("*.qmlproject")));
}
foreach (const QString &filePath
, project->files(ProjectExplorer::Project::ExcludeGeneratedFiles))
- foreach (const Core::MimeGlobPattern &glob, globs)
+ foreach (const MimeGlobPattern &glob, globs)
if (glob.matches(filePath))
projectInfo.sourceFiles << filePath;
activeTarget = project->activeTarget();
}
ProjectExplorer::Kit *activeKit = activeTarget ? activeTarget->kit() :
- ProjectExplorer::KitManager::instance()->defaultKit();
+ ProjectExplorer::KitManager::defaultKit();
QtSupport::BaseQtVersion *qtVersion = QtSupport::QtKitInformation::qtVersion(activeKit);
bool preferDebugDump = false;
@@ -142,7 +142,7 @@ void QmlJSTools::setupProjectInfoQmlBundles(ModelManagerInterface::ProjectInfo &
activeTarget = projectInfo.project->activeTarget();
}
ProjectExplorer::Kit *activeKit = activeTarget
- ? activeTarget->kit() : ProjectExplorer::KitManager::instance()->defaultKit();
+ ? activeTarget->kit() : ProjectExplorer::KitManager::defaultKit();
QHash<QString, QString> replacements;
replacements.insert(QLatin1String("$(QT_INSTALL_IMPORTS)"), projectInfo.qtImportsPath);
replacements.insert(QLatin1String("$(QT_INSTALL_QML)"), projectInfo.qtQmlPath);
@@ -186,17 +186,16 @@ QmlJS::Document::Language QmlJSTools::languageOfFile(const QString &fileName)
QStringList jsonSuffixes(QLatin1String("json"));
QStringList qbsSuffixes(QLatin1String("qbs"));
- if (Core::ICore::instance()) {
- Core::MimeDatabase *db = Core::ICore::mimeDatabase();
- Core::MimeType jsSourceTy = db->findByType(QLatin1String(Constants::JS_MIMETYPE));
+ if (ICore::instance()) {
+ MimeType jsSourceTy = MimeDatabase::findByType(QLatin1String(Constants::JS_MIMETYPE));
mergeSuffixes(jsSuffixes, jsSourceTy.suffixes());
- Core::MimeType qmlSourceTy = db->findByType(QLatin1String(Constants::QML_MIMETYPE));
+ MimeType qmlSourceTy = MimeDatabase::findByType(QLatin1String(Constants::QML_MIMETYPE));
mergeSuffixes(qmlSuffixes, qmlSourceTy.suffixes());
- Core::MimeType qbsSourceTy = db->findByType(QLatin1String(Constants::QBS_MIMETYPE));
+ MimeType qbsSourceTy = MimeDatabase::findByType(QLatin1String(Constants::QBS_MIMETYPE));
mergeSuffixes(qbsSuffixes, qbsSourceTy.suffixes());
- Core::MimeType qmlProjectSourceTy = db->findByType(QLatin1String(Constants::QMLPROJECT_MIMETYPE));
+ MimeType qmlProjectSourceTy = MimeDatabase::findByType(QLatin1String(Constants::QMLPROJECT_MIMETYPE));
mergeSuffixes(qmlProjectSuffixes, qmlProjectSourceTy.suffixes());
- Core::MimeType jsonSourceTy = db->findByType(QLatin1String(Constants::JSON_MIMETYPE));
+ MimeType jsonSourceTy = MimeDatabase::findByType(QLatin1String(Constants::JSON_MIMETYPE));
mergeSuffixes(jsonSuffixes, jsonSourceTy.suffixes());
}
@@ -216,15 +215,14 @@ QmlJS::Document::Language QmlJSTools::languageOfFile(const QString &fileName)
QStringList QmlJSTools::qmlAndJsGlobPatterns()
{
QStringList pattern;
- if (Core::ICore::instance()) {
- Core::MimeDatabase *db = Core::ICore::mimeDatabase();
- Core::MimeType jsSourceTy = db->findByType(QLatin1String(Constants::JS_MIMETYPE));
- Core::MimeType qmlSourceTy = db->findByType(QLatin1String(Constants::QML_MIMETYPE));
+ if (ICore::instance()) {
+ MimeType jsSourceTy = MimeDatabase::findByType(QLatin1String(Constants::JS_MIMETYPE));
+ MimeType qmlSourceTy = MimeDatabase::findByType(QLatin1String(Constants::QML_MIMETYPE));
QStringList pattern;
- foreach (const Core::MimeGlobPattern &glob, jsSourceTy.globPatterns())
+ foreach (const MimeGlobPattern &glob, jsSourceTy.globPatterns())
pattern << glob.pattern();
- foreach (const Core::MimeGlobPattern &glob, qmlSourceTy.globPatterns())
+ foreach (const MimeGlobPattern &glob, qmlSourceTy.globPatterns())
pattern << glob.pattern();
} else {
pattern << QLatin1String("*.qml") << QLatin1String("*.js");
@@ -275,16 +273,15 @@ void ModelManager::delayedInitialization()
this, SLOT(maybeQueueCppQmlTypeUpdate(CPlusPlus::Document::Ptr)), Qt::DirectConnection);
}
- ProjectExplorer::SessionManager *sessionManager = ProjectExplorer::ProjectExplorerPlugin::instance()->session();
- connect(sessionManager, SIGNAL(projectRemoved(ProjectExplorer::Project*)),
+ connect(ProjectExplorer::SessionManager::instance(), SIGNAL(projectRemoved(ProjectExplorer::Project*)),
this, SLOT(removeProjectInfo(ProjectExplorer::Project*)));
}
void ModelManager::loadQmlTypeDescriptions()
{
- if (Core::ICore::instance()) {
- loadQmlTypeDescriptions(Core::ICore::resourcePath());
- loadQmlTypeDescriptions(Core::ICore::userResourcePath());
+ if (ICore::instance()) {
+ loadQmlTypeDescriptions(ICore::resourcePath());
+ loadQmlTypeDescriptions(ICore::userResourcePath());
}
}
@@ -316,27 +313,22 @@ void ModelManager::loadQmlTypeDescriptions(const QString &resourcePath)
CppQmlTypesLoader::defaultLibraryObjects.unite(
CppQmlTypesLoader::loadQmlTypes(qmlTypesFiles, &errors, &warnings));
- Core::MessageManager *messageManager = Core::MessageManager::instance();
foreach (const QString &error, errors)
- messageManager->printToOutputPane(error, Core::MessageManager::Flash);
+ MessageManager::write(error, MessageManager::Flash);
foreach (const QString &warning, warnings)
- messageManager->printToOutputPane(warning, Core::MessageManager::Flash);
+ MessageManager::write(warning, MessageManager::Flash);
}
ModelManagerInterface::WorkingCopy ModelManager::workingCopy() const
{
WorkingCopy workingCopy;
- if (!Core::ICore::instance())
- return workingCopy;
-
- foreach (Core::IEditor *editor, Core::ICore::editorManager()->openedEditors()) {
- const QString key = editor->document()->fileName();
-
- 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()))
- workingCopy.insert(key, ed->toPlainText(), ed->document()->revision());
- }
+ DocumentModel *documentModel = EditorManager::documentModel();
+ foreach (IDocument *document, documentModel->openedDocuments()) {
+ const QString key = document->filePath();
+ if (TextEditor::BaseTextDocument *textDocument = qobject_cast<TextEditor::BaseTextDocument *>(document)) {
+ // TODO the language should be a property on the document, not the editor
+ if (documentModel->editorsForDocument(document).first()->context().contains(ProjectExplorer::Constants::LANG_QMLJS))
+ workingCopy.insert(key, textDocument->contents(), textDocument->document()->revision());
}
}
@@ -386,8 +378,7 @@ QFuture<void> ModelManager::refreshSourceFiles(const QStringList &sourceFiles,
m_synchronizer.addFuture(result);
if (sourceFiles.count() > 1) {
- Core::ICore::progressManager()->addTask(result, tr("Indexing"),
- QLatin1String(Constants::TASK_INDEX));
+ ProgressManager::addTask(result, tr("Indexing"), Constants::TASK_INDEX);
}
return result;
@@ -892,10 +883,8 @@ void ModelManager::parse(QFutureInterface<void> &future,
}
// Check whether fileMimeType is the same or extends knownMimeType
-bool ModelManager::matchesMimeType(const Core::MimeType &fileMimeType, const Core::MimeType &knownMimeType)
+bool ModelManager::matchesMimeType(const MimeType &fileMimeType, const MimeType &knownMimeType)
{
- Core::MimeDatabase *db = Core::ICore::mimeDatabase();
-
const QStringList knownTypeNames = QStringList(knownMimeType.type()) + knownMimeType.aliases();
foreach (const QString &knownTypeName, knownTypeNames)
@@ -903,10 +892,9 @@ bool ModelManager::matchesMimeType(const Core::MimeType &fileMimeType, const Cor
return true;
// recursion to parent types of fileMimeType
- foreach (const QString &parentMimeType, fileMimeType.subClassesOf()) {
- if (matchesMimeType(db->findByType(parentMimeType), knownMimeType))
+ foreach (const QString &parentMimeType, fileMimeType.subClassesOf())
+ if (matchesMimeType(MimeDatabase::findByType(parentMimeType), knownMimeType))
return true;
- }
return false;
}
@@ -1121,8 +1109,7 @@ ModelManager::CppDataHash ModelManager::cppData() const
LibraryInfo ModelManager::builtins(const Document::Ptr &doc) const
{
- ProjectExplorer::SessionManager *sessionManager = ProjectExplorer::ProjectExplorerPlugin::instance()->session();
- ProjectExplorer::Project *project = sessionManager->projectForFile(doc->fileName());
+ ProjectExplorer::Project *project = ProjectExplorer::SessionManager::projectForFile(doc->fileName());
if (!project)
return LibraryInfo();
diff --git a/src/plugins/qmljstools/qmljsplugindumper.cpp b/src/plugins/qmljstools/qmljsplugindumper.cpp
index 5338220afc..3356530767 100644
--- a/src/plugins/qmljstools/qmljsplugindumper.cpp
+++ b/src/plugins/qmljstools/qmljsplugindumper.cpp
@@ -31,7 +31,7 @@
#include "qmljsmodelmanager.h"
#include <qmljs/qmljsinterpreter.h>
-#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/session.h>
#include <coreplugin/messagemanager.h>
#include <utils/filesystemwatcher.h>
#include <utils/fileutils.h>
@@ -253,8 +253,7 @@ static QString qmldumpFailedMessage(const QString &libraryPath, const QString &e
static void printParseWarnings(const QString &libraryPath, const QString &warning)
{
- Core::MessageManager *messageManager = Core::MessageManager::instance();
- messageManager->printToOutputPane(
+ Core::MessageManager::write(
PluginDumper::tr("Warnings while parsing qmltypes information of %1:\n"
"%2").arg(libraryPath, warning),
Core::MessageManager::Flash);
@@ -314,9 +313,8 @@ void PluginDumper::qmlPluginTypeDumpDone(int exitCode)
LibraryInfo libraryInfo = snapshot.libraryInfo(libraryPath);
if (exitCode != 0) {
- Core::MessageManager *messageManager = Core::MessageManager::instance();
const QString errorMessages = qmlPluginDumpErrorMessage(process);
- messageManager->printToOutputPane(qmldumpErrorMessage(libraryPath, errorMessages),
+ Core::MessageManager::write(qmldumpErrorMessage(libraryPath, errorMessages),
Core::MessageManager::Flash);
libraryInfo.setPluginTypeInfoStatus(LibraryInfo::DumpError, qmldumpFailedMessage(libraryPath, errorMessages));
}
@@ -356,9 +354,8 @@ void PluginDumper::qmlPluginTypeDumpError(QProcess::ProcessError)
if (libraryPath.isEmpty())
return;
- Core::MessageManager *messageManager = Core::MessageManager::instance();
const QString errorMessages = qmlPluginDumpErrorMessage(process);
- messageManager->printToOutputPane(qmldumpErrorMessage(libraryPath, errorMessages),
+ Core::MessageManager::write(qmldumpErrorMessage(libraryPath, errorMessages),
Core::MessageManager::Flash);
if (!libraryPath.isEmpty()) {
const Snapshot snapshot = m_modelManager->snapshot();
@@ -437,7 +434,7 @@ void PluginDumper::dump(const Plugin &plugin)
return;
}
- ProjectExplorer::Project *activeProject = ProjectExplorer::ProjectExplorerPlugin::instance()->startupProject();
+ ProjectExplorer::Project *activeProject = ProjectExplorer::SessionManager::startupProject();
if (!activeProject)
return;
diff --git a/src/plugins/qmljstools/qmljssemanticinfo.cpp b/src/plugins/qmljstools/qmljssemanticinfo.cpp
index 031bba46a1..af8891f57e 100644
--- a/src/plugins/qmljstools/qmljssemanticinfo.cpp
+++ b/src/plugins/qmljstools/qmljssemanticinfo.cpp
@@ -154,7 +154,7 @@ QmlJS::AST::Node *SemanticInfo::declaringMemberNoProperties(int cursorPosition)
AST::Node *node = rangeAt(cursorPosition);
if (UiObjectDefinition *objectDefinition = cast<UiObjectDefinition*>(node)) {
- const QString &name = objectDefinition->qualifiedTypeNameId->name.toString();
+ const QStringRef name = objectDefinition->qualifiedTypeNameId->name;
if (!name.isEmpty() && name.at(0).isLower()) {
QList<AST::Node *> path = rangePath(cursorPosition);
if (path.size() > 1)
@@ -165,7 +165,7 @@ QmlJS::AST::Node *SemanticInfo::declaringMemberNoProperties(int cursorPosition)
return path.at(path.size() - 3);
}
} else if (UiObjectBinding *objectBinding = cast<UiObjectBinding*>(node)) {
- const QString &name = objectBinding->qualifiedTypeNameId->name.toString();
+ const QStringRef name = objectBinding->qualifiedTypeNameId->name;
if (name.contains(QLatin1String("Gradient"))) {
QList<AST::Node *> path = rangePath(cursorPosition);
if (path.size() > 1)
diff --git a/src/plugins/qmljstools/qmljstools.qbs b/src/plugins/qmljstools/qmljstools.qbs
index 8e61109c0d..3a2b06a33e 100644
--- a/src/plugins/qmljstools/qmljstools.qbs
+++ b/src/plugins/qmljstools/qmljstools.qbs
@@ -1,7 +1,6 @@
import qbs.base 1.0
import "../QtcPlugin.qbs" as QtcPlugin
-import "../../../qbs/defaults.js" as Defaults
QtcPlugin {
name: "QmlJSTools"
@@ -17,8 +16,6 @@ QtcPlugin {
Depends { name: "QmlDebug" }
Depends { name: "QtSupport" }
- cpp.includePaths: base.concat("../../libs/3rdparty")
-
files: [
"QmlJSTools.mimetypes.xml",
"qmljsbundleprovider.cpp",
@@ -75,7 +72,7 @@ QtcPlugin {
Group {
name: "Tests"
- condition: Defaults.testsEnabled(qbs)
+ condition: project.testsEnabled
files: ["qmljstools_test.cpp"]
}
diff --git a/src/plugins/qmljstools/qmljstoolsplugin.cpp b/src/plugins/qmljstools/qmljstoolsplugin.cpp
index 50d76d8427..fa8eff614a 100644
--- a/src/plugins/qmljstools/qmljstoolsplugin.cpp
+++ b/src/plugins/qmljstools/qmljstoolsplugin.cpp
@@ -48,6 +48,7 @@
#include <QDebug>
#include <QMenu>
+using namespace Core;
using namespace QmlJSTools;
using namespace QmlJSTools::Internal;
@@ -71,10 +72,8 @@ QmlJSToolsPlugin::~QmlJSToolsPlugin()
bool QmlJSToolsPlugin::initialize(const QStringList &arguments, QString *error)
{
Q_UNUSED(arguments)
- Q_UNUSED(error)
- if (!Core::ICore::mimeDatabase()
- ->addMimeTypes(QLatin1String(":/qmljstools/QmlJSTools.mimetypes.xml"), error))
+ if (!MimeDatabase::addMimeTypes(QLatin1String(":/qmljstools/QmlJSTools.mimetypes.xml"), error))
return false;
m_settings = new QmlJSToolsSettings(this); // force registration of qmljstools settings
@@ -83,8 +82,8 @@ bool QmlJSToolsPlugin::initialize(const QStringList &arguments, QString *error)
m_modelManager = new ModelManager(this);
m_consoleManager = new QmlConsoleManager(this);
-// Core::VCSManager *vcsManager = core->vcsManager();
-// Core::DocumentManager *fileManager = core->fileManager();
+// VCSManager *vcsManager = core->vcsManager();
+// DocumentManager *fileManager = core->fileManager();
// connect(vcsManager, SIGNAL(repositoryChanged(QString)),
// m_modelManager, SLOT(updateModifiedSourceFiles()));
// connect(fileManager, SIGNAL(filesChangedInternally(QStringList)),
@@ -97,8 +96,8 @@ bool QmlJSToolsPlugin::initialize(const QStringList &arguments, QString *error)
addAutoReleasedObject(new BasicBundleProvider);
// Menus
- Core::ActionContainer *mtools = Core::ActionManager::actionContainer(Core::Constants::M_TOOLS);
- Core::ActionContainer *mqmljstools = Core::ActionManager::createMenu(Constants::M_TOOLS_QMLJS);
+ ActionContainer *mtools = ActionManager::actionContainer(Core::Constants::M_TOOLS);
+ ActionContainer *mqmljstools = ActionManager::createMenu(Constants::M_TOOLS_QMLJS);
QMenu *menu = mqmljstools->menu();
menu->setTitle(tr("&QML/JS"));
menu->setEnabled(true);
@@ -106,17 +105,17 @@ bool QmlJSToolsPlugin::initialize(const QStringList &arguments, QString *error)
// Update context in global context
m_resetCodeModelAction = new QAction(tr("Reset Code Model"), this);
- Core::Context globalContext(Core::Constants::C_GLOBAL);
- Core::Command *cmd = Core::ActionManager::registerAction(
- m_resetCodeModelAction, Core::Id(Constants::RESET_CODEMODEL), globalContext);
+ Context globalContext(Core::Constants::C_GLOBAL);
+ Command *cmd = ActionManager::registerAction(
+ m_resetCodeModelAction, Constants::RESET_CODEMODEL, globalContext);
connect(m_resetCodeModelAction, SIGNAL(triggered()), m_modelManager, SLOT(resetCodeModel()));
mqmljstools->addAction(cmd);
// watch task progress
- connect(Core::ICore::progressManager(), SIGNAL(taskStarted(QString)),
- this, SLOT(onTaskStarted(QString)));
- connect(Core::ICore::progressManager(), SIGNAL(allTasksFinished(QString)),
- this, SLOT(onAllTasksFinished(QString)));
+ connect(ProgressManager::instance(), SIGNAL(taskStarted(Core::Id)),
+ this, SLOT(onTaskStarted(Core::Id)));
+ connect(ProgressManager::instance(), SIGNAL(allTasksFinished(Core::Id)),
+ this, SLOT(onAllTasksFinished(Core::Id)));
return true;
}
@@ -131,15 +130,15 @@ ExtensionSystem::IPlugin::ShutdownFlag QmlJSToolsPlugin::aboutToShutdown()
return SynchronousShutdown;
}
-void QmlJSToolsPlugin::onTaskStarted(const QString &type)
+void QmlJSToolsPlugin::onTaskStarted(Core::Id type)
{
- if (type == QLatin1String(QmlJSTools::Constants::TASK_INDEX))
+ if (type == QmlJSTools::Constants::TASK_INDEX)
m_resetCodeModelAction->setEnabled(false);
}
-void QmlJSToolsPlugin::onAllTasksFinished(const QString &type)
+void QmlJSToolsPlugin::onAllTasksFinished(Core::Id type)
{
- if (type == QLatin1String(QmlJSTools::Constants::TASK_INDEX))
+ if (type == QmlJSTools::Constants::TASK_INDEX)
m_resetCodeModelAction->setEnabled(true);
}
diff --git a/src/plugins/qmljstools/qmljstoolsplugin.h b/src/plugins/qmljstools/qmljstoolsplugin.h
index e36e08d6fe..6aa5ea1c70 100644
--- a/src/plugins/qmljstools/qmljstoolsplugin.h
+++ b/src/plugins/qmljstools/qmljstoolsplugin.h
@@ -30,6 +30,7 @@
#ifndef QMLJSTOOLS_H
#define QMLJSTOOLS_H
+#include <coreplugin/id.h>
#include <extensionsystem/iplugin.h>
QT_BEGIN_NAMESPACE
@@ -64,8 +65,8 @@ public:
ModelManager *modelManager() { return m_modelManager; }
private slots:
- void onTaskStarted(const QString &type);
- void onAllTasksFinished(const QString &type);
+ void onTaskStarted(Core::Id type);
+ void onAllTasksFinished(Core::Id type);
#ifdef WITH_TESTS
void test_basic();
diff --git a/src/plugins/qmljstools/qmljstoolssettings.cpp b/src/plugins/qmljstools/qmljstoolssettings.cpp
index 388a120ad4..caab131726 100644
--- a/src/plugins/qmljstools/qmljstoolssettings.cpp
+++ b/src/plugins/qmljstools/qmljstoolssettings.cpp
@@ -55,28 +55,26 @@ QmlJSToolsSettings::QmlJSToolsSettings(QObject *parent)
{
QTC_ASSERT(!m_globalCodeStyle, return);
- TextEditorSettings *textEditorSettings = TextEditorSettings::instance();
-
// code style factory
ICodeStylePreferencesFactory *factory = new QmlJSCodeStylePreferencesFactory();
- textEditorSettings->registerCodeStyleFactory(factory);
+ TextEditorSettings::registerCodeStyleFactory(factory);
// code style pool
CodeStylePool *pool = new CodeStylePool(factory, this);
- textEditorSettings->registerCodeStylePool(Constants::QML_JS_SETTINGS_ID, pool);
+ TextEditorSettings::registerCodeStylePool(Constants::QML_JS_SETTINGS_ID, pool);
// global code style settings
m_globalCodeStyle = new SimpleCodeStylePreferences(this);
m_globalCodeStyle->setDelegatingPool(pool);
m_globalCodeStyle->setDisplayName(tr("Global", "Settings"));
- m_globalCodeStyle->setId(QLatin1String(idKey));
+ m_globalCodeStyle->setId(idKey);
pool->addCodeStyle(m_globalCodeStyle);
- textEditorSettings->registerCodeStyle(QmlJSTools::Constants::QML_JS_SETTINGS_ID, m_globalCodeStyle);
+ TextEditorSettings::registerCodeStyle(QmlJSTools::Constants::QML_JS_SETTINGS_ID, m_globalCodeStyle);
// built-in settings
// Qt style
SimpleCodeStylePreferences *qtCodeStyle = new SimpleCodeStylePreferences();
- qtCodeStyle->setId(QLatin1String("qt"));
+ qtCodeStyle->setId("qt");
qtCodeStyle->setDisplayName(tr("Qt"));
qtCodeStyle->setReadOnly(true);
TabSettings qtTabSettings;
@@ -119,13 +117,12 @@ QmlJSToolsSettings::QmlJSToolsSettings(QObject *parent)
QString(), s, &legacyTabSettings);
} else {
// delegating to global
- legacyTabSettings = textEditorSettings->codeStyle()->currentTabSettings();
+ legacyTabSettings = TextEditorSettings::codeStyle()->currentTabSettings();
}
// create custom code style out of old settings
ICodeStylePreferences *oldCreator = pool->createCodeStyle(
- QLatin1String("legacy"), legacyTabSettings,
- QVariant(), tr("Old Creator"));
+ "legacy", legacyTabSettings, QVariant(), tr("Old Creator"));
// change the current delegate and save
m_globalCodeStyle->setCurrentDelegate(oldCreator);
@@ -137,32 +134,19 @@ QmlJSToolsSettings::QmlJSToolsSettings(QObject *parent)
}
// mimetypes to be handled
- textEditorSettings->registerMimeTypeForLanguageId(
- 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(
- QLatin1String(Constants::JSON_MIMETYPE),
- Constants::QML_JS_SETTINGS_ID);
+ TextEditorSettings::registerMimeTypeForLanguageId(Constants::QML_MIMETYPE, Constants::QML_JS_SETTINGS_ID);
+ TextEditorSettings::registerMimeTypeForLanguageId(Constants::QBS_MIMETYPE, Constants::QML_JS_SETTINGS_ID);
+ TextEditorSettings::registerMimeTypeForLanguageId(Constants::QMLPROJECT_MIMETYPE, Constants::QML_JS_SETTINGS_ID);
+ TextEditorSettings::registerMimeTypeForLanguageId(Constants::QMLTYPES_MIMETYPE, Constants::QML_JS_SETTINGS_ID);
+ TextEditorSettings::registerMimeTypeForLanguageId(Constants::JS_MIMETYPE, Constants::QML_JS_SETTINGS_ID);
+ TextEditorSettings::registerMimeTypeForLanguageId(Constants::JSON_MIMETYPE, Constants::QML_JS_SETTINGS_ID);
}
QmlJSToolsSettings::~QmlJSToolsSettings()
{
- TextEditor::TextEditorSettings *textEditorSettings = TextEditor::TextEditorSettings::instance();
- textEditorSettings->unregisterCodeStyle(QmlJSTools::Constants::QML_JS_SETTINGS_ID);
- textEditorSettings->unregisterCodeStylePool(QmlJSTools::Constants::QML_JS_SETTINGS_ID);
- textEditorSettings->unregisterCodeStyleFactory(QmlJSTools::Constants::QML_JS_SETTINGS_ID);
+ TextEditorSettings::unregisterCodeStyle(QmlJSTools::Constants::QML_JS_SETTINGS_ID);
+ TextEditorSettings::unregisterCodeStylePool(QmlJSTools::Constants::QML_JS_SETTINGS_ID);
+ TextEditorSettings::unregisterCodeStyleFactory(QmlJSTools::Constants::QML_JS_SETTINGS_ID);
delete m_globalCodeStyle;
m_globalCodeStyle = 0;
diff --git a/src/plugins/qmlprofiler/QmlProfiler.pluginspec.in b/src/plugins/qmlprofiler/QmlProfiler.pluginspec.in
index 65dc165b7f..e51bd8f1de 100644
--- a/src/plugins/qmlprofiler/QmlProfiler.pluginspec.in
+++ b/src/plugins/qmlprofiler/QmlProfiler.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"QmlProfiler\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"QmlProfiler\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/qmlprofiler/abstracttimelinemodel.cpp b/src/plugins/qmlprofiler/abstracttimelinemodel.cpp
new file mode 100644
index 0000000000..b45b3cc0c1
--- /dev/null
+++ b/src/plugins/qmlprofiler/abstracttimelinemodel.cpp
@@ -0,0 +1,82 @@
+/****************************************************************************
+**
+** 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 "abstracttimelinemodel.h"
+
+namespace QmlProfiler {
+
+AbstractTimelineModel::AbstractTimelineModel(QObject *parent) : QObject(parent), m_modelManager(0)
+{}
+
+AbstractTimelineModel::~AbstractTimelineModel()
+{}
+
+void AbstractTimelineModel::setModelManager(QmlProfilerModelManager *modelManager)
+{
+ m_modelManager = modelManager;
+ connect(modelManager->simpleModel(),SIGNAL(changed()),this,SLOT(dataChanged()));
+ m_modelId = modelManager->registerModelProxy();
+}
+
+qint64 AbstractTimelineModel::traceStartTime() const
+{
+ return m_modelManager->traceTime()->startTime();
+}
+
+qint64 AbstractTimelineModel::traceEndTime() const
+{
+ return m_modelManager->traceTime()->endTime();
+}
+
+qint64 AbstractTimelineModel::traceDuration() const
+{
+ return m_modelManager->traceTime()->duration();
+}
+
+int AbstractTimelineModel::getState() const
+{
+ return (int)m_modelManager->state();
+}
+
+int AbstractTimelineModel::rowCount() const
+{
+ int count = 0;
+ for (int i=0; i<categoryCount(); i++)
+ count += categoryDepth(i);
+ return count;
+}
+
+int AbstractTimelineModel::getBindingLoopDest(int index) const
+{
+ Q_UNUSED(index);
+ return -1;
+}
+
+
+}
diff --git a/src/plugins/qmlprofiler/abstracttimelinemodel.h b/src/plugins/qmlprofiler/abstracttimelinemodel.h
new file mode 100644
index 0000000000..0efcd60631
--- /dev/null
+++ b/src/plugins/qmlprofiler/abstracttimelinemodel.h
@@ -0,0 +1,113 @@
+/****************************************************************************
+**
+** 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 ABSTRACTTIMELINEMODEL_H
+#define ABSTRACTTIMELINEMODEL_H
+
+
+#include "qmlprofiler_global.h"
+#include "qmlprofilermodelmanager.h"
+#include "qmlprofilersimplemodel.h"
+#include <QObject>
+#include <QVariant>
+#include <QColor>
+
+namespace QmlProfiler {
+
+class QMLPROFILER_EXPORT AbstractTimelineModel : public QObject
+{
+ Q_OBJECT
+
+public:
+ explicit AbstractTimelineModel(QObject *parent = 0);
+ ~AbstractTimelineModel();
+
+ void setModelManager(QmlProfilerModelManager *modelManager);
+
+ virtual int categories() const = 0;
+ virtual QStringList categoryTitles() const = 0;
+ virtual QString name() const = 0;
+ virtual int count() const = 0;
+
+ virtual bool isEmpty() const = 0;
+
+ virtual bool eventAccepted(const QmlProfilerSimpleModel::QmlEventData &event) const = 0;
+
+ Q_INVOKABLE virtual qint64 lastTimeMark() const = 0;
+ Q_INVOKABLE qint64 traceStartTime() const;
+ Q_INVOKABLE qint64 traceEndTime() const;
+ Q_INVOKABLE qint64 traceDuration() const;
+ Q_INVOKABLE int getState() const;
+
+ Q_INVOKABLE virtual bool expanded(int category) const = 0;
+ Q_INVOKABLE virtual void setExpanded(int category, bool expanded) = 0;
+ Q_INVOKABLE virtual int categoryDepth(int categoryIndex) const = 0;
+ Q_INVOKABLE virtual int categoryCount() const = 0;
+ Q_INVOKABLE virtual int rowCount() const;
+ Q_INVOKABLE virtual const QString categoryLabel(int categoryIndex) const = 0;
+
+ virtual int findFirstIndex(qint64 startTime) const = 0;
+ virtual int findFirstIndexNoParents(qint64 startTime) const = 0;
+ virtual int findLastIndex(qint64 endTime) const = 0;
+
+ virtual int getEventType(int index) const = 0;
+ virtual int getEventCategory(int index) const = 0;
+ virtual int getEventRow(int index) const = 0;
+ Q_INVOKABLE virtual qint64 getDuration(int index) const = 0;
+ Q_INVOKABLE virtual qint64 getStartTime(int index) const = 0;
+ Q_INVOKABLE virtual qint64 getEndTime(int index) const = 0;
+ Q_INVOKABLE virtual int getEventId(int index) const = 0;
+ Q_INVOKABLE virtual int getBindingLoopDest(int index) const;
+ Q_INVOKABLE virtual QColor getColor(int index) const = 0;
+ Q_INVOKABLE virtual float getHeight(int index) const = 0;
+
+ Q_INVOKABLE virtual const QVariantList getLabelsForCategory(int category) const = 0;
+
+ Q_INVOKABLE virtual const QVariantList getEventDetails(int index) const = 0;
+
+ // returned map should contain "file", "line", "column" properties, or be empty
+ Q_INVOKABLE virtual const QVariantMap getEventLocation(int index) const = 0;
+ Q_INVOKABLE virtual int getEventIdForHash(const QString &eventHash) const = 0;
+ Q_INVOKABLE virtual int getEventIdForLocation(const QString &filename, int line, int column) const = 0;
+
+signals:
+ void countChanged();
+ void dataAvailable();
+ void stateChanged();
+ void emptyChanged();
+ void expandedChanged();
+
+protected:
+ QmlProfilerModelManager *m_modelManager;
+ int m_modelId;
+};
+
+}
+
+#endif // ABSTRACTTIMELINEMODEL_H
diff --git a/src/plugins/qmlprofiler/canvas/canvas.pri b/src/plugins/qmlprofiler/canvas/canvas.pri
index 8b5621fb44..2960e94527 100644
--- a/src/plugins/qmlprofiler/canvas/canvas.pri
+++ b/src/plugins/qmlprofiler/canvas/canvas.pri
@@ -1,5 +1,3 @@
-INCLUDEPATH += $$PWD
-
HEADERS += $$PWD/qdeclarativecontext2d_p.h \
$$PWD/qdeclarativecanvas_p.h \
$$PWD/qmlprofilercanvas.h \
diff --git a/src/plugins/qmlprofiler/canvas/qdeclarativecanvas.cpp b/src/plugins/qmlprofiler/canvas/qdeclarativecanvas.cpp
index 70a849f39b..4611d7096b 100644
--- a/src/plugins/qmlprofiler/canvas/qdeclarativecanvas.cpp
+++ b/src/plugins/qmlprofiler/canvas/qdeclarativecanvas.cpp
@@ -35,16 +35,14 @@
QT_BEGIN_NAMESPACE
-Canvas::Canvas(QDeclarativeItem *parent)
- : QDeclarativeItem(parent),
+Canvas::Canvas(QQuickPaintedItem *parent)
+ : QQuickPaintedItem(parent),
m_context(new Context2D(this)),
m_canvasWidth(0),
m_canvasHeight(0),
m_fillMode(Canvas::Stretch),
m_color(Qt::white)
{
- setFlag(QGraphicsItem::ItemHasNoContents, false);
- setCacheMode(QGraphicsItem::DeviceCoordinateCache);
}
@@ -57,10 +55,10 @@ void Canvas::componentComplete()
connect(m_context, SIGNAL(changed()), this, SLOT(requestPaint()));
emit init();
- QDeclarativeItem::componentComplete();
+ QQuickItem::componentComplete();
}
-void Canvas::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *)
+void Canvas::paint(QPainter *painter)
{
m_context->setInPaint(true);
emit paint();
@@ -160,7 +158,7 @@ void Canvas::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometr
&& newGeometry.width() > 0 && newGeometry.height() > 0) {
m_context->setSize(width(), height());
}
- QDeclarativeItem::geometryChanged(newGeometry, oldGeometry);
+ QQuickItem::geometryChanged(newGeometry, oldGeometry);
}
void Canvas::setCanvasWidth(int newWidth)
@@ -219,24 +217,24 @@ CanvasImage *Canvas::toImage() const
return new CanvasImage(m_context->pixmap());
}
-void Canvas::setTimeout(const QScriptValue &handler, long timeout)
+void Canvas::setTimeout(const QJSValue &handler, long timeout)
{
- if (handler.isFunction())
+ if (handler.isCallable())
CanvasTimer::createTimer(this, handler, timeout, true);
}
-void Canvas::setInterval(const QScriptValue &handler, long interval)
+void Canvas::setInterval(const QJSValue &handler, long interval)
{
- if (handler.isFunction())
+ if (handler.isCallable())
CanvasTimer::createTimer(this, handler, interval, false);
}
-void Canvas::clearTimeout(const QScriptValue &handler)
+void Canvas::clearTimeout(const QJSValue &handler)
{
CanvasTimer::removeTimer(handler);
}
-void Canvas::clearInterval(const QScriptValue &handler)
+void Canvas::clearInterval(const QJSValue &handler)
{
CanvasTimer::removeTimer(handler);
}
diff --git a/src/plugins/qmlprofiler/canvas/qdeclarativecanvas_p.h b/src/plugins/qmlprofiler/canvas/qdeclarativecanvas_p.h
index 429097d5b4..3f4fd8b0dd 100644
--- a/src/plugins/qmlprofiler/canvas/qdeclarativecanvas_p.h
+++ b/src/plugins/qmlprofiler/canvas/qdeclarativecanvas_p.h
@@ -30,15 +30,14 @@
#ifndef QDECLARATIVECANVAS_P_H
#define QDECLARATIVECANVAS_P_H
-#include <qdeclarativeitem.h>
+#include <QQuickPaintedItem>
#include "qdeclarativecontext2d_p.h"
#include "qdeclarativecanvastimer_p.h"
QT_BEGIN_NAMESPACE
-QT_MODULE(Declarative)
-class Canvas : public QDeclarativeItem
+class Canvas : public QQuickPaintedItem
{
Q_OBJECT
@@ -49,11 +48,11 @@ class Canvas : public QDeclarativeItem
Q_PROPERTY(FillMode fillMode READ fillMode WRITE setFillMode NOTIFY fillModeChanged)
public:
- Canvas(QDeclarativeItem *parent = 0);
+ Canvas(QQuickPaintedItem *parent = 0);
enum FillMode { Stretch, PreserveAspectFit, PreserveAspectCrop, Tile, TileVertically, TileHorizontally };
- void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *);
+ void paint(QPainter *);
void geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry);
void setCanvasWidth(int newWidth);
int canvasWidth() {return m_canvasWidth;}
@@ -78,10 +77,10 @@ public Q_SLOTS:
bool save(const QString& filename) const;
// Timers
- void setInterval(const QScriptValue &handler, long timeout);
- void setTimeout(const QScriptValue &handler, long timeout);
- void clearInterval(const QScriptValue &handler);
- void clearTimeout(const QScriptValue &handler);
+ void setInterval(const QJSValue &handler, long timeout);
+ void setTimeout(const QJSValue &handler, long timeout);
+ void clearInterval(const QJSValue &handler);
+ void clearTimeout(const QJSValue &handler);
Q_SIGNALS:
void fillModeChanged();
diff --git a/src/plugins/qmlprofiler/canvas/qdeclarativecanvastimer.cpp b/src/plugins/qmlprofiler/canvas/qdeclarativecanvastimer.cpp
index 4d41aec983..8069fbbcb7 100644
--- a/src/plugins/qmlprofiler/canvas/qdeclarativecanvastimer.cpp
+++ b/src/plugins/qmlprofiler/canvas/qdeclarativecanvastimer.cpp
@@ -29,28 +29,28 @@
#include "qdeclarativecanvastimer_p.h"
-#include <qscriptengine.h>
-#include <qscriptvalue.h>
+#include <QJSEngine>
+#include <QJSValue>
#include <qtimer.h>
QT_BEGIN_NAMESPACE
Q_GLOBAL_STATIC(QList<CanvasTimer*> , activeTimers);
-CanvasTimer::CanvasTimer(QObject *parent, const QScriptValue &data)
+CanvasTimer::CanvasTimer(QObject *parent, const QJSValue &data)
: QTimer(parent), m_value(data)
{
}
void CanvasTimer::handleTimeout()
{
- Q_ASSERT(m_value.isFunction());
+ Q_ASSERT(m_value.isCallable());
m_value.call();
if (isSingleShot())
removeTimer(this);
}
-void CanvasTimer::createTimer(QObject *parent, const QScriptValue &val, long timeout, bool singleshot)
+void CanvasTimer::createTimer(QObject *parent, const QJSValue &val, long timeout, bool singleshot)
{
CanvasTimer *timer = new CanvasTimer(parent, val);
@@ -67,9 +67,9 @@ void CanvasTimer::removeTimer(CanvasTimer *timer)
timer->deleteLater();
}
-void CanvasTimer::removeTimer(const QScriptValue &val)
+void CanvasTimer::removeTimer(const QJSValue &val)
{
- if (!val.isFunction())
+ if (!val.isCallable())
return;
for (int i = 0 ; i < activeTimers()->count() ; ++i) {
diff --git a/src/plugins/qmlprofiler/canvas/qdeclarativecanvastimer_p.h b/src/plugins/qmlprofiler/canvas/qdeclarativecanvastimer_p.h
index 915afa542d..b25a98eb44 100644
--- a/src/plugins/qmlprofiler/canvas/qdeclarativecanvastimer_p.h
+++ b/src/plugins/qmlprofiler/canvas/qdeclarativecanvastimer_p.h
@@ -30,32 +30,30 @@
#ifndef QDECLARATIVECANVASTIMER_P_H
#define QDECLARATIVECANVASTIMER_P_H
-#include <qscriptvalue.h>
+#include <QJSValue>
#include <qtimer.h>
#include <qlist.h>
QT_BEGIN_NAMESPACE
-QT_MODULE(Declarative)
-
class CanvasTimer : public QTimer
{
Q_OBJECT
public:
- CanvasTimer(QObject *parent, const QScriptValue &data);
+ CanvasTimer(QObject *parent, const QJSValue &data);
public Q_SLOTS:
void handleTimeout();
- bool equals(const QScriptValue &value){return m_value.equals(value);}
+ bool equals(const QJSValue &value){return m_value.equals(value);}
public:
- static void createTimer(QObject *parent, const QScriptValue &val, long timeout, bool singleshot);
+ static void createTimer(QObject *parent, const QJSValue &val, long timeout, bool singleshot);
static void removeTimer(CanvasTimer *timer);
- static void removeTimer(const QScriptValue &);
+ static void removeTimer(const QJSValue &);
private:
- QScriptValue m_value;
+ QJSValue m_value;
};
diff --git a/src/plugins/qmlprofiler/canvas/qdeclarativecontext2d.cpp b/src/plugins/qmlprofiler/canvas/qdeclarativecontext2d.cpp
index 62e7f09207..be092b12ad 100644
--- a/src/plugins/qmlprofiler/canvas/qdeclarativecontext2d.cpp
+++ b/src/plugins/qmlprofiler/canvas/qdeclarativecontext2d.cpp
@@ -39,6 +39,7 @@
#include <qgraphicseffect.h>
#include <QImage>
+#include <QWidget>
QT_BEGIN_NAMESPACE
@@ -511,17 +512,17 @@ QString Context2D::textBaseline()
void Context2D::setTextBaseline(const QString &baseline)
{
- if (baseline==QLatin1String("alphabetic"))
+ if (baseline==QLatin1String("alphabetic")) {
m_state.textBaseline = Context2D::Alphabetic;
- else if (baseline == QLatin1String("hanging"))
+ } else if (baseline == QLatin1String("hanging")) {
m_state.textBaseline = Context2D::Hanging;
- else if (baseline == QLatin1String("top"))
+ } else if (baseline == QLatin1String("top")) {
m_state.textBaseline = Context2D::Top;
- else if (baseline == QLatin1String("bottom"))
+ } else if (baseline == QLatin1String("bottom")) {
m_state.textBaseline = Context2D::Bottom;
- else if (baseline == QLatin1String("middle"))
+ } else if (baseline == QLatin1String("middle")) {
m_state.textBaseline = Context2D::Middle;
- else {
+ } else {
m_state.textBaseline = Context2D::Alphabetic;
qWarning() << (QLatin1String("Context2D: invalid baseline:") + baseline);
}
@@ -550,17 +551,17 @@ QString Context2D::textAlign()
void Context2D::setTextAlign(const QString &baseline)
{
- if (baseline==QLatin1String("start"))
+ if (baseline==QLatin1String("start")) {
m_state.textAlign = Context2D::Start;
- else if (baseline == QLatin1String("end"))
+ } else if (baseline == QLatin1String("end")) {
m_state.textAlign = Context2D::End;
- else if (baseline == QLatin1String("left"))
+ } else if (baseline == QLatin1String("left")) {
m_state.textAlign = Context2D::Left;
- else if (baseline == QLatin1String("right"))
+ } else if (baseline == QLatin1String("right")) {
m_state.textAlign = Context2D::Right;
- else if (baseline == QLatin1String("center"))
+ } else if (baseline == QLatin1String("center")) {
m_state.textAlign = Context2D::Center;
- else {
+ } else {
m_state.textAlign= Context2D::Start;
qWarning("Context2D: invalid text align");
}
@@ -574,11 +575,11 @@ void Context2D::setFont(const QString &fontString)
// ### this is simplified and incomplete
QStringList tokens = fontString.split(QLatin1Char(QLatin1Char(' ')));
foreach (const QString &token, tokens) {
- if (token == QLatin1String("italic"))
+ if (token == QLatin1String("italic")) {
font.setItalic(true);
- else if (token == QLatin1String("bold"))
+ } else if (token == QLatin1String("bold")) {
font.setBold(true);
- else if (token.endsWith(QLatin1String("px"))) {
+ } else if (token.endsWith(QLatin1String("px"))) {
QString number = token;
number.remove(QLatin1String("px"));
#ifdef Q_OS_MACX
@@ -589,8 +590,9 @@ void Context2D::setFont(const QString &fontString)
#else
font.setPointSizeF(number.trimmed().toFloat());
#endif
- } else
+ } else {
font.setFamily(token);
+ }
}
m_state.font = font;
m_state.flags |= DirtyFont;
@@ -736,8 +738,8 @@ void Context2D::strokeRect(qreal x, qreal y, qreal w, qreal h)
scheduleChange();
}
-void Context2D::mouseArea(qreal x, qreal y, qreal w, qreal h, const QScriptValue &callback,
- const QScriptValue &data)
+void Context2D::mouseArea(qreal x, qreal y, qreal w, qreal h, const QJSValue &callback,
+ const QJSValue &data)
{
MouseArea a = { callback, data, QRectF(x, y, w, h), m_state.matrix };
m_mouseAreas << a;
@@ -1103,8 +1105,13 @@ void Context2D::setPainterTranslate(const QPoint &translate)
void Context2D::scheduleChange()
{
+ QMetaObject::invokeMethod(this, "onScheduleChange", Qt::QueuedConnection, Q_ARG(int, 0));
+}
+
+void Context2D::onScheduleChange(int interval)
+{
if (m_changeTimerId == -1 && !m_inPaint)
- m_changeTimerId = startTimer(0);
+ m_changeTimerId = startTimer(interval);
}
void Context2D::timerEvent(QTimerEvent *e)
diff --git a/src/plugins/qmlprofiler/canvas/qdeclarativecontext2d_p.h b/src/plugins/qmlprofiler/canvas/qdeclarativecontext2d_p.h
index 7183875768..cd84e1fa2b 100644
--- a/src/plugins/qmlprofiler/canvas/qdeclarativecontext2d_p.h
+++ b/src/plugins/qmlprofiler/canvas/qdeclarativecontext2d_p.h
@@ -38,11 +38,10 @@
#include <qmetatype.h>
#include <qcoreevent.h>
#include <qvariant.h>
-#include <qscriptvalue.h>
-QT_BEGIN_NAMESPACE
+#include <QJSValue>
-QT_MODULE(Declarative)
+QT_BEGIN_NAMESPACE
QColor colorFromString(const QString &name);
@@ -174,8 +173,8 @@ public:
void setShadowColor(const QString &str);
struct MouseArea {
- QScriptValue callback;
- QScriptValue data;
+ QJSValue callback;
+ QJSValue data;
QRectF rect;
QMatrix matrix;
};
@@ -209,7 +208,7 @@ public slots:
void strokeRect(qreal x, qreal y, qreal w, qreal h);
// mouse
- void mouseArea(qreal x, qreal y, qreal w, qreal h, const QScriptValue &, const QScriptValue & = QScriptValue());
+ void mouseArea(qreal x, qreal y, qreal w, qreal h, const QJSValue &, const QJSValue & = QJSValue());
// path API
void beginPath();
@@ -239,6 +238,9 @@ public slots:
void putImageData(ImageData image, qreal dx, qreal dy);
void endPainting();
+private slots:
+ void onScheduleChange(int interval);
+
signals:
void changed();
diff --git a/src/plugins/qmlprofiler/canvas/qmlprofilercanvas.cpp b/src/plugins/qmlprofiler/canvas/qmlprofilercanvas.cpp
index 01e3b3cdda..e078680863 100644
--- a/src/plugins/qmlprofiler/canvas/qmlprofilercanvas.cpp
+++ b/src/plugins/qmlprofiler/canvas/qmlprofilercanvas.cpp
@@ -41,9 +41,7 @@ QmlProfilerCanvas::QmlProfilerCanvas()
: m_context2d(new Context2D(this))
, m_dirty(true)
{
- setFlag(QGraphicsItem::ItemHasNoContents, false);
setAcceptedMouseButtons(Qt::LeftButton);
- setCacheMode(QGraphicsItem::DeviceCoordinateCache);
}
void QmlProfilerCanvas::requestPaint()
@@ -57,7 +55,7 @@ void QmlProfilerCanvas::requestRedraw()
update();
}
-void QmlProfilerCanvas::paint(QPainter *p, const QStyleOptionGraphicsItem *, QWidget *)
+void QmlProfilerCanvas::paint(QPainter *p)
{
if (m_context2d->size().width() != width() || m_context2d->size().height() != height()) {
m_dirty = true;
@@ -84,7 +82,7 @@ void QmlProfilerCanvas::componentComplete()
if (p.hasNotifySignal())
QMetaObject::connect(this, p.notifySignalIndex(), this, requestPaintMethod, 0, 0);
}
- QDeclarativeItem::componentComplete();
+ QQuickItem::componentComplete();
}
}
diff --git a/src/plugins/qmlprofiler/canvas/qmlprofilercanvas.h b/src/plugins/qmlprofiler/canvas/qmlprofilercanvas.h
index 51289d8b96..f7837f2ed0 100644
--- a/src/plugins/qmlprofiler/canvas/qmlprofilercanvas.h
+++ b/src/plugins/qmlprofiler/canvas/qmlprofilercanvas.h
@@ -30,7 +30,7 @@
#ifndef QMLPROFILERCANVAS_H
#define QMLPROFILERCANVAS_H
-#include <QDeclarativeItem>
+#include <QQuickPaintedItem>
QT_BEGIN_NAMESPACE
class Context2D;
@@ -39,7 +39,7 @@ QT_END_NAMESPACE
namespace QmlProfiler {
namespace Internal {
-class QmlProfilerCanvas : public QDeclarativeItem
+class QmlProfilerCanvas : public QQuickPaintedItem
{
Q_OBJECT
@@ -67,7 +67,7 @@ public slots:
void requestRedraw();
protected:
- virtual void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *);
+ virtual void paint(QPainter *);
virtual void componentComplete();
private:
diff --git a/src/plugins/qmlprofiler/localqmlprofilerrunner.cpp b/src/plugins/qmlprofiler/localqmlprofilerrunner.cpp
index 2a47feb46a..14f7de97dd 100644
--- a/src/plugins/qmlprofiler/localqmlprofilerrunner.cpp
+++ b/src/plugins/qmlprofiler/localqmlprofilerrunner.cpp
@@ -45,7 +45,7 @@ LocalQmlProfilerRunner *LocalQmlProfilerRunner::createLocalRunner(
RunConfiguration *runConfiguration,
const Analyzer::AnalyzerStartParameters &sp,
QString *errorMessage,
- QmlProfilerEngine *engine)
+ QmlProfilerRunControl *engine)
{
QmlProjectManager::QmlProjectRunConfiguration *rc1 =
qobject_cast<QmlProjectManager::QmlProjectRunConfiguration *>(runConfiguration);
@@ -81,7 +81,7 @@ LocalQmlProfilerRunner *LocalQmlProfilerRunner::createLocalRunner(
}
LocalQmlProfilerRunner::LocalQmlProfilerRunner(const Configuration &configuration,
- QmlProfilerEngine *engine) :
+ QmlProfilerRunControl *engine) :
AbstractQmlProfilerRunner(engine),
m_configuration(configuration),
m_engine(engine)
@@ -97,7 +97,7 @@ LocalQmlProfilerRunner::~LocalQmlProfilerRunner()
void LocalQmlProfilerRunner::start()
{
- if (m_engine->mode() != Analyzer::StartQml)
+ if (m_engine->mode() != Analyzer::StartLocal)
return;
QString arguments = QString::fromLatin1("-qmljsdebugger=port:%1,block").arg(m_configuration.port);
@@ -111,26 +111,32 @@ void LocalQmlProfilerRunner::start()
m_launcher.setWorkingDirectory(m_configuration.workingDirectory);
m_launcher.setEnvironment(m_configuration.environment);
- connect(&m_launcher, SIGNAL(processExited(int)), this, SLOT(spontaneousStop(int)));
+ connect(&m_launcher, SIGNAL(processExited(int,QProcess::ExitStatus)),
+ this, SLOT(spontaneousStop(int,QProcess::ExitStatus)));
m_launcher.start(ProjectExplorer::ApplicationLauncher::Gui, m_configuration.executable,
arguments);
emit started();
}
-void LocalQmlProfilerRunner::spontaneousStop(int exitCode)
+void LocalQmlProfilerRunner::spontaneousStop(int exitCode, QProcess::ExitStatus status)
{
- if (QmlProfilerPlugin::debugOutput)
- qWarning("QmlProfiler: Application exited (exit code %d).", exitCode);
+ if (QmlProfilerPlugin::debugOutput) {
+ if (status == QProcess::CrashExit)
+ qWarning("QmlProfiler: Application crashed.");
+ else
+ qWarning("QmlProfiler: Application exited (exit code %d).", exitCode);
+ }
- disconnect(&m_launcher, SIGNAL(processExited(int)), this, SLOT(spontaneousStop(int)));
+ disconnect(&m_launcher, SIGNAL(processExited(int,QProcess::ExitStatus)),
+ this, SLOT(spontaneousStop(int,QProcess::ExitStatus)));
emit stopped();
}
void LocalQmlProfilerRunner::stop()
{
- if (m_engine->mode() != Analyzer::StartQml)
+ if (m_engine->mode() != Analyzer::StartLocal)
return;
if (QmlProfilerPlugin::debugOutput)
diff --git a/src/plugins/qmlprofiler/localqmlprofilerrunner.h b/src/plugins/qmlprofiler/localqmlprofilerrunner.h
index 37591917da..540f472241 100644
--- a/src/plugins/qmlprofiler/localqmlprofilerrunner.h
+++ b/src/plugins/qmlprofiler/localqmlprofilerrunner.h
@@ -41,7 +41,7 @@ namespace Analyzer { class AnalyzerStartParameters; }
namespace QmlProfiler {
namespace Internal {
-class QmlProfilerEngine;
+class QmlProfilerRunControl;
class LocalQmlProfilerRunner : public AbstractQmlProfilerRunner
{
Q_OBJECT
@@ -58,7 +58,7 @@ public:
static LocalQmlProfilerRunner *createLocalRunner(ProjectExplorer::RunConfiguration *runConfiguration,
const Analyzer::AnalyzerStartParameters &sp,
QString *errorMessage,
- QmlProfilerEngine *engine);
+ QmlProfilerRunControl *engine);
~LocalQmlProfilerRunner();
@@ -68,15 +68,15 @@ public:
virtual quint16 debugPort() const;
private slots:
- void spontaneousStop(int exitCode);
+ void spontaneousStop(int exitCode, QProcess::ExitStatus status);
private:
- LocalQmlProfilerRunner(const Configuration &configuration, QmlProfilerEngine *engine);
+ LocalQmlProfilerRunner(const Configuration &configuration, QmlProfilerRunControl *engine);
private:
Configuration m_configuration;
ProjectExplorer::ApplicationLauncher m_launcher;
- QmlProfilerEngine *m_engine;
+ QmlProfilerRunControl *m_engine;
};
} // namespace Internal
diff --git a/src/plugins/qmlprofiler/qml/Detail.qml b/src/plugins/qmlprofiler/qml/Detail.qml
index 567ea7f02a..361b7bc6c7 100644
--- a/src/plugins/qmlprofiler/qml/Detail.qml
+++ b/src/plugins/qmlprofiler/qml/Detail.qml
@@ -27,14 +27,13 @@
**
****************************************************************************/
-import QtQuick 1.0
+import QtQuick 2.1
import Monitor 1.0
Item {
id: detail
property string label
property string content
- signal linkActivated(string url)
height: childrenRect.height+2
width: childrenRect.width
@@ -55,7 +54,6 @@ Item {
font.pixelSize: 12
anchors.baseline: lbl.baseline
anchors.left: guideline.right
- onLinkActivated: detail.linkActivated(link)
textFormat: Text.PlainText
}
}
diff --git a/src/plugins/qmlprofiler/qml/Label.qml b/src/plugins/qmlprofiler/qml/Label.qml
index f7db9ab34c..f8cc12d859 100644
--- a/src/plugins/qmlprofiler/qml/Label.qml
+++ b/src/plugins/qmlprofiler/qml/Label.qml
@@ -27,27 +27,28 @@
**
****************************************************************************/
-import QtQuick 1.0
+import QtQuick 2.1
Item {
id: labelContainer
- property alias text: txt.text
+ property string text: qmlProfilerModelProxy.categoryLabel(modelIndex, categoryIndex)
property bool expanded: false
- property int typeIndex: index
+ property int categoryIndex: qmlProfilerModelProxy.correctedCategoryIndexForModel(modelIndex, index)
+ property int modelIndex: qmlProfilerModelProxy.modelIndexForCategory(index);
- property variant descriptions: []
- property variant extdescriptions: []
- property variant eventIds: []
+ property var descriptions: []
+ property var extdescriptions: []
+ property var eventIds: []
+
+ visible: qmlProfilerModelProxy.categoryDepth(modelIndex, categoryIndex) > 0;
height: root.singleRowHeight
width: 150
onExpandedChanged: {
- var rE = labels.rowExpanded;
- rE[typeIndex] = expanded;
- labels.rowExpanded = rE;
+ qmlProfilerModelProxy.setExpanded(modelIndex, categoryIndex, expanded);
backgroundMarks.requestRedraw();
- view.setRowExpanded(typeIndex, expanded);
+ getDescriptions();
updateHeight();
}
@@ -56,20 +57,24 @@ Item {
}
function updateHeight() {
- height = root.singleRowHeight * (1 +
- (expanded ? qmlProfilerDataModel.uniqueEventsOfType(typeIndex) :
- qmlProfilerDataModel.maxNestingForType(typeIndex)));
+ if (expanded != qmlProfilerModelProxy.expanded(modelIndex, categoryIndex))
+ expanded = qmlProfilerModelProxy.expanded(modelIndex, categoryIndex);
+ height = root.singleRowHeight * qmlProfilerModelProxy.categoryDepth(modelIndex, categoryIndex);
}
function getDescriptions() {
+ visible = qmlProfilerModelProxy.categoryDepth(modelIndex, categoryIndex) > 0;
+ if (!visible)
+ return;
+
var desc=[];
var ids=[];
var extdesc=[];
- for (var i=0; i<qmlProfilerDataModel.uniqueEventsOfType(typeIndex); i++) {
- desc[i] = qmlProfilerDataModel.eventTextForType(typeIndex, i);
- ids[i] = qmlProfilerDataModel.eventIdForType(typeIndex, i);
- extdesc[i] = qmlProfilerDataModel.eventDisplayNameForType(typeIndex, i) +
- " : " + desc[i];
+ var labelList = qmlProfilerModelProxy.getLabelsForCategory(modelIndex, categoryIndex);
+ for (var i = 0; i < labelList.length; i++ ) {
+ desc[i] = labelList[i].description;
+ ids[i] = labelList[i].id;
+ extdesc[i] = labelList[i].displayName + ":" + labelList[i].description;
}
descriptions = desc;
eventIds = ids;
@@ -78,20 +83,13 @@ Item {
}
Connections {
- target: qmlProfilerDataModel
- onReloadDetailLabels: getDescriptions();
+ target: qmlProfilerModelProxy
+ onExpandedChanged: {
+ updateHeight();
+ }
+
onStateChanged: {
- // Empty
- if (qmlProfilerDataModel.getCurrentStateFromQml() == 0) {
- descriptions = [];
- eventIds = [];
- extdescriptions = [];
- updateHeight();
- } else
- // Done
- if (qmlProfilerDataModel.getCurrentStateFromQml() == 3) {
- getDescriptions();
- }
+ getDescriptions();
}
}
@@ -99,6 +97,7 @@ Item {
id: txt
x: 5
font.pixelSize: 12
+ text: labelContainer.text
color: "#232323"
height: root.singleRowHeight
width: 140
@@ -140,9 +139,9 @@ Item {
onExited: changeToolTip("");
onClicked: {
if (mouse.modifiers & Qt.ShiftModifier)
- view.selectPrevFromId(eventIds[index]);
+ view.selectPrevFromId(modelIndex,eventIds[index]);
else
- view.selectNextFromId(eventIds[index]);
+ view.selectNextFromId(modelIndex,eventIds[index]);
}
}
}
@@ -150,7 +149,6 @@ Item {
}
Image {
- visible: descriptions.length > 0
source: expanded ? "arrow_down.png" : "arrow_right.png"
x: parent.width - 12
y: root.singleRowHeight / 2 - height / 2
diff --git a/src/plugins/qmlprofiler/qml/MainView.qml b/src/plugins/qmlprofiler/qml/MainView.qml
index df8b8922a3..82a77d6bcc 100644
--- a/src/plugins/qmlprofiler/qml/MainView.qml
+++ b/src/plugins/qmlprofiler/qml/MainView.qml
@@ -27,7 +27,7 @@
**
****************************************************************************/
-import QtQuick 1.0
+import QtQuick 2.1
import Monitor 1.0
Rectangle {
@@ -51,15 +51,7 @@ Rectangle {
signal selectedEventChanged(int eventId)
property bool lockItemSelection : false
- property variant names: [ qsTr("Painting"),
- qsTr("Compiling"),
- qsTr("Creating"),
- qsTr("Binding"),
- qsTr("Handling Signal")]
- property variant colors : [ "#99CCB3", "#99CCCC", "#99B3CC",
- "#9999CC", "#CC99B3", "#CC99CC", "#CCCC99", "#CCB399" ]
-
- property variant mainviewTimePerPixel : 0
+ property real mainviewTimePerPixel : 0
signal updateCursorPosition
property string fileName: ""
@@ -70,8 +62,8 @@ Rectangle {
property bool selectionRangeMode: false
property bool selectionRangeReady: selectionRange.ready
- property variant selectionRangeStart: selectionRange.startTime
- property variant selectionRangeEnd: selectionRange.startTime + selectionRange.duration
+ property real selectionRangeStart: selectionRange.startTime
+ property real selectionRangeEnd: selectionRange.startTime + selectionRange.duration
signal changeToolTip(string text)
signal updateVerticalScroll(int newPosition)
@@ -95,7 +87,7 @@ Rectangle {
backgroundMarks.updateMarks(startTime, endTime);
view.updateFlickRange(startTime, endTime);
if (duration > 0) {
- var candidateWidth = qmlProfilerDataModel.traceDuration() *
+ var candidateWidth = qmlProfilerModelProxy.traceDuration() *
flick.width / duration;
if (flick.contentWidth !== candidateWidth)
flick.contentWidth = candidateWidth;
@@ -104,22 +96,23 @@ Rectangle {
}
}
+
Connections {
- target: qmlProfilerDataModel
+ target: qmlProfilerModelProxy
onCountChanged: {
- eventCount = qmlProfilerDataModel.count();
+ eventCount = qmlProfilerModelProxy.count();
if (eventCount === 0)
root.clearAll();
if (eventCount > 1) {
root.progress = Math.min(1.0,
- (qmlProfilerDataModel.lastTimeMark() -
- qmlProfilerDataModel.traceStartTime()) / root.elapsedTime * 1e-9 );
+ (qmlProfilerModelProxy.lastTimeMark() -
+ qmlProfilerModelProxy.traceStartTime()) / root.elapsedTime * 1e-9 );
} else {
root.progress = 0;
}
}
onStateChanged: {
- switch (qmlProfilerDataModel.getCurrentStateFromQml()) {
+ switch (qmlProfilerModelProxy.getState()) {
case 0: {
root.clearAll();
break;
@@ -132,27 +125,30 @@ Rectangle {
root.progress = 0.9; // jump to 90%
break;
}
- case 3: {
- view.clearData();
- progress = 1.0;
- dataAvailable = true;
- view.visible = true;
- view.requestPaint();
- zoomControl.setRange(qmlProfilerDataModel.traceStartTime(),
- qmlProfilerDataModel.traceStartTime() +
- qmlProfilerDataModel.traceDuration()/10);
- break;
- }
}
}
+ onDataAvailable: {
+ view.clearData();
+ zoomControl.setRange(0,0);
+ progress = 1.0;
+ dataAvailable = true;
+ view.visible = true;
+ view.requestPaint();
+ zoomControl.setRange(qmlProfilerModelProxy.traceStartTime(),
+ qmlProfilerModelProxy.traceStartTime() +
+ qmlProfilerModelProxy.traceDuration()/10);
+ }
}
+
// ***** functions
function gotoSourceLocation(file,line,column) {
- root.fileName = file;
- root.lineNumber = line;
- root.columnNumber = column;
- root.updateCursorPosition();
+ if (file !== undefined) {
+ root.fileName = file;
+ root.lineNumber = line;
+ root.columnNumber = column;
+ root.updateCursorPosition();
+ }
}
function clearData() {
@@ -186,10 +182,10 @@ Rectangle {
function updateWindowLength(absoluteFactor) {
var windowLength = view.endTime - view.startTime;
- if (qmlProfilerDataModel.traceEndTime() <= qmlProfilerDataModel.traceStartTime() ||
+ if (qmlProfilerModelProxy.traceEndTime() <= qmlProfilerModelProxy.traceStartTime() ||
windowLength <= 0)
return;
- var currentFactor = windowLength / qmlProfilerDataModel.traceDuration();
+ var currentFactor = windowLength / qmlProfilerModelProxy.traceDuration();
updateZoom(absoluteFactor / currentFactor);
}
@@ -200,8 +196,8 @@ Rectangle {
windowLength = min_length;
var newWindowLength = windowLength * relativeFactor;
- if (newWindowLength > qmlProfilerDataModel.traceDuration()) {
- newWindowLength = qmlProfilerDataModel.traceDuration();
+ if (newWindowLength > qmlProfilerModelProxy.traceDuration()) {
+ newWindowLength = qmlProfilerModelProxy.traceDuration();
relativeFactor = newWindowLength / windowLength;
}
if (newWindowLength < min_length) {
@@ -210,13 +206,15 @@ Rectangle {
}
var fixedPoint = (view.startTime + view.endTime) / 2;
+
if (view.selectedItem !== -1) {
// center on selected item if it's inside the current screen
- var newFixedPoint = qmlProfilerDataModel.getStartTime(view.selectedItem);
+ var newFixedPoint = qmlProfilerModelProxy.getStartTime(view.selectedModel, view.selectedItem);
if (newFixedPoint >= view.startTime && newFixedPoint < view.endTime)
fixedPoint = newFixedPoint;
}
+
var startTime = fixedPoint - relativeFactor*(fixedPoint - view.startTime);
zoomControl.setRange(startTime, startTime + newWindowLength);
}
@@ -229,8 +227,8 @@ Rectangle {
windowLength = min_length;
var newWindowLength = windowLength * relativeFactor;
- if (newWindowLength > qmlProfilerDataModel.traceDuration()) {
- newWindowLength = qmlProfilerDataModel.traceDuration();
+ if (newWindowLength > qmlProfilerModelProxy.traceDuration()) {
+ newWindowLength = qmlProfilerModelProxy.traceDuration();
relativeFactor = newWindowLength / windowLength;
}
if (newWindowLength < min_length) {
@@ -248,26 +246,27 @@ Rectangle {
var newStart = Math.floor(centerPoint - windowLength/2);
if (newStart < 0)
newStart = 0;
- if (newStart + windowLength > qmlProfilerDataModel.traceEndTime())
- newStart = qmlProfilerDataModel.traceEndTime() - windowLength;
+ if (newStart + windowLength > qmlProfilerModelProxy.traceEndTime())
+ newStart = qmlProfilerModelProxy.traceEndTime() - windowLength;
zoomControl.setRange(newStart, newStart + windowLength);
}
- function recenterOnItem( itemIndex )
+ function recenterOnItem( modelIndex, itemIndex )
{
if (itemIndex === -1)
return;
// if item is outside of the view, jump back to its position
- if (qmlProfilerDataModel.getEndTime(itemIndex) < view.startTime ||
- qmlProfilerDataModel.getStartTime(itemIndex) > view.endTime) {
- recenter((qmlProfilerDataModel.getStartTime(itemIndex) +
- qmlProfilerDataModel.getEndTime(itemIndex)) / 2);
+ if (qmlProfilerModelProxy.getEndTime(modelIndex, itemIndex) < view.startTime ||
+ qmlProfilerModelProxy.getStartTime(modelIndex, itemIndex) > view.endTime) {
+ recenter((qmlProfilerModelProxy.getStartTime(modelIndex, itemIndex) +
+ qmlProfilerModelProxy.getEndTime(modelIndex, itemIndex)) / 2);
}
+
}
function wheelZoom(wheelCenter, wheelDelta) {
- if (qmlProfilerDataModel.traceEndTime() > qmlProfilerDataModel.traceStartTime() &&
+ if (qmlProfilerModelProxy.traceEndTime() > qmlProfilerModelProxy.traceStartTime() &&
wheelDelta !== 0) {
if (wheelDelta>0)
updateZoomCentered(wheelCenter, 1/1.2);
@@ -280,24 +279,35 @@ Rectangle {
rangeDetails.visible = false;
rangeDetails.duration = "";
rangeDetails.label = "";
- rangeDetails.type = "";
+ //rangeDetails.type = "";
rangeDetails.file = "";
rangeDetails.line = -1;
rangeDetails.column = 0;
rangeDetails.isBindingLoop = false;
}
- function selectNextWithId( eventId )
+ function selectNextByHash(hash) {
+ var eventId = qmlProfilerModelProxy.getEventIdForHash(hash);
+ if (eventId !== -1) {
+ selectNextById(eventId);
+ }
+ }
+
+ function selectNextById(eventId)
{
+ // this is a slot responding to events from the other pane
+ // which tracks only events from the basic model
if (!lockItemSelection) {
lockItemSelection = true;
- var itemIndex = view.nextItemFromId( eventId );
+ var modelIndex = qmlProfilerModelProxy.basicModelIndex();
+ var itemIndex = view.nextItemFromId( modelIndex, eventId );
// select an item, lock to it, and recenter if necessary
- if (view.selectedItem != itemIndex) {
+ if (view.selectedItem != itemIndex || view.selectedModel != modelIndex) {
+ view.selectedModel = modelIndex;
view.selectedItem = itemIndex;
if (itemIndex !== -1) {
view.selectionLocked = true;
- recenterOnItem(itemIndex);
+ recenterOnItem(modelIndex, itemIndex);
}
}
lockItemSelection = false;
@@ -317,7 +327,9 @@ Rectangle {
onSelectedItemChanged: {
if (selectedItem != -1 && !lockItemSelection) {
lockItemSelection = true;
- selectedEventChanged( qmlProfilerDataModel.getEventId(selectedItem) );
+ // update in other views
+ var eventLocation = qmlProfilerModelProxy.getEventLocation(view.selectedModel, view.selectedItem);
+ gotoSourceLocation(eventLocation.file, eventLocation.line, eventLocation.column);
lockItemSelection = false;
}
}
@@ -392,21 +404,21 @@ Rectangle {
TimelineRenderer {
id: view
- profilerDataModel: qmlProfilerDataModel
+ profilerModelProxy: qmlProfilerModelProxy
x: flick.contentX
width: flick.width
height: root.height
- property variant startX: 0
+ property real startX: 0
onStartXChanged: {
var newStartTime = Math.round(startX * (endTime - startTime) / flick.width) +
- qmlProfilerDataModel.traceStartTime();
+ qmlProfilerModelProxy.traceStartTime();
if (Math.abs(newStartTime - startTime) > 1) {
var newEndTime = Math.round((startX+flick.width) *
(endTime - startTime) /
flick.width) +
- qmlProfilerDataModel.traceStartTime();
+ qmlProfilerModelProxy.traceStartTime();
zoomControl.setRange(newStartTime, newEndTime);
}
@@ -418,7 +430,7 @@ Rectangle {
if (start !== startTime || end !== endTime) {
startTime = start;
endTime = end;
- var newStartX = (startTime - qmlProfilerDataModel.traceStartTime()) *
+ var newStartX = (startTime - qmlProfilerModelProxy.traceStartTime()) *
flick.width / (endTime-startTime);
if (Math.abs(newStartX - startX) >= 1)
startX = newStartX;
@@ -428,32 +440,26 @@ Rectangle {
onSelectedItemChanged: {
if (selectedItem !== -1) {
// display details
- rangeDetails.duration = qmlProfilerDataModel.getDuration(selectedItem)/1000.0;
- rangeDetails.label = qmlProfilerDataModel.getDetails(selectedItem);
- rangeDetails.file = qmlProfilerDataModel.getFilename(selectedItem);
- rangeDetails.line = qmlProfilerDataModel.getLine(selectedItem);
- rangeDetails.column = qmlProfilerDataModel.getColumn(selectedItem);
- rangeDetails.type = root.names[qmlProfilerDataModel.getType(selectedItem)];
- rangeDetails.isBindingLoop = qmlProfilerDataModel.getBindingLoopDest(selectedItem)!==-1;
-
- rangeDetails.visible = true;
+ rangeDetails.showInfo(qmlProfilerModelProxy.getEventDetails(selectedModel, selectedItem));
+ rangeDetails.setLocation(qmlProfilerModelProxy.getEventLocation(selectedModel, selectedItem));
// center view (horizontally)
var windowLength = view.endTime - view.startTime;
- var eventStartTime = qmlProfilerDataModel.getStartTime(selectedItem);
+ var eventStartTime = qmlProfilerModelProxy.getStartTime(selectedModel, selectedItem);
var eventEndTime = eventStartTime +
- qmlProfilerDataModel.getDuration(selectedItem);
+ qmlProfilerModelProxy.getDuration(selectedModel, selectedItem);
if (eventEndTime < view.startTime || eventStartTime > view.endTime) {
var center = (eventStartTime + eventEndTime)/2;
- var from = Math.min(qmlProfilerDataModel.traceEndTime()-windowLength,
+ var from = Math.min(qmlProfilerModelProxy.traceEndTime()-windowLength,
Math.max(0, Math.floor(center - windowLength/2)));
zoomControl.setRange(from, from + windowLength);
+
}
// center view (vertically)
- var itemY = view.getYPosition(selectedItem);
+ var itemY = view.getYPosition(selectedModel, selectedItem);
if (itemY < root.scrollY) {
root.updateVerticalScroll(itemY);
} else
@@ -462,17 +468,16 @@ Rectangle {
root.updateVerticalScroll(itemY + root.singleRowHeight -
root.candidateHeight);
}
+
} else {
root.hideRangeDetails();
}
}
onItemPressed: {
- if (pressedItem !== -1) {
- root.gotoSourceLocation(qmlProfilerDataModel.getFilename(pressedItem),
- qmlProfilerDataModel.getLine(pressedItem),
- qmlProfilerDataModel.getColumn(pressedItem));
- }
+ var location = qmlProfilerModelProxy.getEventLocation(modelIndex, pressedItem);
+ if (location.hasOwnProperty("file")) // not empty
+ root.gotoSourceLocation(location.file, location.line, location.column);
}
// hack to pass mouse events to the other mousearea if enabled
@@ -497,7 +502,7 @@ Rectangle {
onPressed: {
selectionRange.pressedOnCreation();
}
- onMousePositionChanged: {
+ onPositionChanged: {
selectionRange.movedOnCreation();
}
}
@@ -522,17 +527,13 @@ Rectangle {
color: "#dcdcdc"
height: col.height
- property int rowCount: 5
- property variant rowExpanded: [false,false,false,false,false];
+ property int rowCount: qmlProfilerModelProxy.categories();
Column {
id: col
Repeater {
model: labels.rowCount
- delegate: Label {
- text: root.names[index]
- height: labels.height/labels.rowCount
- }
+ delegate: Label { }
}
}
}
diff --git a/src/plugins/qmlprofiler/qml/Overview.js b/src/plugins/qmlprofiler/qml/Overview.js
index 06b4d7c91d..4ef2187b43 100644
--- a/src/plugins/qmlprofiler/qml/Overview.js
+++ b/src/plugins/qmlprofiler/qml/Overview.js
@@ -29,7 +29,7 @@
.pragma library
-var qmlProfilerDataModel = 0;
+var qmlProfilerModelProxy = 0;
//draw background of the graph
function drawGraph(canvas, ctxt, region)
@@ -41,89 +41,82 @@ function drawGraph(canvas, ctxt, region)
//draw the actual data to be graphed
function drawData(canvas, ctxt, region)
{
- if ((!qmlProfilerDataModel) || qmlProfilerDataModel.count() == 0)
+ if ((!qmlProfilerModelProxy) || qmlProfilerModelProxy.count() == 0)
return;
- var typeCount = 5;
var width = canvas.width;
var bump = 10;
var height = canvas.height - bump;
+
+ var typeCount = qmlProfilerModelProxy.visibleCategories();
var blockHeight = height / typeCount;
- var spacing = width / qmlProfilerDataModel.traceDuration();
-
- var highest = [0,0,0,0,0]; // note: change if typeCount changes
-
- for (var ii = 0; ii < qmlProfilerDataModel.count(); ++ii) {
-
- var xx = (qmlProfilerDataModel.getStartTime(ii) -
- qmlProfilerDataModel.traceStartTime()) * spacing;
- if (xx > region.x + region.width)
- continue;
-
- var eventWidth = qmlProfilerDataModel.getDuration(ii) * spacing;
- if (xx + eventWidth < region.x)
- continue;
-
- if (eventWidth < 1)
- eventWidth = 1;
-
- xx = Math.round(xx);
- var ty = qmlProfilerDataModel.getType(ii);
- if (xx + eventWidth > highest[ty]) {
- // special: animations
- if (ty === 0 && qmlProfilerDataModel.getAnimationCount(ii) >= 0) {
- var vertScale = qmlProfilerDataModel.getMaximumAnimationCount() -
- qmlProfilerDataModel.getMinimumAnimationCount();
- if (vertScale < 1)
- vertScale = 1;
- var fraction = (qmlProfilerDataModel.getAnimationCount(ii) -
- qmlProfilerDataModel.getMinimumAnimationCount()) / vertScale;
- var eventHeight = blockHeight * (fraction * 0.85 + 0.15);
- var yy = bump + ty*blockHeight + blockHeight - eventHeight;
-
- var fpsFraction = qmlProfilerDataModel.getFramerate(ii) / 60.0;
- if (fpsFraction > 1.0)
- fpsFraction = 1.0;
- ctxt.fillStyle = "hsl("+(fpsFraction*0.27+0.028)+",0.3,0.65)";
- ctxt.fillRect(xx, yy, eventWidth, eventHeight);
- } else {
- var hue = ( qmlProfilerDataModel.getEventId(ii) * 25 ) % 360;
- ctxt.fillStyle = "hsl("+(hue/360.0+0.001)+",0.3,0.65)";
- ctxt.fillRect(xx, bump + ty*blockHeight, eventWidth, blockHeight);
- }
- highest[ty] = xx+eventWidth;
+ var spacing = width / qmlProfilerModelProxy.traceDuration();
+
+ var modelRowStart = 0;
+ for (var modelIndex = 0; modelIndex < qmlProfilerModelProxy.modelCount(); modelIndex++) {
+ for (var ii = 0; ii < qmlProfilerModelProxy.count(modelIndex); ++ii) {
+
+ var xx = (qmlProfilerModelProxy.getStartTime(modelIndex,ii) -
+ qmlProfilerModelProxy.traceStartTime()) * spacing;
+ if (xx > region.x + region.width)
+ continue;
+
+ var eventWidth = qmlProfilerModelProxy.getDuration(modelIndex,ii) * spacing;
+ if (xx + eventWidth < region.x)
+ continue;
+
+ if (eventWidth < 1)
+ eventWidth = 1;
+
+ xx = Math.round(xx);
+
+ var rowNumber = modelRowStart + qmlProfilerModelProxy.getEventCategoryInModel(modelIndex, ii);
+
+ var itemHeight = qmlProfilerModelProxy.getHeight(modelIndex,ii) * blockHeight;
+ var yy = (rowNumber + 1) * blockHeight - itemHeight ;
+
+ var itemColor = qmlProfilerModelProxy.getColorRGB(modelIndex, ii);
+ ctxt.fillStyle = "rgb("+itemColor[0]+","+itemColor[1]+","+itemColor[2]+")";
+ ctxt.fillRect(xx, bump + yy, eventWidth, itemHeight);
}
+ modelRowStart += qmlProfilerModelProxy.categoryCount(modelIndex);
}
// binding loops
ctxt.strokeStyle = "orange";
ctxt.lineWidth = 2;
var radius = 1;
- for (var ii = 0; ii < qmlProfilerDataModel.count(); ++ii) {
- if (qmlProfilerDataModel.getBindingLoopDest(ii) >= 0) {
- var xcenter = Math.round(qmlProfilerDataModel.getStartTime(ii) +
- qmlProfilerDataModel.getDuration(ii) -
- qmlProfilerDataModel.traceStartTime()) * spacing;
- var ycenter = Math.round(bump + qmlProfilerDataModel.getType(ii) *
- blockHeight + blockHeight/2);
- ctxt.arc(xcenter, ycenter, radius, 0, 2*Math.PI, true);
- ctxt.stroke();
+ modelRowStart = 0;
+ for (modelIndex = 0; modelIndex < qmlProfilerModelProxy.modelCount(); modelIndex++) {
+ for (ii = 0; ii < qmlProfilerModelProxy.count(modelIndex); ++ii) {
+ if (qmlProfilerModelProxy.getBindingLoopDest(modelIndex,ii) >= 0) {
+ var xcenter = Math.round(qmlProfilerModelProxy.getStartTime(modelIndex,ii) +
+ qmlProfilerModelProxy.getDuration(modelIndex,ii) -
+ qmlProfilerModelProxy.traceStartTime()) * spacing;
+ var ycenter = Math.round(bump + (modelRowStart +
+ qmlProfilerModelProxy.getEventCategoryInModel(modelIndex, ii)) *
+ blockHeight + blockHeight/2);
+ ctxt.arc(xcenter, ycenter, radius, 0, 2*Math.PI, true);
+ ctxt.stroke();
+ }
}
+ modelRowStart += qmlProfilerModelProxy.categoryCount(modelIndex);
}
+
}
function drawTimeBar(canvas, ctxt, region)
{
- if (!qmlProfilerDataModel)
+ if (!qmlProfilerModelProxy)
return;
var width = canvas.width;
var height = 10;
- var startTime = qmlProfilerDataModel.traceStartTime();
- var endTime = qmlProfilerDataModel.traceEndTime();
+ var startTime = qmlProfilerModelProxy.traceStartTime();
+ var endTime = qmlProfilerModelProxy.traceEndTime();
- var totalTime = qmlProfilerDataModel.traceDuration();
+ var totalTime = qmlProfilerModelProxy.traceDuration();
var spacing = width / totalTime;
var initialBlockLength = 120;
diff --git a/src/plugins/qmlprofiler/qml/Overview.qml b/src/plugins/qmlprofiler/qml/Overview.qml
index 65686be9de..bf94a56a09 100644
--- a/src/plugins/qmlprofiler/qml/Overview.qml
+++ b/src/plugins/qmlprofiler/qml/Overview.qml
@@ -27,7 +27,7 @@
**
****************************************************************************/
-import QtQuick 1.0
+import QtQuick 2.1
import Monitor 1.0
import "Overview.js" as Plotter
@@ -36,36 +36,37 @@ Canvas2D {
// ***** properties
height: 50
- property bool dataAvailable: false
- property variant startTime : 0
- property variant endTime : 0
+ property bool dataReady: false
+ property real startTime : 0
+ property real endTime : 0
// ***** functions
function clearDisplay()
{
- dataAvailable = false;
+ dataReady = false;
requestRedraw();
}
function updateRange() {
- var newStartTime = Math.round(rangeMover.x * qmlProfilerDataModel.traceDuration() / width) + qmlProfilerDataModel.traceStartTime();
- var newEndTime = Math.round((rangeMover.x + rangeMover.width) * qmlProfilerDataModel.traceDuration() / width) + qmlProfilerDataModel.traceStartTime();
+ var newStartTime = Math.round(rangeMover.x * qmlProfilerModelProxy.traceDuration() / width) + qmlProfilerModelProxy.traceStartTime();
+ var newEndTime = Math.round((rangeMover.x + rangeMover.width) * qmlProfilerModelProxy.traceDuration() / width) + qmlProfilerModelProxy.traceStartTime();
if (startTime !== newStartTime || endTime !== newEndTime) {
zoomControl.setRange(newStartTime, newEndTime);
}
+
}
// ***** connections to external objects
Connections {
target: zoomControl
onRangeChanged: {
- if (qmlProfilerDataModel) {
+ if (qmlProfilerModelProxy) {
startTime = zoomControl.startTime();
endTime = zoomControl.endTime();
- var newRangeX = (startTime - qmlProfilerDataModel.traceStartTime()) * width / qmlProfilerDataModel.traceDuration();
+ var newRangeX = (startTime - qmlProfilerModelProxy.traceStartTime()) * width / qmlProfilerModelProxy.traceDuration();
if (rangeMover.x !== newRangeX)
rangeMover.x = newRangeX;
- var newWidth = (endTime-startTime) * width / qmlProfilerDataModel.traceDuration();
+ var newWidth = (endTime-startTime) * width / qmlProfilerModelProxy.traceDuration();
if (rangeMover.width !== newWidth)
rangeMover.width = newWidth;
}
@@ -73,20 +74,18 @@ Canvas2D {
}
Connections {
- target: qmlProfilerDataModel
- onStateChanged: {
- // State is "done"
- if (qmlProfilerDataModel.getCurrentStateFromQml() == 3) {
- dataAvailable = true;
+ target: qmlProfilerModelProxy
+ onDataAvailable: {
+ dataReady = true;
requestRedraw();
- }
}
}
+
// ***** slots
onDrawRegion: {
- Plotter.qmlProfilerDataModel = qmlProfilerDataModel;
- if (dataAvailable) {
+ Plotter.qmlProfilerModelProxy = qmlProfilerModelProxy;
+ if (dataReady) {
Plotter.plot(canvas, ctxt, region);
} else {
Plotter.drawGraph(canvas, ctxt, region) //just draw the background
@@ -109,14 +108,14 @@ Canvas2D {
onPressed: {
jumpTo(mouse.x);
}
- onMousePositionChanged: {
+ onPositionChanged: {
jumpTo(mouse.x);
}
}
RangeMover {
id: rangeMover
- visible: dataAvailable
+ visible: dataReady
}
Rectangle {
diff --git a/src/plugins/qmlprofiler/qml/RangeDetails.qml b/src/plugins/qmlprofiler/qml/RangeDetails.qml
index 965458c690..2fe6e398f2 100644
--- a/src/plugins/qmlprofiler/qml/RangeDetails.qml
+++ b/src/plugins/qmlprofiler/qml/RangeDetails.qml
@@ -27,7 +27,7 @@
**
****************************************************************************/
-import QtQuick 1.0
+import QtQuick 2.1
import Monitor 1.0
Item {
@@ -35,7 +35,7 @@ Item {
property string duration
property string label
- property string type
+ property string dialogTitle
property string file
property int line
property int column
@@ -65,6 +65,36 @@ Item {
onCandidateHeightChanged: fitInView();
}
+ //property int eventInfo
+
+ ListModel {
+ id: eventInfo
+ }
+
+ function showInfo(eventData) {
+ eventInfo.clear();
+ rangeDetails.dialogTitle = eventData[0]["title"];
+ for (var i = 1; i < eventData.length; i++) {
+ for (var k in eventData[i]) {
+ eventInfo.append({"key": k, "value":eventData[i][k]});
+ }
+ }
+ rangeDetails.visible = true;
+ }
+
+ function setLocation(location) {
+ if (location.hasOwnProperty("file")) { // not empty
+ file = location.file;
+ line = location.line;
+ column = location.column;
+ } else {
+ // reset to default values
+ file = "";
+ line = 0;
+ column = -1;
+ }
+ }
+
function fitInView() {
// don't reposition if it does not fit
if (root.width < width || root.candidateHeight < height)
@@ -122,7 +152,7 @@ Item {
//title
Text {
id: typeTitle
- text: " "+rangeDetails.type
+ text: " "+rangeDetails.dialogTitle
font.bold: true
height: 18
y: 2
@@ -145,42 +175,14 @@ Item {
id: col
x: 10
y: 5
- Detail {
- label: qsTr("Duration:")
- content: rangeDetails.duration < 1000 ? rangeDetails.duration + "μs" : Math.floor(rangeDetails.duration/10)/100 + "ms"
- }
- Detail {
- opacity: content.length !== 0 ? 1 : 0
- label: qsTr("Details:")
- content: {
- var inputString = rangeDetails.label;
- if (inputString.length > 7 && inputString.substring(0,7) == "file://") {
- var pos = inputString.lastIndexOf("/");
- return inputString.substr(pos+1);
- }
- var maxLen = 40;
- if (inputString.length > maxLen)
- inputString = inputString.substring(0,maxLen)+"...";
-
- return inputString;
- }
- }
- Detail {
- opacity: content.length !== 0 ? 1 : 0
- label: qsTr("Location:")
- content: {
- var file = rangeDetails.file;
- var pos = file.lastIndexOf("/");
- if (pos != -1)
- file = file.substr(pos+1);
- return (file.length !== 0) ? (file + ":" + rangeDetails.line) : "";
+
+ Repeater {
+ model: eventInfo
+ Detail {
+ label: key
+ content: value
}
}
- Detail {
- visible: isBindingLoop
- opacity: content.length != 0 ? 1 : 0
- label: qsTr("Binding loop detected")
- }
}
}
@@ -194,7 +196,7 @@ Item {
drag.maximumY: root.candidateHeight - parent.height + yoffset
onClicked: {
root.gotoSourceLocation(file, line, column);
- root.recenterOnItem(view.selectedItem);
+ root.recenterOnItem(view.selectedModel, view.selectedItem);
}
}
diff --git a/src/plugins/qmlprofiler/qml/RangeMover.qml b/src/plugins/qmlprofiler/qml/RangeMover.qml
index 18226d8d25..5c786153db 100644
--- a/src/plugins/qmlprofiler/qml/RangeMover.qml
+++ b/src/plugins/qmlprofiler/qml/RangeMover.qml
@@ -27,7 +27,7 @@
**
****************************************************************************/
-import QtQuick 1.0
+import QtQuick 2.1
Rectangle {
id: rangeMover
diff --git a/src/plugins/qmlprofiler/qml/SelectionRange.qml b/src/plugins/qmlprofiler/qml/SelectionRange.qml
index cd8c986ddd..1e12458c7e 100644
--- a/src/plugins/qmlprofiler/qml/SelectionRange.qml
+++ b/src/plugins/qmlprofiler/qml/SelectionRange.qml
@@ -27,7 +27,7 @@
**
****************************************************************************/
-import QtQuick 1.0
+import QtQuick 2.1
Rectangle {
id: selectionRange
@@ -47,15 +47,15 @@ Rectangle {
property string endTimeString: detailedPrintTime(startTime+duration)
property string durationString: detailedPrintTime(duration)
- property variant startTime: x * selectionRange.viewTimePerPixel + qmlProfilerDataModel.traceStartTime()
- property variant duration: width * selectionRange.viewTimePerPixel
- property variant viewTimePerPixel: 1
- property variant creationState : 0
+ property real startTime: x * selectionRange.viewTimePerPixel + qmlProfilerModelProxy.traceStartTime()
+ property real duration: width * selectionRange.viewTimePerPixel
+ property real viewTimePerPixel: 1
+ property int creationState : 0
- property variant x1
- property variant x2
- property variant x3: Math.min(x1, x2)
- property variant x4: Math.max(x1, x2)
+ property real x1
+ property real x2
+ property real x3: Math.min(x1, x2)
+ property real x4: Math.max(x1, x2)
property bool isDragging: false
diff --git a/src/plugins/qmlprofiler/qml/SelectionRangeDetails.qml b/src/plugins/qmlprofiler/qml/SelectionRangeDetails.qml
index 5af24af14d..c7e281bf08 100644
--- a/src/plugins/qmlprofiler/qml/SelectionRangeDetails.qml
+++ b/src/plugins/qmlprofiler/qml/SelectionRangeDetails.qml
@@ -27,7 +27,7 @@
**
****************************************************************************/
-import QtQuick 1.0
+import QtQuick 2.1
import Monitor 1.0
Item {
diff --git a/src/plugins/qmlprofiler/qml/TimeDisplay.qml b/src/plugins/qmlprofiler/qml/TimeDisplay.qml
index 2f5a8bfaaf..b962222481 100644
--- a/src/plugins/qmlprofiler/qml/TimeDisplay.qml
+++ b/src/plugins/qmlprofiler/qml/TimeDisplay.qml
@@ -27,15 +27,15 @@
**
****************************************************************************/
-import QtQuick 1.0
+import QtQuick 2.1
import Monitor 1.0
Canvas2D {
id: timeDisplay
- property variant startTime : 0
- property variant endTime : 0
- property variant timePerPixel: 0
+ property real startTime : 0
+ property real endTime : 0
+ property real timePerPixel: 0
Component.onCompleted: {
diff --git a/src/plugins/qmlprofiler/qml/TimeMarks.qml b/src/plugins/qmlprofiler/qml/TimeMarks.qml
index bb0c07e400..bee2288a30 100644
--- a/src/plugins/qmlprofiler/qml/TimeMarks.qml
+++ b/src/plugins/qmlprofiler/qml/TimeMarks.qml
@@ -27,15 +27,15 @@
**
****************************************************************************/
-import QtQuick 1.0
+import QtQuick 2.1
import Monitor 1.0
Canvas2D {
id: timeDisplay
- property variant startTime
- property variant endTime
- property variant timePerPixel
+ property real startTime
+ property real endTime
+ property real timePerPixel
Component.onCompleted: {
requestRedraw();
@@ -48,6 +48,11 @@ Canvas2D {
requestRedraw();
}
+ Connections {
+ target: labels
+ onHeightChanged: { requestRedraw(); }
+ }
+
onDrawRegion: {
drawBackgroundBars( ctxt, region );
@@ -86,19 +91,21 @@ Canvas2D {
}
}
+
// gray off out-of-bounds areas
var rectWidth;
- if (startTime < qmlProfilerDataModel.traceStartTime()) {
+ if (startTime < qmlProfilerModelProxy.traceStartTime()) {
ctxt.fillStyle = "rgba(127,127,127,0.2)";
- rectWidth = (qmlProfilerDataModel.traceStartTime() - startTime) * spacing;
+ rectWidth = (qmlProfilerModelProxy.traceStartTime() - startTime) * spacing;
ctxt.fillRect(0, 0, rectWidth, height);
}
- if (endTime > qmlProfilerDataModel.traceEndTime()) {
+ if (endTime > qmlProfilerModelProxy.traceEndTime()) {
ctxt.fillStyle = "rgba(127,127,127,0.2)";
- var rectX = (qmlProfilerDataModel.traceEndTime() - startTime) * spacing;
- rectWidth = (endTime - qmlProfilerDataModel.traceEndTime()) * spacing;
+ var rectX = (qmlProfilerModelProxy.traceEndTime() - startTime) * spacing;
+ rectWidth = (endTime - qmlProfilerModelProxy.traceEndTime()) * spacing;
ctxt.fillRect(rectX, 0, rectWidth, height);
}
+
}
function updateMarks(start, end) {
@@ -121,16 +128,16 @@ Canvas2D {
// separators
var cumulatedHeight = 0;
- for (var i=0; i<labels.rowCount; i++) {
- cumulatedHeight += root.singleRowHeight + (labels.rowExpanded[i] ?
- qmlProfilerDataModel.uniqueEventsOfType(i) * root.singleRowHeight :
- qmlProfilerDataModel.maxNestingForType(i) * root.singleRowHeight);
+ for (var modelIndex = 0; modelIndex < qmlProfilerModelProxy.modelCount(); modelIndex++) {
+ for (var i=0; i<qmlProfilerModelProxy.categoryCount(modelIndex); i++) {
+ cumulatedHeight += root.singleRowHeight * qmlProfilerModelProxy.categoryDepth(modelIndex, i);
- ctxt.strokeStyle = "#B0B0B0";
- ctxt.beginPath();
- ctxt.moveTo(0, cumulatedHeight);
- ctxt.lineTo(width, cumulatedHeight);
- ctxt.stroke();
+ ctxt.strokeStyle = "#B0B0B0";
+ ctxt.beginPath();
+ ctxt.moveTo(0, cumulatedHeight);
+ ctxt.lineTo(width, cumulatedHeight);
+ ctxt.stroke();
+ }
}
// bottom
diff --git a/src/plugins/qmlprofiler/qmlprofiler.pro b/src/plugins/qmlprofiler/qmlprofiler.pro
index d644e47527..f5b68699d5 100644
--- a/src/plugins/qmlprofiler/qmlprofiler.pro
+++ b/src/plugins/qmlprofiler/qmlprofiler.pro
@@ -1,6 +1,6 @@
DEFINES += QMLPROFILER_LIBRARY
-QT += network script declarative
+QT += network qml quick
include(../../qtcreatorplugin.pri)
include(canvas/canvas.pri)
@@ -12,16 +12,26 @@ SOURCES += \
qmlprofilerattachdialog.cpp \
localqmlprofilerrunner.cpp \
qmlprofilereventview.cpp \
+ qv8profilereventview.cpp \
qmlprofilerdetailsrewriter.cpp \
qmlprofilertraceview.cpp \
timelinerenderer.cpp \
qmlprofilerstatemanager.cpp \
qv8profilerdatamodel.cpp \
- qmlprofilerdatamodel.cpp \
qmlprofilerclientmanager.cpp \
qmlprofilerviewmanager.cpp \
qmlprofilerstatewidget.cpp \
- qmlprofilerruncontrolfactory.cpp
+ qmlprofilerruncontrolfactory.cpp \
+ qmlprofilermodelmanager.cpp \
+ qmlprofilersimplemodel.cpp \
+ qmlprofilerprocessedmodel.cpp \
+ qmlprofilereventsmodelproxy.cpp \
+ qmlprofilertimelinemodelproxy.cpp \
+ qmlprofilertreeview.cpp \
+ qmlprofilertracefile.cpp \
+ abstracttimelinemodel.cpp \
+ timelinemodelaggregator.cpp \
+ qmlprofilerpainteventsmodelproxy.cpp
HEADERS += \
qmlprofilerconstants.h \
@@ -33,16 +43,26 @@ HEADERS += \
abstractqmlprofilerrunner.h \
localqmlprofilerrunner.h \
qmlprofilereventview.h \
+ qv8profilereventview.h \
qmlprofilerdetailsrewriter.h \
qmlprofilertraceview.h \
timelinerenderer.h \
qmlprofilerstatemanager.h \
qv8profilerdatamodel.h \
- qmlprofilerdatamodel.h \
qmlprofilerclientmanager.h \
qmlprofilerviewmanager.h \
qmlprofilerstatewidget.h \
- qmlprofilerruncontrolfactory.h
+ qmlprofilerruncontrolfactory.h \
+ qmlprofilermodelmanager.h \
+ qmlprofilersimplemodel.h \
+ qmlprofilerprocessedmodel.h \
+ qmlprofilereventsmodelproxy.h \
+ qmlprofilertimelinemodelproxy.h \
+ qmlprofilertreeview.h \
+ qmlprofilertracefile.h \
+ abstracttimelinemodel.h \
+ timelinemodelaggregator.h \
+ qmlprofilerpainteventsmodelproxy.h
RESOURCES += \
qml/qmlprofiler.qrc
diff --git a/src/plugins/qmlprofiler/qmlprofiler.qbs b/src/plugins/qmlprofiler/qmlprofiler.qbs
index 4550ec894f..2670654cf6 100644
--- a/src/plugins/qmlprofiler/qmlprofiler.qbs
+++ b/src/plugins/qmlprofiler/qmlprofiler.qbs
@@ -4,11 +4,12 @@ import "../QtcPlugin.qbs" as QtcPlugin
QtcPlugin {
name: "QmlProfiler"
+ minimumQtVersion: "5.1"
- Depends { name: "Qt"; submodules: ["widgets", "network", "script", "declarative"] }
+ Depends { name: "Qt"; submodules: ["widgets", "network"] }
+ Depends { name: "Qt.quick"; condition: product.condition; }
Depends { name: "Core" }
Depends { name: "AnalyzerBase" }
- Depends { name: "Debugger" }
Depends { name: "QmlProjectManager" }
Depends { name: "Qt4ProjectManager" }
Depends { name: "RemoteLinux" }
@@ -20,63 +21,68 @@ QtcPlugin {
Depends { name: "QmlJSTools" }
Depends { name: "CPlusPlus" }
- cpp.includePaths: base.concat("canvas")
+ Group {
+ name: "General"
+ files: [
+ "abstractqmlprofilerrunner.h",
+ "abstracttimelinemodel.h", "abstracttimelinemodel.cpp",
+ "localqmlprofilerrunner.cpp", "localqmlprofilerrunner.h",
+ "qmlprofiler_global.h",
+ "qmlprofilerattachdialog.cpp", "qmlprofilerattachdialog.h",
+ "qmlprofilerclientmanager.cpp", "qmlprofilerclientmanager.h",
+ "qmlprofilerconstants.h",
+ "qmlprofilerdetailsrewriter.cpp", "qmlprofilerdetailsrewriter.h",
+ "qmlprofilerengine.cpp", "qmlprofilerengine.h",
+ "qmlprofilereventsmodelproxy.cpp", "qmlprofilereventsmodelproxy.h",
+ "qmlprofilereventview.cpp", "qmlprofilereventview.h",
+ "qmlprofilermodelmanager.cpp", "qmlprofilermodelmanager.h",
+ "qmlprofilerpainteventsmodelproxy.h", "qmlprofilerpainteventsmodelproxy.cpp",
+ "qmlprofilerplugin.cpp", "qmlprofilerplugin.h",
+ "qmlprofilerprocessedmodel.cpp", "qmlprofilerprocessedmodel.h",
+ "qmlprofilerruncontrolfactory.cpp", "qmlprofilerruncontrolfactory.h",
+ "qmlprofilersimplemodel.cpp", "qmlprofilersimplemodel.h",
+ "qmlprofilerstatemanager.cpp", "qmlprofilerstatemanager.h",
+ "qmlprofilerstatewidget.cpp", "qmlprofilerstatewidget.h",
+ "qmlprofilertimelinemodelproxy.cpp", "qmlprofilertimelinemodelproxy.h",
+ "qmlprofilertool.cpp", "qmlprofilertool.h",
+ "qmlprofilertracefile.cpp", "qmlprofilertracefile.h",
+ "qmlprofilertraceview.cpp", "qmlprofilertraceview.h",
+ "qmlprofilertreeview.cpp", "qmlprofilertreeview.h",
+ "qmlprofilerviewmanager.cpp", "qmlprofilerviewmanager.h",
+ "qv8profilerdatamodel.cpp", "qv8profilerdatamodel.h",
+ "qv8profilereventview.h", "qv8profilereventview.cpp",
+ "timelinemodelaggregator.cpp", "timelinemodelaggregator.h",
+ "timelinerenderer.cpp", "timelinerenderer.h",
+ ]
+ }
- files: [
- "abstractqmlprofilerrunner.h",
- "localqmlprofilerrunner.cpp",
- "localqmlprofilerrunner.h",
- "qmlprofiler_global.h",
- "qmlprofilerattachdialog.cpp",
- "qmlprofilerattachdialog.h",
- "qmlprofilerclientmanager.cpp",
- "qmlprofilerclientmanager.h",
- "qmlprofilerconstants.h",
- "qmlprofilerdatamodel.cpp",
- "qmlprofilerdatamodel.h",
- "qmlprofilerdetailsrewriter.cpp",
- "qmlprofilerdetailsrewriter.h",
- "qmlprofilerengine.cpp",
- "qmlprofilerengine.h",
- "qmlprofilereventview.cpp",
- "qmlprofilereventview.h",
- "qmlprofilerplugin.cpp",
- "qmlprofilerplugin.h",
- "qmlprofilerruncontrolfactory.cpp",
- "qmlprofilerruncontrolfactory.h",
- "qmlprofilerstatemanager.cpp",
- "qmlprofilerstatemanager.h",
- "qmlprofilerstatewidget.cpp",
- "qmlprofilerstatewidget.h",
- "qmlprofilertool.cpp",
- "qmlprofilertool.h",
- "qmlprofilertraceview.cpp",
- "qmlprofilertraceview.h",
- "qmlprofilerviewmanager.cpp",
- "qmlprofilerviewmanager.h",
- "qv8profilerdatamodel.cpp",
- "qv8profilerdatamodel.h",
- "timelinerenderer.cpp",
- "timelinerenderer.h",
- "canvas/qdeclarativecanvas.cpp",
- "canvas/qdeclarativecanvas_p.h",
- "canvas/qdeclarativecanvastimer.cpp",
- "canvas/qdeclarativecanvastimer_p.h",
- "canvas/qdeclarativecontext2d.cpp",
- "canvas/qdeclarativecontext2d_p.h",
- "canvas/qmlprofilercanvas.cpp",
- "canvas/qmlprofilercanvas.h",
- "qml/Detail.qml",
- "qml/Label.qml",
- "qml/MainView.qml",
- "qml/Overview.js",
- "qml/Overview.qml",
- "qml/RangeDetails.qml",
- "qml/RangeMover.qml",
- "qml/SelectionRange.qml",
- "qml/SelectionRangeDetails.qml",
- "qml/TimeDisplay.qml",
- "qml/TimeMarks.qml",
- "qml/qmlprofiler.qrc",
- ]
+ Group {
+ name: "Canvas"
+ prefix: "canvas/"
+ files: [
+ "qdeclarativecanvas.cpp", "qdeclarativecanvas_p.h",
+ "qdeclarativecanvastimer.cpp", "qdeclarativecanvastimer_p.h",
+ "qdeclarativecontext2d.cpp", "qdeclarativecontext2d_p.h",
+ "qmlprofilercanvas.cpp", "qmlprofilercanvas.h"
+ ]
+ }
+
+ Group {
+ name: "QML"
+ prefix: "qml/"
+ files: [
+ "Detail.qml",
+ "Label.qml",
+ "MainView.qml",
+ "Overview.js",
+ "Overview.qml",
+ "RangeDetails.qml",
+ "RangeMover.qml",
+ "SelectionRange.qml",
+ "SelectionRangeDetails.qml",
+ "TimeDisplay.qml",
+ "TimeMarks.qml",
+ "qmlprofiler.qrc",
+ ]
+ }
}
diff --git a/src/plugins/qmlprofiler/qmlprofiler_dependencies.pri b/src/plugins/qmlprofiler/qmlprofiler_dependencies.pri
index 47e65ba235..f43ea85f53 100644
--- a/src/plugins/qmlprofiler/qmlprofiler_dependencies.pri
+++ b/src/plugins/qmlprofiler/qmlprofiler_dependencies.pri
@@ -5,7 +5,6 @@ QTC_LIB_DEPENDS += \
QTC_PLUGIN_DEPENDS += \
analyzerbase \
coreplugin \
- debugger \
projectexplorer \
qmlprojectmanager \
qmljstools \
diff --git a/src/plugins/qmlprofiler/qmlprofilerclientmanager.cpp b/src/plugins/qmlprofiler/qmlprofilerclientmanager.cpp
index e1855fad95..775668f7c8 100644
--- a/src/plugins/qmlprofiler/qmlprofilerclientmanager.cpp
+++ b/src/plugins/qmlprofiler/qmlprofilerclientmanager.cpp
@@ -40,17 +40,18 @@
#include <QTimer>
#include <QMessageBox>
+#include "qmlprofilermodelmanager.h"
+
using namespace QmlDebug;
using namespace Core;
namespace QmlProfiler {
namespace Internal {
-class QmlProfilerClientManager::QmlProfilerClientManagerPrivate {
+class QmlProfilerClientManager::QmlProfilerClientManagerPrivate
+{
public:
- QmlProfilerClientManagerPrivate(QmlProfilerClientManager *qq) { Q_UNUSED(qq); }
-
- QmlProfilerStateManager* profilerState;
+ QmlProfilerStateManager *profilerState;
QmlDebugConnection *connection;
QPointer<QmlProfilerTraceClient> qmlclientplugin;
@@ -70,10 +71,12 @@ public:
bool v8DataReady;
bool qmlDataReady;
+
+ QmlProfilerModelManager *modelManager;
};
QmlProfilerClientManager::QmlProfilerClientManager(QObject *parent) :
- QObject(parent), d(new QmlProfilerClientManagerPrivate(this))
+ QObject(parent), d(new QmlProfilerClientManagerPrivate)
{
setObjectName(QLatin1String("QML Profiler Connections"));
@@ -84,6 +87,8 @@ QmlProfilerClientManager::QmlProfilerClientManager(QObject *parent) :
d->v8DataReady = false;
d->qmlDataReady = false;
+ d->modelManager = 0;
+
d->connectionTimer.setInterval(200);
connect(&d->connectionTimer, SIGNAL(timeout()), SLOT(tryToConnect()));
}
@@ -97,6 +102,18 @@ QmlProfilerClientManager::~QmlProfilerClientManager()
delete d;
}
+
+void QmlProfilerClientManager::setModelManager(QmlProfilerModelManager *m)
+{
+ if (d->modelManager) {
+ disconnect(this,SIGNAL(dataReadyForProcessing()), d->modelManager, SLOT(complete()));
+ }
+ d->modelManager = m;
+ if (d->modelManager) {
+ connect(this,SIGNAL(dataReadyForProcessing()), d->modelManager, SLOT(complete()));
+ }
+}
+
////////////////////////////////////////////////////////////////
// Interface
void QmlProfilerClientManager::setTcpConnection(QString host, quint64 port)
@@ -161,15 +178,15 @@ void QmlProfilerClientManager::connectClientSignals()
connect(d->qmlclientplugin.data(), SIGNAL(complete()),
this, SLOT(qmlComplete()));
connect(d->qmlclientplugin.data(),
- SIGNAL(range(int,int,qint64,qint64,QStringList,QmlDebug::QmlEventLocation)),
- this,
- SIGNAL(addRangedEvent(int,int,qint64,qint64,QStringList,QmlDebug::QmlEventLocation)));
+ SIGNAL(rangedEvent(int,int,qint64,qint64,QStringList,QmlDebug::QmlEventLocation,
+ qint64,qint64,qint64,qint64,qint64)),
+ d->modelManager,
+ SLOT(addQmlEvent(int,int,qint64,qint64,QStringList,QmlDebug::QmlEventLocation,
+ qint64,qint64,qint64,qint64,qint64)));
connect(d->qmlclientplugin.data(), SIGNAL(traceFinished(qint64)),
- this, SIGNAL(traceFinished(qint64)));
+ d->modelManager->traceTime(), SLOT(setEndTime(qint64)));
connect(d->qmlclientplugin.data(), SIGNAL(traceStarted(qint64)),
- this, SIGNAL(traceStarted(qint64)));
- connect(d->qmlclientplugin.data(), SIGNAL(frame(qint64,int,int)),
- this, SIGNAL(addFrameEvent(qint64,int,int)));
+ d->modelManager->traceTime(), SLOT(setStartTime(qint64)));
connect(d->qmlclientplugin.data(), SIGNAL(enabledChanged()),
d->qmlclientplugin.data(), SLOT(sendRecordingStatus()));
// fixme: this should be unified for both clients
@@ -180,8 +197,8 @@ void QmlProfilerClientManager::connectClientSignals()
connect(d->v8clientplugin.data(), SIGNAL(complete()), this, SLOT(v8Complete()));
connect(d->v8clientplugin.data(),
SIGNAL(v8range(int,QString,QString,int,double,double)),
- this,
- SIGNAL(addV8Event(int,QString,QString,int,double,double)));
+ d->modelManager,
+ SLOT(addV8Event(int,QString,QString,int,double,double)));
connect(d->v8clientplugin.data(), SIGNAL(enabledChanged()),
d->v8clientplugin.data(), SLOT(sendRecordingStatus()));
}
@@ -193,15 +210,17 @@ void QmlProfilerClientManager::disconnectClientSignals()
disconnect(d->qmlclientplugin.data(), SIGNAL(complete()),
this, SLOT(qmlComplete()));
disconnect(d->qmlclientplugin.data(),
- SIGNAL(range(int,int,qint64,qint64,QStringList,QmlDebug::QmlEventLocation)),
- this,
- SIGNAL(addRangedEvent(int,int,qint64,qint64,QStringList,QmlDebug::QmlEventLocation)));
+ SIGNAL(rangedEvent(int,int,qint64,qint64,QStringList,QmlDebug::QmlEventLocation,
+ qint64,qint64,qint64,qint64,qint64)),
+ d->modelManager,
+ SLOT(addQmlEvent(int,int,qint64,qint64,QStringList,QmlDebug::QmlEventLocation,
+ qint64,qint64,qint64,qint64,qint64)));
disconnect(d->qmlclientplugin.data(), SIGNAL(traceFinished(qint64)),
- this, SIGNAL(traceFinished(qint64)));
+ d->modelManager->traceTime(), SLOT(setEndTime(qint64)));
disconnect(d->qmlclientplugin.data(), SIGNAL(traceStarted(qint64)),
- this, SIGNAL(traceStarted(qint64)));
+ d->modelManager->traceTime(), SLOT(setStartTime(qint64)));
disconnect(d->qmlclientplugin.data(), SIGNAL(frame(qint64,int,int)),
- this, SIGNAL(addFrameEvent(qint64,int,int)));
+ d->modelManager, SLOT(addFrameEvent(qint64,int,int)));
disconnect(d->qmlclientplugin.data(), SIGNAL(enabledChanged()),
d->qmlclientplugin.data(), SLOT(sendRecordingStatus()));
// fixme: this should be unified for both clients
@@ -212,8 +231,8 @@ void QmlProfilerClientManager::disconnectClientSignals()
disconnect(d->v8clientplugin.data(), SIGNAL(complete()), this, SLOT(v8Complete()));
disconnect(d->v8clientplugin.data(),
SIGNAL(v8range(int,QString,QString,int,double,double)),
- this,
- SIGNAL(addV8Event(int,QString,QString,int,double,double)));
+ d->modelManager,
+ SLOT(addV8Event(int,QString,QString,int,double,double)));
disconnect(d->v8clientplugin.data(), SIGNAL(enabledChanged()),
d->v8clientplugin.data(), SLOT(sendRecordingStatus()));
}
diff --git a/src/plugins/qmlprofiler/qmlprofilerclientmanager.h b/src/plugins/qmlprofiler/qmlprofilerclientmanager.h
index 333ef17820..c1e2f22214 100644
--- a/src/plugins/qmlprofiler/qmlprofilerclientmanager.h
+++ b/src/plugins/qmlprofiler/qmlprofilerclientmanager.h
@@ -30,13 +30,15 @@
#ifndef QMLPROFILERCLIENTMANAGER_H
#define QMLPROFILERCLIENTMANAGER_H
-#include <QObject>
-#include <QStringList>
-
#include "qmlprofilerstatemanager.h"
#include <qmldebug/qmlprofilereventlocation.h>
+#include <QObject>
+#include <QStringList>
+
namespace QmlProfiler {
+class QmlProfilerModelManager;
+
namespace Internal {
class QmlProfilerClientManager : public QObject
@@ -55,16 +57,10 @@ public:
void discardPendingData();
bool isConnected() const;
+ void setModelManager(QmlProfilerModelManager *m);
signals:
void connectionFailed();
void connectionClosed();
-
- // data
- void addRangedEvent(int,int,qint64,qint64,QStringList,QmlDebug::QmlEventLocation);
- void addV8Event(int,QString,QString,int,double,double);
- void addFrameEvent(qint64,int,int);
- void traceStarted(qint64);
- void traceFinished(qint64);
void dataReadyForProcessing();
public slots:
diff --git a/src/plugins/qmlprofiler/qmlprofilerdatamodel.cpp b/src/plugins/qmlprofiler/qmlprofilerdatamodel.cpp
deleted file mode 100644
index d6091ef9a1..0000000000
--- a/src/plugins/qmlprofiler/qmlprofilerdatamodel.cpp
+++ /dev/null
@@ -1,1689 +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 "qmlprofilerdatamodel.h"
-
-#include <QUrl>
-#include <QHash>
-#include <QtAlgorithms>
-#include <QString>
-#include <QStringList>
-
-#include <QFile>
-#include <QXmlStreamReader>
-#include <QXmlStreamWriter>
-
-#include <QTimer>
-#include <utils/qtcassert.h>
-
-using namespace QmlDebug;
-
-namespace QmlProfiler {
-namespace Internal {
-
-typedef QHash <QString, QmlRangeEventRelative *> EventHash;
-
-static EventHash cloneEventHash(const EventHash &src)
-{
- EventHash result;
- const EventHash::ConstIterator cend = src.constEnd();
- for (EventHash::ConstIterator it = src.constBegin(); it != cend; ++it)
- result.insert(it.key(), new QmlRangeEventRelative(it.value()));
- return result;
-}
-
-///////////////////////////////////////////////////////////
-QmlRangeEventData::QmlRangeEventData()
-{
- eventType = MaximumQmlEventType;
- eventId = -1;
- duration = 0;
- calls = 0;
- minTime = 0;
- maxTime = 0;
- timePerCall = 0;
- percentOfTime = 0;
- medianTime = 0;
- isBindingLoop = false;
-}
-
-QmlRangeEventData::~QmlRangeEventData()
-{
- qDeleteAll(parentHash);
- parentHash.clear();
- qDeleteAll(childrenHash);
- childrenHash.clear();
-}
-
-QmlRangeEventData &QmlRangeEventData::operator=(const QmlRangeEventData &ref)
-{
- if (this == &ref)
- return *this;
-
- displayName = ref.displayName;
- location = ref.location;
- eventHashStr = ref.eventHashStr;
- details = ref.details;
- eventType = ref.eventType;
- duration = ref.duration;
- calls = ref.calls;
- minTime = ref.minTime;
- maxTime = ref.maxTime;
- timePerCall = ref.timePerCall;
- percentOfTime = ref.percentOfTime;
- medianTime = ref.medianTime;
- eventId = ref.eventId;
- isBindingLoop = ref.isBindingLoop;
-
- qDeleteAll(parentHash);
- parentHash = cloneEventHash(ref.parentHash);
-
- qDeleteAll(childrenHash);
- childrenHash = cloneEventHash(ref.childrenHash);
-
- return *this;
-}
-
-///////////////////////////////////////////////////////////
-
-// endtimedata
-struct QmlRangeEventEndInstance {
- qint64 endTime;
- int startTimeIndex;
- QmlRangeEventData *description;
-};
-
-// starttimedata
-struct QmlRangeEventStartInstance {
- qint64 startTime;
- qint64 duration;
- qint64 level;
- int endTimeIndex;
- qint64 nestingLevel;
- qint64 nestingDepth;
- QmlRangeEventData *statsInfo;
-
- int baseEventIndex;
-
- // animation-related data
- int frameRate;
- int animationCount;
-
- int bindingLoopHead;
-};
-
-struct QmlRangeEventTypeCount {
- QVector<int> eventIds;
- int nestingCount;
-};
-
-// used by quicksort
-bool compareEndTimes(const QmlRangeEventEndInstance &t1, const QmlRangeEventEndInstance &t2)
-{
- return t1.endTime < t2.endTime;
-}
-
-bool compareStartTimes(const QmlRangeEventStartInstance &t1, const QmlRangeEventStartInstance &t2)
-{
- return t1.startTime < t2.startTime;
-}
-
-bool compareStartIndexes(const QmlRangeEventEndInstance &t1, const QmlRangeEventEndInstance &t2)
-{
- return t1.startTimeIndex < t2.startTimeIndex;
-}
-
-//////////////////////////////////////////////////////////////
-class QmlProfilerDataModel::QmlProfilerDataModelPrivate
-{
-public:
- QmlProfilerDataModelPrivate(QmlProfilerDataModel *qq) : q(qq) {}
-
- QmlProfilerDataModel *q;
-
- // convenience functions
- void clearQmlRootEvent();
- void insertQmlRootEvent();
- void postProcess();
- void sortEndTimes();
- void findAnimationLimits();
- void sortStartTimes();
- void computeNestingLevels();
- void computeNestingDepth();
- void prepareForDisplay();
- void linkStartsToEnds();
- void linkEndsToStarts();
-
-
- // stats
- void clearStatistics();
- void redoTree(qint64 fromTime, qint64 toTime);
- void computeMedianTime(qint64 fromTime, qint64 toTime);
- void findBindingLoops(qint64 fromTime, qint64 toTime);
-
- QmlProfilerDataModel::State listState;
-
- // Stored data
- QHash<QString, QmlRangeEventData *> rangeEventDictionary;
- QVector<QmlRangeEventEndInstance> endInstanceList;
- QVector<QmlRangeEventStartInstance> startInstanceList;
-
- QmlRangeEventData qmlRootEvent;
-
- QV8ProfilerDataModel *v8DataModel;
-
- QHash<int, QmlRangeEventTypeCount *> typeCounts;
-
- qint64 traceEndTime;
- qint64 traceStartTime;
- qint64 qmlMeasuredTime;
-
- int lastFrameEventIndex;
- qint64 maxAnimationCount;
- qint64 minAnimationCount;
-
- // file to load
- QString fileName;
-};
-
-
-////////////////////////////////////////////////////////////////////////////////////
-
-
-QmlProfilerDataModel::QmlProfilerDataModel(QObject *parent) :
- QObject(parent), d(new QmlProfilerDataModelPrivate(this))
-{
- setObjectName(QLatin1String("QmlProfilerDataModel"));
-
- d->listState = Empty;
-
- d->traceEndTime = 0;
- d->traceStartTime = -1;
- d->qmlMeasuredTime = 0;
- d->clearQmlRootEvent();
- d->lastFrameEventIndex = -1;
- d->maxAnimationCount = 0;
- d->minAnimationCount = 0;
- d->v8DataModel = new QV8ProfilerDataModel(this, this);
-}
-
-QmlProfilerDataModel::~QmlProfilerDataModel()
-{
- clear();
- delete d;
-}
-
-////////////////////////////////////////////////////////////////////////////////////
-QList<QmlRangeEventData *> QmlProfilerDataModel::getEventDescriptions() const
-{
- return d->rangeEventDictionary.values();
-}
-
-QmlRangeEventData *QmlProfilerDataModel::eventDescription(int eventId) const
-{
- foreach (QmlRangeEventData *event, d->rangeEventDictionary.values()) {
- if (event->eventId == eventId)
- return event;
- }
- return 0;
-}
-
-QList<QV8EventData *> QmlProfilerDataModel::getV8Events() const
-{
- return d->v8DataModel->getV8Events();
-}
-
-QV8EventData *QmlProfilerDataModel::v8EventDescription(int eventId) const
-{
- return d->v8DataModel->v8EventDescription(eventId);
-}
-
-////////////////////////////////////////////////////////////////////////////////////
-
-void QmlProfilerDataModel::clear()
-{
- qDeleteAll(d->rangeEventDictionary);
- d->rangeEventDictionary.clear();
-
- d->endInstanceList.clear();
- d->startInstanceList.clear();
-
- d->clearQmlRootEvent();
-
- foreach (QmlRangeEventTypeCount *typeCount, d->typeCounts.values())
- delete typeCount;
- d->typeCounts.clear();
-
- d->traceEndTime = 0;
- d->traceStartTime = -1;
- d->qmlMeasuredTime = 0;
-
- d->lastFrameEventIndex = -1;
- d->maxAnimationCount = 0;
- d->minAnimationCount = 0;
-
- d->v8DataModel->clear();
-
- emit countChanged();
- setState(Empty);
-}
-
-void QmlProfilerDataModel::prepareForWriting()
-{
- setState(AcquiringData);
-}
-
-void QmlProfilerDataModel::addRangedEvent(int type, int bindingType, qint64 startTime,
- qint64 length, const QStringList &data,
- const QmlDebug::QmlEventLocation &location)
-{
- const QChar colon = QLatin1Char(':');
- QString displayName, eventHashStr, details;
- QmlDebug::QmlEventLocation eventLocation = location;
-
- setState(AcquiringData);
-
- // generate details string
- if (data.isEmpty())
- details = tr("Source code not available.");
- else {
- 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) + 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
- // version of the protocol, but the filename is passed in the details string
- if ((type == QmlDebug::Creating || type == QmlDebug::Compiling) && eventLocation.filename.isEmpty()) {
- eventLocation.filename = details;
- eventLocation.line = 1;
- eventLocation.column = 1;
- }
-
- // generate hash
- if (eventLocation.filename.isEmpty()) {
- displayName = tr("<bytecode>");
- eventHashStr = getHashStringForQmlEvent(eventLocation, type);
- } else {
- const QString filePath = QUrl(eventLocation.filename).path();
- displayName = filePath.mid(filePath.lastIndexOf(QLatin1Char('/')) + 1) + colon +
- QString::number(eventLocation.line);
- eventHashStr = getHashStringForQmlEvent(eventLocation, type);
- }
-
- QmlRangeEventData *newEvent;
- if (d->rangeEventDictionary.contains(eventHashStr)) {
- newEvent = d->rangeEventDictionary[eventHashStr];
- } else {
- newEvent = new QmlRangeEventData;
- newEvent->displayName = displayName;
- newEvent->location = eventLocation;
- newEvent->eventHashStr = eventHashStr;
- newEvent->eventType = (QmlDebug::QmlEventType)type;
- newEvent->details = details;
- newEvent->bindingType = bindingType;
- d->rangeEventDictionary.insert(eventHashStr, newEvent);
- }
-
- QmlRangeEventEndInstance endTimeData;
- endTimeData.endTime = startTime + length;
- endTimeData.description = newEvent;
- endTimeData.startTimeIndex = d->startInstanceList.count();
-
- QmlRangeEventStartInstance startTimeData;
- startTimeData.startTime = startTime;
- startTimeData.duration = length;
- startTimeData.statsInfo = newEvent;
- startTimeData.endTimeIndex = d->endInstanceList.count();
- startTimeData.animationCount = -1;
- startTimeData.frameRate = 1e9/length;
- startTimeData.baseEventIndex = d->startInstanceList.count(); // point to itself by default
-
- d->endInstanceList << endTimeData;
- d->startInstanceList << startTimeData;
-
- emit countChanged();
-}
-
-void QmlProfilerDataModel::addV8Event(int depth, const QString &function,
- const QString &filename, int lineNumber,
- double totalTime, double selfTime)
-{
- d->v8DataModel->addV8Event(depth, function, filename, lineNumber, totalTime, selfTime);
-}
-
-void QmlProfilerDataModel::addFrameEvent(qint64 time, int framerate, int animationcount)
-{
- QString displayName, eventHashStr, details;
-
- setState(AcquiringData);
-
- details = tr("Animation Timer Update");
- displayName = tr("<Animation Update>");
- eventHashStr = displayName;
-
- QmlRangeEventData *newEvent;
- if (d->rangeEventDictionary.contains(eventHashStr)) {
- newEvent = d->rangeEventDictionary[eventHashStr];
- } else {
- newEvent = new QmlRangeEventData;
- newEvent->displayName = displayName;
- newEvent->eventHashStr = eventHashStr;
- newEvent->eventType = QmlDebug::Painting;
- newEvent->details = details;
- d->rangeEventDictionary.insert(eventHashStr, newEvent);
- }
-
- qint64 length = 1e9/framerate;
- // avoid overlap
- QmlRangeEventStartInstance *lastFrameEvent = 0;
- if (d->lastFrameEventIndex > -1) {
- lastFrameEvent = &d->startInstanceList[d->lastFrameEventIndex];
- if (lastFrameEvent->startTime + lastFrameEvent->duration >= time) {
- lastFrameEvent->duration = time - 1 - lastFrameEvent->startTime;
- d->endInstanceList[lastFrameEvent->endTimeIndex].endTime =
- lastFrameEvent->startTime + lastFrameEvent->duration;
- }
- }
-
- QmlRangeEventEndInstance endTimeData;
- endTimeData.endTime = time + length;
- endTimeData.description = newEvent;
- endTimeData.startTimeIndex = d->startInstanceList.count();
-
- QmlRangeEventStartInstance startTimeData;
- startTimeData.startTime = time;
- startTimeData.duration = length;
- startTimeData.statsInfo = newEvent;
- startTimeData.endTimeIndex = d->endInstanceList.count();
- startTimeData.animationCount = animationcount;
- startTimeData.frameRate = framerate;
- startTimeData.baseEventIndex = d->startInstanceList.count(); // point to itself by default
-
- d->endInstanceList << endTimeData;
- d->startInstanceList << startTimeData;
-
- d->lastFrameEventIndex = d->startInstanceList.count() - 1;
-
- emit countChanged();
-}
-
-void QmlProfilerDataModel::setTraceEndTime(qint64 time)
-{
- d->traceEndTime = time;
-}
-
-void QmlProfilerDataModel::setTraceStartTime(qint64 time)
-{
- d->traceStartTime = time;
-}
-
-////////////////////////////////////////////////////////////////////////////////////
-
-QString QmlProfilerDataModel::getHashStringForQmlEvent(
- const QmlDebug::QmlEventLocation &location, int eventType)
-{
- return QString::fromLatin1("%1:%2:%3:%4").arg(location.filename,
- QString::number(location.line),
- QString::number(location.column),
- QString::number(eventType));
-}
-
-QString QmlProfilerDataModel::getHashStringForV8Event(const QString &displayName,
- const QString &function)
-{
- return QString::fromLatin1("%1:%2").arg(displayName, function);
-}
-
-QString QmlProfilerDataModel::rootEventName()
-{
- return tr("<program>");
-}
-
-QString QmlProfilerDataModel::rootEventDescription()
-{
- return tr("Main Program");
-}
-
-QString QmlProfilerDataModel::qmlEventTypeAsString(QmlEventType typeEnum)
-{
- switch (typeEnum) {
- case Painting:
- return QLatin1String(Constants::TYPE_PAINTING_STR);
- break;
- case Compiling:
- return QLatin1String(Constants::TYPE_COMPILING_STR);
- break;
- case Creating:
- return QLatin1String(Constants::TYPE_CREATING_STR);
- break;
- case Binding:
- return QLatin1String(Constants::TYPE_BINDING_STR);
- break;
- case HandlingSignal:
- return QLatin1String(Constants::TYPE_HANDLINGSIGNAL_STR);
- break;
- default:
- return QString::number((int)typeEnum);
- }
-}
-
-QmlEventType QmlProfilerDataModel::qmlEventTypeAsEnum(const QString &typeString)
-{
- if (typeString == QLatin1String(Constants::TYPE_PAINTING_STR)) {
- return Painting;
- } else if (typeString == QLatin1String(Constants::TYPE_COMPILING_STR)) {
- return Compiling;
- } else if (typeString == QLatin1String(Constants::TYPE_CREATING_STR)) {
- return Creating;
- } else if (typeString == QLatin1String(Constants::TYPE_BINDING_STR)) {
- return Binding;
- } else if (typeString == QLatin1String(Constants::TYPE_HANDLINGSIGNAL_STR)) {
- return HandlingSignal;
- } else {
- bool isNumber = false;
- int type = typeString.toUInt(&isNumber);
- if (isNumber)
- return (QmlEventType)type;
- else
- return MaximumQmlEventType;
- }
-}
-
-////////////////////////////////////////////////////////////////////////////////////
-
-int QmlProfilerDataModel::findFirstIndex(qint64 startTime) const
-{
- int candidate = -1;
- // in the "endtime" list, find the first event that ends after startTime
- if (d->endInstanceList.isEmpty())
- return 0; // -1
- if (d->endInstanceList.count() == 1 || d->endInstanceList.first().endTime >= startTime)
- candidate = 0;
- else
- if (d->endInstanceList.last().endTime <= startTime)
- return 0; // -1
-
- if (candidate == -1)
- {
- int fromIndex = 0;
- int toIndex = d->endInstanceList.count()-1;
- while (toIndex - fromIndex > 1) {
- int midIndex = (fromIndex + toIndex)/2;
- if (d->endInstanceList[midIndex].endTime < startTime)
- fromIndex = midIndex;
- else
- toIndex = midIndex;
- }
-
- candidate = toIndex;
- }
-
- int eventIndex = d->endInstanceList[candidate].startTimeIndex;
- return d->startInstanceList[eventIndex].baseEventIndex;
-}
-
-int QmlProfilerDataModel::findFirstIndexNoParents(qint64 startTime) const
-{
- int candidate = -1;
- // in the "endtime" list, find the first event that ends after startTime
- if (d->endInstanceList.isEmpty())
- return 0; // -1
- if (d->endInstanceList.count() == 1 || d->endInstanceList.first().endTime >= startTime)
- candidate = 0;
- else
- if (d->endInstanceList.last().endTime <= startTime)
- return 0; // -1
-
- if (candidate == -1) {
- int fromIndex = 0;
- int toIndex = d->endInstanceList.count()-1;
- while (toIndex - fromIndex > 1) {
- int midIndex = (fromIndex + toIndex)/2;
- if (d->endInstanceList[midIndex].endTime < startTime)
- fromIndex = midIndex;
- else
- toIndex = midIndex;
- }
-
- candidate = toIndex;
- }
-
- int ndx = d->endInstanceList[candidate].startTimeIndex;
-
- return ndx;
-}
-
-int QmlProfilerDataModel::findLastIndex(qint64 endTime) const
-{
- // in the "starttime" list, find the last event that starts before endtime
- if (d->startInstanceList.isEmpty())
- return 0; // -1
- if (d->startInstanceList.first().startTime >= endTime)
- return 0; // -1
- if (d->startInstanceList.count() == 1)
- return 0;
- if (d->startInstanceList.last().startTime <= endTime)
- return d->startInstanceList.count()-1;
-
- int fromIndex = 0;
- int toIndex = d->startInstanceList.count()-1;
- while (toIndex - fromIndex > 1) {
- int midIndex = (fromIndex + toIndex)/2;
- if (d->startInstanceList[midIndex].startTime < endTime)
- fromIndex = midIndex;
- else
- toIndex = midIndex;
- }
-
- return fromIndex;
-}
-
-qint64 QmlProfilerDataModel::firstTimeMark() const
-{
- if (d->startInstanceList.isEmpty())
- return 0;
- else {
- return d->startInstanceList[0].startTime;
- }
-}
-
-qint64 QmlProfilerDataModel::lastTimeMark() const
-{
- if (d->endInstanceList.isEmpty())
- return 0;
- else {
- return d->endInstanceList.last().endTime;
- }
-}
-
-////////////////////////////////////////////////////////////////////////////////////
-
-int QmlProfilerDataModel::count() const
-{
- return d->startInstanceList.count();
-}
-
-bool QmlProfilerDataModel::isEmpty() const
-{
- return d->startInstanceList.isEmpty() && d->v8DataModel->isEmpty();
-}
-
-qint64 QmlProfilerDataModel::getStartTime(int index) const
-{
- return d->startInstanceList[index].startTime;
-}
-
-qint64 QmlProfilerDataModel::getEndTime(int index) const
-{
- return d->startInstanceList[index].startTime + d->startInstanceList[index].duration;
-}
-
-qint64 QmlProfilerDataModel::getDuration(int index) const
-{
- return d->startInstanceList[index].duration;
-}
-
-int QmlProfilerDataModel::getType(int index) const
-{
- return d->startInstanceList[index].statsInfo->eventType;
-}
-
-int QmlProfilerDataModel::getNestingLevel(int index) const
-{
- return d->startInstanceList[index].nestingLevel;
-}
-
-int QmlProfilerDataModel::getNestingDepth(int index) const
-{
- return d->startInstanceList[index].nestingDepth;
-}
-
-QString QmlProfilerDataModel::getFilename(int index) const
-{
- return d->startInstanceList[index].statsInfo->location.filename;
-}
-
-int QmlProfilerDataModel::getLine(int index) const
-{
- return d->startInstanceList[index].statsInfo->location.line;
-}
-
-int QmlProfilerDataModel::getColumn(int index) const
-{
- return d->startInstanceList[index].statsInfo->location.column;
-}
-
-QString QmlProfilerDataModel::getDetails(int index) const
-{
- // special: animations
- if (d->startInstanceList[index].statsInfo->eventType == QmlDebug::Painting &&
- d->startInstanceList[index].animationCount >= 0)
- return tr("%1 animations at %2 FPS.").arg(
- QString::number(d->startInstanceList[index].animationCount),
- QString::number(d->startInstanceList[index].frameRate));
- return d->startInstanceList[index].statsInfo->details;
-}
-
-int QmlProfilerDataModel::getEventId(int index) const
-{
- return d->startInstanceList[index].statsInfo->eventId;
-}
-
-int QmlProfilerDataModel::getBindingLoopDest(int index) const
-{
- return d->startInstanceList[index].bindingLoopHead;
-}
-
-int QmlProfilerDataModel::getFramerate(int index) const
-{
- return d->startInstanceList[index].frameRate;
-}
-
-int QmlProfilerDataModel::getAnimationCount(int index) const
-{
- return d->startInstanceList[index].animationCount;
-}
-
-int QmlProfilerDataModel::getMaximumAnimationCount() const
-{
- return d->maxAnimationCount;
-}
-
-int QmlProfilerDataModel::getMinimumAnimationCount() const
-{
- return d->minAnimationCount;
-}
-
-/////////////////////////////////////////
-
-int QmlProfilerDataModel::uniqueEventsOfType(int type) const
-{
- if (!d->typeCounts.contains(type))
- return 0;
- return d->typeCounts[type]->eventIds.count();
-}
-
-int QmlProfilerDataModel::maxNestingForType(int type) const
-{
- if (!d->typeCounts.contains(type))
- return 0;
- return d->typeCounts[type]->nestingCount;
-}
-
-QString QmlProfilerDataModel::eventTextForType(int type, int index) const
-{
- if (!d->typeCounts.contains(type))
- return QString();
- return d->rangeEventDictionary.values().at(d->typeCounts[type]->eventIds[index])->details;
-}
-
-QString QmlProfilerDataModel::eventDisplayNameForType(int type, int index) const
-{
- if (!d->typeCounts.contains(type))
- return QString();
- return d->rangeEventDictionary.values().at(d->typeCounts[type]->eventIds[index])->displayName;
-}
-
-int QmlProfilerDataModel::eventIdForType(int type, int index) const
-{
- if (!d->typeCounts.contains(type))
- return -1;
- return d->typeCounts[type]->eventIds[index];
-}
-
-int QmlProfilerDataModel::eventPosInType(int index) const
-{
- int eventType = d->startInstanceList[index].statsInfo->eventType;
- return d->typeCounts[eventType]->eventIds.indexOf(d->startInstanceList[index].statsInfo->eventId);
-}
-
-/////////////////////////////////////////
-
-qint64 QmlProfilerDataModel::traceStartTime() const
-{
- return d->traceStartTime != -1? d->traceStartTime : firstTimeMark();
-}
-
-qint64 QmlProfilerDataModel::traceEndTime() const
-{
- return d->traceEndTime ? d->traceEndTime : lastTimeMark();
-}
-
-qint64 QmlProfilerDataModel::traceDuration() const
-{
- return traceEndTime() - traceStartTime();
-}
-
-qint64 QmlProfilerDataModel::qmlMeasuredTime() const
-{
- return d->qmlMeasuredTime;
-}
-qint64 QmlProfilerDataModel::v8MeasuredTime() const
-{
- return d->v8DataModel->v8MeasuredTime();
-}
-
-////////////////////////////////////////////////////////////////////////////////////
-
-void QmlProfilerDataModel::complete()
-{
- if (currentState() == AcquiringData) {
- setState(ProcessingData);
- d->v8DataModel->collectV8Statistics();
- d->postProcess();
- } else
- if (currentState() == Empty) {
- d->v8DataModel->collectV8Statistics();
- compileStatistics(traceStartTime(), traceEndTime());
- setState(Done);
- } else
- if (currentState() == Done) {
- // ignore duplicated complete signals
- } else {
- emit error(tr("Unexpected complete signal in data model."));
- }
-}
-
-void QmlProfilerDataModel::QmlProfilerDataModelPrivate::postProcess()
-{
- if (q->count() != 0) {
- sortStartTimes();
- sortEndTimes();
- findAnimationLimits();
- computeNestingLevels();
- computeNestingDepth();
- linkEndsToStarts();
- insertQmlRootEvent();
- q->reloadDetails();
- prepareForDisplay();
- q->compileStatistics(q->traceStartTime(), q->traceEndTime());
- }
- q->setState(Done);
-}
-
-
-void QmlProfilerDataModel::QmlProfilerDataModelPrivate::prepareForDisplay()
-{
- // generate numeric ids
- int ndx = 0;
- foreach (QmlRangeEventData *binding, rangeEventDictionary.values()) {
- binding->eventId = ndx++;
- }
-
- // collect type counts
- foreach (const QmlRangeEventStartInstance &eventStartData, startInstanceList) {
- int typeNumber = eventStartData.statsInfo->eventType;
- if (!typeCounts.contains(typeNumber)) {
- typeCounts[typeNumber] = new QmlRangeEventTypeCount;
- typeCounts[typeNumber]->nestingCount = 0;
- }
- 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;
- }
-}
-
-void QmlProfilerDataModel::QmlProfilerDataModelPrivate::sortStartTimes()
-{
- if (startInstanceList.count() < 2)
- return;
-
- // assuming startTimes is partially sorted
- // identify blocks of events and sort them with quicksort
- QVector<QmlRangeEventStartInstance>::iterator itFrom = startInstanceList.end() - 2;
- QVector<QmlRangeEventStartInstance>::iterator itTo = startInstanceList.end() - 1;
-
- while (itFrom != startInstanceList.begin() && itTo != startInstanceList.begin()) {
- // find block to sort
- while (itFrom != startInstanceList.begin()
- && itTo->startTime > itFrom->startTime) {
- itTo--;
- itFrom = itTo - 1;
- }
-
- // if we're at the end of the list
- if (itFrom == startInstanceList.begin())
- break;
-
- // find block length
- while (itFrom != startInstanceList.begin()
- && itTo->startTime <= itFrom->startTime)
- itFrom--;
-
- if (itTo->startTime <= itFrom->startTime)
- qSort(itFrom, itTo + 1, compareStartTimes);
- else
- qSort(itFrom + 1, itTo + 1, compareStartTimes);
-
- // move to next block
- itTo = itFrom;
- itFrom = itTo - 1;
- }
-
- // link back the endTimes
- linkEndsToStarts();
-}
-
-void QmlProfilerDataModel::QmlProfilerDataModelPrivate::sortEndTimes()
-{
- // assuming endTimes is partially sorted
- // identify blocks of events and sort them with quicksort
-
- if (endInstanceList.count() < 2)
- return;
-
- QVector<QmlRangeEventEndInstance>::iterator itFrom = endInstanceList.begin();
- QVector<QmlRangeEventEndInstance>::iterator itTo = endInstanceList.begin() + 1;
-
- while (itTo != endInstanceList.end() && itFrom != endInstanceList.end()) {
- // find block to sort
- while (itTo != endInstanceList.end()
- && startInstanceList[itTo->startTimeIndex].startTime >
- startInstanceList[itFrom->startTimeIndex].startTime +
- startInstanceList[itFrom->startTimeIndex].duration) {
- itFrom++;
- itTo = itFrom+1;
- }
-
- // if we're at the end of the list
- if (itTo == endInstanceList.end())
- break;
-
- // find block length
- while (itTo != endInstanceList.end()
- && startInstanceList[itTo->startTimeIndex].startTime <=
- startInstanceList[itFrom->startTimeIndex].startTime +
- startInstanceList[itFrom->startTimeIndex].duration)
- itTo++;
-
- // sort block
- qSort(itFrom, itTo, compareEndTimes);
-
- // move to next block
- itFrom = itTo;
- itTo = itFrom+1;
-
- }
-
- // link back the startTimes
- linkStartsToEnds();
-}
-
-void QmlProfilerDataModel::QmlProfilerDataModelPrivate::linkStartsToEnds()
-{
- for (int i = 0; i < endInstanceList.count(); i++)
- startInstanceList[endInstanceList[i].startTimeIndex].endTimeIndex = i;
-}
-
-void QmlProfilerDataModel::QmlProfilerDataModelPrivate::findAnimationLimits()
-{
- maxAnimationCount = 0;
- minAnimationCount = 0;
- lastFrameEventIndex = -1;
-
- for (int i = 0; i < startInstanceList.count(); i++) {
- if (startInstanceList[i].statsInfo->eventType == QmlDebug::Painting &&
- startInstanceList[i].animationCount >= 0) {
- int animationcount = startInstanceList[i].animationCount;
- if (lastFrameEventIndex > -1) {
- if (animationcount > maxAnimationCount)
- maxAnimationCount = animationcount;
- if (animationcount < minAnimationCount)
- minAnimationCount = animationcount;
- } else {
- maxAnimationCount = animationcount;
- minAnimationCount = animationcount;
- }
- lastFrameEventIndex = i;
- }
- }
-}
-
-void QmlProfilerDataModel::QmlProfilerDataModelPrivate::computeNestingLevels()
-{
- // compute levels
- QHash<int, qint64> endtimesPerLevel;
- QList<int> nestingLevels;
- QList< QHash<int, qint64> > endtimesPerNestingLevel;
- int level = Constants::QML_MIN_LEVEL;
- endtimesPerLevel[Constants::QML_MIN_LEVEL] = 0;
- int lastBaseEventIndex = 0;
- qint64 lastBaseEventEndTime = traceStartTime;
-
- for (int i = 0; i < QmlDebug::MaximumQmlEventType; i++) {
- nestingLevels << Constants::QML_MIN_LEVEL;
- QHash<int, qint64> dummyHash;
- dummyHash[Constants::QML_MIN_LEVEL] = 0;
- endtimesPerNestingLevel << dummyHash;
- }
-
- for (int i=0; i<startInstanceList.count(); i++) {
- qint64 st = startInstanceList[i].startTime;
- int type = startInstanceList[i].statsInfo->eventType;
-
- if (type == QmlDebug::Painting) {
- // animation/paint events have level 0 by definition (same as "mainprogram"),
- // but are not considered parents of other events for statistical purposes
- startInstanceList[i].level = Constants::QML_MIN_LEVEL - 1;
- startInstanceList[i].nestingLevel = Constants::QML_MIN_LEVEL;
- if (lastBaseEventEndTime < startInstanceList[i].startTime) {
- lastBaseEventIndex = i;
- lastBaseEventEndTime = startInstanceList[i].startTime + startInstanceList[i].duration;
- }
- startInstanceList[i].baseEventIndex = lastBaseEventIndex;
- continue;
- }
-
- // general level
- if (endtimesPerLevel[level] > st) {
- level++;
- } else {
- while (level > Constants::QML_MIN_LEVEL && endtimesPerLevel[level-1] <= st)
- level--;
- }
- endtimesPerLevel[level] = st + startInstanceList[i].duration;
-
- // per type
- if (endtimesPerNestingLevel[type][nestingLevels[type]] > st) {
- nestingLevels[type]++;
- } else {
- while (nestingLevels[type] > Constants::QML_MIN_LEVEL &&
- endtimesPerNestingLevel[type][nestingLevels[type]-1] <= st)
- nestingLevels[type]--;
- }
- endtimesPerNestingLevel[type][nestingLevels[type]] =
- st + startInstanceList[i].duration;
-
- startInstanceList[i].level = level;
- startInstanceList[i].nestingLevel = nestingLevels[type];
-
- if (level == Constants::QML_MIN_LEVEL) {
- qmlMeasuredTime += startInstanceList[i].duration;
- if (lastBaseEventEndTime < startInstanceList[i].startTime) {
- lastBaseEventIndex = i;
- lastBaseEventEndTime = startInstanceList[i].startTime + startInstanceList[i].duration;
- }
- }
- startInstanceList[i].baseEventIndex = lastBaseEventIndex;
- }
-}
-
-void QmlProfilerDataModel::QmlProfilerDataModelPrivate::computeNestingDepth()
-{
- QHash<int, int> nestingDepth;
- for (int i = 0; i < endInstanceList.count(); i++) {
- int type = endInstanceList[i].description->eventType;
- int nestingInType = startInstanceList[endInstanceList[i].startTimeIndex].nestingLevel;
- if (!nestingDepth.contains(type))
- nestingDepth[type] = nestingInType;
- else {
- int nd = nestingDepth[type];
- nestingDepth[type] = nd > nestingInType ? nd : nestingInType;
- }
-
- startInstanceList[endInstanceList[i].startTimeIndex].nestingDepth = nestingDepth[type];
- if (nestingInType == Constants::QML_MIN_LEVEL)
- nestingDepth[type] = Constants::QML_MIN_LEVEL;
- }
-}
-
-void QmlProfilerDataModel::QmlProfilerDataModelPrivate::linkEndsToStarts()
-{
- for (int i = 0; i < startInstanceList.count(); i++)
- endInstanceList[startInstanceList[i].endTimeIndex].startTimeIndex = i;
-}
-
-////////////////////////////////////////////////////////////////////////////////////
-
-void QmlProfilerDataModel::compileStatistics(qint64 startTime, qint64 endTime)
-{
- d->clearStatistics();
- if (traceDuration() > 0) {
- if (count() > 0) {
- d->redoTree(startTime, endTime);
- d->computeMedianTime(startTime, endTime);
- d->findBindingLoops(startTime, endTime);
- } else {
- d->insertQmlRootEvent();
- QmlRangeEventData *listedRootEvent = d->rangeEventDictionary.value(rootEventName());
- listedRootEvent->calls = 1;
- listedRootEvent->percentOfTime = 100;
- }
- }
-}
-
-void QmlProfilerDataModel::QmlProfilerDataModelPrivate::clearStatistics()
-{
- // clear existing statistics
- foreach (QmlRangeEventData *eventDescription, rangeEventDictionary.values()) {
- eventDescription->calls = 0;
- // maximum possible value
- eventDescription->minTime = traceEndTime;
- eventDescription->maxTime = 0;
- eventDescription->medianTime = 0;
- eventDescription->duration = 0;
- qDeleteAll(eventDescription->parentHash);
- qDeleteAll(eventDescription->childrenHash);
- eventDescription->parentHash.clear();
- eventDescription->childrenHash.clear();
- }
-}
-
-void QmlProfilerDataModel::QmlProfilerDataModelPrivate::redoTree(qint64 fromTime,
- qint64 toTime)
-{
- double totalTime = 0;
- int fromIndex = q->findFirstIndex(fromTime);
- int toIndex = q->findLastIndex(toTime);
-
- QmlRangeEventData *listedRootEvent = rangeEventDictionary.value(rootEventName());
- QTC_ASSERT(listedRootEvent, /**/);
-
- // compute parent-child relationship and call count
- QHash<int, QmlRangeEventData*> lastParent;
- for (int index = fromIndex; index <= toIndex; index++) {
- QmlRangeEventData *eventDescription = startInstanceList[index].statsInfo;
-
- if (startInstanceList[index].startTime > toTime ||
- startInstanceList[index].startTime+startInstanceList[index].duration < fromTime) {
- continue;
- }
-
- if (eventDescription->eventType == QmlDebug::Painting) {
- // skip animation/paint events
- continue;
- }
-
- eventDescription->calls++;
- qint64 duration = startInstanceList[index].duration;
- eventDescription->duration += duration;
- if (eventDescription->maxTime < duration)
- eventDescription->maxTime = duration;
- if (eventDescription->minTime > duration)
- eventDescription->minTime = duration;
-
- int level = startInstanceList[index].level;
-
- QmlRangeEventData *parentEvent = listedRootEvent;
- 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);
- newParentEvent->calls = 1;
- newParentEvent->duration = duration;
-
- eventDescription->parentHash.insert(parentEvent->eventHashStr, newParentEvent);
- } else {
- QmlRangeEventRelative *newParentEvent =
- eventDescription->parentHash.value(parentEvent->eventHashStr);
- newParentEvent->duration += duration;
- newParentEvent->calls++;
- }
-
- if (!parentEvent->childrenHash.contains(eventDescription->eventHashStr)) {
- QmlRangeEventRelative *newChildEvent = new QmlRangeEventRelative(eventDescription);
- newChildEvent->calls = 1;
- newChildEvent->duration = duration;
-
- parentEvent->childrenHash.insert(eventDescription->eventHashStr, newChildEvent);
- } else {
- QmlRangeEventRelative *newChildEvent =
- parentEvent->childrenHash.value(eventDescription->eventHashStr);
- newChildEvent->duration += duration;
- newChildEvent->calls++;
- }
-
- lastParent[level] = eventDescription;
-
- if (level == Constants::QML_MIN_LEVEL)
- totalTime += duration;
- }
-
- // fake rootEvent statistics
- // the +1 nanosecond is to force it to be on top of the sorted list
- listedRootEvent->duration = totalTime+1;
- listedRootEvent->minTime = totalTime+1;
- listedRootEvent->maxTime = totalTime+1;
- listedRootEvent->medianTime = totalTime+1;
- if (totalTime > 0)
- listedRootEvent->calls = 1;
-
- // copy to the global root reference
- qmlRootEvent = *listedRootEvent;
-
- // compute percentages
- foreach (QmlRangeEventData *binding, rangeEventDictionary.values()) {
- binding->percentOfTime = binding->duration * 100.0 / totalTime;
- binding->timePerCall = binding->calls > 0 ? double(binding->duration) / binding->calls : 0;
- }
-}
-
-void QmlProfilerDataModel::QmlProfilerDataModelPrivate::computeMedianTime(qint64 fromTime,
- qint64 toTime)
-{
- int fromIndex = q->findFirstIndex(fromTime);
- int toIndex = q->findLastIndex(toTime);
-
- // compute median time
- QHash< QmlRangeEventData* , QList<qint64> > durationLists;
- for (int index = fromIndex; index <= toIndex; index++) {
- QmlRangeEventData *desc = startInstanceList[index].statsInfo;
- qint64 len = startInstanceList[index].duration;
- durationLists[desc].append(len);
- }
- QMutableHashIterator < QmlRangeEventData* , QList<qint64> > iter(durationLists);
- while (iter.hasNext()) {
- iter.next();
- if (!iter.value().isEmpty()) {
- qSort(iter.value());
- iter.key()->medianTime = iter.value().at(iter.value().count()/2);
- }
- }
-}
-
-void QmlProfilerDataModel::QmlProfilerDataModelPrivate::findBindingLoops(qint64 fromTime,
- qint64 toTime)
-{
- int fromIndex = q->findFirstIndex(fromTime);
- int toIndex = q->findLastIndex(toTime);
-
- // first clear existing data
- foreach (QmlRangeEventData *event, rangeEventDictionary.values()) {
- event->isBindingLoop = false;
- foreach (QmlRangeEventRelative *parentEvent, event->parentHash.values())
- parentEvent->inLoopPath = false;
- foreach (QmlRangeEventRelative *childEvent, event->childrenHash.values())
- childEvent->inLoopPath = false;
- }
-
- QList<QmlRangeEventData *> stackRefs;
- QList<QmlRangeEventStartInstance *> stack;
-
- for (int i = 0; i < startInstanceList.count(); i++) {
- QmlRangeEventData *currentEvent = startInstanceList[i].statsInfo;
- QmlRangeEventStartInstance *inTimeEvent = &startInstanceList[i];
- inTimeEvent->bindingLoopHead = -1;
-
- // special: skip animation events (but not old paint events)
- if (inTimeEvent->statsInfo->eventType == Painting && inTimeEvent->animationCount >= 0)
- continue;
-
- // managing call stack
- for (int j = stack.count() - 1; j >= 0; j--) {
- if (stack[j]->startTime + stack[j]->duration <= inTimeEvent->startTime) {
- stack.removeAt(j);
- stackRefs.removeAt(j);
- }
- }
-
- bool loopDetected = stackRefs.contains(currentEvent);
- stack << inTimeEvent;
- stackRefs << currentEvent;
-
- // skip loops if bindings are anonymous
- if (loopDetected && !currentEvent->location.filename.isEmpty()) {
- if (i >= fromIndex && i <= toIndex) {
- // for the statistics
- currentEvent->isBindingLoop = true;
- for (int j = stackRefs.indexOf(currentEvent); j < stackRefs.count()-1; j++) {
- QmlRangeEventRelative *nextEventSub =
- stackRefs[j]->childrenHash.value(stackRefs[j+1]->eventHashStr);
- nextEventSub->inLoopPath = true;
- QmlRangeEventRelative *prevEventSub =
- stackRefs[j+1]->parentHash.value(stackRefs[j]->eventHashStr);
- prevEventSub->inLoopPath = true;
- }
- }
-
- // use crossed references to find index in starttimesortedlist
- QmlRangeEventStartInstance *head = stack[stackRefs.indexOf(currentEvent)];
- inTimeEvent->bindingLoopHead = endInstanceList[head->endTimeIndex].startTimeIndex;
- startInstanceList[inTimeEvent->bindingLoopHead].bindingLoopHead = i;
- }
- }
-}
-
-////////////////////////////////////////////////////////////////////////////////////
-
-void QmlProfilerDataModel::QmlProfilerDataModelPrivate::clearQmlRootEvent()
-{
- qmlRootEvent.displayName = rootEventName();
- qmlRootEvent.location = QmlEventLocation();
- qmlRootEvent.eventHashStr = rootEventName();
- qmlRootEvent.details = rootEventDescription();
- qmlRootEvent.eventType = QmlDebug::Binding;
- qmlRootEvent.duration = 0;
- qmlRootEvent.calls = 0;
- qmlRootEvent.minTime = 0;
- qmlRootEvent.maxTime = 0;
- qmlRootEvent.timePerCall = 0;
- qmlRootEvent.percentOfTime = 0;
- qmlRootEvent.medianTime = 0;
- qmlRootEvent.eventId = -1;
-
- qDeleteAll(qmlRootEvent.parentHash);
- qDeleteAll(qmlRootEvent.childrenHash);
- qmlRootEvent.parentHash.clear();
- qmlRootEvent.childrenHash.clear();
-}
-
-void QmlProfilerDataModel::QmlProfilerDataModelPrivate::insertQmlRootEvent()
-{
- // create root event for statistics & insert into list
- clearQmlRootEvent();
- QmlRangeEventData *listedRootEvent = rangeEventDictionary.value(rootEventName());
- if (!listedRootEvent) {
- listedRootEvent = new QmlRangeEventData;
- rangeEventDictionary.insert(rootEventName(), listedRootEvent);
- }
- *listedRootEvent = qmlRootEvent;
-}
-
-void QmlProfilerDataModel::reloadDetails()
-{
- // request binding/signal details from the AST
- foreach (QmlRangeEventData *event, d->rangeEventDictionary.values()) {
- if (event->eventType != Binding && event->eventType != HandlingSignal)
- continue;
-
- // This skips anonymous bindings in Qt4.8 (we don't have valid location data for them)
- if (event->location.filename.isEmpty())
- continue;
-
- // Skip non-anonymous bindings from Qt4.8 (we already have correct details for them)
- if (event->location.column == -1)
- continue;
-
- emit requestDetailsForLocation(event->eventType, event->location);
- }
- emit reloadDocumentsForDetails();
-}
-
-void QmlProfilerDataModel::rewriteDetailsString(int eventType,
- const QmlDebug::QmlEventLocation &location,
- const QString &newString)
-{
- QString eventHashStr = getHashStringForQmlEvent(location, eventType);
- QTC_ASSERT(d->rangeEventDictionary.contains(eventHashStr), return);
- d->rangeEventDictionary.value(eventHashStr)->details = newString;
- emit detailsChanged(d->rangeEventDictionary.value(eventHashStr)->eventId, newString);
-}
-
-void QmlProfilerDataModel::finishedRewritingDetails()
-{
- emit reloadDetailLabels();
-}
-
-////////////////////////////////////////////////////////////////////////////////////
-
-bool QmlProfilerDataModel::save(const QString &filename)
-{
- if (isEmpty()) {
- emit error(tr("No data to save."));
- return false;
- }
-
- QFile file(filename);
- if (!file.open(QIODevice::WriteOnly)) {
- emit error(tr("Could not open %1 for writing.").arg(filename));
- return false;
- }
-
- QXmlStreamWriter stream(&file);
- stream.setAutoFormatting(true);
- stream.writeStartDocument();
-
- stream.writeStartElement(QLatin1String("trace"));
- stream.writeAttribute(QLatin1String("version"), QLatin1String(Constants::PROFILER_FILE_VERSION));
-
- stream.writeAttribute(QLatin1String("traceStart"), QString::number(traceStartTime()));
- stream.writeAttribute(QLatin1String("traceEnd"), QString::number(traceEndTime()));
-
- stream.writeStartElement(QLatin1String("eventData"));
- stream.writeAttribute(QLatin1String("totalTime"), QString::number(d->qmlMeasuredTime));
-
- foreach (const QmlRangeEventData *eventData, d->rangeEventDictionary.values()) {
- 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(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(QLatin1String("details"), eventData->details);
- if (eventData->eventType == Binding)
- stream.writeTextElement(QLatin1String("bindingType"), QString::number((int)eventData->bindingType));
- stream.writeEndElement();
- }
- stream.writeEndElement(); // eventData
-
- stream.writeStartElement(QLatin1String("profilerDataModel"));
- foreach (const QmlRangeEventStartInstance &rangedEvent, d->startInstanceList) {
- 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(QLatin1String("framerate"), QString::number(rangedEvent.frameRate));
- stream.writeAttribute(QLatin1String("animationcount"), QString::number(rangedEvent.animationCount));
- }
- stream.writeEndElement();
- }
- stream.writeEndElement(); // profilerDataModel
-
- d->v8DataModel->save(stream);
-
- stream.writeEndElement(); // trace
- stream.writeEndDocument();
-
- file.close();
- return true;
-}
-
-void QmlProfilerDataModel::setFilename(const QString &filename)
-{
- d->fileName = filename;
-}
-
-void QmlProfilerDataModel::load(const QString &filename)
-{
- setFilename(filename);
- load();
-}
-
-// "be strict in your output but tolerant in your inputs"
-void QmlProfilerDataModel::load()
-{
- QString filename = d->fileName;
-
- QFile file(filename);
-
- if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
- emit error(tr("Could not open %1 for reading.").arg(filename));
- return;
- }
-
- // erase current
- clear();
-
- setState(AcquiringData);
-
- bool readingQmlEvents = false;
- QHash<int, QmlRangeEventData *> descriptionBuffer;
- QmlRangeEventData *currentEvent = 0;
- bool startTimesAreSorted = true;
- bool validVersion = true;
-
- // time computation
- d->qmlMeasuredTime = 0;
-
- QXmlStreamReader stream(&file);
-
- while (validVersion && !stream.atEnd() && !stream.hasError()) {
- QXmlStreamReader::TokenType token = stream.readNext();
- QString elementName = stream.name().toString();
- switch (token) {
- case QXmlStreamReader::StartDocument : continue;
- case QXmlStreamReader::StartElement : {
- if (elementName == QLatin1String("trace")) {
- QXmlStreamAttributes attributes = stream.attributes();
- if (attributes.hasAttribute(QLatin1String("version")))
- validVersion = attributes.value(QLatin1String("version")).toString() == QLatin1String(Constants::PROFILER_FILE_VERSION);
- else
- validVersion = false;
- 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 == QLatin1String("eventData")) {
- readingQmlEvents = true;
- QXmlStreamAttributes attributes = stream.attributes();
- if (attributes.hasAttribute(QLatin1String("totalTime")))
- d->qmlMeasuredTime = attributes.value(QLatin1String("totalTime")).toString().toDouble();
- break;
- }
- if (elementName == QLatin1String("v8profile") && !readingQmlEvents) {
- d->v8DataModel->load(stream);
- break;
- }
-
- if (elementName == QLatin1String("trace")) {
- QXmlStreamAttributes attributes = stream.attributes();
- 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 == QLatin1String("range")) {
- QmlRangeEventStartInstance rangedEvent;
- QXmlStreamAttributes attributes = stream.attributes();
- 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(QLatin1String("eventIndex"))) {
- int ndx = attributes.value(QLatin1String("eventIndex")).toString().toInt();
- if (!descriptionBuffer.value(ndx))
- descriptionBuffer[ndx] = new QmlRangeEventData;
- rangedEvent.statsInfo = descriptionBuffer.value(ndx);
- }
- rangedEvent.endTimeIndex = d->endInstanceList.count();
-
- if (!d->startInstanceList.isEmpty()
- && rangedEvent.startTime < d->startInstanceList.last().startTime)
- startTimesAreSorted = false;
- d->startInstanceList << rangedEvent;
-
- QmlRangeEventEndInstance endTimeEvent;
- endTimeEvent.endTime = rangedEvent.startTime + rangedEvent.duration;
- endTimeEvent.startTimeIndex = d->startInstanceList.count()-1;
- endTimeEvent.description = rangedEvent.statsInfo;
- d->endInstanceList << endTimeEvent;
- break;
- }
-
- if (readingQmlEvents) {
- if (elementName == QLatin1String("event")) {
- QXmlStreamAttributes attributes = stream.attributes();
- if (attributes.hasAttribute(QLatin1String("index"))) {
- int ndx = attributes.value(QLatin1String("index")).toString().toInt();
- if (!descriptionBuffer.value(ndx))
- descriptionBuffer[ndx] = new QmlRangeEventData;
- currentEvent = descriptionBuffer[ndx];
- // backwards compatibility: default bindingType
- currentEvent->bindingType = QmlBinding;
- } else {
- currentEvent = 0;
- }
- break;
- }
-
- // the remaining are eventdata or v8eventdata elements
- if (!currentEvent)
- break;
-
- stream.readNext();
- if (stream.tokenType() != QXmlStreamReader::Characters)
- break;
- QString readData = stream.text().toString();
-
- if (elementName == QLatin1String("displayname")) {
- currentEvent->displayName = readData;
- break;
- }
- if (elementName == QLatin1String("type")) {
- currentEvent->eventType = qmlEventTypeAsEnum(readData);
- break;
- }
- if (elementName == QLatin1String("filename")) {
- currentEvent->location.filename = readData;
- break;
- }
- if (elementName == QLatin1String("line")) {
- currentEvent->location.line = readData.toInt();
- break;
- }
- if (elementName == QLatin1String("column"))
- currentEvent->location.column = readData.toInt();
- if (elementName == QLatin1String("details")) {
- currentEvent->details = readData;
- break;
- }
- if (elementName == QLatin1String("bindingType")) {
- currentEvent->bindingType = readData.toInt();
- break;
- }
- }
- break;
- }
- case QXmlStreamReader::EndElement : {
- if (elementName == QLatin1String("event")) {
- currentEvent = 0;
- break;
- }
- if (elementName == QLatin1String("eventData")) {
- readingQmlEvents = false;
- break;
- }
- }
- default: break;
- }
- }
-
- file.close();
-
- if (stream.hasError()) {
- emit error(tr("Error while parsing %1.").arg(filename));
- clear();
- return;
- }
-
- stream.clear();
-
- if (!validVersion) {
- clear();
- emit error(tr("Invalid version of QML Trace file."));
- return;
- }
-
- // move the buffered data to the details cache
- foreach (QmlRangeEventData *desc, descriptionBuffer.values()) {
- desc->eventHashStr = getHashStringForQmlEvent(desc->location, desc->eventType);;
- d->rangeEventDictionary[desc->eventHashStr] = desc;
- }
-
- // sort startTimeSortedList
- if (!startTimesAreSorted) {
- qSort(d->startInstanceList.begin(), d->startInstanceList.end(), compareStartTimes);
- for (int i = 0; i< d->startInstanceList.count(); i++) {
- QmlRangeEventStartInstance startTimeData = d->startInstanceList[i];
- d->endInstanceList[startTimeData.endTimeIndex].startTimeIndex = i;
- }
- qSort(d->endInstanceList.begin(), d->endInstanceList.end(), compareStartIndexes);
- }
-
- emit countChanged();
-
- descriptionBuffer.clear();
-
- setState(ProcessingData);
- d->postProcess();
-}
-
-////////////////////////////////////////////////////////////////////////////////////
-
-QmlProfilerDataModel::State QmlProfilerDataModel::currentState() const
-{
- return d->listState;
-}
-
-int QmlProfilerDataModel::getCurrentStateFromQml() const
-{
- return (int)d->listState;
-}
-
-void QmlProfilerDataModel::setState(QmlProfilerDataModel::State state)
-{
- // It's not an error, we are continuously calling "AcquiringData" for example
- if (d->listState == state)
- return;
-
- switch (state) {
- case Empty:
- // if it's not empty, complain but go on
- QTC_ASSERT(isEmpty(), /**/);
- break;
- case AcquiringData:
- // we're not supposed to receive new data while processing older data
- QTC_ASSERT(d->listState != ProcessingData, return);
- break;
- case ProcessingData:
- QTC_ASSERT(d->listState == AcquiringData, return);
- break;
- case Done:
- QTC_ASSERT(d->listState == ProcessingData || d->listState == Empty, return);
- break;
- default:
- emit error(tr("Trying to set unknown state in events list."));
- break;
- }
-
- d->listState = state;
- emit stateChanged();
-
- return;
-}
-
-} // namespace Internal
-} // namespace QmlProfiler
-
-QT_BEGIN_NAMESPACE
-Q_DECLARE_TYPEINFO(QmlProfiler::Internal::QmlRangeEventData, Q_MOVABLE_TYPE);
-Q_DECLARE_TYPEINFO(QmlProfiler::Internal::QmlRangeEventStartInstance, Q_MOVABLE_TYPE);
-Q_DECLARE_TYPEINFO(QmlProfiler::Internal::QmlRangeEventEndInstance, Q_MOVABLE_TYPE);
-Q_DECLARE_TYPEINFO(QmlProfiler::Internal::QmlRangeEventRelative, Q_MOVABLE_TYPE);
-QT_END_NAMESPACE
diff --git a/src/plugins/qmlprofiler/qmlprofilerdatamodel.h b/src/plugins/qmlprofiler/qmlprofilerdatamodel.h
deleted file mode 100644
index 0eb31b43f2..0000000000
--- a/src/plugins/qmlprofiler/qmlprofilerdatamodel.h
+++ /dev/null
@@ -1,201 +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 QMLPROFILERDATAMODEL_H
-#define QMLPROFILERDATAMODEL_H
-
-#include <qmldebug/qmlprofilereventtypes.h>
-#include <qmldebug/qmlprofilereventlocation.h>
-#include "qv8profilerdatamodel.h"
-
-#include <QHash>
-#include <QObject>
-
-namespace QmlProfiler {
-namespace Internal {
-
-// used for parents and children
-struct QmlRangeEventRelative;
-
-struct QmlRangeEventData
-{
- QmlRangeEventData();
- ~QmlRangeEventData();
-
- int eventId;
- int bindingType;
- QString displayName;
- QString eventHashStr;
- QString details;
- QmlDebug::QmlEventLocation location;
- QmlDebug::QmlEventType eventType;
-
- bool isBindingLoop;
-
- QHash <QString, QmlRangeEventRelative *> parentHash;
- QHash <QString, QmlRangeEventRelative *> childrenHash;
-
- qint64 duration;
- qint64 calls;
- qint64 minTime;
- qint64 maxTime;
- double timePerCall;
- double percentOfTime;
- qint64 medianTime;
-
- QmlRangeEventData &operator=(const QmlRangeEventData &ref);
-};
-
-struct QmlRangeEventRelative {
- QmlRangeEventRelative(QmlRangeEventData *from) : reference(from), duration(0), calls(0), inLoopPath(false) {}
- QmlRangeEventRelative(QmlRangeEventRelative *from) : reference(from->reference), duration(from->duration), calls(from->calls), inLoopPath(from->inLoopPath) {}
- QmlRangeEventData *reference;
- qint64 duration;
- qint64 calls;
- bool inLoopPath;
-};
-
-class QmlProfilerDataModel : public QObject
-{
- Q_OBJECT
-public:
- enum State {
- Empty,
- AcquiringData,
- ProcessingData,
- Done
- };
-
- explicit QmlProfilerDataModel(QObject *parent = 0);
- ~QmlProfilerDataModel();
-
- QList<QmlRangeEventData *> getEventDescriptions() const;
- QmlRangeEventData *eventDescription(int eventId) const;
- QList<QV8EventData *> getV8Events() const;
- QV8EventData *v8EventDescription(int eventId) const;
-
- static QString getHashStringForQmlEvent(const QmlDebug::QmlEventLocation &location, int eventType);
- static QString getHashStringForV8Event(const QString &displayName, const QString &function);
- static QString rootEventName();
- static QString rootEventDescription();
- static QString qmlEventTypeAsString(QmlDebug::QmlEventType typeEnum);
- static QmlDebug::QmlEventType qmlEventTypeAsEnum(const QString &typeString);
-
- int findFirstIndex(qint64 startTime) const;
- int findFirstIndexNoParents(qint64 startTime) const;
- int findLastIndex(qint64 endTime) const;
- Q_INVOKABLE qint64 firstTimeMark() const;
- Q_INVOKABLE qint64 lastTimeMark() const;
-
- // data access
- Q_INVOKABLE int count() const;
- Q_INVOKABLE bool isEmpty() const;
- Q_INVOKABLE qint64 getStartTime(int index) const;
- Q_INVOKABLE qint64 getEndTime(int index) const;
- Q_INVOKABLE qint64 getDuration(int index) const;
- Q_INVOKABLE int getType(int index) const;
- Q_INVOKABLE int getNestingLevel(int index) const;
- Q_INVOKABLE int getNestingDepth(int index) const;
- Q_INVOKABLE QString getFilename(int index) const;
- Q_INVOKABLE int getLine(int index) const;
- Q_INVOKABLE int getColumn(int index) const;
- Q_INVOKABLE QString getDetails(int index) const;
- Q_INVOKABLE int getEventId(int index) const;
- Q_INVOKABLE int getBindingLoopDest(int index) const;
- Q_INVOKABLE int getFramerate(int index) const;
- Q_INVOKABLE int getAnimationCount(int index) const;
- Q_INVOKABLE int getMaximumAnimationCount() const;
- Q_INVOKABLE int getMinimumAnimationCount() const;
-
-
- // per-type data
- Q_INVOKABLE int uniqueEventsOfType(int type) const;
- Q_INVOKABLE int maxNestingForType(int type) const;
- Q_INVOKABLE QString eventTextForType(int type, int index) const;
- Q_INVOKABLE QString eventDisplayNameForType(int type, int index) const;
- Q_INVOKABLE int eventIdForType(int type, int index) const;
- Q_INVOKABLE int eventPosInType(int index) const;
-
- Q_INVOKABLE qint64 traceStartTime() const;
- Q_INVOKABLE qint64 traceEndTime() const;
- Q_INVOKABLE qint64 traceDuration() const;
- Q_INVOKABLE qint64 qmlMeasuredTime() const;
- Q_INVOKABLE qint64 v8MeasuredTime() const;
-
- void compileStatistics(qint64 startTime, qint64 endTime);
- State currentState() const;
- Q_INVOKABLE int getCurrentStateFromQml() const;
-
-signals:
- void stateChanged();
- void countChanged();
- void error(const QString &error);
-
- void requestDetailsForLocation(int eventType, const QmlDebug::QmlEventLocation &location);
- void detailsChanged(int eventId, const QString &newString);
- void reloadDetailLabels();
- void reloadDocumentsForDetails();
-
-public slots:
- void clear();
-
- void prepareForWriting();
- void addRangedEvent(int type, int bindingType, qint64 startTime, qint64 length,
- const QStringList &data, const QmlDebug::QmlEventLocation &location);
- void addV8Event(int depth,const QString &function,const QString &filename, int lineNumber, double totalTime, double selfTime);
- void addFrameEvent(qint64 time, int framerate, int animationcount);
- void setTraceStartTime(qint64 time);
- void setTraceEndTime(qint64 time);
-
- void complete();
-
- bool save(const QString &filename);
- void load(const QString &filename);
- void setFilename(const QString &filename);
- void load();
-
- void rewriteDetailsString(int eventType, const QmlDebug::QmlEventLocation &location, const QString &newString);
- void finishedRewritingDetails();
-
-private:
- void setState(State state);
- void reloadDetails();
-
-private:
- class QmlProfilerDataModelPrivate;
- QmlProfilerDataModelPrivate *d;
-
- friend class QV8ProfilerDataModel;
-};
-
-
-} // namespace Internal
-} // namespace QmlProfiler
-
-#endif // QMLPROFILERDATAMODEL_H
diff --git a/src/plugins/qmlprofiler/qmlprofilerdetailsrewriter.cpp b/src/plugins/qmlprofiler/qmlprofilerdetailsrewriter.cpp
index 2385e42c1c..0b078f9c86 100644
--- a/src/plugins/qmlprofiler/qmlprofilerdetailsrewriter.cpp
+++ b/src/plugins/qmlprofiler/qmlprofilerdetailsrewriter.cpp
@@ -41,7 +41,7 @@ namespace Internal {
struct PendingEvent {
QmlDebug::QmlEventLocation location;
QString localFile;
- int eventType;
+ int requestId;
};
class PropertyVisitor: protected QmlJS::AST::Visitor
@@ -122,7 +122,7 @@ QmlProfilerDetailsRewriter::~QmlProfilerDetailsRewriter()
delete d;
}
-void QmlProfilerDetailsRewriter::requestDetailsForLocation(int type,
+void QmlProfilerDetailsRewriter::requestDetailsForLocation(int requestId,
const QmlDebug::QmlEventLocation &location)
{
const QString localFile = d->m_projectFinder->findFile(location.filename);
@@ -132,7 +132,7 @@ void QmlProfilerDetailsRewriter::requestDetailsForLocation(int type,
if (!QmlJS::Document::isQmlLikeLanguage(QmlJSTools::languageOfFile(localFile)))
return;
- PendingEvent ev = {location, localFile, type};
+ PendingEvent ev = {location, localFile, requestId};
d->m_pendingEvents << ev;
if (!d->m_pendingDocs.contains(localFile)) {
if (d->m_pendingDocs.isEmpty())
@@ -154,7 +154,7 @@ void QmlProfilerDetailsRewriter::reloadDocuments()
}
void QmlProfilerDetailsRewriter::rewriteDetailsForLocation(QTextStream &textDoc,
- QmlJS::Document::Ptr doc, int type, const QmlDebug::QmlEventLocation &location)
+ QmlJS::Document::Ptr doc, int requestId, const QmlDebug::QmlEventLocation &location)
{
PropertyVisitor propertyVisitor;
QmlJS::AST::Node *node = propertyVisitor(doc->ast(), location.line, location.column);
@@ -168,7 +168,12 @@ void QmlProfilerDetailsRewriter::rewriteDetailsForLocation(QTextStream &textDoc,
textDoc.seek(startPos);
QString details = textDoc.read(len).replace(QLatin1Char('\n'), QLatin1Char(' ')).simplified();
- emit rewriteDetailsString(type, location, details);
+ emit rewriteDetailsString(requestId, details);
+}
+
+void QmlProfilerDetailsRewriter::clearRequests()
+{
+ d->m_pendingDocs.clear();
}
void QmlProfilerDetailsRewriter::documentReady(QmlJS::Document::Ptr doc)
@@ -186,7 +191,7 @@ void QmlProfilerDetailsRewriter::documentReady(QmlJS::Document::Ptr doc)
PendingEvent ev = d->m_pendingEvents[i];
if (ev.localFile == doc->fileName()) {
d->m_pendingEvents.removeAt(i);
- rewriteDetailsForLocation(st, doc, ev.eventType, ev.location);
+ rewriteDetailsForLocation(st, doc, ev.requestId, ev.location);
}
}
}
diff --git a/src/plugins/qmlprofiler/qmlprofilerdetailsrewriter.h b/src/plugins/qmlprofiler/qmlprofilerdetailsrewriter.h
index 2ec65606d2..21e94a1bf3 100644
--- a/src/plugins/qmlprofiler/qmlprofilerdetailsrewriter.h
+++ b/src/plugins/qmlprofiler/qmlprofilerdetailsrewriter.h
@@ -46,16 +46,18 @@ public:
explicit QmlProfilerDetailsRewriter(QObject *parent, Utils::FileInProjectFinder *fileFinder);
~QmlProfilerDetailsRewriter();
+ void clearRequests();
+
private:
- void rewriteDetailsForLocation(QTextStream &textDoc,QmlJS::Document::Ptr doc, int type,
+ void rewriteDetailsForLocation(QTextStream &textDoc, QmlJS::Document::Ptr doc, int requestId,
const QmlDebug::QmlEventLocation &location);
+
public slots:
- void requestDetailsForLocation(int type, const QmlDebug::QmlEventLocation &location);
+ void requestDetailsForLocation(int requestId, const QmlDebug::QmlEventLocation &location);
void reloadDocuments();
void documentReady(QmlJS::Document::Ptr doc);
signals:
- void rewriteDetailsString(int type, const QmlDebug::QmlEventLocation &location,
- const QString &details);
+ void rewriteDetailsString(int requestId, const QString &details);
void eventDetailsChanged();
private:
class QmlProfilerDetailsRewriterPrivate;
diff --git a/src/plugins/qmlprofiler/qmlprofilerengine.cpp b/src/plugins/qmlprofiler/qmlprofilerengine.cpp
index 19395845b6..6282c5c0e6 100644
--- a/src/plugins/qmlprofiler/qmlprofilerengine.cpp
+++ b/src/plugins/qmlprofiler/qmlprofilerengine.cpp
@@ -33,7 +33,6 @@
#include <analyzerbase/analyzermanager.h>
#include <coreplugin/icore.h>
-#include <debugger/debuggerrunconfigurationaspect.h>
#include <utils/qtcassert.h>
#include <coreplugin/helpmanager.h>
#include <projectexplorer/projectexplorerconstants.h>
@@ -52,6 +51,7 @@
#include <QTcpServer>
using namespace Analyzer;
+using namespace Core;
using namespace ProjectExplorer;
namespace QmlProfiler {
@@ -61,20 +61,14 @@ namespace Internal {
// QmlProfilerEnginePrivate
//
-class QmlProfilerEngine::QmlProfilerEnginePrivate
+class QmlProfilerRunControl::QmlProfilerEnginePrivate
{
public:
- QmlProfilerEnginePrivate(QmlProfilerEngine *qq, const AnalyzerStartParameters &sp) : q(qq), sp(sp), m_running(false) {}
-
- bool attach(const QString &address, uint port);
-
- QmlProfilerEngine *q;
+ QmlProfilerEnginePrivate() : m_running(false) {}
QmlProfilerStateManager *m_profilerState;
-
QTimer m_noDebugOutputTimer;
QmlDebug::QmlOutputParser m_outputParser;
- const AnalyzerStartParameters sp;
bool m_running;
};
@@ -82,15 +76,14 @@ public:
// QmlProfilerEngine
//
-QmlProfilerEngine::QmlProfilerEngine(IAnalyzerTool *tool,
- const Analyzer::AnalyzerStartParameters &sp,
- ProjectExplorer::RunConfiguration *runConfiguration)
- : IAnalyzerEngine(tool, sp, runConfiguration)
- , d(new QmlProfilerEnginePrivate(this, sp))
+QmlProfilerRunControl::QmlProfilerRunControl(const AnalyzerStartParameters &sp,
+ RunConfiguration *runConfiguration)
+ : AnalyzerRunControl(sp, runConfiguration)
+ , d(new QmlProfilerEnginePrivate)
{
d->m_profilerState = 0;
- // Only wait 4 seconds for the 'Waiting for connection' on application ouput, then just try to connect
+ // Only wait 4 seconds for the 'Waiting for connection' on application output, then just try to connect
// (application output might be redirected / blocked)
d->m_noDebugOutputTimer.setSingleShot(true);
d->m_noDebugOutputTimer.setInterval(4000);
@@ -105,14 +98,14 @@ QmlProfilerEngine::QmlProfilerEngine(IAnalyzerTool *tool,
this, SLOT(wrongSetupMessageBox(QString)));
}
-QmlProfilerEngine::~QmlProfilerEngine()
+QmlProfilerRunControl::~QmlProfilerRunControl()
{
if (d->m_profilerState && d->m_profilerState->currentState() == QmlProfilerStateManager::AppRunning)
- stop();
+ stopEngine();
delete d;
}
-bool QmlProfilerEngine::start()
+bool QmlProfilerRunControl::startEngine()
{
QTC_ASSERT(d->m_profilerState, return false);
@@ -128,7 +121,7 @@ bool QmlProfilerEngine::start()
}
}
- if (d->sp.startMode == StartQmlRemote || d->sp.startMode == StartLocal) {
+ if (startParameters().startMode == StartLocal) {
d->m_noDebugOutputTimer.start();
} else {
emit processRunning(startParameters().analyzerPort);
@@ -139,7 +132,7 @@ bool QmlProfilerEngine::start()
return true;
}
-void QmlProfilerEngine::stop()
+void QmlProfilerRunControl::stopEngine()
{
QTC_ASSERT(d->m_profilerState, return);
@@ -164,7 +157,7 @@ void QmlProfilerEngine::stop()
}
}
-void QmlProfilerEngine::notifyRemoteFinished(bool success)
+void QmlProfilerRunControl::notifyRemoteFinished(bool success)
{
QTC_ASSERT(d->m_profilerState, return);
@@ -176,7 +169,7 @@ void QmlProfilerEngine::notifyRemoteFinished(bool success)
d->m_profilerState->setCurrentState(QmlProfilerStateManager::AppKilled);
AnalyzerManager::stopTool();
- engineFinished();
+ runControlFinished();
break;
}
case QmlProfilerStateManager::AppStopped :
@@ -192,7 +185,7 @@ void QmlProfilerEngine::notifyRemoteFinished(bool success)
}
}
-void QmlProfilerEngine::cancelProcess()
+void QmlProfilerRunControl::cancelProcess()
{
QTC_ASSERT(d->m_profilerState, return);
@@ -212,18 +205,18 @@ void QmlProfilerEngine::cancelProcess()
return;
}
}
- engineFinished();
+ runControlFinished();
}
-void QmlProfilerEngine::logApplicationMessage(const QString &msg, Utils::OutputFormat format)
+void QmlProfilerRunControl::logApplicationMessage(const QString &msg, Utils::OutputFormat format)
{
- emit outputReceived(msg, format);
+ appendMessage(msg, format);
d->m_outputParser.processOutput(msg);
}
-void QmlProfilerEngine::wrongSetupMessageBox(const QString &errorMessage)
+void QmlProfilerRunControl::wrongSetupMessageBox(const QString &errorMessage)
{
- QMessageBox *infoBox = new QMessageBox(Core::ICore::mainWindow());
+ QMessageBox *infoBox = new QMessageBox(ICore::mainWindow());
infoBox->setIcon(QMessageBox::Critical);
infoBox->setWindowTitle(tr("Qt Creator"));
//: %1 is detailed error message
@@ -241,21 +234,20 @@ void QmlProfilerEngine::wrongSetupMessageBox(const QString &errorMessage)
// KILL
d->m_profilerState->setCurrentState(QmlProfilerStateManager::AppDying);
AnalyzerManager::stopTool();
- engineFinished();
+ runControlFinished();
}
-void QmlProfilerEngine::wrongSetupMessageBoxFinished(int button)
+void QmlProfilerRunControl::wrongSetupMessageBoxFinished(int button)
{
if (button == QMessageBox::Help) {
- Core::HelpManager *helpManager = Core::HelpManager::instance();
- helpManager->handleHelpRequest(QLatin1String("qthelp://org.qt-project.qtcreator/doc/creator-debugging-qml.html"
+ HelpManager::handleHelpRequest(QLatin1String("qthelp://org.qt-project.qtcreator/doc/creator-debugging-qml.html"
"#setting-up-qml-debugging"));
}
}
-void QmlProfilerEngine::showNonmodalWarning(const QString &warningMsg)
+void QmlProfilerRunControl::showNonmodalWarning(const QString &warningMsg)
{
- QMessageBox *noExecWarning = new QMessageBox(Core::ICore::mainWindow());
+ QMessageBox *noExecWarning = new QMessageBox(ICore::mainWindow());
noExecWarning->setIcon(QMessageBox::Warning);
noExecWarning->setWindowTitle(tr("QML Profiler"));
noExecWarning->setText(warningMsg);
@@ -265,27 +257,27 @@ void QmlProfilerEngine::showNonmodalWarning(const QString &warningMsg)
noExecWarning->show();
}
-void QmlProfilerEngine::notifyRemoteSetupDone(quint16 port)
+void QmlProfilerRunControl::notifyRemoteSetupDone(quint16 port)
{
d->m_noDebugOutputTimer.stop();
emit processRunning(port);
}
-void QmlProfilerEngine::processIsRunning(quint16 port)
+void QmlProfilerRunControl::processIsRunning(quint16 port)
{
d->m_noDebugOutputTimer.stop();
- if (port > 0 && mode() != StartQmlRemote)
+ if (port > 0 && startParameters().analyzerPort != 0)
emit processRunning(port);
}
-void QmlProfilerEngine::engineStarted()
+void QmlProfilerRunControl::engineStarted()
{
d->m_running = true;
emit starting(this);
}
-void QmlProfilerEngine::engineFinished()
+void QmlProfilerRunControl::runControlFinished()
{
d->m_running = false;
emit finished();
@@ -293,7 +285,7 @@ void QmlProfilerEngine::engineFinished()
////////////////////////////////////////////////////////////////
// Profiler State
-void QmlProfilerEngine::registerProfilerStateManager( QmlProfilerStateManager *profilerState )
+void QmlProfilerRunControl::registerProfilerStateManager( QmlProfilerStateManager *profilerState )
{
// disconnect old
if (d->m_profilerState)
@@ -306,7 +298,7 @@ void QmlProfilerEngine::registerProfilerStateManager( QmlProfilerStateManager *p
connect(d->m_profilerState, SIGNAL(stateChanged()), this, SLOT(profilerStateChanged()));
}
-void QmlProfilerEngine::profilerStateChanged()
+void QmlProfilerRunControl::profilerStateChanged()
{
switch (d->m_profilerState->currentState()) {
case QmlProfilerStateManager::AppReadyToStop : {
diff --git a/src/plugins/qmlprofiler/qmlprofilerengine.h b/src/plugins/qmlprofiler/qmlprofilerengine.h
index aea3c8bf8d..cf0b476f9f 100644
--- a/src/plugins/qmlprofiler/qmlprofilerengine.h
+++ b/src/plugins/qmlprofiler/qmlprofilerengine.h
@@ -30,22 +30,22 @@
#ifndef QMLPROFILERENGINE_H
#define QMLPROFILERENGINE_H
-#include <analyzerbase/ianalyzerengine.h>
#include "qmlprofilerstatemanager.h"
+
+#include <analyzerbase/analyzerruncontrol.h>
#include <utils/outputformat.h>
namespace QmlProfiler {
namespace Internal {
-class QmlProfilerEngine : public Analyzer::IAnalyzerEngine
+class QmlProfilerRunControl : public Analyzer::AnalyzerRunControl
{
Q_OBJECT
public:
- QmlProfilerEngine(Analyzer::IAnalyzerTool *tool,
- const Analyzer::AnalyzerStartParameters &sp,
+ QmlProfilerRunControl(const Analyzer::AnalyzerStartParameters &sp,
ProjectExplorer::RunConfiguration *runConfiguration);
- ~QmlProfilerEngine();
+ ~QmlProfilerRunControl();
void registerProfilerStateManager( QmlProfilerStateManager *profilerState );
@@ -58,8 +58,8 @@ signals:
void timeUpdate();
public slots:
- bool start();
- void stop();
+ bool startEngine();
+ void stopEngine();
private slots:
void notifyRemoteFinished(bool success = true);
@@ -70,7 +70,7 @@ private slots:
void wrongSetupMessageBoxFinished(int);
void processIsRunning(quint16 port = 0);
void engineStarted();
- void engineFinished();
+ void runControlFinished();
private slots:
void profilerStateChanged();
diff --git a/src/plugins/qmlprofiler/qmlprofilereventsmodelproxy.cpp b/src/plugins/qmlprofiler/qmlprofilereventsmodelproxy.cpp
new file mode 100644
index 0000000000..d1be7cfdb3
--- /dev/null
+++ b/src/plugins/qmlprofiler/qmlprofilereventsmodelproxy.cpp
@@ -0,0 +1,479 @@
+/****************************************************************************
+**
+** 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 "qmlprofilereventsmodelproxy.h"
+#include "qmlprofilermodelmanager.h"
+#include "qmlprofilersimplemodel.h"
+
+#include <utils/qtcassert.h>
+
+#include <QVector>
+#include <QHash>
+#include <QUrl>
+#include <QString>
+#include <QStack>
+#include <QElapsedTimer>
+
+#include <QDebug>
+
+namespace QmlProfiler {
+namespace Internal {
+
+class QmlProfilerEventsModelProxy::QmlProfilerEventsModelProxyPrivate
+{
+public:
+ QmlProfilerEventsModelProxyPrivate(QmlProfilerEventsModelProxy *qq) : q(qq) {}
+ ~QmlProfilerEventsModelProxyPrivate() {}
+
+ QHash<QString, QmlProfilerEventsModelProxy::QmlEventStats> data;
+
+ QmlProfilerModelManager *modelManager;
+ QmlProfilerEventsModelProxy *q;
+
+ int modelId;
+
+ QVector<int> acceptedTypes;
+ QSet<QString> eventsInBindingLoop;
+};
+
+QmlProfilerEventsModelProxy::QmlProfilerEventsModelProxy(QmlProfilerModelManager *modelManager, QObject *parent)
+ : QObject(parent), d(new QmlProfilerEventsModelProxyPrivate(this))
+{
+ d->modelManager = modelManager;
+ connect(modelManager->simpleModel(), SIGNAL(changed()), this, SLOT(dataChanged()));
+ d->modelId = modelManager->registerModelProxy();
+
+ d->acceptedTypes << QmlDebug::Compiling << QmlDebug::Creating << QmlDebug::Binding << QmlDebug::HandlingSignal;
+}
+
+QmlProfilerEventsModelProxy::~QmlProfilerEventsModelProxy()
+{
+ delete d;
+}
+
+const QList<QmlProfilerEventsModelProxy::QmlEventStats> QmlProfilerEventsModelProxy::getData() const
+{
+ return d->data.values();
+}
+
+void QmlProfilerEventsModelProxy::clear()
+{
+ d->modelManager->modelProxyCountUpdated(d->modelId, 0, 1);
+ d->data.clear();
+ d->eventsInBindingLoop.clear();
+}
+
+void QmlProfilerEventsModelProxy::limitToRange(qint64 rangeStart, qint64 rangeEnd)
+{
+ loadData(rangeStart, rangeEnd);
+}
+
+void QmlProfilerEventsModelProxy::dataChanged()
+{
+ if (d->modelManager->state() == QmlProfilerDataState::ProcessingData)
+ loadData();
+
+ if (d->modelManager->state() == QmlProfilerDataState::Empty)
+ clear();
+}
+
+QSet<QString> QmlProfilerEventsModelProxy::eventsInBindingLoop() const
+{
+ return d->eventsInBindingLoop;
+}
+
+void QmlProfilerEventsModelProxy::loadData(qint64 rangeStart, qint64 rangeEnd)
+{
+ clear();
+
+ qint64 qmlTime = 0;
+ qint64 lastEndTime = 0;
+ QHash <QString, QVector<qint64> > durations;
+
+ const bool checkRanges = (rangeStart != -1) && (rangeEnd != -1);
+
+ const QVector<QmlProfilerSimpleModel::QmlEventData> eventList
+ = d->modelManager->simpleModel()->getEvents();
+
+ // used by binding loop detection
+ typedef QPair<QString, const QmlProfilerSimpleModel::QmlEventData*> CallStackEntry;
+ QStack<CallStackEntry> callStack;
+ callStack.push(CallStackEntry(QString(), 0)); // artificial root
+
+ for (int i = 0; i < eventList.size(); ++i) {
+ const QmlProfilerSimpleModel::QmlEventData *event = &eventList[i];
+
+ if (!d->acceptedTypes.contains(event->eventType))
+ continue;
+
+ if (checkRanges) {
+ if ((event->startTime + event->duration < rangeStart)
+ || (event->startTime > rangeEnd))
+ continue;
+ }
+
+ // put event in hash
+ QString hash = QmlProfilerSimpleModel::getHashString(*event);
+ if (!d->data.contains(hash)) {
+ QmlEventStats stats = {
+ event->displayName,
+ hash,
+ event->data.join(QLatin1String(" ")),
+ event->location,
+ event->eventType,
+ event->bindingType,
+ event->duration,
+ 1, //calls
+ event->duration, //minTime
+ event->duration, // maxTime
+ 0, //timePerCall
+ 0, //percentOfTime
+ 0, //medianTime
+ false //isBindingLoop
+ };
+
+ d->data.insert(hash, stats);
+
+ // for median computing
+ durations.insert(hash, QVector<qint64>());
+ durations[hash].append(event->duration);
+ } else {
+ // update stats
+ QmlEventStats *stats = &d->data[hash];
+
+ stats->duration += event->duration;
+ if (event->duration < stats->minTime)
+ stats->minTime = event->duration;
+ if (event->duration > stats->maxTime)
+ stats->maxTime = event->duration;
+ stats->calls++;
+
+ // for median computing
+ durations[hash].append(event->duration);
+ }
+
+ // qml time computation
+ if (event->startTime > lastEndTime) { // assume parent event if starts before last end
+ qmlTime += event->duration;
+ lastEndTime = event->startTime + event->duration;
+ }
+
+
+ //
+ // binding loop detection
+ //
+ const QmlProfilerSimpleModel::QmlEventData *potentialParent = callStack.top().second;
+ while (potentialParent
+ && !(potentialParent->startTime + potentialParent->duration > event->startTime)) {
+ callStack.pop();
+ potentialParent = callStack.top().second;
+ }
+
+ // check whether event is already in stack
+ bool inLoop = false;
+ for (int ii = 1; ii < callStack.size(); ++ii) {
+ if (callStack.at(ii).first == hash)
+ inLoop = true;
+ if (inLoop)
+ d->eventsInBindingLoop.insert(hash);
+ }
+
+
+ CallStackEntry newEntry(hash, event);
+ callStack.push(newEntry);
+
+ d->modelManager->modelProxyCountUpdated(d->modelId, i, eventList.count()*2);
+ }
+
+ // post-process: calc mean time, median time, percentoftime
+ foreach (const QString &hash, d->data.keys()) {
+ QmlEventStats* stats = &d->data[hash];
+ if (stats->calls > 0)
+ stats->timePerCall = stats->duration / (double)stats->calls;
+
+ QVector<qint64> eventDurations = durations.value(hash);
+ if (!eventDurations.isEmpty()) {
+ qSort(eventDurations);
+ stats->medianTime = eventDurations.at(eventDurations.count()/2);
+ }
+
+ stats->percentOfTime = stats->duration * 100.0 / qmlTime;
+ }
+
+ // set binding loop flag
+ foreach (const QString &eventHash, d->eventsInBindingLoop)
+ d->data[eventHash].isBindingLoop = true;
+
+ QString rootEventName = tr("<program>");
+ QmlDebug::QmlEventLocation rootEventLocation(rootEventName, 1, 1);
+
+ // insert root event
+ QmlEventStats rootEvent = {
+ rootEventName, //event.displayName,
+ rootEventName, // hash
+ tr("Main Program"), //event.details,
+ rootEventLocation, // location
+ (int)QmlDebug::Binding, // event type
+ 0, // binding type
+ qmlTime + 1,
+ 1, //calls
+ qmlTime + 1, //minTime
+ qmlTime + 1, // maxTime
+ qmlTime + 1, //timePerCall
+ 100.0, //percentOfTime
+ qmlTime + 1, //medianTime;
+ false
+ };
+
+ d->data.insert(rootEventName, rootEvent);
+
+ d->modelManager->modelProxyCountUpdated(d->modelId, 1, 1);
+ emit dataAvailable();
+}
+
+int QmlProfilerEventsModelProxy::count() const
+{
+ return d->data.count();
+}
+
+//////////////////////////////////////////////////////////////////////////////////
+QmlProfilerEventRelativesModelProxy::QmlProfilerEventRelativesModelProxy(QmlProfilerModelManager *modelManager,
+ QmlProfilerEventsModelProxy *eventsModel,
+ QObject *parent)
+ : QObject(parent)
+{
+ QTC_CHECK(modelManager);
+ m_modelManager = modelManager;
+ connect(modelManager->simpleModel(), SIGNAL(changed()), this, SLOT(dataChanged()));
+
+ QTC_CHECK(eventsModel);
+ m_eventsModel = eventsModel;
+
+ m_acceptedTypes << QmlDebug::Compiling << QmlDebug::Creating << QmlDebug::Binding << QmlDebug::HandlingSignal;
+}
+
+QmlProfilerEventRelativesModelProxy::~QmlProfilerEventRelativesModelProxy()
+{
+}
+
+const QmlProfilerEventRelativesModelProxy::QmlEventRelativesMap QmlProfilerEventRelativesModelProxy::getData(const QString &hash) const
+{
+ if (m_data.contains(hash))
+ return m_data[hash];
+ return QmlEventRelativesMap();
+}
+
+int QmlProfilerEventRelativesModelProxy::count() const
+{
+ return m_data.count();
+}
+
+void QmlProfilerEventRelativesModelProxy::clear()
+{
+ m_data.clear();
+}
+
+void QmlProfilerEventRelativesModelProxy::dataChanged()
+{
+ loadData();
+
+ emit dataAvailable();
+}
+
+
+//////////////////////////////////////////////////////////////////////////////////
+QmlProfilerEventParentsModelProxy::QmlProfilerEventParentsModelProxy(QmlProfilerModelManager *modelManager,
+ QmlProfilerEventsModelProxy *eventsModel,
+ QObject *parent)
+ : QmlProfilerEventRelativesModelProxy(modelManager, eventsModel, parent)
+{}
+
+QmlProfilerEventParentsModelProxy::~QmlProfilerEventParentsModelProxy()
+{}
+
+void QmlProfilerEventParentsModelProxy::loadData()
+{
+ clear();
+ QmlProfilerSimpleModel *simpleModel = m_modelManager->simpleModel();
+ if (simpleModel->isEmpty())
+ return;
+
+ QHash<QString, QmlProfilerSimpleModel::QmlEventData> cachedEvents;
+ QString rootEventName = tr("<program>");
+ QmlProfilerSimpleModel::QmlEventData rootEvent = {
+ rootEventName,
+ QmlDebug::Binding,
+ 0,
+ 0,
+ 0,
+ QStringList() << tr("Main Program"),
+ QmlDebug::QmlEventLocation(rootEventName, 0, 0),
+ 0,0,0,0,0 // numericData fields
+ };
+ cachedEvents.insert(rootEventName, rootEvent);
+
+ // for level computation
+ QHash<int, qint64> endtimesPerLevel;
+ int level = QmlDebug::Constants::QML_MIN_LEVEL;
+ endtimesPerLevel[0] = 0;
+
+ const QSet<QString> eventsInBindingLoop = m_eventsModel->eventsInBindingLoop();
+
+ // compute parent-child relationship and call count
+ QHash<int, QString> lastParent;
+ //for (int index = fromIndex; index <= toIndex; index++) {
+ const QVector<QmlProfilerSimpleModel::QmlEventData> eventList = simpleModel->getEvents();
+ foreach (const QmlProfilerSimpleModel::QmlEventData &event, eventList) {
+ // whitelist
+ if (!m_acceptedTypes.contains(event.eventType))
+ continue;
+
+ // level computation
+ if (endtimesPerLevel[level] > event.startTime) {
+ level++;
+ } else {
+ while (level > QmlDebug::Constants::QML_MIN_LEVEL && endtimesPerLevel[level-1] <= event.startTime)
+ level--;
+ }
+ endtimesPerLevel[level] = event.startTime + event.duration;
+
+
+ QString parentHash = rootEventName;
+ QString eventHash = QmlProfilerSimpleModel::getHashString(event);
+
+ // save in cache
+ if (!cachedEvents.contains(eventHash))
+ cachedEvents.insert(eventHash, event);
+
+ if (level > QmlDebug::Constants::QML_MIN_LEVEL && lastParent.contains(level-1))
+ parentHash = lastParent[level-1];
+
+ QmlProfilerSimpleModel::QmlEventData *parentEvent = &(cachedEvents[parentHash]);
+
+ // generate placeholder if needed
+ if (!m_data.contains(eventHash))
+ m_data.insert(eventHash, QmlEventRelativesMap());
+
+ if (m_data[eventHash].contains(parentHash)) {
+ QmlEventRelativesData *parent = &(m_data[eventHash][parentHash]);
+ parent->calls++;
+ parent->duration += event.duration;
+ } else {
+ m_data[eventHash].insert(parentHash, QmlEventRelativesData());
+ QmlEventRelativesData *parent = &(m_data[eventHash][parentHash]);
+ parent->displayName = parentEvent->displayName;
+ parent->eventType = parentEvent->eventType;
+ parent->duration = event.duration;
+ parent->calls = 1;
+ parent->details = parentEvent->data.join(QLatin1String(""));
+ parent->isBindingLoop = eventsInBindingLoop.contains(parentHash);
+ }
+
+ // now lastparent is a string with the hash
+ lastParent[level] = eventHash;
+ }
+}
+
+//////////////////////////////////////////////////////////////////////////////////
+QmlProfilerEventChildrenModelProxy::QmlProfilerEventChildrenModelProxy(QmlProfilerModelManager *modelManager,
+ QmlProfilerEventsModelProxy *eventsModel,
+ QObject *parent)
+ : QmlProfilerEventRelativesModelProxy(modelManager, eventsModel, parent)
+{}
+
+QmlProfilerEventChildrenModelProxy::~QmlProfilerEventChildrenModelProxy()
+{}
+
+void QmlProfilerEventChildrenModelProxy::loadData()
+{
+ clear();
+ QmlProfilerSimpleModel *simpleModel = m_modelManager->simpleModel();
+ if (simpleModel->isEmpty())
+ return;
+
+ QString rootEventName = tr("<program>");
+
+ // for level computation
+ QHash<int, qint64> endtimesPerLevel;
+ int level = QmlDebug::Constants::QML_MIN_LEVEL;
+ endtimesPerLevel[0] = 0;
+
+ const QSet<QString> eventsInBindingLoop = m_eventsModel->eventsInBindingLoop();
+
+ // compute parent-child relationship and call count
+ QHash<int, QString> lastParent;
+ const QVector<QmlProfilerSimpleModel::QmlEventData> eventList = simpleModel->getEvents();
+ foreach (const QmlProfilerSimpleModel::QmlEventData &event, eventList) {
+ // whitelist
+ if (!m_acceptedTypes.contains(event.eventType))
+ continue;
+
+ // level computation
+ if (endtimesPerLevel[level] > event.startTime) {
+ level++;
+ } else {
+ while (level > QmlDebug::Constants::QML_MIN_LEVEL && endtimesPerLevel[level-1] <= event.startTime)
+ level--;
+ }
+ endtimesPerLevel[level] = event.startTime + event.duration;
+
+ QString parentHash = rootEventName;
+ QString eventHash = QmlProfilerSimpleModel::getHashString(event);
+
+ if (level > QmlDebug::Constants::QML_MIN_LEVEL && lastParent.contains(level-1))
+ parentHash = lastParent[level-1];
+
+ // generate placeholder if needed
+ if (!m_data.contains(parentHash))
+ m_data.insert(parentHash, QmlEventRelativesMap());
+
+ if (m_data[parentHash].contains(eventHash)) {
+ QmlEventRelativesData *child = &(m_data[parentHash][eventHash]);
+ child->calls++;
+ child->duration += event.duration;
+ } else {
+ m_data[parentHash].insert(eventHash, QmlEventRelativesData());
+ QmlEventRelativesData *child = &(m_data[parentHash][eventHash]);
+ child->displayName = event.displayName;
+ child->eventType = event.eventType;
+ child->duration = event.duration;
+ child->calls = 1;
+ child->details = event.data.join(QLatin1String(""));
+ child->isBindingLoop = eventsInBindingLoop.contains(parentHash);
+ }
+
+ // now lastparent is a string with the hash
+ lastParent[level] = eventHash;
+ }
+}
+
+
+
+}
+}
diff --git a/src/plugins/qmlprofiler/qmlprofilereventsmodelproxy.h b/src/plugins/qmlprofiler/qmlprofilereventsmodelproxy.h
new file mode 100644
index 0000000000..b10dd7e49a
--- /dev/null
+++ b/src/plugins/qmlprofiler/qmlprofilereventsmodelproxy.h
@@ -0,0 +1,172 @@
+/****************************************************************************
+**
+** 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 QMLPROFILEREVENTSMODELPROXY_H
+#define QMLPROFILEREVENTSMODELPROXY_H
+
+#include "qmlprofilersimplemodel.h"
+#include <QObject>
+#include <qmldebug/qmlprofilereventtypes.h>
+#include <qmldebug/qmlprofilereventlocation.h>
+#include <QHash>
+#include <QVector>
+
+
+namespace QmlProfiler {
+class QmlProfilerModelManager;
+
+namespace Internal {
+
+class QmlProfilerEventsModelProxy : public QObject
+{
+ Q_OBJECT
+public:
+ struct QmlEventStats {
+ QString displayName;
+ QString eventHashStr;
+ QString details;
+ QmlDebug::QmlEventLocation location;
+ int eventType;
+ int bindingType;
+
+ qint64 duration;
+ qint64 calls;
+ qint64 minTime;
+ qint64 maxTime;
+ qint64 timePerCall;
+ double percentOfTime;
+ qint64 medianTime;
+
+ bool isBindingLoop;
+ };
+
+ QmlProfilerEventsModelProxy(QmlProfilerModelManager *modelManager, QObject *parent = 0);
+ ~QmlProfilerEventsModelProxy();
+
+ const QList<QmlEventStats> getData() const;
+ int count() const;
+ void clear();
+
+ void limitToRange(qint64 rangeStart, qint64 rangeEnd);
+
+signals:
+ void dataAvailable();
+
+private:
+ void loadData(qint64 rangeStart = -1, qint64 rangeEnd = -1);
+
+ QSet<QString> eventsInBindingLoop() const;
+
+private slots:
+ void dataChanged();
+
+private:
+ class QmlProfilerEventsModelProxyPrivate;
+ QmlProfilerEventsModelProxyPrivate *d;
+
+ friend class QmlProfilerEventParentsModelProxy;
+ friend class QmlProfilerEventChildrenModelProxy;
+};
+
+class QmlProfilerEventRelativesModelProxy : public QObject
+{
+ Q_OBJECT
+public:
+ struct QmlEventRelativesData {
+ QString displayName;
+ int eventType;
+ qint64 duration;
+ qint64 calls;
+ QString details;
+ bool isBindingLoop;
+ };
+ typedef QHash <QString, QmlEventRelativesData> QmlEventRelativesMap;
+
+ QmlProfilerEventRelativesModelProxy(QmlProfilerModelManager *modelManager,
+ QmlProfilerEventsModelProxy *eventsModel,
+ QObject *parent = 0);
+ ~QmlProfilerEventRelativesModelProxy();
+
+
+ int count() const;
+ void clear();
+
+ const QmlEventRelativesMap getData(const QString &hash) const;
+
+protected:
+ virtual void loadData() = 0;
+
+signals:
+ void dataAvailable();
+
+protected slots:
+ void dataChanged();
+
+protected:
+ QHash <QString, QmlEventRelativesMap> m_data;
+ QmlProfilerModelManager *m_modelManager;
+ QmlProfilerEventsModelProxy *m_eventsModel;
+ QVector <int> m_acceptedTypes;
+};
+
+class QmlProfilerEventParentsModelProxy : public QmlProfilerEventRelativesModelProxy
+{
+ Q_OBJECT
+public:
+ QmlProfilerEventParentsModelProxy(QmlProfilerModelManager *modelManager,
+ QmlProfilerEventsModelProxy *eventsModel,
+ QObject *parent = 0);
+ ~QmlProfilerEventParentsModelProxy();
+
+protected:
+ virtual void loadData();
+signals:
+ void dataAvailable();
+};
+
+class QmlProfilerEventChildrenModelProxy : public QmlProfilerEventRelativesModelProxy
+{
+ Q_OBJECT
+public:
+ QmlProfilerEventChildrenModelProxy(QmlProfilerModelManager *modelManager,
+ QmlProfilerEventsModelProxy *eventsModel,
+ QObject *parent = 0);
+ ~QmlProfilerEventChildrenModelProxy();
+
+protected:
+ virtual void loadData();
+signals:
+ void dataAvailable();
+};
+
+}
+}
+
+#endif
diff --git a/src/plugins/qmlprofiler/qmlprofilereventview.cpp b/src/plugins/qmlprofiler/qmlprofilereventview.cpp
index d04a0203e0..01d8504510 100644
--- a/src/plugins/qmlprofiler/qmlprofilereventview.cpp
+++ b/src/plugins/qmlprofiler/qmlprofilereventview.cpp
@@ -68,6 +68,9 @@ Q_GLOBAL_STATIC(Colors, colors)
////////////////////////////////////////////////////////////////////////////////////
+
+////////////////////////////////////////////////////////////////////////////////////
+
class EventsViewItem : public QStandardItem
{
public:
@@ -100,50 +103,52 @@ public:
QmlProfilerEventsWidget *q;
- Analyzer::IAnalyzerTool *m_profilerTool;
+ QmlProfilerTool *m_profilerTool;
QmlProfilerViewManager *m_viewContainer;
QmlProfilerEventsMainView *m_eventTree;
- QmlProfilerEventsParentsAndChildrenView *m_eventChildren;
- QmlProfilerEventsParentsAndChildrenView *m_eventParents;
- QmlProfilerDataModel *m_profilerDataModel;
+ QmlProfilerEventRelativesView *m_eventChildren;
+ QmlProfilerEventRelativesView *m_eventParents;
- bool m_globalStatsEnabled;
+ QmlProfilerEventsModelProxy *modelProxy;
+ bool globalStats;
};
QmlProfilerEventsWidget::QmlProfilerEventsWidget(QWidget *parent,
- Analyzer::IAnalyzerTool *profilerTool,
+ QmlProfilerTool *profilerTool,
QmlProfilerViewManager *container,
- QmlProfilerDataModel *profilerDataModel )
+ QmlProfilerModelManager *profilerModelManager )
+
: QWidget(parent), d(new QmlProfilerEventsWidgetPrivate(this))
{
setObjectName(QLatin1String("QmlProfilerEventsView"));
- d->m_profilerDataModel = profilerDataModel;
- connect(d->m_profilerDataModel, SIGNAL(stateChanged()),
+ d->modelProxy = new QmlProfilerEventsModelProxy(profilerModelManager, this);
+ connect(profilerModelManager, SIGNAL(stateChanged()),
this, SLOT(profilerDataModelStateChanged()));
- d->m_eventTree = new QmlProfilerEventsMainView(QmlProfilerEventsMainView::EventsView, this, d->m_profilerDataModel);
+ d->m_eventTree = new QmlProfilerEventsMainView(this, d->modelProxy);
connect(d->m_eventTree, SIGNAL(gotoSourceLocation(QString,int,int)), this, SIGNAL(gotoSourceLocation(QString,int,int)));
- connect(d->m_eventTree, SIGNAL(showEventInTimeline(int)), this, SIGNAL(showEventInTimeline(int)));
-
- d->m_eventChildren = new QmlProfilerEventsParentsAndChildrenView(
- QmlProfilerEventsParentsAndChildrenView::ChildrenView,
- this,
- d->m_profilerDataModel);
- d->m_eventParents = new QmlProfilerEventsParentsAndChildrenView(
- QmlProfilerEventsParentsAndChildrenView::ParentsView,
- this,
- d->m_profilerDataModel);
- connect(d->m_eventTree, SIGNAL(eventSelected(int)), d->m_eventChildren, SLOT(displayEvent(int)));
- connect(d->m_eventTree, SIGNAL(eventSelected(int)), d->m_eventParents, SLOT(displayEvent(int)));
- connect(d->m_eventChildren, SIGNAL(eventClicked(int)), d->m_eventTree, SLOT(selectEvent(int)));
- connect(d->m_eventParents, SIGNAL(eventClicked(int)), d->m_eventTree, SLOT(selectEvent(int)));
+ connect(d->m_eventTree, SIGNAL(eventSelected(QString)), this, SIGNAL(eventSelectedByHash(QString)));
+
+ d->m_eventChildren = new QmlProfilerEventRelativesView(
+ profilerModelManager,
+ new QmlProfilerEventChildrenModelProxy(profilerModelManager, d->modelProxy, this),
+ this);
+ d->m_eventParents = new QmlProfilerEventRelativesView(
+ profilerModelManager,
+ new QmlProfilerEventParentsModelProxy(profilerModelManager, d->modelProxy, this),
+ this);
+ connect(d->m_eventTree, SIGNAL(eventSelected(QString)), d->m_eventChildren, SLOT(displayEvent(QString)));
+ connect(d->m_eventTree, SIGNAL(eventSelected(QString)), d->m_eventParents, SLOT(displayEvent(QString)));
+ connect(d->m_eventChildren, SIGNAL(eventClicked(QString)), d->m_eventTree, SLOT(selectEvent(QString)));
+ connect(d->m_eventParents, SIGNAL(eventClicked(QString)), d->m_eventTree, SLOT(selectEvent(QString)));
// widget arrangement
QVBoxLayout *groupLayout = new QVBoxLayout;
groupLayout->setContentsMargins(0,0,0,0);
groupLayout->setSpacing(0);
+
Core::MiniSplitter *splitterVertical = new Core::MiniSplitter;
splitterVertical->addWidget(d->m_eventTree);
Core::MiniSplitter *splitterHorizontal = new Core::MiniSplitter;
@@ -159,30 +164,17 @@ QmlProfilerEventsWidget::QmlProfilerEventsWidget(QWidget *parent,
d->m_profilerTool = profilerTool;
d->m_viewContainer = container;
- d->m_globalStatsEnabled = true;
+ d->globalStats = true;
}
QmlProfilerEventsWidget::~QmlProfilerEventsWidget()
{
+ delete d->modelProxy;
delete d;
}
void QmlProfilerEventsWidget::profilerDataModelStateChanged()
{
- if (d->m_profilerDataModel) {
- QmlProfilerDataModel::State newState = d->m_profilerDataModel->currentState();
- if (newState == QmlProfilerDataModel::Empty)
- clear();
- }
-}
-
-void QmlProfilerEventsWidget::switchToV8View()
-{
- setObjectName(QLatin1String("QmlProfilerV8ProfileView"));
- d->m_eventTree->setViewType(QmlProfilerEventsMainView::V8ProfileView);
- d->m_eventParents->setViewType(QmlProfilerEventsParentsAndChildrenView::V8ParentsView);
- d->m_eventChildren->setViewType(QmlProfilerEventsParentsAndChildrenView::V8ChildrenView);
- setToolTip(tr("Trace information from the v8 JavaScript engine. Available only in Qt5 based applications."));
}
void QmlProfilerEventsWidget::clear()
@@ -194,9 +186,8 @@ void QmlProfilerEventsWidget::clear()
void QmlProfilerEventsWidget::getStatisticsInRange(qint64 rangeStart, qint64 rangeEnd)
{
- clear();
- d->m_eventTree->getStatisticsInRange(rangeStart, rangeEnd);
- d->m_globalStatsEnabled = d->m_eventTree->isRangeGlobal(rangeStart, rangeEnd);
+ d->modelProxy->limitToRange(rangeStart, rangeEnd);
+ d->globalStats = (rangeStart == -1) && (rangeEnd == -1);
}
QModelIndex QmlProfilerEventsWidget::selectedItem() const
@@ -215,11 +206,10 @@ void QmlProfilerEventsWidget::contextMenuEvent(QContextMenuEvent *ev)
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();
+ if (d->m_profilerTool) {
+ QList <QAction *> commonActions = d->m_profilerTool->profilerContextMenuActions();
foreach (QAction *act, commonActions) {
menu.addAction(act);
}
@@ -231,23 +221,18 @@ void QmlProfilerEventsWidget::contextMenuEvent(QContextMenuEvent *ev)
copyRowAction = menu.addAction(tr("Copy Row"));
copyTableAction = menu.addAction(tr("Copy Table"));
- if (isQml()) {
- // only for qml events view, not for v8
- showExtendedStatsAction = menu.addAction(tr("Extended Event Statistics"));
- showExtendedStatsAction->setCheckable(true);
- showExtendedStatsAction->setChecked(showExtendedStatistics());
- }
+ showExtendedStatsAction = menu.addAction(tr("Extended Event Statistics"));
+ showExtendedStatsAction->setCheckable(true);
+ showExtendedStatsAction->setChecked(showExtendedStatistics());
}
- if (isQml()) {
- menu.addSeparator();
- 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"));
- if (hasGlobalStats())
- getGlobalStatsAction->setEnabled(false);
- }
+ menu.addSeparator();
+ 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"));
+ if (hasGlobalStats())
+ getGlobalStatsAction->setEnabled(false);
QAction *selectedAction = menu.exec(position);
@@ -260,12 +245,8 @@ void QmlProfilerEventsWidget::contextMenuEvent(QContextMenuEvent *ev)
getStatisticsInRange(d->m_viewContainer->selectionStart(),
d->m_viewContainer->selectionEnd());
}
- if (selectedAction == getGlobalStatsAction) {
- if (d->m_profilerDataModel) {
- getStatisticsInRange(d->m_profilerDataModel->traceStartTime(),
- d->m_profilerDataModel->traceEndTime());
- }
- }
+ if (selectedAction == getGlobalStatsAction)
+ getStatisticsInRange(-1, -1);
if (selectedAction == showExtendedStatsAction)
setShowExtendedStatistics(!showExtendedStatistics());
}
@@ -294,24 +275,20 @@ void QmlProfilerEventsWidget::copyRowToClipboard() const
d->m_eventTree->copyRowToClipboard();
}
-void QmlProfilerEventsWidget::updateSelectedEvent(int eventId) const
+void QmlProfilerEventsWidget::updateSelectedEvent(const QString &eventHash) const
{
- if (d->m_eventTree->selectedEventId() != eventId)
- d->m_eventTree->selectEvent(eventId);
+ if (d->m_eventTree->selectedEventHash() != eventHash)
+ d->m_eventTree->selectEvent(eventHash);
}
void QmlProfilerEventsWidget::selectBySourceLocation(const QString &filename, int line, int column)
{
- // This slot is used to connect the javascript pane with the qml events pane
- // Our javascript trace data does not store column information
- // thus we ignore it here
- Q_UNUSED(column);
- d->m_eventTree->selectEventByLocation(filename, line);
+ d->m_eventTree->selectEventByLocation(filename, line, column);
}
bool QmlProfilerEventsWidget::hasGlobalStats() const
{
- return d->m_globalStatsEnabled;
+ return d->globalStats;
}
void QmlProfilerEventsWidget::setShowExtendedStatistics(bool show)
@@ -324,15 +301,6 @@ bool QmlProfilerEventsWidget::showExtendedStatistics() const
return d->m_eventTree->showExtendedStatistics();
}
-bool QmlProfilerEventsWidget::isQml() const
-{
- return d->m_eventTree->viewType() == QmlProfilerEventsMainView::EventsView;
-}
-bool QmlProfilerEventsWidget::isV8() const
-{
- return d->m_eventTree->viewType() == QmlProfilerEventsMainView::V8ProfileView;
-}
-
////////////////////////////////////////////////////////////////////////////////////
class QmlProfilerEventsMainView::QmlProfilerEventsMainViewPrivate
@@ -340,17 +308,14 @@ class QmlProfilerEventsMainView::QmlProfilerEventsMainViewPrivate
public:
QmlProfilerEventsMainViewPrivate(QmlProfilerEventsMainView *qq) : q(qq) {}
- void buildModelFromList(const QList<QmlRangeEventData *> &list, QStandardItem *parentItem );
- void buildV8ModelFromList( const QList<QV8EventData *> &list );
int getFieldCount();
- QString textForItem(QStandardItem *item, bool recursive) const;
+ QString textForItem(QStandardItem *item, bool recursive = false) const;
QmlProfilerEventsMainView *q;
- QmlProfilerEventsMainView::ViewTypes m_viewType;
- QmlProfilerDataModel *m_profilerDataModel;
+ QmlProfilerEventsModelProxy *modelProxy;
QStandardItemModel *m_model;
QList<bool> m_fieldShown;
QHash<int, int> m_columnIndex; // maps field enum to column index
@@ -362,49 +327,52 @@ public:
////////////////////////////////////////////////////////////////////////////////////
-QmlProfilerEventsMainView::QmlProfilerEventsMainView(ViewTypes viewType,
- QWidget *parent,
- QmlProfilerDataModel *dataModel)
- : QTreeView(parent), d(new QmlProfilerEventsMainViewPrivate(this))
+QmlProfilerEventsMainView::QmlProfilerEventsMainView(QWidget *parent,
+ QmlProfilerEventsModelProxy *modelProxy)
+: QmlProfilerTreeView(parent), d(new QmlProfilerEventsMainViewPrivate(this))
{
setObjectName(QLatin1String("QmlProfilerEventsTable"));
- header()->setResizeMode(QHeaderView::Interactive);
- header()->setDefaultSectionSize(100);
- header()->setMinimumSectionSize(50);
+
setSortingEnabled(false);
- setFrameStyle(QFrame::NoFrame);
d->m_model = new QStandardItemModel(this);
setModel(d->m_model);
connect(this,SIGNAL(clicked(QModelIndex)), this,SLOT(jumpToItem(QModelIndex)));
- d->m_profilerDataModel = dataModel;
- connect(d->m_profilerDataModel,SIGNAL(stateChanged()),
- this,SLOT(profilerDataModelStateChanged()));
- connect(d->m_profilerDataModel,SIGNAL(detailsChanged(int,QString)),
- this,SLOT(changeDetailsForEvent(int,QString)));
-
+ d->modelProxy = modelProxy;
+ connect(d->modelProxy,SIGNAL(dataAvailable()), this, SLOT(buildModel()));
+// connect(d->modelProxy,SIGNAL(stateChanged()),
+// this,SLOT(profilerDataModelStateChanged()));
d->m_firstNumericColumn = 0;
d->m_preventSelectBounce = false;
d->m_showExtendedStatistics = false;
- setViewType(viewType);
+ setFieldViewable(Name, true);
+ setFieldViewable(Type, true);
+ setFieldViewable(TimeInPercent, true);
+ setFieldViewable(TotalTime, true);
+ setFieldViewable(SelfTimeInPercent, false);
+ setFieldViewable(SelfTime, false);
+ setFieldViewable(CallCount, true);
+ setFieldViewable(TimePerCall, true);
+ setFieldViewable(MaxTime, true);
+ setFieldViewable(MinTime, true);
+ setFieldViewable(MedianTime, true);
+ setFieldViewable(Details, true);
+
+ buildModel();
}
QmlProfilerEventsMainView::~QmlProfilerEventsMainView()
{
clear();
+ //delete d->modelProxy;
delete d->m_model;
delete d;
}
void QmlProfilerEventsMainView::profilerDataModelStateChanged()
{
- if (d->m_profilerDataModel) {
- QmlProfilerDataModel::State newState = d->m_profilerDataModel->currentState();
- if (newState == QmlProfilerDataModel::Done)
- buildModel();
- }
}
void QmlProfilerEventsMainView::setFieldViewable(Fields field, bool show)
@@ -419,52 +387,6 @@ void QmlProfilerEventsMainView::setFieldViewable(Fields field, bool show)
}
}
-QmlProfilerEventsMainView::ViewTypes QmlProfilerEventsMainView::viewType() const
-{
- return d->m_viewType;
-}
-
-void QmlProfilerEventsMainView::setViewType(ViewTypes type)
-{
- d->m_viewType = type;
- switch (type) {
- case EventsView: {
- setObjectName(QLatin1String("QmlProfilerEventsTable"));
- setFieldViewable(Name, true);
- setFieldViewable(Type, true);
- setFieldViewable(Percent, true);
- setFieldViewable(TotalDuration, true);
- setFieldViewable(SelfPercent, false);
- setFieldViewable(SelfDuration, false);
- setFieldViewable(CallCount, true);
- setFieldViewable(TimePerCall, true);
- setFieldViewable(MaxTime, true);
- setFieldViewable(MinTime, true);
- setFieldViewable(MedianTime, true);
- setFieldViewable(Details, true);
- break;
- }
- case V8ProfileView: {
- setObjectName(QLatin1String("QmlProfilerV8ProfileTable"));
- setFieldViewable(Name, true);
- setFieldViewable(Type, false);
- setFieldViewable(Percent, true);
- setFieldViewable(TotalDuration, true);
- setFieldViewable(SelfPercent, true);
- setFieldViewable(SelfDuration, true);
- setFieldViewable(CallCount, false);
- setFieldViewable(TimePerCall, false);
- setFieldViewable(MaxTime, false);
- setFieldViewable(MinTime, false);
- setFieldViewable(MedianTime, false);
- setFieldViewable(Details, true);
- break;
- }
- default: break;
- }
-
- buildModel();
-}
void QmlProfilerEventsMainView::setHeaderLabels()
{
@@ -474,53 +396,53 @@ void QmlProfilerEventsMainView::setHeaderLabels()
d->m_columnIndex.clear();
if (d->m_fieldShown[Name]) {
d->m_columnIndex[Name] = fieldIndex;
- d->m_model->setHeaderData(fieldIndex++, Qt::Horizontal, QVariant(tr("Location")));
+ d->m_model->setHeaderData(fieldIndex++, Qt::Horizontal, QVariant(displayHeader(Location)));
d->m_firstNumericColumn++;
}
if (d->m_fieldShown[Type]) {
d->m_columnIndex[Type] = fieldIndex;
- d->m_model->setHeaderData(fieldIndex++, Qt::Horizontal, QVariant(tr("Type")));
+ d->m_model->setHeaderData(fieldIndex++, Qt::Horizontal, QVariant(displayHeader(Type)));
d->m_firstNumericColumn++;
}
- if (d->m_fieldShown[Percent]) {
- d->m_columnIndex[Percent] = fieldIndex;
- d->m_model->setHeaderData(fieldIndex++, Qt::Horizontal, QVariant(tr("Time in Percent")));
+ if (d->m_fieldShown[TimeInPercent]) {
+ d->m_columnIndex[TimeInPercent] = fieldIndex;
+ d->m_model->setHeaderData(fieldIndex++, Qt::Horizontal, QVariant(displayHeader(TimeInPercent)));
}
- if (d->m_fieldShown[TotalDuration]) {
- d->m_columnIndex[TotalDuration] = fieldIndex;
- d->m_model->setHeaderData(fieldIndex++, Qt::Horizontal, QVariant(tr("Total Time")));
+ if (d->m_fieldShown[TotalTime]) {
+ d->m_columnIndex[TotalTime] = fieldIndex;
+ d->m_model->setHeaderData(fieldIndex++, Qt::Horizontal, QVariant(displayHeader(TotalTime)));
}
- if (d->m_fieldShown[SelfPercent]) {
+ if (d->m_fieldShown[SelfTimeInPercent]) {
d->m_columnIndex[Type] = fieldIndex;
- d->m_model->setHeaderData(fieldIndex++, Qt::Horizontal, QVariant(tr("Self Time in Percent")));
+ d->m_model->setHeaderData(fieldIndex++, Qt::Horizontal, QVariant(displayHeader(SelfTimeInPercent)));
}
- if (d->m_fieldShown[SelfDuration]) {
- d->m_columnIndex[SelfDuration] = fieldIndex;
- d->m_model->setHeaderData(fieldIndex++, Qt::Horizontal, QVariant(tr("Self Time")));
+ if (d->m_fieldShown[SelfTime]) {
+ d->m_columnIndex[SelfTime] = fieldIndex;
+ d->m_model->setHeaderData(fieldIndex++, Qt::Horizontal, QVariant(displayHeader(SelfTime)));
}
if (d->m_fieldShown[CallCount]) {
d->m_columnIndex[CallCount] = fieldIndex;
- d->m_model->setHeaderData(fieldIndex++, Qt::Horizontal, QVariant(tr("Calls")));
+ d->m_model->setHeaderData(fieldIndex++, Qt::Horizontal, QVariant(displayHeader(CallCount)));
}
if (d->m_fieldShown[TimePerCall]) {
d->m_columnIndex[TimePerCall] = fieldIndex;
- d->m_model->setHeaderData(fieldIndex++, Qt::Horizontal, QVariant(tr("Mean Time")));
+ d->m_model->setHeaderData(fieldIndex++, Qt::Horizontal, QVariant(displayHeader(TimePerCall)));
}
if (d->m_fieldShown[MedianTime]) {
d->m_columnIndex[MedianTime] = fieldIndex;
- d->m_model->setHeaderData(fieldIndex++, Qt::Horizontal, QVariant(tr("Median Time")));
+ d->m_model->setHeaderData(fieldIndex++, Qt::Horizontal, QVariant(displayHeader(MedianTime)));
}
if (d->m_fieldShown[MaxTime]) {
d->m_columnIndex[MaxTime] = fieldIndex;
- d->m_model->setHeaderData(fieldIndex++, Qt::Horizontal, QVariant(tr("Longest Time")));
+ d->m_model->setHeaderData(fieldIndex++, Qt::Horizontal, QVariant(displayHeader(MaxTime)));
}
if (d->m_fieldShown[MinTime]) {
d->m_columnIndex[MinTime] = fieldIndex;
- d->m_model->setHeaderData(fieldIndex++, Qt::Horizontal, QVariant(tr("Shortest Time")));
+ d->m_model->setHeaderData(fieldIndex++, Qt::Horizontal, QVariant(displayHeader(MinTime)));
}
if (d->m_fieldShown[Details]) {
d->m_columnIndex[Details] = fieldIndex;
- d->m_model->setHeaderData(fieldIndex++, Qt::Horizontal, QVariant(tr("Details")));
+ d->m_model->setHeaderData(fieldIndex++, Qt::Horizontal, QVariant(displayHeader(Details)));
}
}
@@ -570,47 +492,41 @@ int QmlProfilerEventsMainView::QmlProfilerEventsMainViewPrivate::getFieldCount()
void QmlProfilerEventsMainView::buildModel()
{
- if (d->m_profilerDataModel) {
- clear();
- if (d->m_viewType == V8ProfileView)
- d->buildV8ModelFromList( d->m_profilerDataModel->getV8Events() );
- else
- d->buildModelFromList( d->m_profilerDataModel->getEventDescriptions(), d->m_model->invisibleRootItem() );
-
- setShowExtendedStatistics(d->m_showExtendedStatistics);
+ clear();
+ parseModelProxy();
+ setShowExtendedStatistics(d->m_showExtendedStatistics);
- setRootIsDecorated(false);
- setSortingEnabled(true);
- sortByColumn(d->m_firstNumericColumn,Qt::DescendingOrder);
+ setRootIsDecorated(false);
+ setSortingEnabled(true);
+ sortByColumn(d->m_firstNumericColumn,Qt::DescendingOrder);
- expandAll();
- if (d->m_fieldShown[Name])
- resizeColumnToContents(0);
+ expandAll();
+ if (d->m_fieldShown[Name])
+ resizeColumnToContents(0);
- if (d->m_fieldShown[Type])
- resizeColumnToContents(d->m_fieldShown[Name]?1:0);
- collapseAll();
- }
+ if (d->m_fieldShown[Type])
+ resizeColumnToContents(d->m_fieldShown[Name]?1:0);
+ collapseAll();
}
-void QmlProfilerEventsMainView::QmlProfilerEventsMainViewPrivate::buildModelFromList( const QList<QmlRangeEventData *> &list, QStandardItem *parentItem)
+void QmlProfilerEventsMainView::parseModelProxy()
{
- foreach (QmlRangeEventData *binding, list) {
- if (binding->calls == 0)
- continue;
-
+ const QList <QmlProfilerEventsModelProxy::QmlEventStats> eventList = d->modelProxy->getData();
+ foreach (const QmlProfilerEventsModelProxy::QmlEventStats &event, eventList) {
+ QStandardItem *parentItem = d->m_model->invisibleRootItem();
QList<QStandardItem *> newRow;
- if (m_fieldShown[Name])
- newRow << new EventsViewItem(binding->displayName);
- if (m_fieldShown[Type]) {
- QString typeString = QmlProfilerEventsMainView::nameForType(binding->eventType);
+ if (d->m_fieldShown[Name])
+ newRow << new EventsViewItem(event.displayName);
+
+ if (d->m_fieldShown[Type]) {
+ QString typeString = QmlProfilerEventsMainView::nameForType(event.eventType);
QString toolTipText;
- if (binding->eventType == Binding) {
- if (binding->bindingType == (int)OptimizedBinding) {
+ if (event.eventType == Binding) {
+ if (event.bindingType == (int)OptimizedBinding) {
typeString = typeString + tr(" (Opt)");
toolTipText = tr("Binding is evaluated by the optimized engine.");
- } else if (binding->bindingType == (int)V8Binding) {
+ } else if (event.bindingType == (int)V8Binding) {
toolTipText = tr("Binding not optimized (e.g. has side effects or assignments,\n"
"references to elements in other files, loops, etc.)");
@@ -622,44 +538,44 @@ void QmlProfilerEventsMainView::QmlProfilerEventsMainViewPrivate::buildModelFrom
newRow.last()->setToolTip(toolTipText);
}
- if (m_fieldShown[Percent]) {
- newRow << new EventsViewItem(QString::number(binding->percentOfTime,'f',2)+QLatin1String(" %"));
- newRow.last()->setData(QVariant(binding->percentOfTime));
+ if (d->m_fieldShown[TimeInPercent]) {
+ newRow << new EventsViewItem(QString::number(event.percentOfTime,'f',2)+QLatin1String(" %"));
+ newRow.last()->setData(QVariant(event.percentOfTime));
}
- if (m_fieldShown[TotalDuration]) {
- newRow << new EventsViewItem(displayTime(binding->duration));
- newRow.last()->setData(QVariant(binding->duration));
+ if (d->m_fieldShown[TotalTime]) {
+ newRow << new EventsViewItem(displayTime(event.duration));
+ newRow.last()->setData(QVariant(event.duration));
}
- if (m_fieldShown[CallCount]) {
- newRow << new EventsViewItem(QString::number(binding->calls));
- newRow.last()->setData(QVariant(binding->calls));
+ if (d->m_fieldShown[CallCount]) {
+ newRow << new EventsViewItem(QString::number(event.calls));
+ newRow.last()->setData(QVariant(event.calls));
}
- if (m_fieldShown[TimePerCall]) {
- newRow << new EventsViewItem(displayTime(binding->timePerCall));
- newRow.last()->setData(QVariant(binding->timePerCall));
+ if (d->m_fieldShown[TimePerCall]) {
+ newRow << new EventsViewItem(displayTime(event.timePerCall));
+ newRow.last()->setData(QVariant(event.timePerCall));
}
- if (m_fieldShown[MedianTime]) {
- newRow << new EventsViewItem(displayTime(binding->medianTime));
- newRow.last()->setData(QVariant(binding->medianTime));
+ if (d->m_fieldShown[MedianTime]) {
+ newRow << new EventsViewItem(displayTime(event.medianTime));
+ newRow.last()->setData(QVariant(event.medianTime));
}
- if (m_fieldShown[MaxTime]) {
- newRow << new EventsViewItem(displayTime(binding->maxTime));
- newRow.last()->setData(QVariant(binding->maxTime));
+ if (d->m_fieldShown[MaxTime]) {
+ newRow << new EventsViewItem(displayTime(event.maxTime));
+ newRow.last()->setData(QVariant(event.maxTime));
}
- if (m_fieldShown[MinTime]) {
- newRow << new EventsViewItem(displayTime(binding->minTime));
- newRow.last()->setData(QVariant(binding->minTime));
+ if (d->m_fieldShown[MinTime]) {
+ newRow << new EventsViewItem(displayTime(event.minTime));
+ newRow.last()->setData(QVariant(event.minTime));
}
- if (m_fieldShown[Details]) {
- newRow << new EventsViewItem(binding->details);
- newRow.last()->setData(QVariant(binding->details));
+ if (d->m_fieldShown[Details]) {
+ newRow << new EventsViewItem(event.details);
+ newRow.last()->setData(QVariant(event.details));
}
@@ -670,16 +586,17 @@ void QmlProfilerEventsMainView::QmlProfilerEventsMainViewPrivate::buildModelFrom
item->setEditable(false);
// metadata
- newRow.at(0)->setData(QVariant(binding->eventHashStr),EventHashStrRole);
- newRow.at(0)->setData(QVariant(binding->location.filename),FilenameRole);
- newRow.at(0)->setData(QVariant(binding->location.line),LineRole);
- newRow.at(0)->setData(QVariant(binding->location.column),ColumnRole);
- newRow.at(0)->setData(QVariant(binding->eventId),EventIdRole);
- if (binding->isBindingLoop)
+ newRow.at(0)->setData(QVariant(event.eventHashStr),EventHashStrRole);
+ newRow.at(0)->setData(QVariant(event.location.filename),FilenameRole);
+ newRow.at(0)->setData(QVariant(event.location.line),LineRole);
+ newRow.at(0)->setData(QVariant(event.location.column),ColumnRole);
+
+ if (event.isBindingLoop) {
foreach (QStandardItem *item, newRow) {
item->setBackground(colors()->bindingLoopBackground);
item->setToolTip(tr("Binding loop detected."));
}
+ }
// append
parentItem->appendRow(newRow);
@@ -687,58 +604,6 @@ void QmlProfilerEventsMainView::QmlProfilerEventsMainViewPrivate::buildModelFrom
}
}
-void QmlProfilerEventsMainView::QmlProfilerEventsMainViewPrivate::buildV8ModelFromList(const QList<QV8EventData *> &list)
-{
- for (int index = 0; index < list.count(); index++) {
- QV8EventData *v8event = list.at(index);
- QList<QStandardItem *> newRow;
-
- if (m_fieldShown[Name])
- newRow << new EventsViewItem(v8event->displayName);
-
- if (m_fieldShown[Percent]) {
- newRow << new EventsViewItem(QString::number(v8event->totalPercent,'f',2)+QLatin1String(" %"));
- newRow.last()->setData(QVariant(v8event->totalPercent));
- }
-
- if (m_fieldShown[TotalDuration]) {
- newRow << new EventsViewItem(displayTime(v8event->totalTime));
- newRow.last()->setData(QVariant(v8event->totalTime));
- }
-
- if (m_fieldShown[SelfPercent]) {
- newRow << new EventsViewItem(QString::number(v8event->selfPercent,'f',2)+QLatin1String(" %"));
- newRow.last()->setData(QVariant(v8event->selfPercent));
- }
-
- if (m_fieldShown[SelfDuration]) {
- newRow << new EventsViewItem(displayTime(v8event->selfTime));
- newRow.last()->setData(QVariant(v8event->selfTime));
- }
-
- if (m_fieldShown[Details]) {
- newRow << new EventsViewItem(v8event->functionName);
- newRow.last()->setData(QVariant(v8event->functionName));
- }
-
- if (!newRow.isEmpty()) {
- // no edit
- foreach (QStandardItem *item, newRow)
- item->setEditable(false);
-
- // metadata
- 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
- newRow.at(0)->setData(QVariant(v8event->eventId), EventIdRole);
-
- // append
- m_model->invisibleRootItem()->appendRow(newRow);
- }
- }
-}
-
QString QmlProfilerEventsMainView::displayTime(double time)
{
if (time < 1e6)
@@ -763,26 +628,16 @@ QString QmlProfilerEventsMainView::nameForType(int typeNumber)
void QmlProfilerEventsMainView::getStatisticsInRange(qint64 rangeStart, qint64 rangeEnd)
{
- if (d->m_profilerDataModel)
- d->m_profilerDataModel->compileStatistics(rangeStart, rangeEnd);
- buildModel();
-}
-
-bool QmlProfilerEventsMainView::isRangeGlobal(qint64 rangeStart, qint64 rangeEnd) const
-{
- if (d->m_profilerDataModel)
- return d->m_profilerDataModel->traceStartTime() == rangeStart && d->m_profilerDataModel->traceEndTime() == rangeEnd;
- else
- return true;
+ d->modelProxy->limitToRange(rangeStart, rangeEnd);
}
-int QmlProfilerEventsMainView::selectedEventId() const
+QString QmlProfilerEventsMainView::selectedEventHash() const
{
QModelIndex index = selectedItem();
if (!index.isValid())
- return -1;
+ return QString();
QStandardItem *item = d->m_model->item(index.row(), 0);
- return item->data(EventIdRole).toInt();
+ return item->data(EventHashStrRole).toString();
}
@@ -807,20 +662,16 @@ void QmlProfilerEventsMainView::jumpToItem(const QModelIndex &index)
emit gotoSourceLocation(fileName, line, column);
// show in callers/callees subwindow
- emit eventSelected(infoItem->data(EventIdRole).toInt());
-
- // show in timelinerenderer
- if (d->m_viewType == EventsView)
- emit showEventInTimeline(infoItem->data(EventIdRole).toInt());
+ emit eventSelected(infoItem->data(EventHashStrRole).toString());
d->m_preventSelectBounce = false;
}
-void QmlProfilerEventsMainView::selectEvent(int eventId)
+void QmlProfilerEventsMainView::selectEvent(const QString &eventHash)
{
for (int i=0; i<d->m_model->rowCount(); i++) {
QStandardItem *infoItem = d->m_model->item(i, 0);
- if (infoItem->data(EventIdRole).toInt() == eventId) {
+ if (infoItem->data(EventHashStrRole).toString() == eventHash) {
setCurrentIndex(d->m_model->indexFromItem(infoItem));
jumpToItem(currentIndex());
return;
@@ -828,14 +679,18 @@ void QmlProfilerEventsMainView::selectEvent(int eventId)
}
}
-void QmlProfilerEventsMainView::selectEventByLocation(const QString &filename, int line)
+void QmlProfilerEventsMainView::selectEventByLocation(const QString &filename, int line, int column)
{
if (d->m_preventSelectBounce)
return;
for (int i=0; i<d->m_model->rowCount(); i++) {
QStandardItem *infoItem = d->m_model->item(i, 0);
- if (currentIndex() != d->m_model->indexFromItem(infoItem) && infoItem->data(FilenameRole).toString() == filename && infoItem->data(LineRole).toInt() == line) {
+ if (currentIndex() != d->m_model->indexFromItem(infoItem) &&
+ infoItem->data(FilenameRole).toString() == filename &&
+ infoItem->data(LineRole).toInt() == line &&
+ (column == -1 ||
+ infoItem->data(ColumnRole).toInt() == column)) {
setCurrentIndex(d->m_model->indexFromItem(infoItem));
jumpToItem(currentIndex());
return;
@@ -852,23 +707,7 @@ QModelIndex QmlProfilerEventsMainView::selectedItem() const
return sel.first();
}
-void QmlProfilerEventsMainView::changeDetailsForEvent(int eventId, const QString &newString)
-{
- // available only for QML
- if (d->m_viewType != EventsView)
- return;
-
- for (int i=0; i<d->m_model->rowCount(); i++) {
- QStandardItem *infoItem = d->m_model->item(i, 0);
- if (infoItem->data(EventIdRole).toInt() == eventId) {
- d->m_model->item(i,d->m_columnIndex[Details])->setData(QVariant(newString),Qt::DisplayRole);
- d->m_model->item(i,d->m_columnIndex[Details])->setData(QVariant(newString));
- return;
- }
- }
-}
-
-QString QmlProfilerEventsMainView::QmlProfilerEventsMainViewPrivate::textForItem(QStandardItem *item, bool recursive = true) const
+QString QmlProfilerEventsMainView::QmlProfilerEventsMainViewPrivate::textForItem(QStandardItem *item, bool recursive) const
{
QString str;
@@ -932,116 +771,82 @@ void QmlProfilerEventsMainView::copyRowToClipboard() const
////////////////////////////////////////////////////////////////////////////////////
-QmlProfilerEventsParentsAndChildrenView::QmlProfilerEventsParentsAndChildrenView(
- SubViewType subtableType, QWidget *parent, QmlProfilerDataModel *model)
- : QTreeView(parent)
+class QmlProfilerEventRelativesView::QmlProfilerEventParentsViewPrivate
+{
+public:
+ QmlProfilerEventParentsViewPrivate(QmlProfilerEventRelativesView *qq):q(qq) {}
+ ~QmlProfilerEventParentsViewPrivate() {}
+
+ QmlProfilerEventRelativesModelProxy *modelProxy;
+
+ QmlProfilerEventRelativesView *q;
+};
+
+QmlProfilerEventRelativesView::QmlProfilerEventRelativesView(QmlProfilerModelManager *modelManager, QmlProfilerEventRelativesModelProxy *modelProxy, QWidget *parent)
+ : QmlProfilerTreeView(parent), d(new QmlProfilerEventParentsViewPrivate(this))
{
- m_profilerDataModel = model;
+ Q_UNUSED(modelManager);
+ setSortingEnabled(false);
+ d->modelProxy = modelProxy;
setModel(new QStandardItemModel(this));
setRootIsDecorated(false);
- setFrameStyle(QFrame::NoFrame);
- m_subtableType = subtableType;
updateHeader();
connect(this,SIGNAL(clicked(QModelIndex)), this,SLOT(jumpToItem(QModelIndex)));
}
-QmlProfilerEventsParentsAndChildrenView::~QmlProfilerEventsParentsAndChildrenView()
-{
-}
-
-void QmlProfilerEventsParentsAndChildrenView::setViewType(SubViewType type)
+QmlProfilerEventRelativesView::~QmlProfilerEventRelativesView()
{
- m_subtableType = type;
- updateHeader();
+ delete d;
}
-void QmlProfilerEventsParentsAndChildrenView::displayEvent(int eventId)
+void QmlProfilerEventRelativesView::displayEvent(const QString &eventHash)
{
- if (!m_profilerDataModel)
- return;
-
- bool isV8 = m_subtableType == V8ParentsView || m_subtableType == V8ChildrenView;
- bool isChildren = m_subtableType == ChildrenView || m_subtableType == V8ChildrenView;
-
- if (isV8) {
- QV8EventData *v8event = m_profilerDataModel->v8EventDescription(eventId);
- if (v8event) {
- if (isChildren) {
- QList <QV8EventSub *> childrenList = v8event->childrenHash.values();
- rebuildTree((QObject *)&childrenList);
- }
- else {
- QList <QV8EventSub *> parentList = v8event->parentHash.values();
- rebuildTree((QObject *)&parentList);
- }
- }
- } else {
- QmlRangeEventData *qmlEvent = m_profilerDataModel->eventDescription(eventId);
- if (qmlEvent) {
- if (isChildren) {
- QList <QmlRangeEventRelative *> childrenList = qmlEvent->childrenHash.values();
- rebuildTree((QObject *)&childrenList);
- }
- else {
- QList <QmlRangeEventRelative *> parentList = qmlEvent->parentHash.values();
- rebuildTree((QObject *)&parentList);
- }
- }
- }
+ rebuildTree(d->modelProxy->getData(eventHash));
updateHeader();
resizeColumnToContents(0);
setSortingEnabled(true);
- if (isV8)
- sortByColumn(1);
- else
- sortByColumn(2);
+ sortByColumn(2);
}
-void QmlProfilerEventsParentsAndChildrenView::rebuildTree(void *profilerDataModel)
+void QmlProfilerEventRelativesView::rebuildTree(QmlProfilerEventRelativesModelProxy::QmlEventRelativesMap eventMap)
{
Q_ASSERT(treeModel());
treeModel()->clear();
QStandardItem *topLevelItem = treeModel()->invisibleRootItem();
- bool isV8 = m_subtableType == V8ParentsView || m_subtableType == V8ChildrenView;
-
- QList <QmlRangeEventRelative *> *qmlList = static_cast< QList <QmlRangeEventRelative *> *>(profilerDataModel);
- QList <QV8EventSub*> *v8List = static_cast< QList <QV8EventSub *> *>(profilerDataModel);
- int listLength;
- if (!isV8)
- listLength = qmlList->length();
- else
- listLength = v8List->length();
-
- for (int index=0; index < listLength; index++) {
+ //foreach (const QmlProfilerEventParentsModelProxy::QmlEventParentData &event, eventMap.values()) {
+ foreach (const QString &key, eventMap.keys()) {
+ const QmlProfilerEventRelativesModelProxy::QmlEventRelativesData &event = eventMap[key];
QList<QStandardItem *> newRow;
- if (!isV8) {
- QmlRangeEventRelative *event = qmlList->at(index);
-
- newRow << new EventsViewItem(event->reference->displayName);
- newRow << new EventsViewItem(QmlProfilerEventsMainView::nameForType(event->reference->eventType));
- newRow << new EventsViewItem(QmlProfilerEventsMainView::displayTime(event->duration));
- newRow << new EventsViewItem(QString::number(event->calls));
- newRow << new EventsViewItem(event->reference->details);
- newRow.at(0)->setData(QVariant(event->reference->eventId), EventIdRole);
- newRow.at(2)->setData(QVariant(event->duration));
- newRow.at(3)->setData(QVariant(event->calls));
- if (event->inLoopPath)
- foreach (QStandardItem *item, newRow) {
- item->setBackground(colors()->bindingLoopBackground);
- item->setToolTip(tr("Part of binding loop."));
- }
- } else {
- QV8EventSub *event = v8List->at(index);
- newRow << new EventsViewItem(event->reference->displayName);
- newRow << new EventsViewItem(QmlProfilerEventsMainView::displayTime(event->totalTime));
- newRow << new EventsViewItem(event->reference->functionName);
- newRow.at(0)->setData(QVariant(event->reference->eventId), EventIdRole);
- newRow.at(1)->setData(QVariant(event->totalTime));
+
+ // ToDo: here we were going to search for the data in the other modelproxy
+ // maybe we should store the data in this proxy and get it here
+ // no indirections at this level of abstraction!
+ newRow << new EventsViewItem(event.displayName);
+ newRow << new EventsViewItem(QmlProfilerEventsMainView::nameForType(event.eventType));
+ newRow << new EventsViewItem(QmlProfilerEventsMainView::displayTime(event.duration));
+ newRow << new EventsViewItem(QString::number(event.calls));
+ newRow << new EventsViewItem(event.details);
+
+// newRow << new EventsViewItem(event->reference->displayName);
+// newRow << new EventsViewItem(QmlProfilerEventsMainView::nameForType(event->reference->eventType));
+// newRow << new EventsViewItem(QmlProfilerEventsMainView::displayTime(event->duration));
+// newRow << new EventsViewItem(QString::number(event->calls));
+// newRow << new EventsViewItem(event->reference->details);
+ newRow.at(0)->setData(QVariant(key), EventHashStrRole);
+ newRow.at(2)->setData(QVariant(event.duration));
+ newRow.at(3)->setData(QVariant(event.calls));
+
+ if (event.isBindingLoop) {
+ foreach (QStandardItem *item, newRow) {
+ item->setBackground(colors()->bindingLoopBackground);
+ item->setToolTip(tr("Part of binding loop."));
+ }
}
+
foreach (QStandardItem *item, newRow)
item->setEditable(false);
@@ -1049,7 +854,7 @@ void QmlProfilerEventsParentsAndChildrenView::rebuildTree(void *profilerDataMode
}
}
-void QmlProfilerEventsParentsAndChildrenView::clear()
+void QmlProfilerEventRelativesView::clear()
{
if (treeModel()) {
treeModel()->clear();
@@ -1057,52 +862,43 @@ void QmlProfilerEventsParentsAndChildrenView::clear()
}
}
-void QmlProfilerEventsParentsAndChildrenView::updateHeader()
+void QmlProfilerEventRelativesView::updateHeader()
{
- bool isV8 = m_subtableType == V8ParentsView || m_subtableType == V8ChildrenView;
- bool isChildren = m_subtableType == ChildrenView || m_subtableType == V8ChildrenView;
-
- header()->setResizeMode(QHeaderView::Interactive);
- header()->setDefaultSectionSize(100);
- header()->setMinimumSectionSize(50);
+ bool calleesView = qobject_cast<QmlProfilerEventChildrenModelProxy *>(d->modelProxy) != 0;
if (treeModel()) {
- if (isV8)
- treeModel()->setColumnCount(3);
- else
- treeModel()->setColumnCount(5);
+ treeModel()->setColumnCount(5);
int columnIndex = 0;
- if (isChildren)
- treeModel()->setHeaderData(columnIndex++, Qt::Horizontal, QVariant(tr("Callee")));
+ if (calleesView)
+ treeModel()->setHeaderData(columnIndex++, Qt::Horizontal, QVariant(displayHeader(Callee)));
else
- treeModel()->setHeaderData(columnIndex++, Qt::Horizontal, QVariant(tr("Caller")));
+ treeModel()->setHeaderData(columnIndex++, Qt::Horizontal, QVariant(displayHeader(Caller)));
+
+ treeModel()->setHeaderData(columnIndex++, Qt::Horizontal, QVariant(displayHeader(Type)));
- if (!isV8)
- treeModel()->setHeaderData(columnIndex++, Qt::Horizontal, QVariant(tr("Type")));
+ treeModel()->setHeaderData(columnIndex++, Qt::Horizontal, QVariant(displayHeader(TotalTime)));
- treeModel()->setHeaderData(columnIndex++, Qt::Horizontal, QVariant(tr("Total Time")));
+ treeModel()->setHeaderData(columnIndex++, Qt::Horizontal, QVariant(displayHeader(CallCount)));
- if (!isV8)
- treeModel()->setHeaderData(columnIndex++, Qt::Horizontal, QVariant(tr("Calls")));
- if (isChildren)
- treeModel()->setHeaderData(columnIndex++, Qt::Horizontal, QVariant(tr("Callee Description")));
+ if (calleesView)
+ treeModel()->setHeaderData(columnIndex++, Qt::Horizontal, QVariant(displayHeader(CalleeDescription)));
else
- treeModel()->setHeaderData(columnIndex++, Qt::Horizontal, QVariant(tr("Caller Description")));
+ treeModel()->setHeaderData(columnIndex++, Qt::Horizontal, QVariant(displayHeader(CallerDescription)));
}
}
-QStandardItemModel *QmlProfilerEventsParentsAndChildrenView::treeModel()
+QStandardItemModel *QmlProfilerEventRelativesView::treeModel()
{
return qobject_cast<QStandardItemModel *>(model());
}
-void QmlProfilerEventsParentsAndChildrenView::jumpToItem(const QModelIndex &index)
+void QmlProfilerEventRelativesView::jumpToItem(const QModelIndex &index)
{
if (treeModel()) {
QStandardItem *infoItem = treeModel()->item(index.row(), 0);
- emit eventClicked(infoItem->data(EventIdRole).toInt());
+ emit eventClicked(infoItem->data(EventHashStrRole).toString());
}
}
diff --git a/src/plugins/qmlprofiler/qmlprofilereventview.h b/src/plugins/qmlprofiler/qmlprofilereventview.h
index e794a07ef6..747cc613d3 100644
--- a/src/plugins/qmlprofiler/qmlprofilereventview.h
+++ b/src/plugins/qmlprofiler/qmlprofilereventview.h
@@ -33,7 +33,9 @@
#include <QTreeView>
#include <QStandardItemModel>
#include <qmldebug/qmlprofilereventtypes.h>
-#include "qmlprofilerdatamodel.h"
+#include "qmlprofilermodelmanager.h"
+#include "qmlprofilereventsmodelproxy.h"
+#include "qmlprofilertreeview.h"
#include <analyzerbase/ianalyzertool.h>
@@ -43,7 +45,8 @@ namespace QmlProfiler {
namespace Internal {
class QmlProfilerEventsMainView;
-class QmlProfilerEventsParentsAndChildrenView;
+class QmlProfilerEventChildrenView;
+class QmlProfilerEventRelativesView;
enum ItemRole {
EventHashStrRole = Qt::UserRole+1,
@@ -58,12 +61,11 @@ class QmlProfilerEventsWidget : public QWidget
Q_OBJECT
public:
explicit QmlProfilerEventsWidget(QWidget *parent,
- Analyzer::IAnalyzerTool *profilerTool,
+ QmlProfilerTool *profilerTool,
QmlProfilerViewManager *container,
- QmlProfilerDataModel *profilerDataModel );
+ QmlProfilerModelManager *profilerModelManager );
~QmlProfilerEventsWidget();
- void switchToV8View();
void clear();
void getStatisticsInRange(qint64 rangeStart, qint64 rangeEnd);
@@ -76,16 +78,14 @@ public:
void setShowExtendedStatistics(bool show);
bool showExtendedStatistics() const;
- bool isQml() const;
- bool isV8() const;
signals:
void gotoSourceLocation(const QString &fileName, int lineNumber, int columnNumber);
- void showEventInTimeline(int eventId);
+ void eventSelectedByHash(const QString &eventHash);
void resized();
public slots:
- void updateSelectedEvent(int eventId) const;
+ void updateSelectedEvent(const QString &eventHash) const;
void selectBySourceLocation(const QString &filename, int line, int column);
private slots:
@@ -100,44 +100,15 @@ private:
QmlProfilerEventsWidgetPrivate *d;
};
-class QmlProfilerEventsMainView : public QTreeView
+class QmlProfilerEventsMainView : public QmlProfilerTreeView
{
Q_OBJECT
public:
- enum Fields {
- Name,
- Type,
- Percent,
- TotalDuration,
- SelfPercent,
- SelfDuration,
- CallCount,
- TimePerCall,
- MaxTime,
- MinTime,
- MedianTime,
- Details,
-
- MaxFields
- };
-
- enum ViewTypes {
- EventsView,
- CallersView,
- CalleesView,
- V8ProfileView,
-
- MaxViewTypes
- };
-
- explicit QmlProfilerEventsMainView(ViewTypes viewType,
- QWidget *parent,
- QmlProfilerDataModel *dataModel);
+ explicit QmlProfilerEventsMainView(QWidget *parent,
+ QmlProfilerEventsModelProxy *modelProxy);
~QmlProfilerEventsMainView();
void setFieldViewable(Fields field, bool show);
- void setViewType(ViewTypes type);
- ViewTypes viewType() const;
void setShowAnonymousEvents( bool showThem );
QModelIndex selectedItem() const;
@@ -148,30 +119,30 @@ public:
static QString nameForType(int typeNumber);
void getStatisticsInRange(qint64 rangeStart, qint64 rangeEnd);
- bool isRangeGlobal(qint64 rangeStart, qint64 rangeEnd) const;
- int selectedEventId() const;
+// int selectedEventId() const;
+ QString selectedEventHash() const;
void setShowExtendedStatistics(bool);
bool showExtendedStatistics() const;
+
signals:
void gotoSourceLocation(const QString &fileName, int lineNumber, int columnNumber);
- void eventSelected(int eventId);
- void showEventInTimeline(int eventId);
+ void eventSelected(const QString &eventHash);
public slots:
void clear();
void jumpToItem(const QModelIndex &index);
- void selectEvent(int eventId);
- void selectEventByLocation(const QString &filename, int line);
+ void selectEvent(const QString &eventHash);
+ void selectEventByLocation(const QString &filename, int line, int column);
void buildModel();
- void changeDetailsForEvent(int eventId, const QString &newString);
private slots:
void profilerDataModelStateChanged();
private:
void setHeaderLabels();
+ void parseModelProxy();
private:
class QmlProfilerEventsMainViewPrivate;
@@ -179,40 +150,31 @@ private:
};
-class QmlProfilerEventsParentsAndChildrenView : public QTreeView
+class QmlProfilerEventRelativesView : public QmlProfilerTreeView
{
Q_OBJECT
public:
- enum SubViewType {
- ParentsView,
- ChildrenView,
- V8ParentsView,
- V8ChildrenView,
- MaxSubtableTypes
- };
-
- explicit QmlProfilerEventsParentsAndChildrenView(SubViewType subtableType,
- QWidget *parent,
- QmlProfilerDataModel *model);
- ~QmlProfilerEventsParentsAndChildrenView();
-
- void setViewType(SubViewType type);
+ explicit QmlProfilerEventRelativesView(QmlProfilerModelManager *modelManager,
+ QmlProfilerEventRelativesModelProxy *modelProxy,
+ QWidget *parent );
+ ~QmlProfilerEventRelativesView();
signals:
- void eventClicked(int eventId);
+ void eventClicked(const QString &eventHash);
public slots:
- void displayEvent(int eventId);
+ void displayEvent(const QString &eventHash);
void jumpToItem(const QModelIndex &);
void clear();
private:
- void rebuildTree(void *profilerDataModel);
+ void rebuildTree(QmlProfilerEventParentsModelProxy::QmlEventRelativesMap eventMap);
void updateHeader();
QStandardItemModel *treeModel();
- QmlProfilerDataModel *m_profilerDataModel;
+// QmlProfilerModelManager *m_profilerModelManager;
- SubViewType m_subtableType;
+ class QmlProfilerEventParentsViewPrivate;
+ QmlProfilerEventParentsViewPrivate *d;
};
} // namespace Internal
diff --git a/src/plugins/qmlprofiler/qmlprofilermodelmanager.cpp b/src/plugins/qmlprofiler/qmlprofilermodelmanager.cpp
new file mode 100644
index 0000000000..46df68f9b3
--- /dev/null
+++ b/src/plugins/qmlprofiler/qmlprofilermodelmanager.cpp
@@ -0,0 +1,364 @@
+/****************************************************************************
+**
+** 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 "qmlprofilermodelmanager.h"
+#include "qmlprofilersimplemodel.h"
+#include "qmlprofilerprocessedmodel.h"
+#include "qv8profilerdatamodel.h"
+#include "qmlprofilertracefile.h"
+
+#include <utils/qtcassert.h>
+
+#include <QDebug>
+#include <QFile>
+
+namespace QmlProfiler {
+namespace Internal {
+
+
+/////////////////////////////////////////////////////////////////////
+QmlProfilerDataState::QmlProfilerDataState(QmlProfilerModelManager *modelManager, QObject *parent)
+ : QObject(parent), m_state(Empty), m_modelManager(modelManager)
+{
+ connect(this, SIGNAL(error(QString)), m_modelManager, SIGNAL(error(QString)));
+ connect(this, SIGNAL(stateChanged()), m_modelManager, SIGNAL(stateChanged()));
+}
+
+void QmlProfilerDataState::setState(QmlProfilerDataState::State state)
+{
+ // It's not an error, we are continuously calling "AcquiringData" for example
+ if (m_state == state)
+ return;
+
+ switch (state) {
+ case Empty:
+ // if it's not empty, complain but go on
+ QTC_ASSERT(m_modelManager->isEmpty(), /**/);
+ break;
+ case AcquiringData:
+ // we're not supposed to receive new data while processing older data
+ QTC_ASSERT(m_state != ProcessingData, return);
+ break;
+ case ProcessingData:
+ QTC_ASSERT(m_state == AcquiringData, return);
+ break;
+ case Done:
+ QTC_ASSERT(m_state == ProcessingData || m_state == Empty, return);
+ break;
+ default:
+ emit error(tr("Trying to set unknown state in events list"));
+ break;
+ }
+
+ m_state = state;
+ emit stateChanged();
+
+ return;
+}
+
+
+/////////////////////////////////////////////////////////////////////
+QmlProfilerTraceTime::QmlProfilerTraceTime(QObject *parent) : QObject(parent)
+{
+ clear();
+}
+
+QmlProfilerTraceTime::~QmlProfilerTraceTime()
+{
+}
+
+qint64 QmlProfilerTraceTime::startTime() const
+{
+ return m_startTime;
+}
+
+qint64 QmlProfilerTraceTime::endTime() const
+{
+ return m_endTime;
+}
+
+qint64 QmlProfilerTraceTime::duration() const
+{
+ return endTime() - startTime();
+}
+
+void QmlProfilerTraceTime::clear()
+{
+ m_startTime = -1;
+ m_endTime = 0;
+}
+
+void QmlProfilerTraceTime::setStartTime(qint64 time)
+{
+ m_startTime = time;
+}
+
+void QmlProfilerTraceTime::setEndTime(qint64 time)
+{
+ m_endTime = time;
+}
+
+
+} // namespace Internal
+
+/////////////////////////////////////////////////////////////////////
+
+class QmlProfilerModelManager::QmlProfilerModelManagerPrivate
+{
+public:
+ QmlProfilerModelManagerPrivate(QmlProfilerModelManager *qq) : q(qq) {}
+ ~QmlProfilerModelManagerPrivate() {}
+ QmlProfilerModelManager *q;
+
+ QmlProfilerSimpleModel *model;
+ QV8ProfilerDataModel *v8Model;
+ QmlProfilerDataState *dataState;
+ QmlProfilerTraceTime *traceTime;
+
+ QVector <double> partialCounts;
+ double progress;
+ qint64 estimatedTime;
+
+ // file to load
+ QString fileName;
+};
+
+
+QmlProfilerModelManager::QmlProfilerModelManager(Utils::FileInProjectFinder *finder, QObject *parent) :
+ QObject(parent), d(new QmlProfilerModelManagerPrivate(this))
+{
+ d->model = new QmlProfilerProcessedModel(finder, this);
+ d->v8Model = new QV8ProfilerDataModel(this);
+// d->model = new QmlProfilerSimpleModel(this);
+ d->dataState = new QmlProfilerDataState(this, this);
+ d->traceTime = new QmlProfilerTraceTime(this);
+}
+
+QmlProfilerModelManager::~QmlProfilerModelManager()
+{
+ delete d;
+}
+
+QmlProfilerTraceTime *QmlProfilerModelManager::traceTime() const
+{
+ return d->traceTime;
+}
+
+QmlProfilerSimpleModel *QmlProfilerModelManager::simpleModel() const
+{
+ return d->model;
+}
+
+QV8ProfilerDataModel *QmlProfilerModelManager::v8Model() const
+{
+ return d->v8Model;
+}
+
+bool QmlProfilerModelManager::isEmpty() const
+{
+ return d->model->isEmpty() && d->v8Model->isEmpty();
+}
+
+int QmlProfilerModelManager::count() const
+{
+ return d->model->count();
+}
+
+double QmlProfilerModelManager::progress() const
+{
+ return d->progress;
+}
+
+int QmlProfilerModelManager::registerModelProxy()
+{
+ d->partialCounts << 0;
+ return d->partialCounts.count()-1;
+}
+
+void QmlProfilerModelManager::modelProxyCountUpdated(int proxyId, qint64 count, qint64 max)
+{
+ d->progress -= d->partialCounts[proxyId] / d->partialCounts.count();
+
+ if (max <= 0)
+ d->partialCounts[proxyId] = 1;
+ else
+ d->partialCounts[proxyId] = (double)count / (double) max;
+
+ d->progress += d->partialCounts[proxyId] / d->partialCounts.count();
+
+ emit progressChanged();
+ if (d->progress > 0.99)
+ emit dataAvailable();
+}
+
+qint64 QmlProfilerModelManager::estimatedProfilingTime() const
+{
+ return d->estimatedTime;
+}
+
+void QmlProfilerModelManager::newTimeEstimation(qint64 estimation)
+{
+ d->estimatedTime = estimation;
+}
+
+void QmlProfilerModelManager::addQmlEvent(int type,
+ int bindingType,
+ qint64 startTime,
+ qint64 length,
+ const QStringList &data,
+ const QmlDebug::QmlEventLocation &location,
+ qint64 ndata1,
+ qint64 ndata2,
+ qint64 ndata3,
+ qint64 ndata4,
+ qint64 ndata5)
+{
+ // If trace start time was not explicitly set, use the first event
+ if (d->traceTime->startTime() == -1)
+ d->traceTime->setStartTime(startTime);
+
+ QTC_ASSERT(state() == QmlProfilerDataState::AcquiringData, /**/);
+ d->model->addQmlEvent(type, bindingType, startTime, length, data, location, ndata1, ndata2, ndata3, ndata4, ndata5);
+ emit countChanged();
+}
+
+void QmlProfilerModelManager::addV8Event(int depth, const QString &function, const QString &filename,
+ int lineNumber, double totalTime, double selfTime)
+{
+ d->v8Model->addV8Event(depth, function, filename, lineNumber,totalTime, selfTime);
+}
+
+void QmlProfilerModelManager::complete()
+{
+ if (state() == QmlProfilerDataState::AcquiringData) {
+ // If trace end time was not explicitly set, use the last event
+ if (d->traceTime->endTime() == 0)
+ d->traceTime->setEndTime(d->model->lastTimeMark());
+ setState(QmlProfilerDataState::ProcessingData);
+ d->model->complete();
+ d->v8Model->complete();
+ setState(QmlProfilerDataState::Done);
+ } else
+ if (state() == QmlProfilerDataState::Empty) {
+ setState(QmlProfilerDataState::Done);
+ } else
+ if (state() == QmlProfilerDataState::Done) {
+ // repeated Done states are ignored
+ } else {
+ emit error(tr("Unexpected complete signal in data model"));
+ }
+}
+
+void QmlProfilerModelManager::save(const QString &filename)
+{
+ QFile file(filename);
+ if (!file.open(QIODevice::WriteOnly)) {
+ emit error(tr("Could not open %1 for writing.").arg(filename));
+ return;
+ }
+
+ QmlProfilerFileWriter writer;
+
+ writer.setTraceTime(traceTime()->startTime(), traceTime()->endTime(), traceTime()->duration());
+ writer.setV8DataModel(d->v8Model);
+ writer.setQmlEvents(d->model->getEvents());
+ writer.save(&file);
+}
+
+void QmlProfilerModelManager::load(const QString &filename)
+{
+ d->fileName = filename;
+ load();
+}
+
+void QmlProfilerModelManager::setFilename(const QString &filename)
+{
+ d->fileName = filename;
+}
+
+void QmlProfilerModelManager::load()
+{
+ QString filename = d->fileName;
+
+ QFile file(filename);
+
+ if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
+ emit error(tr("Could not open %1 for reading.").arg(filename));
+ return;
+ }
+
+ // erase current
+ clear();
+
+ setState(QmlProfilerDataState::AcquiringData);
+
+ QmlProfilerFileReader reader;
+ connect(&reader, SIGNAL(error(QString)), this, SIGNAL(error(QString)));
+ connect(&reader, SIGNAL(rangedEvent(int,int,qint64,qint64,QStringList,QmlDebug::QmlEventLocation,
+ qint64, qint64, qint64, qint64, qint64)),
+ this, SLOT(addQmlEvent(int,int,qint64,qint64,QStringList,QmlDebug::QmlEventLocation,
+ qint64, qint64, qint64, qint64, qint64)));
+ connect(&reader, SIGNAL(traceStartTime(qint64)), traceTime(), SLOT(setStartTime(qint64)));
+ connect(&reader, SIGNAL(traceEndTime(qint64)), traceTime(), SLOT(setEndTime(qint64)));
+ reader.setV8DataModel(d->v8Model);
+ reader.load(&file);
+
+ complete();
+}
+
+
+void QmlProfilerModelManager::setState(QmlProfilerDataState::State state)
+{
+ d->dataState->setState(state);
+}
+
+QmlProfilerDataState::State QmlProfilerModelManager::state() const
+{
+ return d->dataState->state();
+}
+
+void QmlProfilerModelManager::clear()
+{
+ for (int i = 0; i < d->partialCounts.count(); i++)
+ d->partialCounts[i] = 0;
+ d->progress = 0;
+ d->model->clear();
+ d->v8Model->clear();
+ d->traceTime->clear();
+
+ emit countChanged();
+ setState(QmlProfilerDataState::Empty);
+}
+
+void QmlProfilerModelManager::prepareForWriting()
+{
+ setState(QmlProfilerDataState::AcquiringData);
+}
+
+} // namespace QmlProfiler
diff --git a/src/plugins/qmlprofiler/qmlprofilermodelmanager.h b/src/plugins/qmlprofiler/qmlprofilermodelmanager.h
new file mode 100644
index 0000000000..f814ec432c
--- /dev/null
+++ b/src/plugins/qmlprofiler/qmlprofilermodelmanager.h
@@ -0,0 +1,161 @@
+/****************************************************************************
+**
+** 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 QMLPROFILERMODELMANAGER_H
+#define QMLPROFILERMODELMANAGER_H
+
+#include "qmlprofiler_global.h"
+
+#include <qmldebug/qmlprofilereventlocation.h>
+#include <utils/fileinprojectfinder.h>
+
+#include <QObject>
+
+namespace QmlProfiler {
+class QmlProfilerSimpleModel;
+class QmlProfilerModelManager;
+
+namespace Internal {
+
+class QV8ProfilerDataModel;
+class QmlProfilerDataState : public QObject
+{
+ Q_OBJECT
+public:
+ enum State {
+ Empty,
+ AcquiringData,
+ ProcessingData,
+ Done
+ };
+
+ explicit QmlProfilerDataState(QmlProfilerModelManager *modelManager, QObject *parent = 0);
+ ~QmlProfilerDataState() {}
+
+ State state() const { return m_state; }
+
+signals:
+ void stateChanged();
+ void error(const QString &error);
+
+private:
+ void setState(State state);
+ State m_state;
+ QmlProfilerModelManager *m_modelManager;
+
+ friend class QmlProfiler::QmlProfilerModelManager;
+};
+
+class QmlProfilerTraceTime : public QObject
+{
+ Q_OBJECT
+public:
+ explicit QmlProfilerTraceTime(QObject *parent);
+ ~QmlProfilerTraceTime();
+
+ qint64 startTime() const;
+ qint64 endTime() const;
+ qint64 duration() const;
+
+public slots:
+ void clear();
+ void setStartTime(qint64 time);
+ void setEndTime(qint64 time);
+
+private:
+ qint64 m_startTime;
+ qint64 m_endTime;
+};
+
+} // End internal namespace
+
+using namespace Internal;
+
+// Interface between the Data Model and the Engine/Tool
+class QMLPROFILER_EXPORT QmlProfilerModelManager : public QObject
+{
+ Q_OBJECT
+public:
+
+ explicit QmlProfilerModelManager(Utils::FileInProjectFinder *finder, QObject *parent = 0);
+ ~QmlProfilerModelManager();
+
+ QmlProfilerDataState::State state() const;
+ QmlProfilerTraceTime *traceTime() const;
+ QmlProfilerSimpleModel *simpleModel() const;
+ QV8ProfilerDataModel *v8Model() const;
+
+ bool isEmpty() const;
+ int count() const;
+
+ double progress() const;
+ int registerModelProxy();
+ void modelProxyCountUpdated(int proxyId, qint64 count, qint64 max);
+
+ qint64 estimatedProfilingTime() const;
+
+signals:
+ void countChanged();
+ void error(const QString &error);
+ void stateChanged();
+ void progressChanged();
+ void dataAvailable();
+
+ void requestDetailsForLocation(int eventType, const QmlDebug::QmlEventLocation &location);
+
+public slots:
+ void clear();
+
+ void prepareForWriting();
+ void addQmlEvent(int type, int bindingType, qint64 startTime, qint64 length,
+ const QStringList &data, const QmlDebug::QmlEventLocation &location,
+ qint64 ndata1, qint64 ndata2, qint64 ndata3, qint64 ndata4, qint64 ndata5);
+ void addV8Event(int depth, const QString &function,const QString &filename, int lineNumber,
+ double totalTime, double selfTime);
+
+ void complete();
+
+ void save(const QString &filename);
+ void load(const QString &filename);
+ void setFilename(const QString &filename);
+ void load();
+
+ void newTimeEstimation(qint64 estimation);
+private:
+ void setState(QmlProfilerDataState::State state);
+
+
+private:
+ class QmlProfilerModelManagerPrivate;
+ QmlProfilerModelManagerPrivate *d;
+};
+
+}
+
+#endif
diff --git a/src/plugins/qmlprofiler/qmlprofilerpainteventsmodelproxy.cpp b/src/plugins/qmlprofiler/qmlprofilerpainteventsmodelproxy.cpp
new file mode 100644
index 0000000000..9cc160b1a5
--- /dev/null
+++ b/src/plugins/qmlprofiler/qmlprofilerpainteventsmodelproxy.cpp
@@ -0,0 +1,458 @@
+/****************************************************************************
+**
+** 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 "qmlprofilerpainteventsmodelproxy.h"
+#include "qmlprofilermodelmanager.h"
+#include "qmlprofilersimplemodel.h"
+#include <QCoreApplication>
+
+#include <QVector>
+#include <QHash>
+#include <QUrl>
+#include <QString>
+#include <QStack>
+
+#include <QDebug>
+
+namespace QmlProfiler {
+namespace Internal {
+
+struct CategorySpan {
+ bool expanded;
+ int expandedRows;
+ int contractedRows;
+};
+
+class PaintEventsModelProxy::PaintEventsModelProxyPrivate
+{
+public:
+ PaintEventsModelProxyPrivate(PaintEventsModelProxy *qq) : q(qq) {}
+ ~PaintEventsModelProxyPrivate() {}
+
+ QString displayTime(double time);
+ void computeAnimationCountLimit();
+
+ QVector <PaintEventsModelProxy::QmlPaintEventData> eventList;
+ int minAnimationCount;
+ int maxAnimationCount;
+ bool expanded;
+
+ PaintEventsModelProxy *q;
+};
+
+PaintEventsModelProxy::PaintEventsModelProxy(QObject *parent)
+ : AbstractTimelineModel(parent), d(new PaintEventsModelProxyPrivate(this))
+{
+}
+
+PaintEventsModelProxy::~PaintEventsModelProxy()
+{
+ delete d;
+}
+
+int PaintEventsModelProxy::categories() const
+{
+ return categoryCount();
+}
+
+QStringList PaintEventsModelProxy::categoryTitles() const
+{
+ QStringList retString;
+ for (int i=0; i<categories(); i++)
+ retString << categoryLabel(i);
+ return retString;
+}
+
+QString PaintEventsModelProxy::name() const
+{
+ return QLatin1String("PaintEventsModelProxy");
+}
+
+const QVector<PaintEventsModelProxy::QmlPaintEventData> PaintEventsModelProxy::getData() const
+{
+ return d->eventList;
+}
+
+const QVector<PaintEventsModelProxy::QmlPaintEventData> PaintEventsModelProxy::getData(qint64 fromTime, qint64 toTime) const
+{
+ int fromIndex = findFirstIndex(fromTime);
+ int toIndex = findLastIndex(toTime);
+ if (fromIndex != -1 && toIndex > fromIndex)
+ return d->eventList.mid(fromIndex, toIndex - fromIndex + 1);
+ else
+ return QVector<PaintEventsModelProxy::QmlPaintEventData>();
+}
+
+void PaintEventsModelProxy::clear()
+{
+ d->eventList.clear();
+ d->minAnimationCount = 1;
+ d->maxAnimationCount = 1;
+ d->expanded = false;
+ m_modelManager->modelProxyCountUpdated(m_modelId, 0, 1);
+}
+
+void PaintEventsModelProxy::dataChanged()
+{
+ if (m_modelManager->state() == QmlProfilerDataState::ProcessingData)
+ loadData();
+
+ if (m_modelManager->state() == QmlProfilerDataState::Empty)
+ clear();
+
+ emit stateChanged();
+ emit dataAvailable();
+ emit emptyChanged();
+ emit expandedChanged();
+}
+
+bool compareStartTimes(const PaintEventsModelProxy::QmlPaintEventData &t1, const PaintEventsModelProxy::QmlPaintEventData &t2)
+{
+ return t1.startTime < t2.startTime;
+}
+
+bool PaintEventsModelProxy::eventAccepted(const QmlProfilerSimpleModel::QmlEventData &event) const
+{
+ return (event.eventType == QmlDebug::Painting && event.bindingType == QmlDebug::AnimationFrame);
+}
+
+void PaintEventsModelProxy::loadData()
+{
+ clear();
+ QmlProfilerSimpleModel *simpleModel = m_modelManager->simpleModel();
+ if (simpleModel->isEmpty())
+ return;
+
+ // collect events
+ const QVector<QmlProfilerSimpleModel::QmlEventData> referenceList = simpleModel->getEvents();
+ foreach (const QmlProfilerSimpleModel::QmlEventData &event, referenceList) {
+ if (!eventAccepted(event))
+ continue;
+
+ qint64 estimatedDuration = 0;
+ // initial estimation of the event duration: 1/framerate
+ if (event.numericData1 > 0)
+ estimatedDuration = 1e9/event.numericData1;
+
+ // the profiler registers the animation events at the end of them
+ qint64 realStartTime = event.startTime - estimatedDuration;
+
+ // the duration of the events is estimated from the framerate
+ // we need to correct it before appending a new event
+ if (d->eventList.count() > 0) {
+ QmlPaintEventData *lastEvent = &d->eventList[d->eventList.count()-1];
+ if (lastEvent->startTime + lastEvent->duration >= realStartTime) {
+ // 1 nanosecond less to prevent overlap
+ lastEvent->duration = realStartTime - lastEvent->startTime - 1;
+ lastEvent->framerate = 1e9/lastEvent->duration;
+ }
+ }
+
+ QmlPaintEventData newEvent = {
+ realStartTime,
+ estimatedDuration,
+ (int)event.numericData1,
+ (int)event.numericData2
+ };
+
+ d->eventList.append(newEvent);
+
+ m_modelManager->modelProxyCountUpdated(m_modelId, d->eventList.count(), referenceList.count());
+ }
+
+ d->computeAnimationCountLimit();
+
+ qSort(d->eventList.begin(), d->eventList.end(), compareStartTimes);
+
+ m_modelManager->modelProxyCountUpdated(m_modelId, 1, 1);
+
+ emit countChanged();
+}
+
+/////////////////// QML interface
+
+bool PaintEventsModelProxy::isEmpty() const
+{
+ return count() == 0;
+}
+
+int PaintEventsModelProxy::count() const
+{
+ return d->eventList.count();
+}
+
+qint64 PaintEventsModelProxy::lastTimeMark() const
+{
+ return d->eventList.last().startTime + d->eventList.last().duration;
+}
+
+bool PaintEventsModelProxy::expanded(int ) const
+{
+ return d->expanded;
+}
+
+void PaintEventsModelProxy::setExpanded(int category, bool expanded)
+{
+ Q_UNUSED(category);
+ d->expanded = expanded;
+ emit expandedChanged();
+}
+
+int PaintEventsModelProxy::categoryDepth(int categoryIndex) const
+{
+ Q_UNUSED(categoryIndex);
+ if (isEmpty())
+ return 0;
+ else
+ return 2;
+}
+
+int PaintEventsModelProxy::categoryCount() const
+{
+ return 1;
+}
+
+const QString PaintEventsModelProxy::categoryLabel(int categoryIndex) const
+{
+ Q_UNUSED(categoryIndex);
+ return tr("Painting");
+}
+
+
+int PaintEventsModelProxy::findFirstIndex(qint64 startTime) const
+{
+ return findFirstIndexNoParents(startTime);
+}
+
+int PaintEventsModelProxy::findFirstIndexNoParents(qint64 startTime) const
+{
+ if (d->eventList.isEmpty())
+ return -1;
+ if (d->eventList.count() == 1 || d->eventList.first().startTime+d->eventList.first().duration >= startTime)
+ return 0;
+ else
+ if (d->eventList.last().startTime+d->eventList.last().duration <= startTime)
+ return -1;
+
+ int fromIndex = 0;
+ int toIndex = d->eventList.count()-1;
+ while (toIndex - fromIndex > 1) {
+ int midIndex = (fromIndex + toIndex)/2;
+ if (d->eventList[midIndex].startTime + d->eventList[midIndex].duration < startTime)
+ fromIndex = midIndex;
+ else
+ toIndex = midIndex;
+ }
+ return toIndex;
+}
+
+int PaintEventsModelProxy::findLastIndex(qint64 endTime) const
+{
+ if (d->eventList.isEmpty())
+ return -1;
+ if (d->eventList.first().startTime >= endTime)
+ return -1;
+ if (d->eventList.count() == 1)
+ return 0;
+ if (d->eventList.last().startTime <= endTime)
+ return d->eventList.count()-1;
+
+ int fromIndex = 0;
+ int toIndex = d->eventList.count()-1;
+ while (toIndex - fromIndex > 1) {
+ int midIndex = (fromIndex + toIndex)/2;
+ if (d->eventList[midIndex].startTime < endTime)
+ fromIndex = midIndex;
+ else
+ toIndex = midIndex;
+ }
+
+ return fromIndex;
+}
+
+int PaintEventsModelProxy::getEventType(int index) const
+{
+ Q_UNUSED(index);
+ return (int)QmlDebug::Painting;
+}
+
+int PaintEventsModelProxy::getEventCategory(int index) const
+{
+ Q_UNUSED(index);
+ // there is only one category, all events belong to it
+ return 0;
+}
+
+int PaintEventsModelProxy::getEventRow(int index) const
+{
+ Q_UNUSED(index);
+ return 1;
+}
+
+qint64 PaintEventsModelProxy::getDuration(int index) const
+{
+ return d->eventList[index].duration;
+}
+
+qint64 PaintEventsModelProxy::getStartTime(int index) const
+{
+ return d->eventList[index].startTime;
+}
+
+qint64 PaintEventsModelProxy::getEndTime(int index) const
+{
+ return d->eventList[index].startTime + d->eventList[index].duration;
+}
+
+int PaintEventsModelProxy::getEventId(int index) const
+{
+ // there is only one event Id for all painting events
+ Q_UNUSED(index);
+ return 0;
+}
+
+QColor PaintEventsModelProxy::getColor(int index) const
+{
+ double fpsFraction = d->eventList[index].framerate / 60.0;
+ if (fpsFraction > 1.0)
+ fpsFraction = 1.0;
+ if (fpsFraction < 0.0)
+ fpsFraction = 0.0;
+ return QColor::fromHsl((fpsFraction*96)+10, 76, 166);
+}
+
+float PaintEventsModelProxy::getHeight(int index) const
+{
+ float scale = d->maxAnimationCount - d->minAnimationCount;
+ float fraction = 1.0f;
+ if (scale > 1)
+ fraction = (float)(d->eventList[index].animationcount -
+ d->minAnimationCount) / scale;
+
+ return fraction * 0.85f + 0.15f;
+}
+
+const QVariantList PaintEventsModelProxy::getLabelsForCategory(int category) const
+{
+ Q_UNUSED(category);
+ QVariantList result;
+
+ if (!isEmpty()) {
+ QVariantMap element;
+ element.insert(QLatin1String("displayName"), QVariant(QLatin1String("Animations")));
+ element.insert(QLatin1String("description"), QVariant(QLatin1String("Animations")));
+ element.insert(QLatin1String("id"), QVariant(0));
+ result << element;
+ }
+
+ return result;
+}
+
+QString PaintEventsModelProxy::PaintEventsModelProxyPrivate::displayTime(double time)
+{
+ if (time < 1e6)
+ return QString::number(time/1e3,'f',3) + trUtf8(" \xc2\xb5s");
+ if (time < 1e9)
+ return QString::number(time/1e6,'f',3) + tr(" ms");
+
+ return QString::number(time/1e9,'f',3) + tr(" s");
+}
+
+void PaintEventsModelProxy::PaintEventsModelProxyPrivate::computeAnimationCountLimit()
+{
+ minAnimationCount = 1;
+ maxAnimationCount = 1;
+ if (eventList.isEmpty())
+ return;
+
+ for (int i=0; i < eventList.count(); i++) {
+ if (eventList[i].animationcount < minAnimationCount)
+ minAnimationCount = eventList[i].animationcount;
+ if (eventList[i].animationcount > maxAnimationCount)
+ maxAnimationCount = eventList[i].animationcount;
+ }
+}
+
+const QVariantList PaintEventsModelProxy::getEventDetails(int index) const
+{
+ QVariantList result;
+// int eventId = getEventId(index);
+
+ static const char trContext[] = "RangeDetails";
+ {
+ QVariantMap valuePair;
+ valuePair.insert(QLatin1String("title"), QVariant(categoryLabel(0)));
+ result << valuePair;
+ }
+
+ // duration
+ {
+ QVariantMap valuePair;
+ valuePair.insert(QCoreApplication::translate(trContext, "Duration:"), QVariant(d->displayTime(d->eventList[index].duration)));
+ result << valuePair;
+ }
+
+ // duration
+ {
+ QVariantMap valuePair;
+ valuePair.insert(QCoreApplication::translate(trContext, "Framerate:"), QVariant(QString::fromLatin1("%1 FPS").arg(d->eventList[index].framerate)));
+ result << valuePair;
+ }
+
+ // duration
+ {
+ QVariantMap valuePair;
+ valuePair.insert(QCoreApplication::translate(trContext, "Animations:"), QVariant(QString::fromLatin1("%1").arg(d->eventList[index].animationcount)));
+ result << valuePair;
+ }
+
+ return result;
+}
+
+const QVariantMap PaintEventsModelProxy::getEventLocation(int /*index*/) const
+{
+ QVariantMap map;
+ return map;
+}
+
+int PaintEventsModelProxy::getEventIdForHash(const QString &/*eventHash*/) const
+{
+ // paint events do not have an eventHash
+ return -1;
+}
+
+int PaintEventsModelProxy::getEventIdForLocation(const QString &/*filename*/, int /*line*/, int /*column*/) const
+{
+ // paint events do not have a defined location
+ return -1;
+}
+
+}
+}
+
diff --git a/src/plugins/qmlprofiler/qmlprofilerpainteventsmodelproxy.h b/src/plugins/qmlprofiler/qmlprofilerpainteventsmodelproxy.h
new file mode 100644
index 0000000000..4be60850ef
--- /dev/null
+++ b/src/plugins/qmlprofiler/qmlprofilerpainteventsmodelproxy.h
@@ -0,0 +1,123 @@
+/****************************************************************************
+**
+** 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 QMLPROFILERPAINTEVENTSMODELPROXY_H
+#define QMLPROFILERPAINTEVENTSMODELPROXY_H
+
+#include <QObject>
+#include "abstracttimelinemodel.h"
+#include <qmldebug/qmlprofilereventtypes.h>
+#include <qmldebug/qmlprofilereventlocation.h>
+//#include <QHash>
+//#include <QVector>
+#include <QVariantList>
+//#include <QVariantMap>
+#include "qmlprofilersimplemodel.h"
+#include <QColor>
+
+
+namespace QmlProfiler {
+class QmlProfilerModelManager;
+
+namespace Internal {
+
+class PaintEventsModelProxy : public AbstractTimelineModel
+{
+// Q_PROPERTY(bool empty READ isEmpty NOTIFY emptyChanged)
+
+ Q_OBJECT
+public:
+
+ struct QmlPaintEventData {
+ qint64 startTime;
+ qint64 duration;
+ int framerate;
+ int animationcount;
+ };
+
+ PaintEventsModelProxy(QObject *parent = 0);
+ ~PaintEventsModelProxy();
+
+
+ int categories() const;
+ QStringList categoryTitles() const;
+ QString name() const;
+
+ const QVector<QmlPaintEventData> getData() const;
+ const QVector<QmlPaintEventData> getData(qint64 fromTime, qint64 toTime) const;
+ void loadData();
+ Q_INVOKABLE int count() const;
+ void clear();
+
+ bool isEmpty() const;
+
+ Q_INVOKABLE qint64 lastTimeMark() const;
+
+ Q_INVOKABLE bool expanded(int category) const;
+ Q_INVOKABLE void setExpanded(int category, bool expanded);
+ Q_INVOKABLE int categoryDepth(int categoryIndex) const;
+ Q_INVOKABLE int categoryCount() const;
+ Q_INVOKABLE const QString categoryLabel(int categoryIndex) const;
+
+ int findFirstIndex(qint64 startTime) const;
+ int findFirstIndexNoParents(qint64 startTime) const;
+ int findLastIndex(qint64 endTime) const;
+
+ int getEventType(int index) const;
+ Q_INVOKABLE int getEventCategory(int index) const;
+ int getEventRow(int index) const;
+ Q_INVOKABLE qint64 getDuration(int index) const;
+ Q_INVOKABLE qint64 getStartTime(int index) const;
+ Q_INVOKABLE qint64 getEndTime(int index) const;
+ Q_INVOKABLE int getEventId(int index) const;
+ Q_INVOKABLE QColor getColor(int index) const;
+ Q_INVOKABLE float getHeight(int index) const;
+
+ Q_INVOKABLE const QVariantList getLabelsForCategory(int category) const;
+ Q_INVOKABLE const QVariantList getEventDetails(int index) const;
+ Q_INVOKABLE const QVariantMap getEventLocation(int index) const;
+ Q_INVOKABLE int getEventIdForHash(const QString &eventHash) const;
+ Q_INVOKABLE int getEventIdForLocation(const QString &filename, int line, int column) const;
+
+private slots:
+ bool eventAccepted(const QmlProfilerSimpleModel::QmlEventData &event) const;
+protected slots:
+ void dataChanged();
+
+private:
+ class PaintEventsModelProxyPrivate;
+ PaintEventsModelProxyPrivate *d;
+
+};
+
+}
+}
+
+#endif
diff --git a/src/plugins/qmlprofiler/qmlprofilerplugin.cpp b/src/plugins/qmlprofiler/qmlprofilerplugin.cpp
index 70e016cf09..e4fd95a5a4 100644
--- a/src/plugins/qmlprofiler/qmlprofilerplugin.cpp
+++ b/src/plugins/qmlprofiler/qmlprofilerplugin.cpp
@@ -31,36 +31,67 @@
#include "qmlprofilerruncontrolfactory.h"
#include "qmlprofilertool.h"
+#include "abstracttimelinemodel.h"
#include <analyzerbase/analyzermanager.h>
+#include <extensionsystem/pluginmanager.h>
#include <QtPlugin>
using namespace Analyzer;
-using namespace QmlProfiler::Internal;
+
+namespace QmlProfiler {
+namespace Internal {
+
+class QmlProfilerAction : public AnalyzerAction
+{
+public:
+ QmlProfilerAction() {}
+};
bool QmlProfilerPlugin::debugOutput = false;
+QmlProfilerPlugin *QmlProfilerPlugin::instance = 0;
bool QmlProfilerPlugin::initialize(const QStringList &arguments, QString *errorString)
{
Q_UNUSED(arguments)
Q_UNUSED(errorString)
- StartModes modes;
- modes.append(StartMode(StartLocal));
- modes.append(StartMode(StartRemote));
- AnalyzerManager::addTool(new QmlProfilerTool(this), modes);
+ IAnalyzerTool *tool = new QmlProfilerTool(this);
+
+ QmlProfilerAction *action = 0;
+
+ QString description = QmlProfilerTool::tr(
+ "The QML Profiler can be used to find performance bottlenecks in "
+ "applications using QML.");
+
+ action = new QmlProfilerAction;
+ action->setId("QmlProfiler.Local");
+ action->setTool(tool);
+ action->setText(tr("QML Profiler"));
+ action->setToolTip(description);
+ action->setStartMode(StartLocal);
+ action->setMenuGroup(Constants::G_ANALYZER_TOOLS);
+ AnalyzerManager::addAction(action);
+
+ action = new QmlProfilerAction;
+ action->setId("QmlProfiler.Remote");
+ action->setTool(tool);
+ action->setText(tr("QML Profiler (External)"));
+ action->setToolTip(description);
+ action->setStartMode(StartRemote);
+ action->setMenuGroup(Constants::G_ANALYZER_REMOTE_TOOLS);
+ AnalyzerManager::addAction(action);
addAutoReleasedObject(new QmlProfilerRunControlFactory());
+ QmlProfilerPlugin::instance = this;
return true;
}
void QmlProfilerPlugin::extensionsInitialized()
{
- // Retrieve objects from the plugin manager's object pool.
- // "In the extensionsInitialized method, a plugin can be sure that all
- // plugins that depend on it are completely initialized."
+ timelineModels = ExtensionSystem::PluginManager::getObjects<AbstractTimelineModel>();
}
ExtensionSystem::IPlugin::ShutdownFlag QmlProfilerPlugin::aboutToShutdown()
@@ -71,5 +102,12 @@ ExtensionSystem::IPlugin::ShutdownFlag QmlProfilerPlugin::aboutToShutdown()
return SynchronousShutdown;
}
-Q_EXPORT_PLUGIN(QmlProfilerPlugin)
+QList<AbstractTimelineModel *> QmlProfilerPlugin::getModels() const
+{
+ return timelineModels;
+}
+
+} // namespace Internal
+} // namespace QmlProfiler
+Q_EXPORT_PLUGIN(QmlProfiler::Internal::QmlProfilerPlugin)
diff --git a/src/plugins/qmlprofiler/qmlprofilerplugin.h b/src/plugins/qmlprofiler/qmlprofilerplugin.h
index aa8d15d730..0550fa1eec 100644
--- a/src/plugins/qmlprofiler/qmlprofilerplugin.h
+++ b/src/plugins/qmlprofiler/qmlprofilerplugin.h
@@ -34,6 +34,8 @@
#include <extensionsystem/iplugin.h>
+#include "abstracttimelinemodel.h"
+
namespace QmlProfiler {
namespace Internal {
@@ -50,6 +52,14 @@ public:
ShutdownFlag aboutToShutdown();
static bool debugOutput;
+ static QmlProfilerPlugin *instance;
+
+ QList<AbstractTimelineModel *> getModels() const;
+
+private:
+ QList<AbstractTimelineModel*> timelineModels;
+
+
};
} // namespace Internal
diff --git a/src/plugins/qmlprofiler/qmlprofilerprocessedmodel.cpp b/src/plugins/qmlprofiler/qmlprofilerprocessedmodel.cpp
new file mode 100644
index 0000000000..2e4331f735
--- /dev/null
+++ b/src/plugins/qmlprofiler/qmlprofilerprocessedmodel.cpp
@@ -0,0 +1,182 @@
+/****************************************************************************
+**
+** 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 "qmlprofilerprocessedmodel.h"
+#include <qmldebug/qmlprofilereventtypes.h>
+#include <utils/qtcassert.h>
+#include <QUrl>
+#include <QDebug>
+
+namespace QmlProfiler {
+namespace Internal {
+
+QmlDebug::QmlEventLocation getLocation(const QmlProfilerSimpleModel::QmlEventData &event);
+QString getDisplayName(const QmlProfilerSimpleModel::QmlEventData &event);
+QString getInitialDetails(const QmlProfilerSimpleModel::QmlEventData &event);
+
+QmlDebug::QmlEventLocation getLocation(const QmlProfilerSimpleModel::QmlEventData &event)
+{
+ QmlDebug::QmlEventLocation eventLocation = event.location;
+ if ((event.eventType == QmlDebug::Creating || event.eventType == QmlDebug::Compiling)
+ && eventLocation.filename.isEmpty()) {
+ eventLocation.filename = getInitialDetails(event);
+ eventLocation.line = 1;
+ eventLocation.column = 1;
+ }
+ return eventLocation;
+}
+
+QString getDisplayName(const QmlProfilerSimpleModel::QmlEventData &event)
+{
+ const QmlDebug::QmlEventLocation eventLocation = getLocation(event);
+ QString displayName;
+
+ // generate hash
+ if (eventLocation.filename.isEmpty()) {
+ displayName = QmlProfilerProcessedModel::tr("<bytecode>");
+ } else {
+ const QString filePath = QUrl(eventLocation.filename).path();
+ displayName = filePath.mid(filePath.lastIndexOf(QLatin1Char('/')) + 1) + QLatin1Char(':') +
+ QString::number(eventLocation.line);
+ }
+
+ return displayName;
+}
+
+QString getInitialDetails(const QmlProfilerSimpleModel::QmlEventData &event)
+{
+ QString details;
+ // generate details string
+ if (event.data.isEmpty())
+ details = QmlProfilerProcessedModel::tr("Source code not available.");
+ else {
+ details = event.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) + QLatin1String(": ") + rewrite.cap(3);
+ if (details.startsWith(QLatin1String("file://")))
+ details = details.mid(details.lastIndexOf(QLatin1Char('/')) + 1);
+ }
+
+ return details;
+}
+
+
+bool compareStartTimes(const QmlProfilerSimpleModel::QmlEventData &t1, const QmlProfilerSimpleModel::QmlEventData &t2)
+{
+ return t1.startTime < t2.startTime;
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+QmlProfilerProcessedModel::QmlProfilerProcessedModel(Utils::FileInProjectFinder *fileFinder, QObject *parent)
+ : QmlProfilerSimpleModel(parent)
+ , m_detailsRewriter(new QmlProfilerDetailsRewriter(this, fileFinder))
+ , m_emitChanged(false)
+{
+ connect(m_detailsRewriter, SIGNAL(rewriteDetailsString(int,QString)),
+ this, SLOT(detailsChanged(int,QString)));
+ connect(m_detailsRewriter, SIGNAL(eventDetailsChanged()),
+ this, SLOT(detailsDone()));
+}
+
+QmlProfilerProcessedModel::~QmlProfilerProcessedModel()
+{
+}
+
+void QmlProfilerProcessedModel::clear()
+{
+ m_detailsRewriter->clearRequests();
+ QmlProfilerSimpleModel::clear();
+
+ emit changed();
+ m_emitChanged = false;
+}
+
+void QmlProfilerProcessedModel::complete()
+{
+ // post-processing
+
+ // sort events by start time
+ qSort(eventList.begin(), eventList.end(), compareStartTimes);
+
+ // rewrite strings
+ int n = eventList.count();
+ for (int i = 0; i < n; i++) {
+ QmlEventData *event = &eventList[i];
+ event->location = getLocation(*event);
+ event->displayName = getDisplayName(*event);
+ event->data = QStringList() << getInitialDetails(*event);
+
+ //
+ // request further details from files
+ //
+
+ if (event->eventType != QmlDebug::Binding && event->eventType != QmlDebug::HandlingSignal)
+ continue;
+
+ // This skips anonymous bindings in Qt4.8 (we don't have valid location data for them)
+ if (event->location.filename.isEmpty())
+ continue;
+
+ // Skip non-anonymous bindings from Qt4.8 (we already have correct details for them)
+ if (event->location.column == -1)
+ continue;
+
+ m_detailsRewriter->requestDetailsForLocation(i, event->location);
+ }
+
+ m_detailsRewriter->reloadDocuments();
+
+ QmlProfilerSimpleModel::complete();
+ emit changed();
+ m_emitChanged = false;
+}
+
+void QmlProfilerProcessedModel::detailsChanged(int requestId, const QString &newString)
+{
+ QTC_ASSERT(requestId < eventList.count(), return);
+
+ QmlEventData *event = &eventList[requestId];
+ event->data = QStringList(newString);
+
+ m_emitChanged = true;
+}
+
+void QmlProfilerProcessedModel::detailsDone()
+{
+ if (m_emitChanged) {
+ emit changed();
+ m_emitChanged = false;
+ }
+}
+
+}
+}
diff --git a/src/plugins/analyzerbase/analyzeroptionspage.h b/src/plugins/qmlprofiler/qmlprofilerprocessedmodel.h
index e001148795..4c293711f2 100644
--- a/src/plugins/analyzerbase/analyzeroptionspage.h
+++ b/src/plugins/qmlprofiler/qmlprofilerprocessedmodel.h
@@ -2,7 +2,6 @@
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
-** Author: Nicolas Arnaud-Cormos, KDAB (nicolas.arnaud-cormos@kdab.com)
**
** This file is part of Qt Creator.
**
@@ -28,33 +27,36 @@
**
****************************************************************************/
-#ifndef ANALYZER_INTERNAL_ANALYZEROPTIONSPAGE_H
-#define ANALYZER_INTERNAL_ANALYZEROPTIONSPAGE_H
+#ifndef QMLPROFILERPROCESSEDMODEL_H
+#define QMLPROFILERPROCESSEDMODEL_H
-#include <coreplugin/dialogs/ioptionspage.h>
-
-namespace Analyzer {
-
-class AbstractAnalyzerSubConfig;
+#include "qmlprofilersimplemodel.h"
+#include "qmlprofilerdetailsrewriter.h"
+namespace QmlProfiler {
namespace Internal {
-class AnalyzerOptionsPage : public Core::IOptionsPage
+class QmlProfilerProcessedModel : public QmlProfilerSimpleModel
{
Q_OBJECT
public:
- explicit AnalyzerOptionsPage(AbstractAnalyzerSubConfig *config, QObject *parent = 0);
+ explicit QmlProfilerProcessedModel(Utils::FileInProjectFinder *fileFinder, QObject *parent = 0);
+ ~QmlProfilerProcessedModel();
+
+ virtual void clear();
+ virtual void complete();
- QWidget *createPage(QWidget *parent);
- void apply();
- void finish();
+private slots:
+ void detailsChanged(int requestId, const QString &newString);
+ void detailsDone();
private:
- AbstractAnalyzerSubConfig *m_config;
+ QmlProfilerDetailsRewriter *m_detailsRewriter;
+ bool m_emitChanged;
};
-} // namespace Internal
-} // namespace Analyzer
+}
+}
-#endif // ANALYZER_INTERNAL_ANALYZEROPTIONSPAGE_H
+#endif
diff --git a/src/plugins/qmlprofiler/qmlprofilerruncontrolfactory.cpp b/src/plugins/qmlprofiler/qmlprofilerruncontrolfactory.cpp
index 6e3ab3ff6a..6c139e8746 100644
--- a/src/plugins/qmlprofiler/qmlprofilerruncontrolfactory.cpp
+++ b/src/plugins/qmlprofiler/qmlprofilerruncontrolfactory.cpp
@@ -35,13 +35,23 @@
#include <analyzerbase/analyzermanager.h>
#include <analyzerbase/analyzerstartparameters.h>
#include <analyzerbase/analyzerruncontrol.h>
-#include <analyzerbase/analyzersettings.h>
+#include <debugger/debuggerrunconfigurationaspect.h>
+
+#include <projectexplorer/environmentaspect.h>
#include <projectexplorer/kitinformation.h>
+#include <projectexplorer/localapplicationrunconfiguration.h>
+#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/project.h>
+#include <projectexplorer/session.h>
#include <projectexplorer/target.h>
+#include <qmlprojectmanager/qmlprojectrunconfiguration.h>
+
#include <utils/qtcassert.h>
+#include <QTcpServer>
+
using namespace Analyzer;
using namespace ProjectExplorer;
@@ -55,35 +65,65 @@ QmlProfilerRunControlFactory::QmlProfilerRunControlFactory(QObject *parent) :
bool QmlProfilerRunControlFactory::canRun(RunConfiguration *runConfiguration, RunMode mode) const
{
- if (mode != QmlProfilerRunMode)
- return false;
- IAnalyzerTool *tool = AnalyzerManager::toolFromRunMode(mode);
- if (tool)
- return tool->canRun(runConfiguration, mode);
- return false;
+ return mode == QmlProfilerRunMode
+ && (qobject_cast<QmlProjectManager::QmlProjectRunConfiguration *>(runConfiguration)
+ || qobject_cast<LocalApplicationRunConfiguration *>(runConfiguration));
}
-RunControl *QmlProfilerRunControlFactory::create(RunConfiguration *runConfiguration, RunMode mode, QString *errorMessage)
+static AnalyzerStartParameters createQmlProfilerStartParameters(RunConfiguration *runConfiguration)
{
- IAnalyzerTool *tool = AnalyzerManager::toolFromRunMode(mode);
- if (!tool) {
- if (errorMessage)
- *errorMessage = tr("No analyzer tool selected"); // never happens
- return 0;
+ AnalyzerStartParameters sp;
+ EnvironmentAspect *environment = runConfiguration->extraAspect<EnvironmentAspect>();
+
+ // FIXME: This is only used to communicate the connParams settings.
+ if (QmlProjectManager::QmlProjectRunConfiguration *rc1 =
+ qobject_cast<QmlProjectManager::QmlProjectRunConfiguration *>(runConfiguration)) {
+ // This is a "plain" .qmlproject.
+ if (environment)
+ sp.environment = environment->environment();
+ sp.workingDirectory = rc1->workingDirectory();
+ sp.debuggee = rc1->observerPath();
+ sp.debuggeeArgs = rc1->viewerArguments();
+ sp.displayName = rc1->displayName();
+ } else if (LocalApplicationRunConfiguration *rc2 =
+ qobject_cast<LocalApplicationRunConfiguration *>(runConfiguration)) {
+ if (environment)
+ sp.environment = environment->environment();
+ sp.workingDirectory = rc2->workingDirectory();
+ sp.debuggee = rc2->executable();
+ sp.debuggeeArgs = rc2->commandLineArguments();
+ sp.displayName = rc2->displayName();
+ } else {
+ // What could that be?
+ QTC_ASSERT(false, return sp);
+ }
+ const IDevice::ConstPtr device = DeviceKitInformation::device(runConfiguration->target()->kit());
+ if (device->type() == ProjectExplorer::Constants::DESKTOP_DEVICE_TYPE) {
+ QTcpServer server;
+ if (!server.listen(QHostAddress::LocalHost) && !server.listen(QHostAddress::LocalHostIPv6)) {
+ qWarning() << "Cannot open port on host for QML profiling.";
+ return sp;
+ }
+ sp.analyzerHost = server.serverAddress().toString();
+ sp.analyzerPort = server.serverPort();
}
+ sp.startMode = StartLocal;
+ return sp;
+}
+RunControl *QmlProfilerRunControlFactory::create(RunConfiguration *runConfiguration, RunMode mode, QString *errorMessage)
+{
QTC_ASSERT(canRun(runConfiguration, mode), return 0);
- AnalyzerStartParameters sp = tool->createStartParameters(runConfiguration, mode);
- sp.toolId = tool->id();
+ AnalyzerStartParameters sp = createQmlProfilerStartParameters(runConfiguration);
+ sp.runMode = mode;
// only desktop device is supported
- const ProjectExplorer::IDevice::ConstPtr device =
- ProjectExplorer::DeviceKitInformation::device(runConfiguration->target()->kit());
+ const IDevice::ConstPtr device = DeviceKitInformation::device(runConfiguration->target()->kit());
QTC_ASSERT(device->type() == ProjectExplorer::Constants::DESKTOP_DEVICE_TYPE, return 0);
- AnalyzerRunControl *rc = new AnalyzerRunControl(tool, sp, runConfiguration);
- QmlProfilerEngine *engine = qobject_cast<QmlProfilerEngine *>(rc->engine());
+ AnalyzerRunControl *rc = AnalyzerManager::createRunControl(sp, runConfiguration);
+ QmlProfilerRunControl *engine = qobject_cast<QmlProfilerRunControl *>(rc);
if (!engine) {
delete rc;
return 0;
@@ -94,7 +134,7 @@ RunControl *QmlProfilerRunControlFactory::create(RunConfiguration *runConfigurat
connect(runner, SIGNAL(stopped()), engine, SLOT(notifyRemoteFinished()));
connect(runner, SIGNAL(appendMessage(QString,Utils::OutputFormat)),
engine, SLOT(logApplicationMessage(QString,Utils::OutputFormat)));
- connect(engine, SIGNAL(starting(const Analyzer::IAnalyzerEngine*)), runner,
+ connect(engine, SIGNAL(starting(const Analyzer::AnalyzerRunControl*)), runner,
SLOT(start()));
connect(rc, SIGNAL(finished()), runner, SLOT(stop()));
return rc;
diff --git a/src/plugins/qmlprofiler/qmlprofilersimplemodel.cpp b/src/plugins/qmlprofiler/qmlprofilersimplemodel.cpp
new file mode 100644
index 0000000000..0ab64ae572
--- /dev/null
+++ b/src/plugins/qmlprofiler/qmlprofilersimplemodel.cpp
@@ -0,0 +1,117 @@
+/****************************************************************************
+**
+** 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 "qmlprofilersimplemodel.h"
+
+#include "qmlprofilermodelmanager.h"
+
+#include <qmldebug/qmlprofilereventtypes.h>
+
+#include <QStringList>
+#include <QVector>
+#include <QDebug>
+
+namespace QmlProfiler {
+
+QmlProfilerSimpleModel::QmlProfilerSimpleModel(QObject *parent)
+ : QObject(parent)
+{
+ m_modelManager = qobject_cast<QmlProfilerModelManager *>(parent);
+ Q_ASSERT(m_modelManager);
+ m_modelId = m_modelManager->registerModelProxy();
+}
+
+QmlProfilerSimpleModel::~QmlProfilerSimpleModel()
+{
+}
+
+void QmlProfilerSimpleModel::clear()
+{
+ m_modelManager->modelProxyCountUpdated(m_modelId, 0, 1);
+ eventList.clear();
+ emit changed();
+}
+
+bool QmlProfilerSimpleModel::isEmpty() const
+{
+ return eventList.isEmpty();
+}
+
+const QVector<QmlProfilerSimpleModel::QmlEventData> &QmlProfilerSimpleModel::getEvents() const
+{
+ return eventList;
+}
+
+int QmlProfilerSimpleModel::count() const
+{
+ return eventList.count();
+}
+
+void QmlProfilerSimpleModel::addQmlEvent(int type, int bindingType, qint64 startTime, qint64 duration, const QStringList &data, const QmlDebug::QmlEventLocation &location, qint64 ndata1, qint64 ndata2, qint64 ndata3, qint64 ndata4, qint64 ndata5)
+{
+ QString displayName;
+ if (type == QmlDebug::Painting && bindingType == QmlDebug::AnimationFrame) {
+ displayName = tr("Animations");
+ } else {
+ displayName = QString::fromLatin1("%1:%2").arg(
+ location.filename,
+ QString::number(location.line));
+ }
+
+ QmlEventData eventData = {displayName, type, bindingType, startTime, duration, data, location, ndata1, ndata2, ndata3, ndata4, ndata5};
+ eventList.append(eventData);
+
+ m_modelManager->modelProxyCountUpdated(m_modelId, startTime, m_modelManager->estimatedProfilingTime());
+}
+
+qint64 QmlProfilerSimpleModel::lastTimeMark() const
+{
+ if (eventList.isEmpty())
+ return 0;
+
+ return eventList.last().startTime + eventList.last().duration;
+}
+
+void QmlProfilerSimpleModel::complete()
+{
+ m_modelManager->modelProxyCountUpdated(m_modelId, 1, 1);
+ emit changed();
+}
+
+QString QmlProfilerSimpleModel::getHashString(const QmlProfilerSimpleModel::QmlEventData &event)
+{
+ return QString::fromLatin1("%1:%2:%3:%4:%5").arg(
+ event.location.filename,
+ QString::number(event.location.line),
+ QString::number(event.location.column),
+ QString::number(event.eventType),
+ QString::number(event.bindingType));
+}
+
+}
diff --git a/src/plugins/coreplugin/scriptmanager/scriptmanager.h b/src/plugins/qmlprofiler/qmlprofilersimplemodel.h
index 284b57b42a..4551cec283 100644
--- a/src/plugins/coreplugin/scriptmanager/scriptmanager.h
+++ b/src/plugins/qmlprofiler/qmlprofilersimplemodel.h
@@ -27,51 +27,64 @@
**
****************************************************************************/
-#ifndef SCRIPTMANAGER_H
-#define SCRIPTMANAGER_H
+#ifndef QMLPROFILERSIMPLEMODEL_H
+#define QMLPROFILERSIMPLEMODEL_H
-#include <coreplugin/core_global.h>
+#include "qmlprofiler_global.h"
-#include <QObject>
-#include <QString>
-#include <QSharedPointer>
+#include <qmldebug/qmlprofilereventlocation.h>
-QT_BEGIN_NAMESPACE
-class QScriptEngine;
-QT_END_NAMESPACE
+#include <QObject>
+#include <QVector>
+#include <QStringList>
-namespace Core {
+namespace QmlProfiler {
-/* Script Manager.
- * Provides a script engine that is initialized with
- * Qt Creator's interfaces and allows for running scripts.
- * @{todo} Should it actually manage script files, too? */
+class QmlProfilerModelManager;
-class CORE_EXPORT ScriptManager : public QObject
+// stores the data from the client as-is
+class QMLPROFILER_EXPORT QmlProfilerSimpleModel : public QObject
{
Q_OBJECT
public:
- typedef QSharedPointer<QScriptEngine> QScriptEnginePtr;
-
- // A stack frame as returned by a failed invocation (exception)
- // fileName may be empty. lineNumber can be 0 for the top frame (goof-up?).
- struct StackFrame {
- QString function;
- QString fileName;
- int lineNumber;
+ struct QmlEventData {
+ QString displayName;
+ int eventType;
+ int bindingType;
+ qint64 startTime;
+ qint64 duration;
+ QStringList data;
+ QmlDebug::QmlEventLocation location;
+ qint64 numericData1;
+ qint64 numericData2;
+ qint64 numericData3;
+ qint64 numericData4;
+ qint64 numericData5;
};
- typedef QList<StackFrame> Stack;
- ScriptManager(QObject *parent = 0) : QObject(parent) {}
- virtual ~ScriptManager() { }
+ explicit QmlProfilerSimpleModel(QObject *parent = 0);
+ ~QmlProfilerSimpleModel();
+
+ virtual void clear();
+ bool isEmpty() const;
+ const QVector<QmlEventData> &getEvents() const;
+ int count() const;
+ void addQmlEvent(int type, int bindingType, qint64 startTime, qint64 duration, const QStringList &data, const QmlDebug::QmlEventLocation &location,
+ qint64 ndata1, qint64 ndata2, qint64 ndata3, qint64 ndata4, qint64 ndata5);
+ qint64 lastTimeMark() const;
+ virtual void complete();
+
+ static QString getHashString(const QmlProfilerSimpleModel::QmlEventData &event);
- // Run a script
- virtual bool runScript(const QString &script, QString *errorMessage, Stack *errorStack) = 0;
- virtual bool runScript(const QString &script, QString *errorMessage) = 0;
+signals:
+ void changed();
- virtual QScriptEnginePtr scriptEngine() = 0;
+protected:
+ QVector<QmlEventData> eventList;
+ QmlProfilerModelManager *m_modelManager;
+ int m_modelId;
};
-} // namespace Core
+}
-#endif // SCRIPTMANAGER_H
+#endif
diff --git a/src/plugins/qmlprofiler/qmlprofilerstatewidget.cpp b/src/plugins/qmlprofiler/qmlprofilerstatewidget.cpp
index cf46cbeeb1..193f4f7569 100644
--- a/src/plugins/qmlprofiler/qmlprofilerstatewidget.cpp
+++ b/src/plugins/qmlprofiler/qmlprofilerstatewidget.cpp
@@ -35,6 +35,7 @@
#include <QLabel>
#include <QProgressBar>
#include <QTime>
+#include <QDebug>
namespace QmlProfiler {
namespace Internal {
@@ -49,7 +50,7 @@ class QmlProfilerStateWidget::QmlProfilerStateWidgetPrivate
QPixmap shadowPic;
QmlProfilerStateManager *m_profilerState;
- QmlProfilerDataModel *m_profilerDataModel;
+ QmlProfilerModelManager *m_modelManager;
bool isRecording;
bool appKilled;
@@ -60,11 +61,9 @@ class QmlProfilerStateWidget::QmlProfilerStateWidgetPrivate
qint64 estimatedProfilingTime;
};
-
-
QmlProfilerStateWidget::QmlProfilerStateWidget(QmlProfilerStateManager *stateManager,
- QmlProfilerDataModel *dataModel, QWidget *parent) :
- QWidget(parent), d(new QmlProfilerStateWidgetPrivate(this))
+ QmlProfilerModelManager *modelManager, QWidget *parent)
+ : QWidget(parent), d(new QmlProfilerStateWidgetPrivate(this))
{
setObjectName(QLatin1String("QML Profiler State Display"));
@@ -80,6 +79,7 @@ QmlProfilerStateWidget::QmlProfilerStateWidget(QmlProfilerStateManager *stateMan
d->progressBar = new QProgressBar(this);
layout->addWidget(d->progressBar);
+ d->progressBar->setMaximum(1000);
d->progressBar->setVisible(false);
setLayout(layout);
@@ -92,9 +92,11 @@ QmlProfilerStateWidget::QmlProfilerStateWidget(QmlProfilerStateManager *stateMan
d->emptyList = true;
// profiler state
- d->m_profilerDataModel = dataModel;
- connect(d->m_profilerDataModel,SIGNAL(stateChanged()), this, SLOT(dataStateChanged()));
- connect(d->m_profilerDataModel,SIGNAL(countChanged()), this, SLOT(dataStateChanged()));
+ d->m_modelManager = modelManager;
+ connect(d->m_modelManager,SIGNAL(stateChanged()), this, SLOT(dataStateChanged()));
+ connect(d->m_modelManager,SIGNAL(countChanged()), this, SLOT(dataStateChanged()));
+ connect(d->m_modelManager,SIGNAL(progressChanged()), this, SLOT(dataStateChanged()));
+ connect(this, SIGNAL(newTimeEstimation(qint64)), d->m_modelManager, SLOT(newTimeEstimation(qint64)));
d->m_profilerState = stateManager;
connect(d->m_profilerState,SIGNAL(stateChanged()), this, SLOT(profilerStateChanged()));
connect(d->m_profilerState, SIGNAL(serverRecordingChanged()),
@@ -196,9 +198,9 @@ void QmlProfilerStateWidget::updateDisplay()
if (d->isRecording) {
d->isRecording = false;
d->estimatedProfilingTime = d->profilingTimer.elapsed();
+ emit newTimeEstimation(d->estimatedProfilingTime);
}
- d->progressBar->setMaximum(d->estimatedProfilingTime);
- d->progressBar->setValue(d->m_profilerDataModel->lastTimeMark() * 1e-6);
+ d->progressBar->setValue(d->m_modelManager->progress() * 1000);
d->progressBar->setVisible(true);
resize(300,70);
reposition();
@@ -232,9 +234,9 @@ void QmlProfilerStateWidget::updateDisplay()
if (d->isRecording) {
d->isRecording = false;
d->estimatedProfilingTime = d->profilingTimer.elapsed();
+ emit newTimeEstimation(d->estimatedProfilingTime);
}
- d->progressBar->setMaximum(d->estimatedProfilingTime);
- d->progressBar->setValue(d->m_profilerDataModel->lastTimeMark() * 1e-6);
+ d->progressBar->setValue(d->m_modelManager->progress() * 1000);
d->progressBar->setVisible(true);
resize(300,70);
reposition();
@@ -252,15 +254,17 @@ void QmlProfilerStateWidget::updateDisplay()
// }
// There is a trace on view, hide this dialog
+ d->progressBar->setVisible(false);
setVisible(false);
}
void QmlProfilerStateWidget::dataStateChanged()
{
- d->loadingDone = d->m_profilerDataModel->currentState() == QmlProfilerDataModel::Done ||
- d->m_profilerDataModel->currentState() == QmlProfilerDataModel::Empty;
- d->traceAvailable = d->m_profilerDataModel->traceDuration() > 0;
- d->emptyList = d->m_profilerDataModel->count() == 0;
+ // consider possible rounding errors
+ d->loadingDone = d->m_modelManager->progress() >= 0.99 ||
+ d->m_modelManager->state() == QmlProfilerDataState::Empty;
+ d->traceAvailable = d->m_modelManager->traceTime()->duration() > 0;
+ d->emptyList = d->m_modelManager->isEmpty() || d->m_modelManager->progress() == 0;
updateDisplay();
}
@@ -275,8 +279,11 @@ void QmlProfilerStateWidget::profilerStateChanged()
d->isRecording = d->m_profilerState->serverRecording();
if (d->isRecording)
d->profilingTimer.start();
- else
- d->estimatedProfilingTime = d->profilingTimer.elapsed();
+ else {
+ // estimated time in ns
+ d->estimatedProfilingTime = d->profilingTimer.elapsed() * 1e6;
+ emit newTimeEstimation(d->estimatedProfilingTime);
+ }
updateDisplay();
}
diff --git a/src/plugins/qmlprofiler/qmlprofilerstatewidget.h b/src/plugins/qmlprofiler/qmlprofilerstatewidget.h
index 57c27f78de..bf32aa2b47 100644
--- a/src/plugins/qmlprofiler/qmlprofilerstatewidget.h
+++ b/src/plugins/qmlprofiler/qmlprofilerstatewidget.h
@@ -33,7 +33,7 @@
#include <QWidget>
#include "qmlprofilerstatemanager.h"
-#include "qmlprofilerdatamodel.h"
+#include "qmlprofilermodelmanager.h"
namespace QmlProfiler {
namespace Internal {
@@ -43,7 +43,7 @@ class QmlProfilerStateWidget : public QWidget
Q_OBJECT
public:
explicit QmlProfilerStateWidget(QmlProfilerStateManager *stateManager,
- QmlProfilerDataModel *dataModel, QWidget *parent = 0);
+ QmlProfilerModelManager *modelManager, QWidget *parent = 0);
~QmlProfilerStateWidget();
private slots:
@@ -52,6 +52,9 @@ private slots:
void profilerStateChanged();
void reposition();
+signals:
+ void newTimeEstimation(qint64);
+
protected:
void paintEvent(QPaintEvent *event);
diff --git a/src/plugins/qmlprofiler/qmlprofilertimelinemodelproxy.cpp b/src/plugins/qmlprofiler/qmlprofilertimelinemodelproxy.cpp
new file mode 100644
index 0000000000..e6a280aadd
--- /dev/null
+++ b/src/plugins/qmlprofiler/qmlprofilertimelinemodelproxy.cpp
@@ -0,0 +1,721 @@
+/****************************************************************************
+**
+** 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 "qmlprofilertimelinemodelproxy.h"
+#include "qmlprofilermodelmanager.h"
+#include "qmlprofilersimplemodel.h"
+
+#include <QCoreApplication>
+#include <QVector>
+#include <QHash>
+#include <QUrl>
+#include <QString>
+#include <QStack>
+
+#include <QDebug>
+
+namespace QmlProfiler {
+namespace Internal {
+
+struct CategorySpan {
+ bool expanded;
+ int expandedRows;
+ int contractedRows;
+ int rowStart;
+ bool empty;
+};
+
+class BasicTimelineModel::BasicTimelineModelPrivate
+{
+public:
+ BasicTimelineModelPrivate(BasicTimelineModel *qq) : q(qq) {}
+ ~BasicTimelineModelPrivate() {}
+
+ // convenience functions
+ void prepare();
+ void computeNestingContracted();
+ void computeExpandedLevels();
+ void buildEndTimeList();
+ void findBindingLoops();
+ void computeRowStarts();
+
+ QString displayTime(double time);
+
+ QVector <BasicTimelineModel::QmlRangeEventData> eventDict;
+ QVector <QString> eventHashes;
+ QVector <BasicTimelineModel::QmlRangeEventStartInstance> startTimeData;
+ QVector <BasicTimelineModel::QmlRangeEventEndInstance> endTimeData;
+ QVector <CategorySpan> categorySpan;
+
+ BasicTimelineModel *q;
+};
+
+BasicTimelineModel::BasicTimelineModel(QObject *parent)
+ : AbstractTimelineModel(parent), d(new BasicTimelineModelPrivate(this))
+{
+}
+
+BasicTimelineModel::~BasicTimelineModel()
+{
+ delete d;
+}
+
+int BasicTimelineModel::categories() const
+{
+ return categoryCount();
+}
+
+QStringList BasicTimelineModel::categoryTitles() const
+{
+ QStringList retString;
+ for (int i=0; i<categories(); i++)
+ retString << categoryLabel(i);
+ return retString;
+}
+
+QString BasicTimelineModel::name() const
+{
+ return QLatin1String("BasicTimelineModel");
+}
+
+const QVector<BasicTimelineModel::QmlRangeEventStartInstance> BasicTimelineModel::getData() const
+{
+ return d->startTimeData;
+}
+
+const QVector<BasicTimelineModel::QmlRangeEventStartInstance> BasicTimelineModel::getData(qint64 fromTime, qint64 toTime) const
+{
+ int fromIndex = findFirstIndex(fromTime);
+ int toIndex = findLastIndex(toTime);
+ if (fromIndex != -1 && toIndex > fromIndex)
+ return d->startTimeData.mid(fromIndex, toIndex - fromIndex + 1);
+ else
+ return QVector<BasicTimelineModel::QmlRangeEventStartInstance>();
+}
+
+void BasicTimelineModel::clear()
+{
+ d->eventDict.clear();
+ d->eventHashes.clear();
+ d->startTimeData.clear();
+ d->endTimeData.clear();
+ d->categorySpan.clear();
+
+ m_modelManager->modelProxyCountUpdated(m_modelId, 0, 1);
+}
+
+void BasicTimelineModel::dataChanged()
+{
+ if (m_modelManager->state() == QmlProfilerDataState::ProcessingData)
+ loadData();
+
+ if (m_modelManager->state() == QmlProfilerDataState::Empty)
+ clear();
+
+ emit stateChanged();
+ emit dataAvailable();
+ emit emptyChanged();
+ emit expandedChanged();
+}
+
+void BasicTimelineModel::BasicTimelineModelPrivate::prepare()
+{
+ categorySpan.clear();
+ for (int i = 0; i < QmlDebug::MaximumQmlEventType; i++) {
+ CategorySpan newCategory = {false, 1, 1, i, true};
+ categorySpan << newCategory;
+ }
+}
+
+bool compareStartTimes(const BasicTimelineModel::QmlRangeEventStartInstance&t1, const BasicTimelineModel::QmlRangeEventStartInstance &t2)
+{
+ return t1.startTime < t2.startTime;
+}
+
+bool compareEndTimes(const BasicTimelineModel::QmlRangeEventEndInstance &t1, const BasicTimelineModel::QmlRangeEventEndInstance &t2)
+{
+ return t1.endTime < t2.endTime;
+}
+
+bool BasicTimelineModel::eventAccepted(const QmlProfilerSimpleModel::QmlEventData &event) const
+{
+ // only accept Qt4.x Painting events
+ if (event.eventType == QmlDebug::Painting)
+ return event.bindingType == QmlDebug::QPainterEvent;
+
+ return (event.eventType <= QmlDebug::HandlingSignal);
+}
+
+void BasicTimelineModel::loadData()
+{
+ clear();
+ QmlProfilerSimpleModel *simpleModel = m_modelManager->simpleModel();
+ if (simpleModel->isEmpty())
+ return;
+
+ int lastEventId = 0;
+
+ d->prepare();
+
+ // collect events
+ const QVector<QmlProfilerSimpleModel::QmlEventData> eventList = simpleModel->getEvents();
+ foreach (const QmlProfilerSimpleModel::QmlEventData &event, eventList) {
+ if (!eventAccepted(event))
+ continue;
+
+ QString eventHash = QmlProfilerSimpleModel::getHashString(event);
+
+ // store in dictionary
+ if (!d->eventHashes.contains(eventHash)) {
+ QmlRangeEventData rangeEventData = {
+ event.displayName,
+ event.data.join(QLatin1String(" ")),
+ event.location,
+ (QmlDebug::QmlEventType)event.eventType,
+ lastEventId++ // event id
+ };
+ d->eventDict << rangeEventData;
+ d->eventHashes << eventHash;
+ }
+
+ // store starttime-based instance
+ QmlRangeEventStartInstance eventStartInstance = {
+ event.startTime,
+ event.duration,
+ d->eventHashes.indexOf(eventHash), // event id
+ QmlDebug::Constants::QML_MIN_LEVEL, // displayRowExpanded;
+ QmlDebug::Constants::QML_MIN_LEVEL, // displayRowCollapsed;
+ 1,
+ -1 // bindingLoopHead
+ };
+ d->startTimeData.append(eventStartInstance);
+
+ m_modelManager->modelProxyCountUpdated(m_modelId, d->startTimeData.count(), eventList.count() * 7);
+ }
+
+ qSort(d->startTimeData.begin(), d->startTimeData.end(), compareStartTimes);
+
+ m_modelManager->modelProxyCountUpdated(m_modelId, 2, 7);
+
+ // compute nestingLevel - nonexpanded
+ d->computeNestingContracted();
+
+ m_modelManager->modelProxyCountUpdated(m_modelId, 3, 7);
+
+ // compute nestingLevel - expanded
+ d->computeExpandedLevels();
+
+ m_modelManager->modelProxyCountUpdated(m_modelId, 4, 7);
+
+ // populate endtimelist
+ d->buildEndTimeList();
+
+ m_modelManager->modelProxyCountUpdated(m_modelId, 5, 7);
+
+ d->findBindingLoops();
+
+ m_modelManager->modelProxyCountUpdated(m_modelId, 6, 7);
+
+ d->computeRowStarts();
+
+ m_modelManager->modelProxyCountUpdated(m_modelId, 1, 1);
+
+ emit countChanged();
+}
+
+void BasicTimelineModel::BasicTimelineModelPrivate::computeNestingContracted()
+{
+ int i;
+ int eventCount = startTimeData.count();
+
+ QHash<int, qint64> endtimesPerLevel;
+ QList<int> nestingLevels;
+ QList< QHash<int, qint64> > endtimesPerNestingLevel;
+ int level = QmlDebug::Constants::QML_MIN_LEVEL;
+ endtimesPerLevel[QmlDebug::Constants::QML_MIN_LEVEL] = 0;
+ int lastBaseEventIndex = 0;
+ qint64 lastBaseEventEndTime = q->m_modelManager->traceTime()->startTime();
+
+ for (i = 0; i < QmlDebug::MaximumQmlEventType; i++) {
+ nestingLevels << QmlDebug::Constants::QML_MIN_LEVEL;
+ QHash<int, qint64> dummyHash;
+ dummyHash[QmlDebug::Constants::QML_MIN_LEVEL] = 0;
+ endtimesPerNestingLevel << dummyHash;
+ }
+
+ for (i = 0; i < eventCount; i++) {
+ qint64 st = startTimeData[i].startTime;
+ int type = q->getEventType(i);
+
+ // general level
+ if (endtimesPerLevel[level] > st) {
+ level++;
+ } else {
+ while (level > QmlDebug::Constants::QML_MIN_LEVEL && endtimesPerLevel[level-1] <= st)
+ level--;
+ }
+ endtimesPerLevel[level] = st + startTimeData[i].duration;
+
+ // per type
+ if (endtimesPerNestingLevel[type][nestingLevels[type]] > st) {
+ nestingLevels[type]++;
+ } else {
+ while (nestingLevels[type] > QmlDebug::Constants::QML_MIN_LEVEL &&
+ endtimesPerNestingLevel[type][nestingLevels[type]-1] <= st)
+ nestingLevels[type]--;
+ }
+ endtimesPerNestingLevel[type][nestingLevels[type]] =
+ st + startTimeData[i].duration;
+
+ startTimeData[i].displayRowCollapsed = nestingLevels[type];
+
+ if (level == QmlDebug::Constants::QML_MIN_LEVEL) {
+ if (lastBaseEventEndTime < startTimeData[i].startTime) {
+ lastBaseEventIndex = i;
+ lastBaseEventEndTime = startTimeData[i].startTime + startTimeData[i].duration;
+ }
+ }
+ startTimeData[i].baseEventIndex = lastBaseEventIndex;
+ }
+
+ // nestingdepth
+ for (i = 0; i < eventCount; i++) {
+ int eventType = q->getEventType(i);
+ categorySpan[eventType].empty = false;
+ if (categorySpan[eventType].contractedRows <= startTimeData[i].displayRowCollapsed)
+ categorySpan[eventType].contractedRows = startTimeData[i].displayRowCollapsed + 1;
+ }
+}
+
+void BasicTimelineModel::BasicTimelineModelPrivate::computeExpandedLevels()
+{
+ QHash<int, int> eventRow;
+ int eventCount = startTimeData.count();
+ for (int i = 0; i < eventCount; i++) {
+ int eventId = startTimeData[i].eventId;
+ int eventType = eventDict[eventId].eventType;
+ if (!eventRow.contains(eventId)) {
+ categorySpan[eventType].empty = false;
+ eventRow[eventId] = categorySpan[eventType].expandedRows++;
+ }
+ startTimeData[i].displayRowExpanded = eventRow[eventId];
+ }
+}
+
+void BasicTimelineModel::BasicTimelineModelPrivate::buildEndTimeList()
+{
+ endTimeData.clear();
+
+ int eventCount = startTimeData.count();
+ for (int i = 0; i < eventCount; i++) {
+ BasicTimelineModel::QmlRangeEventEndInstance endInstance = {
+ i,
+ startTimeData[i].startTime + startTimeData[i].duration
+ };
+
+ endTimeData << endInstance;
+ }
+
+ qSort(endTimeData.begin(), endTimeData.end(), compareEndTimes);
+}
+
+void BasicTimelineModel::BasicTimelineModelPrivate::findBindingLoops()
+{
+ typedef QPair<QString, int> CallStackEntry;
+ QStack<CallStackEntry> callStack;
+
+ for (int i = 0; i < startTimeData.size(); ++i) {
+ QmlRangeEventStartInstance *event = &startTimeData[i];
+
+ BasicTimelineModel::QmlRangeEventData data = eventDict.at(event->eventId);
+
+ static QVector<QmlDebug::QmlEventType> acceptedTypes =
+ QVector<QmlDebug::QmlEventType>() << QmlDebug::Compiling << QmlDebug::Creating
+ << QmlDebug::Binding << QmlDebug::HandlingSignal;
+
+ if (!acceptedTypes.contains(data.eventType))
+ continue;
+
+ const QString eventHash = eventHashes.at(event->eventId);
+ const QmlRangeEventStartInstance *potentialParent = callStack.isEmpty()
+ ? 0 : &startTimeData[callStack.top().second];
+
+ while (potentialParent
+ && !(potentialParent->startTime + potentialParent->duration > event->startTime)) {
+ callStack.pop();
+ potentialParent = callStack.isEmpty() ? 0
+ : &startTimeData[callStack.top().second];
+ }
+
+ // check whether event is already in stack
+ for (int ii = 0; ii < callStack.size(); ++ii) {
+ if (callStack.at(ii).first == eventHash) {
+ event->bindingLoopHead = callStack.at(ii).second;
+ break;
+ }
+ }
+
+
+ CallStackEntry newEntry(eventHash, i);
+ callStack.push(newEntry);
+ }
+
+}
+
+void BasicTimelineModel::BasicTimelineModelPrivate::computeRowStarts()
+{
+ int rowStart = 0;
+ for (int i = 0; i < categorySpan.count(); i++) {
+ categorySpan[i].rowStart = rowStart;
+ rowStart += q->categoryDepth(i);
+ }
+}
+
+/////////////////// QML interface
+
+bool BasicTimelineModel::isEmpty() const
+{
+ return count() == 0;
+}
+
+int BasicTimelineModel::count() const
+{
+ return d->startTimeData.count();
+}
+
+qint64 BasicTimelineModel::lastTimeMark() const
+{
+ return d->startTimeData.last().startTime + d->startTimeData.last().duration;
+}
+
+bool BasicTimelineModel::expanded(int category) const
+{
+ if (d->categorySpan.count() <= category)
+ return false;
+ return d->categorySpan[category].expanded;
+}
+
+void BasicTimelineModel::setExpanded(int category, bool expanded)
+{
+ if (d->categorySpan.count() <= category)
+ return;
+
+ d->categorySpan[category].expanded = expanded;
+ d->computeRowStarts();
+ emit expandedChanged();
+}
+
+int BasicTimelineModel::categoryDepth(int categoryIndex) const
+{
+ if (d->categorySpan.count() <= categoryIndex)
+ return 1;
+ // special for paint events: show only when empty model or there's actual events
+ if (categoryIndex == QmlDebug::Painting && d->categorySpan[categoryIndex].empty && !isEmpty())
+ return 0;
+ if (d->categorySpan[categoryIndex].expanded)
+ return d->categorySpan[categoryIndex].expandedRows;
+ else
+ return d->categorySpan[categoryIndex].contractedRows;
+}
+
+int BasicTimelineModel::categoryCount() const
+{
+ return 5;
+}
+
+const QString BasicTimelineModel::categoryLabel(int categoryIndex) const
+{
+ switch (categoryIndex) {
+ case 0: return QCoreApplication::translate("MainView", "Painting"); break;
+ case 1: return QCoreApplication::translate("MainView", "Compiling"); break;
+ case 2: return QCoreApplication::translate("MainView", "Creating"); break;
+ case 3: return QCoreApplication::translate("MainView", "Binding"); break;
+ case 4: return QCoreApplication::translate("MainView", "Handling Signal"); break;
+ default: return QString();
+ }
+}
+
+
+int BasicTimelineModel::findFirstIndex(qint64 startTime) const
+{
+ int candidate = -1;
+ // in the "endtime" list, find the first event that ends after startTime
+ if (d->endTimeData.isEmpty())
+ return -1;
+ if (d->endTimeData.count() == 1 || d->endTimeData.first().endTime >= startTime)
+ candidate = 0;
+ else
+ if (d->endTimeData.last().endTime <= startTime)
+ return -1;
+
+ if (candidate == -1)
+ {
+ int fromIndex = 0;
+ int toIndex = d->endTimeData.count()-1;
+ while (toIndex - fromIndex > 1) {
+ int midIndex = (fromIndex + toIndex)/2;
+ if (d->endTimeData[midIndex].endTime < startTime)
+ fromIndex = midIndex;
+ else
+ toIndex = midIndex;
+ }
+
+ candidate = toIndex;
+ }
+
+ int eventIndex = d->endTimeData[candidate].startTimeIndex;
+ return d->startTimeData[eventIndex].baseEventIndex;
+
+}
+
+int BasicTimelineModel::findFirstIndexNoParents(qint64 startTime) const
+{
+ int candidate = -1;
+ // in the "endtime" list, find the first event that ends after startTime
+ if (d->endTimeData.isEmpty())
+ return -1;
+ if (d->endTimeData.count() == 1 || d->endTimeData.first().endTime >= startTime)
+ candidate = 0;
+ else
+ if (d->endTimeData.last().endTime <= startTime)
+ return -1;
+
+ if (candidate == -1) {
+ int fromIndex = 0;
+ int toIndex = d->endTimeData.count()-1;
+ while (toIndex - fromIndex > 1) {
+ int midIndex = (fromIndex + toIndex)/2;
+ if (d->endTimeData[midIndex].endTime < startTime)
+ fromIndex = midIndex;
+ else
+ toIndex = midIndex;
+ }
+
+ candidate = toIndex;
+ }
+
+ int ndx = d->endTimeData[candidate].startTimeIndex;
+
+ return ndx;
+}
+
+int BasicTimelineModel::findLastIndex(qint64 endTime) const
+{
+ // in the "starttime" list, find the last event that starts before endtime
+ if (d->startTimeData.isEmpty())
+ return -1;
+ if (d->startTimeData.first().startTime >= endTime)
+ return -1;
+ if (d->startTimeData.count() == 1)
+ return 0;
+ if (d->startTimeData.last().startTime <= endTime)
+ return d->startTimeData.count()-1;
+
+ int fromIndex = 0;
+ int toIndex = d->startTimeData.count()-1;
+ while (toIndex - fromIndex > 1) {
+ int midIndex = (fromIndex + toIndex)/2;
+ if (d->startTimeData[midIndex].startTime < endTime)
+ fromIndex = midIndex;
+ else
+ toIndex = midIndex;
+ }
+
+ return fromIndex;
+}
+
+int BasicTimelineModel::getEventType(int index) const
+{
+ return d->eventDict[d->startTimeData[index].eventId].eventType;
+}
+
+int BasicTimelineModel::getEventCategory(int index) const
+{
+ int evTy = getEventType(index);
+ // special: paint events shown?
+ if (d->categorySpan[0].empty && !isEmpty())
+ return evTy - 1;
+ return evTy;
+}
+
+int BasicTimelineModel::getEventRow(int index) const
+{
+ if (d->categorySpan[getEventType(index)].expanded)
+ return d->startTimeData[index].displayRowExpanded + d->categorySpan[getEventType(index)].rowStart;
+ else
+ return d->startTimeData[index].displayRowCollapsed + d->categorySpan[getEventType(index)].rowStart;
+}
+
+qint64 BasicTimelineModel::getDuration(int index) const
+{
+ return d->startTimeData[index].duration;
+}
+
+qint64 BasicTimelineModel::getStartTime(int index) const
+{
+ return d->startTimeData[index].startTime;
+}
+
+qint64 BasicTimelineModel::getEndTime(int index) const
+{
+ return d->startTimeData[index].startTime + d->startTimeData[index].duration;
+}
+
+int BasicTimelineModel::getEventId(int index) const
+{
+ return d->startTimeData[index].eventId;
+}
+
+int BasicTimelineModel::getBindingLoopDest(int index) const
+{
+ return d->startTimeData[index].bindingLoopHead;
+}
+
+QColor BasicTimelineModel::getColor(int index) const
+{
+ int ndx = getEventId(index);
+ return QColor::fromHsl((ndx*25)%360, 76, 166);
+}
+
+float BasicTimelineModel::getHeight(int index) const
+{
+ Q_UNUSED(index);
+ // 100% height for regular events
+ return 1.0f;
+}
+
+const QVariantList BasicTimelineModel::getLabelsForCategory(int category) const
+{
+ QVariantList result;
+
+ if (d->categorySpan.count() > category && d->categorySpan[category].expanded) {
+ int eventCount = d->eventDict.count();
+ for (int i = 0; i < eventCount; i++) {
+ if (d->eventDict[i].eventType == category) {
+ QVariantMap element;
+ element.insert(QLatin1String("displayName"), QVariant(d->eventDict[i].displayName));
+ element.insert(QLatin1String("description"), QVariant(d->eventDict[i].details));
+ element.insert(QLatin1String("id"), QVariant(d->eventDict[i].eventId));
+ result << element;
+ }
+ }
+ }
+
+ return result;
+}
+
+QString BasicTimelineModel::BasicTimelineModelPrivate::displayTime(double time)
+{
+ if (time < 1e6)
+ return QString::number(time/1e3,'f',3) + trUtf8(" \xc2\xb5s");
+ if (time < 1e9)
+ return QString::number(time/1e6,'f',3) + tr(" ms");
+
+ return QString::number(time/1e9,'f',3) + tr(" s");
+}
+
+const QVariantList BasicTimelineModel::getEventDetails(int index) const
+{
+ QVariantList result;
+ int eventId = getEventId(index);
+
+ static const char trContext[] = "RangeDetails";
+ {
+ QVariantMap valuePair;
+ valuePair.insert(QLatin1String("title"), QVariant(categoryLabel(d->eventDict[eventId].eventType)));
+ result << valuePair;
+ }
+
+ // duration
+ {
+ QVariantMap valuePair;
+ valuePair.insert(QCoreApplication::translate(trContext, "Duration:"), QVariant(d->displayTime(d->startTimeData[index].duration)));
+ result << valuePair;
+ }
+
+ // details
+ {
+ QVariantMap valuePair;
+ QString detailsString = d->eventDict[eventId].details;
+ if (detailsString.length() > 40)
+ detailsString = detailsString.left(40) + QLatin1String("...");
+ valuePair.insert(QCoreApplication::translate(trContext, "Details:"), QVariant(detailsString));
+ result << valuePair;
+ }
+
+ // location
+ {
+ QVariantMap valuePair;
+ valuePair.insert(QCoreApplication::translate(trContext, "Location:"), QVariant(d->eventDict[eventId].displayName));
+ result << valuePair;
+ }
+
+ // isbindingloop
+ {}
+
+
+ return result;
+}
+
+const QVariantMap BasicTimelineModel::getEventLocation(int index) const
+{
+ QVariantMap result;
+ int eventId = getEventId(index);
+
+ QmlDebug::QmlEventLocation location
+ = d->eventDict.at(eventId).location;
+
+ result.insert(QLatin1String("file"), location.filename);
+ result.insert(QLatin1String("line"), location.line);
+ result.insert(QLatin1String("column"), location.column);
+
+ return result;
+}
+
+int BasicTimelineModel::getEventIdForHash(const QString &eventHash) const
+{
+ return d->eventHashes.indexOf(eventHash);
+}
+
+int BasicTimelineModel::getEventIdForLocation(const QString &filename, int line, int column) const
+{
+ // if this is called from v8 view, we don't have the column number, it will be -1
+ foreach (const QmlRangeEventData &eventData, d->eventDict) {
+ if (eventData.location.filename == filename &&
+ eventData.location.line == line &&
+ (column == -1 || eventData.location.column == column))
+ return eventData.eventId;
+ }
+ return -1;
+}
+
+
+
+}
+}
diff --git a/src/plugins/qmlprofiler/qmlprofilertimelinemodelproxy.h b/src/plugins/qmlprofiler/qmlprofilertimelinemodelproxy.h
new file mode 100644
index 0000000000..3ffcf707ff
--- /dev/null
+++ b/src/plugins/qmlprofiler/qmlprofilertimelinemodelproxy.h
@@ -0,0 +1,146 @@
+/****************************************************************************
+**
+** 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 QMLPROFILERTIMELINEMODELPROXY_H
+#define QMLPROFILERTIMELINEMODELPROXY_H
+
+#include <QObject>
+#include "abstracttimelinemodel.h"
+#include <qmldebug/qmlprofilereventtypes.h>
+#include <qmldebug/qmlprofilereventlocation.h>
+//#include <QHash>
+//#include <QVector>
+#include <QVariantList>
+//#include <QVariantMap>
+#include "qmlprofilersimplemodel.h"
+#include <QColor>
+
+
+namespace QmlProfiler {
+class QmlProfilerModelManager;
+
+namespace Internal {
+
+class BasicTimelineModel : public AbstractTimelineModel
+{
+// Q_PROPERTY(bool empty READ isEmpty NOTIFY emptyChanged)
+
+ Q_OBJECT
+public:
+ struct QmlRangeEventData
+ {
+ QString displayName;
+ QString details;
+ QmlDebug::QmlEventLocation location;
+ QmlDebug::QmlEventType eventType;
+
+ int eventId; // separate
+ };
+
+ struct QmlRangeEventStartInstance {
+ qint64 startTime;
+ qint64 duration;
+ int eventId;
+
+ // not-expanded, per type
+ int displayRowExpanded;
+ int displayRowCollapsed;
+ int baseEventIndex; // used by findfirstindex
+ int bindingLoopHead;
+ };
+
+ struct QmlRangeEventEndInstance {
+ int startTimeIndex;
+ qint64 endTime;
+ };
+
+ BasicTimelineModel(QObject *parent = 0);
+ ~BasicTimelineModel();
+
+
+ int categories() const;
+ QStringList categoryTitles() const;
+ QString name() const;
+
+ const QVector<QmlRangeEventStartInstance> getData() const;
+ const QVector<QmlRangeEventStartInstance> getData(qint64 fromTime, qint64 toTime) const;
+ void loadData();
+ Q_INVOKABLE int count() const;
+ void clear();
+
+
+// QML interface
+ bool isEmpty() const;
+
+ Q_INVOKABLE qint64 lastTimeMark() const;
+
+ Q_INVOKABLE bool expanded(int category) const;
+ Q_INVOKABLE void setExpanded(int category, bool expanded);
+ Q_INVOKABLE int categoryDepth(int categoryIndex) const;
+ Q_INVOKABLE int categoryCount() const;
+ Q_INVOKABLE const QString categoryLabel(int categoryIndex) const;
+
+ int findFirstIndex(qint64 startTime) const;
+ int findFirstIndexNoParents(qint64 startTime) const;
+ int findLastIndex(qint64 endTime) const;
+
+ int getEventType(int index) const;
+ int getEventCategory(int index) const;
+ int getEventRow(int index) const;
+ Q_INVOKABLE qint64 getDuration(int index) const;
+ Q_INVOKABLE qint64 getStartTime(int index) const;
+ Q_INVOKABLE qint64 getEndTime(int index) const;
+ Q_INVOKABLE int getEventId(int index) const;
+ int getBindingLoopDest(int index) const;
+ Q_INVOKABLE QColor getColor(int index) const;
+ Q_INVOKABLE float getHeight(int index) const;
+
+ Q_INVOKABLE const QVariantList getLabelsForCategory(int category) const;
+ Q_INVOKABLE const QVariantList getEventDetails(int index) const;
+ Q_INVOKABLE const QVariantMap getEventLocation(int index) const;
+
+ Q_INVOKABLE int getEventIdForHash(const QString &eventHash) const;
+ Q_INVOKABLE int getEventIdForLocation(const QString &filename, int line, int column) const;
+
+private slots:
+ bool eventAccepted(const QmlProfilerSimpleModel::QmlEventData &event) const;
+protected slots:
+ void dataChanged();
+
+private:
+ class BasicTimelineModelPrivate;
+ BasicTimelineModelPrivate *d;
+
+};
+
+}
+}
+
+#endif
diff --git a/src/plugins/qmlprofiler/qmlprofilertool.cpp b/src/plugins/qmlprofiler/qmlprofilertool.cpp
index f1528cfa31..f8812232de 100644
--- a/src/plugins/qmlprofiler/qmlprofilertool.cpp
+++ b/src/plugins/qmlprofiler/qmlprofilertool.cpp
@@ -34,7 +34,7 @@
#include "qmlprofilerattachdialog.h"
#include "qmlprofilerviewmanager.h"
#include "qmlprofilerclientmanager.h"
-#include "qmlprofilerdatamodel.h"
+#include "qmlprofilermodelmanager.h"
#include "qmlprofilerdetailsrewriter.h"
#include "timelinerenderer.h"
@@ -70,8 +70,6 @@
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/actioncontainer.h>
-#include <debugger/debuggerrunconfigurationaspect.h>
-
#include <qtsupport/qtkitinformation.h>
#include <QApplication>
@@ -98,19 +96,12 @@ using namespace QmlProjectManager;
class QmlProfilerTool::QmlProfilerToolPrivate
{
public:
- QmlProfilerToolPrivate(QmlProfilerTool *qq) : q(qq) {}
- ~QmlProfilerToolPrivate() {}
-
- QmlProfilerTool *q;
-
QmlProfilerStateManager *m_profilerState;
QmlProfilerClientManager *m_profilerConnections;
- QmlProfilerDataModel *m_profilerDataModel;
- QmlProfilerDetailsRewriter *m_detailsRewriter;
+ QmlProfilerModelManager *m_profilerModelManager;
QmlProfilerViewManager *m_viewContainer;
Utils::FileInProjectFinder m_projectFinder;
- RunConfiguration *m_runConfiguration;
QToolButton *m_recordButton;
QToolButton *m_clearButton;
@@ -125,13 +116,12 @@ public:
};
QmlProfilerTool::QmlProfilerTool(QObject *parent)
- : IAnalyzerTool(parent), d(new QmlProfilerToolPrivate(this))
+ : IAnalyzerTool(parent), d(new QmlProfilerToolPrivate)
{
setObjectName(QLatin1String("QmlProfilerTool"));
d->m_profilerState = 0;
d->m_viewContainer = 0;
- d->m_runConfiguration = 0;
qmlRegisterType<QmlProfilerCanvas>("Monitor", 1, 0, "Canvas2D");
qmlRegisterType<Context2D>();
@@ -147,31 +137,11 @@ QmlProfilerTool::QmlProfilerTool(QObject *parent)
d->m_profilerConnections->registerProfilerStateManager(d->m_profilerState);
connect(d->m_profilerConnections, SIGNAL(connectionClosed()), this, SLOT(clientsDisconnected()));
- d->m_profilerDataModel = new QmlProfilerDataModel(this);
- connect(d->m_profilerDataModel, SIGNAL(stateChanged()), this, SLOT(profilerDataModelStateChanged()));
- connect(d->m_profilerDataModel, SIGNAL(error(QString)), this, SLOT(showErrorDialog(QString)));
- connect(d->m_profilerConnections,
- SIGNAL(addRangedEvent(int,int,qint64,qint64,QStringList,QmlDebug::QmlEventLocation)),
- d->m_profilerDataModel,
- SLOT(addRangedEvent(int,int,qint64,qint64,QStringList,QmlDebug::QmlEventLocation)));
- connect(d->m_profilerConnections,
- SIGNAL(addV8Event(int,QString,QString,int,double,double)),
- d->m_profilerDataModel,
- SLOT(addV8Event(int,QString,QString,int,double,double)));
- connect(d->m_profilerConnections, SIGNAL(addFrameEvent(qint64,int,int)), d->m_profilerDataModel, SLOT(addFrameEvent(qint64,int,int)));
- connect(d->m_profilerConnections, SIGNAL(traceStarted(qint64)), d->m_profilerDataModel, SLOT(setTraceStartTime(qint64)));
- connect(d->m_profilerConnections, SIGNAL(traceFinished(qint64)), d->m_profilerDataModel, SLOT(setTraceEndTime(qint64)));
- connect(d->m_profilerConnections, SIGNAL(dataReadyForProcessing()), d->m_profilerDataModel, SLOT(complete()));
-
-
- d->m_detailsRewriter = new QmlProfilerDetailsRewriter(this, &d->m_projectFinder);
- connect(d->m_profilerDataModel, SIGNAL(requestDetailsForLocation(int,QmlDebug::QmlEventLocation)),
- d->m_detailsRewriter, SLOT(requestDetailsForLocation(int,QmlDebug::QmlEventLocation)));
- connect(d->m_detailsRewriter, SIGNAL(rewriteDetailsString(int,QmlDebug::QmlEventLocation,QString)),
- d->m_profilerDataModel, SLOT(rewriteDetailsString(int,QmlDebug::QmlEventLocation,QString)));
- connect(d->m_detailsRewriter, SIGNAL(eventDetailsChanged()), d->m_profilerDataModel, SLOT(finishedRewritingDetails()));
- connect(d->m_profilerDataModel, SIGNAL(reloadDocumentsForDetails()), d->m_detailsRewriter, SLOT(reloadDocuments()));
+ d->m_profilerModelManager = new QmlProfilerModelManager(&d->m_projectFinder, this);
+ connect(d->m_profilerModelManager, SIGNAL(stateChanged()), this, SLOT(profilerDataModelStateChanged()));
+ connect(d->m_profilerModelManager, SIGNAL(error(QString)), this, SLOT(showErrorDialog(QString)));
+ d->m_profilerConnections->setModelManager(d->m_profilerModelManager);
Command *command = 0;
const Context globalContext(C_GLOBAL);
@@ -201,36 +171,20 @@ QmlProfilerTool::~QmlProfilerTool()
delete d;
}
-Core::Id QmlProfilerTool::id() const
-{
- return Core::Id("QmlProfiler");
-}
-
RunMode QmlProfilerTool::runMode() const
{
return QmlProfilerRunMode;
}
-QString QmlProfilerTool::displayName() const
-{
- return tr("QML Profiler");
-}
-
-QString QmlProfilerTool::description() const
-{
- return tr("The QML Profiler can be used to find performance bottlenecks in "
- "applications using QML.");
-}
-
IAnalyzerTool::ToolMode QmlProfilerTool::toolMode() const
{
return AnyMode;
}
-IAnalyzerEngine *QmlProfilerTool::createEngine(const AnalyzerStartParameters &sp,
+AnalyzerRunControl *QmlProfilerTool::createRunControl(const AnalyzerStartParameters &sp,
RunConfiguration *runConfiguration)
{
- QmlProfilerEngine *engine = new QmlProfilerEngine(this, sp, runConfiguration);
+ QmlProfilerRunControl *engine = new QmlProfilerRunControl(sp, runConfiguration);
engine->registerProfilerStateManager(d->m_profilerState);
@@ -257,15 +211,13 @@ IAnalyzerEngine *QmlProfilerTool::createEngine(const AnalyzerStartParameters &sp
if (isTcpConnection)
d->m_profilerConnections->setTcpConnection(sp.analyzerHost, sp.analyzerPort);
- d->m_runConfiguration = runConfiguration;
-
//
// Initialize m_projectFinder
//
QString projectDirectory;
- if (d->m_runConfiguration) {
- Project *project = d->m_runConfiguration->target()->project();
+ if (runConfiguration) {
+ Project *project = runConfiguration->target()->project();
projectDirectory = project->projectDirectory();
}
@@ -277,14 +229,6 @@ IAnalyzerEngine *QmlProfilerTool::createEngine(const AnalyzerStartParameters &sp
return engine;
}
-bool QmlProfilerTool::canRun(RunConfiguration *runConfiguration, RunMode mode) const
-{
- if (qobject_cast<QmlProjectRunConfiguration *>(runConfiguration)
- || qobject_cast<LocalApplicationRunConfiguration *>(runConfiguration))
- return mode == runMode();
- return false;
-}
-
static QString sysroot(RunConfiguration *runConfig)
{
QTC_ASSERT(runConfig, return QString());
@@ -294,54 +238,6 @@ static QString sysroot(RunConfiguration *runConfig)
return QString();
}
-AnalyzerStartParameters QmlProfilerTool::createStartParameters(RunConfiguration *runConfiguration, RunMode mode) const
-{
- Q_UNUSED(mode);
-
- AnalyzerStartParameters sp;
- ProjectExplorer::EnvironmentAspect *environment
- = runConfiguration->extraAspect<ProjectExplorer::EnvironmentAspect>();
- Debugger::DebuggerRunConfigurationAspect *debugger
- = runConfiguration->extraAspect<Debugger::DebuggerRunConfigurationAspect>();
- QTC_ASSERT(debugger, return sp);
-
- // FIXME: This is only used to communicate the connParams settings.
- if (QmlProjectRunConfiguration *rc1 =
- qobject_cast<QmlProjectRunConfiguration *>(runConfiguration)) {
- // This is a "plain" .qmlproject.
- if (environment)
- sp.environment = environment->environment();
- sp.workingDirectory = rc1->workingDirectory();
- sp.debuggee = rc1->observerPath();
- sp.debuggeeArgs = rc1->viewerArguments();
- sp.displayName = rc1->displayName();
- } else if (LocalApplicationRunConfiguration *rc2 =
- qobject_cast<LocalApplicationRunConfiguration *>(runConfiguration)) {
- if (environment)
- sp.environment = environment->environment();
- sp.workingDirectory = rc2->workingDirectory();
- sp.debuggee = rc2->executable();
- sp.debuggeeArgs = rc2->commandLineArguments();
- sp.displayName = rc2->displayName();
- } else {
- // What could that be?
- QTC_ASSERT(false, return sp);
- }
- const ProjectExplorer::IDevice::ConstPtr device =
- ProjectExplorer::DeviceKitInformation::device(runConfiguration->target()->kit());
- if (device->type() == ProjectExplorer::Constants::DESKTOP_DEVICE_TYPE) {
- QTcpServer server;
- if (!server.listen(QHostAddress::LocalHost) && !server.listen(QHostAddress::LocalHostIPv6)) {
- qWarning() << "Cannot open port on host for QML profiling.";
- return sp;
- }
- sp.analyzerHost = server.serverAddress().toString();
- sp.analyzerPort = server.serverPort();
- }
- sp.startMode = StartQml;
- return sp;
-}
-
QWidget *QmlProfilerTool::createWidgets()
{
QTC_ASSERT(!d->m_viewContainer, return 0);
@@ -349,7 +245,7 @@ QWidget *QmlProfilerTool::createWidgets()
d->m_viewContainer = new QmlProfilerViewManager(this,
this,
- d->m_profilerDataModel,
+ d->m_profilerModelManager,
d->m_profilerState);
connect(d->m_viewContainer, SIGNAL(gotoSourceLocation(QString,int,int)),
this, SLOT(gotoSourceLocation(QString,int,int)));
@@ -401,11 +297,10 @@ void QmlProfilerTool::populateFileFinder(QString projectDirectory, QString activ
{
// Initialize filefinder with some sensible default
QStringList sourceFiles;
- SessionManager *sessionManager = ProjectExplorerPlugin::instance()->session();
- QList<Project *> projects = sessionManager->projects();
- if (Project *startupProject = ProjectExplorerPlugin::instance()->startupProject()) {
+ QList<Project *> projects = SessionManager::projects();
+ if (Project *startupProject = SessionManager::startupProject()) {
// startup project first
- projects.removeOne(ProjectExplorerPlugin::instance()->startupProject());
+ projects.removeOne(startupProject);
projects.insert(0, startupProject);
}
foreach (Project *project, projects)
@@ -467,7 +362,7 @@ void QmlProfilerTool::gotoSourceLocation(const QString &fileUrl, int lineNumber,
TextEditor::ITextEditor *textEditor = qobject_cast<TextEditor::ITextEditor*>(editor);
if (textEditor) {
- EditorManager::instance()->addCurrentPositionToNavigationHistory();
+ EditorManager::addCurrentPositionToNavigationHistory();
// textEditor counts columns starting with 0, but the ASTs store the
// location starting with 1, therefore the -1 in the call to gotoLine
textEditor->gotoLine(lineNumber, columnNumber - 1);
@@ -481,8 +376,9 @@ void QmlProfilerTool::updateTimeDisplay()
if (d->m_profilerState->serverRecording() &&
d->m_profilerState->currentState() == QmlProfilerStateManager::AppRunning) {
seconds = d->m_recordingElapsedTime.elapsed() / 1000.0;
- } else if (d->m_profilerDataModel->currentState() != QmlProfilerDataModel::Empty ) {
- seconds = (d->m_profilerDataModel->traceEndTime() - d->m_profilerDataModel->traceStartTime()) / 1.0e9;
+ } else if (d->m_profilerModelManager->state() != QmlProfilerDataState::Empty ) {
+ //seconds = d->m_profilerModelManager->traceDuration() / 1.0e9;
+ seconds = d->m_profilerModelManager->traceTime()->duration() / 1.0e9;
}
QString timeString = QString::number(seconds,'f',1);
QString profilerTimeStr = QmlProfilerTool::tr("%1 s").arg(timeString, 6);
@@ -491,7 +387,7 @@ void QmlProfilerTool::updateTimeDisplay()
void QmlProfilerTool::clearData()
{
- d->m_profilerDataModel->clear();
+ d->m_profilerModelManager->clear();
d->m_profilerConnections->discardPendingData();
}
@@ -532,7 +428,6 @@ static void startRemoteTool(IAnalyzerTool *tool, StartMode mode)
}
AnalyzerStartParameters sp;
- sp.toolId = tool->id();
sp.startMode = mode;
IDevice::ConstPtr device = DeviceKitInformation::device(kit);
@@ -548,7 +443,8 @@ static void startRemoteTool(IAnalyzerTool *tool, StartMode mode)
sp.sysroot = SysRootKitInformation::sysRoot(kit).toString();
sp.analyzerPort = port;
- AnalyzerRunControl *rc = new AnalyzerRunControl(tool, sp, 0);
+ //AnalyzerRunControl *rc = new AnalyzerRunControl(tool, sp, 0);
+ AnalyzerRunControl *rc = tool->createRunControl(sp, 0);
QObject::connect(AnalyzerManager::stopAction(), SIGNAL(triggered()), rc, SLOT(stopIt()));
ProjectExplorerPlugin::instance()->startRunControl(rc, tool->runMode());
@@ -562,10 +458,9 @@ void QmlProfilerTool::startTool(StartMode mode)
AnalyzerManager::showMode();
if (mode == StartLocal) {
- ProjectExplorerPlugin *pe = ProjectExplorerPlugin::instance();
// ### not sure if we're supposed to check if the RunConFiguration isEnabled
- Project *pro = pe->startupProject();
- pe->runProject(pro, runMode());
+ Project *pro = SessionManager::startupProject();
+ ProjectExplorerPlugin::instance()->runProject(pro, runMode());
} else if (mode == StartRemote) {
startRemoteTool(this, mode);
}
@@ -573,14 +468,12 @@ void QmlProfilerTool::startTool(StartMode mode)
void QmlProfilerTool::logStatus(const QString &msg)
{
- MessageManager *messageManager = MessageManager::instance();
- messageManager->printToOutputPane(msg, Core::MessageManager::Flash);
+ MessageManager::write(msg, Core::MessageManager::Flash);
}
void QmlProfilerTool::logError(const QString &msg)
{
- MessageManager *messageManager = MessageManager::instance();
- messageManager->printToOutputPane(msg, Core::MessageManager::NoModeSwitch);
+ MessageManager::write(msg);
}
void QmlProfilerTool::showErrorDialog(const QString &error)
@@ -597,7 +490,7 @@ void QmlProfilerTool::showErrorDialog(const QString &error)
void QmlProfilerTool::showSaveOption()
{
- d->m_saveQmlTrace->setEnabled(!d->m_profilerDataModel->isEmpty());
+ d->m_saveQmlTrace->setEnabled(!d->m_profilerModelManager->isEmpty());
}
void QmlProfilerTool::showSaveDialog()
@@ -607,7 +500,7 @@ void QmlProfilerTool::showSaveDialog()
if (!filename.isEmpty()) {
if (!filename.endsWith(QLatin1String(TraceFileExtension)))
filename += QLatin1String(TraceFileExtension);
- d->m_profilerDataModel->save(filename);
+ d->m_profilerModelManager->save(filename);
}
}
@@ -616,16 +509,15 @@ void QmlProfilerTool::showLoadDialog()
if (ModeManager::currentMode()->id() != MODE_ANALYZE)
AnalyzerManager::showMode();
- if (AnalyzerManager::currentSelectedTool() != this)
- AnalyzerManager::selectTool(this, StartRemote);
+ AnalyzerManager::selectTool(this, StartRemote);
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)
- d->m_profilerDataModel->setFilename(filename);
- QTimer::singleShot(100, d->m_profilerDataModel, SLOT(load()));
+ d->m_profilerModelManager->setFilename(filename);
+ QTimer::singleShot(100, d->m_profilerModelManager, SLOT(load()));
}
}
@@ -633,7 +525,7 @@ void QmlProfilerTool::clientsDisconnected()
{
// If the application stopped by itself, check if we have all the data
if (d->m_profilerState->currentState() == QmlProfilerStateManager::AppDying) {
- if (d->m_profilerDataModel->currentState() == QmlProfilerDataModel::AcquiringData)
+ if (d->m_profilerModelManager->state() == QmlProfilerDataState::AcquiringData)
d->m_profilerState->setCurrentState(QmlProfilerStateManager::AppKilled);
else
d->m_profilerState->setCurrentState(QmlProfilerStateManager::AppStopped);
@@ -641,21 +533,20 @@ void QmlProfilerTool::clientsDisconnected()
// ... and return to the "base" state
d->m_profilerState->setCurrentState(QmlProfilerStateManager::Idle);
}
-
// If the connection is closed while the app is still running, no special action is needed
}
void QmlProfilerTool::profilerDataModelStateChanged()
{
- switch (d->m_profilerDataModel->currentState()) {
- case QmlProfilerDataModel::Empty :
+ switch (d->m_profilerModelManager->state()) {
+ case QmlProfilerDataState::Empty :
clearDisplay();
break;
- case QmlProfilerDataModel::AcquiringData :
- case QmlProfilerDataModel::ProcessingData :
+ case QmlProfilerDataState::AcquiringData :
+ case QmlProfilerDataState::ProcessingData :
// nothing to be done for these two
break;
- case QmlProfilerDataModel::Done :
+ case QmlProfilerDataState::Done :
if (d->m_profilerState->currentState() == QmlProfilerStateManager::AppStopRequested)
d->m_profilerState->setCurrentState(QmlProfilerStateManager::AppReadyToStop);
showSaveOption();
@@ -692,8 +583,7 @@ QMessageBox *QmlProfilerTool::requestMessageBox()
void QmlProfilerTool::handleHelpRequest(const QString &link)
{
- HelpManager *helpManager = HelpManager::instance();
- helpManager->handleHelpRequest(link);
+ HelpManager::handleHelpRequest(link);
}
void QmlProfilerTool::profilerStateChanged()
@@ -707,7 +597,7 @@ void QmlProfilerTool::profilerStateChanged()
}
case QmlProfilerStateManager::AppKilled : {
showNonmodalWarning(tr("Application finished before loading profiled data.\nPlease use the stop button instead."));
- d->m_profilerDataModel->clear();
+ d->m_profilerModelManager->clear();
break;
}
case QmlProfilerStateManager::Idle :
@@ -734,9 +624,13 @@ void QmlProfilerTool::serverRecordingChanged()
setRecording(d->m_profilerState->serverRecording());
// clear the old data each time we start a new profiling session
if (d->m_profilerState->serverRecording()) {
+ d->m_clearButton->setEnabled(false);
clearData();
- d->m_profilerDataModel->prepareForWriting();
+ d->m_profilerModelManager->prepareForWriting();
+ } else {
+ d->m_clearButton->setEnabled(true);
}
+ } else {
+ d->m_clearButton->setEnabled(true);
}
}
-
diff --git a/src/plugins/qmlprofiler/qmlprofilertool.h b/src/plugins/qmlprofiler/qmlprofilertool.h
index 412cb6a87f..9cd45407d8 100644
--- a/src/plugins/qmlprofiler/qmlprofilertool.h
+++ b/src/plugins/qmlprofiler/qmlprofilertool.h
@@ -31,7 +31,7 @@
#define QMLPROFILERTOOL_H
#include <analyzerbase/ianalyzertool.h>
-#include <analyzerbase/ianalyzerengine.h>
+#include <analyzerbase/analyzerruncontrol.h>
QT_BEGIN_NAMESPACE
class QMessageBox;
@@ -48,24 +48,12 @@ public:
explicit QmlProfilerTool(QObject *parent);
~QmlProfilerTool();
- Core::Id id() const;
ProjectExplorer::RunMode runMode() const;
- QString displayName() const;
- QString description() const;
ToolMode toolMode() const;
- void extensionsInitialized() {}
-
- Analyzer::IAnalyzerEngine *createEngine(const Analyzer::AnalyzerStartParameters &sp,
+ Analyzer::AnalyzerRunControl *createRunControl(const Analyzer::AnalyzerStartParameters &sp,
ProjectExplorer::RunConfiguration *runConfiguration = 0);
- bool canRun(ProjectExplorer::RunConfiguration *runConfiguration,
- ProjectExplorer::RunMode mode) const;
-
- Analyzer::AnalyzerStartParameters createStartParameters(
- ProjectExplorer::RunConfiguration *runConfiguration,
- ProjectExplorer::RunMode mode) const;
-
QWidget *createWidgets();
void startTool(Analyzer::StartMode mode);
diff --git a/src/plugins/qmlprofiler/qmlprofilertracefile.cpp b/src/plugins/qmlprofiler/qmlprofilertracefile.cpp
new file mode 100644
index 0000000000..0da6a4a853
--- /dev/null
+++ b/src/plugins/qmlprofiler/qmlprofilertracefile.cpp
@@ -0,0 +1,561 @@
+/****************************************************************************
+**
+** 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 "qmlprofilertracefile.h"
+
+#include <utils/qtcassert.h>
+
+#include <QIODevice>
+#include <QStringList>
+#include <QXmlStreamReader>
+#include <QXmlStreamWriter>
+#include <QDebug>
+
+// import QmlEventType, QmlBindingType enums, QmlEventLocation
+using namespace QmlDebug;
+
+
+const char PROFILER_FILE_VERSION[] = "1.02";
+
+const char TYPE_PAINTING_STR[] = "Painting";
+const char TYPE_COMPILING_STR[] = "Compiling";
+const char TYPE_CREATING_STR[] = "Creating";
+const char TYPE_BINDING_STR[] = "Binding";
+const char TYPE_HANDLINGSIGNAL_STR[] = "HandlingSignal";
+const char TYPE_PIXMAPCACHE_STR[] = "PixmapCache";
+const char TYPE_SCENEGRAPH_STR[] = "SceneGraph";
+
+#define _(X) QLatin1String(X)
+
+
+//
+// "be strict in your output but tolerant in your inputs"
+//
+
+namespace QmlProfiler {
+namespace Internal {
+
+static QmlEventType qmlEventTypeAsEnum(const QString &typeString)
+{
+ if (typeString == _(TYPE_PAINTING_STR)) {
+ return Painting;
+ } else if (typeString == _(TYPE_COMPILING_STR)) {
+ return Compiling;
+ } else if (typeString == _(TYPE_CREATING_STR)) {
+ return Creating;
+ } else if (typeString == _(TYPE_BINDING_STR)) {
+ return Binding;
+ } else if (typeString == _(TYPE_HANDLINGSIGNAL_STR)) {
+ return HandlingSignal;
+ } else if (typeString == _(TYPE_PIXMAPCACHE_STR)) {
+ return PixmapCacheEvent;
+ } else if (typeString == _(TYPE_SCENEGRAPH_STR)) {
+ return SceneGraphFrameEvent;
+ } else {
+ bool isNumber = false;
+ int type = typeString.toUInt(&isNumber);
+ if (isNumber)
+ return (QmlEventType)type;
+ else
+ return MaximumQmlEventType;
+ }
+}
+
+static QString qmlEventTypeAsString(QmlEventType typeEnum)
+{
+ switch (typeEnum) {
+ case Painting:
+ return _(TYPE_PAINTING_STR);
+ break;
+ case Compiling:
+ return _(TYPE_COMPILING_STR);
+ break;
+ case Creating:
+ return _(TYPE_CREATING_STR);
+ break;
+ case Binding:
+ return _(TYPE_BINDING_STR);
+ break;
+ case HandlingSignal:
+ return _(TYPE_HANDLINGSIGNAL_STR);
+ break;
+ case PixmapCacheEvent:
+ return _(TYPE_PIXMAPCACHE_STR);
+ break;
+ case SceneGraphFrameEvent:
+ return _(TYPE_SCENEGRAPH_STR);
+ break;
+ default:
+ return QString::number((int)typeEnum);
+ }
+}
+
+
+QmlProfilerFileReader::QmlProfilerFileReader(QObject *parent) :
+ QObject(parent),
+ m_v8Model(0)
+{
+}
+
+void QmlProfilerFileReader::setV8DataModel(QV8ProfilerDataModel *dataModel)
+{
+ m_v8Model = dataModel;
+}
+
+bool QmlProfilerFileReader::load(QIODevice *device)
+{
+ QXmlStreamReader stream(device);
+
+ bool validVersion = true;
+
+ while (validVersion && !stream.atEnd() && !stream.hasError()) {
+ QXmlStreamReader::TokenType token = stream.readNext();
+ const QStringRef elementName = stream.name();
+ switch (token) {
+ case QXmlStreamReader::StartDocument : continue;
+ case QXmlStreamReader::StartElement : {
+ if (elementName == _("trace")) {
+ QXmlStreamAttributes attributes = stream.attributes();
+ if (attributes.hasAttribute(_("version")))
+ validVersion = attributes.value(_("version")) == _(PROFILER_FILE_VERSION);
+ else
+ validVersion = false;
+ if (attributes.hasAttribute(_("traceStart")))
+ emit traceStartTime(attributes.value(_("traceStart")).toString().toLongLong());
+ if (attributes.hasAttribute(_("traceEnd")))
+ emit traceEndTime(attributes.value(_("traceEnd")).toString().toLongLong());
+ }
+
+ if (elementName == _("eventData")) {
+ loadEventData(stream);
+ break;
+ }
+
+ if (elementName == _("profilerDataModel")) {
+ loadProfilerDataModel(stream);
+ break;
+ }
+
+ if (elementName == _("v8profile")) {
+ if (m_v8Model)
+ m_v8Model->load(stream);
+ break;
+ }
+
+ break;
+ }
+ default: break;
+ }
+ }
+
+ if (stream.hasError()) {
+ emit error(tr("Error while parsing trace data file: %1").arg(stream.errorString()));
+ return false;
+ } else {
+ processQmlEvents();
+
+ return true;
+ }
+}
+
+void QmlProfilerFileReader::loadEventData(QXmlStreamReader &stream)
+{
+ QTC_ASSERT(stream.name() == _("eventData"), return);
+
+ QXmlStreamAttributes attributes = stream.attributes();
+ if (attributes.hasAttribute(_("totalTime"))) {
+ // not used any more
+ }
+
+ int eventIndex = -1;
+ QmlEvent event = {
+ QString(), // displayname
+ QString(), // filename
+ QString(), // details
+ Painting, // type
+ QmlBinding, // bindingType, set for backwards compatibility
+ 0, // line
+ 0 // column
+ };
+ const QmlEvent defaultEvent = event;
+
+ while (!stream.atEnd() && !stream.hasError()) {
+ QXmlStreamReader::TokenType token = stream.readNext();
+ const QStringRef elementName = stream.name();
+
+ switch (token) {
+ case QXmlStreamReader::StartElement: {
+ if (elementName == _("event")) {
+ event = defaultEvent;
+
+ const QXmlStreamAttributes attributes = stream.attributes();
+ if (attributes.hasAttribute(_("index"))) {
+ eventIndex = attributes.value(_("index")).toString().toInt();
+ } else {
+ // ignore event
+ eventIndex = -1;
+ }
+ break;
+ }
+
+ stream.readNext();
+ if (stream.tokenType() != QXmlStreamReader::Characters)
+ break;
+
+ const QString readData = stream.text().toString();
+
+ if (elementName == _("displayname")) {
+ event.displayName = readData;
+ break;
+ }
+
+ if (elementName == _("type")) {
+ event.type = qmlEventTypeAsEnum(readData);
+ break;
+ }
+
+ if (elementName == _("filename")) {
+ event.filename = readData;
+ break;
+ }
+
+ if (elementName == _("line")) {
+ event.line = readData.toInt();
+ break;
+ }
+
+ if (elementName == _("column")) {
+ event.column = readData.toInt();
+ break;
+ }
+
+ if (elementName == _("details")) {
+ event.details = readData;
+ break;
+ }
+
+ if (elementName == _("bindingType") ||
+ elementName == _("animationFrame") ||
+ elementName == _("cacheEventType") ||
+ elementName == _("sgEventType")) {
+ event.bindingType = readData.toInt();
+ break;
+ }
+
+ break;
+ }
+ case QXmlStreamReader::EndElement: {
+ if (elementName == _("event")) {
+ if (eventIndex >= 0) {
+ if (eventIndex >= m_qmlEvents.size())
+ m_qmlEvents.resize(eventIndex + 1);
+ m_qmlEvents[eventIndex] = event;
+ }
+ break;
+ }
+
+ if (elementName == _("eventData")) {
+ // done reading eventData
+ return;
+ }
+ break;
+ }
+ default: break;
+ } // switch
+ }
+}
+
+void QmlProfilerFileReader::loadProfilerDataModel(QXmlStreamReader &stream)
+{
+ QTC_ASSERT(stream.name() == _("profilerDataModel"), return);
+
+ while (!stream.atEnd() && !stream.hasError()) {
+ QXmlStreamReader::TokenType token = stream.readNext();
+ const QStringRef elementName = stream.name();
+
+ switch (token) {
+ case QXmlStreamReader::StartElement: {
+ if (elementName == _("range")) {
+ Range range = { 0, 0, 0, 0, 0, 0, 0 };
+
+ const QXmlStreamAttributes attributes = stream.attributes();
+ if (!attributes.hasAttribute(_("startTime"))
+ || !attributes.hasAttribute(_("eventIndex"))) {
+ // ignore incomplete entry
+ continue;
+ }
+
+ range.startTime = attributes.value(_("startTime")).toString().toLongLong();
+ if (attributes.hasAttribute(_("duration")))
+ range.duration = attributes.value(_("duration")).toString().toLongLong();
+
+ // attributes for special events
+ if (attributes.hasAttribute(_("framerate")))
+ range.numericData1 = attributes.value(_("framerate")).toString().toLongLong();
+ if (attributes.hasAttribute(_("animationcount")))
+ range.numericData2 = attributes.value(_("animationcount")).toString().toLongLong();
+ if (attributes.hasAttribute(_("width")))
+ range.numericData1 = attributes.value(_("width")).toString().toLongLong();
+ if (attributes.hasAttribute(_("height")))
+ range.numericData2 = attributes.value(_("height")).toString().toLongLong();
+ if (attributes.hasAttribute(_("refCount")))
+ range.numericData3 = attributes.value(_("refCount")).toString().toLongLong();
+ if (attributes.hasAttribute(_("timing1")))
+ range.numericData1 = attributes.value(_("timing1")).toString().toLongLong();
+ if (attributes.hasAttribute(_("timing2")))
+ range.numericData2 = attributes.value(_("timing2")).toString().toLongLong();
+ if (attributes.hasAttribute(_("timing3")))
+ range.numericData3 = attributes.value(_("timing3")).toString().toLongLong();
+ if (attributes.hasAttribute(_("timing4")))
+ range.numericData4 = attributes.value(_("timing4")).toString().toLongLong();
+ if (attributes.hasAttribute(_("timing5")))
+ range.numericData5 = attributes.value(_("timing5")).toString().toLongLong();
+
+
+ int eventIndex = attributes.value(_("eventIndex")).toString().toInt();
+
+
+ m_ranges.append(QPair<Range,int>(range, eventIndex));
+ }
+ break;
+ }
+ case QXmlStreamReader::EndElement: {
+ if (elementName == _("profilerDataModel")) {
+ // done reading profilerDataModel
+ return;
+ }
+ break;
+ }
+ default: break;
+ } // switch
+ }
+}
+
+void QmlProfilerFileReader::processQmlEvents()
+{
+ for (int i = 0; i < m_ranges.size(); ++i) {
+ Range range = m_ranges[i].first;
+ int eventIndex = m_ranges[i].second;
+
+ if (eventIndex < 0 || eventIndex >= m_qmlEvents.size()) {
+ qWarning() << ".qtd file - range index" << eventIndex
+ << "is outside of bounds (0, " << m_qmlEvents.size() << ")";
+ continue;
+ }
+
+ QmlEvent &event = m_qmlEvents[eventIndex];
+
+ emit rangedEvent(event.type, event.bindingType, range.startTime, range.duration,
+ QStringList(event.displayName),
+ QmlEventLocation(event.filename, event.line, event.column),
+ range.numericData1,range.numericData2, range.numericData3, range.numericData4, range.numericData5);
+
+ }
+}
+
+QmlProfilerFileWriter::QmlProfilerFileWriter(QObject *parent) :
+ QObject(parent),
+ m_startTime(0),
+ m_endTime(0),
+ m_measuredTime(0),
+ m_v8Model(0)
+{
+ m_acceptedTypes << QmlDebug::Compiling << QmlDebug::Creating << QmlDebug::Binding << QmlDebug::HandlingSignal;
+}
+
+void QmlProfilerFileWriter::setTraceTime(qint64 startTime, qint64 endTime, qint64 measuredTime)
+{
+ m_startTime = startTime;
+ m_endTime = endTime;
+ m_measuredTime = measuredTime;
+}
+
+void QmlProfilerFileWriter::setV8DataModel(QV8ProfilerDataModel *dataModel)
+{
+ m_v8Model = dataModel;
+}
+
+void QmlProfilerFileWriter::setQmlEvents(const QVector<QmlProfilerSimpleModel::QmlEventData> &events)
+{
+ foreach (const QmlProfilerSimpleModel::QmlEventData &event, events) {
+ const QString hashStr = QmlProfilerSimpleModel::getHashString(event);
+ if (!m_qmlEvents.contains(hashStr)) {
+ QmlEvent e = { event.displayName,
+ event.location.filename,
+ event.data.join(_("")),
+ static_cast<QmlDebug::QmlEventType>(event.eventType),
+ event.bindingType,
+ event.location.line,
+ event.location.column
+ };
+ m_qmlEvents.insert(hashStr, e);
+ }
+
+ Range r = { event.startTime, event.duration, event.numericData1, event.numericData2, event.numericData3, event.numericData4, event.numericData5 };
+ m_ranges.append(QPair<Range, QString>(r, hashStr));
+ }
+
+ calculateMeasuredTime(events);
+}
+
+void QmlProfilerFileWriter::save(QIODevice *device)
+{
+ QXmlStreamWriter stream(device);
+
+ stream.setAutoFormatting(true);
+ stream.writeStartDocument();
+
+ stream.writeStartElement(_("trace"));
+ stream.writeAttribute(_("version"), _(PROFILER_FILE_VERSION));
+
+ stream.writeAttribute(_("traceStart"), QString::number(m_startTime));
+ stream.writeAttribute(_("traceEnd"), QString::number(m_endTime));
+
+ stream.writeStartElement(_("eventData"));
+ stream.writeAttribute(_("totalTime"), QString::number(m_measuredTime));
+
+ QHash<QString,QmlEvent>::const_iterator eventIter = m_qmlEvents.constBegin();
+ for (; eventIter != m_qmlEvents.constEnd(); ++eventIter) {
+ QmlEvent event = eventIter.value();
+
+ stream.writeStartElement(_("event"));
+ stream.writeAttribute(_("index"), QString::number(m_qmlEvents.keys().indexOf(eventIter.key())));
+ stream.writeTextElement(_("displayname"), event.displayName);
+ stream.writeTextElement(_("type"), qmlEventTypeAsString(event.type));
+ if (!event.filename.isEmpty()) {
+ stream.writeTextElement(_("filename"), event.filename);
+ stream.writeTextElement(_("line"), QString::number(event.line));
+ stream.writeTextElement(_("column"), QString::number(event.column));
+ }
+ stream.writeTextElement(_("details"), event.details);
+ if (event.type == Binding)
+ stream.writeTextElement(_("bindingType"), QString::number(event.bindingType));
+ if (event.type == Painting && event.bindingType == AnimationFrame)
+ stream.writeTextElement(_("animationFrame"), QString::number(event.bindingType));
+ if (event.type == PixmapCacheEvent)
+ stream.writeTextElement(_("cacheEventType"), QString::number(event.bindingType));
+ if (event.type == SceneGraphFrameEvent)
+ stream.writeTextElement(_("sgEventType"), QString::number(event.bindingType));
+ stream.writeEndElement();
+ }
+ stream.writeEndElement(); // eventData
+
+ stream.writeStartElement(_("profilerDataModel"));
+
+ QVector<QPair<Range, QString> >::const_iterator rangeIter = m_ranges.constBegin();
+ for (; rangeIter != m_ranges.constEnd(); ++rangeIter) {
+ Range range = rangeIter->first;
+ QString eventHash = rangeIter->second;
+
+ stream.writeStartElement(_("range"));
+ stream.writeAttribute(_("startTime"), QString::number(range.startTime));
+ if (range.duration > 0) // no need to store duration of instantaneous events
+ stream.writeAttribute(_("duration"), QString::number(range.duration));
+ stream.writeAttribute(_("eventIndex"), QString::number(m_qmlEvents.keys().indexOf(eventHash)));
+
+ QmlEvent event = m_qmlEvents.value(eventHash);
+
+ // special: animation event
+ if (event.type == QmlDebug::Painting && event.bindingType == QmlDebug::AnimationFrame) {
+
+ stream.writeAttribute(_("framerate"), QString::number(range.numericData1));
+ stream.writeAttribute(_("animationcount"), QString::number(range.numericData2));
+ }
+
+ // special: pixmap cache event
+ if (event.type == QmlDebug::PixmapCacheEvent) {
+ // pixmap image size
+ if (event.bindingType == 0) {
+ stream.writeAttribute(_("width"), QString::number(range.numericData1));
+ stream.writeAttribute(_("height"), QString::number(range.numericData2));
+ }
+
+ // reference count (1) / cache size changed (2)
+ if (event.bindingType == 1 || event.bindingType == 2)
+ stream.writeAttribute(_("refCount"), QString::number(range.numericData3));
+ }
+
+ if (event.type == QmlDebug::SceneGraphFrameEvent) {
+ // special: scenegraph frame events
+ if (range.numericData1 > 0)
+ stream.writeAttribute(_("timing1"), QString::number(range.numericData1));
+ if (range.numericData2 > 0)
+ stream.writeAttribute(_("timing2"), QString::number(range.numericData2));
+ if (range.numericData3 > 0)
+ stream.writeAttribute(_("timing3"), QString::number(range.numericData3));
+ if (range.numericData4 > 0)
+ stream.writeAttribute(_("timing4"), QString::number(range.numericData4));
+ if (range.numericData5 > 0)
+ stream.writeAttribute(_("timing5"), QString::number(range.numericData5));
+ }
+ stream.writeEndElement();
+ }
+ stream.writeEndElement(); // profilerDataModel
+
+ m_v8Model->save(stream);
+
+ stream.writeEndElement(); // trace
+ stream.writeEndDocument();
+}
+
+void QmlProfilerFileWriter::calculateMeasuredTime(const QVector<QmlProfilerSimpleModel::QmlEventData> &events)
+{
+ // measured time isn't used, but old clients might still need it
+ // -> we calculate it explicitly
+
+ qint64 duration = 0;
+
+ QHash<int, qint64> endtimesPerLevel;
+ int level = QmlDebug::Constants::QML_MIN_LEVEL;
+ endtimesPerLevel[0] = 0;
+
+ foreach (const QmlProfilerSimpleModel::QmlEventData &event, events) {
+ // whitelist
+ if (!m_acceptedTypes.contains(event.eventType))
+ continue;
+
+ // level computation
+ if (endtimesPerLevel[level] > event.startTime) {
+ level++;
+ } else {
+ while (level > QmlDebug::Constants::QML_MIN_LEVEL && endtimesPerLevel[level-1] <= event.startTime)
+ level--;
+ }
+ endtimesPerLevel[level] = event.startTime + event.duration;
+ if (level == QmlDebug::Constants::QML_MIN_LEVEL) {
+ duration += event.duration;
+ }
+ }
+
+ m_measuredTime = duration;
+}
+
+
+} // namespace Internal
+} // namespace QmlProfiler
diff --git a/src/plugins/qmlprofiler/qmlprofilertracefile.h b/src/plugins/qmlprofiler/qmlprofilertracefile.h
new file mode 100644
index 0000000000..f4e1b71d10
--- /dev/null
+++ b/src/plugins/qmlprofiler/qmlprofilertracefile.h
@@ -0,0 +1,134 @@
+/****************************************************************************
+**
+** 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 QMLPROFILERTRACEFILE_H
+#define QMLPROFILERTRACEFILE_H
+
+#include <QObject>
+#include <QVector>
+#include <QString>
+
+#include <qmldebug/qmlprofilereventlocation.h>
+#include <qmldebug/qmlprofilereventtypes.h>
+
+#include "qmlprofilersimplemodel.h"
+#include "qv8profilerdatamodel.h"
+
+QT_FORWARD_DECLARE_CLASS(QIODevice)
+QT_FORWARD_DECLARE_CLASS(QXmlStreamReader)
+
+
+namespace QmlProfiler {
+namespace Internal {
+
+
+struct QmlEvent {
+ QString displayName;
+ QString filename;
+ QString details;
+ QmlDebug::QmlEventType type;
+ int bindingType;
+ int line;
+ int column;
+};
+
+struct Range {
+ qint64 startTime;
+ qint64 duration;
+
+ // numeric data used by animations, pixmap cache, scenegraph
+ qint64 numericData1;
+ qint64 numericData2;
+ qint64 numericData3;
+ qint64 numericData4;
+ qint64 numericData5;
+};
+
+class QmlProfilerFileReader : public QObject
+{
+ Q_OBJECT
+
+public:
+ explicit QmlProfilerFileReader(QObject *parent = 0);
+
+ void setV8DataModel(QV8ProfilerDataModel *dataModel);
+
+ bool load(QIODevice *device);
+
+signals:
+ void traceStartTime(qint64 traceStartTime);
+ void traceEndTime(qint64 traceStartTime);
+
+ void rangedEvent(int type, int bindingType, qint64 startTime, qint64 length,
+ const QStringList &data, const QmlDebug::QmlEventLocation &location,
+ qint64 param1, qint64 param2, qint64 param3, qint64 param4, qint64 param5);
+ void error(const QString &error);
+
+private:
+ void loadEventData(QXmlStreamReader &reader);
+ void loadProfilerDataModel(QXmlStreamReader &reader);
+
+ void processQmlEvents();
+
+
+ QV8ProfilerDataModel *m_v8Model;
+ QVector<QmlEvent> m_qmlEvents;
+ QVector<QPair<Range, int> > m_ranges;
+};
+
+
+class QmlProfilerFileWriter : public QObject
+{
+ Q_OBJECT
+
+public:
+ explicit QmlProfilerFileWriter(QObject *parent = 0);
+
+ void setTraceTime(qint64 startTime, qint64 endTime, qint64 measturedTime);
+ void setV8DataModel(QV8ProfilerDataModel *dataModel);
+ void setQmlEvents(const QVector<QmlProfilerSimpleModel::QmlEventData> &events);
+
+ void save(QIODevice *device);
+
+private:
+ void calculateMeasuredTime(const QVector<QmlProfilerSimpleModel::QmlEventData> &events);
+
+
+ qint64 m_startTime, m_endTime, m_measuredTime;
+ QV8ProfilerDataModel *m_v8Model;
+ QHash<QString,QmlEvent> m_qmlEvents;
+ QVector<QPair<Range, QString> > m_ranges;
+ QVector <int> m_acceptedTypes;
+};
+
+
+} // namespace Internal
+} // namespace QmlProfiler
+
+#endif // QMLPROFILERTRACEFILE_H
diff --git a/src/plugins/qmlprofiler/qmlprofilertraceview.cpp b/src/plugins/qmlprofiler/qmlprofilertraceview.cpp
index 5fbad1247a..76874e9272 100644
--- a/src/plugins/qmlprofiler/qmlprofilertraceview.cpp
+++ b/src/plugins/qmlprofiler/qmlprofilertraceview.cpp
@@ -30,17 +30,19 @@
#include "qmlprofilertraceview.h"
#include "qmlprofilertool.h"
#include "qmlprofilerstatemanager.h"
-#include "qmlprofilerdatamodel.h"
+#include "qmlprofilermodelmanager.h"
+#include "qmlprofilertimelinemodelproxy.h"
+#include "timelinemodelaggregator.h"
// Needed for the load&save actions in the context menu
#include <analyzerbase/ianalyzertool.h>
-// Comunication with the other views (limit events to range)
+// Communication with the other views (limit events to range)
#include "qmlprofilerviewmanager.h"
#include <utils/styledbar.h>
-#include <QDeclarativeContext>
+#include <QQmlContext>
#include <QToolButton>
#include <QEvent>
#include <QVBoxLayout>
@@ -48,6 +50,7 @@
#include <QScrollBar>
#include <QSlider>
#include <QMenu>
+#include <QQuickItem>
#include <math.h>
@@ -84,23 +87,22 @@ void ZoomControl::setRange(qint64 startTime, qint64 endTime)
}
/////////////////////////////////////////////////////////
-ScrollableDeclarativeView::ScrollableDeclarativeView(QWidget *parent)
- : QDeclarativeView(parent)
+ScrollableQuickView::ScrollableQuickView(QQuickView *parent)
+ : QQuickView(parent)
{
}
-ScrollableDeclarativeView::~ScrollableDeclarativeView()
+ScrollableQuickView::~ScrollableQuickView()
{
}
-void ScrollableDeclarativeView::scrollContentsBy(int dx, int dy)
+void ScrollableQuickView::scrollContentsBy(int /*dx*/, int dy)
{
// special workaround to track the scrollbar
if (rootObject()) {
int scrollY = rootObject()->property("scrollY").toInt();
rootObject()->setProperty("scrollY", QVariant(scrollY - dy));
}
- QDeclarativeView::scrollContentsBy(dx,dy);
}
/////////////////////////////////////////////////////////
@@ -108,6 +110,13 @@ class QmlProfilerTraceView::QmlProfilerTraceViewPrivate
{
public:
QmlProfilerTraceViewPrivate(QmlProfilerTraceView *qq) : q(qq) {}
+ ~QmlProfilerTraceViewPrivate()
+ {
+ delete m_mainView;
+ delete m_timebar;
+ delete m_overview;
+ }
+
QmlProfilerTraceView *q;
QmlProfilerStateManager *m_profilerState;
@@ -116,10 +125,12 @@ public:
QSize m_sizeHint;
- ScrollableDeclarativeView *m_mainView;
- QDeclarativeView *m_timebar;
- QDeclarativeView *m_overview;
- QmlProfilerDataModel *m_profilerDataModel;
+ ScrollableQuickView *m_mainView;
+ QQuickView *m_timebar;
+ QQuickView *m_overview;
+ QmlProfilerModelManager *m_modelManager;
+ TimelineModelAggregator *m_modelProxy;
+
ZoomControl *m_zoomControl;
@@ -129,7 +140,7 @@ public:
int m_currentZoomLevel;
};
-QmlProfilerTraceView::QmlProfilerTraceView(QWidget *parent, Analyzer::IAnalyzerTool *profilerTool, QmlProfilerViewManager *container, QmlProfilerDataModel *model, QmlProfilerStateManager *profilerState)
+QmlProfilerTraceView::QmlProfilerTraceView(QWidget *parent, Analyzer::IAnalyzerTool *profilerTool, QmlProfilerViewManager *container, QmlProfilerModelManager *modelManager, QmlProfilerStateManager *profilerState)
: QWidget(parent), d(new QmlProfilerTraceViewPrivate(this))
{
setObjectName(QLatin1String("QML Profiler"));
@@ -141,52 +152,52 @@ QmlProfilerTraceView::QmlProfilerTraceView(QWidget *parent, Analyzer::IAnalyzerT
groupLayout->setContentsMargins(0, 0, 0, 0);
groupLayout->setSpacing(0);
- d->m_mainView = new ScrollableDeclarativeView(this);
- d->m_mainView->setResizeMode(QDeclarativeView::SizeViewToRootObject);
- d->m_mainView->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
- d->m_mainView->setBackgroundBrush(QBrush(Qt::white));
- d->m_mainView->setAlignment(Qt::AlignLeft | Qt::AlignTop);
- d->m_mainView->setFocus();
+ d->m_mainView = new ScrollableQuickView();
+ d->m_mainView->setResizeMode(QQuickView::SizeViewToRootObject);
+ QWidget *mainViewContainer = QWidget::createWindowContainer(d->m_mainView);
MouseWheelResizer *resizer = new MouseWheelResizer(this);
connect(resizer,SIGNAL(mouseWheelMoved(int,int,int)), this, SLOT(mouseWheelMoved(int,int,int)));
- d->m_mainView->viewport()->installEventFilter(resizer);
QHBoxLayout *toolsLayout = new QHBoxLayout;
- d->m_timebar = new QDeclarativeView(this);
- d->m_timebar->setResizeMode(QDeclarativeView::SizeRootObjectToView);
- d->m_timebar->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
- d->m_timebar->setFixedHeight(24);
+ d->m_timebar = new QQuickView();
+ d->m_timebar->setResizeMode(QQuickView::SizeRootObjectToView);
+ QWidget *timeBarContainer = QWidget::createWindowContainer(d->m_timebar);
+ timeBarContainer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
+ timeBarContainer->setFixedHeight(24);
- d->m_overview = new QDeclarativeView(this);
- d->m_overview->setResizeMode(QDeclarativeView::SizeRootObjectToView);
- d->m_overview->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
- d->m_overview->setMaximumHeight(50);
+ d->m_overview = new QQuickView();
+ d->m_overview->setResizeMode(QQuickView::SizeRootObjectToView);
+ QWidget *overviewContainer = QWidget::createWindowContainer(d->m_overview);
+ overviewContainer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
+ overviewContainer->setMaximumHeight(50);
d->m_zoomToolbar = createZoomToolbar();
d->m_zoomToolbar->move(0, d->m_timebar->height());
d->m_zoomToolbar->setVisible(false);
toolsLayout->addWidget(createToolbar());
- toolsLayout->addWidget(d->m_timebar);
+ toolsLayout->addWidget(timeBarContainer);
emit enableToolbar(false);
groupLayout->addLayout(toolsLayout);
- groupLayout->addWidget(d->m_mainView);
- groupLayout->addWidget(d->m_overview);
+ groupLayout->addWidget(mainViewContainer);
+ groupLayout->addWidget(overviewContainer);
setLayout(groupLayout);
d->m_profilerTool = profilerTool;
d->m_viewContainer = container;
- d->m_profilerDataModel = model;
- connect(d->m_profilerDataModel, SIGNAL(stateChanged()),
+ d->m_modelManager = modelManager;
+ d->m_modelProxy = new TimelineModelAggregator(this);
+ d->m_modelProxy->setModelManager(modelManager);
+ connect(d->m_modelManager, SIGNAL(stateChanged()),
this, SLOT(profilerDataModelStateChanged()));
- d->m_mainView->rootContext()->setContextProperty(QLatin1String("qmlProfilerDataModel"),
- d->m_profilerDataModel);
- d->m_overview->rootContext()->setContextProperty(QLatin1String("qmlProfilerDataModel"),
- d->m_profilerDataModel);
+ d->m_mainView->rootContext()->setContextProperty(QLatin1String("qmlProfilerModelProxy"),
+ d->m_modelProxy);
+ d->m_overview->rootContext()->setContextProperty(QLatin1String("qmlProfilerModelProxy"),
+ d->m_modelProxy);
d->m_profilerState = profilerState;
connect(d->m_profilerState, SIGNAL(stateChanged()),
@@ -218,7 +229,7 @@ void QmlProfilerTraceView::reset()
d->m_overview->setSource(QUrl(QLatin1String("qrc:/qmlprofiler/Overview.qml")));
d->m_mainView->setSource(QUrl(QLatin1String("qrc:/qmlprofiler/MainView.qml")));
- QGraphicsObject *rootObject = d->m_mainView->rootObject();
+ QQuickItem *rootObject = d->m_mainView->rootObject();
rootObject->setProperty("width", QVariant(width()));
rootObject->setProperty("candidateHeight", QVariant(height() - d->m_timebar->height() - d->m_overview->height()));
@@ -339,7 +350,7 @@ QWidget *QmlProfilerTraceView::createZoomToolbar()
/////////////////////////////////////////////////////////
bool QmlProfilerTraceView::hasValidSelection() const
{
- QGraphicsObject *rootObject = d->m_mainView->rootObject();
+ QQuickItem *rootObject = d->m_mainView->rootObject();
if (rootObject)
return rootObject->property("selectionRangeReady").toBool();
return false;
@@ -347,7 +358,7 @@ bool QmlProfilerTraceView::hasValidSelection() const
qint64 QmlProfilerTraceView::selectionStart() const
{
- QGraphicsObject *rootObject = d->m_mainView->rootObject();
+ QQuickItem *rootObject = d->m_mainView->rootObject();
if (rootObject)
return rootObject->property("selectionRangeStart").toLongLong();
return 0;
@@ -355,7 +366,7 @@ qint64 QmlProfilerTraceView::selectionStart() const
qint64 QmlProfilerTraceView::selectionEnd() const
{
- QGraphicsObject *rootObject = d->m_mainView->rootObject();
+ QQuickItem *rootObject = d->m_mainView->rootObject();
if (rootObject)
return rootObject->property("selectionRangeEnd").toLongLong();
return 0;
@@ -372,19 +383,32 @@ void QmlProfilerTraceView::clearDisplay()
QMetaObject::invokeMethod(d->m_overview->rootObject(), "clearDisplay");
}
-void QmlProfilerTraceView::selectNextEventWithId(int eventId)
+void QmlProfilerTraceView::selectNextEventByHash(const QString &hash)
{
- QGraphicsObject *rootObject = d->m_mainView->rootObject();
+ QQuickItem *rootObject = d->m_mainView->rootObject();
+
if (rootObject)
- QMetaObject::invokeMethod(rootObject, "selectNextWithId",
- Q_ARG(QVariant,QVariant(eventId)));
+ QMetaObject::invokeMethod(rootObject, "selectNextByHash",
+ Q_ARG(QVariant,QVariant(hash)));
+}
+
+void QmlProfilerTraceView::selectNextEventByLocation(const QString &filename, const int line, const int column)
+{
+ int eventId = d->m_modelProxy->getEventIdForLocation(filename, line, column);
+
+ if (eventId != -1) {
+ QQuickItem *rootObject = d->m_mainView->rootObject();
+ if (rootObject)
+ QMetaObject::invokeMethod(rootObject, "selectNextById",
+ Q_ARG(QVariant,QVariant(eventId)));
+ }
}
/////////////////////////////////////////////////////////
// Goto source location
void QmlProfilerTraceView::updateCursorPosition()
{
- QGraphicsObject *rootObject = d->m_mainView->rootObject();
+ QQuickItem *rootObject = d->m_mainView->rootObject();
emit gotoSourceLocation(rootObject->property("fileName").toString(),
rootObject->property("lineNumber").toInt(),
rootObject->property("columnNumber").toInt());
@@ -394,7 +418,7 @@ void QmlProfilerTraceView::updateCursorPosition()
// Toolbar buttons
void QmlProfilerTraceView::toggleRangeMode(bool active)
{
- QGraphicsObject *rootObject = d->m_mainView->rootObject();
+ QQuickItem *rootObject = d->m_mainView->rootObject();
bool rangeMode = rootObject->property("selectionRangeMode").toBool();
if (active != rangeMode) {
if (active)
@@ -417,7 +441,7 @@ void QmlProfilerTraceView::updateRangeButton()
void QmlProfilerTraceView::toggleLockMode(bool active)
{
- QGraphicsObject *rootObject = d->m_mainView->rootObject();
+ QQuickItem *rootObject = d->m_mainView->rootObject();
bool lockMode = !rootObject->property("selectionLocked").toBool();
if (active != lockMode) {
rootObject->setProperty("selectionLocked", QVariant(!active));
@@ -444,14 +468,14 @@ void QmlProfilerTraceView::setZoomLevel(int zoomLevel)
void QmlProfilerTraceView::updateRange()
{
- if (!d->m_profilerDataModel)
+ if (!d->m_modelManager)
return;
qreal duration = d->m_zoomControl->endTime() - d->m_zoomControl->startTime();
if (duration <= 0)
return;
- if (d->m_profilerDataModel->traceDuration() <= 0)
+ if (d->m_modelManager->traceTime()->duration() <= 0)
return;
- int newLevel = pow(duration / d->m_profilerDataModel->traceDuration(), 1/sliderExp) * sliderTicks;
+ int newLevel = pow(duration / d->m_modelManager->traceTime()->duration(), 1/sliderExp) * sliderTicks;
if (d->m_currentZoomLevel != newLevel) {
d->m_currentZoomLevel = newLevel;
emit zoomLevelChanged(newLevel);
@@ -461,7 +485,7 @@ void QmlProfilerTraceView::updateRange()
void QmlProfilerTraceView::mouseWheelMoved(int mouseX, int mouseY, int wheelDelta)
{
Q_UNUSED(mouseY);
- QGraphicsObject *rootObject = d->m_mainView->rootObject();
+ QQuickItem *rootObject = d->m_mainView->rootObject();
if (rootObject) {
QMetaObject::invokeMethod(rootObject, "wheelZoom",
Q_ARG(QVariant, QVariant(mouseX)),
@@ -474,15 +498,14 @@ void QmlProfilerTraceView::updateToolTip(const QString &text)
setToolTip(text);
}
-void QmlProfilerTraceView::updateVerticalScroll(int newPosition)
+void QmlProfilerTraceView::updateVerticalScroll(int /*newPosition*/)
{
- d->m_mainView->verticalScrollBar()->setValue(newPosition);
}
void QmlProfilerTraceView::resizeEvent(QResizeEvent *event)
{
QWidget::resizeEvent(event);
- QGraphicsObject *rootObject = d->m_mainView->rootObject();
+ QQuickItem *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();
@@ -513,7 +536,7 @@ void QmlProfilerTraceView::contextMenuEvent(QContextMenuEvent *ev)
if (d->m_viewContainer->hasGlobalStats())
getGlobalStatsAction->setEnabled(false);
- if (d->m_profilerDataModel->count() > 0) {
+ if (!d->m_modelProxy->isEmpty()) {
menu.addSeparator();
viewAllAction = menu.addAction(tr("Reset Zoom"));
}
@@ -523,8 +546,8 @@ void QmlProfilerTraceView::contextMenuEvent(QContextMenuEvent *ev)
if (selectedAction) {
if (selectedAction == viewAllAction) {
d->m_zoomControl->setRange(
- d->m_profilerDataModel->traceStartTime(),
- d->m_profilerDataModel->traceEndTime());
+ d->m_modelManager->traceTime()->startTime(),
+ d->m_modelManager->traceTime()->endTime());
}
if (selectedAction == getLocalStatsAction) {
d->m_viewContainer->getStatisticsInRange(
@@ -532,9 +555,7 @@ void QmlProfilerTraceView::contextMenuEvent(QContextMenuEvent *ev)
d->m_viewContainer->selectionEnd());
}
if (selectedAction == getGlobalStatsAction) {
- d->m_viewContainer->getStatisticsInRange(
- d->m_profilerDataModel->traceStartTime(),
- d->m_profilerDataModel->traceEndTime());
+ d->m_viewContainer->getStatisticsInRange(-1, -1);
}
}
}
@@ -543,14 +564,14 @@ void QmlProfilerTraceView::contextMenuEvent(QContextMenuEvent *ev)
// Tell QML the state of the profiler
void QmlProfilerTraceView::setRecording(bool recording)
{
- QGraphicsObject *rootObject = d->m_mainView->rootObject();
+ QQuickItem *rootObject = d->m_mainView->rootObject();
if (rootObject)
rootObject->setProperty("recordingEnabled", QVariant(recording));
}
void QmlProfilerTraceView::setAppKilled()
{
- QGraphicsObject *rootObject = d->m_mainView->rootObject();
+ QQuickItem *rootObject = d->m_mainView->rootObject();
if (rootObject)
rootObject->setProperty("appKilled",QVariant(true));
}
@@ -558,19 +579,15 @@ void QmlProfilerTraceView::setAppKilled()
// Profiler State
void QmlProfilerTraceView::profilerDataModelStateChanged()
{
- switch (d->m_profilerDataModel->currentState()) {
- case QmlProfilerDataModel::Empty :
- emit enableToolbar(false);
- break;
- case QmlProfilerDataModel::AcquiringData :
- // nothing to be done
+ switch (d->m_modelManager->state()) {
+ case QmlProfilerDataState::Empty:
+ emit enableToolbar(false);
break;
- case QmlProfilerDataModel::ProcessingData :
- // nothing to be done
+ case QmlProfilerDataState::AcquiringData: break;
+ case QmlProfilerDataState::ProcessingData: break;
+ case QmlProfilerDataState::Done:
+ emit enableToolbar(true);
break;
- case QmlProfilerDataModel::Done :
- emit enableToolbar(true);
- break;
default:
break;
}
@@ -580,7 +597,7 @@ void QmlProfilerTraceView::profilerStateChanged()
{
switch (d->m_profilerState->currentState()) {
case QmlProfilerStateManager::AppKilled : {
- if (d->m_profilerDataModel->currentState() == QmlProfilerDataModel::AcquiringData)
+ if (d->m_modelManager->state() == QmlProfilerDataState::AcquiringData)
setAppKilled();
break;
}
diff --git a/src/plugins/qmlprofiler/qmlprofilertraceview.h b/src/plugins/qmlprofiler/qmlprofilertraceview.h
index 0ff15025ab..985838f7aa 100644
--- a/src/plugins/qmlprofiler/qmlprofilertraceview.h
+++ b/src/plugins/qmlprofiler/qmlprofilertraceview.h
@@ -30,18 +30,20 @@
#ifndef QMLPROFILERTRACEVIEW_H
#define QMLPROFILERTRACEVIEW_H
-#include <QDeclarativeView>
+#include <QQuickView>
+#include <QWidget>
namespace Analyzer {
class IAnalyzerTool;
}
namespace QmlProfiler {
+
+class QmlProfilerModelManager;
namespace Internal {
class QmlProfilerStateManager;
class QmlProfilerViewManager;
-class QmlProfilerDataModel;
// capture mouse wheel events
class MouseWheelResizer : public QObject {
@@ -73,22 +75,23 @@ private:
qint64 m_endTime;
};
-class ScrollableDeclarativeView : public QDeclarativeView
+class ScrollableQuickView : public QQuickView
{
Q_OBJECT
public:
- explicit ScrollableDeclarativeView(QWidget *parent = 0);
- ~ScrollableDeclarativeView();
+ explicit ScrollableQuickView(QQuickView *parent = 0);
+ ~ScrollableQuickView();
protected:
void scrollContentsBy(int dx, int dy);
};
+
class QmlProfilerTraceView : public QWidget
{
Q_OBJECT
public:
- explicit QmlProfilerTraceView(QWidget *parent, Analyzer::IAnalyzerTool *profilerTool, QmlProfilerViewManager *container, QmlProfilerDataModel *model, QmlProfilerStateManager *profilerState);
+ explicit QmlProfilerTraceView(QWidget *parent, Analyzer::IAnalyzerTool *profilerTool, QmlProfilerViewManager *container, QmlProfilerModelManager *modelManager, QmlProfilerStateManager *profilerState);
~QmlProfilerTraceView();
void reset();
@@ -99,7 +102,8 @@ public:
public slots:
void clearDisplay();
- void selectNextEventWithId(int eventId);
+ void selectNextEventByHash(const QString &eventHash);
+ void selectNextEventByLocation(const QString &filename, const int line, const int column);
private slots:
void updateCursorPosition();
diff --git a/src/plugins/qmlprofiler/qmlprofilertreeview.cpp b/src/plugins/qmlprofiler/qmlprofilertreeview.cpp
new file mode 100644
index 0000000000..8c7c4a8e92
--- /dev/null
+++ b/src/plugins/qmlprofiler/qmlprofilertreeview.cpp
@@ -0,0 +1,92 @@
+/****************************************************************************
+**
+** 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 "qmlprofilertreeview.h"
+#include <QCoreApplication>
+#include <QHeaderView>
+
+namespace QmlProfiler {
+namespace Internal {
+
+QmlProfilerTreeView::QmlProfilerTreeView(QWidget *parent)
+ : QTreeView(parent)
+{
+ setFrameStyle(QFrame::NoFrame);
+ header()->setResizeMode(QHeaderView::Interactive);
+ header()->setDefaultSectionSize(100);
+ header()->setMinimumSectionSize(50);
+}
+
+
+// Translate from "old" context to keep 2.8 string freeze
+QString QmlProfilerTreeView::displayHeader(Fields header) const
+{
+ static const char ctxt1[] = "QmlProfiler::Internal::QmlProfilerEventsParentsAndChildrenView";
+ static const char ctxt2[] = "QmlProfiler::Internal::QmlProfilerEventsMainView";
+
+ switch (header) {
+ case Callee:
+ return QCoreApplication::translate(ctxt1, "Callee");
+ case CalleeDescription:
+ return QCoreApplication::translate(ctxt1, "Callee Description");
+ case Caller:
+ return QCoreApplication::translate(ctxt1, "Caller");
+ case CallerDescription:
+ return QCoreApplication::translate(ctxt1, "Caller Description");
+ case CallCount:
+ return QCoreApplication::translate(ctxt2, "Calls");
+ case Details:
+ return QCoreApplication::translate(ctxt2, "Details");
+ case Location:
+ return QCoreApplication::translate(ctxt2, "Location");
+ case MaxTime:
+ return QCoreApplication::translate(ctxt2, "Longest Time");
+ case TimePerCall:
+ return QCoreApplication::translate(ctxt2, "Mean Time");
+ case SelfTime:
+ return QCoreApplication::translate(ctxt2, "Self Time");
+ case SelfTimeInPercent:
+ return QCoreApplication::translate(ctxt2, "Self Time in Percent");
+ case MinTime:
+ return QCoreApplication::translate(ctxt2, "Shortest Time");
+ case TimeInPercent:
+ return QCoreApplication::translate(ctxt2, "Time in Percent");
+ case TotalTime:
+ return QCoreApplication::translate(ctxt2, "Total Time");
+ case Type:
+ return QCoreApplication::translate(ctxt2, "Type");
+ case MedianTime:
+ return QCoreApplication::translate(ctxt2, "Median Time");
+ default:
+ return QString();
+ }
+}
+
+} // namespace Internal
+} // namespace QmlProfiler
diff --git a/src/plugins/coreplugin/scriptmanager/scriptmanager_p.h b/src/plugins/qmlprofiler/qmlprofilertreeview.h
index 8a6fb697b7..73b2b5d769 100644
--- a/src/plugins/coreplugin/scriptmanager/scriptmanager_p.h
+++ b/src/plugins/qmlprofiler/qmlprofilertreeview.h
@@ -27,37 +27,46 @@
**
****************************************************************************/
-#ifndef SCRIPTMANAGER_P_H
-#define SCRIPTMANAGER_P_H
+#ifndef QMLPROFILERTREEVIEW
+#define QMLPROFILERTREEVIEW
-#include "scriptmanager.h"
+#include <QTreeView>
-#include <QObject>
-#include <QScriptEngine>
-
-namespace Core {
+namespace QmlProfiler {
namespace Internal {
-class ScriptManagerPrivate : public Core::ScriptManager
+class QmlProfilerTreeView : public QTreeView
{
Q_OBJECT
-public:
- explicit ScriptManagerPrivate(QObject *parent);
-
- bool runScript(const QString &script, QString *errorMessage, Stack *stack);
- bool runScript(const QString &script, QString *errorMessage);
- virtual QScriptEnginePtr scriptEngine() { return ensureEngineInitialized(); }
-
- static QString engineError(const QScriptEnginePtr &scriptEngine);
+protected:
+ QmlProfilerTreeView(QWidget *parent = 0);
-private:
- QScriptEnginePtr ensureEngineInitialized();
- QScriptEnginePtr m_engine;
+ enum Fields {
+ Name,
+ Callee,
+ CalleeDescription,
+ Caller,
+ CallerDescription,
+ CallCount,
+ Details,
+ Location,
+ MaxTime,
+ TimePerCall,
+ SelfTime,
+ SelfTimeInPercent,
+ MinTime,
+ TimeInPercent,
+ TotalTime,
+ Type,
+ MedianTime,
+ MaxFields
+ };
+ QString displayHeader(Fields header) const;
};
} // namespace Internal
-} // namespace Core
+} // namespace QmlProfiler
-#endif // SCRIPTMANAGER_P_H
+#endif // QMLPROFILERTREEVIEW
diff --git a/src/plugins/qmlprofiler/qmlprofilerviewmanager.cpp b/src/plugins/qmlprofiler/qmlprofilerviewmanager.cpp
index 9b9fa32e12..5374b1c3c7 100644
--- a/src/plugins/qmlprofiler/qmlprofilerviewmanager.cpp
+++ b/src/plugins/qmlprofiler/qmlprofilerviewmanager.cpp
@@ -33,8 +33,9 @@
#include "qmlprofilereventview.h"
#include "qmlprofilertool.h"
#include "qmlprofilerstatemanager.h"
-#include "qmlprofilerdatamodel.h"
+#include "qmlprofilermodelmanager.h"
#include "qmlprofilerstatewidget.h"
+#include "qv8profilereventview.h"
#include <utils/qtcassert.h>
#include <utils/fancymainwindow.h>
@@ -53,15 +54,15 @@ public:
QmlProfilerTraceView *traceView;
QmlProfilerEventsWidget *eventsView;
- QmlProfilerEventsWidget *v8profilerView;
+ QV8ProfilerEventsWidget *v8profilerView;
QmlProfilerStateManager *profilerState;
- QmlProfilerDataModel *profilerDataModel;
+ QmlProfilerModelManager *profilerModelManager;
QmlProfilerTool *profilerTool;
};
QmlProfilerViewManager::QmlProfilerViewManager(QObject *parent,
QmlProfilerTool *profilerTool,
- QmlProfilerDataModel *model,
+ QmlProfilerModelManager *modelManager,
QmlProfilerStateManager *profilerState)
: QObject(parent), d(new QmlProfilerViewManagerPrivate(this))
{
@@ -70,7 +71,7 @@ QmlProfilerViewManager::QmlProfilerViewManager(QObject *parent,
d->eventsView = 0;
d->v8profilerView = 0;
d->profilerState = profilerState;
- d->profilerDataModel = model;
+ d->profilerModelManager = modelManager;
d->profilerTool = profilerTool;
createViews();
}
@@ -84,7 +85,8 @@ QmlProfilerViewManager::~QmlProfilerViewManager()
// Views
void QmlProfilerViewManager::createViews()
{
- QTC_ASSERT(d->profilerDataModel, return);
+
+ QTC_ASSERT(d->profilerModelManager, return);
QTC_ASSERT(d->profilerState, return);
Utils::FancyMainWindow *mw = AnalyzerManager::mainWindow();
@@ -92,26 +94,28 @@ void QmlProfilerViewManager::createViews()
d->traceView = new QmlProfilerTraceView(mw,
d->profilerTool,
this,
- d->profilerDataModel,
+ d->profilerModelManager,
d->profilerState);
connect(d->traceView, SIGNAL(gotoSourceLocation(QString,int,int)),
this, SIGNAL(gotoSourceLocation(QString,int,int)));
-
d->traceView->reset();
- d->eventsView = new QmlProfilerEventsWidget(mw, d->profilerTool, this, d->profilerDataModel);
+
+ d->eventsView = new QmlProfilerEventsWidget(mw, d->profilerTool, this,
+ d->profilerModelManager);
connect(d->eventsView, SIGNAL(gotoSourceLocation(QString,int,int)), this,
SIGNAL(gotoSourceLocation(QString,int,int)));
- connect(d->eventsView, SIGNAL(showEventInTimeline(int)), d->traceView,
- SLOT(selectNextEventWithId(int)));
- connect(d->traceView, SIGNAL(selectedEventChanged(int)), d->eventsView,
- SLOT(updateSelectedEvent(int)));
-
- d->v8profilerView = new QmlProfilerEventsWidget(mw, d->profilerTool,
- this, d->profilerDataModel);
- d->v8profilerView->switchToV8View();
+ connect(d->eventsView, SIGNAL(eventSelectedByHash(QString)), d->traceView,
+ SLOT(selectNextEventByHash(QString)));
+ connect(d->traceView, SIGNAL(gotoSourceLocation(QString,int,int)),
+ d->eventsView, SLOT(selectBySourceLocation(QString,int,int)));
+
+ d->v8profilerView = new QV8ProfilerEventsWidget(mw, d->profilerTool, this,
+ d->profilerModelManager);
+ connect(d->traceView, SIGNAL(gotoSourceLocation(QString,int,int)),
+ d->v8profilerView, SLOT(selectBySourceLocation(QString,int,int)));
connect(d->v8profilerView, SIGNAL(gotoSourceLocation(QString,int,int)),
- this, SIGNAL(gotoSourceLocation(QString,int,int)));
+ d->traceView, SLOT(selectNextEventByLocation(QString,int,int)));
connect(d->v8profilerView, SIGNAL(gotoSourceLocation(QString,int,int)),
d->eventsView, SLOT(selectBySourceLocation(QString,int,int)));
connect(d->eventsView, SIGNAL(gotoSourceLocation(QString,int,int)),
@@ -121,8 +125,8 @@ void QmlProfilerViewManager::createViews()
(d->profilerTool, tr("Events"), d->eventsView, Qt::BottomDockWidgetArea);
QDockWidget *timelineDock = AnalyzerManager::createDockWidget
(d->profilerTool, tr("Timeline"), d->traceView, Qt::BottomDockWidgetArea);
- QDockWidget *v8profilerDock = AnalyzerManager::createDockWidget
- (d->profilerTool, tr("JavaScript"), d->v8profilerView, Qt::BottomDockWidgetArea);
+ QDockWidget *v8profilerDock = AnalyzerManager::createDockWidget(
+ d->profilerTool, tr("JavaScript"), d->v8profilerView, Qt::BottomDockWidgetArea);
eventsDock->show();
timelineDock->show();
@@ -132,9 +136,9 @@ void QmlProfilerViewManager::createViews()
mw->tabifyDockWidget(timelineDock, eventsDock);
mw->tabifyDockWidget(eventsDock, v8profilerDock);
- new QmlProfilerStateWidget(d->profilerState, d->profilerDataModel, d->traceView);
- new QmlProfilerStateWidget(d->profilerState, d->profilerDataModel, d->eventsView);
- new QmlProfilerStateWidget(d->profilerState, d->profilerDataModel, d->v8profilerView);
+ new QmlProfilerStateWidget(d->profilerState, d->profilerModelManager, d->eventsView);
+ new QmlProfilerStateWidget(d->profilerState, d->profilerModelManager, d->traceView);
+ new QmlProfilerStateWidget(d->profilerState, d->profilerModelManager, d->v8profilerView);
}
bool QmlProfilerViewManager::hasValidSelection() const
diff --git a/src/plugins/qmlprofiler/qmlprofilerviewmanager.h b/src/plugins/qmlprofiler/qmlprofilerviewmanager.h
index 8b4b2bda8d..122e5bb644 100644
--- a/src/plugins/qmlprofiler/qmlprofilerviewmanager.h
+++ b/src/plugins/qmlprofiler/qmlprofilerviewmanager.h
@@ -33,10 +33,11 @@
#include <QObject>
namespace QmlProfiler {
+class QmlProfilerModelManager;
+
namespace Internal {
class QmlProfilerTool;
-class QmlProfilerDataModel;
class QmlProfilerStateManager;
class QmlProfilerViewManager : public QObject
@@ -45,7 +46,7 @@ class QmlProfilerViewManager : public QObject
public:
explicit QmlProfilerViewManager(QObject *parent,
QmlProfilerTool *profilerTool,
- QmlProfilerDataModel *model,
+ QmlProfilerModelManager *modelManager,
QmlProfilerStateManager *profilerState);
~QmlProfilerViewManager();
diff --git a/src/plugins/qmlprofiler/qv8profilerdatamodel.cpp b/src/plugins/qmlprofiler/qv8profilerdatamodel.cpp
index 482677d31d..fd45bc0e47 100644
--- a/src/plugins/qmlprofiler/qv8profilerdatamodel.cpp
+++ b/src/plugins/qmlprofiler/qv8profilerdatamodel.cpp
@@ -28,12 +28,9 @@
****************************************************************************/
#include "qv8profilerdatamodel.h"
-#include "qmlprofilerdatamodel.h"
#include <QStringList>
-using namespace QmlDebug;
-
QT_BEGIN_NAMESPACE
Q_DECLARE_TYPEINFO(QmlProfiler::Internal::QV8EventData, Q_MOVABLE_TYPE);
Q_DECLARE_TYPEINFO(QmlProfiler::Internal::QV8EventSub, Q_MOVABLE_TYPE);
@@ -66,7 +63,7 @@ QV8EventData &QV8EventData::operator=(const QV8EventData &ref)
totalTime = ref.totalTime;
totalPercent = ref.totalPercent;
selfTime = ref.selfTime;
- selfPercent = ref.selfPercent;
+ SelfTimeInPercent = ref.SelfTimeInPercent;
eventId = ref.eventId;
qDeleteAll(parentHash);
@@ -85,7 +82,7 @@ QV8EventData::QV8EventData()
totalTime = 0;
selfTime = 0;
totalPercent = 0;
- selfPercent = 0;
+ SelfTimeInPercent = 0;
}
QV8EventData::~QV8EventData()
@@ -101,8 +98,6 @@ class QV8ProfilerDataModel::QV8ProfilerDataModelPrivate
public:
QV8ProfilerDataModelPrivate(QV8ProfilerDataModel *qq) {Q_UNUSED(qq);}
- QmlProfilerDataModel *qmlProfilerDataModel;
-
void clearV8RootEvent();
void collectV8Statistics();
@@ -112,13 +107,12 @@ public:
qint64 v8MeasuredTime;
};
-QV8ProfilerDataModel::QV8ProfilerDataModel(QObject *parent,
- QmlProfilerDataModel *profilerDataModel)
- : QObject(parent), d(new QV8ProfilerDataModelPrivate(this))
+QV8ProfilerDataModel::QV8ProfilerDataModel(QObject *parent)
+ : QObject(parent)
+ , d(new QV8ProfilerDataModelPrivate(this))
{
d->v8MeasuredTime = 0;
d->clearV8RootEvent();
- d->qmlProfilerDataModel = profilerDataModel;
}
QV8ProfilerDataModel::~QV8ProfilerDataModel()
@@ -133,6 +127,8 @@ void QV8ProfilerDataModel::clear()
d->v8parents.clear();
d->clearV8RootEvent();
d->v8MeasuredTime = 0;
+
+ emit changed();
}
bool QV8ProfilerDataModel::isEmpty() const
@@ -159,6 +155,11 @@ QList<QV8EventData *> QV8ProfilerDataModel::getV8Events() const
return d->v8EventHash.values();
}
+QString getHashStringForV8Event(const QString &displayName, const QString &function)
+{
+ return QString::fromLatin1("%1:%2").arg(displayName, function);
+}
+
void QV8ProfilerDataModel::addV8Event(int depth,
const QString &function,
const QString &filename,
@@ -168,9 +169,7 @@ void QV8ProfilerDataModel::addV8Event(int depth,
{
QString displayName = filename.mid(filename.lastIndexOf(QLatin1Char('/')) + 1) +
QLatin1Char(':') + QString::number(lineNumber);
- QString hashStr = QmlProfilerDataModel::getHashStringForV8Event(displayName, function);
-
- d->qmlProfilerDataModel->setState(QmlProfilerDataModel::AcquiringData);
+ QString hashStr = getHashStringForV8Event(displayName, function);
// time is given in milliseconds, but internally we store it in microseconds
totalTime *= 1e6;
@@ -223,6 +222,7 @@ void QV8ProfilerDataModel::addV8Event(int depth,
newChildSub->totalTime += totalTime;
}
}
+
}
void QV8ProfilerDataModel::collectV8Statistics()
@@ -250,9 +250,9 @@ void QV8ProfilerDataModel::QV8ProfilerDataModelPrivate::collectV8Statistics()
v8RootEvent.totalTime = v8MeasuredTime + 1;
v8RootEvent.selfTime = 0;
- QString rootEventHash = QmlProfilerDataModel::getHashStringForV8Event(
- QmlProfilerDataModel::rootEventName(),
- QmlProfilerDataModel::rootEventDescription());
+ QString rootEventHash = getHashStringForV8Event(
+ tr("<program>"),
+ tr("Main Program"));
QV8EventData *v8RootEventPointer = v8EventHash[rootEventHash];
if (v8RootEventPointer) {
v8RootEvent = *v8RootEventPointer;
@@ -263,7 +263,7 @@ void QV8ProfilerDataModel::QV8ProfilerDataModelPrivate::collectV8Statistics()
foreach (QV8EventData *v8event, v8EventHash.values()) {
v8event->totalPercent = v8event->totalTime * 100.0 / totalTimes;
- v8event->selfPercent = v8event->selfTime * 100.0 / selfTimes;
+ v8event->SelfTimeInPercent = v8event->selfTime * 100.0 / selfTimes;
}
int index = 0;
@@ -274,25 +274,20 @@ void QV8ProfilerDataModel::QV8ProfilerDataModelPrivate::collectV8Statistics()
} else {
// On empty data, still add a fake root event
clearV8RootEvent();
- v8RootEvent.totalPercent = 100;
- QString rootEventHash = QmlProfilerDataModel::getHashStringForV8Event(
- QmlProfilerDataModel::rootEventName(),
- QmlProfilerDataModel::rootEventDescription());
- v8EventHash[rootEventHash] = new QV8EventData;
- *v8EventHash[rootEventHash] = v8RootEvent;
}
}
void QV8ProfilerDataModel::QV8ProfilerDataModelPrivate::clearV8RootEvent()
{
- v8RootEvent.displayName = QmlProfilerDataModel::rootEventName();
- v8RootEvent.eventHashStr = QmlProfilerDataModel::rootEventName();
- v8RootEvent.functionName = QmlProfilerDataModel::rootEventDescription();
+ v8RootEvent.displayName = tr("<program>");
+ v8RootEvent.eventHashStr = tr("<program>");
+ v8RootEvent.functionName = tr("Main Program");
+
v8RootEvent.line = -1;
v8RootEvent.totalTime = 0;
v8RootEvent.totalPercent = 0;
v8RootEvent.selfTime = 0;
- v8RootEvent.selfPercent = 0;
+ v8RootEvent.SelfTimeInPercent = 0;
v8RootEvent.eventId = -1;
qDeleteAll(v8RootEvent.parentHash.values());
@@ -359,7 +354,7 @@ void QV8ProfilerDataModel::load(QXmlStreamReader &stream)
while (!stream.atEnd() && !stream.hasError()) {
QXmlStreamReader::TokenType token = stream.readNext();
- QString elementName = stream.name().toString();
+ const QStringRef elementName = stream.name();
switch (token) {
case QXmlStreamReader::StartDocument : continue;
case QXmlStreamReader::StartElement : {
@@ -439,7 +434,7 @@ void QV8ProfilerDataModel::load(QXmlStreamReader &stream)
}
default: break;
}
-}
+ }
// backwards compatibility
if (d->v8MeasuredTime == 0)
@@ -472,11 +467,10 @@ void QV8ProfilerDataModel::load(QXmlStreamReader &stream)
}
}
}
-
// store v8 events
foreach (QV8EventData *storedV8Event, v8eventBuffer.values()) {
storedV8Event->eventHashStr =
- QmlProfilerDataModel::getHashStringForV8Event(
+ getHashStringForV8Event(
storedV8Event->displayName, storedV8Event->functionName);
d->v8EventHash[storedV8Event->eventHashStr] = storedV8Event;
}
@@ -485,5 +479,11 @@ void QV8ProfilerDataModel::load(QXmlStreamReader &stream)
}
+void QV8ProfilerDataModel::complete()
+{
+ collectV8Statistics();
+ emit changed();
+}
+
} // namespace Internal
} // namespace QmlProfiler
diff --git a/src/plugins/qmlprofiler/qv8profilerdatamodel.h b/src/plugins/qmlprofiler/qv8profilerdatamodel.h
index b4430613d0..633c2107f2 100644
--- a/src/plugins/qmlprofiler/qv8profilerdatamodel.h
+++ b/src/plugins/qmlprofiler/qv8profilerdatamodel.h
@@ -39,7 +39,6 @@
namespace QmlProfiler {
namespace Internal {
-class QmlProfilerDataModel;
struct QV8EventSub;
struct QV8EventData
@@ -55,7 +54,7 @@ struct QV8EventData
double totalTime; // given in milliseconds
double totalPercent;
double selfTime;
- double selfPercent;
+ double SelfTimeInPercent;
QHash <QString, QV8EventSub *> parentHash;
QHash <QString, QV8EventSub *> childrenHash;
int eventId;
@@ -75,7 +74,7 @@ class QV8ProfilerDataModel : public QObject
{
Q_OBJECT
public:
- explicit QV8ProfilerDataModel(QObject *parent, QmlProfilerDataModel *profilerDataModel);
+ QV8ProfilerDataModel(QObject *parent = 0);
~QV8ProfilerDataModel();
void clear();
@@ -89,6 +88,11 @@ public:
void save(QXmlStreamWriter &stream);
void load(QXmlStreamReader &stream);
+ void complete();
+
+signals:
+ void changed();
+
public slots:
void addV8Event(int depth,
const QString &function,
diff --git a/src/plugins/qmlprofiler/qv8profilereventview.cpp b/src/plugins/qmlprofiler/qv8profilereventview.cpp
new file mode 100644
index 0000000000..fdc3ee9592
--- /dev/null
+++ b/src/plugins/qmlprofiler/qv8profilereventview.cpp
@@ -0,0 +1,725 @@
+/****************************************************************************
+**
+** 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 "qv8profilereventview.h"
+
+#include <QUrl>
+#include <QHash>
+
+#include <QStandardItem>
+#include <QHeaderView>
+
+#include <QApplication>
+#include <QClipboard>
+
+#include <QContextMenuEvent>
+#include <QDebug>
+
+#include <coreplugin/minisplitter.h>
+#include <QVBoxLayout>
+#include <QHBoxLayout>
+
+#include "qmlprofilerviewmanager.h"
+#include "qmlprofilertool.h"
+#include "qv8profilerdatamodel.h"
+#include <QMenu>
+
+#include <utils/qtcassert.h>
+
+using namespace QmlDebug;
+
+namespace QmlProfiler {
+namespace Internal {
+
+enum ItemRole {
+ EventHashStrRole = Qt::UserRole+1,
+ FilenameRole = Qt::UserRole+2,
+ LineRole = Qt::UserRole+3,
+ ColumnRole = Qt::UserRole+4,
+ EventIdRole = Qt::UserRole+5
+};
+
+////////////////////////////////////////////////////////////////////////////////////
+
+
+////////////////////////////////////////////////////////////////////////////////////
+
+class EventsViewItem : public QStandardItem
+{
+public:
+ EventsViewItem(const QString &text) : QStandardItem(text) {}
+
+ virtual bool operator<(const QStandardItem &other) const
+ {
+ if (data().type() == QVariant::String) {
+ // first column
+ if (column() == 0) {
+ return data(FilenameRole).toString() == other.data(FilenameRole).toString() ?
+ data(LineRole).toInt() < other.data(LineRole).toInt() :
+ data(FilenameRole).toString() < other.data(FilenameRole).toString();
+ } else {
+ return data().toString().toLower() < other.data().toString().toLower();
+ }
+ }
+
+ return data().toDouble() < other.data().toDouble();
+ }
+};
+
+////////////////////////////////////////////////////////////////////////////////////
+
+class QV8ProfilerEventsWidget::QV8ProfilerEventsWidgetPrivate
+{
+public:
+ QV8ProfilerEventsWidgetPrivate(QV8ProfilerEventsWidget *qq):q(qq) {}
+ ~QV8ProfilerEventsWidgetPrivate() {}
+
+ QV8ProfilerEventsWidget *q;
+
+ Analyzer::IAnalyzerTool *m_profilerTool;
+ QmlProfilerViewManager *m_viewContainer;
+
+ QV8ProfilerEventsMainView *m_eventTree;
+ QV8ProfilerEventRelativesView *m_eventChildren;
+ QV8ProfilerEventRelativesView *m_eventParents;
+
+ QV8ProfilerDataModel *v8Model;
+};
+
+QV8ProfilerEventsWidget::QV8ProfilerEventsWidget(QWidget *parent,
+ Analyzer::IAnalyzerTool *profilerTool,
+ QmlProfilerViewManager *container,
+ QmlProfilerModelManager *profilerModelManager )
+ : QWidget(parent), d(new QV8ProfilerEventsWidgetPrivate(this))
+{
+ setObjectName(QLatin1String("QmlProfilerV8ProfileView"));
+
+ d->v8Model = profilerModelManager->v8Model();
+
+ d->m_eventTree = new QV8ProfilerEventsMainView(this, d->v8Model);
+ connect(d->m_eventTree, SIGNAL(gotoSourceLocation(QString,int,int)), this, SIGNAL(gotoSourceLocation(QString,int,int)));
+
+ d->m_eventChildren = new QV8ProfilerEventRelativesView(d->v8Model,
+ QV8ProfilerEventRelativesView::ChildrenView,
+ this);
+ d->m_eventParents = new QV8ProfilerEventRelativesView(d->v8Model,
+ QV8ProfilerEventRelativesView::ParentsView,
+ this);
+ connect(d->m_eventTree, SIGNAL(eventSelected(int)), d->m_eventChildren, SLOT(displayEvent(int)));
+ connect(d->m_eventTree, SIGNAL(eventSelected(int)), d->m_eventParents, SLOT(displayEvent(int)));
+ connect(d->m_eventChildren, SIGNAL(eventClicked(int)), d->m_eventTree, SLOT(selectEvent(int)));
+ connect(d->m_eventParents, SIGNAL(eventClicked(int)), d->m_eventTree, SLOT(selectEvent(int)));
+
+ // widget arrangement
+ QVBoxLayout *groupLayout = new QVBoxLayout;
+ groupLayout->setContentsMargins(0,0,0,0);
+ groupLayout->setSpacing(0);
+
+ Core::MiniSplitter *splitterVertical = new Core::MiniSplitter;
+ splitterVertical->addWidget(d->m_eventTree);
+ Core::MiniSplitter *splitterHorizontal = new Core::MiniSplitter;
+ splitterHorizontal->addWidget(d->m_eventParents);
+ splitterHorizontal->addWidget(d->m_eventChildren);
+ splitterHorizontal->setOrientation(Qt::Horizontal);
+ splitterVertical->addWidget(splitterHorizontal);
+ splitterVertical->setOrientation(Qt::Vertical);
+ splitterVertical->setStretchFactor(0,5);
+ splitterVertical->setStretchFactor(1,2);
+ groupLayout->addWidget(splitterVertical);
+ setLayout(groupLayout);
+
+ d->m_profilerTool = profilerTool;
+ d->m_viewContainer = container;
+
+}
+
+QV8ProfilerEventsWidget::~QV8ProfilerEventsWidget()
+{
+ delete d;
+}
+
+void QV8ProfilerEventsWidget::clear()
+{
+ d->m_eventTree->clear();
+ d->m_eventChildren->clear();
+ d->m_eventParents->clear();
+}
+
+QModelIndex QV8ProfilerEventsWidget::selectedItem() const
+{
+ return d->m_eventTree->selectedItem();
+}
+
+void QV8ProfilerEventsWidget::contextMenuEvent(QContextMenuEvent *ev)
+{
+ QTC_ASSERT(d->m_viewContainer, return;);
+
+ QMenu menu;
+ QAction *copyRowAction = 0;
+ QAction *copyTableAction = 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 (mouseOnTable(position)) {
+ menu.addSeparator();
+ if (selectedItem().isValid())
+ copyRowAction = menu.addAction(QCoreApplication::translate("QmlProfiler::Internal::QmlProfilerEventsWidget", "Copy Row"));
+ copyTableAction = menu.addAction(QCoreApplication::translate("QmlProfiler::Internal::QmlProfilerEventsWidget", "Copy Table"));
+ }
+
+ QAction *selectedAction = menu.exec(position);
+
+ if (selectedAction) {
+ if (selectedAction == copyRowAction)
+ copyRowToClipboard();
+ if (selectedAction == copyTableAction)
+ copyTableToClipboard();
+ }
+}
+
+void QV8ProfilerEventsWidget::resizeEvent(QResizeEvent *event)
+{
+ QWidget::resizeEvent(event);
+ emit resized();
+}
+
+bool QV8ProfilerEventsWidget::mouseOnTable(const QPoint &position) const
+{
+ QPoint tableTopLeft = d->m_eventTree->mapToGlobal(QPoint(0,0));
+ QPoint tableBottomRight = d->m_eventTree->mapToGlobal(QPoint(d->m_eventTree->width(), d->m_eventTree->height()));
+ return (position.x() >= tableTopLeft.x() && position.x() <= tableBottomRight.x() && position.y() >= tableTopLeft.y() && position.y() <= tableBottomRight.y());
+}
+
+void QV8ProfilerEventsWidget::copyTableToClipboard() const
+{
+ d->m_eventTree->copyTableToClipboard();
+}
+
+void QV8ProfilerEventsWidget::copyRowToClipboard() const
+{
+ d->m_eventTree->copyRowToClipboard();
+}
+
+void QV8ProfilerEventsWidget::updateSelectedEvent(int eventId) const
+{
+ if (d->m_eventTree->selectedEventId() != eventId)
+ d->m_eventTree->selectEvent(eventId);
+}
+
+void QV8ProfilerEventsWidget::selectBySourceLocation(const QString &filename, int line, int column)
+{
+ // This slot is used to connect the javascript pane with the qml events pane
+ // Our javascript trace data does not store column information
+ // thus we ignore it here
+ Q_UNUSED(column);
+ d->m_eventTree->selectEventByLocation(filename, line);
+}
+
+////////////////////////////////////////////////////////////////////////////////////
+
+class QV8ProfilerEventsMainView::QV8ProfilerEventsMainViewPrivate
+{
+public:
+ QV8ProfilerEventsMainViewPrivate(QV8ProfilerEventsMainView *qq) : q(qq) {}
+
+ void buildV8ModelFromList( const QList<QV8EventData *> &list );
+ int getFieldCount();
+
+ QString textForItem(QStandardItem *item, bool recursive) const;
+
+
+ QV8ProfilerEventsMainView *q;
+
+ QV8ProfilerDataModel *m_v8Model;
+ QStandardItemModel *m_model;
+ QList<bool> m_fieldShown;
+ QHash<int, int> m_columnIndex; // maps field enum to column index
+ int m_firstNumericColumn;
+ bool m_preventSelectBounce;
+};
+
+
+////////////////////////////////////////////////////////////////////////////////////
+
+QV8ProfilerEventsMainView::QV8ProfilerEventsMainView(QWidget *parent,
+ QV8ProfilerDataModel *v8Model)
+: QmlProfilerTreeView(parent), d(new QV8ProfilerEventsMainViewPrivate(this))
+{
+ setObjectName(QLatin1String("QmlProfilerEventsTable"));
+ setSortingEnabled(false);
+
+ d->m_model = new QStandardItemModel(this);
+ setModel(d->m_model);
+ connect(this,SIGNAL(clicked(QModelIndex)), this,SLOT(jumpToItem(QModelIndex)));
+
+ d->m_v8Model = v8Model;
+ connect(d->m_v8Model, SIGNAL(changed()), this, SLOT(buildModel()));
+ d->m_firstNumericColumn = 0;
+ d->m_preventSelectBounce = false;
+
+ setFieldViewable(Name, true);
+ setFieldViewable(Type, false);
+ setFieldViewable(TimeInPercent, true);
+ setFieldViewable(TotalTime, true);
+ setFieldViewable(SelfTimeInPercent, true);
+ setFieldViewable(SelfTime, true);
+ setFieldViewable(CallCount, false);
+ setFieldViewable(TimePerCall, false);
+ setFieldViewable(MaxTime, false);
+ setFieldViewable(MinTime, false);
+ setFieldViewable(MedianTime, false);
+ setFieldViewable(Details, true);
+
+ buildModel();
+}
+
+QV8ProfilerEventsMainView::~QV8ProfilerEventsMainView()
+{
+ clear();
+ delete d->m_model;
+ delete d;
+}
+
+void QV8ProfilerEventsMainView::setFieldViewable(Fields field, bool show)
+{
+ if (field < MaxFields) {
+ int length = d->m_fieldShown.count();
+ if (field >= length) {
+ for (int i=length; i<MaxFields; i++)
+ d->m_fieldShown << false;
+ }
+ d->m_fieldShown[field] = show;
+ }
+}
+
+
+void QV8ProfilerEventsMainView::setHeaderLabels()
+{
+ int fieldIndex = 0;
+ d->m_firstNumericColumn = 0;
+
+ d->m_columnIndex.clear();
+ if (d->m_fieldShown[Name]) {
+ d->m_columnIndex[Name] = fieldIndex;
+ d->m_model->setHeaderData(fieldIndex++, Qt::Horizontal, QVariant(displayHeader(Location)));
+ d->m_firstNumericColumn++;
+ }
+ if (d->m_fieldShown[Type]) {
+ d->m_columnIndex[Type] = fieldIndex;
+ d->m_model->setHeaderData(fieldIndex++, Qt::Horizontal, QVariant(displayHeader(Type)));
+ d->m_firstNumericColumn++;
+ }
+ if (d->m_fieldShown[TimeInPercent]) {
+ d->m_columnIndex[TimeInPercent] = fieldIndex;
+ d->m_model->setHeaderData(fieldIndex++, Qt::Horizontal, QVariant(displayHeader(TimeInPercent)));
+ }
+ if (d->m_fieldShown[TotalTime]) {
+ d->m_columnIndex[TotalTime] = fieldIndex;
+ d->m_model->setHeaderData(fieldIndex++, Qt::Horizontal, QVariant(displayHeader(TotalTime)));
+ }
+ if (d->m_fieldShown[SelfTimeInPercent]) {
+ d->m_columnIndex[Type] = fieldIndex;
+ d->m_model->setHeaderData(fieldIndex++, Qt::Horizontal, QVariant(displayHeader(SelfTimeInPercent)));
+ }
+ if (d->m_fieldShown[SelfTime]) {
+ d->m_columnIndex[SelfTime] = fieldIndex;
+ d->m_model->setHeaderData(fieldIndex++, Qt::Horizontal, QVariant(displayHeader(SelfTime)));
+ }
+ if (d->m_fieldShown[CallCount]) {
+ d->m_columnIndex[CallCount] = fieldIndex;
+ d->m_model->setHeaderData(fieldIndex++, Qt::Horizontal, QVariant(displayHeader(CallCount)));
+ }
+ if (d->m_fieldShown[TimePerCall]) {
+ d->m_columnIndex[TimePerCall] = fieldIndex;
+ d->m_model->setHeaderData(fieldIndex++, Qt::Horizontal, QVariant(displayHeader(TimePerCall)));
+ }
+ if (d->m_fieldShown[MedianTime]) {
+ d->m_columnIndex[MedianTime] = fieldIndex;
+ d->m_model->setHeaderData(fieldIndex++, Qt::Horizontal, QVariant(displayHeader(MedianTime)));
+ }
+ if (d->m_fieldShown[MaxTime]) {
+ d->m_columnIndex[MaxTime] = fieldIndex;
+ d->m_model->setHeaderData(fieldIndex++, Qt::Horizontal, QVariant(displayHeader(MaxTime)));
+ }
+ if (d->m_fieldShown[MinTime]) {
+ d->m_columnIndex[MinTime] = fieldIndex;
+ d->m_model->setHeaderData(fieldIndex++, Qt::Horizontal, QVariant(displayHeader(MinTime)));
+ }
+ if (d->m_fieldShown[Details]) {
+ d->m_columnIndex[Details] = fieldIndex;
+ d->m_model->setHeaderData(fieldIndex++, Qt::Horizontal, QVariant(displayHeader(Details)));
+ }
+}
+
+void QV8ProfilerEventsMainView::clear()
+{
+ d->m_model->clear();
+ d->m_model->setColumnCount(d->getFieldCount());
+
+ setHeaderLabels();
+ setSortingEnabled(false);
+}
+
+int QV8ProfilerEventsMainView::QV8ProfilerEventsMainViewPrivate::getFieldCount()
+{
+ int count = 0;
+ for (int i=0; i < m_fieldShown.count(); ++i)
+ if (m_fieldShown[i])
+ count++;
+ return count;
+}
+
+void QV8ProfilerEventsMainView::buildModel()
+{
+ clear();
+ d->buildV8ModelFromList( d->m_v8Model->getV8Events() );
+
+ setRootIsDecorated(false);
+ setSortingEnabled(true);
+ sortByColumn(d->m_firstNumericColumn,Qt::DescendingOrder);
+
+ expandAll();
+ if (d->m_fieldShown[Name])
+ resizeColumnToContents(0);
+
+ if (d->m_fieldShown[Type])
+ resizeColumnToContents(d->m_fieldShown[Name]?1:0);
+ collapseAll();
+}
+
+void QV8ProfilerEventsMainView::QV8ProfilerEventsMainViewPrivate::buildV8ModelFromList(const QList<QV8EventData *> &list)
+{
+ for (int index = 0; index < list.count(); index++) {
+ QV8EventData *v8event = list.at(index);
+ QList<QStandardItem *> newRow;
+
+ if (m_fieldShown[Name])
+ newRow << new EventsViewItem(v8event->displayName);
+
+ if (m_fieldShown[TimeInPercent]) {
+ newRow << new EventsViewItem(QString::number(v8event->totalPercent,'f',2)+QLatin1String(" %"));
+ newRow.last()->setData(QVariant(v8event->totalPercent));
+ }
+
+ if (m_fieldShown[TotalTime]) {
+ newRow << new EventsViewItem(displayTime(v8event->totalTime));
+ newRow.last()->setData(QVariant(v8event->totalTime));
+ }
+
+ if (m_fieldShown[SelfTimeInPercent]) {
+ newRow << new EventsViewItem(QString::number(v8event->SelfTimeInPercent,'f',2)+QLatin1String(" %"));
+ newRow.last()->setData(QVariant(v8event->SelfTimeInPercent));
+ }
+
+ if (m_fieldShown[SelfTime]) {
+ newRow << new EventsViewItem(displayTime(v8event->selfTime));
+ newRow.last()->setData(QVariant(v8event->selfTime));
+ }
+
+ if (m_fieldShown[Details]) {
+ newRow << new EventsViewItem(v8event->functionName);
+ newRow.last()->setData(QVariant(v8event->functionName));
+ }
+
+ if (!newRow.isEmpty()) {
+ // no edit
+ foreach (QStandardItem *item, newRow)
+ item->setEditable(false);
+
+ // metadata
+ 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(-1),ColumnRole); // v8 events have no column info
+ newRow.at(0)->setData(QVariant(v8event->eventId), EventIdRole);
+
+ // append
+ m_model->invisibleRootItem()->appendRow(newRow);
+ }
+ }
+}
+
+QString QV8ProfilerEventsMainView::displayTime(double time)
+{
+ if (time < 1e6)
+ return QString::number(time/1e3,'f',3) + trUtf8(" \xc2\xb5s");
+ if (time < 1e9)
+ return QString::number(time/1e6,'f',3) + tr(" ms");
+
+ return QString::number(time/1e9,'f',3) + tr(" s");
+}
+
+QString QV8ProfilerEventsMainView::nameForType(int typeNumber)
+{
+ switch (typeNumber) {
+ case 0: return QV8ProfilerEventsMainView::tr("Paint");
+ case 1: return QV8ProfilerEventsMainView::tr("Compile");
+ case 2: return QV8ProfilerEventsMainView::tr("Create");
+ case 3: return QV8ProfilerEventsMainView::tr("Binding");
+ case 4: return QV8ProfilerEventsMainView::tr("Signal");
+ }
+ return QString();
+}
+
+int QV8ProfilerEventsMainView::selectedEventId() const
+{
+ QModelIndex index = selectedItem();
+ if (!index.isValid())
+ return -1;
+ QStandardItem *item = d->m_model->item(index.row(), 0);
+ return item->data(EventIdRole).toInt();
+}
+
+void QV8ProfilerEventsMainView::jumpToItem(const QModelIndex &index)
+{
+ if (d->m_preventSelectBounce)
+ return;
+
+ d->m_preventSelectBounce = true;
+ QStandardItem *clickedItem = d->m_model->itemFromIndex(index);
+ QStandardItem *infoItem;
+ if (clickedItem->parent())
+ infoItem = clickedItem->parent()->child(clickedItem->row(), 0);
+ else
+ infoItem = d->m_model->item(index.row(), 0);
+
+ // show in editor
+ int line = infoItem->data(LineRole).toInt();
+ int column = infoItem->data(ColumnRole).toInt();
+ QString fileName = infoItem->data(FilenameRole).toString();
+ if (line!=-1 && !fileName.isEmpty())
+ emit gotoSourceLocation(fileName, line, column);
+
+ // show in callers/callees subwindow
+ emit eventSelected(infoItem->data(EventIdRole).toInt());
+
+ d->m_preventSelectBounce = false;
+}
+
+void QV8ProfilerEventsMainView::selectEvent(int eventId)
+{
+ for (int i=0; i<d->m_model->rowCount(); i++) {
+ QStandardItem *infoItem = d->m_model->item(i, 0);
+ if (infoItem->data(EventIdRole).toInt() == eventId) {
+ setCurrentIndex(d->m_model->indexFromItem(infoItem));
+ jumpToItem(currentIndex());
+ return;
+ }
+ }
+}
+
+void QV8ProfilerEventsMainView::selectEventByLocation(const QString &filename, int line)
+{
+ if (d->m_preventSelectBounce)
+ return;
+
+ for (int i=0; i<d->m_model->rowCount(); i++) {
+ QStandardItem *infoItem = d->m_model->item(i, 0);
+ if (currentIndex() != d->m_model->indexFromItem(infoItem) &&
+ infoItem->data(FilenameRole).toString() == filename &&
+ infoItem->data(LineRole).toInt() == line) {
+ setCurrentIndex(d->m_model->indexFromItem(infoItem));
+ jumpToItem(currentIndex());
+ return;
+ }
+ }
+}
+
+QModelIndex QV8ProfilerEventsMainView::selectedItem() const
+{
+ QModelIndexList sel = selectedIndexes();
+ if (sel.isEmpty())
+ return QModelIndex();
+ else
+ return sel.first();
+}
+
+QString QV8ProfilerEventsMainView::QV8ProfilerEventsMainViewPrivate::textForItem(QStandardItem *item, bool recursive = true) const
+{
+ QString str;
+
+ if (recursive) {
+ // indentation
+ QStandardItem *itemParent = item->parent();
+ while (itemParent) {
+ str += QLatin1String(" ");
+ itemParent = itemParent->parent();
+ }
+ }
+
+ // item's data
+ int colCount = m_model->columnCount();
+ 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 += QLatin1Char('\t');
+ }
+ str += QLatin1Char('\n');
+
+ // recursively print children
+ if (recursive && item->child(0))
+ for (int j = 0; j != item->rowCount(); j++)
+ str += textForItem(item->child(j));
+
+ return str;
+}
+
+void QV8ProfilerEventsMainView::copyTableToClipboard() const
+{
+ QString str;
+ // headers
+ int columnCount = d->m_model->columnCount();
+ for (int i = 0; i < columnCount; ++i) {
+ str += d->m_model->headerData(i, Qt::Horizontal, Qt::DisplayRole).toString();
+ if (i < columnCount - 1)
+ str += QLatin1Char('\t');
+ else
+ str += QLatin1Char('\n');
+ }
+ // data
+ int rowCount = d->m_model->rowCount();
+ for (int i = 0; i != rowCount; ++i) {
+ str += d->textForItem(d->m_model->item(i));
+ }
+ QClipboard *clipboard = QApplication::clipboard();
+ clipboard->setText(str, QClipboard::Selection);
+ clipboard->setText(str, QClipboard::Clipboard);
+}
+
+void QV8ProfilerEventsMainView::copyRowToClipboard() const
+{
+ QString str;
+ str = d->textForItem(d->m_model->itemFromIndex(selectedItem()), false);
+
+ QClipboard *clipboard = QApplication::clipboard();
+ clipboard->setText(str, QClipboard::Selection);
+ clipboard->setText(str, QClipboard::Clipboard);
+}
+
+////////////////////////////////////////////////////////////////////////////////////
+
+QV8ProfilerEventRelativesView::QV8ProfilerEventRelativesView(QV8ProfilerDataModel *model,
+ SubViewType viewType,
+ QWidget *parent)
+ : QmlProfilerTreeView(parent)
+ , m_type(viewType)
+ , m_v8Model(model)
+ , m_model(new QStandardItemModel(this))
+{
+ setModel(m_model);
+
+ updateHeader();
+ setSortingEnabled(false);
+
+ connect(this, SIGNAL(clicked(QModelIndex)), this, SLOT(jumpToItem(QModelIndex)));
+}
+
+QV8ProfilerEventRelativesView::~QV8ProfilerEventRelativesView()
+{
+}
+
+void QV8ProfilerEventRelativesView::displayEvent(int index)
+{
+ QV8EventData *event = m_v8Model->v8EventDescription(index);
+ QTC_CHECK(event);
+
+ QList<QV8EventSub*> events;
+ if (m_type == ParentsView)
+ events = event->parentHash.values();
+ else
+ events = event->childrenHash.values();
+
+ rebuildTree(events);
+
+ updateHeader();
+ resizeColumnToContents(0);
+ setSortingEnabled(true);
+ sortByColumn(1);
+}
+
+void QV8ProfilerEventRelativesView::rebuildTree(QList<QV8EventSub*> events)
+{
+ clear();
+
+ QStandardItem *topLevelItem = m_model->invisibleRootItem();
+
+ foreach (QV8EventSub *event, events) {
+ QList<QStandardItem *> newRow;
+ newRow << new EventsViewItem(event->reference->displayName);
+ newRow << new EventsViewItem(QV8ProfilerEventsMainView::displayTime(event->totalTime));
+ newRow << new EventsViewItem(event->reference->functionName);
+ newRow.at(0)->setData(QVariant(event->reference->eventId), EventIdRole);
+ newRow.at(1)->setData(QVariant(event->totalTime));
+
+ foreach (QStandardItem *item, newRow)
+ item->setEditable(false);
+
+ topLevelItem->appendRow(newRow);
+ }
+}
+
+void QV8ProfilerEventRelativesView::clear()
+{
+ m_model->clear();
+}
+
+void QV8ProfilerEventRelativesView::updateHeader()
+{
+ m_model->setColumnCount(3);
+
+ int columnIndex = 0;
+ if (m_type == ChildrenView)
+ m_model->setHeaderData(columnIndex++, Qt::Horizontal, QVariant(displayHeader(Callee)));
+ else
+ m_model->setHeaderData(columnIndex++, Qt::Horizontal, QVariant(displayHeader(Caller)));
+
+ m_model->setHeaderData(columnIndex++, Qt::Horizontal, QVariant(displayHeader(TotalTime)));
+
+ if (m_type == ChildrenView)
+ m_model->setHeaderData(columnIndex++, Qt::Horizontal, QVariant(displayHeader(CalleeDescription)));
+ else
+ m_model->setHeaderData(columnIndex++, Qt::Horizontal, QVariant(displayHeader(CallerDescription)));
+}
+
+void QV8ProfilerEventRelativesView::jumpToItem(const QModelIndex &index)
+{
+ QStandardItem *infoItem = m_model->item(index.row(), 0);
+ emit eventClicked(infoItem->data(EventIdRole).toInt());
+}
+
+} // namespace Internal
+} // namespace QmlProfiler
diff --git a/src/plugins/qmlprofiler/qv8profilereventview.h b/src/plugins/qmlprofiler/qv8profilereventview.h
new file mode 100644
index 0000000000..d32b499c1c
--- /dev/null
+++ b/src/plugins/qmlprofiler/qv8profilereventview.h
@@ -0,0 +1,163 @@
+/****************************************************************************
+**
+** 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 QV8PROFILEREVENTVIEW_H
+#define QV8PROFILEREVENTVIEW_H
+
+#include <QStandardItemModel>
+#include <qmldebug/qmlprofilereventtypes.h>
+#include "qmlprofilermodelmanager.h"
+#include "qmlprofilereventsmodelproxy.h"
+#include "qmlprofilertreeview.h"
+
+#include <analyzerbase/ianalyzertool.h>
+
+#include "qmlprofilerviewmanager.h"
+
+namespace QmlProfiler {
+namespace Internal {
+
+class QV8ProfilerEventsMainView;
+class QV8ProfilerEventRelativesView;
+struct QV8EventSub;
+
+
+class QV8ProfilerEventsWidget : public QWidget
+{
+ Q_OBJECT
+public:
+ explicit QV8ProfilerEventsWidget(QWidget *parent,
+ Analyzer::IAnalyzerTool *profilerTool,
+ QmlProfilerViewManager *container,
+ QmlProfilerModelManager *profilerModelManager );
+ ~QV8ProfilerEventsWidget();
+
+ void clear();
+
+ void getStatisticsInRange(qint64 rangeStart, qint64 rangeEnd);
+ QModelIndex selectedItem() const;
+ bool mouseOnTable(const QPoint &position) const;
+ void copyTableToClipboard() const;
+ void copyRowToClipboard() const;
+
+signals:
+ void gotoSourceLocation(const QString &fileName, int lineNumber, int columnNumber);
+ void showEventInTimeline(int eventId);
+ void resized();
+
+public slots:
+ void updateSelectedEvent(int eventId) const;
+ void selectBySourceLocation(const QString &filename, int line, int column);
+
+protected:
+ void contextMenuEvent(QContextMenuEvent *ev);
+ virtual void resizeEvent(QResizeEvent *event);
+
+private:
+ class QV8ProfilerEventsWidgetPrivate;
+ QV8ProfilerEventsWidgetPrivate *d;
+};
+
+class QV8ProfilerEventsMainView : public QmlProfilerTreeView
+{
+ Q_OBJECT
+public:
+
+ explicit QV8ProfilerEventsMainView(QWidget *parent,
+ QV8ProfilerDataModel *v8Model);
+ ~QV8ProfilerEventsMainView();
+
+ void setFieldViewable(Fields field, bool show);
+ void setShowAnonymousEvents( bool showThem );
+
+ QModelIndex selectedItem() const;
+ void copyTableToClipboard() const;
+ void copyRowToClipboard() const;
+
+ static QString displayTime(double time);
+ static QString nameForType(int typeNumber);
+
+ int selectedEventId() const;
+
+ void setShowExtendedStatistics(bool);
+ bool showExtendedStatistics() const;
+
+signals:
+ void gotoSourceLocation(const QString &fileName, int lineNumber, int columnNumber);
+ void eventSelected(int eventId);
+
+public slots:
+ void clear();
+ void jumpToItem(const QModelIndex &index);
+ void selectEvent(int eventId);
+ void selectEventByLocation(const QString &filename, int line);
+ void buildModel();
+
+private:
+ void setHeaderLabels();
+
+private:
+ class QV8ProfilerEventsMainViewPrivate;
+ QV8ProfilerEventsMainViewPrivate *d;
+};
+
+class QV8ProfilerEventRelativesView : public QmlProfilerTreeView
+{
+ Q_OBJECT
+public:
+ enum SubViewType {
+ ParentsView,
+ ChildrenView
+ };
+
+ QV8ProfilerEventRelativesView(QV8ProfilerDataModel *model, SubViewType viewType,
+ QWidget *parent);
+ ~QV8ProfilerEventRelativesView();
+
+signals:
+ void eventClicked(int eventId);
+
+public slots:
+ void displayEvent(int eventId);
+ void jumpToItem(const QModelIndex &);
+ void clear();
+
+private:
+ void rebuildTree(QList<QV8EventSub*> events);
+ void updateHeader();
+
+ QV8ProfilerEventRelativesView::SubViewType m_type;
+ QV8ProfilerDataModel *m_v8Model;
+ QStandardItemModel *m_model;
+};
+
+} // namespace Internal
+} // namespace QmlProfiler
+
+#endif // QV8PROFILEREVENTVIEW_H
diff --git a/src/plugins/qmlprofiler/timelinemodelaggregator.cpp b/src/plugins/qmlprofiler/timelinemodelaggregator.cpp
new file mode 100644
index 0000000000..ccdf84dd5f
--- /dev/null
+++ b/src/plugins/qmlprofiler/timelinemodelaggregator.cpp
@@ -0,0 +1,373 @@
+/****************************************************************************
+**
+** 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 "timelinemodelaggregator.h"
+
+#include "qmlprofilertimelinemodelproxy.h"
+#include "qmlprofilerpainteventsmodelproxy.h"
+#include "qmlprofilerplugin.h"
+
+#include <QStringList>
+#include <QVariant>
+
+namespace QmlProfiler {
+namespace Internal {
+
+
+class TimelineModelAggregator::TimelineModelAggregatorPrivate {
+public:
+ TimelineModelAggregatorPrivate(TimelineModelAggregator *qq):q(qq) {}
+ ~TimelineModelAggregatorPrivate() {}
+
+ TimelineModelAggregator *q;
+
+ int basicModelIndex;
+ QList <AbstractTimelineModel *> modelList;
+ QmlProfilerModelManager *modelManager;
+};
+
+TimelineModelAggregator::TimelineModelAggregator(QObject *parent)
+ : QObject(parent), d(new TimelineModelAggregatorPrivate(this))
+{
+}
+
+TimelineModelAggregator::~TimelineModelAggregator()
+{
+ delete d;
+}
+
+void TimelineModelAggregator::setModelManager(QmlProfilerModelManager *modelManager)
+{
+ d->modelManager = modelManager;
+ connect(modelManager,SIGNAL(stateChanged()),this,SLOT(dataChanged()));
+ connect(modelManager,SIGNAL(countChanged()),this,SIGNAL(countChanged()));
+ connect(modelManager,SIGNAL(dataAvailable()),this,SIGNAL(dataAvailable()));
+
+ // external models pushed on top
+ foreach (AbstractTimelineModel *timelineModel, QmlProfilerPlugin::instance->getModels()) {
+ timelineModel->setModelManager(modelManager);
+ addModel(timelineModel);
+ }
+
+ PaintEventsModelProxy *paintEventsModelProxy = new PaintEventsModelProxy(this);
+ paintEventsModelProxy->setModelManager(modelManager);
+ addModel(paintEventsModelProxy);
+
+ BasicTimelineModel *basicTimelineModel = new BasicTimelineModel(this);
+ basicTimelineModel->setModelManager(modelManager);
+ addModel(basicTimelineModel);
+ // the basic model is the last one here
+ d->basicModelIndex = d->modelList.count() - 1;
+
+}
+
+void TimelineModelAggregator::addModel(AbstractTimelineModel *m)
+{
+ d->modelList << m;
+ connect(m,SIGNAL(countChanged()),this,SIGNAL(countChanged()));
+ connect(m,SIGNAL(emptyChanged()),this,SIGNAL(emptyChanged()));
+ connect(m,SIGNAL(expandedChanged()),this,SIGNAL(expandedChanged()));
+ connect(m,SIGNAL(stateChanged()),this,SIGNAL(stateChanged()));
+}
+
+// order?
+int TimelineModelAggregator::categories() const
+{
+ int categoryCount = 0;
+ foreach (const AbstractTimelineModel *modelProxy, d->modelList)
+ categoryCount += modelProxy->categories();
+ return categoryCount;
+}
+
+int TimelineModelAggregator::visibleCategories() const
+{
+ int categoryCount = 0;
+ foreach (const AbstractTimelineModel *modelProxy, d->modelList) {
+ for (int i = 0; i < modelProxy->categories(); i++)
+ if (modelProxy->categoryDepth(i) > 0)
+ categoryCount ++;
+ }
+ return categoryCount;
+}
+
+QStringList TimelineModelAggregator::categoryTitles() const
+{
+ QStringList retString;
+ foreach (const AbstractTimelineModel *modelProxy, d->modelList)
+ retString += modelProxy->categoryTitles();
+ return retString;
+}
+
+int TimelineModelAggregator::count(int modelIndex) const
+{
+ if (modelIndex == -1) {
+ int totalCount = 0;
+ foreach (const AbstractTimelineModel *modelProxy, d->modelList)
+ totalCount += modelProxy->count();
+
+ return totalCount;
+ } else {
+ return d->modelList[modelIndex]->count();
+ }
+}
+
+bool TimelineModelAggregator::isEmpty() const
+{
+ foreach (const AbstractTimelineModel *modelProxy, d->modelList)
+ if (!modelProxy->isEmpty())
+ return false;
+ return true;
+}
+
+bool TimelineModelAggregator::eventAccepted(const QmlProfilerSimpleModel::QmlEventData &/*event*/) const
+{
+ // accept all events
+ return true;
+}
+
+int TimelineModelAggregator::basicModelIndex() const
+{
+ return d->basicModelIndex;
+}
+
+qint64 TimelineModelAggregator::lastTimeMark() const
+{
+ qint64 mark = -1;
+ foreach (const AbstractTimelineModel *modelProxy, d->modelList) {
+ if (!modelProxy->isEmpty()) {
+ qint64 mk = modelProxy->lastTimeMark();
+ if (mark > mk)
+ mark = mk;
+ }
+ }
+ return mark;
+}
+
+bool TimelineModelAggregator::expanded(int modelIndex, int category) const
+{
+ return d->modelList[modelIndex]->expanded(category);
+}
+
+void TimelineModelAggregator::setExpanded(int modelIndex, int category, bool expanded)
+{
+// int modelIndex = modelIndexForCategory(category);
+// category = correctedCategoryIndexForModel(modelIndex, categoryIndex);
+ d->modelList[modelIndex]->setExpanded(category, expanded);
+}
+
+int TimelineModelAggregator::categoryDepth(int modelIndex, int categoryIndex) const
+{
+ return d->modelList[modelIndex]->categoryDepth(categoryIndex);
+}
+
+int TimelineModelAggregator::categoryCount(int modelIndex) const
+{
+ return d->modelList[modelIndex]->categoryCount();
+}
+
+int TimelineModelAggregator::rowCount(int modelIndex) const
+{
+ return d->modelList[modelIndex]->rowCount();
+}
+
+const QString TimelineModelAggregator::categoryLabel(int modelIndex, int categoryIndex) const
+{
+// int modelIndex = modelIndexForCategory(categoryIndex);
+// categoryIndex = correctedCategoryIndexForModel(modelIndex, categoryIndex);
+ return d->modelList[modelIndex]->categoryLabel(categoryIndex);
+}
+
+int TimelineModelAggregator::modelIndexForCategory(int absoluteCategoryIndex) const
+{
+ int categoryIndex = absoluteCategoryIndex;
+ for (int modelIndex = 0; modelIndex < d->modelList.count(); modelIndex++)
+ if (categoryIndex < d->modelList[modelIndex]->categoryCount()) {
+ return modelIndex;
+ } else {
+ categoryIndex -= d->modelList[modelIndex]->categoryCount();
+ }
+
+ return modelCount()-1;
+}
+
+int TimelineModelAggregator::correctedCategoryIndexForModel(int modelIndex, int absoluteCategoryIndex) const
+{
+ int categoryIndex = absoluteCategoryIndex;
+ for (int mi = 0; mi < modelIndex; mi++)
+ categoryIndex -= d->modelList[mi]->categoryCount();
+ return categoryIndex;
+}
+
+int TimelineModelAggregator::findFirstIndex(int modelIndex, qint64 startTime) const
+{
+ return d->modelList[modelIndex]->findFirstIndex(startTime);
+}
+
+int TimelineModelAggregator::findFirstIndexNoParents(int modelIndex, qint64 startTime) const
+{
+ return d->modelList[modelIndex]->findFirstIndexNoParents(startTime);
+}
+
+int TimelineModelAggregator::findLastIndex(int modelIndex, qint64 endTime) const
+{
+ return d->modelList[modelIndex]->findLastIndex(endTime);
+}
+
+int TimelineModelAggregator::getEventType(int modelIndex, int index) const
+{
+ return d->modelList[modelIndex]->getEventType(index);
+}
+
+int TimelineModelAggregator::getEventCategoryInModel(int modelIndex, int index) const
+{
+ return d->modelList[modelIndex]->getEventCategory(index);
+}
+
+int TimelineModelAggregator::getEventRow(int modelIndex, int index) const
+{
+ return d->modelList[modelIndex]->getEventRow(index);
+}
+
+qint64 TimelineModelAggregator::getDuration(int modelIndex, int index) const
+{
+ return d->modelList[modelIndex]->getDuration(index);
+}
+
+qint64 TimelineModelAggregator::getStartTime(int modelIndex, int index) const
+{
+ return d->modelList[modelIndex]->getStartTime(index);
+}
+
+qint64 TimelineModelAggregator::getEndTime(int modelIndex, int index) const
+{
+ return d->modelList[modelIndex]->getEndTime(index);
+}
+
+int TimelineModelAggregator::getEventId(int modelIndex, int index) const
+{
+ return d->modelList[modelIndex]->getEventId(index);
+}
+
+int TimelineModelAggregator::getBindingLoopDest(int modelIndex,int index) const
+{
+ return d->modelList[modelIndex]->getBindingLoopDest(index);
+}
+
+QColor TimelineModelAggregator::getColor(int modelIndex, int index) const
+{
+ return d->modelList[modelIndex]->getColor(index);
+}
+
+QVariantList TimelineModelAggregator::getColorRGB(int modelIndex, int itemIndex) const
+{
+ // return color as RGB list, for use in Qml
+ QColor c = getColor(modelIndex, itemIndex);
+ QVariantList res;
+ res.append(QVariant(c.red()));
+ res.append(QVariant(c.green()));
+ res.append(QVariant(c.blue()));
+ return res;
+}
+
+float TimelineModelAggregator::getHeight(int modelIndex, int index) const
+{
+ return d->modelList[modelIndex]->getHeight(index);
+}
+
+const QVariantList TimelineModelAggregator::getLabelsForCategory(int modelIndex, int category) const
+{
+// int modelIndex = modelIndexForCategory(category);
+// category = correctedCategoryIndexForModel(modelIndex, category);
+ return d->modelList[modelIndex]->getLabelsForCategory(category);
+}
+
+const QVariantList TimelineModelAggregator::getEventDetails(int modelIndex, int index) const
+{
+ return d->modelList[modelIndex]->getEventDetails(index);
+}
+
+const QVariantMap TimelineModelAggregator::getEventLocation(int modelIndex, int index) const
+{
+ return d->modelList[modelIndex]->getEventLocation(index);
+}
+
+int TimelineModelAggregator::getEventIdForHash(const QString &hash) const
+{
+ foreach (const AbstractTimelineModel *model, d->modelList) {
+ int eventId = model->getEventIdForHash(hash);
+ if (eventId != -1)
+ return eventId;
+ }
+ return -1;
+}
+
+int TimelineModelAggregator::getEventIdForLocation(const QString &filename, int line, int column) const
+{
+ foreach (const AbstractTimelineModel *model, d->modelList) {
+ int eventId = model->getEventIdForLocation(filename, line, column);
+ if (eventId != -1)
+ return eventId;
+ }
+ return -1;
+}
+
+void TimelineModelAggregator::dataChanged()
+{
+ // this is a slot connected for every modelproxy
+ // nothing to do here, each model will take care of itself
+}
+
+int TimelineModelAggregator::modelCount() const
+{
+ return d->modelList.count();
+}
+
+qint64 TimelineModelAggregator::traceStartTime() const
+{
+ return d->modelManager->traceTime()->startTime();
+}
+
+qint64 TimelineModelAggregator::traceEndTime() const
+{
+ return d->modelManager->traceTime()->endTime();
+}
+
+qint64 TimelineModelAggregator::traceDuration() const
+{
+ return d->modelManager->traceTime()->duration();
+}
+
+int TimelineModelAggregator::getState() const
+{
+ return (int)d->modelManager->state();
+}
+
+
+} // namespace Internal
+} // namespace QmlProfiler
diff --git a/src/plugins/qmlprofiler/timelinemodelaggregator.h b/src/plugins/qmlprofiler/timelinemodelaggregator.h
new file mode 100644
index 0000000000..7b1e832840
--- /dev/null
+++ b/src/plugins/qmlprofiler/timelinemodelaggregator.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 TIMELINEMODELAGGREGATOR_H
+#define TIMELINEMODELAGGREGATOR_H
+
+#include "abstracttimelinemodel.h"
+#include "qmlprofilermodelmanager.h"
+
+namespace QmlProfiler {
+namespace Internal {
+
+class TimelineModelAggregator : public QObject
+{
+ Q_OBJECT
+public:
+ TimelineModelAggregator(QObject *parent = 0);
+ ~TimelineModelAggregator();
+
+ void setModelManager(QmlProfilerModelManager *modelManager);
+ void addModel(AbstractTimelineModel *m);
+
+
+ Q_INVOKABLE int categories() const;
+ Q_INVOKABLE int visibleCategories() const;
+ Q_INVOKABLE QStringList categoryTitles() const;
+ Q_INVOKABLE int count(int modelIndex = -1) const;
+ void clear();
+ Q_INVOKABLE int modelCount() const;
+
+ Q_INVOKABLE qint64 traceStartTime() const;
+ Q_INVOKABLE qint64 traceEndTime() const;
+ Q_INVOKABLE qint64 traceDuration() const;
+ Q_INVOKABLE int getState() const;
+
+ bool isEmpty() const;
+
+ bool eventAccepted(const QmlProfilerSimpleModel::QmlEventData &event) const;
+
+ Q_INVOKABLE int basicModelIndex() const;
+
+ Q_INVOKABLE qint64 lastTimeMark() const;
+
+ Q_INVOKABLE bool expanded(int modelIndex, int category) const;
+ Q_INVOKABLE void setExpanded(int modelIndex, int category, bool expanded);
+ Q_INVOKABLE int categoryDepth(int modelIndex, int categoryIndex) const;
+ Q_INVOKABLE int categoryCount(int modelIndex) const;
+ Q_INVOKABLE int rowCount(int modelIndex) const;
+ Q_INVOKABLE const QString categoryLabel(int modelIndex, int categoryIndex) const;
+
+ int findFirstIndex(int modelIndex, qint64 startTime) const;
+ int findFirstIndexNoParents(int modelIndex, qint64 startTime) const;
+ int findLastIndex(int modelIndex, qint64 endTime) const;
+
+ int getEventType(int modelIndex, int index) const;
+ Q_INVOKABLE int getEventCategoryInModel(int modelIndex, int index) const;
+ int getEventRow(int modelIndex, int index) const;
+ Q_INVOKABLE qint64 getDuration(int modelIndex, int index) const;
+ Q_INVOKABLE qint64 getStartTime(int modelIndex, int index) const;
+ Q_INVOKABLE qint64 getEndTime(int modelIndex, int index) const;
+ Q_INVOKABLE int getEventId(int modelIndex, int index) const;
+ Q_INVOKABLE int getBindingLoopDest(int modelIndex, int index) const;
+ Q_INVOKABLE QColor getColor(int modelIndex, int index) const;
+ Q_INVOKABLE QVariantList getColorRGB(int modelIndex, int itemIndex) const;
+ Q_INVOKABLE float getHeight(int modelIndex, int index) const;
+
+ Q_INVOKABLE const QVariantList getLabelsForCategory(int modelIndex, int category) const;
+
+ Q_INVOKABLE const QVariantList getEventDetails(int modelIndex, int index) const;
+ Q_INVOKABLE const QVariantMap getEventLocation(int modelIndex, int index) const;
+
+ Q_INVOKABLE int getEventIdForHash(const QString &hash) const;
+ Q_INVOKABLE int getEventIdForLocation(const QString &filename, int line, int column) const;
+
+ Q_INVOKABLE int modelIndexForCategory(int absoluteCategoryIndex) const;
+ Q_INVOKABLE int correctedCategoryIndexForModel(int modelIndex, int absoluteCategoryIndex) const;
+
+signals:
+ void countChanged();
+ void dataAvailable();
+ void stateChanged();
+ void emptyChanged();
+ void expandedChanged();
+
+protected slots:
+ void dataChanged();
+
+private:
+ class TimelineModelAggregatorPrivate;
+ TimelineModelAggregatorPrivate *d;
+};
+
+}
+}
+
+#endif // TIMELINEMODELAGGREGATOR_H
diff --git a/src/plugins/qmlprofiler/timelinerenderer.cpp b/src/plugins/qmlprofiler/timelinerenderer.cpp
index 9af59c3d64..77d895cf24 100644
--- a/src/plugins/qmlprofiler/timelinerenderer.cpp
+++ b/src/plugins/qmlprofiler/timelinerenderer.cpp
@@ -29,12 +29,13 @@
#include "timelinerenderer.h"
-#include <qdeclarativecontext.h>
-#include <qdeclarativeproperty.h>
+#include <QQmlContext>
+#include <QQmlProperty>
#include <QTimer>
#include <QPixmap>
#include <QPainter>
#include <QGraphicsSceneMouseEvent>
+#include <QVarLengthArray>
#include <math.h>
@@ -42,16 +43,27 @@ using namespace QmlProfiler::Internal;
const int DefaultRowHeight = 30;
-TimelineRenderer::TimelineRenderer(QDeclarativeItem *parent) :
- QDeclarativeItem(parent), m_startTime(0), m_endTime(0), m_spacing(0),
- m_lastStartTime(0), m_lastEndTime(0), m_profilerDataModel(0)
+TimelineRenderer::TimelineRenderer(QQuickPaintedItem *parent) :
+ QQuickPaintedItem(parent), m_startTime(0), m_endTime(0), m_spacing(0),
+ m_lastStartTime(0), m_lastEndTime(0)
+ , m_profilerModelProxy(0)
{
clearData();
- setFlag(QGraphicsItem::ItemHasNoContents, false);
setAcceptedMouseButtons(Qt::LeftButton);
setAcceptHoverEvents(true);
- for (int i=0; i<QmlDebug::MaximumQmlEventType; i++)
- m_rowsExpanded << false;
+}
+
+void TimelineRenderer::setProfilerModelProxy(QObject *profilerModelProxy)
+{
+ if (m_profilerModelProxy) {
+ disconnect(m_profilerModelProxy, SIGNAL(expandedChanged()), this, SLOT(requestPaint()));
+ }
+ m_profilerModelProxy = qobject_cast<TimelineModelAggregator *>(profilerModelProxy);
+
+ if (m_profilerModelProxy) {
+ connect(m_profilerModelProxy, SIGNAL(expandedChanged()), this, SLOT(requestPaint()));
+ }
+ emit profilerModelProxyChanged(m_profilerModelProxy);
}
void TimelineRenderer::componentComplete()
@@ -64,7 +76,7 @@ void TimelineRenderer::componentComplete()
if (p.hasNotifySignal())
QMetaObject::connect(this, p.notifySignalIndex(), this, requestPaintMethod, 0, 0);
}
- QDeclarativeItem::componentComplete();
+ QQuickItem::componentComplete();
}
void TimelineRenderer::requestPaint()
@@ -72,7 +84,7 @@ void TimelineRenderer::requestPaint()
update();
}
-void TimelineRenderer::paint(QPainter *p, const QStyleOptionGraphicsItem *, QWidget *)
+void TimelineRenderer::paint(QPainter *p)
{
qint64 windowDuration = m_endTime - m_startTime;
if (windowDuration <= 0)
@@ -80,105 +92,68 @@ void TimelineRenderer::paint(QPainter *p, const QStyleOptionGraphicsItem *, QWid
m_spacing = qreal(width()) / windowDuration;
- m_rowWidths.clear();
- // The "1+" is because the reference screenshot features an empty row per type, in order to leave space for the title
- for (int i=0; i<QmlDebug::MaximumQmlEventType; i++) {
- m_rowWidths << 1 + (m_rowsExpanded[i] ? m_profilerDataModel->uniqueEventsOfType(i) :
- m_profilerDataModel->maxNestingForType(i));
- }
-
- // event rows
- m_rowStarts.clear();
- int pos = 0;
- for (int i=0; i<QmlDebug::MaximumQmlEventType; i++) {
- m_rowStarts << pos;
- pos += DefaultRowHeight * m_rowWidths[i];
- }
-
p->setPen(Qt::transparent);
- // speedup: don't draw overlapping events, just skip them
- m_rowLastX.clear();
- for (int i=0; i<QmlDebug::MaximumQmlEventType; i++)
- for (int j=0; j<m_rowWidths[i]; j++)
- m_rowLastX << -m_startTime * m_spacing;
-
- int firstIndex = m_profilerDataModel->findFirstIndex(m_startTime);
- int lastIndex = m_profilerDataModel->findLastIndex(m_endTime);
-
- if (lastIndex < m_profilerDataModel->count()) {
- drawItemsToPainter(p, firstIndex, lastIndex);
- drawSelectionBoxes(p, firstIndex, lastIndex);
- drawBindingLoopMarkers(p, firstIndex, lastIndex);
+ for (int modelIndex = 0; modelIndex < m_profilerModelProxy->modelCount(); modelIndex++) {
+ int lastIndex = m_profilerModelProxy->findLastIndex(modelIndex, m_endTime);
+ if (lastIndex >= 0 && lastIndex < m_profilerModelProxy->count(modelIndex)) {
+ int firstIndex = m_profilerModelProxy->findFirstIndex(modelIndex, m_startTime);
+ if (firstIndex >= 0) {
+ drawItemsToPainter(p, modelIndex, firstIndex, lastIndex);
+ if (m_selectedModel == modelIndex)
+ drawSelectionBoxes(p, modelIndex, firstIndex, lastIndex);
+ drawBindingLoopMarkers(p, modelIndex, firstIndex, lastIndex);
+ }
+ }
}
-
m_lastStartTime = m_startTime;
m_lastEndTime = m_endTime;
-}
-QColor TimelineRenderer::colorForItem(int itemIndex)
-{
- int ndx = m_profilerDataModel->getEventId(itemIndex);
- return QColor::fromHsl((ndx*25)%360, 76, 166);
}
-void TimelineRenderer::drawItemsToPainter(QPainter *p, int fromIndex, int toIndex)
+void TimelineRenderer::drawItemsToPainter(QPainter *p, int modelIndex, int fromIndex, int toIndex)
{
- int x, y, width, height, rowNumber, eventType;
+ p->save();
+ p->setPen(Qt::transparent);
+ int modelRowStart = 0;
+ for (int mi = 0; mi < modelIndex; mi++)
+ modelRowStart += m_profilerModelProxy->rowCount(mi);
+
for (int i = fromIndex; i <= toIndex; i++) {
- x = (m_profilerDataModel->getStartTime(i) - m_startTime) * m_spacing;
+ int x, y, width, height;
+ x = (m_profilerModelProxy->getStartTime(modelIndex, i) - m_startTime) * m_spacing;
- eventType = m_profilerDataModel->getType(i);
- if (m_rowsExpanded[eventType])
- y = m_rowStarts[eventType] + DefaultRowHeight *
- (m_profilerDataModel->eventPosInType(i) + 1);
- else
- y = m_rowStarts[eventType] + DefaultRowHeight *
- m_profilerDataModel->getNestingLevel(i);
+ int rowNumber = m_profilerModelProxy->getEventRow(modelIndex, i);
+ y = (modelRowStart + rowNumber) * DefaultRowHeight;
- width = m_profilerDataModel->getDuration(i)*m_spacing;
- if (width<1)
+ width = m_profilerModelProxy->getDuration(modelIndex, i) * m_spacing;
+ if (width < 1)
width = 1;
- rowNumber = y/DefaultRowHeight;
- if (m_rowLastX[rowNumber] > x+width)
- continue;
- m_rowLastX[rowNumber] = x+width;
-
- // special: animations
- if (eventType == 0 && m_profilerDataModel->getAnimationCount(i) >= 0) {
- double scale = m_profilerDataModel->getMaximumAnimationCount() -
- m_profilerDataModel->getMinimumAnimationCount();
- double fraction;
- if (scale > 1)
- fraction = (double)(m_profilerDataModel->getAnimationCount(i) -
- m_profilerDataModel->getMinimumAnimationCount()) / scale;
- else
- fraction = 1.0;
- height = DefaultRowHeight * (fraction * 0.85 + 0.15);
- y += DefaultRowHeight - height;
-
- double fpsFraction = m_profilerDataModel->getFramerate(i) / 60.0;
- if (fpsFraction > 1.0)
- fpsFraction = 1.0;
- p->setBrush(QColor::fromHsl((fpsFraction*96)+10, 76, 166));
- p->drawRect(x, y, width, height);
- } else {
- // normal events
- p->setBrush(colorForItem(i));
- p->drawRect(x, y, width, DefaultRowHeight);
- }
+ height = DefaultRowHeight * m_profilerModelProxy->getHeight(modelIndex, i);
+ y += DefaultRowHeight - height;
+
+ // normal events
+ p->setBrush(m_profilerModelProxy->getColor(modelIndex, i));
+ p->drawRect(x, y, width, height);
}
+ p->restore();
}
-void TimelineRenderer::drawSelectionBoxes(QPainter *p, int fromIndex, int toIndex)
+void TimelineRenderer::drawSelectionBoxes(QPainter *p, int modelIndex, int fromIndex, int toIndex)
{
if (m_selectedItem == -1)
return;
- int id = m_profilerDataModel->getEventId(m_selectedItem);
- p->setBrush(Qt::transparent);
+ int id = m_profilerModelProxy->getEventId(modelIndex, m_selectedItem);
+
+ int modelRowStart = 0;
+ for (int mi = 0; mi < modelIndex; mi++)
+ modelRowStart += m_profilerModelProxy->rowCount(mi);
+
+ p->save();
+
QColor selectionColor = Qt::blue;
if (m_selectionLocked)
selectionColor = QColor(96,0,255);
@@ -186,25 +161,18 @@ void TimelineRenderer::drawSelectionBoxes(QPainter *p, int fromIndex, int toInde
QPen lightPen(QBrush(selectionColor.lighter(130)), 2);
lightPen.setJoinStyle(Qt::MiterJoin);
p->setPen(lightPen);
+ p->setBrush(Qt::transparent);
- int x, y, width, eventType;
- p->setPen(lightPen);
-
+ int x, y, width;
QRect selectedItemRect(0,0,0,0);
for (int i = fromIndex; i <= toIndex; i++) {
- if (m_profilerDataModel->getEventId(i) != id)
+ if (m_profilerModelProxy->getEventId(modelIndex, i) != id)
continue;
- x = (m_profilerDataModel->getStartTime(i) - m_startTime) * m_spacing;
- eventType = m_profilerDataModel->getType(i);
- if (m_rowsExpanded[eventType])
- y = m_rowStarts[eventType] + DefaultRowHeight *
- (m_profilerDataModel->eventPosInType(i) + 1);
- else
- y = m_rowStarts[eventType] + DefaultRowHeight *
- m_profilerDataModel->getNestingLevel(i);
+ x = (m_profilerModelProxy->getStartTime(modelIndex, i) - m_startTime) * m_spacing;
+ y = (modelRowStart + m_profilerModelProxy->getEventRow(modelIndex, i)) * DefaultRowHeight;
- width = m_profilerDataModel->getDuration(i)*m_spacing;
+ width = m_profilerModelProxy->getDuration(modelIndex, i)*m_spacing;
if (width<1)
width = 1;
@@ -219,12 +187,14 @@ void TimelineRenderer::drawSelectionBoxes(QPainter *p, int fromIndex, int toInde
p->setPen(strongPen);
p->drawRect(selectedItemRect);
}
+
+ p->restore();
}
-void TimelineRenderer::drawBindingLoopMarkers(QPainter *p, int fromIndex, int toIndex)
+void TimelineRenderer::drawBindingLoopMarkers(QPainter *p, int modelIndex, int fromIndex, int toIndex)
{
int destindex;
- int xfrom, xto, eventType;
+ int xfrom, xto;
int yfrom, yto;
int radius = DefaultRowHeight / 3;
QPen shadowPen = QPen(QColor("grey"),2);
@@ -234,38 +204,24 @@ void TimelineRenderer::drawBindingLoopMarkers(QPainter *p, int fromIndex, int to
p->save();
for (int i = fromIndex; i <= toIndex; i++) {
- destindex = m_profilerDataModel->getBindingLoopDest(i);
+ destindex = m_profilerModelProxy->getBindingLoopDest(modelIndex, i);
if (destindex >= 0) {
// from
- xfrom = (m_profilerDataModel->getStartTime(i) +
- m_profilerDataModel->getDuration(i)/2 -
+ xfrom = (m_profilerModelProxy->getStartTime(modelIndex, i) +
+ m_profilerModelProxy->getDuration(modelIndex, i)/2 -
m_startTime) * m_spacing;
- eventType = m_profilerDataModel->getType(i);
- if (m_rowsExpanded[eventType])
- yfrom = m_rowStarts[eventType] + DefaultRowHeight*
- (m_profilerDataModel->eventPosInType(i) + 1);
- else
- yfrom = m_rowStarts[eventType] + DefaultRowHeight *
- m_profilerDataModel->getNestingLevel(i);
-
+ yfrom = getYPosition(modelIndex, i);
yfrom += DefaultRowHeight / 2;
// to
- xto = (m_profilerDataModel->getStartTime(destindex) +
- m_profilerDataModel->getDuration(destindex)/2 -
+ xto = (m_profilerModelProxy->getStartTime(modelIndex, destindex) +
+ m_profilerModelProxy->getDuration(modelIndex, destindex)/2 -
m_startTime) * m_spacing;
- eventType = m_profilerDataModel->getType(destindex);
- if (m_rowsExpanded[eventType])
- yto = m_rowStarts[eventType] + DefaultRowHeight *
- (m_profilerDataModel->eventPosInType(destindex) + 1);
- else
- yto = m_rowStarts[eventType] + DefaultRowHeight *
- m_profilerDataModel->getNestingLevel(destindex);
-
+ yto = getYPosition(modelIndex, destindex);
yto += DefaultRowHeight / 2;
// radius
- int eventWidth = m_profilerDataModel->getDuration(i) * m_spacing;
+ int eventWidth = m_profilerModelProxy->getDuration(modelIndex, i) * m_spacing;
radius = 5;
if (radius * 2 > eventWidth)
radius = eventWidth / 2;
@@ -292,7 +248,18 @@ void TimelineRenderer::drawBindingLoopMarkers(QPainter *p, int fromIndex, int to
p->restore();
}
-void TimelineRenderer::mousePressEvent(QGraphicsSceneMouseEvent *event)
+int TimelineRenderer::modelFromPosition(int y)
+{
+ y = y / DefaultRowHeight;
+ for (int modelIndex = 0; modelIndex < m_profilerModelProxy->modelCount(); modelIndex++) {
+ y -= m_profilerModelProxy->rowCount(modelIndex);
+ if (y < 0)
+ return modelIndex;
+ }
+ return 0;
+}
+
+void TimelineRenderer::mousePressEvent(QMouseEvent *event)
{
// special case: if there is a drag area below me, don't accept the
// events unless I'm actually clicking inside an item
@@ -303,19 +270,19 @@ void TimelineRenderer::mousePressEvent(QGraphicsSceneMouseEvent *event)
}
-void TimelineRenderer::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
+void TimelineRenderer::mouseReleaseEvent(QMouseEvent *event)
{
Q_UNUSED(event);
manageClicked();
}
-void TimelineRenderer::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
+void TimelineRenderer::mouseMoveEvent(QMouseEvent *event)
{
event->setAccepted(false);
}
-void TimelineRenderer::hoverMoveEvent(QGraphicsSceneHoverEvent *event)
+void TimelineRenderer::hoverMoveEvent(QHoverEvent *event)
{
Q_UNUSED(event);
manageHovered(event->pos().x(), event->pos().y());
@@ -326,15 +293,17 @@ void TimelineRenderer::hoverMoveEvent(QGraphicsSceneHoverEvent *event)
void TimelineRenderer::manageClicked()
{
if (m_currentSelection.eventIndex != -1) {
- if (m_currentSelection.eventIndex == m_selectedItem)
+ if (m_currentSelection.eventIndex == m_selectedItem && m_currentSelection.modelIndex == m_selectedModel)
setSelectionLocked(!m_selectionLocked);
else
setSelectionLocked(true);
- emit itemPressed(m_currentSelection.eventIndex);
+ emit itemPressed(m_currentSelection.modelIndex, m_currentSelection.eventIndex);
} else {
-// setSelectionLocked(false);
+ setSelectionLocked(false);
}
+ setSelectedModel(m_currentSelection.modelIndex);
setSelectedItem(m_currentSelection.eventIndex);
+
}
void TimelineRenderer::manageHovered(int x, int y)
@@ -344,6 +313,7 @@ void TimelineRenderer::manageHovered(int x, int y)
qint64 time = x * (m_endTime - m_startTime) / width() + m_startTime;
int row = y / DefaultRowHeight;
+ int modelIndex = modelFromPosition(y);
// already covered? nothing to do
if (m_currentSelection.eventIndex != -1 &&
@@ -354,34 +324,37 @@ void TimelineRenderer::manageHovered(int x, int y)
}
// find if there's items in the time range
- int eventFrom = m_profilerDataModel->findFirstIndex(time);
- int eventTo = m_profilerDataModel->findLastIndex(time);
- if (eventTo < eventFrom || eventTo >= m_profilerDataModel->count()) {
+ int eventFrom = m_profilerModelProxy->findFirstIndex(modelIndex, time);
+ int eventTo = m_profilerModelProxy->findLastIndex(modelIndex, time);
+ if (eventFrom == -1 ||
+ eventTo < eventFrom || eventTo >= m_profilerModelProxy->count()) {
m_currentSelection.eventIndex = -1;
return;
}
+ int modelRowStart = 0;
+ for (int mi = 0; mi < modelIndex; mi++)
+ modelRowStart += m_profilerModelProxy->rowCount(mi);
+
// find if we are in the right column
- int itemRow, eventType;
+ int itemRow;
for (int i=eventTo; i>=eventFrom; --i) {
- if (ceil(m_profilerDataModel->getEndTime(i)*m_spacing) < floor(time*m_spacing))
+ if (ceil(m_profilerModelProxy->getEndTime(modelIndex, i)*m_spacing) < floor(time*m_spacing))
continue;
- eventType = m_profilerDataModel->getType(i);
- if (m_rowsExpanded[eventType])
- itemRow = m_rowStarts[eventType]/DefaultRowHeight +
- m_profilerDataModel->eventPosInType(i) + 1;
- else
- itemRow = m_rowStarts[eventType]/DefaultRowHeight +
- m_profilerDataModel->getNestingLevel(i);
+ itemRow = modelRowStart + m_profilerModelProxy->getEventRow(modelIndex, i);
+
if (itemRow == row) {
// match
m_currentSelection.eventIndex = i;
- m_currentSelection.startTime = m_profilerDataModel->getStartTime(i);
- m_currentSelection.endTime = m_profilerDataModel->getEndTime(i);
+ m_currentSelection.startTime = m_profilerModelProxy->getStartTime(modelIndex, i);
+ m_currentSelection.endTime = m_profilerModelProxy->getEndTime(modelIndex, i);
m_currentSelection.row = row;
- if (!m_selectionLocked)
+ m_currentSelection.modelIndex = modelIndex;
+ if (!m_selectionLocked) {
+ setSelectedModel(modelIndex);
setSelectedItem(i);
+ }
return;
}
}
@@ -400,131 +373,189 @@ void TimelineRenderer::clearData()
m_currentSelection.endTime = -1;
m_currentSelection.row = -1;
m_currentSelection.eventIndex = -1;
+ m_currentSelection.modelIndex = -1;
m_selectedItem = -1;
+ m_selectedModel = -1;
m_selectionLocked = true;
}
-qint64 TimelineRenderer::getDuration(int index) const
-{
- Q_ASSERT(m_profilerDataModel);
- return m_profilerDataModel->getEndTime(index) -
- m_profilerDataModel->getStartTime(index);
-}
-
-QString TimelineRenderer::getFilename(int index) const
-{
- Q_ASSERT(m_profilerDataModel);
- return m_profilerDataModel->getFilename(index);
-}
-
-int TimelineRenderer::getLine(int index) const
+int TimelineRenderer::getYPosition(int modelIndex, int index) const
{
- Q_ASSERT(m_profilerDataModel);
- return m_profilerDataModel->getLine(index);
-}
+ Q_ASSERT(m_profilerModelProxy);
+ if (index >= m_profilerModelProxy->count())
+ return 0;
-QString TimelineRenderer::getDetails(int index) const
-{
- Q_ASSERT(m_profilerDataModel);
- return m_profilerDataModel->getDetails(index);
-}
+ int modelRowStart = 0;
+ for (int mi = 0; mi < modelIndex; mi++)
+ modelRowStart += m_profilerModelProxy->rowCount(mi);
-int TimelineRenderer::getYPosition(int index) const
-{
- Q_ASSERT(m_profilerDataModel);
- if (index >= m_profilerDataModel->count() || m_rowStarts.isEmpty())
- return 0;
- int y, eventType = m_profilerDataModel->getType(index);
- if (m_rowsExpanded[eventType])
- y = m_rowStarts[eventType] + DefaultRowHeight *
- (m_profilerDataModel->eventPosInType(index) + 1);
- else
- y = m_rowStarts[eventType] + DefaultRowHeight *
- m_profilerDataModel->getNestingLevel(index);
+ int y = DefaultRowHeight * (modelRowStart + m_profilerModelProxy->getEventRow(modelIndex, index));
return y;
}
-void TimelineRenderer::setRowExpanded(int rowIndex, bool expanded)
-{
- m_rowsExpanded[rowIndex] = expanded;
- update();
-}
-
void TimelineRenderer::selectNext()
{
- if (m_profilerDataModel->count() == 0)
+ if (m_profilerModelProxy->count() == 0)
return;
- // select next in view or after
- int newIndex = m_selectedItem+1;
- if (newIndex >= m_profilerDataModel->count())
- newIndex = 0;
- if (m_profilerDataModel->getEndTime(newIndex) < m_startTime)
- newIndex = m_profilerDataModel->findFirstIndexNoParents(m_startTime);
- setSelectedItem(newIndex);
+ qint64 searchTime = m_startTime;
+ if (m_selectedItem != -1)
+ searchTime = m_profilerModelProxy->getStartTime(m_selectedModel, m_selectedItem);
+
+ QVarLengthArray<int> itemIndexes(m_profilerModelProxy->modelCount());
+ for (int i = 0; i < m_profilerModelProxy->modelCount(); i++) {
+ if (m_profilerModelProxy->count(i) > 0) {
+ if (m_selectedModel == i) {
+ itemIndexes[i] = (m_selectedItem + 1) % m_profilerModelProxy->count(i);
+ } else {
+ if (m_profilerModelProxy->getStartTime(i, 0) > searchTime)
+ itemIndexes[i] = 0;
+ else
+ itemIndexes[i] = (m_profilerModelProxy->findLastIndex(i, searchTime) + 1) % m_profilerModelProxy->count(i);
+ }
+ } else {
+ itemIndexes[i] = -1;
+ }
+ }
+
+ int candidateModelIndex = -1;
+ qint64 candidateStartTime = m_profilerModelProxy->traceEndTime();
+ for (int i = 0; i < m_profilerModelProxy->modelCount(); i++) {
+ if (itemIndexes[i] == -1)
+ continue;
+ qint64 newStartTime = m_profilerModelProxy->getStartTime(i, itemIndexes[i]);
+ if (newStartTime > searchTime && newStartTime < candidateStartTime) {
+ candidateStartTime = newStartTime;
+ candidateModelIndex = i;
+ }
+ }
+
+ int itemIndex;
+ if (candidateModelIndex != -1) {
+ itemIndex = itemIndexes[candidateModelIndex];
+ } else {
+ // find the first index of them all (todo: the modelproxy should do this)
+ itemIndex = -1;
+ candidateStartTime = m_profilerModelProxy->traceEndTime();
+ for (int i = 0; i < m_profilerModelProxy->modelCount(); i++)
+ if (m_profilerModelProxy->count(i) > 0 &&
+ m_profilerModelProxy->getStartTime(i,0) < candidateStartTime) {
+ candidateModelIndex = i;
+ itemIndex = 0;
+ candidateStartTime = m_profilerModelProxy->getStartTime(i,0);
+ }
+ }
+
+ setSelectedModel(candidateModelIndex);
+ setSelectedItem(itemIndex);
}
void TimelineRenderer::selectPrev()
{
- if (m_profilerDataModel->count() == 0)
+ if (m_profilerModelProxy->count() == 0)
return;
- // select last in view or before
- int newIndex = m_selectedItem-1;
- if (newIndex < 0)
- newIndex = m_profilerDataModel->count()-1;
- if (m_profilerDataModel->getStartTime(newIndex) > m_endTime)
- newIndex = m_profilerDataModel->findLastIndex(m_endTime);
- setSelectedItem(newIndex);
+ qint64 searchTime = m_endTime;
+ if (m_selectedItem != -1)
+ searchTime = m_profilerModelProxy->getEndTime(m_selectedModel, m_selectedItem);
+
+ QVarLengthArray<int> itemIndexes(m_profilerModelProxy->modelCount());
+ for (int i = 0; i < m_profilerModelProxy->modelCount(); i++) {
+ if (m_selectedModel == i) {
+ itemIndexes[i] = m_selectedItem - 1;
+ if (itemIndexes[i] < 0)
+ itemIndexes[i] = m_profilerModelProxy->count(m_selectedModel) -1;
+ }
+ else
+ itemIndexes[i] = m_profilerModelProxy->findLastIndex(i, searchTime);
+ }
+
+ int candidateModelIndex = -1;
+ qint64 candidateStartTime = m_profilerModelProxy->traceStartTime();
+ for (int i = 0; i < m_profilerModelProxy->modelCount(); i++) {
+ if (itemIndexes[i] == -1
+ || itemIndexes[i] >= m_profilerModelProxy->count(i))
+ continue;
+ qint64 newStartTime = m_profilerModelProxy->getStartTime(i, itemIndexes[i]);
+ if (newStartTime < searchTime && newStartTime > candidateStartTime) {
+ candidateStartTime = newStartTime;
+ candidateModelIndex = i;
+ }
+ }
+
+ int itemIndex = -1;
+ if (candidateModelIndex != -1) {
+ itemIndex = itemIndexes[candidateModelIndex];
+ } else {
+ // find the last index of them all (todo: the modelproxy should do this)
+ candidateModelIndex = 0;
+ candidateStartTime = m_profilerModelProxy->traceStartTime();
+ for (int i = 0; i < m_profilerModelProxy->modelCount(); i++)
+ if (m_profilerModelProxy->count(i) > 0 &&
+ m_profilerModelProxy->getStartTime(i,m_profilerModelProxy->count(i)-1) > candidateStartTime) {
+ candidateModelIndex = i;
+ itemIndex = m_profilerModelProxy->count(candidateModelIndex) - 1;
+ candidateStartTime = m_profilerModelProxy->getStartTime(i,m_profilerModelProxy->count(i)-1);
+ }
+ }
+
+ setSelectedModel(candidateModelIndex);
+ setSelectedItem(itemIndex);
}
-int TimelineRenderer::nextItemFromId(int eventId) const
+int TimelineRenderer::nextItemFromId(int modelIndex, int eventId) const
{
int ndx = -1;
if (m_selectedItem == -1)
- ndx = m_profilerDataModel->findFirstIndexNoParents(m_startTime);
+ ndx = m_profilerModelProxy->findFirstIndexNoParents(modelIndex, m_startTime);
else
ndx = m_selectedItem + 1;
- if (ndx >= m_profilerDataModel->count())
+ if (ndx < 0)
+ return -1;
+ if (ndx >= m_profilerModelProxy->count(modelIndex))
ndx = 0;
int startIndex = ndx;
do {
- if (m_profilerDataModel->getEventId(ndx) == eventId)
+ if (m_profilerModelProxy->getEventId(modelIndex, ndx) == eventId)
return ndx;
- ndx = (ndx + 1) % m_profilerDataModel->count();
+ ndx = (ndx + 1) % m_profilerModelProxy->count(modelIndex);
} while (ndx != startIndex);
return -1;
}
-int TimelineRenderer::prevItemFromId(int eventId) const
+int TimelineRenderer::prevItemFromId(int modelIndex, int eventId) const
{
int ndx = -1;
if (m_selectedItem == -1)
- ndx = m_profilerDataModel->findFirstIndexNoParents(m_startTime);
+ ndx = m_profilerModelProxy->findFirstIndexNoParents(modelIndex, m_startTime);
else
ndx = m_selectedItem - 1;
if (ndx < 0)
- ndx = m_profilerDataModel->count() - 1;
+ ndx = m_profilerModelProxy->count(modelIndex) - 1;
int startIndex = ndx;
do {
- if (m_profilerDataModel->getEventId(ndx) == eventId)
+ if (m_profilerModelProxy->getEventId(modelIndex, ndx) == eventId)
return ndx;
if (--ndx < 0)
- ndx = m_profilerDataModel->count()-1;
+ ndx = m_profilerModelProxy->count(modelIndex)-1;
} while (ndx != startIndex);
return -1;
}
-void TimelineRenderer::selectNextFromId(int eventId)
+void TimelineRenderer::selectNextFromId(int modelIndex, int eventId)
{
- int eventIndex = nextItemFromId(eventId);
- if (eventIndex != -1)
+ int eventIndex = nextItemFromId(modelIndex, eventId);
+ if (eventIndex != -1) {
+ setSelectedModel(modelIndex);
setSelectedItem(eventIndex);
+ }
}
-void TimelineRenderer::selectPrevFromId(int eventId)
+void TimelineRenderer::selectPrevFromId(int modelIndex, int eventId)
{
- int eventIndex = prevItemFromId(eventId);
- if (eventIndex != -1)
+ int eventIndex = prevItemFromId(modelIndex, eventId);
+ if (eventIndex != -1) {
+ setSelectedModel(modelIndex);
setSelectedItem(eventIndex);
+ }
}
diff --git a/src/plugins/qmlprofiler/timelinerenderer.h b/src/plugins/qmlprofiler/timelinerenderer.h
index d408b5ef25..e5018565d7 100644
--- a/src/plugins/qmlprofiler/timelinerenderer.h
+++ b/src/plugins/qmlprofiler/timelinerenderer.h
@@ -30,26 +30,28 @@
#ifndef TIMELINERENDERER_H
#define TIMELINERENDERER_H
-#include <QDeclarativeItem>
-#include <QScriptValue>
-#include "qmlprofilerdatamodel.h"
+#include <QQuickPaintedItem>
+#include <QJSValue>
+#include "qmlprofilertimelinemodelproxy.h"
+#include "timelinemodelaggregator.h"
namespace QmlProfiler {
namespace Internal {
-class TimelineRenderer : public QDeclarativeItem
+class TimelineRenderer : public QQuickPaintedItem
{
Q_OBJECT
Q_PROPERTY(qint64 startTime READ startTime WRITE setStartTime NOTIFY startTimeChanged)
Q_PROPERTY(qint64 endTime READ endTime WRITE setEndTime NOTIFY endTimeChanged)
- Q_PROPERTY(QObject* profilerDataModel READ profilerDataModel WRITE setProfilerDataModel NOTIFY profilerDataModelChanged)
+ Q_PROPERTY(QObject *profilerModelProxy READ profilerModelProxy WRITE setProfilerModelProxy NOTIFY profilerModelProxyChanged)
Q_PROPERTY(bool selectionLocked READ selectionLocked WRITE setSelectionLocked NOTIFY selectionLockedChanged)
Q_PROPERTY(int selectedItem READ selectedItem WRITE setSelectedItem NOTIFY selectedItemChanged)
+ Q_PROPERTY(int selectedModel READ selectedModel WRITE setSelectedModel NOTIFY selectedModelChanged)
Q_PROPERTY(int startDragArea READ startDragArea WRITE setStartDragArea NOTIFY startDragAreaChanged)
Q_PROPERTY(int endDragArea READ endDragArea WRITE setEndDragArea NOTIFY endDragAreaChanged)
public:
- explicit TimelineRenderer(QDeclarativeItem *parent = 0);
+ explicit TimelineRenderer(QQuickPaintedItem *parent = 0);
qint64 startTime() const
{
@@ -71,6 +73,11 @@ public:
return m_selectedItem;
}
+ int selectedModel() const
+ {
+ return m_selectedModel;
+ }
+
int startDragArea() const
{
return m_startDragArea;
@@ -81,37 +88,28 @@ public:
return m_endDragArea;
}
- QmlProfilerDataModel *profilerDataModel() const { return m_profilerDataModel; }
- void setProfilerDataModel(QObject *profilerDataModel)
- {
- m_profilerDataModel = qobject_cast<QmlProfilerDataModel *>(profilerDataModel);
- emit profilerDataModelChanged(m_profilerDataModel);
- }
-
- Q_INVOKABLE qint64 getDuration(int index) const;
- Q_INVOKABLE QString getFilename(int index) const;
- Q_INVOKABLE int getLine(int index) const;
- Q_INVOKABLE QString getDetails(int index) const;
- Q_INVOKABLE int getYPosition(int index) const;
+ TimelineModelAggregator *profilerModelProxy() const { return m_profilerModelProxy; }
+ void setProfilerModelProxy(QObject *profilerModelProxy);
- Q_INVOKABLE void setRowExpanded(int rowIndex, bool expanded);
+ Q_INVOKABLE int getYPosition(int modelIndex, int index) const;
Q_INVOKABLE void selectNext();
Q_INVOKABLE void selectPrev();
- Q_INVOKABLE int nextItemFromId(int eventId) const;
- Q_INVOKABLE int prevItemFromId(int eventId) const;
- Q_INVOKABLE void selectNextFromId(int eventId);
- Q_INVOKABLE void selectPrevFromId(int eventId);
+ Q_INVOKABLE int nextItemFromId(int modelIndex, int eventId) const;
+ Q_INVOKABLE int prevItemFromId(int modelIndex, int eventId) const;
+ Q_INVOKABLE void selectNextFromId(int modelIndex, int eventId);
+ Q_INVOKABLE void selectPrevFromId(int modelIndex, int eventId);
signals:
void startTimeChanged(qint64 arg);
void endTimeChanged(qint64 arg);
- void profilerDataModelChanged(QmlProfilerDataModel *list);
+ void profilerModelProxyChanged(TimelineModelAggregator *list);
void selectionLockedChanged(bool locked);
- void selectedItemChanged(int itemIndex);
+ void selectedItemChanged(int modelIndex, int itemIndex);
+ void selectedModelChanged(int modelIndex);
void startDragAreaChanged(int startDragArea);
void endDragAreaChanged(int endDragArea);
- void itemPressed(int pressedItem);
+ void itemPressed(int modelIndex, int pressedItem);
public slots:
void clearData();
@@ -148,7 +146,16 @@ public slots:
if (m_selectedItem != itemIndex) {
m_selectedItem = itemIndex;
update();
- emit selectedItemChanged(itemIndex);
+ emit selectedItemChanged(m_selectedModel, itemIndex);
+ }
+ }
+
+ void setSelectedModel(int modelIndex)
+ {
+ if (m_selectedModel != modelIndex) {
+ m_selectedModel = modelIndex;
+ update();
+ emit selectedModelChanged(modelIndex);
}
}
@@ -169,18 +176,18 @@ public slots:
}
protected:
- virtual void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *);
+ virtual void paint(QPainter *);
virtual void componentComplete();
- virtual void mousePressEvent(QGraphicsSceneMouseEvent *event);
- virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
- virtual void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
- virtual void hoverMoveEvent(QGraphicsSceneHoverEvent *event);
+ virtual void mousePressEvent(QMouseEvent *event);
+ virtual void mouseReleaseEvent(QMouseEvent *event);
+ virtual void mouseMoveEvent(QMouseEvent *event);
+ virtual void hoverMoveEvent(QHoverEvent *event);
private:
- QColor colorForItem(int itemIndex);
- void drawItemsToPainter(QPainter *p, int fromIndex, int toIndex);
- void drawSelectionBoxes(QPainter *p, int fromIndex, int toIndex);
- void drawBindingLoopMarkers(QPainter *p, int fromIndex, int toIndex);
+ void drawItemsToPainter(QPainter *p, int modelIndex, int fromIndex, int toIndex);
+ void drawSelectionBoxes(QPainter *p, int modelIndex, int fromIndex, int toIndex);
+ void drawBindingLoopMarkers(QPainter *p, int modelIndex, int fromIndex, int toIndex);
+ int modelFromPosition(int y);
void manageClicked();
void manageHovered(int x, int y);
@@ -192,21 +199,18 @@ private:
qint64 m_lastStartTime;
qint64 m_lastEndTime;
- QmlProfilerDataModel *m_profilerDataModel;
-
- QList<int> m_rowLastX;
- QList<int> m_rowStarts;
- QList<int> m_rowWidths;
- QList<bool> m_rowsExpanded;
+ TimelineModelAggregator *m_profilerModelProxy;
struct {
qint64 startTime;
qint64 endTime;
int row;
int eventIndex;
+ int modelIndex;
} m_currentSelection;
int m_selectedItem;
+ int m_selectedModel;
bool m_selectionLocked;
int m_startDragArea;
int m_endDragArea;
diff --git a/src/plugins/qmlprojectmanager/QmlProjectManager.pluginspec.in b/src/plugins/qmlprojectmanager/QmlProjectManager.pluginspec.in
index f53fcb55a6..72784c7c7f 100644
--- a/src/plugins/qmlprojectmanager/QmlProjectManager.pluginspec.in
+++ b/src/plugins/qmlprojectmanager/QmlProjectManager.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"QmlProjectManager\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"QmlProjectManager\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/qmlprojectmanager/fileformat/filefilteritems.h b/src/plugins/qmlprojectmanager/fileformat/filefilteritems.h
index b3d2093a01..7f5cea6423 100644
--- a/src/plugins/qmlprojectmanager/fileformat/filefilteritems.h
+++ b/src/plugins/qmlprojectmanager/fileformat/filefilteritems.h
@@ -36,8 +36,6 @@
#include <QSet>
#include <QTimer>
-#include <qdeclarative.h>
-
QT_FORWARD_DECLARE_CLASS(QDir)
namespace Utils {
@@ -181,10 +179,4 @@ public:
} // namespace QmlProjectManager
-QML_DECLARE_TYPE(QmlProjectManager::QmlFileFilterItem)
-QML_DECLARE_TYPE(QmlProjectManager::JsFileFilterItem)
-QML_DECLARE_TYPE(QmlProjectManager::ImageFileFilterItem)
-QML_DECLARE_TYPE(QmlProjectManager::CssFileFilterItem)
-QML_DECLARE_TYPE(QmlProjectManager::OtherFileFilterItem)
-
#endif // FILEFILTERITEMS_HPROJECTITEM_H
diff --git a/src/plugins/qmlprojectmanager/fileformat/qmlprojectfileformat.cpp b/src/plugins/qmlprojectmanager/fileformat/qmlprojectfileformat.cpp
index a78b35cf65..f08452a845 100644
--- a/src/plugins/qmlprojectmanager/fileformat/qmlprojectfileformat.cpp
+++ b/src/plugins/qmlprojectmanager/fileformat/qmlprojectfileformat.cpp
@@ -30,26 +30,105 @@
#include "qmlprojectfileformat.h"
#include "qmlprojectitem.h"
#include "filefilteritems.h"
+#include <qmljs/qmljssimplereader.h>
-#include <qdeclarative.h>
+#include <QVariant>
+#include <QDebug>
+
+enum {
+ debug = false
+};
+
+namespace {
+
+void setupFileFilterItem(QmlProjectManager::FileFilterBaseItem *fileFilterItem, const QmlJS::SimpleReaderNode::Ptr &node)
+{
+ const QVariant directoryProperty = node->property(QLatin1String("directory"));
+ if (directoryProperty.isValid())
+ fileFilterItem->setDirectory(directoryProperty.toString());
+
+ const QVariant recursiveProperty = node->property(QLatin1String("recursive"));
+ if (recursiveProperty.isValid())
+ fileFilterItem->setRecursive(recursiveProperty.toBool());
+
+ const QVariant pathsProperty = node->property(QLatin1String("paths"));
+ if (pathsProperty.isValid())
+ fileFilterItem->setPathsProperty(pathsProperty.toStringList());
+
+ if (debug)
+ qDebug() << "directory:" << directoryProperty << "recursive" << recursiveProperty << "paths" << pathsProperty;
+}
+
+} //namespace
namespace QmlProjectManager {
-void QmlProjectFileFormat::registerDeclarativeTypes()
+QmlProjectItem *QmlProjectFileFormat::parseProjectFile(const QString &fileName, QString *errorMessage)
{
- qmlRegisterType<QmlProjectManager::QmlProjectContentItem>();
- qmlRegisterType<QmlProjectManager::QmlProjectItem>("QmlProject",1,0,"Project");
- qmlRegisterType<QmlProjectManager::QmlProjectItem>("QmlProject",1,1,"Project");
-
- qmlRegisterType<QmlProjectManager::QmlFileFilterItem>("QmlProject",1,0,"QmlFiles");
- qmlRegisterType<QmlProjectManager::QmlFileFilterItem>("QmlProject",1,1,"QmlFiles");
- qmlRegisterType<QmlProjectManager::JsFileFilterItem>("QmlProject",1,0,"JavaScriptFiles");
- qmlRegisterType<QmlProjectManager::JsFileFilterItem>("QmlProject",1,1,"JavaScriptFiles");
- qmlRegisterType<QmlProjectManager::ImageFileFilterItem>("QmlProject",1,0,"ImageFiles");
- qmlRegisterType<QmlProjectManager::ImageFileFilterItem>("QmlProject",1,1,"ImageFiles");
- qmlRegisterType<QmlProjectManager::CssFileFilterItem>("QmlProject",1,0,"CssFiles");
- qmlRegisterType<QmlProjectManager::CssFileFilterItem>("QmlProject",1,1,"CssFiles");
- qmlRegisterType<QmlProjectManager::OtherFileFilterItem>("QmlProject",1,1,"Files");
+ QmlJS::SimpleReader simpleQmlJSReader;
+
+ const QmlJS::SimpleReaderNode::Ptr rootNode = simpleQmlJSReader.readFile(fileName);
+
+ if (!simpleQmlJSReader.errors().isEmpty() || !rootNode->isValid()) {
+ qWarning() << "unable to parse:" << fileName;
+ qWarning() << simpleQmlJSReader.errors();
+ if (errorMessage)
+ *errorMessage = simpleQmlJSReader.errors().join(QLatin1String(", "));
+ return 0;
+ }
+
+ if (rootNode->name() == QLatin1String("Project")) {
+ QmlProjectItem *projectItem = new QmlProjectItem();
+
+ const QVariant mainFileProperty = rootNode->property(QLatin1String("mainFile"));
+ if (mainFileProperty.isValid())
+ projectItem->setMainFile(mainFileProperty.toString());
+
+ const QVariant importPathsProperty = rootNode->property(QLatin1String("importPaths"));
+ if (importPathsProperty.isValid())
+ projectItem->setImportPaths(importPathsProperty.toStringList());
+
+ if (debug) {
+ qDebug() << "importPath:" << importPathsProperty << "mainFile:" << mainFileProperty;
+ }
+
+ foreach (const QmlJS::SimpleReaderNode::Ptr &childNode, rootNode->children()) {
+ if (childNode->name() == QLatin1String("QmlFiles")) {
+ if (debug)
+ qDebug() << "QmlFiles";
+ QmlFileFilterItem *qmlFileFilterItem = new QmlFileFilterItem(projectItem);
+ setupFileFilterItem(qmlFileFilterItem, childNode);
+ projectItem->appendContent(qmlFileFilterItem);
+ } else if (childNode->name() == QLatin1String("JavaScriptFiles")) {
+ if (debug)
+ qDebug() << "JavaScriptFiles";
+ JsFileFilterItem *jsFileFilterItem = new JsFileFilterItem(projectItem);
+ setupFileFilterItem(jsFileFilterItem, childNode);
+ projectItem->appendContent(jsFileFilterItem);
+ } else if (childNode->name() == QLatin1String("ImageFiles")) {
+ if (debug)
+ qDebug() << "ImageFiles";
+ ImageFileFilterItem *imageFileFilterItem = new ImageFileFilterItem(projectItem);
+ setupFileFilterItem(imageFileFilterItem, childNode);
+ projectItem->appendContent(imageFileFilterItem);
+
+ } else if (childNode->name() == QLatin1String("CssFiles")) {
+ if (debug)
+ qDebug() << "CssFiles";
+ CssFileFilterItem *cssFileFilterItem = new CssFileFilterItem(projectItem);
+ setupFileFilterItem(cssFileFilterItem, childNode);
+ projectItem->appendContent(cssFileFilterItem);
+ } else {
+ qWarning() << "Unkwown type:" << childNode->name();
+ }
+ }
+ return projectItem;
+ }
+
+ if (errorMessage)
+ *errorMessage = tr("Invalid root element: %1").arg(rootNode->name());
+
+ return 0;
}
} // namespace QmlProjectManager
diff --git a/src/plugins/qmlprojectmanager/fileformat/qmlprojectfileformat.h b/src/plugins/qmlprojectmanager/fileformat/qmlprojectfileformat.h
index 89f8cc1e98..6cc762a5a5 100644
--- a/src/plugins/qmlprojectmanager/fileformat/qmlprojectfileformat.h
+++ b/src/plugins/qmlprojectmanager/fileformat/qmlprojectfileformat.h
@@ -30,11 +30,19 @@
#ifndef QMLPROJECTFILEFORMAT_H
#define QMLPROJECTFILEFORMAT_H
+#include <QCoreApplication>
+#include <QString>
+
namespace QmlProjectManager {
-class QmlProjectFileFormat {
+class QmlProjectItem;
+
+class QmlProjectFileFormat
+{
+ Q_DECLARE_TR_FUNCTIONS(QmlProjectManager::QmlProjectFileFormat)
+
public:
- static void registerDeclarativeTypes();
+ static QmlProjectItem *parseProjectFile(const QString &fileName, QString *errorMessage = 0);
};
} // namespace QmlProjectManager
diff --git a/src/plugins/qmlprojectmanager/fileformat/qmlprojectitem.cpp b/src/plugins/qmlprojectmanager/fileformat/qmlprojectitem.cpp
index 7b6eef9e2a..8ac084271e 100644
--- a/src/plugins/qmlprojectmanager/fileformat/qmlprojectitem.cpp
+++ b/src/plugins/qmlprojectmanager/fileformat/qmlprojectitem.cpp
@@ -77,12 +77,6 @@ QmlProjectItem::~QmlProjectItem()
delete d_ptr;
}
-QDeclarativeListProperty<QmlProjectContentItem> QmlProjectItem::content()
-{
- Q_D(QmlProjectItem);
- return QDeclarativeListProperty<QmlProjectContentItem>(this, d->content);
-}
-
QString QmlProjectItem::sourceDirectory() const
{
Q_D(const QmlProjectItem);
@@ -194,6 +188,12 @@ void QmlProjectItem::setMainFile(const QString &mainFilePath)
emit mainFileChanged();
}
+void QmlProjectItem::appendContent(QmlProjectContentItem *contentItem)
+{
+ Q_D(QmlProjectItem);
+ d->content.append(contentItem);
+}
+
} // namespace QmlProjectManager
#include "qmlprojectitem.moc"
diff --git a/src/plugins/qmlprojectmanager/fileformat/qmlprojectitem.h b/src/plugins/qmlprojectmanager/fileformat/qmlprojectitem.h
index e4b78ffe22..af73e0b17a 100644
--- a/src/plugins/qmlprojectmanager/fileformat/qmlprojectitem.h
+++ b/src/plugins/qmlprojectmanager/fileformat/qmlprojectitem.h
@@ -33,7 +33,6 @@
#include <QObject>
#include <QSet>
#include <QStringList>
-#include <qdeclarative.h>
namespace QmlProjectManager {
@@ -52,19 +51,14 @@ class QmlProjectItem : public QObject
Q_OBJECT
Q_DECLARE_PRIVATE(QmlProjectItem)
- Q_PROPERTY(QDeclarativeListProperty<QmlProjectManager::QmlProjectContentItem> content READ content DESIGNABLE false)
Q_PROPERTY(QString sourceDirectory READ sourceDirectory NOTIFY sourceDirectoryChanged)
Q_PROPERTY(QStringList importPaths READ importPaths WRITE setImportPaths NOTIFY importPathsChanged)
Q_PROPERTY(QString mainFile READ mainFile WRITE setMainFile NOTIFY mainFileChanged)
- Q_CLASSINFO("DefaultProperty", "content")
-
public:
QmlProjectItem(QObject *parent = 0);
~QmlProjectItem();
- QDeclarativeListProperty<QmlProjectContentItem> content();
-
QString sourceDirectory() const;
void setSourceDirectory(const QString &directoryPath);
@@ -77,6 +71,7 @@ public:
QString mainFile() const;
void setMainFile(const QString &mainFilePath);
+ void appendContent(QmlProjectContentItem* contentItem);
signals:
void qmlFilesChanged(const QSet<QString> &, const QSet<QString> &);
@@ -90,8 +85,4 @@ protected:
} // namespace QmlProjectManager
-QML_DECLARE_TYPE(QmlProjectManager::QmlProjectItem)
-QML_DECLARE_TYPE(QmlProjectManager::QmlProjectContentItem)
-Q_DECLARE_METATYPE(QList<QmlProjectManager::QmlProjectContentItem *>)
-
#endif // QMLPROJECTITEM_H
diff --git a/src/plugins/qmlprojectmanager/qmlapp.cpp b/src/plugins/qmlprojectmanager/qmlapp.cpp
index edffa2c3ed..fd3998a08a 100644
--- a/src/plugins/qmlprojectmanager/qmlapp.cpp
+++ b/src/plugins/qmlprojectmanager/qmlapp.cpp
@@ -52,7 +52,7 @@ static QStringList binaryFiles()
QString QmlApp::templateRootDirectory()
{
- return Core::ICore::instance()->resourcePath() + QLatin1String("/templates/qml/");
+ return Core::ICore::resourcePath() + QLatin1String("/templates/qml/");
}
TemplateInfo::TemplateInfo()
diff --git a/src/plugins/qmlprojectmanager/qmlapplicationwizard.cpp b/src/plugins/qmlprojectmanager/qmlapplicationwizard.cpp
index ae4dbcf4c6..74661acaa5 100644
--- a/src/plugins/qmlprojectmanager/qmlapplicationwizard.cpp
+++ b/src/plugins/qmlprojectmanager/qmlapplicationwizard.cpp
@@ -65,58 +65,51 @@ 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))
+QmlApplicationWizard::QmlApplicationWizard(const TemplateInfo &templateInfo)
+ : m_qmlApp(new QmlApp(this))
{
+ setWizardKind(ProjectWizard);
+ setCategory(QLatin1String(ProjectExplorer::Constants::QT_APPLICATION_WIZARD_CATEGORY));
+ setId(QLatin1String("QA.QMLB Application"));
+ setIcon(QIcon(QLatin1String(Qt4ProjectManager::Constants::ICON_QTQUICK_APP)));
+ setDisplayCategory(
+ QLatin1String(ProjectExplorer::Constants::QT_APPLICATION_WIZARD_CATEGORY_DISPLAY));
+ setDisplayName(tr("Qt Quick Application"));
+ setDescription(tr("Creates a Qt Quick application project."));
+
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);
+ QmlApplicationWizard *wizard = new QmlApplicationWizard(templateInfo);
+ wizard->setDisplayName(templateInfo.displayName);
+ wizard->setDescription(templateInfo.description);
const QString imagePath = templateInfo.templatePath + QLatin1String("/template.png");
if (QFileInfo(imagePath).exists())
- parameters.setDescriptionImage(imagePath);
- parameters.setCategory(
+ wizard->setDescriptionImage(imagePath);
+ wizard->setCategory(
QLatin1String(ProjectExplorer::Constants::QT_APPLICATION_WIZARD_CATEGORY));
- parameters.setDisplayCategory(
+ wizard->setDisplayCategory(
QLatin1String(ProjectExplorer::Constants::QT_APPLICATION_WIZARD_CATEGORY_DISPLAY));
- parameters.setKind(IWizard::ProjectWizard);
- parameters.setId(templateInfo.wizardId);
+ wizard->setWizardKind(IWizard::ProjectWizard);
+ wizard->setId(templateInfo.wizardId);
QStringList stringList =
- templateInfo.featuresRequired.split(QLatin1Char(','), QString::SkipEmptyParts);;
+ 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);
+ wizard->setRequiredFeatures(features);
+ wizard->setIcon(QIcon(QLatin1String(Qt4ProjectManager::Constants::ICON_QTQUICK_APP)));
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
{
@@ -136,22 +129,6 @@ QWizard *QmlApplicationWizard::createWizardDialog(QWidget *parent,
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
{
@@ -161,7 +138,6 @@ GeneratedFiles QmlApplicationWizard::generateFiles(const QWizard * /*wizard*/,
bool QmlApplicationWizard::postGenerateFiles(const QWizard * /*wizard*/, const GeneratedFiles &l,
QString *errorMessage)
{
- writeUserFile(m_qmlApp->creatorFileName());
return ProjectExplorer::CustomProjectWizard::postGenerateOpen(l, errorMessage);
}
diff --git a/src/plugins/qmlprojectmanager/qmlapplicationwizard.h b/src/plugins/qmlprojectmanager/qmlapplicationwizard.h
index 506429eca1..6d56198837 100644
--- a/src/plugins/qmlprojectmanager/qmlapplicationwizard.h
+++ b/src/plugins/qmlprojectmanager/qmlapplicationwizard.h
@@ -60,25 +60,21 @@ private:
class QmlApplicationWizard : public Core::BaseFileWizard
{
Q_OBJECT
- Q_DISABLE_COPY(QmlApplicationWizard)
+
public:
- QmlApplicationWizard(const Core::BaseFileWizardParameters &parameters,
- const TemplateInfo &templateInfo, QObject *parent = 0);
+ explicit QmlApplicationWizard(const TemplateInfo &templateInfo);
static void createInstances(ExtensionSystem::IPlugin *plugin);
-
-private: // functions
+private:
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);
- static Core::BaseFileWizardParameters parameters();
-
-private: //variables
- mutable QString m_id;
+private:
+// mutable QString m_id;
QmlApp *m_qmlApp;
};
diff --git a/src/plugins/qmlprojectmanager/qmlproject.cpp b/src/plugins/qmlprojectmanager/qmlproject.cpp
index 0973750a3c..dabdf32771 100644
--- a/src/plugins/qmlprojectmanager/qmlproject.cpp
+++ b/src/plugins/qmlprojectmanager/qmlproject.cpp
@@ -29,6 +29,7 @@
#include "qmlproject.h"
#include "qmlprojectfile.h"
+#include "fileformat/qmlprojectfileformat.h"
#include "fileformat/qmlprojectitem.h"
#include "qmlprojectrunconfiguration.h"
#include "qmlprojectconstants.h"
@@ -46,11 +47,12 @@
#include <projectexplorer/target.h>
#include <qtsupport/qtsupportconstants.h>
-#include <QDeclarativeComponent>
#include <QDebug>
-namespace QmlProjectManager {
+using namespace Core;
+using namespace ProjectExplorer;
+namespace QmlProjectManager {
namespace Internal {
class QmlProjectKitMatcher : public ProjectExplorer::KitMatcher
@@ -108,8 +110,8 @@ QmlProject::QmlProject(Internal::Manager *manager, const QString &fileName)
m_defaultImport(UnknownImport),
m_modelManager(QmlJS::ModelManagerInterface::instance())
{
- setProjectContext(Core::Context(QmlProjectManager::Constants::PROJECTCONTEXT));
- setProjectLanguages(Core::Context(ProjectExplorer::Constants::LANG_QMLJS));
+ setProjectContext(Context(QmlProjectManager::Constants::PROJECTCONTEXT));
+ setProjectLanguages(Context(ProjectExplorer::Constants::LANG_QMLJS));
QFileInfo fileInfo(m_fileName);
m_projectName = fileInfo.completeBaseName();
@@ -117,7 +119,7 @@ QmlProject::QmlProject(Internal::Manager *manager, const QString &fileName)
m_file = new Internal::QmlProjectFile(this, fileName);
m_rootNode = new Internal::QmlProjectNode(this, m_file);
- Core::DocumentManager::addDocument(m_file, true);
+ DocumentManager::addDocument(m_file, true);
m_manager->registerProject(this);
}
@@ -126,7 +128,7 @@ QmlProject::~QmlProject()
{
m_manager->unregisterProject(this);
- Core::DocumentManager::removeDocument(m_file);
+ DocumentManager::removeDocument(m_file);
delete m_projectItem.data();
delete m_rootNode;
@@ -157,7 +159,7 @@ void QmlProject::addedRunConfiguration(ProjectExplorer::RunConfiguration *rc)
QDir QmlProject::projectDir() const
{
- return QFileInfo(document()->fileName()).dir();
+ return QFileInfo(projectFilePath()).dir();
}
QString QmlProject::filesFileName() const
@@ -177,27 +179,20 @@ static QmlProject::QmlImport detectImport(const QString &qml) {
void QmlProject::parseProject(RefreshOptions options)
{
- Core::MessageManager *messageManager = Core::ICore::messageManager();
if (options & Files) {
if (options & ProjectFile)
delete m_projectItem.data();
if (!m_projectItem) {
- Utils::FileReader reader;
- if (reader.fetch(m_fileName)) {
- QDeclarativeComponent *component = new QDeclarativeComponent(&m_engine, this);
- component->setData(reader.data(), QUrl::fromLocalFile(m_fileName));
- if (component->isReady()
- && qobject_cast<QmlProjectItem*>(component->create())) {
- m_projectItem = qobject_cast<QmlProjectItem*>(component->create());
- connect(m_projectItem.data(), SIGNAL(qmlFilesChanged(QSet<QString>,QSet<QString>)),
- this, SLOT(refreshFiles(QSet<QString>,QSet<QString>)));
- } else {
- messageManager->printToOutputPane(tr("Error while loading project file %1.").arg(m_fileName), Core::MessageManager::NoModeSwitch);
- messageManager->printToOutputPane(component->errorString(), Core::MessageManager::NoModeSwitch);
- }
- } else {
- messageManager->printToOutputPane(tr("QML project: %1").arg(reader.errorString()), Core::MessageManager::NoModeSwitch);
- }
+ QString errorMessage;
+ m_projectItem = QmlProjectFileFormat::parseProjectFile(m_fileName, &errorMessage);
+ if (m_projectItem) {
+ connect(m_projectItem.data(), SIGNAL(qmlFilesChanged(QSet<QString>,QSet<QString>)),
+ this, SLOT(refreshFiles(QSet<QString>,QSet<QString>)));
+
+ } else {
+ MessageManager::write(tr("Error while loading project file %1.").arg(m_fileName), MessageManager::NoModeSwitch);
+ MessageManager::write(errorMessage);
+ }
}
if (m_projectItem) {
m_projectItem.data()->setSourceDirectory(projectDir().path());
@@ -209,10 +204,8 @@ void QmlProject::parseProject(RefreshOptions options)
Utils::FileReader reader;
QString errorMessage;
if (!reader.fetch(mainFilePath, &errorMessage)) {
- messageManager->printToOutputPane(
- tr("Warning while loading project file %1.").arg(m_fileName),
- Core::MessageManager::NoModeSwitch);
- messageManager->printToOutputPane(errorMessage, Core::MessageManager::NoModeSwitch);
+ MessageManager::write(tr("Warning while loading project file %1.").arg(m_fileName));
+ MessageManager::write(errorMessage);
} else {
m_defaultImport = detectImport(QString::fromUtf8(reader.data()));
}
@@ -318,12 +311,12 @@ QString QmlProject::displayName() const
return m_projectName;
}
-Core::Id QmlProject::id() const
+Id QmlProject::id() const
{
- return Core::Id("QmlProjectManager.QmlProject");
+ return "QmlProjectManager.QmlProject";
}
-Core::IDocument *QmlProject::document() const
+IDocument *QmlProject::document() const
{
return m_file;
}
@@ -335,7 +328,7 @@ ProjectExplorer::IProjectManager *QmlProject::projectManager() const
bool QmlProject::supportsKit(ProjectExplorer::Kit *k, QString *errorMessage) const
{
- Core::Id deviceType = ProjectExplorer::DeviceTypeKitInformation::deviceTypeId(k);
+ Id deviceType = ProjectExplorer::DeviceTypeKitInformation::deviceTypeId(k);
if (deviceType != ProjectExplorer::Constants::DESKTOP_DEVICE_TYPE) {
if (errorMessage)
*errorMessage = tr("Device type is not desktop.");
@@ -385,13 +378,12 @@ bool QmlProject::fromMap(const QVariantMap &map)
if (!activeTarget()) {
// find a kit that matches prerequisites (prefer default one)
Internal::QmlProjectKitMatcher matcher(defaultImport());
- ProjectExplorer::KitManager *kitManager = ProjectExplorer::KitManager::instance();
- QList<ProjectExplorer::Kit*> kits = kitManager->kits(&matcher);
+ QList<Kit*> kits = KitManager::matchingKits(matcher);
if (!kits.isEmpty()) {
- ProjectExplorer::Kit *kit = 0;
- if (kits.contains(kitManager->defaultKit())) {
- kit = kitManager->defaultKit();
+ Kit *kit = 0;
+ if (kits.contains(KitManager::defaultKit())) {
+ kit = KitManager::defaultKit();
} else {
kit = kits.first();
}
@@ -401,7 +393,7 @@ bool QmlProject::fromMap(const QVariantMap &map)
// addedTarget calls updateEnabled on the runconfigurations
// which needs to happen after refresh
- foreach (ProjectExplorer::Target *t, targets())
+ foreach (Target *t, targets())
addedTarget(t);
connect(this, SIGNAL(addedTarget(ProjectExplorer::Target*)),
diff --git a/src/plugins/qmlprojectmanager/qmlproject.h b/src/plugins/qmlprojectmanager/qmlproject.h
index cc34f18f65..01b6ccb589 100644
--- a/src/plugins/qmlprojectmanager/qmlproject.h
+++ b/src/plugins/qmlprojectmanager/qmlproject.h
@@ -34,7 +34,6 @@
#include <projectexplorer/project.h>
-#include <QDeclarativeEngine>
#include <QPointer>
namespace ProjectExplorer { class RunConfiguration; }
@@ -119,8 +118,6 @@ private:
// plain format
QStringList m_files;
- // qml based, new format
- QDeclarativeEngine m_engine;
QPointer<QmlProjectItem> m_projectItem;
Internal::QmlProjectNode *m_rootNode;
diff --git a/src/plugins/qmlprojectmanager/qmlprojectconstants.h b/src/plugins/qmlprojectmanager/qmlprojectconstants.h
index b3b98ab6a4..0ec4d20bc6 100644
--- a/src/plugins/qmlprojectmanager/qmlprojectconstants.h
+++ b/src/plugins/qmlprojectmanager/qmlprojectconstants.h
@@ -35,8 +35,8 @@
namespace QmlProjectManager {
namespace Constants {
-const char *const PROJECTCONTEXT = "QmlProject.ProjectContext";
-const char *const QMLPROJECT_MIMETYPE = QmlJSTools::Constants::QMLPROJECT_MIMETYPE;
+const char PROJECTCONTEXT[] = "QmlProject.ProjectContext";
+const char * const QMLPROJECT_MIMETYPE = QmlJSTools::Constants::QMLPROJECT_MIMETYPE;
} // namespace Constants
} // namespace QmlProjectManager
diff --git a/src/plugins/qmlprojectmanager/qmlprojectenvironmentaspect.cpp b/src/plugins/qmlprojectmanager/qmlprojectenvironmentaspect.cpp
index 406e906e76..cef5dfeee4 100644
--- a/src/plugins/qmlprojectmanager/qmlprojectenvironmentaspect.cpp
+++ b/src/plugins/qmlprojectmanager/qmlprojectenvironmentaspect.cpp
@@ -58,14 +58,9 @@ QmlProjectEnvironmentAspect::QmlProjectEnvironmentAspect(ProjectExplorer::RunCon
ProjectExplorer::EnvironmentAspect(rc)
{ }
-QmlProjectEnvironmentAspect *QmlProjectEnvironmentAspect::clone(ProjectExplorer::RunConfiguration *parent) const
+QmlProjectEnvironmentAspect *QmlProjectEnvironmentAspect::create(ProjectExplorer::RunConfiguration *parent) const
{
- return new QmlProjectEnvironmentAspect(this, parent);
+ return new QmlProjectEnvironmentAspect(parent);
}
-QmlProjectEnvironmentAspect::QmlProjectEnvironmentAspect(const QmlProjectManager::QmlProjectEnvironmentAspect *other,
- ProjectExplorer::RunConfiguration *parent) :
- ProjectExplorer::EnvironmentAspect(other, parent)
-{ }
-
} // namespace QmlProjectManager
diff --git a/src/plugins/qmlprojectmanager/qmlprojectenvironmentaspect.h b/src/plugins/qmlprojectmanager/qmlprojectenvironmentaspect.h
index a0f806ee03..6b6e464f67 100644
--- a/src/plugins/qmlprojectmanager/qmlprojectenvironmentaspect.h
+++ b/src/plugins/qmlprojectmanager/qmlprojectenvironmentaspect.h
@@ -42,7 +42,7 @@ class QmlProjectEnvironmentAspect : public ProjectExplorer::EnvironmentAspect
public:
QmlProjectEnvironmentAspect(ProjectExplorer::RunConfiguration *rc);
- QmlProjectEnvironmentAspect *clone(ProjectExplorer::RunConfiguration *parent) const;
+ QmlProjectEnvironmentAspect *create(ProjectExplorer::RunConfiguration *parent) const;
QList<int> possibleBaseEnvironments() const;
QString baseEnvironmentDisplayName(int base) const;
@@ -52,8 +52,6 @@ private:
enum BaseEnvironmentBase {
SystemEnvironmentBase = 0
};
-
- QmlProjectEnvironmentAspect(const QmlProjectEnvironmentAspect *other, ProjectExplorer::RunConfiguration *parent);
};
} // namespace QmlProjectManager
diff --git a/src/plugins/qmlprojectmanager/qmlprojectfile.cpp b/src/plugins/qmlprojectmanager/qmlprojectfile.cpp
index 93ca0ccac8..80347c0316 100644
--- a/src/plugins/qmlprojectmanager/qmlprojectfile.cpp
+++ b/src/plugins/qmlprojectmanager/qmlprojectfile.cpp
@@ -37,11 +37,11 @@ namespace Internal {
QmlProjectFile::QmlProjectFile(QmlProject *parent, QString fileName)
: Core::IDocument(parent),
- m_project(parent),
- m_fileName(fileName)
+ m_project(parent)
{
QTC_CHECK(m_project);
QTC_CHECK(!fileName.isEmpty());
+ setFilePath(fileName);
}
QmlProjectFile::~QmlProjectFile()
@@ -53,18 +53,6 @@ bool QmlProjectFile::save(QString *, const QString &, bool)
return false;
}
-void QmlProjectFile::rename(const QString &newName)
-{
- // Can't happen...
- Q_UNUSED(newName);
- Q_ASSERT(false);
-}
-
-QString QmlProjectFile::fileName() const
-{
- return m_fileName;
-}
-
QString QmlProjectFile::defaultPath() const
{
return QString();
diff --git a/src/plugins/qmlprojectmanager/qmlprojectfile.h b/src/plugins/qmlprojectmanager/qmlprojectfile.h
index 36c5a3c7e4..842d9f5297 100644
--- a/src/plugins/qmlprojectmanager/qmlprojectfile.h
+++ b/src/plugins/qmlprojectmanager/qmlprojectfile.h
@@ -47,8 +47,6 @@ public:
virtual ~QmlProjectFile();
virtual bool save(QString *errorString, const QString &fileName, bool autoSave);
- virtual QString fileName() const;
- virtual void rename(const QString &newName);
virtual QString defaultPath() const;
virtual QString suggestedFileName() const;
@@ -62,7 +60,6 @@ public:
private:
QmlProject *m_project;
- QString m_fileName;
};
} // namespace Internal
diff --git a/src/plugins/qmlprojectmanager/qmlprojectmanager.pro b/src/plugins/qmlprojectmanager/qmlprojectmanager.pro
index 28888a726b..cd42fc753f 100644
--- a/src/plugins/qmlprojectmanager/qmlprojectmanager.pro
+++ b/src/plugins/qmlprojectmanager/qmlprojectmanager.pro
@@ -1,4 +1,4 @@
-QT += network declarative
+QT += network
include(../../qtcreatorplugin.pri)
include(fileformat/fileformat.pri)
diff --git a/src/plugins/qmlprojectmanager/qmlprojectmanager.qbs b/src/plugins/qmlprojectmanager/qmlprojectmanager.qbs
index eaf376ebc3..e44877e3e4 100644
--- a/src/plugins/qmlprojectmanager/qmlprojectmanager.qbs
+++ b/src/plugins/qmlprojectmanager/qmlprojectmanager.qbs
@@ -12,44 +12,40 @@ QtcPlugin {
Depends { name: "QmlJSEditor" }
Depends { name: "QmlJS" }
Depends { name: "QmlJSTools" }
+ Depends { name: "QmlDebug" }
Depends { name: "Debugger" }
Depends { name: "QtSupport" }
Depends { name: "app_version_header" }
- files: [
- "qmlapp.cpp",
- "qmlapp.h",
- "qmlapplicationwizard.cpp",
- "qmlapplicationwizard.h",
- "qmlproject.cpp",
- "qmlproject.h",
- "qmlproject.qrc",
- "qmlprojectconstants.h",
- "qmlprojectenvironmentaspect.cpp",
- "qmlprojectenvironmentaspect.h",
- "qmlprojectfile.cpp",
- "qmlprojectfile.h",
- "qmlprojectmanager.cpp",
- "qmlprojectmanager.h",
- "qmlprojectmanager_global.h",
- "qmlprojectmanagerconstants.h",
- "qmlprojectnodes.cpp",
- "qmlprojectnodes.h",
- "qmlprojectplugin.cpp",
- "qmlprojectplugin.h",
- "qmlprojectrunconfiguration.cpp",
- "qmlprojectrunconfiguration.h",
- "qmlprojectrunconfigurationfactory.cpp",
- "qmlprojectrunconfigurationfactory.h",
- "qmlprojectrunconfigurationwidget.cpp",
- "qmlprojectrunconfigurationwidget.h",
- "qmlprojectruncontrol.cpp",
- "qmlprojectruncontrol.h",
- "fileformat/filefilteritems.cpp",
- "fileformat/filefilteritems.h",
- "fileformat/qmlprojectfileformat.cpp",
- "fileformat/qmlprojectfileformat.h",
- "fileformat/qmlprojectitem.cpp",
- "fileformat/qmlprojectitem.h",
- ]
+ Group {
+ name: "General"
+ files: [
+ "qmlapp.cpp", "qmlapp.h",
+ "qmlapplicationwizard.cpp", "qmlapplicationwizard.h",
+ "qmlproject.cpp", "qmlproject.h",
+ "qmlproject.qrc",
+ "qmlprojectconstants.h",
+ "qmlprojectenvironmentaspect.cpp", "qmlprojectenvironmentaspect.h",
+ "qmlprojectfile.cpp", "qmlprojectfile.h",
+ "qmlprojectmanager.cpp", "qmlprojectmanager.h",
+ "qmlprojectmanager_global.h",
+ "qmlprojectmanagerconstants.h",
+ "qmlprojectnodes.cpp", "qmlprojectnodes.h",
+ "qmlprojectplugin.cpp", "qmlprojectplugin.h",
+ "qmlprojectrunconfiguration.cpp", "qmlprojectrunconfiguration.h",
+ "qmlprojectrunconfigurationfactory.cpp", "qmlprojectrunconfigurationfactory.h",
+ "qmlprojectrunconfigurationwidget.cpp", "qmlprojectrunconfigurationwidget.h",
+ "qmlprojectruncontrol.cpp", "qmlprojectruncontrol.h",
+ ]
+ }
+
+ Group {
+ name: "File Format"
+ prefix: "fileformat/"
+ files: [
+ "filefilteritems.cpp", "filefilteritems.h",
+ "qmlprojectfileformat.cpp", "qmlprojectfileformat.h",
+ "qmlprojectitem.cpp", "qmlprojectitem.h",
+ ]
+ }
}
diff --git a/src/plugins/qmlprojectmanager/qmlprojectnodes.cpp b/src/plugins/qmlprojectmanager/qmlprojectnodes.cpp
index 70cd26e826..bbf8165091 100644
--- a/src/plugins/qmlprojectmanager/qmlprojectnodes.cpp
+++ b/src/plugins/qmlprojectmanager/qmlprojectnodes.cpp
@@ -41,11 +41,11 @@ namespace QmlProjectManager {
namespace Internal {
QmlProjectNode::QmlProjectNode(QmlProject *project, Core::IDocument *projectFile)
- : ProjectExplorer::ProjectNode(QFileInfo(projectFile->fileName()).absoluteFilePath()),
+ : ProjectExplorer::ProjectNode(QFileInfo(projectFile->filePath()).absoluteFilePath()),
m_project(project),
m_projectFile(projectFile)
{
- setDisplayName(QFileInfo(projectFile->fileName()).completeBaseName());
+ setDisplayName(QFileInfo(projectFile->filePath()).completeBaseName());
// make overlay
const QSize desiredSize = QSize(16, 16);
const QIcon projectBaseIcon(QLatin1String(":/qmlproject/images/qmlfolder.png"));
@@ -62,7 +62,7 @@ Core::IDocument *QmlProjectNode::projectFile() const
{ return m_projectFile; }
QString QmlProjectNode::projectFilePath() const
-{ return m_projectFile->fileName(); }
+{ return m_projectFile->filePath(); }
void QmlProjectNode::refresh()
{
@@ -198,26 +198,22 @@ bool QmlProjectNode::removeSubProjects(const QStringList &proFilePaths)
return false;
}
-bool QmlProjectNode::addFiles(const ProjectExplorer::FileType /*fileType*/,
- const QStringList &filePaths, QStringList * /*notAdded*/)
+bool QmlProjectNode::addFiles(const QStringList &filePaths, QStringList * /*notAdded*/)
{
return m_project->addFiles(filePaths);
}
-bool QmlProjectNode::removeFiles(const ProjectExplorer::FileType /*fileType*/,
- const QStringList & /*filePaths*/, QStringList * /*notRemoved*/)
+bool QmlProjectNode::removeFiles(const QStringList & /*filePaths*/, QStringList * /*notRemoved*/)
{
return false;
}
-bool QmlProjectNode::deleteFiles(const ProjectExplorer::FileType /*fileType*/,
- const QStringList & /*filePaths*/)
+bool QmlProjectNode::deleteFiles(const QStringList & /*filePaths*/)
{
return true;
}
-bool QmlProjectNode::renameFile(const ProjectExplorer::FileType /*fileType*/,
- const QString & /*filePath*/, const QString & /*newFilePath*/)
+bool QmlProjectNode::renameFile(const QString & /*filePath*/, const QString & /*newFilePath*/)
{
return true;
}
diff --git a/src/plugins/qmlprojectmanager/qmlprojectnodes.h b/src/plugins/qmlprojectmanager/qmlprojectnodes.h
index 6796467c5f..d75d4ece21 100644
--- a/src/plugins/qmlprojectmanager/qmlprojectnodes.h
+++ b/src/plugins/qmlprojectmanager/qmlprojectnodes.h
@@ -63,20 +63,10 @@ public:
virtual bool addSubProjects(const QStringList &proFilePaths);
virtual bool removeSubProjects(const QStringList &proFilePaths);
- virtual bool addFiles(const ProjectExplorer::FileType fileType,
- const QStringList &filePaths,
- QStringList *notAdded = 0);
-
- virtual bool removeFiles(const ProjectExplorer::FileType fileType,
- const QStringList &filePaths,
- QStringList *notRemoved = 0);
-
- virtual bool deleteFiles(const ProjectExplorer::FileType fileType,
- const QStringList &filePaths);
-
- virtual bool renameFile(const ProjectExplorer::FileType fileType,
- const QString &filePath,
- const QString &newFilePath);
+ virtual bool addFiles(const QStringList &filePaths, QStringList *notAdded = 0);
+ virtual bool removeFiles(const QStringList &filePaths, QStringList *notRemoved = 0);
+ virtual bool deleteFiles(const QStringList &filePaths);
+ virtual bool renameFile(const QString &filePath, const QString &newFilePath);
virtual QList<ProjectExplorer::RunConfiguration *> runConfigurationsFor(Node *node);
diff --git a/src/plugins/qmlprojectmanager/qmlprojectplugin.cpp b/src/plugins/qmlprojectmanager/qmlprojectplugin.cpp
index fa4d7cb8e6..d9a9e38dca 100644
--- a/src/plugins/qmlprojectmanager/qmlprojectplugin.cpp
+++ b/src/plugins/qmlprojectmanager/qmlprojectplugin.cpp
@@ -60,27 +60,18 @@ bool QmlProjectPlugin::initialize(const QStringList &, QString *errorMessage)
{
using namespace Core;
- Core::MimeDatabase *mimeDB = Core::ICore::mimeDatabase();
-
const QLatin1String mimetypesXml(":/qmlproject/QmlProjectManager.mimetypes.xml");
- if (! mimeDB->addMimeTypes(mimetypesXml, errorMessage))
+ if (!MimeDatabase::addMimeTypes(mimetypesXml, errorMessage))
return false;
- Internal::Manager *manager = new Internal::Manager;
-
- addAutoReleasedObject(manager);
+ addAutoReleasedObject(new Internal::Manager);
addAutoReleasedObject(new Internal::QmlProjectRunConfigurationFactory);
addAutoReleasedObject(new Internal::QmlProjectRunControlFactory);
-
Internal::QmlApplicationWizard::createInstances(this);
- QmlProjectFileFormat::registerDeclarativeTypes();
-
- Core::FileIconProvider *iconProvider = Core::FileIconProvider::instance();
- iconProvider->registerIconOverlayForSuffix(QIcon(QLatin1String(":/qmlproject/images/qmlproject.png")),
- QLatin1String("qmlproject"));
+ FileIconProvider::registerIconOverlayForSuffix(":/qmlproject/images/qmlproject.png", "qmlproject");
return true;
}
diff --git a/src/plugins/qmlprojectmanager/qmlprojectrunconfiguration.cpp b/src/plugins/qmlprojectmanager/qmlprojectrunconfiguration.cpp
index ce8e908125..803c67bcb0 100644
--- a/src/plugins/qmlprojectmanager/qmlprojectrunconfiguration.cpp
+++ b/src/plugins/qmlprojectmanager/qmlprojectrunconfiguration.cpp
@@ -46,18 +46,14 @@
#include <utils/winutils.h>
#endif
-using Core::EditorManager;
-using Core::ICore;
-using Core::IEditor;
-
+using namespace Core;
using namespace QmlProjectManager::Internal;
namespace QmlProjectManager {
-const char * const M_CURRENT_FILE = "CurrentFile";
+const char M_CURRENT_FILE[] = "CurrentFile";
-QmlProjectRunConfiguration::QmlProjectRunConfiguration(ProjectExplorer::Target *parent,
- Core::Id id) :
+QmlProjectRunConfiguration::QmlProjectRunConfiguration(ProjectExplorer::Target *parent, Id id) :
ProjectExplorer::RunConfiguration(parent, id),
m_scriptFile(QLatin1String(M_CURRENT_FILE)),
m_isEnabled(false)
@@ -90,8 +86,7 @@ QString QmlProjectRunConfiguration::disabledReason() const
void QmlProjectRunConfiguration::ctor()
{
// reset default settings in constructor
- EditorManager *em = Core::EditorManager::instance();
- connect(em, SIGNAL(currentEditorChanged(Core::IEditor*)),
+ connect(EditorManager::instance(), SIGNAL(currentEditorChanged(Core::IEditor*)),
this, SLOT(changeCurrentFile(Core::IEditor*)));
connect(target(), SIGNAL(kitChanged()),
@@ -153,7 +148,7 @@ QString QmlProjectRunConfiguration::viewerArguments() const
QString QmlProjectRunConfiguration::workingDirectory() const
{
- QFileInfo projectFile(target()->project()->document()->fileName());
+ QFileInfo projectFile(target()->project()->projectFilePath());
return canonicalCapsPath(projectFile.absolutePath());
}
@@ -270,10 +265,10 @@ bool QmlProjectRunConfiguration::fromMap(const QVariantMap &map)
return RunConfiguration::fromMap(map);
}
-void QmlProjectRunConfiguration::changeCurrentFile(Core::IEditor *editor)
+void QmlProjectRunConfiguration::changeCurrentFile(IEditor *editor)
{
if (editor)
- m_currentFileFilename = editor->document()->fileName();
+ m_currentFileFilename = editor->document()->filePath();
updateEnabled();
}
@@ -281,22 +276,21 @@ void QmlProjectRunConfiguration::updateEnabled()
{
bool qmlFileFound = false;
if (mainScriptSource() == FileInEditor) {
- Core::IEditor *editor = Core::EditorManager::currentEditor();
- Core::MimeDatabase *db = ICore::mimeDatabase();
- if (editor) {
- m_currentFileFilename = editor->document()->fileName();
- if (db->findByFile(mainScript()).type() == QLatin1String("application/x-qml"))
+ IDocument *document = EditorManager::currentDocument();
+ if (document) {
+ m_currentFileFilename = document->filePath();
+ if (MimeDatabase::findByFile(mainScript()).type() == QLatin1String("application/x-qml"))
qmlFileFound = true;
}
- if (!editor
- || db->findByFile(mainScript()).type() == QLatin1String("application/x-qmlproject")) {
+ if (!document
+ || MimeDatabase::findByFile(mainScript()).type() == QLatin1String("application/x-qmlproject")) {
// find a qml file with lowercase filename. This is slow, but only done
// in initialization/other border cases.
foreach (const QString &filename, target()->project()->files(ProjectExplorer::Project::AllFiles)) {
const QFileInfo fi(filename);
if (!filename.isEmpty() && fi.baseName()[0].isLower()
- && db->findByFile(fi).type() == QLatin1String("application/x-qml"))
+ && MimeDatabase::findByFile(fi).type() == QLatin1String("application/x-qml"))
{
m_currentFileFilename = filename;
qmlFileFound = true;
diff --git a/src/plugins/qmlprojectmanager/qmlprojectruncontrol.cpp b/src/plugins/qmlprojectmanager/qmlprojectruncontrol.cpp
index a6e555d882..27fb2a5952 100644
--- a/src/plugins/qmlprojectmanager/qmlprojectruncontrol.cpp
+++ b/src/plugins/qmlprojectmanager/qmlprojectruncontrol.cpp
@@ -71,8 +71,8 @@ QmlProjectRunControl::QmlProjectRunControl(QmlProjectRunConfiguration *runConfig
connect(&m_applicationLauncher, SIGNAL(appendMessage(QString,Utils::OutputFormat)),
this, SLOT(slotAppendMessage(QString,Utils::OutputFormat)));
- connect(&m_applicationLauncher, SIGNAL(processExited(int)),
- this, SLOT(processExited(int)));
+ connect(&m_applicationLauncher, SIGNAL(processExited(int,QProcess::ExitStatus)),
+ this, SLOT(processExited(int,QProcess::ExitStatus)));
connect(&m_applicationLauncher, SIGNAL(bringToForegroundRequested(qint64)),
this, SLOT(slotBringApplicationToForeground(qint64)));
}
@@ -119,10 +119,15 @@ void QmlProjectRunControl::slotAppendMessage(const QString &line, Utils::OutputF
appendMessage(line, format);
}
-void QmlProjectRunControl::processExited(int exitCode)
+void QmlProjectRunControl::processExited(int exitCode,QProcess::ExitStatus status)
{
- QString msg = tr("%1 exited with code %2\n")
- .arg(QDir::toNativeSeparators(m_executable)).arg(exitCode);
+ QString msg;
+ if (status == QProcess::CrashExit)
+ msg = tr("%1 crashed\n") .arg(QDir::toNativeSeparators(m_executable));
+ else
+ msg = tr("%1 exited with code %2\n")
+ .arg(QDir::toNativeSeparators(m_executable)).arg(exitCode);
+
appendMessage(msg, exitCode ? Utils::ErrorMessageFormat : Utils::NormalMessageFormat);
emit finished();
}
diff --git a/src/plugins/qmlprojectmanager/qmlprojectruncontrol.h b/src/plugins/qmlprojectmanager/qmlprojectruncontrol.h
index 9eea9736d5..6a041bd776 100644
--- a/src/plugins/qmlprojectmanager/qmlprojectruncontrol.h
+++ b/src/plugins/qmlprojectmanager/qmlprojectruncontrol.h
@@ -56,7 +56,7 @@ public:
QString mainQmlFile() const;
private slots:
- void processExited(int exitCode);
+ void processExited(int exitCode, QProcess::ExitStatus status);
void slotBringApplicationToForeground(qint64 pid);
void slotAppendMessage(const QString &line, Utils::OutputFormat);
diff --git a/src/plugins/qnx/Qnx.pluginspec.in b/src/plugins/qnx/Qnx.pluginspec.in
index a5b8750880..4ca4fedcd1 100644
--- a/src/plugins/qnx/Qnx.pluginspec.in
+++ b/src/plugins/qnx/Qnx.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"Qnx\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"Qnx\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Research In Motion</vendor>
<copyright>(C) 2013 Research In Motion</copyright>
<license>
diff --git a/src/plugins/qnx/bardescriptordocument.cpp b/src/plugins/qnx/bardescriptordocument.cpp
index 7b78bf7748..1236186b6e 100644
--- a/src/plugins/qnx/bardescriptordocument.cpp
+++ b/src/plugins/qnx/bardescriptordocument.cpp
@@ -78,7 +78,7 @@ BarDescriptorDocument::BarDescriptorDocument(BarDescriptorEditorWidget *editorWi
if (QTextCodec *defaultUTF8 = QTextCodec::codecForName("UTF-8"))
setCodec(defaultUTF8);
else
- setCodec(Core::EditorManager::instance()->defaultTextCodec());
+ setCodec(Core::EditorManager::defaultTextCodec());
}
BarDescriptorDocument::~BarDescriptorDocument()
@@ -94,8 +94,8 @@ bool BarDescriptorDocument::open(QString *errorString, const QString &fileName)
if (read(fileName, &contents, errorString) != Utils::TextFileFormat::ReadSuccess)
return false;
- m_fileName = fileName;
- m_editorWidget->editor()->setDisplayName(QFileInfo(fileName).fileName());
+ setFilePath(fileName);
+ m_editorWidget->setFilePath(fileName);
bool result = loadContent(contents);
@@ -105,12 +105,12 @@ bool BarDescriptorDocument::open(QString *errorString, const QString &fileName)
return result;
}
-bool BarDescriptorDocument::save(QString *errorString, const QString &fileName, bool autoSave)
+bool BarDescriptorDocument::save(QString *errorString, const QString &fn, bool autoSave)
{
QTC_ASSERT(!autoSave, return false);
- QTC_ASSERT(fileName.isEmpty(), return false);
+ QTC_ASSERT(fn.isEmpty(), return false);
- bool result = write(m_fileName, xmlSource(), errorString);
+ bool result = write(filePath(), xmlSource(), errorString);
if (!result)
return false;
@@ -119,20 +119,15 @@ bool BarDescriptorDocument::save(QString *errorString, const QString &fileName,
return true;
}
-QString BarDescriptorDocument::fileName() const
-{
- return m_fileName;
-}
-
QString BarDescriptorDocument::defaultPath() const
{
- QFileInfo fi(fileName());
+ QFileInfo fi(filePath());
return fi.absolutePath();
}
QString BarDescriptorDocument::suggestedFileName() const
{
- QFileInfo fi(fileName());
+ QFileInfo fi(filePath());
return fi.fileName();
}
@@ -172,16 +167,7 @@ bool BarDescriptorDocument::reload(QString *errorString, Core::IDocument::Reload
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();
+ return open(errorString, filePath());
}
QString BarDescriptorDocument::xmlSource() const
diff --git a/src/plugins/qnx/bardescriptordocument.h b/src/plugins/qnx/bardescriptordocument.h
index 1f271801b7..88e5929a7d 100644
--- a/src/plugins/qnx/bardescriptordocument.h
+++ b/src/plugins/qnx/bardescriptordocument.h
@@ -58,7 +58,6 @@ public:
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;
@@ -70,7 +69,6 @@ public:
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);
@@ -82,8 +80,6 @@ private:
QList<BarDescriptorDocumentAbstractNodeHandler *> m_nodeHandlers;
- QString m_fileName;
-
BarDescriptorEditorWidget *m_editorWidget;
};
diff --git a/src/plugins/qnx/bardescriptoreditor.cpp b/src/plugins/qnx/bardescriptoreditor.cpp
index a33dab4a31..93f93e6e97 100644
--- a/src/plugins/qnx/bardescriptoreditor.cpp
+++ b/src/plugins/qnx/bardescriptoreditor.cpp
@@ -35,7 +35,6 @@
#include "bardescriptoreditorwidget.h"
#include "bardescriptordocument.h"
-#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/task.h>
#include <projectexplorer/taskhub.h>
@@ -44,11 +43,12 @@
#include <QAction>
#include <QToolBar>
-using namespace Qnx;
-using namespace Qnx::Internal;
+using namespace ProjectExplorer;
+
+namespace Qnx {
+namespace Internal {
BarDescriptorEditor::BarDescriptorEditor(BarDescriptorEditorWidget *editorWidget)
- : Core::IEditor()
{
setWidget(editorWidget);
@@ -82,12 +82,6 @@ BarDescriptorEditor::BarDescriptorEditor(BarDescriptorEditorWidget *editorWidget
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);
@@ -104,25 +98,6 @@ 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::isTemporary() const
-{
- return false;
-}
-
QWidget *BarDescriptorEditor::toolBar()
{
return m_toolBar;
@@ -141,11 +116,6 @@ void BarDescriptorEditor::changeEditorPage(QAction *action)
setActivePage(static_cast<EditorPage>(action->data().toInt()));
}
-ProjectExplorer::TaskHub *BarDescriptorEditor::taskHub()
-{
- return ProjectExplorer::ProjectExplorerPlugin::instance()->taskHub();
-}
-
void BarDescriptorEditor::setActivePage(BarDescriptorEditor::EditorPage page)
{
BarDescriptorEditorWidget *editorWidget = qobject_cast<BarDescriptorEditorWidget *>(widget());
@@ -159,14 +129,13 @@ void BarDescriptorEditor::setActivePage(BarDescriptorEditor::EditorPage page)
if (page == Source) {
editorWidget->setXmlSource(m_file->xmlSource());
} else if (prevPage == Source) {
- taskHub()->clearTasks(Constants::QNX_TASK_CATEGORY_BARDESCRIPTOR);
+ 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();
+ TaskHub::addTask(Task::Error, errorMsg, Constants::QNX_TASK_CATEGORY_BARDESCRIPTOR,
+ Utils::FileName::fromString(m_file->filePath()), errorLine);
+ TaskHub::requestPopup();
foreach (QAction *action, m_actionGroup->actions())
if (action->data().toInt() == Source)
@@ -178,3 +147,6 @@ void BarDescriptorEditor::setActivePage(BarDescriptorEditor::EditorPage page)
editorWidget->setCurrentIndex(page);
}
+
+} // namespace Internal
+} // namespace Qnx
diff --git a/src/plugins/qnx/bardescriptoreditor.h b/src/plugins/qnx/bardescriptoreditor.h
index b8bd6bfd9f..cf0397fc75 100644
--- a/src/plugins/qnx/bardescriptoreditor.h
+++ b/src/plugins/qnx/bardescriptoreditor.h
@@ -39,15 +39,10 @@ class QActionGroup;
class QToolBar;
QT_END_NAMESPACE
-namespace ProjectExplorer {
- class TaskHub;
-}
-
namespace Qnx {
namespace Internal {
class BarDescriptorDocument;
-
class BarDescriptorEditorWidget;
class BarDescriptorEditor : public Core::IEditor
@@ -63,13 +58,9 @@ 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 isTemporary() const;
QWidget *toolBar();
EditorPage activePage() const;
@@ -78,14 +69,10 @@ private slots:
void changeEditorPage(QAction *action);
private:
- ProjectExplorer::TaskHub *taskHub();
-
void setActivePage(EditorPage page);
BarDescriptorDocument *m_file;
- QString m_displayName;
-
QToolBar *m_toolBar;
QActionGroup *m_actionGroup;
};
diff --git a/src/plugins/qnx/bardescriptoreditorfactory.cpp b/src/plugins/qnx/bardescriptoreditorfactory.cpp
index ac300d3710..5a2806039d 100644
--- a/src/plugins/qnx/bardescriptoreditorfactory.cpp
+++ b/src/plugins/qnx/bardescriptoreditorfactory.cpp
@@ -42,23 +42,10 @@ 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");
+ setId(Constants::QNX_BAR_DESCRIPTOR_EDITOR_ID);
+ setDisplayName(tr("Bar descriptor editor"));
+ addMimeType(Constants::QNX_BAR_DESCRIPTOR_MIME_TYPE);
}
Core::IEditor *BarDescriptorEditorFactory::createEditor(QWidget *parent)
diff --git a/src/plugins/qnx/bardescriptoreditorfactory.h b/src/plugins/qnx/bardescriptoreditorfactory.h
index 36bade0089..9a7ddfa687 100644
--- a/src/plugins/qnx/bardescriptoreditorfactory.h
+++ b/src/plugins/qnx/bardescriptoreditorfactory.h
@@ -34,25 +34,17 @@
#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::IEditor *createEditor(QWidget *parent);
-
-private:
- QStringList m_mimeTypes;
};
} // namespace Internal
diff --git a/src/plugins/qnx/bardescriptoreditorwidget.cpp b/src/plugins/qnx/bardescriptoreditorwidget.cpp
index 9b1bcae156..10b4447fd6 100644
--- a/src/plugins/qnx/bardescriptoreditorwidget.cpp
+++ b/src/plugins/qnx/bardescriptoreditorwidget.cpp
@@ -163,7 +163,7 @@ Core::IEditor *BarDescriptorEditorWidget::editor() const
{
if (!m_editor) {
m_editor = const_cast<BarDescriptorEditorWidget *>(this)->createEditor();
- connect(this, SIGNAL(changed()), m_editor, SIGNAL(changed()));
+ connect(this, SIGNAL(changed()), m_editor->document(), SIGNAL(changed()));
}
return m_editor;
@@ -204,6 +204,18 @@ BarDescriptorEditorAssetsWidget *BarDescriptorEditorWidget::assetsWidget() const
return m_assetsWidget;
}
+void BarDescriptorEditorWidget::setFilePath(const QString &filePath)
+{
+ Core::IDocument *doc = m_xmlSourceWidget->editorDocument();
+ if (doc) {
+ doc->setFilePath(filePath);
+ // setFilePath() call leads to a textChanged() signal emitted
+ // and therefore having this editor-widget to become dirty
+ // therefore we have to explicitly unset the dirty flag
+ setDirty(false);
+ }
+}
+
QString BarDescriptorEditorWidget::xmlSource() const
{
return m_xmlSourceWidget->toPlainText();
diff --git a/src/plugins/qnx/bardescriptoreditorwidget.h b/src/plugins/qnx/bardescriptoreditorwidget.h
index ba4409268b..14a27da8c1 100644
--- a/src/plugins/qnx/bardescriptoreditorwidget.h
+++ b/src/plugins/qnx/bardescriptoreditorwidget.h
@@ -79,6 +79,7 @@ public:
BarDescriptorEditorAssetsWidget *assetsWidget() const;
+ void setFilePath(const QString &filePath);
QString xmlSource() const;
void setXmlSource(const QString &xmlSource);
diff --git a/src/plugins/qnx/blackberryabstractdeploystep.cpp b/src/plugins/qnx/blackberryabstractdeploystep.cpp
index 8b4b0252b3..f97c56df8e 100644
--- a/src/plugins/qnx/blackberryabstractdeploystep.cpp
+++ b/src/plugins/qnx/blackberryabstractdeploystep.cpp
@@ -81,7 +81,7 @@ bool BlackBerryAbstractDeployStep::init()
m_processCounter = -1;
m_environment = target()->activeBuildConfiguration()->environment();
- m_buildDirectory = target()->activeBuildConfiguration()->buildDirectory();
+ m_buildDirectory = target()->activeBuildConfiguration()->buildDirectory().toString();
return true;
}
@@ -132,7 +132,8 @@ void BlackBerryAbstractDeployStep::reportProgress(int progress)
{
QTC_ASSERT(progress >= 0 && progress <= 100, return);
- m_futureInterface->setProgressValue(100 * m_processCounter + progress);
+ if (m_futureInterface)
+ m_futureInterface->setProgressValue(100 * m_processCounter + progress);
}
void BlackBerryAbstractDeployStep::runCommands()
@@ -186,7 +187,7 @@ void BlackBerryAbstractDeployStep::raiseError(const QString &errorMessage)
{
emit addOutput(errorMessage, BuildStep::ErrorMessageOutput);
emit addTask(ProjectExplorer::Task(ProjectExplorer::Task::Error, errorMessage, Utils::FileName(), -1,
- Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM)));
+ ProjectExplorer::Constants::TASK_CATEGORY_DEPLOYMENT));
}
void BlackBerryAbstractDeployStep::processReadyReadStdOutput()
diff --git a/src/plugins/qnx/blackberryapplicationrunner.cpp b/src/plugins/qnx/blackberryapplicationrunner.cpp
index 1f24c5765f..23ee2c2b0a 100644
--- a/src/plugins/qnx/blackberryapplicationrunner.cpp
+++ b/src/plugins/qnx/blackberryapplicationrunner.cpp
@@ -33,6 +33,7 @@
#include "blackberrydeployconfiguration.h"
#include "blackberryrunconfiguration.h"
+#include "blackberrylogprocessrunner.h"
#include "qnxconstants.h"
#include <projectexplorer/target.h>
@@ -58,18 +59,13 @@ using namespace Qnx::Internal;
BlackBerryApplicationRunner::BlackBerryApplicationRunner(bool debugMode, BlackBerryRunConfiguration *runConfiguration, QObject *parent)
: QObject(parent)
, m_debugMode(debugMode)
- , m_slog2infoFound(false)
- , m_currentLogs(false)
, m_pid(-1)
, m_appId(QString())
, m_running(false)
, m_stopping(false)
- , m_tailCommand(QString())
, m_launchProcess(0)
, m_stopProcess(0)
- , m_tailProcess(0)
- , m_testSlog2Process(0)
- , m_launchDateTimeProcess(0)
+ , m_logProcessRunner(0)
, m_runningStateTimer(new QTimer(this))
, m_runningStateProcess(0)
{
@@ -85,12 +81,12 @@ BlackBerryApplicationRunner::BlackBerryApplicationRunner(bool debugMode, BlackBe
// The BlackBerry device always uses key authentication
m_sshParams = m_device->sshParameters();
- m_sshParams.authenticationType = QSsh::SshConnectionParameters::AuthenticationByKey;
+ m_sshParams.authenticationType = QSsh::SshConnectionParameters::AuthenticationTypePublicKey;
m_runningStateTimer->setInterval(3000);
m_runningStateTimer->setSingleShot(true);
connect(m_runningStateTimer, SIGNAL(timeout()), this, SLOT(determineRunningState()));
- connect(this, SIGNAL(started()), this, SLOT(checkSlog2Info()));
+ connect(this, SIGNAL(started()), this, SLOT(startLogProcessRunner()));
connect(&m_launchStopProcessParser, SIGNAL(pidParsed(qint64)), this, SLOT(setPid(qint64)));
connect(&m_launchStopProcessParser, SIGNAL(applicationIdParsed(QString)), this, SLOT(setApplicationId(QString)));
@@ -122,16 +118,16 @@ void BlackBerryApplicationRunner::start()
m_running = true;
}
-void BlackBerryApplicationRunner::checkSlog2Info()
+void BlackBerryApplicationRunner::startLogProcessRunner()
{
- if (m_slog2infoFound) {
- readLaunchTime();
- } else if (!m_testSlog2Process) {
- m_testSlog2Process = new QSsh::SshRemoteProcessRunner(this);
- connect(m_testSlog2Process, SIGNAL(processClosed(int)),
- this, SLOT(handleSlog2InfoFound()));
- m_testSlog2Process->run("slog2info", m_sshParams);
+ if (!m_logProcessRunner) {
+ m_logProcessRunner = new BlackBerryLogProcessRunner(this, m_appId, m_device);
+ connect(m_logProcessRunner, SIGNAL(output(QString,Utils::OutputFormat)),
+ this, SIGNAL(output(QString,Utils::OutputFormat)));
+ connect(m_logProcessRunner, SIGNAL(finished()), this, SIGNAL(finished()));
}
+
+ m_logProcessRunner->start();
}
void BlackBerryApplicationRunner::startFinished(int exitCode, QProcess::ExitStatus exitStatus)
@@ -156,13 +152,6 @@ ProjectExplorer::RunControl::StopResult BlackBerryApplicationRunner::stop()
return ProjectExplorer::RunControl::AsynchronousStop;
m_stopping = true;
- m_currentLogs = false;
-
- if (m_testSlog2Process && m_testSlog2Process->isProcessRunning()) {
- m_testSlog2Process->cancel();
- delete m_testSlog2Process;
- m_testSlog2Process = 0;
- }
QStringList args;
args << QLatin1String("-terminateApp");
@@ -225,76 +214,6 @@ void BlackBerryApplicationRunner::readStandardError()
}
}
-void BlackBerryApplicationRunner::killTailProcess()
-{
- QTC_ASSERT(!m_tailCommand.isEmpty(), return);
-
- QString killCommand = m_device->processSupport()->killProcessByNameCommandLine(m_tailCommand);
-
- QSsh::SshRemoteProcessRunner *slayProcess = new QSsh::SshRemoteProcessRunner(this);
- connect(slayProcess, SIGNAL(processClosed(int)), this, SIGNAL(finished()));
- slayProcess->run(killCommand.toLatin1(), m_sshParams);
-
- // Not supported by OpenSSH server
- //m_tailProcess->sendSignalToProcess(Utils::SshRemoteProcess::KillSignal);
- m_tailProcess->cancel();
-
- delete m_tailProcess;
- m_tailProcess = 0;
-}
-
-void BlackBerryApplicationRunner::tailApplicationLog()
-{
- QSsh::SshRemoteProcessRunner *process = qobject_cast<QSsh::SshRemoteProcessRunner *>(sender());
- QTC_ASSERT(process, return);
-
- m_launchDateTime = QDateTime::fromString(QString::fromLatin1(process->readAllStandardOutput()).trimmed(),
- QString::fromLatin1("dd HH:mm:ss"));
-
- if (m_stopping || (m_tailProcess && m_tailProcess->isProcessRunning()))
- return;
-
- QTC_CHECK(!m_appId.isEmpty());
-
- if (!m_tailProcess) {
- m_tailProcess = new QSsh::SshRemoteProcessRunner(this);
-
- connect(m_tailProcess, SIGNAL(readyReadStandardOutput()),
- this, SLOT(handleTailOutput()));
- connect(m_tailProcess, SIGNAL(readyReadStandardError()),
- this, SLOT(handleTailError()));
- connect(m_tailProcess, SIGNAL(connectionError()),
- this, SLOT(handleTailConnectionError()));
- }
-
- if (m_slog2infoFound) {
- m_tailCommand = QString::fromLatin1("slog2info -w -b ") + m_appId;
- } else {
- m_tailCommand = QLatin1String("tail -c +1 -f /accounts/1000/appdata/") + m_appId
- + QLatin1String("/logs/log");
- }
- m_tailProcess->run(m_tailCommand.toLatin1(), m_sshParams);
-}
-
-void BlackBerryApplicationRunner::handleSlog2InfoFound()
-{
- QSsh::SshRemoteProcessRunner *process = qobject_cast<QSsh::SshRemoteProcessRunner *>(sender());
- QTC_ASSERT(process, return);
-
- m_slog2infoFound = (process->processExitCode() == 0);
-
- readLaunchTime();
-}
-
-void BlackBerryApplicationRunner::readLaunchTime()
-{
- m_launchDateTimeProcess = new QSsh::SshRemoteProcessRunner(this);
- connect(m_launchDateTimeProcess, SIGNAL(processClosed(int)),
- this, SLOT(tailApplicationLog()));
-
- m_launchDateTimeProcess->run("date +\"%d %H:%M:%S\"", m_sshParams);
-}
-
void BlackBerryApplicationRunner::setPid(qint64 pid)
{
m_pid = pid;
@@ -305,75 +224,6 @@ void BlackBerryApplicationRunner::setApplicationId(const QString &applicationId)
m_appId = applicationId;
}
-void BlackBerryApplicationRunner::handleTailOutput()
-{
- QSsh::SshRemoteProcessRunner *process = qobject_cast<QSsh::SshRemoteProcessRunner *>(sender());
- QTC_ASSERT(process, return);
-
- const QString message = QString::fromLatin1(process->readAllStandardOutput());
- if (m_slog2infoFound) {
- const QStringList multiLine = message.split(QLatin1Char('\n'));
- Q_FOREACH (const QString &line, multiLine) {
- // Check if logs are from the recent launch
- // Note: This is useless if/once slog2info -b displays only logs from recent launches
- if (!m_currentLogs) {
- QDateTime dateTime = QDateTime::fromString(line.split(m_appId).first().mid(4).trimmed(),
- QString::fromLatin1("dd HH:mm:ss.zzz"));
-
- m_currentLogs = dateTime >= m_launchDateTime;
- if (!m_currentLogs)
- continue;
- }
-
- // The line could be a part of a previous log message that contains a '\n'
- // In that case only the message body is displayed
- if (!line.contains(m_appId) && !line.isEmpty()) {
- emit output(line + QLatin1Char('\n'), Utils::StdOutFormat);
- continue;
- }
-
- QStringList validLineBeginnings;
- validLineBeginnings << QLatin1String("qt-msg 0 ")
- << QLatin1String("qt-msg* 0 ")
- << QLatin1String("default* 9000 ")
- << QLatin1String("default 9000 ")
- << QLatin1String(" 0 ");
- Q_FOREACH (const QString &beginning, validLineBeginnings) {
- if (showQtMessage(beginning, line))
- break;
- }
- }
- return;
- }
- emit output(message, Utils::StdOutFormat);
-}
-
-bool BlackBerryApplicationRunner::showQtMessage(const QString& pattern, const QString& line)
-{
- const int index = line.indexOf(pattern);
- if (index != -1) {
- const QString str = line.right(line.length()-index-pattern.length()) + QLatin1Char('\n');
- emit output(str, Utils::StdOutFormat);
- return true;
- }
- return false;
-}
-
-void BlackBerryApplicationRunner::handleTailError()
-{
- QSsh::SshRemoteProcessRunner *process = qobject_cast<QSsh::SshRemoteProcessRunner *>(sender());
- QTC_ASSERT(process, return);
-
- const QString message = QString::fromLatin1(process->readAllStandardError());
- emit output(message, Utils::StdErrFormat);
-}
-
-void BlackBerryApplicationRunner::handleTailConnectionError()
-{
- emit output(tr("Cannot show debug output. Error: %1").arg(m_tailProcess->lastConnectionErrorString()),
- Utils::StdErrFormat);
-}
-
void BlackBerryApplicationRunner::startRunningStateTimer()
{
if (m_running)
@@ -431,8 +281,12 @@ void BlackBerryApplicationRunner::reset()
m_runningStateProcess->kill();
}
- if (m_tailProcess && m_tailProcess->isProcessRunning())
- killTailProcess();
- else
+ if (m_logProcessRunner) {
+ m_logProcessRunner->stop();
+
+ delete m_logProcessRunner;
+ m_logProcessRunner = 0;
+ } else {
emit finished();
+ }
}
diff --git a/src/plugins/qnx/blackberryapplicationrunner.h b/src/plugins/qnx/blackberryapplicationrunner.h
index afe7bba7ee..99ede3b333 100644
--- a/src/plugins/qnx/blackberryapplicationrunner.h
+++ b/src/plugins/qnx/blackberryapplicationrunner.h
@@ -52,6 +52,7 @@ namespace Qnx {
namespace Internal {
class BlackBerryRunConfiguration;
+class BlackBerryLogProcessRunner;
class BlackBerryApplicationRunner : public QObject
{
@@ -66,7 +67,6 @@ public:
public slots:
void start();
- void checkSlog2Info();
signals:
void output(const QString &msg, Utils::OutputFormat format);
@@ -76,37 +76,25 @@ signals:
void startFailed(const QString &msg);
private slots:
- bool showQtMessage(const QString& pattern, const QString& line);
- void tailApplicationLog();
void startFinished(int exitCode, QProcess::ExitStatus exitStatus);
void stopFinished(int exitCode, QProcess::ExitStatus exitStatus);
void readStandardOutput();
void readStandardError();
- void handleTailOutput();
- void handleTailError();
- void handleTailConnectionError();
-
void startRunningStateTimer();
void determineRunningState();
void readRunningStateStandardOutput();
- void handleSlog2InfoFound();
- void readLaunchTime();
-
void setPid(qint64 pid);
void setApplicationId(const QString &applicationId);
+ void startLogProcessRunner();
+
private:
void reset();
- void killTailProcess();
bool m_debugMode;
- bool m_slog2infoFound;
- bool m_currentLogs;
-
- QDateTime m_launchDateTime;
qint64 m_pid;
QString m_appId;
@@ -119,15 +107,13 @@ private:
BlackBerryDeviceConfiguration::ConstPtr m_device;
QString m_barPackage;
QSsh::SshConnectionParameters m_sshParams;
- QString m_tailCommand;
QProcess *m_launchProcess;
QProcess *m_stopProcess;
BlackBerryProcessParser m_launchStopProcessParser;
- QSsh::SshRemoteProcessRunner *m_tailProcess;
- QSsh::SshRemoteProcessRunner *m_testSlog2Process;
- QSsh::SshRemoteProcessRunner *m_launchDateTimeProcess;
+ BlackBerryLogProcessRunner *m_logProcessRunner;
+
QTimer *m_runningStateTimer;
QProcess *m_runningStateProcess;
};
diff --git a/src/plugins/qnx/blackberrycertificate.cpp b/src/plugins/qnx/blackberrycertificate.cpp
index 5f4c84caea..ef80841a89 100644
--- a/src/plugins/qnx/blackberrycertificate.cpp
+++ b/src/plugins/qnx/blackberrycertificate.cpp
@@ -1,8 +1,8 @@
/**************************************************************************
**
-** Copyright (C) 2011 - 2013 Research In Motion
+** Copyright (C) 2013 BlackBerry Limited. All rights reserved.
**
-** Contact: Research In Motion (blackberry-qt@qnx.com)
+** Contact: BlackBerry (qt@blackberry.com)
** Contact: KDAB (info@kdab.com)
**
** This file is part of Qt Creator.
@@ -31,6 +31,7 @@
#include "blackberrycertificate.h"
#include "blackberryconfiguration.h"
+#include "blackberryconfigurationmanager.h"
#include <utils/hostosinfo.h>
@@ -49,6 +50,7 @@ BlackBerryCertificate::BlackBerryCertificate(const QString &fileName,
m_storePass(storePass),
m_process(new QProcess(this))
{
+ m_process->setProcessChannelMode(QProcess::MergedChannels);
}
void BlackBerryCertificate::load()
@@ -141,10 +143,12 @@ void BlackBerryCertificate::loadFinished()
while (!processOutput.atEnd()) {
QString chunk = processOutput.readLine();
- if (chunk.contains(
- QLatin1String("Error: Failed to decrypt keystore, invalid password"))) {
+ if (chunk.contains(QLatin1String("invalid password"))) {
status = WrongPassword;
break;
+ } else if (chunk.contains(QLatin1String("must be at least 6 characters"))) {
+ status = PasswordTooSmall;
+ break;
} else if (chunk.startsWith(QLatin1String("Owner:"))) {
chunk.remove(QLatin1String("Owner:"));
m_author = chunk.remove(QLatin1String("CN=")).trimmed();
@@ -178,12 +182,16 @@ void BlackBerryCertificate::processError()
QString BlackBerryCertificate::command() const
{
- QString command = BlackBerryConfiguration::instance()
- .qnxEnv().value(QLatin1String("QNX_HOST"))
- + QLatin1String("/usr/bin/blackberry-keytool");
-
- if (Utils::HostOsInfo::isWindowsHost())
- command += QLatin1String(".bat");
+ QString command;
+ // TOOD: Give user choice to select NDK from where to get commands
+ QMultiMap<QString, QString> qnxEnv = BlackBerryConfigurationManager::instance().defaultQnxEnv();
+ if (!qnxEnv.isEmpty()) {
+ command = qnxEnv.value(QLatin1String("QNX_HOST"))
+ + QLatin1String("/usr/bin/blackberry-keytool");
+
+ if (Utils::HostOsInfo::isWindowsHost())
+ command += QLatin1String(".bat");
+ }
return command;
}
diff --git a/src/plugins/qnx/blackberrycertificate.h b/src/plugins/qnx/blackberrycertificate.h
index e15cb5f87d..02f380c93d 100644
--- a/src/plugins/qnx/blackberrycertificate.h
+++ b/src/plugins/qnx/blackberrycertificate.h
@@ -1,8 +1,8 @@
/**************************************************************************
**
-** Copyright (C) 2011 - 2013 Research In Motion
+** Copyright (C) 2013 BlackBerry Limited. All rights reserved.
**
-** Contact: Research In Motion (blackberry-qt@qnx.com)
+** Contact: BlackBerry (qt@blackberry.com)
** Contact: KDAB (info@kdab.com)
**
** This file is part of Qt Creator.
@@ -51,6 +51,7 @@ public:
Success,
Busy,
WrongPassword,
+ PasswordTooSmall,
InvalidOutputFormat,
Error
};
diff --git a/src/plugins/qnx/blackberrycertificatemodel.cpp b/src/plugins/qnx/blackberrycertificatemodel.cpp
deleted file mode 100644
index 5837bcea2e..0000000000
--- a/src/plugins/qnx/blackberrycertificatemodel.cpp
+++ /dev/null
@@ -1,205 +0,0 @@
-/**************************************************************************
-**
-** 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 "blackberrycertificatemodel.h"
-#include "blackberrycertificate.h"
-#include "blackberryconfiguration.h"
-
-#include <coreplugin/icore.h>
-
-#include <QSettings>
-#include <QStringList>
-
-namespace Qnx {
-namespace Internal {
-
-const QLatin1String SettingsGroup("BlackBerryConfiguration");
-const QLatin1String CertificateGroup("Certificates");
-
-BlackBerryCertificateModel::BlackBerryCertificateModel(QObject *parent) :
- QAbstractTableModel(parent),
- m_activeCertificate(0)
-{
- load();
-}
-
-BlackBerryCertificateModel::~BlackBerryCertificateModel()
-{
-}
-
-int BlackBerryCertificateModel::rowCount(const QModelIndex &parent) const
-{
- if (parent.isValid())
- return 0;
-
- return m_certificates.count();
-}
-
-int BlackBerryCertificateModel::columnCount(const QModelIndex &parent) const
-{
- if (parent.isValid())
- return 0;
-
- return ColumnCount;
-}
-
-QVariant BlackBerryCertificateModel::data(const QModelIndex &index, int role) const
-{
- if (index.row() >= rowCount() || index.column() >= columnCount())
- return QVariant();
-
- const BlackBerryCertificate *cert = m_certificates.at(index.row());
-
- if (role == Qt::CheckStateRole) {
- if (index.column() == CertActive)
- return (m_activeCertificate == cert) ? Qt::Checked : Qt::Unchecked;
- } else if (role == Qt::DisplayRole) {
- if (index.column() == CertPath)
- return cert->fileName();
- else if (index.column() == CertAuthor)
- return cert->author();
- }
-
- return QVariant();
-}
-
-QVariant BlackBerryCertificateModel::headerData(int section,
- Qt::Orientation orientation, int role) const
-{
- if (role != Qt::DisplayRole)
- return QVariant();
-
- if (orientation == Qt::Vertical)
- return section;
-
- switch (section) {
- case CertPath:
- return tr("Path");
- case CertAuthor:
- return tr("Author");
- case CertActive:
- return tr("Active");
- default:
- break;
- }
-
- return section;
-}
-
-bool BlackBerryCertificateModel::setData(const QModelIndex &ind,
- const QVariant &value, int role)
-{
- Q_UNUSED(value);
-
- if (role == Qt::CheckStateRole && ind.column() == CertActive) {
- const int oldIndex = m_certificates.indexOf(m_activeCertificate);
-
- m_activeCertificate = m_certificates.at(ind.row());
-
- if (oldIndex >= 0)
- emit dataChanged(index(oldIndex, CertActive), index(oldIndex, CertActive));
-
- emit dataChanged(ind, ind);
-
- return true;
- }
-
- return false;
-}
-
-bool BlackBerryCertificateModel::removeRows(int row, int count,
- const QModelIndex &parent)
-{
-
- beginRemoveRows(parent, row, row + count - 1);
-
- for (int i = 0; i < count; i++) {
- m_certificates.removeAt(row);
- //XXX shall we also delete from disk?
- }
-
- endRemoveRows();
-
- return true;
-}
-
-Qt::ItemFlags BlackBerryCertificateModel::flags(const QModelIndex &index) const
-{
- Qt::ItemFlags flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable;
-
- switch (index.column()) {
- case CertActive:
- flags |= Qt::ItemIsUserCheckable;
- break;
- default:
- break;
- }
-
- return flags;
-}
-
-BlackBerryCertificate * BlackBerryCertificateModel::activeCertificate() const
-{
- return m_activeCertificate;
-}
-
-QList<BlackBerryCertificate*> BlackBerryCertificateModel::certificates() const
-{
- return m_certificates;
-}
-
-bool BlackBerryCertificateModel::insertCertificate(BlackBerryCertificate *certificate)
-{
- if (m_certificates.contains(certificate))
- return false;
-
- beginInsertRows(QModelIndex(), m_certificates.count(), m_certificates.count());
-
- if (m_certificates.isEmpty())
- m_activeCertificate = certificate;
-
- certificate->setParent(this);
- m_certificates << certificate;
-
- endInsertRows();
-
- return true;
-}
-
-void BlackBerryCertificateModel::load()
-{
- BlackBerryConfiguration &configuration = BlackBerryConfiguration::instance();
- m_certificates = configuration.certificates();
- m_activeCertificate = configuration.activeCertificate();
-}
-
-} // namespace Internal
-} // namespace Qnx
diff --git a/src/plugins/qnx/blackberryconfiguration.cpp b/src/plugins/qnx/blackberryconfiguration.cpp
index ad30e0f88d..c000b29afc 100644
--- a/src/plugins/qnx/blackberryconfiguration.cpp
+++ b/src/plugins/qnx/blackberryconfiguration.cpp
@@ -31,450 +31,341 @@
#include "blackberryconfiguration.h"
#include "blackberryqtversion.h"
-#include "blackberrycertificate.h"
-#include "qnxutils.h"
-
-#include <coreplugin/icore.h>
-#include <qtsupport/baseqtversion.h>
-#include <qtsupport/qtversionmanager.h>
-#include <qtsupport/qtkitinformation.h>
+#include "qnxutils.h"
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/kitmanager.h>
#include <projectexplorer/kitinformation.h>
-#include <projectexplorer/gcctoolchain.h>
#include <projectexplorer/toolchainmanager.h>
+#include <qtsupport/baseqtversion.h>
+#include <qtsupport/qtversionmanager.h>
+#include <qtsupport/qtkitinformation.h>
+
#include <qt4projectmanager/qmakekitinformation.h>
#include <debugger/debuggerkitinformation.h>
-#include <utils/persistentsettings.h>
-#include <utils/hostosinfo.h>
-
#include <QFileInfo>
#include <QDir>
#include <QMessageBox>
+using namespace ProjectExplorer;
+using namespace QtSupport;
+using namespace Utils;
+
namespace Qnx {
namespace Internal {
-namespace {
-const QLatin1String SettingsGroup("BlackBerryConfiguration");
-const QLatin1String NDKLocationKey("NDKLocation");
-const QLatin1String CertificateGroup("Certificates");
-}
-
-BlackBerryConfiguration::BlackBerryConfiguration(QObject *parent)
- :QObject(parent)
-{
- loadSettings();
- connect(Core::ICore::instance(), SIGNAL(saveSettingsRequested()), this, SLOT(saveSettings()));
-}
-
-bool BlackBerryConfiguration::setNdkPath(const QString &ndkPath)
-{
- if (ndkPath.isEmpty())
- return false;
-
- m_config.ndkPath = ndkPath;
-
- return refresh();
-}
-
-bool BlackBerryConfiguration::refresh()
+BlackBerryConfiguration::BlackBerryConfiguration(const FileName &ndkEnvFile, bool isAutoDetected,
+ const QString &displayName)
{
- m_config.qnxEnv = QnxUtils::parseEnvironmentFile(QnxUtils::envFilePath(m_config.ndkPath));
+ Q_ASSERT(!QFileInfo(ndkEnvFile.toString()).isDir());
+ m_ndkEnvFile = ndkEnvFile;
+ m_isAutoDetected = isAutoDetected;
+ QString ndkPath = ndkEnvFile.parentDir().toString();
+ m_displayName = displayName.isEmpty() ? ndkPath.split(QDir::separator()).last() : displayName;
+ m_qnxEnv = QnxUtils::parseEnvironmentFile(m_ndkEnvFile.toString());
- QString ndkTarget = m_config.qnxEnv.value(QLatin1String("QNX_TARGET"));
+ QString ndkTarget = m_qnxEnv.value(QLatin1String("QNX_TARGET"));
QString sep = QString::fromLatin1("%1qnx6").arg(QDir::separator());
- m_config.targetName = ndkTarget.split(sep).first().split(QDir::separator()).last();
+ m_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:");
- if (!qmakePath.toFileInfo().exists())
- errorMessage += QLatin1Char('\n') + tr("- No Qt version found.");
+ m_sysRoot = FileName::fromString(ndkTarget);
- if (!gccPath.toFileInfo().exists())
- errorMessage += QLatin1Char('\n') + tr("- No GCC compiler found.");
+ QString qnxHost = m_qnxEnv.value(QLatin1String("QNX_HOST"));
+ FileName qmake4Path = QnxUtils::executableWithExtension(FileName::fromString(qnxHost + QLatin1String("/usr/bin/qmake")));
+ FileName qmake5Path = QnxUtils::executableWithExtension(FileName::fromString(qnxHost + QLatin1String("/usr/bin/qt5/qmake")));
+ FileName gccPath = QnxUtils::executableWithExtension(FileName::fromString(qnxHost + QLatin1String("/usr/bin/qcc")));
+ FileName deviceGdbPath = QnxUtils::executableWithExtension(FileName::fromString(qnxHost + QLatin1String("/usr/bin/ntoarm-gdb")));
+ FileName simulatorGdbPath = QnxUtils::executableWithExtension(FileName::fromString(qnxHost + QLatin1String("/usr/bin/ntox86-gdb")));
- if (!deviceGdbPath.toFileInfo().exists())
- errorMessage += QLatin1Char('\n') + tr("- No GDB debugger found for BB10 Device.");
+ if (qmake4Path.toFileInfo().exists())
+ m_qmake4BinaryFile = qmake4Path;
- if (!simulatorGdbPath.toFileInfo().exists())
- errorMessage += QLatin1Char('\n') + tr("- No GDB debugger found for BB10 Simulator.");
+ if (qmake5Path.toFileInfo().exists())
+ m_qmake5BinaryFile = qmake5Path;
- QMessageBox::warning(0, tr("Cannot Set up BB10 Configuration"),
- errorMessage, QMessageBox::Ok);
- return false;
- }
+ if (gccPath.toFileInfo().exists())
+ m_gccCompiler = gccPath;
- m_config.qmakeBinaryFile = qmakePath;
- m_config.gccCompiler = gccPath;
- m_config.deviceDebuger = deviceGdbPath;
- m_config.simulatorDebuger = simulatorGdbPath;
+ if (deviceGdbPath.toFileInfo().exists())
+ m_deviceDebuger = deviceGdbPath;
+
+ if (simulatorGdbPath.toFileInfo().exists())
+ m_simulatorDebuger = simulatorGdbPath;
- return true;
}
-void BlackBerryConfiguration::loadCertificates()
+QString BlackBerryConfiguration::ndkPath() const
{
- QSettings *settings = Core::ICore::settings();
-
- settings->beginGroup(SettingsGroup);
- settings->beginGroup(CertificateGroup);
-
- foreach (const QString &certificateId, settings->childGroups()) {
- settings->beginGroup(certificateId);
-
- BlackBerryCertificate *cert =
- new BlackBerryCertificate(settings->value(QLatin1String(Qnx::Constants::QNX_KEY_PATH)).toString(),
- settings->value(QLatin1String(Qnx::Constants::QNX_KEY_AUTHOR)).toString());
- cert->setParent(this);
-
- if (settings->value(QLatin1String(Qnx::Constants::QNX_KEY_ACTIVE)).toBool())
- m_config.activeCertificate = cert;
-
- m_config.certificates << cert;
-
- settings->endGroup();
- }
-
- settings->endGroup();
- settings->endGroup();
+ return m_ndkEnvFile.parentDir().toString();
}
-void BlackBerryConfiguration::loadNdkSettings()
+QString BlackBerryConfiguration::displayName() const
{
- QSettings *settings = Core::ICore::settings();
-
- settings->beginGroup(SettingsGroup);
- setNdkPath(settings->value(NDKLocationKey).toString());
- settings->endGroup();
+ return m_displayName;
}
-void BlackBerryConfiguration::saveCertificates()
+QString BlackBerryConfiguration::targetName() const
{
- QSettings *settings = Core::ICore::settings();
-
- settings->beginGroup(SettingsGroup);
- settings->beginGroup(CertificateGroup);
-
- settings->remove(QString());
-
- foreach (const BlackBerryCertificate *cert, m_config.certificates) {
- settings->beginGroup(cert->id());
- settings->setValue(QLatin1String(Qnx::Constants::QNX_KEY_PATH), cert->fileName());
- settings->setValue(QLatin1String(Qnx::Constants::QNX_KEY_AUTHOR), cert->author());
-
- if (cert == m_config.activeCertificate)
- settings->setValue(QLatin1String(Qnx::Constants::QNX_KEY_ACTIVE), true);
-
- settings->endGroup();
- }
-
- settings->endGroup();
- settings->endGroup();
+ return m_targetName;
}
-void BlackBerryConfiguration::saveNdkSettings()
+bool BlackBerryConfiguration::isAutoDetected() const
{
- if (m_config.ndkPath.isEmpty())
- return;
-
- QSettings *settings = Core::ICore::settings();
- settings->beginGroup(SettingsGroup);
- settings->setValue(NDKLocationKey, m_config.ndkPath);
- settings->endGroup();
+ return m_isAutoDetected;
}
-void BlackBerryConfiguration::setupNdkConfiguration(const QString &ndkPath)
+bool BlackBerryConfiguration::isActive() const
{
- if (ndkPath.isEmpty())
- return;
-
- if (setNdkPath(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) {
- if (!qtVersion->qtAbis().isEmpty())
- 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();
- }
- }
+ BaseQtVersion *qt4Version = QtVersionManager::qtVersionForQMakeBinary(m_qmake4BinaryFile);
+ BaseQtVersion *qt5Version = QtVersionManager::qtVersionForQMakeBinary(m_qmake5BinaryFile);
+ return (qt4Version || qt5Version);
}
-void BlackBerryConfiguration::cleanNdkConfiguration()
+bool BlackBerryConfiguration::isValid() const
{
- 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;
- conf.activeCertificate = m_config.activeCertificate;
- conf.certificates = m_config.certificates;
- m_config = conf;
- emit updated();
-
- clearNdkSettings();
+ return !((m_qmake4BinaryFile.isEmpty() && m_qmake5BinaryFile.isEmpty()) || m_gccCompiler.isEmpty()
+ || m_deviceDebuger.isEmpty() || m_simulatorDebuger.isEmpty());
}
-void BlackBerryConfiguration::syncCertificates(QList<BlackBerryCertificate*> certificates,
- BlackBerryCertificate *activeCertificate)
+FileName BlackBerryConfiguration::ndkEnvFile() const
{
- m_config.activeCertificate = activeCertificate;
-
- foreach (BlackBerryCertificate *cert, m_config.certificates) {
- if (!certificates.contains(cert))
- removeCertificate(cert);
- }
-
- foreach (BlackBerryCertificate *cert, certificates)
- addCertificate(cert);
+ return m_ndkEnvFile;
}
-void BlackBerryConfiguration::addCertificate(BlackBerryCertificate *certificate)
+FileName BlackBerryConfiguration::qmake4BinaryFile() const
{
- if (m_config.certificates.contains(certificate))
- return;
+ return m_qmake4BinaryFile;
+}
- if (m_config.certificates.isEmpty())
- m_config.activeCertificate = certificate;
+FileName BlackBerryConfiguration::qmake5BinaryFile() const
+{
+ return m_qmake5BinaryFile;
+}
- certificate->setParent(this);
- m_config.certificates << certificate;
+FileName BlackBerryConfiguration::gccCompiler() const
+{
+ return m_gccCompiler;
}
-void BlackBerryConfiguration::removeCertificate(BlackBerryCertificate *certificate)
+FileName BlackBerryConfiguration::deviceDebuger() const
{
- if (m_config.activeCertificate == certificate)
- m_config.activeCertificate = 0;
+ return m_deviceDebuger;
+}
- m_config.certificates.removeAll(certificate);
+FileName BlackBerryConfiguration::simulatorDebuger() const
+{
+ return m_simulatorDebuger;
+}
- delete certificate;
+FileName BlackBerryConfiguration::sysRoot() const
+{
+ return m_sysRoot;
}
-QList<BlackBerryCertificate*> BlackBerryConfiguration::certificates() const
+QMultiMap<QString, QString> BlackBerryConfiguration::qnxEnv() const
{
- return m_config.certificates;
+ return m_qnxEnv;
}
-BlackBerryCertificate * BlackBerryConfiguration::activeCertificate()
+void BlackBerryConfiguration::setupConfigurationPerQtVersion(const FileName &qmakePath, GccToolChain *tc)
{
- return m_config.activeCertificate;
+ if (qmakePath.isEmpty() || !tc)
+ return;
+
+ BaseQtVersion *qtVersion = createQtVersion(qmakePath);
+ Kit *deviceKit = createKit(ArmLeV7, qtVersion, tc);
+ Kit *simulatorKit = createKit(X86, qtVersion, tc);
+ if (qtVersion && tc && deviceKit && simulatorKit) {
+ if (!qtVersion->qtAbis().isEmpty())
+ tc->setTargetAbi(qtVersion->qtAbis().first());
+ // register
+ QtVersionManager::addVersion(qtVersion);
+ ToolChainManager::registerToolChain(tc);
+ KitManager::registerKit(deviceKit);
+ KitManager::registerKit(simulatorKit);
+ }
}
-QtSupport::BaseQtVersion *BlackBerryConfiguration::createQtVersion()
+BaseQtVersion *BlackBerryConfiguration::createQtVersion(const FileName &qmakePath)
{
- if (m_config.qmakeBinaryFile.isEmpty())
+ if (qmakePath.isEmpty())
return 0;
- QString cpuDir = m_config.qnxEnv.value(QLatin1String("CPUVARDIR"));
- QtSupport::BaseQtVersion *version = QtSupport::QtVersionManager::instance()->qtVersionForQMakeBinary(m_config.qmakeBinaryFile);
+ QString cpuDir = m_qnxEnv.value(QLatin1String("CPUVARDIR"));
+ BaseQtVersion *version = QtVersionManager::qtVersionForQMakeBinary(qmakePath);
if (version) {
- QMessageBox::warning(0, tr("Qt Version Already Known"),
+ if (!m_isAutoDetected)
+ 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);
+ version = new BlackBerryQtVersion(QnxUtils::cpudirToArch(cpuDir), qmakePath, m_isAutoDetected, QString(), m_ndkEnvFile.toString());
if (!version) {
- QMessageBox::warning(0, tr("Invalid Qt Version"),
+ if (!m_isAutoDetected)
+ 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));
-
+ version->setDisplayName(QString::fromLatin1("Qt %1 BlackBerry 10 (%2)").arg(version->qtVersionString(), m_targetName));
return version;
}
-ProjectExplorer::GccToolChain *BlackBerryConfiguration::createGccToolChain()
+GccToolChain *BlackBerryConfiguration::createGccToolChain()
{
- if (m_config.qmakeBinaryFile.isEmpty() || m_config.gccCompiler.isEmpty())
+ if ((m_qmake4BinaryFile.isEmpty() && m_qmake5BinaryFile.isEmpty()) || m_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"),
+ foreach (ToolChain *tc, ToolChainManager::toolChains()) {
+ if (tc->compilerCommand() == m_gccCompiler) {
+ if (!m_isAutoDetected)
+ QMessageBox::warning(0, tr("Compiler Already Known"),
tr("This compiler was already registered."), QMessageBox::Ok);
- return dynamic_cast<ProjectExplorer::GccToolChain*>(tc);
+ return dynamic_cast<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);
+ GccToolChain* tc = new GccToolChain(QLatin1String(ProjectExplorer::Constants::GCC_TOOLCHAIN_ID), m_isAutoDetected ? ToolChain::AutoDetection : ToolChain::ManualDetection);
+ tc->setDisplayName(QString::fromLatin1("GCC BlackBerry 10 (%1)").arg(m_targetName));
+ tc->setCompilerCommand(m_gccCompiler);
return tc;
}
-ProjectExplorer::Kit *BlackBerryConfiguration::createKit(QnxArchitecture arch, QtSupport::BaseQtVersion *qtVersion, ProjectExplorer::GccToolChain *tc)
+Kit *BlackBerryConfiguration::createKit(QnxArchitecture arch, BaseQtVersion *qtVersion, GccToolChain *tc)
{
- if (!qtVersion || !tc || m_config.targetName.isEmpty())
+ if (!qtVersion || !tc || m_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) {
+ foreach (Kit *kit, KitManager::kits()) {
+ if (QtKitInformation::qtVersion(kit) == qtVersion && ToolChainKitInformation::toolChain(kit) == tc
+ && DeviceTypeKitInformation::deviceTypeId(kit) == Constants::QNX_BB_OS_TYPE
+ && SysRootKitInformation::sysRoot(kit) == m_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"),
+ && Debugger::DebuggerKitInformation::debuggerCommand(kit) == m_simulatorDebuger)
+ || (arch == ArmLeV7 && Debugger::DebuggerKitInformation::debuggerCommand(kit) == m_deviceDebuger)) {
+ if (!m_isAutoDetected)
+ QMessageBox::warning(0, tr("Kit Already Known"),
tr("This kit was already registered."), QMessageBox::Ok);
+ setSticky(kit);
return kit;
}
}
}
- ProjectExplorer::Kit *kit = new ProjectExplorer::Kit;
- QtSupport::QtKitInformation::setQtVersion(kit, qtVersion);
- ProjectExplorer::ToolChainKitInformation::setToolChain(kit, tc);
+ Kit *kit = new Kit;
+ QtKitInformation::setQtVersion(kit, qtVersion);
+ ToolChainKitInformation::setToolChain(kit, tc);
+
+ QString versionName = QString::fromLatin1("%1 - %2").arg(qtVersion->qtVersionString(), m_targetName);
+
+ Debugger::DebuggerItem debugger;
+ debugger.setCommand(arch == X86 ? m_simulatorDebuger : m_deviceDebuger);
+ debugger.setEngineType(Debugger::GdbEngineType);
+ debugger.setDisplayName(arch == X86
+ ? tr("BlackBerry Debugger (%1) - Simulator").arg(versionName)
+ : tr("BlackBerry Debugger (%1) - Device").arg(versionName));
+ debugger.setAutoDetected(true);
+ debugger.setAbi(tc->targetAbi());
+ Debugger::DebuggerKitInformation::setDebugger(kit, debugger);
+
if (arch == X86) {
- Debugger::DebuggerKitInformation::setDebuggerCommand(kit, m_config.simulatorDebuger);
- Qt4ProjectManager::QmakeKitInformation::setMkspec(kit, Utils::FileName::fromString(QString::fromLatin1("blackberry-x86-qcc")));
+ Qt4ProjectManager::QmakeKitInformation::setMkspec(kit, 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));
+ kit->setDisplayName(tr("BlackBerry 10 (%1) - Simulator").arg(versionName));
} else {
- Debugger::DebuggerKitInformation::setDebuggerCommand(kit, m_config.deviceDebuger);
- kit->setDisplayName(tr("BlackBerry 10 (%1)").arg(m_config.targetName));
+ kit->setDisplayName(tr("BlackBerry 10 (%1)").arg(versionName));
}
- kit->setIconPath(QLatin1String(Constants::QNX_BB_CATEGORY_ICON));
- ProjectExplorer::DeviceTypeKitInformation::setDeviceTypeId(kit, Constants::QNX_BB_OS_TYPE);
- ProjectExplorer::SysRootKitInformation::setSysRoot(kit, m_config.sysRoot);
+ kit->setAutoDetected(m_isAutoDetected);
+ kit->setIconPath(FileName::fromString(QLatin1String(Constants::QNX_BB_CATEGORY_ICON)));
+ kit->setMutable(DeviceKitInformation::id(), true);
+ setSticky(kit);
+ DeviceTypeKitInformation::setDeviceTypeId(kit, Constants::QNX_BB_OS_TYPE);
+ SysRootKitInformation::setSysRoot(kit, m_sysRoot);
return kit;
}
-void BlackBerryConfiguration::loadSettings()
+void BlackBerryConfiguration::setSticky(Kit *kit)
{
- loadNdkSettings();
- loadCertificates();
+ kit->setSticky(QtKitInformation::id(), true);
+ kit->setSticky(ToolChainKitInformation::id(), true);
+ kit->setSticky(DeviceTypeKitInformation::id(), true);
+ kit->setSticky(SysRootKitInformation::id(), true);
+ kit->setSticky(Debugger::DebuggerKitInformation::id(), true);
+ kit->setSticky(Qt4ProjectManager::QmakeKitInformation::id(), true);
}
-void BlackBerryConfiguration::saveSettings()
+bool BlackBerryConfiguration::activate()
{
- saveNdkSettings();
- saveCertificates();
-}
+ if (!isValid()) {
+ if (m_isAutoDetected)
+ return false;
-void BlackBerryConfiguration::clearNdkSettings()
-{
- QSettings *settings = Core::ICore::settings();
- settings->beginGroup(SettingsGroup);
- settings->remove(NDKLocationKey);
- settings->endGroup();
-}
+ QString errorMessage = tr("The following errors occurred while activating Target: %1").arg(m_targetName);
+ if (m_qmake4BinaryFile.isEmpty() && m_qmake5BinaryFile.isEmpty())
+ errorMessage += QLatin1Char('\n') + tr("- No Qt version found.");
-BlackBerryConfiguration &BlackBerryConfiguration::instance()
-{
- if (m_instance == 0)
- m_instance = new BlackBerryConfiguration();
- return *m_instance;
-}
+ if (m_gccCompiler.isEmpty())
+ errorMessage += QLatin1Char('\n') + tr("- No GCC compiler found.");
-QString BlackBerryConfiguration::ndkPath() const
-{
- return m_config.ndkPath;
-}
+ if (m_deviceDebuger.isEmpty())
+ errorMessage += QLatin1Char('\n') + tr("- No GDB debugger found for BB10 Device.");
-QString BlackBerryConfiguration::targetName() const
-{
- return m_config.targetName;
-}
+ if (!m_simulatorDebuger.isEmpty())
+ errorMessage += QLatin1Char('\n') + tr("- No GDB debugger found for BB10 Simulator.");
-BlackBerryConfig BlackBerryConfiguration::config() const
-{
- return m_config;
-}
+ QMessageBox::warning(0, tr("Cannot Set up BB10 Configuration"),
+ errorMessage, QMessageBox::Ok);
+ return false;
+ }
-Utils::FileName BlackBerryConfiguration::qmakePath() const
-{
- return m_config.qmakeBinaryFile;
-}
+ if (isActive() && !m_isAutoDetected)
+ return true;
-Utils::FileName BlackBerryConfiguration::gccPath() const
-{
- return m_config.gccCompiler;
-}
+ GccToolChain *tc = createGccToolChain();
+ if (!m_qmake4BinaryFile.isEmpty())
+ setupConfigurationPerQtVersion(m_qmake4BinaryFile, tc);
-Utils::FileName BlackBerryConfiguration::deviceGdbPath() const
-{
- return m_config.deviceDebuger;
-}
+ if (!m_qmake5BinaryFile.isEmpty())
+ setupConfigurationPerQtVersion(m_qmake5BinaryFile, tc);
-Utils::FileName BlackBerryConfiguration::simulatorGdbPath() const
-{
- return m_config.simulatorDebuger;
+ return true;
}
-Utils::FileName BlackBerryConfiguration::sysRoot() const
+void BlackBerryConfiguration::deactivate()
{
- return m_config.sysRoot;
-}
+ BaseQtVersion *qt4Version = QtVersionManager::qtVersionForQMakeBinary(m_qmake4BinaryFile);
+ BaseQtVersion *qt5Version = QtVersionManager::qtVersionForQMakeBinary(m_qmake5BinaryFile);
+ if (qt4Version || qt5Version) {
+ foreach (Kit *kit, KitManager::kits()) {
+ if (qt4Version && qt4Version == QtKitInformation::qtVersion(kit))
+ KitManager::deregisterKit(kit);
-QString BlackBerryConfiguration::barsignerCskPath() const
-{
- return QnxUtils::dataDirPath() + QLatin1String("/barsigner.csk");
-}
+ else if (qt5Version && qt5Version == QtKitInformation::qtVersion(kit))
+ KitManager::deregisterKit(kit);
+ }
-QString BlackBerryConfiguration::barsignerDbPath() const
-{
- return QnxUtils::dataDirPath() + QLatin1String("/barsigner.db");
-}
+ if (qt4Version)
+ QtVersionManager::removeVersion(qt4Version);
-QString BlackBerryConfiguration::defaultKeystorePath() const
-{
- return QnxUtils::dataDirPath() + QLatin1String("/author.p12");
-}
+ if (qt5Version)
+ QtVersionManager::removeVersion(qt5Version);
-QString BlackBerryConfiguration::defaultDebugTokenPath() const
-{
- return QnxUtils::dataDirPath() + QLatin1String("/debugtoken.bar");
-}
+ }
-// TODO: QnxUtils::parseEnvFile() and qnxEnv() to return Util::Enviroment instead(?)
-QMultiMap<QString, QString> BlackBerryConfiguration::qnxEnv() const
-{
- return m_config.qnxEnv;
+ foreach (ToolChain *tc, ToolChainManager::toolChains())
+ if (tc->compilerCommand() == m_gccCompiler)
+ ToolChainManager::deregisterToolChain(tc);
}
-BlackBerryConfiguration* BlackBerryConfiguration::m_instance = 0;
-
} // namespace Internal
} // namespace Qnx
diff --git a/src/plugins/qnx/blackberryconfiguration.h b/src/plugins/qnx/blackberryconfiguration.h
index d538f610ef..32961201ce 100644
--- a/src/plugins/qnx/blackberryconfiguration.h
+++ b/src/plugins/qnx/blackberryconfiguration.h
@@ -32,7 +32,7 @@
#ifndef BLACKBERRYCONFIGURATIONS_H
#define BLACKBERRYCONFIGURATIONS_H
-#include <qnxconstants.h>
+#include "qnxconstants.h"
#include <utils/environment.h>
#include <utils/fileutils.h>
@@ -42,80 +42,53 @@
#include <projectexplorer/kit.h>
#include <projectexplorer/gcctoolchain.h>
-#include <QSettings>
#include <QObject>
+#include <QCoreApplication>
namespace Qnx {
namespace Internal {
-class BlackBerryCertificate;
-
-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;
- QList<BlackBerryCertificate*> certificates;
- BlackBerryCertificate *activeCertificate;
-
- friend class BlackBerryConfiguration;
-};
-
-class BlackBerryConfiguration: public QObject
+class BlackBerryConfiguration
{
- Q_OBJECT
+ Q_DECLARE_TR_FUNCTIONS(Qnx::Internal::BlackBerryConfiguration)
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 setupNdkConfiguration(const QString &ndkPath);
+ BlackBerryConfiguration(const Utils::FileName &ndkEnvFile, bool isAutoDetected, const QString &displayName = QString());
+ bool activate();
+ void deactivate();
QString ndkPath() const;
+ QString displayName() const;
QString targetName() const;
- QString barsignerCskPath() const;
- QString barsignerDbPath() const;
- QString defaultKeystorePath() const;
- QString defaultDebugTokenPath() const;
- void loadSettings();
- void clearNdkSettings();
- void cleanNdkConfiguration();
- void syncCertificates(QList<BlackBerryCertificate*> certificates,
- BlackBerryCertificate *activeCertificate);
- void addCertificate(BlackBerryCertificate *certificate);
- void removeCertificate(BlackBerryCertificate *certificate);
-
- QList<BlackBerryCertificate*> certificates() const;
- BlackBerryCertificate *activeCertificate();
-
-public slots:
- void saveSettings();
+ bool isAutoDetected() const;
+ bool isActive() const;
+ bool isValid() const;
+ Utils::FileName ndkEnvFile() const;
+ Utils::FileName qmake4BinaryFile() const;
+ Utils::FileName qmake5BinaryFile() const;
+ Utils::FileName gccCompiler() const;
+ Utils::FileName deviceDebuger() const;
+ Utils::FileName simulatorDebuger() const;
+ Utils::FileName sysRoot() const;
+ QMultiMap<QString, QString> qnxEnv() const;
private:
- BlackBerryConfiguration(QObject *parent = 0);
- static BlackBerryConfiguration *m_instance;
- BlackBerryConfig m_config;
-
- void loadCertificates();
- void loadNdkSettings();
- void saveCertificates();
- void saveNdkSettings();
- bool refresh();
- bool setNdkPath(const QString &ndkPath);
- QtSupport::BaseQtVersion* createQtVersion();
+ QString m_displayName;
+ QString m_targetName;
+ bool m_isAutoDetected;
+ Utils::FileName m_ndkEnvFile;
+ Utils::FileName m_qmake4BinaryFile;
+ Utils::FileName m_qmake5BinaryFile;
+ Utils::FileName m_gccCompiler;
+ Utils::FileName m_deviceDebuger;
+ Utils::FileName m_simulatorDebuger;
+ Utils::FileName m_sysRoot;
+ QMultiMap<QString, QString> m_qnxEnv;
+
+ void setupConfigurationPerQtVersion(const Utils::FileName &qmakePath, ProjectExplorer::GccToolChain* tc);
+ QtSupport::BaseQtVersion* createQtVersion(const Utils::FileName &qmakePath);
ProjectExplorer::GccToolChain* createGccToolChain();
ProjectExplorer::Kit* createKit(QnxArchitecture arch, QtSupport::BaseQtVersion* qtVersion, ProjectExplorer::GccToolChain* tc);
+ void setSticky(ProjectExplorer::Kit* kit);
-signals:
- void updated();
};
} // namespace Internal
diff --git a/src/plugins/qnx/blackberryconfigurationmanager.cpp b/src/plugins/qnx/blackberryconfigurationmanager.cpp
new file mode 100644
index 0000000000..fab197f259
--- /dev/null
+++ b/src/plugins/qnx/blackberryconfigurationmanager.cpp
@@ -0,0 +1,372 @@
+/**************************************************************************
+**
+** Copyright (C) 2013 BlackBerry Limited. All rights reserved.
+**
+** Contact: BlackBerry (qt@blackberry.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 "blackberryconfigurationmanager.h"
+#include "blackberrycertificate.h"
+#include "blackberryconfiguration.h"
+
+#include "qnxutils.h"
+
+#include <coreplugin/icore.h>
+
+#include <utils/persistentsettings.h>
+#include <utils/hostosinfo.h>
+
+#include <projectexplorer/kit.h>
+#include <projectexplorer/kitmanager.h>
+#include <projectexplorer/kitinformation.h>
+#include <projectexplorer/toolchainmanager.h>
+
+#include <qtsupport/qtversionmanager.h>
+#include <qtsupport/qtkitinformation.h>
+
+#include <QMessageBox>
+#include <QFileInfo>
+
+using namespace ProjectExplorer;
+
+namespace Qnx {
+namespace Internal {
+
+namespace {
+const QLatin1String SettingsGroup("BlackBerryConfiguration");
+const QLatin1String NDKLocationKey("NDKLocation"); // For 10.1 NDK support (< QTC 3.0)
+const QLatin1String NDKEnvFileKey("NDKEnvFile");
+const QLatin1String CertificateGroup("Certificates");
+const QLatin1String ManualNDKsGroup("ManualNDKs");
+const QLatin1String ActiveNDKsGroup("ActiveNDKs");
+}
+
+BlackBerryConfigurationManager::BlackBerryConfigurationManager(QObject *parent)
+ :QObject(parent)
+{
+ connect(Core::ICore::instance(), SIGNAL(saveSettingsRequested()), this, SLOT(saveSettings()));
+}
+
+void BlackBerryConfigurationManager::loadManualConfigurations()
+{
+ QSettings *settings = Core::ICore::settings();
+
+ settings->beginGroup(SettingsGroup);
+ settings->beginGroup(ManualNDKsGroup);
+
+ foreach (const QString &manualNdk, settings->childGroups()) {
+ settings->beginGroup(manualNdk);
+ QString ndkEnvPath = settings->value(NDKEnvFileKey).toString();
+ // For 10.1 NDK support (< QTC 3.0):
+ // Since QTC 3.0 BBConfigurations are based on the bbndk-env file
+ // to support multiple targets per NDK
+ if (ndkEnvPath.isEmpty()) {
+ QString ndkPath = settings->value(NDKLocationKey).toString();
+ ndkEnvPath = QnxUtils::envFilePath(ndkPath);
+ }
+
+ BlackBerryConfiguration *config = new BlackBerryConfiguration(Utils::FileName::fromString(ndkEnvPath),
+ false);
+ if (!addConfiguration(config))
+ delete config;
+
+ settings->endGroup();
+ }
+
+ settings->endGroup();
+ settings->endGroup();
+}
+
+void BlackBerryConfigurationManager::loadAutoDetectedConfigurations()
+{
+ QStringList activePaths = activeConfigurationNdkEnvPaths();
+ foreach (const NdkInstallInformation &ndkInfo, QnxUtils::installedNdks()) {
+ QString envFilePath = QnxUtils::envFilePath(ndkInfo.path, ndkInfo.version);
+ BlackBerryConfiguration *config = new BlackBerryConfiguration(Utils::FileName::fromString(envFilePath),
+ true, ndkInfo.name);
+ if (!addConfiguration(config)) {
+ delete config;
+ continue;
+ }
+
+ // Activate targets
+ foreach (const QString activeNdkEnvPath, activePaths) {
+ if (config->ndkEnvFile().toString() == activeNdkEnvPath)
+ config->activate();
+ }
+ }
+
+ // If no target was/is activated, activate one since it's needed by
+ // device connection and CSK code.
+ if (activeConfigurations().isEmpty() && !m_configs.isEmpty())
+ m_configs.first()->activate();
+}
+
+QStringList BlackBerryConfigurationManager::activeConfigurationNdkEnvPaths()
+{
+ QStringList actives;
+ QSettings *settings = Core::ICore::settings();
+
+ settings->beginGroup(SettingsGroup);
+ settings->beginGroup(ActiveNDKsGroup);
+
+ foreach (const QString &activeNdkEnvPath, settings->childGroups()) {
+ settings->beginGroup(activeNdkEnvPath);
+ actives.append(settings->value(NDKEnvFileKey).toString());
+ settings->endGroup();
+ }
+
+ settings->endGroup();
+ settings->endGroup();
+
+ return actives;
+}
+
+void BlackBerryConfigurationManager::saveManualConfigurations()
+{
+ if (manualConfigurations().isEmpty())
+ return;
+
+ QSettings *settings = Core::ICore::settings();
+ settings->beginGroup(SettingsGroup);
+ settings->beginGroup(ManualNDKsGroup);
+
+ foreach (BlackBerryConfiguration *config, manualConfigurations()) {
+ settings->beginGroup(config->displayName());
+ settings->setValue(NDKEnvFileKey, config->ndkEnvFile().toString());
+ settings->endGroup();
+ }
+
+ settings->endGroup();
+ settings->endGroup();
+}
+
+void BlackBerryConfigurationManager::saveActiveConfigurationNdkEnvPath()
+{
+ if (activeConfigurations().isEmpty())
+ return;
+
+ QSettings *settings = Core::ICore::settings();
+ settings->beginGroup(SettingsGroup);
+ settings->beginGroup(ActiveNDKsGroup);
+
+ settings->remove(QString());
+
+ foreach (BlackBerryConfiguration *config, activeConfigurations()) {
+ settings->beginGroup(config->displayName());
+ settings->setValue(NDKEnvFileKey, config->ndkEnvFile().toString());
+ settings->endGroup();
+ }
+
+ settings->endGroup();
+ settings->endGroup();
+}
+
+// Remove no longer available/valid 'auto detected' BlackBerry kits and qt versions
+void BlackBerryConfigurationManager::clearInvalidConfigurations()
+{
+ // Deregister invalid auto deteted BlackBerry Kits
+ foreach (Kit *kit, KitManager::kits()) {
+ if (!kit->isAutoDetected())
+ continue;
+
+ if (DeviceTypeKitInformation::deviceTypeId(kit) == Constants::QNX_BB_OS_TYPE
+ && !kit->isValid())
+ KitManager::deregisterKit(kit);
+ }
+
+ // Remove invalid auto detected BlackBerry qtVerions
+ foreach (QtSupport::BaseQtVersion *qtVersion, QtSupport::QtVersionManager::versions()) {
+ if (!qtVersion->isAutodetected())
+ continue;
+
+ if (qtVersion->platformName() == QLatin1String(Constants::QNX_BB_PLATFORM_NAME)
+ && !qtVersion->isValid())
+ QtSupport::QtVersionManager::removeVersion(qtVersion);
+ }
+}
+
+bool BlackBerryConfigurationManager::addConfiguration(BlackBerryConfiguration *config)
+{
+ foreach (BlackBerryConfiguration *c, m_configs) {
+ if (c->ndkPath() == config->ndkPath()
+ && c->targetName() == config->targetName()) {
+ if (!config->isAutoDetected())
+ QMessageBox::warning(0, tr("NDK Already known"),
+ tr("The NDK already has a configuration."), QMessageBox::Ok);
+ return false;
+ }
+ }
+
+ if (config->isValid()) {
+ m_configs.append(config);
+ return true;
+ }
+
+ return false;
+}
+
+void BlackBerryConfigurationManager::removeConfiguration(BlackBerryConfiguration *config)
+{
+ if (!config)
+ return;
+
+ if (config->isActive())
+ config->deactivate();
+
+ clearConfigurationSettings(config);
+
+ m_configs.removeAt(m_configs.indexOf(config));
+ delete config;
+}
+
+QList<BlackBerryConfiguration *> BlackBerryConfigurationManager::configurations() const
+{
+ return m_configs;
+}
+
+QList<BlackBerryConfiguration *> BlackBerryConfigurationManager::manualConfigurations() const
+{
+ QList<BlackBerryConfiguration*> manuals;
+ foreach (BlackBerryConfiguration *config, m_configs) {
+ if (!config->isAutoDetected())
+ manuals << config;
+ }
+
+ return manuals;
+}
+
+QList<BlackBerryConfiguration *> BlackBerryConfigurationManager::activeConfigurations() const
+{
+ QList<BlackBerryConfiguration*> actives;
+ foreach (BlackBerryConfiguration *config, m_configs) {
+ if (config->isActive())
+ actives << config;
+ }
+
+ return actives;
+}
+
+BlackBerryConfiguration *BlackBerryConfigurationManager::configurationFromEnvFile(const Utils::FileName &envFile) const
+{
+ foreach (BlackBerryConfiguration *config, m_configs) {
+ if (config->ndkEnvFile() == envFile)
+ return config;
+ }
+
+ return 0;
+}
+
+// Returns a valid qnxEnv map from a valid configuration;
+// Needed by other classes to get blackberry process path (keys registration, debug token...)
+QMultiMap<QString, QString> BlackBerryConfigurationManager::defaultQnxEnv()
+{
+ foreach (BlackBerryConfiguration *config, m_configs) {
+ if (config->isActive() && !config->qnxEnv().isEmpty())
+ return config->qnxEnv();
+ }
+
+ return QMultiMap<QString, QString>();
+}
+
+void BlackBerryConfigurationManager::loadSettings()
+{
+ clearInvalidConfigurations();
+ loadAutoDetectedConfigurations();
+ loadManualConfigurations();
+
+ emit settingsLoaded();
+}
+
+void BlackBerryConfigurationManager::clearConfigurationSettings(BlackBerryConfiguration *config)
+{
+ if (!config)
+ return;
+
+ QSettings *settings = Core::ICore::settings();
+ settings->beginGroup(SettingsGroup);
+ settings->beginGroup(ManualNDKsGroup);
+
+ foreach (const QString &manualNdk, settings->childGroups()) {
+ if (manualNdk == config->displayName()) {
+ settings->remove(manualNdk);
+ break;
+ }
+ }
+
+ settings->endGroup();
+ settings->endGroup();
+}
+
+void BlackBerryConfigurationManager::saveSettings()
+{
+ saveActiveConfigurationNdkEnvPath();
+ saveManualConfigurations();
+}
+
+BlackBerryConfigurationManager &BlackBerryConfigurationManager::instance()
+{
+ if (m_instance == 0)
+ m_instance = new BlackBerryConfigurationManager();
+
+ return *m_instance;
+}
+
+BlackBerryConfigurationManager::~BlackBerryConfigurationManager()
+{
+ qDeleteAll(m_configs);
+}
+
+QString BlackBerryConfigurationManager::barsignerCskPath() const
+{
+ return QnxUtils::dataDirPath() + QLatin1String("/barsigner.csk");
+}
+
+QString BlackBerryConfigurationManager::idTokenPath() const
+{
+ return QnxUtils::dataDirPath() + QLatin1String("/bbidtoken.csk");
+}
+
+QString BlackBerryConfigurationManager::barsignerDbPath() const
+{
+ return QnxUtils::dataDirPath() + QLatin1String("/barsigner.db");
+}
+
+QString BlackBerryConfigurationManager::defaultKeystorePath() const
+{
+ return QnxUtils::dataDirPath() + QLatin1String("/author.p12");
+}
+
+QString BlackBerryConfigurationManager::defaultDebugTokenPath() const
+{
+ return QnxUtils::dataDirPath() + QLatin1String("/debugtoken.bar");
+}
+
+BlackBerryConfigurationManager* BlackBerryConfigurationManager::m_instance = 0;
+
+} // namespace Internal
+} // namespace Qnx
diff --git a/src/plugins/qnx/blackberryconfigurationmanager.h b/src/plugins/qnx/blackberryconfigurationmanager.h
new file mode 100644
index 0000000000..ea94d90741
--- /dev/null
+++ b/src/plugins/qnx/blackberryconfigurationmanager.h
@@ -0,0 +1,92 @@
+/**************************************************************************
+**
+** Copyright (C) 2013 BlackBerry Limited. All rights reserved.
+**
+** Contact: BlackBerry (qt@blackberry.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 BLACKBERRYCONFIGURATIONMANAGER_H
+#define BLACKBERRYCONFIGURATIONMANAGER_H
+
+#include <utils/environment.h>
+#include <utils/fileutils.h>
+
+#include <QSettings>
+#include <QObject>
+
+namespace Qnx {
+namespace Internal {
+
+class BlackBerryConfiguration;
+
+class BlackBerryConfigurationManager : public QObject
+{
+ Q_OBJECT
+public:
+ static BlackBerryConfigurationManager &instance();
+ ~BlackBerryConfigurationManager();
+ bool addConfiguration(BlackBerryConfiguration *config);
+ void removeConfiguration(BlackBerryConfiguration *config);
+ QList<BlackBerryConfiguration*> configurations() const;
+ QList<BlackBerryConfiguration*> manualConfigurations() const;
+ QList<BlackBerryConfiguration *> activeConfigurations() const;
+ BlackBerryConfiguration *configurationFromEnvFile(const Utils::FileName &envFile) const;
+
+ QString barsignerCskPath() const;
+ QString idTokenPath() const;
+ QString barsignerDbPath() const;
+ QString defaultKeystorePath() const;
+ QString defaultDebugTokenPath() const;
+ void clearConfigurationSettings(BlackBerryConfiguration *config);
+
+ QMultiMap<QString, QString> defaultQnxEnv();
+
+public slots:
+ void loadSettings();
+ void saveSettings();
+
+signals:
+ void settingsLoaded();
+
+private:
+ BlackBerryConfigurationManager(QObject *parent = 0);
+ static BlackBerryConfigurationManager *m_instance;
+ QList<BlackBerryConfiguration*> m_configs;
+
+ void loadManualConfigurations();
+ void loadAutoDetectedConfigurations();
+ void saveManualConfigurations();
+ void saveActiveConfigurationNdkEnvPath();
+ void clearInvalidConfigurations();
+
+ QStringList activeConfigurationNdkEnvPaths();
+};
+
+} // namespace Internal
+} // namespace Qnx
+
+#endif // BLACKBERRYCONFIGURATIONMANAGER_H
diff --git a/src/plugins/qnx/blackberrycreatecertificatedialog.cpp b/src/plugins/qnx/blackberrycreatecertificatedialog.cpp
index 5be8398c00..3fd3ac18c9 100644
--- a/src/plugins/qnx/blackberrycreatecertificatedialog.cpp
+++ b/src/plugins/qnx/blackberrycreatecertificatedialog.cpp
@@ -1,8 +1,8 @@
/**************************************************************************
**
-** Copyright (C) 2011 - 2013 Research In Motion
+** Copyright (C) 2013 BlackBerry Limited. All rights reserved.
**
-** Contact: Research In Motion (blackberry-qt@qnx.com)
+** Contact: BlackBerry (qt@blackberry.com)
** Contact: KDAB (info@kdab.com)
**
** This file is part of Qt Creator.
@@ -31,6 +31,7 @@
#include "blackberrycreatecertificatedialog.h"
#include "blackberrycertificate.h"
+#include "blackberryconfigurationmanager.h"
#include "ui_blackberrycreatecertificatedialog.h"
#include <QPushButton>
@@ -49,9 +50,6 @@ BlackBerryCreateCertificateDialog::BlackBerryCreateCertificateDialog(
{
m_ui->setupUi(this);
m_ui->progressBar->hide();
- m_ui->certPath->setExpectedKind(Utils::PathChooser::Any);
- m_ui->certPath->setPromptDialogTitle(tr("Create Certificate"));
- m_ui->certPath->setPromptDialogFilter(tr("PKCS 12 archives (*.p12)"));
m_ui->status->clear();
m_cancelButton = m_ui->buttonBox->button(QDialogButtonBox::Cancel);
@@ -64,10 +62,6 @@ BlackBerryCreateCertificateDialog::BlackBerryCreateCertificateDialog(
this, SLOT(reject()));
connect(m_okButton, SIGNAL(clicked()),
this, SLOT(createCertificate()));
- connect(m_ui->certPath, SIGNAL(changed(QString)),
- this, SLOT(validate()));
- connect(m_ui->certPath, SIGNAL(editingFinished()),
- this, SLOT(appendExtension()));
connect(m_ui->author, SIGNAL(textChanged(QString)),
this, SLOT(validate()));
connect(m_ui->password, SIGNAL(textChanged(QString)),
@@ -85,7 +79,7 @@ QString BlackBerryCreateCertificateDialog::author() const
QString BlackBerryCreateCertificateDialog::certPath() const
{
- return m_ui->certPath->path();
+ return BlackBerryConfigurationManager::instance().defaultKeystorePath();
}
QString BlackBerryCreateCertificateDialog::keystorePassword() const
@@ -100,8 +94,7 @@ BlackBerryCertificate * BlackBerryCreateCertificateDialog::certificate() const
void BlackBerryCreateCertificateDialog::validate()
{
- if (!m_ui->certPath->isValid()
- || m_ui->author->text().isEmpty()
+ if (m_ui->author->text().isEmpty()
|| m_ui->password->text().isEmpty()
|| m_ui->password2->text().isEmpty()) {
m_ui->status->clear();
@@ -109,7 +102,7 @@ void BlackBerryCreateCertificateDialog::validate()
return;
}
- QFileInfo fileInfo(m_ui->certPath->path());
+ QFileInfo fileInfo(certPath());
if (!fileInfo.dir().exists()) {
m_ui->status->setText(tr("Base directory does not exist."));
@@ -123,6 +116,12 @@ void BlackBerryCreateCertificateDialog::validate()
return;
}
+ if (m_ui->password->text().size() < 6) {
+ m_ui->status->setText(tr("Password must be at least 6 characters long."));
+ m_okButton->setEnabled(false);
+ return;
+ }
+
m_ui->status->clear();
m_okButton->setEnabled(true);
}
@@ -131,7 +130,7 @@ void BlackBerryCreateCertificateDialog::createCertificate()
{
setBusy(true);
- QFile file(m_ui->certPath->path());
+ QFile file(certPath());
if (file.exists()) {
const int result = QMessageBox::question(this, tr("Are you sure?"),
@@ -153,16 +152,6 @@ void BlackBerryCreateCertificateDialog::createCertificate()
m_certificate->store();
}
-void BlackBerryCreateCertificateDialog::appendExtension()
-{
- QString path = m_ui->certPath->path();
-
- if (!path.endsWith(QLatin1String(".p12"))) {
- path += QLatin1String(".p12");
- m_ui->certPath->setPath(path);
- }
-}
-
void BlackBerryCreateCertificateDialog::checkBoxChanged(int state)
{
if (state == Qt::Checked) {
@@ -176,22 +165,41 @@ void BlackBerryCreateCertificateDialog::checkBoxChanged(int state)
void BlackBerryCreateCertificateDialog::certificateCreated(int status)
{
- if (status == BlackBerryCertificate::Success) {
+ QString errorMessage;
+
+ switch (status) {
+ case BlackBerryCertificate::Success:
accept();
- } else {
- m_certificate->deleteLater();
- m_certificate = 0;
- QMessageBox::critical(this, tr("Error"),
- tr("An unknown error occurred while creating the certificate."));
- reject();
+ return;
+ case BlackBerryCertificate::Busy:
+ errorMessage = tr("The blackberry-keytool process is already running");
+ break;
+ case BlackBerryCertificate::WrongPassword:
+ errorMessage = tr("The enteres password is invalid");
+ break;
+ case BlackBerryCertificate::PasswordTooSmall:
+ errorMessage = tr("The enteres password is too small");
+ break;
+ case BlackBerryCertificate::InvalidOutputFormat:
+ errorMessage = tr("Invalid output format");
+ break;
+ case BlackBerryCertificate::Error:
+ default:
+ errorMessage = tr("An unknown error occurred");
+ break;
}
+
+ m_certificate->deleteLater();
+ m_certificate = 0;
+ QMessageBox::critical(this, tr("Error"), errorMessage);
+
+ reject();
}
void BlackBerryCreateCertificateDialog::setBusy(bool busy)
{
m_okButton->setEnabled(!busy);
m_cancelButton->setEnabled(!busy);
- m_ui->certPath->setEnabled(!busy);
m_ui->author->setEnabled(!busy);
m_ui->password->setEnabled(!busy);
m_ui->password2->setEnabled(!busy);
diff --git a/src/plugins/qnx/blackberrycreatecertificatedialog.h b/src/plugins/qnx/blackberrycreatecertificatedialog.h
index 19a7734e64..f347689d37 100644
--- a/src/plugins/qnx/blackberrycreatecertificatedialog.h
+++ b/src/plugins/qnx/blackberrycreatecertificatedialog.h
@@ -1,8 +1,8 @@
/**************************************************************************
**
-** Copyright (C) 2011 - 2013 Research In Motion
+** Copyright (C) 2013 BlackBerry Limited. All rights reserved.
**
-** Contact: Research In Motion (blackberry-qt@qnx.com)
+** Contact: BlackBerry (qt@blackberry.com)
** Contact: KDAB (info@kdab.com)
**
** This file is part of Qt Creator.
@@ -61,7 +61,6 @@ public:
private slots:
void validate();
void createCertificate();
- void appendExtension();
void checkBoxChanged(int state);
void certificateCreated(int status);
diff --git a/src/plugins/qnx/blackberrycreatecertificatedialog.ui b/src/plugins/qnx/blackberrycreatecertificatedialog.ui
index 521ca6dda7..02369458c1 100644
--- a/src/plugins/qnx/blackberrycreatecertificatedialog.ui
+++ b/src/plugins/qnx/blackberrycreatecertificatedialog.ui
@@ -17,19 +17,6 @@
<item>
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0">
- <widget class="QLabel" name="label">
- <property name="text">
- <string>Path:</string>
- </property>
- <property name="alignment">
- <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
- </property>
- </widget>
- </item>
- <item row="0" column="1">
- <widget class="Utils::PathChooser" name="certPath" native="true"/>
- </item>
- <item row="1" column="0">
<widget class="QLabel" name="label_2">
<property name="text">
<string>Author:</string>
@@ -39,10 +26,10 @@
</property>
</widget>
</item>
- <item row="1" column="1">
+ <item row="0" column="1">
<widget class="QLineEdit" name="author"/>
</item>
- <item row="2" column="0">
+ <item row="1" column="0">
<widget class="QLabel" name="label_3">
<property name="text">
<string>Password:</string>
@@ -52,14 +39,14 @@
</property>
</widget>
</item>
- <item row="2" column="1">
+ <item row="1" column="1">
<widget class="QLineEdit" name="password">
<property name="echoMode">
<enum>QLineEdit::Password</enum>
</property>
</widget>
</item>
- <item row="3" column="0">
+ <item row="2" column="0">
<widget class="QLabel" name="label_4">
<property name="text">
<string>Confirm password:</string>
@@ -69,21 +56,21 @@
</property>
</widget>
</item>
- <item row="3" column="1">
+ <item row="2" column="1">
<widget class="QLineEdit" name="password2">
<property name="echoMode">
<enum>QLineEdit::Password</enum>
</property>
</widget>
</item>
- <item row="4" column="0">
+ <item row="3" column="0">
<widget class="QCheckBox" name="showPassword">
<property name="text">
<string>Show password</string>
</property>
</widget>
</item>
- <item row="4" column="1">
+ <item row="3" column="1">
<widget class="QLabel" name="status">
<property name="font">
<font>
@@ -120,14 +107,6 @@
</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/blackberrycreatepackagestep.cpp b/src/plugins/qnx/blackberrycreatepackagestep.cpp
index 4c21158323..b8ef2f8011 100644
--- a/src/plugins/qnx/blackberrycreatepackagestep.cpp
+++ b/src/plugins/qnx/blackberrycreatepackagestep.cpp
@@ -301,8 +301,8 @@ bool BlackBerryCreatePackageStep::prepareAppDescriptorFile(const QString &appDes
}
}
- const QString buildDir = target()->activeBuildConfiguration()->buildDirectory();
if (!preparedFile.open(QIODevice::WriteOnly)) {
+ const QString buildDir = target()->activeBuildConfiguration()->buildDirectory().toUserOutput();
raiseError(tr("Could not create prepared application descriptor file in '%1'").arg(buildDir));
return false;
}
diff --git a/src/plugins/qnx/blackberrycsjregistrar.cpp b/src/plugins/qnx/blackberrycsjregistrar.cpp
deleted file mode 100644
index 1066d6a2af..0000000000
--- a/src/plugins/qnx/blackberrycsjregistrar.cpp
+++ /dev/null
@@ -1,116 +0,0 @@
-/**************************************************************************
-**
-** 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 "blackberrycsjregistrar.h"
-#include "blackberryconfiguration.h"
-
-#include <utils/hostosinfo.h>
-
-#include <QProcess>
-#include <QStringList>
-#include <QString>
-
-namespace Qnx {
-namespace Internal {
-
-BlackBerryCsjRegistrar::BlackBerryCsjRegistrar(QObject *parent) :
- QObject(parent),
- m_process(new QProcess(this))
-{
- connect(m_process, SIGNAL(finished(int,QProcess::ExitStatus)),
- this, SLOT(processFinished()));
- connect(m_process, SIGNAL(error(QProcess::ProcessError)),
- this, SLOT(processError(QProcess::ProcessError)));
-}
-
-void BlackBerryCsjRegistrar::tryRegister(const QStringList &csjFiles,
- const QString &csjPin, const QString &cskPassword)
-{
- if (m_process->state() != QProcess::NotRunning)
- return;
-
- QString command = BlackBerryConfiguration::instance()
- .qnxEnv().value(QLatin1String("QNX_HOST"))
- + (QLatin1String("/usr/bin/blackberry-signer"));
-
- if (Utils::HostOsInfo::isWindowsHost())
- command += QLatin1String(".bat");
-
- QStringList arguments;
-
- arguments << QLatin1String("-register")
- << QLatin1String("-cskpass")
- << cskPassword
- << QLatin1String("-csjpin")
- << csjPin
- << csjFiles;
-
- m_process->start(command, arguments);
-}
-
-void BlackBerryCsjRegistrar::processFinished()
-{
- QByteArray result = m_process->readAllStandardOutput();
-
- if (result.contains("Successfully registered with server."))
- emit finished(RegisterSuccess, QString());
- else
- emit finished(Error, QLatin1String(result));
-}
-
-void BlackBerryCsjRegistrar::processError(QProcess::ProcessError error)
-{
- QString errorMessage;
-
- switch (error) {
- case QProcess::FailedToStart:
- errorMessage = tr("Failed to start blackberry-signer process.");
- break;
- case QProcess::Timedout:
- errorMessage = tr("Process timed out.");
- break;
- case QProcess::Crashed:
- errorMessage = tr("Child process has crashed.");
- break;
- case QProcess::WriteError:
- case QProcess::ReadError:
- errorMessage = tr("Process I/O error.");
- break;
- case QProcess::UnknownError:
- errorMessage = tr("Unknown process error.");
- break;
- }
-
- emit finished(Error, errorMessage);
-}
-
-} // namespace Internal
-} // namespace Qnx
diff --git a/src/plugins/qnx/blackberrydebugtokenrequestdialog.cpp b/src/plugins/qnx/blackberrydebugtokenrequestdialog.cpp
index 8728f11c07..d4011d246b 100644
--- a/src/plugins/qnx/blackberrydebugtokenrequestdialog.cpp
+++ b/src/plugins/qnx/blackberrydebugtokenrequestdialog.cpp
@@ -1,8 +1,8 @@
/**************************************************************************
**
-** Copyright (C) 2011 - 2013 Research In Motion
+** Copyright (C) 2013 BlackBerry Limited. All rights reserved.
**
-** Contact: Research In Motion (blackberry-qt@qnx.com)
+** Contact: BlackBerry (qt@blackberry.com)
** Contact: KDAB (info@kdab.com)
**
** This file is part of Qt Creator.
@@ -32,8 +32,8 @@
#include "blackberrydebugtokenrequestdialog.h"
#include "blackberrydebugtokenrequester.h"
#include "blackberrydeviceinformation.h"
-#include "blackberryconfiguration.h"
-#include "blackberrycertificate.h"
+#include "blackberryconfigurationmanager.h"
+#include "blackberrysigningutils.h"
#include "ui_blackberrydebugtokenrequestdialog.h"
#include <QPushButton>
@@ -48,7 +48,8 @@ BlackBerryDebugTokenRequestDialog::BlackBerryDebugTokenRequestDialog(
QDialog(parent, f),
m_ui(new Ui_BlackBerryDebugTokenRequestDialog),
m_requester(new BlackBerryDebugTokenRequester(this)),
- m_deviceInfo(new BlackBerryDeviceInformation(this))
+ m_deviceInfo(new BlackBerryDeviceInformation(this)),
+ m_utils(BlackBerrySigningUtils::instance())
{
m_ui->setupUi(this);
m_ui->progressBar->hide();
@@ -61,8 +62,6 @@ BlackBerryDebugTokenRequestDialog::BlackBerryDebugTokenRequestDialog(
m_okButton = m_ui->buttonBox->button(QDialogButtonBox::Ok);
m_okButton->setEnabled(false);
- populateComboBox();
-
connect(m_cancelButton, SIGNAL(clicked()),
this, SLOT(reject()));
connect(m_okButton, SIGNAL(clicked()),
@@ -75,14 +74,8 @@ BlackBerryDebugTokenRequestDialog::BlackBerryDebugTokenRequestDialog(
this, SLOT(appendExtension()));
connect(m_ui->debugTokenPath, SIGNAL(editingFinished()),
this, SLOT(expandPath()));
- connect(m_ui->keystorePassword, SIGNAL(textChanged(QString)),
- this, SLOT(validate()));
- connect(m_ui->cskPassword, SIGNAL(textChanged(QString)),
- this, SLOT(validate()));
connect(m_ui->devicePin, SIGNAL(textChanged(QString)),
this, SLOT(validate()));
- connect(m_ui->showPassword, SIGNAL(stateChanged(int)),
- this, SLOT(checkBoxChanged(int)));
connect(m_requester, SIGNAL(finished(int)),
this, SLOT(debugTokenArrived(int)));
connect(m_deviceInfo, SIGNAL(finished(int)),
@@ -99,6 +92,11 @@ QString BlackBerryDebugTokenRequestDialog::debugToken() const
return m_ui->debugTokenPath->path();
}
+void BlackBerryDebugTokenRequestDialog::setDevicePin(const QString &devicePin)
+{
+ m_ui->devicePin->setText(devicePin);
+}
+
void BlackBerryDebugTokenRequestDialog::setTargetDetails(const QString &deviceIp, const QString &password)
{
m_ui->devicePin->setPlaceholderText(tr("Requesting Device PIN..."));
@@ -107,10 +105,7 @@ void BlackBerryDebugTokenRequestDialog::setTargetDetails(const QString &deviceIp
void BlackBerryDebugTokenRequestDialog::validate()
{
- if (!m_ui->debugTokenPath->isValid()
- || m_ui->keystorePassword->text().isEmpty()
- || m_ui->devicePin->text().isEmpty()
- || m_ui->cskPassword->text().isEmpty()) {
+ if (!m_ui->debugTokenPath->isValid() || m_ui->devicePin->text().isEmpty()) {
m_okButton->setEnabled(false);
return;
}
@@ -146,10 +141,11 @@ void BlackBerryDebugTokenRequestDialog::requestDebugToken()
}
}
+ BlackBerryConfigurationManager &configuration = BlackBerryConfigurationManager::instance();
+
m_requester->requestDebugToken(m_ui->debugTokenPath->path(),
- m_ui->cskPassword->text(),
- m_ui->keystore->itemText(m_ui->keystore->currentIndex()),
- m_ui->keystorePassword->text(), m_ui->devicePin->text());
+ m_utils.cskPassword(), configuration.defaultKeystorePath(),
+ m_utils.certificatePassword(), m_ui->devicePin->text());
}
void BlackBerryDebugTokenRequestDialog::setDefaultPath()
@@ -193,17 +189,6 @@ void BlackBerryDebugTokenRequestDialog::expandPath()
m_ui->debugTokenPath->setPath(fileInfo.absoluteFilePath());
}
-void BlackBerryDebugTokenRequestDialog::checkBoxChanged(int state)
-{
- if (state == Qt::Checked) {
- m_ui->cskPassword->setEchoMode(QLineEdit::Normal);
- m_ui->keystorePassword->setEchoMode(QLineEdit::Normal);
- } else {
- m_ui->cskPassword->setEchoMode(QLineEdit::Password);
- m_ui->keystorePassword->setEchoMode(QLineEdit::Password);
- }
-}
-
void BlackBerryDebugTokenRequestDialog::debugTokenArrived(int status)
{
QString errorString = tr("Failed to request debug token: ");
@@ -213,9 +198,11 @@ void BlackBerryDebugTokenRequestDialog::debugTokenArrived(int status)
accept();
return;
case BlackBerryDebugTokenRequester::WrongCskPassword:
+ m_utils.clearCskPassword();
errorString += tr("Wrong CSK password.");
break;
case BlackBerryDebugTokenRequester::WrongKeystorePassword:
+ m_utils.clearCertificatePassword();
errorString += tr("Wrong keystore password.");
break;
case BlackBerryDebugTokenRequester::NetworkUnreachable:
@@ -241,6 +228,9 @@ void BlackBerryDebugTokenRequestDialog::debugTokenArrived(int status)
errorString += tr("Not yet registered to request debug tokens.");
break;
case BlackBerryDebugTokenRequester::UnknownError:
+ default:
+ m_utils.clearCertificatePassword();
+ m_utils.clearCskPassword();
errorString += tr("An unknwon error has occurred.");
break;
}
@@ -268,10 +258,6 @@ void BlackBerryDebugTokenRequestDialog::setBusy(bool busy)
m_okButton->setEnabled(!busy);
m_cancelButton->setEnabled(!busy);
m_ui->debugTokenPath->setEnabled(!busy);
- m_ui->keystore->setEnabled(!busy);
- m_ui->keystorePassword->setEnabled(!busy);
- m_ui->cskPassword->setEnabled(!busy);
- m_ui->showPassword->setEnabled(!busy);
m_ui->devicePin->setEnabled(!busy);
m_ui->progressBar->setVisible(busy);
@@ -281,15 +267,5 @@ void BlackBerryDebugTokenRequestDialog::setBusy(bool busy)
m_ui->status->clear();
}
-void BlackBerryDebugTokenRequestDialog::populateComboBox()
-{
- BlackBerryConfiguration &configuration = BlackBerryConfiguration::instance();
-
- QList<BlackBerryCertificate*> certificates = configuration.certificates();
-
- foreach (const BlackBerryCertificate *certificate, certificates)
- m_ui->keystore->addItem(certificate->fileName());
-}
-
}
} // namespace Qnx
diff --git a/src/plugins/qnx/blackberrydebugtokenrequestdialog.h b/src/plugins/qnx/blackberrydebugtokenrequestdialog.h
index 7fe3e8065f..06fd0468a6 100644
--- a/src/plugins/qnx/blackberrydebugtokenrequestdialog.h
+++ b/src/plugins/qnx/blackberrydebugtokenrequestdialog.h
@@ -1,8 +1,8 @@
/**************************************************************************
**
-** Copyright (C) 2011 - 2013 Research In Motion
+** Copyright (C) 2013 BlackBerry Limited. All rights reserved.
**
-** Contact: Research In Motion (blackberry-qt@qnx.com)
+** Contact: BlackBerry (qt@blackberry.com)
** Contact: KDAB (info@kdab.com)
**
** This file is part of Qt Creator.
@@ -44,6 +44,7 @@ namespace Internal {
class Ui_BlackBerryDebugTokenRequestDialog;
class BlackBerryDebugTokenRequester;
class BlackBerryDeviceInformation;
+class BlackBerrySigningUtils;
class BlackBerryDebugTokenRequestDialog : public QDialog
{
@@ -55,6 +56,7 @@ public:
~BlackBerryDebugTokenRequestDialog();
QString debugToken() const;
+ void setDevicePin(const QString &devicePin);
void setTargetDetails(const QString &deviceIp, const QString &password);
private slots:
@@ -63,18 +65,17 @@ private slots:
void setDefaultPath();
void appendExtension();
void expandPath();
- void checkBoxChanged(int state);
void debugTokenArrived(int status);
void setDevicePin(int status);
private:
void setBusy(bool busy);
- void populateComboBox();
Ui_BlackBerryDebugTokenRequestDialog *m_ui;
BlackBerryDebugTokenRequester *m_requester;
BlackBerryDeviceInformation *m_deviceInfo;
+ BlackBerrySigningUtils &m_utils;
QPushButton *m_cancelButton;
QPushButton *m_okButton;
diff --git a/src/plugins/qnx/blackberrydebugtokenrequestdialog.ui b/src/plugins/qnx/blackberrydebugtokenrequestdialog.ui
index e2059c5555..aa65f78ce4 100644
--- a/src/plugins/qnx/blackberrydebugtokenrequestdialog.ui
+++ b/src/plugins/qnx/blackberrydebugtokenrequestdialog.ui
@@ -7,7 +7,7 @@
<x>0</x>
<y>0</y>
<width>388</width>
- <height>198</height>
+ <height>153</height>
</rect>
</property>
<property name="windowTitle">
@@ -30,53 +30,6 @@
<widget class="Utils::PathChooser" name="debugTokenPath" native="true"/>
</item>
<item row="1" column="0">
- <widget class="QLabel" name="label_2">
- <property name="text">
- <string>Keystore:</string>
- </property>
- <property name="alignment">
- <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
- </property>
- </widget>
- </item>
- <item row="1" column="1">
- <widget class="QComboBox" name="keystore"/>
- </item>
- <item row="2" column="0">
- <widget class="QLabel" name="label_3">
- <property name="text">
- <string>Keystore password:</string>
- </property>
- <property name="alignment">
- <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
- </property>
- </widget>
- </item>
- <item row="2" column="1">
- <widget class="QLineEdit" name="keystorePassword">
- <property name="echoMode">
- <enum>QLineEdit::Password</enum>
- </property>
- </widget>
- </item>
- <item row="3" column="0">
- <widget class="QLabel" name="label_4">
- <property name="text">
- <string>CSK password:</string>
- </property>
- <property name="alignment">
- <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
- </property>
- </widget>
- </item>
- <item row="3" column="1">
- <widget class="QLineEdit" name="cskPassword">
- <property name="echoMode">
- <enum>QLineEdit::Password</enum>
- </property>
- </widget>
- </item>
- <item row="4" column="0">
<widget class="QLabel" name="label_5">
<property name="text">
<string>Device PIN:</string>
@@ -86,36 +39,29 @@
</property>
</widget>
</item>
- <item row="4" column="1">
+ <item row="1" column="1">
<widget class="QLineEdit" name="devicePin">
<property name="inputMask">
- <string notr="true">HHHHHHHH; </string>
+ <string notr="true">HHHHHHHH</string>
</property>
<property name="maxLength">
<number>8</number>
</property>
</widget>
</item>
- <item row="5" column="0">
- <widget class="QCheckBox" name="showPassword">
- <property name="text">
- <string>Show password</string>
- </property>
- </widget>
- </item>
- <item row="5" column="1">
- <widget class="QProgressBar" name="progressBar">
- <property name="maximum">
- <number>0</number>
- </property>
- <property name="value">
- <number>0</number>
- </property>
- </widget>
- </item>
</layout>
</item>
<item>
+ <widget class="QProgressBar" name="progressBar">
+ <property name="maximum">
+ <number>0</number>
+ </property>
+ <property name="value">
+ <number>0</number>
+ </property>
+ </widget>
+ </item>
+ <item>
<widget class="QLabel" name="status">
<property name="font">
<font>
diff --git a/src/plugins/qnx/blackberrydebugtokenrequester.cpp b/src/plugins/qnx/blackberrydebugtokenrequester.cpp
index 2e7c8576d9..c7fdbb3e9d 100644
--- a/src/plugins/qnx/blackberrydebugtokenrequester.cpp
+++ b/src/plugins/qnx/blackberrydebugtokenrequester.cpp
@@ -34,8 +34,9 @@
namespace {
static const char PROCESS_NAME[] = "blackberry-debugtokenrequest";
static const char ERR_WRONG_CSK_PASS[] = "The signature on the code signing request didn't verify.";
+static const char ERR_WRONG_CSK_PASS_10_2[] = "The specified CSK password is not valid.";
static const char ERR_WRONG_KEYSTORE_PASS[] = "Failed to decrypt keystore, invalid password";
-static const char ERR_ILLEGAL_DEVICE_PIN[] = "Illegal device PIN";
+static const char ERR_WRONG_KEYSTORE_PASS_10_2[] = "Failed to decrypt keystore, invalid store password or store password not supplied.";
static const char ERR_NETWORK_UNREACHABLE[] = "Network is unreachable";
static const char ERR_NOT_YET_REGISTGERED[] = "Not yet registered to request debug tokens";
}
@@ -47,8 +48,9 @@ BlackBerryDebugTokenRequester::BlackBerryDebugTokenRequester(QObject *parent) :
BlackBerryNdkProcess(QLatin1String(PROCESS_NAME), parent)
{
addErrorStringMapping(QLatin1String(ERR_WRONG_CSK_PASS), WrongCskPassword);
+ addErrorStringMapping(QLatin1String(ERR_WRONG_CSK_PASS_10_2), WrongCskPassword);
addErrorStringMapping(QLatin1String(ERR_WRONG_KEYSTORE_PASS), WrongKeystorePassword);
- addErrorStringMapping(QLatin1String(ERR_WRONG_KEYSTORE_PASS), WrongKeystorePassword);
+ addErrorStringMapping(QLatin1String(ERR_WRONG_KEYSTORE_PASS_10_2), WrongKeystorePassword);
addErrorStringMapping(QLatin1String(ERR_NETWORK_UNREACHABLE), NetworkUnreachable);
addErrorStringMapping(QLatin1String(ERR_NOT_YET_REGISTGERED), NotYetRegistered);
}
diff --git a/src/plugins/qnx/blackberrydebugtokenuploader.cpp b/src/plugins/qnx/blackberrydebugtokenuploader.cpp
index c87d066727..a2182e8ffe 100644
--- a/src/plugins/qnx/blackberrydebugtokenuploader.cpp
+++ b/src/plugins/qnx/blackberrydebugtokenuploader.cpp
@@ -37,6 +37,7 @@ namespace {
static const char ERR_NO_ROUTE_HOST[] = "Cannot connect";
static const char ERR_AUTH_FAILED[] = "Authentication failed";
static const char ERR_DEVELOPMENT_MODE_DISABLED[] = "Device is not in the Development Mode";
+static const char ERR_FILE_NOT_EXIST[] = "File does not exist";
}
namespace Qnx {
@@ -48,6 +49,7 @@ BlackBerryDebugTokenUploader::BlackBerryDebugTokenUploader(QObject *parent) :
addErrorStringMapping(QLatin1String(ERR_NO_ROUTE_HOST), NoRouteToHost);
addErrorStringMapping(QLatin1String(ERR_AUTH_FAILED), AuthenticationFailed);
addErrorStringMapping(QLatin1String(ERR_DEVELOPMENT_MODE_DISABLED), DevelopmentModeDisabled);
+ addErrorStringMapping(QLatin1String(ERR_FILE_NOT_EXIST), InvalidDebugTokenPath);
}
void BlackBerryDebugTokenUploader::uploadDebugToken(const QString &path,
diff --git a/src/plugins/qnx/blackberrydebugtokenuploader.h b/src/plugins/qnx/blackberrydebugtokenuploader.h
index ff892b8b90..763cdffb95 100644
--- a/src/plugins/qnx/blackberrydebugtokenuploader.h
+++ b/src/plugins/qnx/blackberrydebugtokenuploader.h
@@ -51,7 +51,8 @@ public:
InferiorProcessTimedOut,
InferiorProcessCrashed,
InferiorProcessWriteError,
- InferiorProcessReadError
+ InferiorProcessReadError,
+ InvalidDebugTokenPath
};
explicit BlackBerryDebugTokenUploader(QObject *parent = 0);
diff --git a/src/plugins/qnx/blackberrydeployconfiguration.cpp b/src/plugins/qnx/blackberrydeployconfiguration.cpp
index 734e00d09f..89f163380b 100644
--- a/src/plugins/qnx/blackberrydeployconfiguration.cpp
+++ b/src/plugins/qnx/blackberrydeployconfiguration.cpp
@@ -35,8 +35,6 @@
#include "blackberrydeployconfigurationwidget.h"
#include "blackberrydeployinformation.h"
-#include "utils/checkablemessagebox.h"
-
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/target.h>
#include <projectexplorer/projectexplorer.h>
@@ -46,6 +44,7 @@
#include <qtsupport/qtkitinformation.h>
#include <coreplugin/icore.h>
#include <ssh/sshconnection.h>
+#include <utils/checkablemessagebox.h>
#include <QMessageBox>
@@ -53,7 +52,6 @@ using namespace Qnx;
using namespace Qnx::Internal;
namespace {
-const char DEPLOYMENT_INFO_SETTING[] = "Qnx.BlackBerry.DeploymentInfo";
const char DEPLOYMENT_INFO_KEY[] = "Qnx.BlackBerry.DeployInformation";
const char BAR_DESC_SETUP[] = "Qnx.BlackBerry.DeployInformation.BarDescriptorSetup";
}
diff --git a/src/plugins/qnx/blackberrydeployinformation.cpp b/src/plugins/qnx/blackberrydeployinformation.cpp
index 5698bd8893..ed4412593b 100644
--- a/src/plugins/qnx/blackberrydeployinformation.cpp
+++ b/src/plugins/qnx/blackberrydeployinformation.cpp
@@ -221,7 +221,9 @@ void BlackBerryDeployInformation::fromMap(const QVariantMap &map)
const QString targetName = innerMap.value(QLatin1String(TARGET_KEY)).toString();
const QString sourceDir = innerMap.value(QLatin1String(SOURCE_KEY)).toString();
- BarPackageDeployInformation deployInformation(enabled, proFilePath, sourceDir, m_target->activeBuildConfiguration()->buildDirectory(), targetName);
+ BarPackageDeployInformation deployInformation(enabled, proFilePath, sourceDir,
+ m_target->activeBuildConfiguration()->buildDirectory().toString(),
+ targetName);
deployInformation.userAppDescriptorPath = appDescriptorPath;
deployInformation.userPackagePath = packagePath;
m_deployInformation << deployInformation;
@@ -248,7 +250,7 @@ void BlackBerryDeployInformation::updateModel()
|| !m_deployInformation[i].userPackagePath.isEmpty())) {
BarPackageDeployInformation deployInformation = m_deployInformation[i];
// In case the user resets the bar package path (or if it is empty already), we need the current build dir
- deployInformation.buildDir = m_target->activeBuildConfiguration()->buildDirectory();
+ deployInformation.buildDir = m_target->activeBuildConfiguration()->buildDirectory().toString();
keep << deployInformation;
nodeFound = true;
break;
@@ -302,7 +304,7 @@ BarPackageDeployInformation BlackBerryDeployInformation::deployInformationFromNo
Qt4ProjectManager::TargetInformation ti = node->targetInformation();
QFileInfo fi(node->path());
- const QString buildDir = m_target->activeBuildConfiguration()->buildDirectory();
+ const QString buildDir = m_target->activeBuildConfiguration()->buildDirectory().toString();
return BarPackageDeployInformation(true, node->path(), fi.absolutePath(), buildDir, ti.target);
}
diff --git a/src/plugins/qnx/blackberrydeviceconfiguration.cpp b/src/plugins/qnx/blackberrydeviceconfiguration.cpp
index 7fd5ac0474..d13b793103 100644
--- a/src/plugins/qnx/blackberrydeviceconfiguration.cpp
+++ b/src/plugins/qnx/blackberrydeviceconfiguration.cpp
@@ -32,11 +32,13 @@
#include "blackberrydeviceconfiguration.h"
#include "qnxconstants.h"
+#include "qnxdeviceprocesssignaloperation.h"
#include "blackberrydeviceconfigurationwidget.h"
#include "blackberrydeviceconnectionmanager.h"
-#include "blackberrydeviceprocesssupport.h"
+#include "qnxdeviceprocesslist.h"
#include <projectexplorer/kitinformation.h>
+#include <ssh/sshconnection.h>
using namespace Qnx;
using namespace Qnx::Internal;
@@ -98,15 +100,17 @@ IDevice::Ptr BlackBerryDeviceConfiguration::clone() const
return Ptr(new BlackBerryDeviceConfiguration(*this));
}
-BlackBerryDeviceConfiguration::ConstPtr BlackBerryDeviceConfiguration::device(const Kit *k)
+bool BlackBerryDeviceConfiguration::hasDeviceTester() const
{
- IDevice::ConstPtr dev = DeviceKitInformation::device(k);
- return dev.dynamicCast<const BlackBerryDeviceConfiguration>();
+ // we are unable to easily verify that a device is available unless we duplicate
+ // 'Connect to device' functionality, therefore disabling device-tester
+ return false;
}
-DeviceProcessSupport::Ptr BlackBerryDeviceConfiguration::processSupport() const
+BlackBerryDeviceConfiguration::ConstPtr BlackBerryDeviceConfiguration::device(const Kit *k)
{
- return ProjectExplorer::DeviceProcessSupport::Ptr(new BlackBerryDeviceProcessSupport);
+ IDevice::ConstPtr dev = DeviceKitInformation::device(k);
+ return dev.dynamicCast<const BlackBerryDeviceConfiguration>();
}
QString BlackBerryDeviceConfiguration::displayType() const
@@ -136,7 +140,7 @@ QString BlackBerryDeviceConfiguration::displayNameForActionId(Core::Id actionId)
return QString();
}
-void BlackBerryDeviceConfiguration::executeAction(Core::Id actionId, QWidget *parent) const
+void BlackBerryDeviceConfiguration::executeAction(Core::Id actionId, QWidget *parent)
{
Q_UNUSED(parent);
@@ -158,3 +162,14 @@ QVariantMap BlackBerryDeviceConfiguration::toMap() const
map.insert(QLatin1String(Constants::QNX_DEBUG_TOKEN_KEY), m_debugToken);
return map;
}
+
+DeviceProcessList *BlackBerryDeviceConfiguration::createProcessListModel(QObject *parent) const
+{
+ return new QnxDeviceProcessList(sharedFromThis(), parent);
+}
+
+DeviceProcessSignalOperation::Ptr BlackBerryDeviceConfiguration::signalOperation() const
+{
+ return DeviceProcessSignalOperation::Ptr(
+ new BlackBerryDeviceProcessSignalOperation(sshParameters()));
+}
diff --git a/src/plugins/qnx/blackberrydeviceconfiguration.h b/src/plugins/qnx/blackberrydeviceconfiguration.h
index 154dc0af2e..99dd6790d4 100644
--- a/src/plugins/qnx/blackberrydeviceconfiguration.h
+++ b/src/plugins/qnx/blackberrydeviceconfiguration.h
@@ -62,13 +62,14 @@ public:
ProjectExplorer::IDeviceWidget *createWidget();
QList<Core::Id> actionIds() const;
QString displayNameForActionId(Core::Id actionId) const;
- void executeAction(Core::Id actionId, QWidget *parent) const;
+ void executeAction(Core::Id actionId, QWidget *parent);
ProjectExplorer::IDevice::Ptr clone() const;
+ ProjectExplorer::DeviceProcessList *createProcessListModel(QObject *parent) const;
+ bool hasDeviceTester() const;
+ ProjectExplorer::DeviceProcessSignalOperation::Ptr signalOperation() const;
static ConstPtr device(const ProjectExplorer::Kit *k);
- ProjectExplorer::DeviceProcessSupport::Ptr processSupport() const;
-
protected:
BlackBerryDeviceConfiguration();
BlackBerryDeviceConfiguration(const QString &name, Core::Id type, MachineType machineType,
diff --git a/src/plugins/qnx/blackberrydeviceconfigurationwidget.cpp b/src/plugins/qnx/blackberrydeviceconfigurationwidget.cpp
index 252cbb320c..d9d0115ffd 100644
--- a/src/plugins/qnx/blackberrydeviceconfigurationwidget.cpp
+++ b/src/plugins/qnx/blackberrydeviceconfigurationwidget.cpp
@@ -61,7 +61,7 @@ BlackBerryDeviceConfigurationWidget::BlackBerryDeviceConfigurationWidget(const I
{
ui->setupUi(this);
- ui->connectionLog->setFont(TextEditor::TextEditorSettings::instance()->fontSettings().font());
+ ui->connectionLog->setFont(TextEditor::TextEditorSettings::fontSettings().font());
connect(ui->hostLineEdit, SIGNAL(editingFinished()), this, SLOT(hostNameEditingFinished()));
connect(ui->pwdLineEdit, SIGNAL(editingFinished()), this, SLOT(passwordEditingFinished()));
@@ -78,9 +78,8 @@ BlackBerryDeviceConfigurationWidget::BlackBerryDeviceConfigurationWidget(const I
connect(BlackBerryDeviceConnectionManager::instance(), SIGNAL(deviceAboutToConnect(Core::Id)),
this, SLOT(clearConnectionLog(Core::Id)));
- ui->debugToken->addButton(tr("Request"), this, SLOT(requestDebugToken()));
- ui->debugToken->addButton(tr("Upload"), this, SLOT(uploadDebugToken()));
- uploadButton = ui->debugToken->buttonAtIndex(2);
+ connect(ui->requestButton, SIGNAL(clicked()), this, SLOT(requestDebugToken()));
+ connect(ui->uploadButton, SIGNAL(clicked()), this, SLOT(uploadDebugToken()));
QString debugTokenBrowsePath = QnxUtils::dataDirPath();
if (!QFileInfo(debugTokenBrowsePath).exists())
@@ -145,6 +144,12 @@ void BlackBerryDeviceConfigurationWidget::requestDebugToken()
void BlackBerryDeviceConfigurationWidget::uploadDebugToken()
{
+ // check the debug token path before even laucnhing the uploader process
+ if (!QFileInfo(ui->debugToken->fileName().toString()).exists()) {
+ QMessageBox::critical(this, tr("Error"), tr("Invalid debug token path."));
+ return;
+ }
+
progressDialog->show();
uploader->uploadDebugToken(ui->debugToken->path(),
@@ -153,7 +158,7 @@ void BlackBerryDeviceConfigurationWidget::uploadDebugToken()
void BlackBerryDeviceConfigurationWidget::updateUploadButton()
{
- uploadButton->setEnabled(!ui->debugToken->path().isEmpty());
+ ui->uploadButton->setEnabled(!ui->debugToken->path().isEmpty());
}
void BlackBerryDeviceConfigurationWidget::uploadFinished(int status)
@@ -236,6 +241,8 @@ void BlackBerryDeviceConfigurationWidget::initGui()
if (deviceConfiguration()->machineType() == IDevice::Emulator) {
ui->debugToken->setEnabled(false);
+ ui->requestButton->setEnabled(false);
+ ui->uploadButton->setEnabled(false);
ui->debugTokenLabel->setEnabled(false);
}
diff --git a/src/plugins/qnx/blackberrydeviceconfigurationwidget.ui b/src/plugins/qnx/blackberrydeviceconfigurationwidget.ui
index f0b583ce21..b2c905f322 100644
--- a/src/plugins/qnx/blackberrydeviceconfigurationwidget.ui
+++ b/src/plugins/qnx/blackberrydeviceconfigurationwidget.ui
@@ -6,11 +6,26 @@
<rect>
<x>0</x>
<y>0</y>
- <width>334</width>
- <height>208</height>
+ <width>458</width>
+ <height>308</height>
</rect>
</property>
<layout class="QFormLayout" name="formLayout">
+ <property name="fieldGrowthPolicy">
+ <enum>QFormLayout::AllNonFixedFieldsGrow</enum>
+ </property>
+ <property name="leftMargin">
+ <number>0</number>
+ </property>
+ <property name="topMargin">
+ <number>0</number>
+ </property>
+ <property name="rightMargin">
+ <number>0</number>
+ </property>
+ <property name="bottomMargin">
+ <number>0</number>
+ </property>
<item row="0" column="0">
<widget class="QLabel" name="hostNameLabel">
<property name="text">
@@ -69,31 +84,69 @@
<item row="2" column="1">
<widget class="Utils::PathChooser" name="debugToken" native="true"/>
</item>
- <item row="3" column="0">
+ <item row="5" column="0">
<widget class="QLabel" name="keyLabel">
<property name="text">
<string>Private key file:</string>
</property>
+ <property name="buddy">
+ <cstring>keyFileLineEdit</cstring>
+ </property>
</widget>
</item>
- <item row="3" column="1">
+ <item row="5" column="1">
<widget class="Utils::PathChooser" name="keyFileLineEdit" native="true"/>
</item>
- <item row="4" column="0">
+ <item row="6" column="0">
<widget class="QLabel" name="label">
<property name="text">
<string>Connection log:</string>
</property>
+ <property name="buddy">
+ <cstring>connectionLog</cstring>
+ </property>
</widget>
</item>
- <item row="5" column="0" colspan="2">
+ <item row="7" column="0" colspan="2">
<widget class="QPlainTextEdit" name="connectionLog">
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
+ <item row="3" column="1">
+ <layout class="QHBoxLayout" name="horizontalLayout">
+ <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="requestButton">
+ <property name="text">
+ <string>Request</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="uploadButton">
+ <property name="text">
+ <string>Upload</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
</layout>
+ <zorder>debugToken</zorder>
<zorder>keyFileLineEdit</zorder>
<zorder>hostNameLabel</zorder>
<zorder>hostLineEdit</zorder>
@@ -115,6 +168,14 @@
</slots>
</customwidget>
</customwidgets>
+ <tabstops>
+ <tabstop>hostLineEdit</tabstop>
+ <tabstop>pwdLineEdit</tabstop>
+ <tabstop>showPasswordCheckBox</tabstop>
+ <tabstop>requestButton</tabstop>
+ <tabstop>uploadButton</tabstop>
+ <tabstop>connectionLog</tabstop>
+ </tabstops>
<resources/>
<connections/>
</ui>
diff --git a/src/plugins/qnx/blackberrydeviceconfigurationwizard.cpp b/src/plugins/qnx/blackberrydeviceconfigurationwizard.cpp
index 414ef2c93f..73f9e36a35 100644
--- a/src/plugins/qnx/blackberrydeviceconfigurationwizard.cpp
+++ b/src/plugins/qnx/blackberrydeviceconfigurationwizard.cpp
@@ -33,6 +33,7 @@
#include "blackberrydeviceconfigurationwizardpages.h"
#include "qnxconstants.h"
#include "blackberrydeviceconfiguration.h"
+#include "blackberrydeviceconnectionmanager.h"
#include <ssh/sshconnection.h>
@@ -45,11 +46,13 @@ BlackBerryDeviceConfigurationWizard::BlackBerryDeviceConfigurationWizard(QWidget
setWindowTitle(tr("New BlackBerry Device Configuration Setup"));
m_setupPage = new BlackBerryDeviceConfigurationWizardSetupPage(this);
- m_sshKeyPage = new BlackBerryDeviceConfigurationWizardSshKeyPage(this);
+ m_queryPage = new BlackBerryDeviceConfigurationWizardQueryPage(m_holder, this);
+ m_configPage = new BlackBerryDeviceConfigurationWizardConfigPage(m_holder, this);
m_finalPage = new BlackBerryDeviceConfigurationWizardFinalPage(this);
setPage(SetupPageId, m_setupPage);
- setPage(SshKeyPageId, m_sshKeyPage);
+ setPage(QueryPageId, m_queryPage);
+ setPage(ConfigPageId, m_configPage);
setPage(FinalPageId, m_finalPage);
m_finalPage->setCommitPage(true);
}
@@ -60,16 +63,19 @@ ProjectExplorer::IDevice::Ptr BlackBerryDeviceConfigurationWizard::device()
sshParams.options = QSsh::SshIgnoreDefaultProxy;
sshParams.host = m_setupPage->hostName();
sshParams.password = m_setupPage->password();
- sshParams.authenticationType = QSsh::SshConnectionParameters::AuthenticationByKey;
- sshParams.privateKeyFile = m_sshKeyPage->privateKey();
+ sshParams.authenticationType = QSsh::SshConnectionParameters::AuthenticationTypePublicKey;
+ sshParams.privateKeyFile = BlackBerryDeviceConnectionManager::instance()->privateKeyPath();
sshParams.userName = QLatin1String("devuser");
sshParams.timeout = 10;
sshParams.port = 22;
- BlackBerryDeviceConfiguration::Ptr configuration = BlackBerryDeviceConfiguration::create(m_setupPage->deviceName(),
- Core::Id(Constants::QNX_BB_OS_TYPE),
- m_setupPage->machineType());
+ BlackBerryDeviceConfiguration::Ptr configuration = BlackBerryDeviceConfiguration::create(
+ m_configPage->configurationName(),
+ Core::Id(Constants::QNX_BB_OS_TYPE),
+ m_holder.isSimulator
+ ? ProjectExplorer::IDevice::Emulator
+ : ProjectExplorer::IDevice::Hardware);
configuration->setSshParameters(sshParams);
- configuration->setDebugToken(m_setupPage->debugToken());
+ configuration->setDebugToken(m_configPage->debugToken());
return configuration;
}
diff --git a/src/plugins/qnx/blackberrydeviceconfigurationwizard.h b/src/plugins/qnx/blackberrydeviceconfigurationwizard.h
index f5a31d6787..024e9eb855 100644
--- a/src/plugins/qnx/blackberrydeviceconfigurationwizard.h
+++ b/src/plugins/qnx/blackberrydeviceconfigurationwizard.h
@@ -32,6 +32,8 @@
#ifndef QNX_INTERNAL_BLACKBERRYDEVICECONFIGURATIONWIZARD_H
#define QNX_INTERNAL_BLACKBERRYDEVICECONFIGURATIONWIZARD_H
+#include "blackberrydeviceconfigurationwizardpages.h"
+
#include <QWizard>
#include <projectexplorer/devicesupport/idevice.h>
@@ -39,10 +41,6 @@
namespace Qnx {
namespace Internal {
-class BlackBerryDeviceConfigurationWizardSetupPage;
-class BlackBerryDeviceConfigurationWizardSshKeyPage;
-class BlackBerryDeviceConfigurationWizardFinalPage;
-
class BlackBerryDeviceConfigurationWizard : public QWizard
{
Q_OBJECT
@@ -54,13 +52,17 @@ public:
private:
enum PageId {
SetupPageId,
- SshKeyPageId,
+ QueryPageId,
+ ConfigPageId,
FinalPageId
};
BlackBerryDeviceConfigurationWizardSetupPage *m_setupPage;
- BlackBerryDeviceConfigurationWizardSshKeyPage *m_sshKeyPage;
+ BlackBerryDeviceConfigurationWizardQueryPage *m_queryPage;
+ BlackBerryDeviceConfigurationWizardConfigPage *m_configPage;
BlackBerryDeviceConfigurationWizardFinalPage *m_finalPage;
+
+ BlackBerryDeviceConfigurationWizardHolder m_holder;
};
} // namespace Internal
diff --git a/src/plugins/qnx/blackberrydeviceconfigurationwizardconfigpage.ui b/src/plugins/qnx/blackberrydeviceconfigurationwizardconfigpage.ui
new file mode 100644
index 0000000000..e59a39eba4
--- /dev/null
+++ b/src/plugins/qnx/blackberrydeviceconfigurationwizardconfigpage.ui
@@ -0,0 +1,159 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>Qnx::Internal::BlackBerryDeviceConfigurationWizardConfigPage</class>
+ <widget class="QWizardPage" name="Qnx::Internal::BlackBerryDeviceConfigurationWizardConfigPage">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>477</width>
+ <height>348</height>
+ </rect>
+ </property>
+ <property name="windowTitle">
+ <string>Form</string>
+ </property>
+ <layout class="QGridLayout" name="gridLayout">
+ <item row="3" column="0" colspan="3">
+ <widget class="QGroupBox" name="groupBox_2">
+ <property name="title">
+ <string>Debug Token</string>
+ </property>
+ <layout class="QGridLayout" name="gridLayout_3">
+ <item row="2" column="0">
+ <widget class="QLabel" name="label_5">
+ <property name="text">
+ <string>Location:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="2">
+ <widget class="QPushButton" name="generateButton">
+ <property name="text">
+ <string>Generate</string>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="1">
+ <widget class="Utils::PathChooser" name="debugTokenField" native="true">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Expanding" vsizetype="Preferred">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ </widget>
+ </item>
+ <item row="4" column="0" colspan="3">
+ <widget class="QLabel" name="label_3">
+ <property name="font">
+ <font>
+ <italic>true</italic>
+ </font>
+ </property>
+ <property name="text">
+ <string>Debug Token is needed for BlackBerry applications deployment to a device.</string>
+ </property>
+ <property name="wordWrap">
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item row="4" column="0">
+ <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 row="2" column="0" colspan="3">
+ <widget class="QFrame" name="frame">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="frameShape">
+ <enum>QFrame::StyledPanel</enum>
+ </property>
+ <property name="frameShadow">
+ <enum>QFrame::Raised</enum>
+ </property>
+ <layout class="QGridLayout" name="gridLayout_2">
+ <item row="2" column="1">
+ <widget class="QLabel" name="deviceTypeField">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="0">
+ <widget class="QLabel" name="label_6">
+ <property name="text">
+ <string>Type:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="1">
+ <widget class="QLabel" name="deviceHostNameField">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Expanding" vsizetype="Preferred">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="0">
+ <widget class="QLabel" name="label_4">
+ <property name="text">
+ <string>Host name/IP:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="0">
+ <widget class="QLabel" name="label">
+ <property name="text">
+ <string>Configuration name:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="1">
+ <widget class="QLineEdit" name="configurationNameField"/>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ <customwidgets>
+ <customwidget>
+ <class>Utils::PathChooser</class>
+ <extends>QWidget</extends>
+ <header location="global">utils/pathchooser.h</header>
+ <container>1</container>
+ <slots>
+ <signal>editingFinished()</signal>
+ <signal>browsingFinished()</signal>
+ </slots>
+ </customwidget>
+ </customwidgets>
+ <tabstops>
+ <tabstop>generateButton</tabstop>
+ </tabstops>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/src/plugins/qnx/blackberrydeviceconfigurationwizardpages.cpp b/src/plugins/qnx/blackberrydeviceconfigurationwizardpages.cpp
index 3b13e95071..9d0437a93a 100644
--- a/src/plugins/qnx/blackberrydeviceconfigurationwizardpages.cpp
+++ b/src/plugins/qnx/blackberrydeviceconfigurationwizardpages.cpp
@@ -33,9 +33,12 @@
#include "blackberryconfiguration.h"
#include "blackberrydebugtokenrequestdialog.h"
#include "blackberrysshkeysgenerator.h"
+#include "blackberrydeviceinformation.h"
#include "ui_blackberrydeviceconfigurationwizardsetuppage.h"
-#include "ui_blackberrydeviceconfigurationwizardsshkeypage.h"
+#include "ui_blackberrydeviceconfigurationwizardquerypage.h"
+#include "ui_blackberrydeviceconfigurationwizardconfigpage.h"
#include "blackberryconfiguration.h"
+#include "blackberrydeviceconnectionmanager.h"
#include "qnxutils.h"
#include <coreplugin/icore.h>
@@ -47,43 +50,41 @@
#include <QFileDialog>
#include <QFileInfo>
#include <QHostInfo>
+#include <QAbstractItemModel>
using namespace ProjectExplorer;
using namespace Qnx;
using namespace Qnx::Internal;
namespace {
-const char DEVICENAME_FIELD_ID[] = "DeviceName";
+const char DEVICEHOSTNAME_FIELD_ID[] = "DeviceHostName";
+const char DEVICEPASSWORD_FIELD_ID[] = "DevicePassword";
+const char CONFIGURATIONNAME_FIELD_ID[] = "ConfigurationName";
+const char DEBUGTOKENPATH_FIELD_ID[] = "DebugTokenPath";
-QString defaultDeviceHostIp(IDevice::MachineType type)
+enum DeviceListUserRole
{
- return type == IDevice::Hardware ? QLatin1String("169.254.0.1") : QString();
-}
+ ItemKindRole = Qt::UserRole, DeviceNameRole, DeviceIpRole, DeviceTypeRole
+};
}
BlackBerryDeviceConfigurationWizardSetupPage::BlackBerryDeviceConfigurationWizardSetupPage(QWidget *parent)
: QWizardPage(parent)
, m_ui(new Ui::BlackBerryDeviceConfigurationWizardSetupPage)
+ , m_deviceListDetector(new BlackBerryDeviceListDetector(this))
+
{
m_ui->setupUi(this);
setTitle(tr("Connection Details"));
- m_ui->debugToken->setExpectedKind(Utils::PathChooser::File);
- m_ui->debugToken->setPromptDialogFilter(QLatin1String("*.bar"));
-
- QString debugTokenBrowsePath = QnxUtils::dataDirPath();
- if (!QFileInfo(debugTokenBrowsePath).exists())
- debugTokenBrowsePath = QDir::homePath();
- m_ui->debugToken->setInitialBrowsePathBackup(debugTokenBrowsePath);
-
- connect(m_ui->deviceName, SIGNAL(textChanged(QString)), this, SIGNAL(completeChanged()));
+ connect(m_ui->deviceListWidget, SIGNAL(itemSelectionChanged()), this, SLOT(onDeviceSelectionChanged()));
+ connect(m_deviceListDetector, SIGNAL(deviceDetected(QString,QString,bool)),
+ this, SLOT(onDeviceDetected(QString,QString,bool)));
+ connect(m_deviceListDetector, SIGNAL(finished()), this, SLOT(onDeviceListDetectorFinished()));
connect(m_ui->deviceHostIp, SIGNAL(textChanged(QString)), this, SIGNAL(completeChanged()));
- connect(m_ui->physicalDevice, SIGNAL(toggled(bool)), this, SLOT(handleMachineTypeChanged()));
- connect(m_ui->physicalDevice, SIGNAL(toggled(bool)), this, SIGNAL(completeChanged()));
- connect(m_ui->debugToken, SIGNAL(changed(QString)), this, SIGNAL(completeChanged()));
- connect(m_ui->requestButton, SIGNAL(clicked()), this, SLOT(requestDebugToken()));
- registerField(QLatin1String(DEVICENAME_FIELD_ID), m_ui->deviceName);
+ registerField(QLatin1String(DEVICEHOSTNAME_FIELD_ID), m_ui->deviceHostIp);
+ registerField(QLatin1String(DEVICEPASSWORD_FIELD_ID), m_ui->password);
}
BlackBerryDeviceConfigurationWizardSetupPage::~BlackBerryDeviceConfigurationWizardSetupPage()
@@ -94,208 +95,333 @@ BlackBerryDeviceConfigurationWizardSetupPage::~BlackBerryDeviceConfigurationWiza
void BlackBerryDeviceConfigurationWizardSetupPage::initializePage()
{
- m_ui->deviceName->setText(tr("BlackBerry Device"));
- m_ui->password->setText(QString());
- m_ui->physicalDevice->setChecked(true);
- m_ui->deviceHostIp->setText(defaultDeviceHostIp(machineType()));
+ m_ui->password->clear();
+ refreshDeviceList();
}
-bool BlackBerryDeviceConfigurationWizardSetupPage::isComplete() const
+void BlackBerryDeviceConfigurationWizardSetupPage::refreshDeviceList()
{
- bool debugTokenComplete = m_ui->simulator->isChecked()
- || (m_ui->physicalDevice->isChecked() && !m_ui->debugToken->fileName().isEmpty()
- && QFileInfo(m_ui->debugToken->fileName().toString()).exists());
+ m_ui->deviceListWidget->clear();
+
+ QListWidgetItem *manual = createDeviceListItem(tr("Specify device manually"), SpecifyManually);
+ m_ui->deviceListWidget->addItem(manual);
+ manual->setSelected(true);
- return !m_ui->deviceHostIp->text().isEmpty() && !m_ui->deviceHostIp->text().isEmpty()
- && debugTokenComplete;
+ QListWidgetItem *pleaseWait =
+ createDeviceListItem(tr("Auto-detecting devices - please wait..."), PleaseWait);
+ m_ui->deviceListWidget->addItem(pleaseWait);
+
+ m_deviceListDetector->detectDeviceList();
}
-QString BlackBerryDeviceConfigurationWizardSetupPage::deviceName() const
+void BlackBerryDeviceConfigurationWizardSetupPage::onDeviceListDetectorFinished()
{
- return m_ui->deviceName->text();
+ QListWidgetItem *pleaseWait = findDeviceListItem(PleaseWait);
+ if (pleaseWait) {
+ m_ui->deviceListWidget->removeItemWidget(pleaseWait);
+ delete pleaseWait;
+ }
+
+ if (!findDeviceListItem(Autodetected)) {
+ QListWidgetItem *note = createDeviceListItem(tr("No device has been auto-detected."), Note);
+ note->setToolTip(tr("Device auto-detection is available in BB NDK 10.2. "
+ "Make sure that your device is in Development Mode."));
+ m_ui->deviceListWidget->addItem(note);
+ }
}
-QString BlackBerryDeviceConfigurationWizardSetupPage::hostName() const
+void BlackBerryDeviceConfigurationWizardSetupPage::onDeviceDetected(
+ const QString &deviceName, const QString &hostName, bool isSimulator)
{
- return m_ui->deviceHostIp->text();
+ QString displayName(deviceName);
+ if (displayName != hostName)
+ displayName.append(QLatin1String(" (")).append(hostName).append(QLatin1String(")"));
+
+ QListWidgetItem *device = createDeviceListItem(displayName, Autodetected);
+ device->setData(DeviceNameRole, displayName);
+ device->setData(DeviceIpRole, hostName);
+ device->setData(DeviceTypeRole, isSimulator);
+ QListWidgetItem *pleaseWait = findDeviceListItem(PleaseWait);
+ int row = pleaseWait ? m_ui->deviceListWidget->row(pleaseWait) : m_ui->deviceListWidget->count();
+ m_ui->deviceListWidget->insertItem(row, device);
}
-QString BlackBerryDeviceConfigurationWizardSetupPage::password() const
+void BlackBerryDeviceConfigurationWizardSetupPage::onDeviceSelectionChanged()
{
- return m_ui->password->text();
+ QList<QListWidgetItem *> selectedItems = m_ui->deviceListWidget->selectedItems();
+ const QListWidgetItem *selected = selectedItems.count() == 1 ? selectedItems[0] : 0;
+ const ItemKind itemKind = selected ? selected->data(ItemKindRole).value<ItemKind>() : Note;
+ switch (itemKind) {
+ case SpecifyManually:
+ m_ui->deviceHostIp->setEnabled(true);
+ m_ui->deviceHostIp->setText(QLatin1String("169.254.0.1"));
+ m_ui->password->setEnabled(true);
+ m_ui->deviceHostIp->selectAll();
+ m_ui->deviceHostIp->setFocus();
+ break;
+ case Autodetected:
+ m_ui->deviceHostIp->setEnabled(false);
+ m_ui->deviceHostIp->setText(selected->data(DeviceIpRole).toString());
+ m_ui->password->setEnabled(true);
+ m_ui->password->setFocus();
+ break;
+ case PleaseWait:
+ case Note:
+ m_ui->deviceHostIp->setEnabled(false);
+ m_ui->deviceHostIp->clear();
+ m_ui->password->setEnabled(false);
+ break;
+ }
}
-QString BlackBerryDeviceConfigurationWizardSetupPage::debugToken() const
+QListWidgetItem *BlackBerryDeviceConfigurationWizardSetupPage::createDeviceListItem(
+ const QString &displayName, ItemKind itemKind) const
{
- return m_ui->debugToken->fileName().toString();
+ QListWidgetItem *item = new QListWidgetItem(displayName);
+ if (itemKind == PleaseWait || itemKind == Note) {
+ item->setFlags(item->flags() & ~Qt::ItemIsSelectable);
+ QFont font = item->font();
+ font.setItalic(true);
+ item->setFont(font);
+ }
+ item->setData(ItemKindRole, QVariant::fromValue(itemKind));
+ return item;
}
-IDevice::MachineType BlackBerryDeviceConfigurationWizardSetupPage::machineType() const
+QListWidgetItem *BlackBerryDeviceConfigurationWizardSetupPage::findDeviceListItem(ItemKind itemKind) const
{
- return m_ui->physicalDevice->isChecked() ? IDevice::Hardware : IDevice::Emulator;
+ int count = m_ui->deviceListWidget->count();
+ for (int i = 0; i < count; ++i) {
+ QListWidgetItem *item = m_ui->deviceListWidget->item(i);
+ if (item->data(ItemKindRole).value<ItemKind>() == itemKind) {
+ return item;
+ }
+ }
+ return 0;
}
-void BlackBerryDeviceConfigurationWizardSetupPage::handleMachineTypeChanged()
+bool BlackBerryDeviceConfigurationWizardSetupPage::isComplete() const
{
- if (m_ui->deviceHostIp->text().isEmpty())
- m_ui->deviceHostIp->setText(defaultDeviceHostIp(machineType()));
+ return !m_ui->deviceHostIp->text().isEmpty();
}
-void BlackBerryDeviceConfigurationWizardSetupPage::requestDebugToken()
+QString BlackBerryDeviceConfigurationWizardSetupPage::hostName() const
{
- BlackBerryDebugTokenRequestDialog dialog;
-
- if (!m_ui->deviceHostIp->text().isEmpty() && !m_ui->password->text().isEmpty())
- dialog.setTargetDetails(m_ui->deviceHostIp->text(), m_ui->password->text());
-
- const int result = dialog.exec();
-
- if (result != QDialog::Accepted)
- return;
+ return m_ui->deviceHostIp->text();
+}
- m_ui->debugToken->setPath(dialog.debugToken());
+QString BlackBerryDeviceConfigurationWizardSetupPage::password() const
+{
+ return m_ui->password->text();
}
// ----------------------------------------------------------------------------
-
-BlackBerryDeviceConfigurationWizardSshKeyPage::BlackBerryDeviceConfigurationWizardSshKeyPage(QWidget *parent)
+BlackBerryDeviceConfigurationWizardQueryPage::BlackBerryDeviceConfigurationWizardQueryPage
+ (BlackBerryDeviceConfigurationWizardHolder &holder, QWidget *parent)
: QWizardPage(parent)
- , m_ui(new Ui::BlackBerryDeviceConfigurationWizardSshKeyPage)
- , m_sshKeysGenerator(new BlackBerrySshKeysGenerator(this))
+ , m_ui(new Ui::BlackBerryDeviceConfigurationWizardQueryPage)
+ , m_holder(holder)
+ , m_deviceInformation(new BlackBerryDeviceInformation(this))
{
m_ui->setupUi(this);
+ setTitle(tr("Query Device Information"));
+ m_ui->progressBar->setMaximum(Done);
- m_ui->privateKey->setExpectedKind(Utils::PathChooser::File);
- m_ui->progressBar->hide();
+ connect(m_deviceInformation,SIGNAL(finished(int)),this,SLOT(processQueryFinished(int)));
+}
+
+BlackBerryDeviceConfigurationWizardQueryPage::~BlackBerryDeviceConfigurationWizardQueryPage()
+{
+ delete m_ui;
+ m_ui = 0;
+}
- QString initialBrowsePath = QnxUtils::dataDirPath();
- if (!QFileInfo(initialBrowsePath).exists())
- initialBrowsePath = QDir::homePath();
- m_ui->privateKey->setInitialBrowsePathBackup(initialBrowsePath);
+void BlackBerryDeviceConfigurationWizardQueryPage::initializePage()
+{
+ m_holder.deviceInfoRetrieved = false;
- setTitle(tr("SSH Key Setup"));
- setSubTitle(tr("Please select an existing <b>4096</b>-bit key or click <b>Generate</b> to create a new one."));
+ setState(Querying, tr("Querying device information. Please wait..."));
- connect(m_ui->privateKey, SIGNAL(changed(QString)), this, SLOT(findMatchingPublicKey(QString)));
- connect(m_ui->privateKey, SIGNAL(changed(QString)), this, SIGNAL(completeChanged()));
- connect(m_ui->generate, SIGNAL(clicked()), this, SLOT(generateSshKeys()));
- connect(m_sshKeysGenerator, SIGNAL(sshKeysGenerationFinished(bool)), this, SLOT(processSshKeys(bool)));
+ m_deviceInformation->setDeviceTarget(
+ field(QLatin1String(DEVICEHOSTNAME_FIELD_ID)).toString(),
+ field(QLatin1String(DEVICEPASSWORD_FIELD_ID)).toString());
}
-BlackBerryDeviceConfigurationWizardSshKeyPage::~BlackBerryDeviceConfigurationWizardSshKeyPage()
+void BlackBerryDeviceConfigurationWizardQueryPage::processQueryFinished(int status)
{
- // Make sure the m_sshKeysGenerator thread is terminated before it's destroyed
- m_sshKeysGenerator->terminate();
- m_sshKeysGenerator->wait();
-
- delete m_ui;
- m_ui = 0;
+ m_holder.deviceInfoRetrieved = status == BlackBerryDeviceInformation::Success;
+ m_holder.devicePin = m_deviceInformation->devicePin();
+ m_holder.scmBundle = m_deviceInformation->scmBundle();
+ m_holder.deviceName = m_deviceInformation->hostName();
+ if (m_holder.deviceName.isEmpty())
+ m_holder.deviceName = QLatin1String("BlackBerry at ")
+ + field(QLatin1String(DEVICEHOSTNAME_FIELD_ID)).toString();
+ m_holder.debugTokenAuthor = m_deviceInformation->debugTokenAuthor();
+ m_holder.debugTokenValid = m_deviceInformation->debugTokenValid();
+ m_holder.isSimulator = m_deviceInformation->isSimulator();
+ m_holder.isProductionDevice = m_deviceInformation->isProductionDevice();
+
+ if (m_holder.deviceInfoRetrieved)
+ checkAndGenerateSSHKeys();
+ else
+ setState(Done, tr("Cannot connect to the device. "
+ "Check if the device is in development mode and has matching host name and password."));
}
-void BlackBerryDeviceConfigurationWizardSshKeyPage::initializePage()
+void BlackBerryDeviceConfigurationWizardQueryPage::checkAndGenerateSSHKeys()
{
+ if (! BlackBerryDeviceConnectionManager::instance()->hasValidSSHKeys()) {
+ setState(GeneratingSshKey, tr("Generating SSH keys. Please wait..."));
+
+ BlackBerrySshKeysGenerator *sshKeysGenerator = new BlackBerrySshKeysGenerator();
+ connect(sshKeysGenerator, SIGNAL(sshKeysGenerationFailed(QString)),
+ this, SLOT(sshKeysGenerationFailed(QString)), Qt::QueuedConnection);
+ connect(sshKeysGenerator, SIGNAL(sshKeysGenerationFinished(QByteArray,QByteArray)),
+ this, SLOT(processSshKeys(QByteArray,QByteArray)), Qt::QueuedConnection);
+ sshKeysGenerator->start();
+ } else
+ queryDone();
}
-bool BlackBerryDeviceConfigurationWizardSshKeyPage::isComplete() const
+void BlackBerryDeviceConfigurationWizardQueryPage::sshKeysGenerationFailed(const QString &error)
{
- QFileInfo privateKeyFi(m_ui->privateKey->fileName().toString());
- QFileInfo publicKeyFi(m_ui->publicKey->text());
+ // this slot can be called asynchronously - processing it only in GeneratingSshKey state
+ if (m_state != GeneratingSshKey)
+ return;
- return privateKeyFi.exists() && publicKeyFi.exists();
+ QString message = tr("Failed generating SSH key needed for securing connection to a device. Error: ");
+ message.append(error);
+ setState(Done, message);
}
-QString BlackBerryDeviceConfigurationWizardSshKeyPage::privateKey() const
+void BlackBerryDeviceConfigurationWizardQueryPage::processSshKeys(const QByteArray &privateKey,
+ const QByteArray &publicKey)
{
- return m_ui->privateKey->fileName().toString();
+ // this slot can be called asynchronously - processing it only in GeneratingSshKey state
+ if (m_state != GeneratingSshKey)
+ return;
+
+ // condition prevents overriding already generated SSH keys
+ // this may happens when an user enter the QueryPage several times before
+ // the first SSH keys are generated i.e. when multiple calls of checkAndGenerateSSHKeys()
+ // before processSshKeys() is called, multiple processSshKeys() calls are triggered later.
+ // only the first one is allowed to write the SSH keys.
+ if (! BlackBerryDeviceConnectionManager::instance()->hasValidSSHKeys()) {
+ QString error;
+ if (!BlackBerryDeviceConnectionManager::instance()->setSSHKeys(privateKey, publicKey, &error)) {
+ QString message = tr("Failed saving SSH key needed for securing connection to a device. Error: ");
+ message.append(error);
+ setState(Done, message);
+ return;
+ }
+ }
+
+ queryDone();
}
-QString BlackBerryDeviceConfigurationWizardSshKeyPage::publicKey() const
+void BlackBerryDeviceConfigurationWizardQueryPage::queryDone()
{
- return m_ui->publicKey->text();
+ setState(Done, tr("Device information retrieved successfully."));
}
-void BlackBerryDeviceConfigurationWizardSshKeyPage::findMatchingPublicKey(const QString &privateKeyPath)
+void BlackBerryDeviceConfigurationWizardQueryPage::setState(QueryState state, const QString &message)
{
- const QString candidate = privateKeyPath + QLatin1String(".pub");
- if (QFileInfo(candidate).exists())
- m_ui->publicKey->setText(QDir::toNativeSeparators(candidate));
- else
- m_ui->publicKey->clear();
+ m_state = state;
+ m_ui->statusLabel->setText(message);
+ m_ui->progressBar->setVisible(state != Done);
+ m_ui->progressBar->setValue(state);
+ emit completeChanged();
+
+ if (isComplete())
+ if (wizard()->currentPage() == this)
+ wizard()->next();
}
-void BlackBerryDeviceConfigurationWizardSshKeyPage::processSshKeys(bool success)
+bool BlackBerryDeviceConfigurationWizardQueryPage::isComplete() const
{
- setBusy(false);
+ return m_state == Done
+ && m_holder.deviceInfoRetrieved
+ && BlackBerryDeviceConnectionManager::instance()->hasValidSSHKeys();
+}
- if (!success) {
- QMessageBox::critical(this, tr("Key Generation Failed"), m_sshKeysGenerator->error());
- return;
- }
+// ----------------------------------------------------------------------------
+
+BlackBerryDeviceConfigurationWizardConfigPage::BlackBerryDeviceConfigurationWizardConfigPage
+ (BlackBerryDeviceConfigurationWizardHolder &holder, QWidget *parent)
+ : QWizardPage(parent)
+ , m_ui(new Ui::BlackBerryDeviceConfigurationWizardConfigPage)
+ , m_holder(holder)
+{
+ m_ui->setupUi(this);
+ setTitle(tr("Configuration"));
- const QString publicKeyPath = m_generatedPrivateKeyPath + QLatin1String(".pub");
+ m_ui->debugTokenField->setExpectedKind(Utils::PathChooser::File);
+ m_ui->debugTokenField->setPromptDialogFilter(QLatin1String("*.bar"));
- if (!saveKeys(m_generatedPrivateKeyPath, publicKeyPath)) // saveKeys(..) will show an error message if necessary
- return;
+ QString debugTokenBrowsePath = QnxUtils::dataDirPath();
+ if (!QFileInfo(debugTokenBrowsePath).exists())
+ debugTokenBrowsePath = QDir::homePath();
+ m_ui->debugTokenField->setInitialBrowsePathBackup(debugTokenBrowsePath);
- m_ui->privateKey->setFileName(Utils::FileName::fromString(m_generatedPrivateKeyPath));
- m_ui->publicKey->setText(QDir::toNativeSeparators(publicKeyPath));
+ connect(m_ui->configurationNameField, SIGNAL(textChanged(QString)), this, SIGNAL(completeChanged()));
+ connect(m_ui->debugTokenField, SIGNAL(changed(QString)), this, SIGNAL(completeChanged()));
+ connect(m_ui->generateButton, SIGNAL(clicked()), this, SLOT(generateDebugToken()));
- emit completeChanged();
+ registerField(QLatin1String(CONFIGURATIONNAME_FIELD_ID), m_ui->configurationNameField);
+ registerField(QLatin1String(DEBUGTOKENPATH_FIELD_ID), m_ui->debugTokenField);
}
-bool BlackBerryDeviceConfigurationWizardSshKeyPage::saveKeys(const QString &privateKeyFile, const QString &publicKeyFile)
+BlackBerryDeviceConfigurationWizardConfigPage::~BlackBerryDeviceConfigurationWizardConfigPage()
{
- Utils::FileSaver privSaver(privateKeyFile);
- privSaver.write(m_sshKeysGenerator->keyGenerator()->privateKey());
- if (!privSaver.finalize(this))
- return false; // finalize shows an error message if necessary
- QFile::setPermissions(privateKeyFile, QFile::ReadOwner | QFile::WriteOwner);
-
- Utils::FileSaver pubSaver(publicKeyFile);
+ delete m_ui;
+ m_ui = 0;
+}
- // blackberry-connect requires an @ character to be included in the RSA comment
- const QString atHost = QLatin1Char('@') + QHostInfo::localHostName();
- QByteArray pubKeyContent = m_sshKeysGenerator->keyGenerator()->publicKey();
- pubKeyContent.append(atHost.toLocal8Bit());
+void BlackBerryDeviceConfigurationWizardConfigPage::initializePage()
+{
+ QString deviceHostName = field(QLatin1String(DEVICEHOSTNAME_FIELD_ID)).toString();
+ m_ui->configurationNameField->setText(m_holder.deviceName);
+ m_ui->deviceHostNameField->setText(deviceHostName);
+ m_ui->deviceTypeField->setText(QLatin1String (m_holder.isSimulator ? "Simulator" : "Device"));
+ m_ui->debugTokenField->setEnabled(!m_holder.isSimulator);
+ m_ui->generateButton->setEnabled(!m_holder.isSimulator);
+}
- pubSaver.write(pubKeyContent);
- if (!pubSaver.finalize(this))
- return false;
+bool BlackBerryDeviceConfigurationWizardConfigPage::isComplete() const
+{
+ bool configurationNameComplete = !m_ui->configurationNameField->text().isEmpty();
+ Utils::FileName fileName = m_ui->debugTokenField->fileName();
+ bool debugTokenComplete = m_holder.isSimulator || !m_holder.isProductionDevice
+ || (!fileName.isEmpty() && QFileInfo(fileName.toString()).exists());
- return true;
+ return configurationNameComplete && debugTokenComplete;
}
-void BlackBerryDeviceConfigurationWizardSshKeyPage::generateSshKeys()
+void BlackBerryDeviceConfigurationWizardConfigPage::generateDebugToken()
{
- QString lookInDir = QnxUtils::dataDirPath();
- if (!QFileInfo(lookInDir).exists())
- lookInDir = QDir::homePath();
+ BlackBerryDebugTokenRequestDialog dialog;
+ dialog.setDevicePin(m_holder.devicePin);
- QString privateKeyPath = QFileDialog::getSaveFileName(this, tr("Choose Private Key File Name"), lookInDir);
- if (privateKeyPath.isEmpty())
+ const int result = dialog.exec();
+
+ if (result != QDialog::Accepted)
return;
- m_generatedPrivateKeyPath = privateKeyPath;
+ m_ui->debugTokenField->setPath(dialog.debugToken());
+}
- setBusy(true);
- m_sshKeysGenerator->start();
+QString BlackBerryDeviceConfigurationWizardConfigPage::configurationName() const
+{
+ return m_ui->configurationNameField->text();
}
-void BlackBerryDeviceConfigurationWizardSshKeyPage::setBusy(bool busy)
+QString BlackBerryDeviceConfigurationWizardConfigPage::debugToken() const
{
- m_ui->privateKey->setEnabled(!busy);
- m_ui->publicKey->setEnabled(!busy);
- m_ui->generate->setEnabled(!busy);
- m_ui->progressBar->setVisible(busy);
-
- wizard()->button(QWizard::BackButton)->setEnabled(!busy);
- wizard()->button(QWizard::NextButton)->setEnabled(!busy);
- wizard()->button(QWizard::FinishButton)->setEnabled(!busy);
- wizard()->button(QWizard::CancelButton)->setEnabled(!busy);
+ return m_ui->debugTokenField->fileName().toString();
}
-// ----------------------------------------------------------------------------
+// ----------------------------------------------------------------------------
BlackBerryDeviceConfigurationWizardFinalPage::BlackBerryDeviceConfigurationWizardFinalPage(QWidget *parent)
: QWizardPage(parent)
@@ -303,9 +429,6 @@ BlackBerryDeviceConfigurationWizardFinalPage::BlackBerryDeviceConfigurationWizar
setTitle(tr("Setup Finished"));
QVBoxLayout *layout = new QVBoxLayout(this);
- QLabel *label = new QLabel(tr("The new device configuration will now be created."), this);
+ QLabel *label = new QLabel(tr("The new device configuration will be created now."), this);
layout->addWidget(label);
}
-
-
-
diff --git a/src/plugins/qnx/blackberrydeviceconfigurationwizardpages.h b/src/plugins/qnx/blackberrydeviceconfigurationwizardpages.h
index c9354cd30d..42e3946fb6 100644
--- a/src/plugins/qnx/blackberrydeviceconfigurationwizardpages.h
+++ b/src/plugins/qnx/blackberrydeviceconfigurationwizardpages.h
@@ -32,9 +32,12 @@
#ifndef QNX_INTERNAL_BLACKBERRYDEVICECONFIGURATIONWIZARDPAGES_H
#define QNX_INTERNAL_BLACKBERRYDEVICECONFIGURATIONWIZARDPAGES_H
+#include "blackberrydevicelistdetector.h"
+
#include <projectexplorer/devicesupport/idevice.h>
#include <QWizardPage>
+#include <QListWidgetItem>
namespace QSsh {
class SshKeyGenerator;
@@ -44,60 +47,108 @@ namespace Qnx {
namespace Internal {
namespace Ui {
class BlackBerryDeviceConfigurationWizardSetupPage;
-class BlackBerryDeviceConfigurationWizardSshKeyPage;
+class BlackBerryDeviceConfigurationWizardQueryPage;
+class BlackBerryDeviceConfigurationWizardConfigPage;
}
class BlackBerrySshKeysGenerator;
+class BlackBerryDeviceInformation;
+
+struct BlackBerryDeviceConfigurationWizardHolder {
+ QString devicePin;
+ QString deviceName;
+ QString scmBundle;
+ QString debugTokenAuthor;
+ bool isSimulator;
+ bool debugTokenValid;
+ bool deviceInfoRetrieved;
+ bool isProductionDevice;
+
+ BlackBerryDeviceConfigurationWizardHolder()
+ : isSimulator(false)
+ , debugTokenValid(false)
+ , deviceInfoRetrieved(false)
+ , isProductionDevice(true) {}
+};
class BlackBerryDeviceConfigurationWizardSetupPage : public QWizardPage
{
Q_OBJECT
public:
+ enum ItemKind {
+ SpecifyManually, Autodetected, PleaseWait, Note
+ };
+
explicit BlackBerryDeviceConfigurationWizardSetupPage(QWidget *parent = 0);
~BlackBerryDeviceConfigurationWizardSetupPage();
void initializePage();
bool isComplete() const;
- QString deviceName() const;
QString hostName() const;
QString password() const;
- QString debugToken() const;
- ProjectExplorer::IDevice::MachineType machineType() const;
-
private slots:
- void handleMachineTypeChanged();
- void requestDebugToken();
+ void onDeviceSelectionChanged();
+ void onDeviceDetected(const QString &deviceName, const QString &hostName, bool isSimulator);
+ void onDeviceListDetectorFinished();
private:
+ void refreshDeviceList();
+ QListWidgetItem *createDeviceListItem(const QString &displayName, ItemKind itemKind) const;
+ QListWidgetItem *findDeviceListItem(ItemKind itemKind) const;
+
Ui::BlackBerryDeviceConfigurationWizardSetupPage *m_ui;
+ BlackBerryDeviceListDetector *m_deviceListDetector;
};
-class BlackBerryDeviceConfigurationWizardSshKeyPage : public QWizardPage
+class BlackBerryDeviceConfigurationWizardQueryPage : public QWizardPage
{
Q_OBJECT
+ enum QueryState
+ {
+ Querying = 0, GeneratingSshKey, Done
+ };
+
public:
- explicit BlackBerryDeviceConfigurationWizardSshKeyPage(QWidget *parent = 0);
- ~BlackBerryDeviceConfigurationWizardSshKeyPage();
+ explicit BlackBerryDeviceConfigurationWizardQueryPage(BlackBerryDeviceConfigurationWizardHolder &holder, QWidget *parent = 0);
+ ~BlackBerryDeviceConfigurationWizardQueryPage();
void initializePage();
bool isComplete() const;
- QString privateKey() const;
- QString publicKey() const;
-
private slots:
- void findMatchingPublicKey(const QString &privateKeyPath);
- void processSshKeys(bool success);
- void generateSshKeys();
+ void processQueryFinished(int status);
+ void sshKeysGenerationFailed(const QString &error);
+ void processSshKeys(const QByteArray &privateKey, const QByteArray &publicKey);
private:
- bool saveKeys(const QString &privateKeyFile, const QString &publicKeyFile);
- void setBusy(bool busy);
+ void checkAndGenerateSSHKeys();
+ void queryDone();
+ void setState(QueryState state, const QString &message);
+
+ Ui::BlackBerryDeviceConfigurationWizardQueryPage *m_ui;
+ BlackBerryDeviceConfigurationWizardHolder &m_holder;
+ BlackBerryDeviceInformation *m_deviceInformation;
+ QueryState m_state;
+};
+
+class BlackBerryDeviceConfigurationWizardConfigPage : public QWizardPage
+{
+ Q_OBJECT
+public:
+ explicit BlackBerryDeviceConfigurationWizardConfigPage(BlackBerryDeviceConfigurationWizardHolder &holder, QWidget *parent = 0);
+ ~BlackBerryDeviceConfigurationWizardConfigPage();
+
+ void initializePage();
+ bool isComplete() const;
- Ui::BlackBerryDeviceConfigurationWizardSshKeyPage *m_ui;
+ QString configurationName() const;
+ QString debugToken() const;
+private slots:
+ void generateDebugToken();
- BlackBerrySshKeysGenerator *m_sshKeysGenerator;
- QString m_generatedPrivateKeyPath;
+private:
+ Ui::BlackBerryDeviceConfigurationWizardConfigPage *m_ui;
+ BlackBerryDeviceConfigurationWizardHolder &m_holder;
};
class BlackBerryDeviceConfigurationWizardFinalPage : public QWizardPage
@@ -110,4 +161,6 @@ public:
} // namespace Internal
} // namespace Qnx
+Q_DECLARE_METATYPE(Qnx::Internal::BlackBerryDeviceConfigurationWizardSetupPage::ItemKind)
+
#endif // QNX_INTERNAL_BLACKBERRYDEVICECONFIGURATIONWIZARDPAGES_H
diff --git a/src/plugins/qnx/blackberrydeviceconfigurationwizardquerypage.ui b/src/plugins/qnx/blackberrydeviceconfigurationwizardquerypage.ui
new file mode 100644
index 0000000000..5286649f9d
--- /dev/null
+++ b/src/plugins/qnx/blackberrydeviceconfigurationwizardquerypage.ui
@@ -0,0 +1,47 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>Qnx::Internal::BlackBerryDeviceConfigurationWizardQueryPage</class>
+ <widget class="QWizardPage" name="Qnx::Internal::BlackBerryDeviceConfigurationWizardQueryPage">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>381</width>
+ <height>142</height>
+ </rect>
+ </property>
+ <property name="windowTitle">
+ <string>Form</string>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout">
+ <item>
+ <widget class="QLabel" name="statusLabel">
+ <property name="text">
+ <string/>
+ </property>
+ <property name="wordWrap">
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QProgressBar" name="progressBar"/>
+ </item>
+ <item>
+ <spacer name="verticalSpacer">
+ <property name="orientation">
+ <enum>Qt::Vertical</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>20</width>
+ <height>58</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/src/plugins/qnx/blackberrydeviceconfigurationwizardsetuppage.ui b/src/plugins/qnx/blackberrydeviceconfigurationwizardsetuppage.ui
index 4437a2d7d8..b4a6b27a59 100644
--- a/src/plugins/qnx/blackberrydeviceconfigurationwizardsetuppage.ui
+++ b/src/plugins/qnx/blackberrydeviceconfigurationwizardsetuppage.ui
@@ -6,123 +6,40 @@
<rect>
<x>0</x>
<y>0</y>
- <width>546</width>
- <height>170</height>
+ <width>484</width>
+ <height>182</height>
</rect>
</property>
<property name="windowTitle">
<string>WizardPage</string>
</property>
- <layout class="QFormLayout" name="formLayout">
- <item row="0" column="0">
- <widget class="QLabel" name="label">
- <property name="text">
- <string>The name to identify this configuration:</string>
- </property>
- </widget>
+ <layout class="QVBoxLayout" name="verticalLayout">
+ <item>
+ <widget class="QListWidget" name="deviceListWidget"/>
</item>
- <item row="0" column="1">
- <widget class="QLineEdit" name="deviceName"/>
- </item>
- <item row="1" column="0">
- <widget class="QLabel" name="label_4">
- <property name="text">
- <string>Device type:</string>
- </property>
- </widget>
- </item>
- <item row="1" column="1">
- <layout class="QHBoxLayout" name="horizontalLayout_3">
- <item>
- <widget class="QRadioButton" name="physicalDevice">
- <property name="text">
- <string>Physical device</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QRadioButton" name="simulator">
- <property name="text">
- <string>Simulator</string>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item row="2" 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="2" column="1">
- <layout class="QHBoxLayout" name="horizontalLayout">
- <item>
- <widget class="QLineEdit" name="deviceHostIp"/>
- </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 row="3" column="0">
- <widget class="QLabel" name="label_3">
- <property name="text">
- <string>Device password:</string>
- </property>
- </widget>
- </item>
- <item row="3" column="1">
- <layout class="QHBoxLayout" name="horizontalLayout_2">
- <item>
+ <item>
+ <layout class="QGridLayout" name="gridLayout">
+ <item row="1" column="1">
<widget class="QLineEdit" name="password">
<property name="echoMode">
<enum>QLineEdit::Password</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>
+ <item row="1" column="0">
+ <widget class="QLabel" name="label_3">
+ <property name="text">
+ <string>Device password:</string>
</property>
- </spacer>
+ </widget>
</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">
- <layout class="QHBoxLayout" name="horizontalLayout_4">
- <item>
- <widget class="Utils::PathChooser" name="debugToken" native="true"/>
+ <item row="0" column="1">
+ <widget class="QLineEdit" name="deviceHostIp"/>
</item>
- <item>
- <widget class="QPushButton" name="requestButton">
+ <item row="0" column="0">
+ <widget class="QLabel" name="label_2">
<property name="text">
- <string>Request</string>
+ <string>Device host name or IP address:</string>
</property>
</widget>
</item>
@@ -130,35 +47,6 @@
</item>
</layout>
</widget>
- <customwidgets>
- <customwidget>
- <class>Utils::PathChooser</class>
- <extends>QWidget</extends>
- <header location="global">utils/pathchooser.h</header>
- <container>1</container>
- <slots>
- <signal>editingFinished()</signal>
- <signal>browsingFinished()</signal>
- </slots>
- </customwidget>
- </customwidgets>
<resources/>
- <connections>
- <connection>
- <sender>physicalDevice</sender>
- <signal>toggled(bool)</signal>
- <receiver>debugToken</receiver>
- <slot>setEnabled(bool)</slot>
- <hints>
- <hint type="sourcelabel">
- <x>271</x>
- <y>98</y>
- </hint>
- <hint type="destinationlabel">
- <x>226</x>
- <y>124</y>
- </hint>
- </hints>
- </connection>
- </connections>
+ <connections/>
</ui>
diff --git a/src/plugins/qnx/blackberrydeviceconfigurationwizardsshkeypage.ui b/src/plugins/qnx/blackberrydeviceconfigurationwizardsshkeypage.ui
deleted file mode 100644
index 3eb327e46f..0000000000
--- a/src/plugins/qnx/blackberrydeviceconfigurationwizardsshkeypage.ui
+++ /dev/null
@@ -1,78 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<ui version="4.0">
- <class>Qnx::Internal::BlackBerryDeviceConfigurationWizardSshKeyPage</class>
- <widget class="QWizardPage" name="Qnx::Internal::BlackBerryDeviceConfigurationWizardSshKeyPage">
- <property name="geometry">
- <rect>
- <x>0</x>
- <y>0</y>
- <width>413</width>
- <height>92</height>
- </rect>
- </property>
- <property name="windowTitle">
- <string>WizardPage</string>
- </property>
- <layout class="QFormLayout" name="formLayout">
- <item row="0" column="0">
- <widget class="QLabel" name="label">
- <property name="text">
- <string>Private key file:</string>
- </property>
- </widget>
- </item>
- <item row="0" column="1">
- <layout class="QHBoxLayout" name="horizontalLayout">
- <item>
- <widget class="Utils::PathChooser" name="privateKey" native="true"/>
- </item>
- <item>
- <widget class="QPushButton" name="generate">
- <property name="text">
- <string>Generate...</string>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item row="1" column="0">
- <widget class="QLabel" name="label_2">
- <property name="text">
- <string>Public key file:</string>
- </property>
- </widget>
- </item>
- <item row="1" column="1">
- <widget class="QLineEdit" name="publicKey">
- <property name="readOnly">
- <bool>true</bool>
- </property>
- </widget>
- </item>
- <item row="3" column="1">
- <widget class="QProgressBar" name="progressBar">
- <property name="maximum">
- <number>0</number>
- </property>
- <property name="value">
- <number>-1</number>
- </property>
- </widget>
- </item>
- </layout>
- </widget>
- <customwidgets>
- <customwidget>
- <class>Utils::PathChooser</class>
- <extends>QWidget</extends>
- <header location="global">utils/pathchooser.h</header>
- <container>1</container>
- <slots>
- <signal>editingFinished()</signal>
- <signal>browsingFinished()</signal>
- </slots>
- </customwidget>
- </customwidgets>
- <resources/>
- <connections/>
-</ui>
diff --git a/src/plugins/qnx/blackberrydeviceconnection.cpp b/src/plugins/qnx/blackberrydeviceconnection.cpp
index 5db6264125..97ccd975f6 100644
--- a/src/plugins/qnx/blackberrydeviceconnection.cpp
+++ b/src/plugins/qnx/blackberrydeviceconnection.cpp
@@ -32,6 +32,7 @@
#include "blackberrydeviceconnection.h"
#include "blackberryconfiguration.h"
+#include "blackberryconfigurationmanager.h"
#include "qnxutils.h"
#include <projectexplorer/devicesupport/devicemanager.h>
@@ -61,7 +62,11 @@ BlackBerryDeviceConnection::BlackBerryDeviceConnection() :
void BlackBerryDeviceConnection::connectDevice(const ProjectExplorer::IDevice::ConstPtr &device)
{
Utils::Environment env = Utils::Environment::systemEnvironment();
- QnxUtils::prependQnxMapToEnvironment(BlackBerryConfiguration::instance().qnxEnv(), env);
+
+ QMultiMap<QString, QString> qnxEnv = BlackBerryConfigurationManager::instance().defaultQnxEnv();
+ if (!qnxEnv.isEmpty())
+ QnxUtils::prependQnxMapToEnvironment(qnxEnv, env);
+
m_process->setEnvironment(env.toStringList());
m_host = device->sshParameters().host;
diff --git a/src/plugins/qnx/blackberrydeviceconnectionmanager.cpp b/src/plugins/qnx/blackberrydeviceconnectionmanager.cpp
index d351d660db..339d9e834f 100644
--- a/src/plugins/qnx/blackberrydeviceconnectionmanager.cpp
+++ b/src/plugins/qnx/blackberrydeviceconnectionmanager.cpp
@@ -33,12 +33,19 @@
#include "blackberrydeviceconfiguration.h"
#include "blackberrydeviceconnection.h"
+#include "blackberryconfigurationmanager.h"
#include "qnxconstants.h"
+#include <coreplugin/icore.h>
#include <projectexplorer/devicesupport/devicemanager.h>
#include <ssh/sshconnection.h>
+#include <ssh/sshkeygenerator.h>
+#include <utils/fileutils.h>
#include <utils/qtcassert.h>
+#include <QFileInfo>
+#include <QDir>
+
using namespace Qnx;
using namespace Qnx::Internal;
@@ -59,7 +66,7 @@ void BlackBerryDeviceConnectionManager::initialize()
ProjectExplorer::DeviceManager *deviceManager = ProjectExplorer::DeviceManager::instance();
connect(deviceManager, SIGNAL(deviceAdded(Core::Id)), this, SLOT(connectDevice(Core::Id)));
connect(deviceManager, SIGNAL(deviceRemoved(Core::Id)), this, SLOT(disconnectDevice(Core::Id)));
- connect(deviceManager, SIGNAL(deviceListChanged()), this, SLOT(handleDeviceListChanged()));
+ connect(deviceManager, SIGNAL(deviceListReplaced()), this, SLOT(handleDeviceListChanged()));
}
void BlackBerryDeviceConnectionManager::killAllConnections()
@@ -104,6 +111,16 @@ void BlackBerryDeviceConnectionManager::connectDevice(Core::Id deviceId)
if (device.isNull())
return;
+ // BlackBerry Device connection needs the Qnx environments to be set
+ // in order to find the Connect.jar package.
+ // Let's delay the device connections at startup till the Qnx settings are loaded.
+ if (BlackBerryConfigurationManager::instance().configurations().isEmpty()) {
+ m_pendingDeviceConnections << device;
+ connect(&BlackBerryConfigurationManager::instance(), SIGNAL(settingsLoaded()),
+ this, SLOT(processPendingDeviceConnections()), Qt::UniqueConnection);
+ return;
+ }
+
connectDevice(device);
}
@@ -164,6 +181,59 @@ void BlackBerryDeviceConnectionManager::disconnectDevice(const ProjectExplorer::
disconnectDevice(device->id());
}
+/*!
+ * @brief Returns default private key path in local settings.
+ * @return the default private key path
+ */
+const QString BlackBerryDeviceConnectionManager::privateKeyPath() const
+{
+ return QFileInfo(Core::ICore::settings()->fileName()).absolutePath() + QLatin1String("/qtcreator/qnx/id_rsa");
+}
+
+/*!
+ * @brief Checks validity of default SSH keys used for connecting to a device.
+ * @return true, if the default SSH keys are valid
+ */
+bool BlackBerryDeviceConnectionManager::hasValidSSHKeys() const
+{
+ const QString privateKey = privateKeyPath();
+ QFileInfo privateKeyFileInfo(privateKey);
+ QFileInfo publicKeyFileInfo(privateKey + QLatin1String(".pub"));
+
+ return privateKeyFileInfo.exists() && privateKeyFileInfo.isReadable()
+ && publicKeyFileInfo.exists() && publicKeyFileInfo.isReadable();
+}
+
+/*!
+ * @brief Stores a new private and public SSH key in local settings.
+ * @param privateKeyContent the private key content
+ * @param publicKeyContent the public key content
+ */
+bool BlackBerryDeviceConnectionManager::setSSHKeys(const QByteArray privateKeyContent,
+ const QByteArray publicKeyContent, QString *error)
+{
+ const QString privateKey = privateKeyPath();
+ const QString publicKey = privateKey + QLatin1String(".pub");
+
+ QFileInfo fileInfo(privateKey);
+ QDir dir = fileInfo.dir();
+ if (!dir.exists())
+ dir.mkpath(QLatin1String("."));
+
+ Utils::FileSaver privSaver(privateKey);
+ privSaver.write(privateKeyContent);
+ if (!privSaver.finalize(error))
+ return false;
+ QFile::setPermissions(privateKey, QFile::ReadOwner | QFile::WriteOwner);
+
+ Utils::FileSaver pubSaver(publicKey);
+ pubSaver.write(publicKeyContent);
+ if (!pubSaver.finalize(error))
+ return false;
+
+ return true;
+}
+
void BlackBerryDeviceConnectionManager::disconnectDevice(Core::Id deviceId)
{
BlackBerryDeviceConnection *connection = m_connections.key(deviceId);
@@ -198,6 +268,8 @@ void BlackBerryDeviceConnectionManager::handleDeviceConnected()
ProjectExplorer::IDevice::DeviceReadyToUse);
}
}
+
+ emit deviceConnected();
}
void BlackBerryDeviceConnectionManager::handleDeviceDisconnected()
@@ -231,6 +303,20 @@ void BlackBerryDeviceConnectionManager::handleProcessOutput(const QString &outpu
emit connectionOutput(deviceId, output);
}
+void BlackBerryDeviceConnectionManager::processPendingDeviceConnections()
+{
+ if (m_pendingDeviceConnections.isEmpty()
+ || BlackBerryConfigurationManager::instance().configurations().isEmpty())
+ return;
+
+ foreach (ProjectExplorer::IDevice::ConstPtr device, m_pendingDeviceConnections)
+ connectDevice(device);
+
+ m_pendingDeviceConnections.clear();
+ disconnect(&BlackBerryConfigurationManager::instance(), SIGNAL(settingsLoaded()),
+ this, SLOT(processPendingDeviceConnections()));
+}
+
BlackBerryDeviceConnection *BlackBerryDeviceConnectionManager::connectionForHost(const QString &host) const
{
QList<BlackBerryDeviceConnection*> connections = m_connections.uniqueKeys();
diff --git a/src/plugins/qnx/blackberrydeviceconnectionmanager.h b/src/plugins/qnx/blackberrydeviceconnectionmanager.h
index 3a16cdcdd2..8d41e220b0 100644
--- a/src/plugins/qnx/blackberrydeviceconnectionmanager.h
+++ b/src/plugins/qnx/blackberrydeviceconnectionmanager.h
@@ -60,9 +60,15 @@ public:
void connectDevice(const ProjectExplorer::IDevice::ConstPtr &device);
void disconnectDevice(const ProjectExplorer::IDevice::ConstPtr &device);
+ const QString privateKeyPath() const;
+ bool hasValidSSHKeys() const;
+ bool setSSHKeys(const QByteArray privateKeyContent, const QByteArray publicKeyContent,
+ QString *error);
+
signals:
void connectionOutput(Core::Id deviceId, const QString &output);
void deviceAboutToConnect(Core::Id deviceId);
+ void deviceConnected();
public slots:
void connectDevice(Core::Id deviceId);
@@ -77,6 +83,8 @@ private slots:
void handleProcessOutput(const QString &output);
+ void processPendingDeviceConnections();
+
private:
explicit BlackBerryDeviceConnectionManager();
@@ -91,6 +99,8 @@ private:
static BlackBerryDeviceConnectionManager *m_instance;
QMultiMap<BlackBerryDeviceConnection*, Core::Id> m_connections;
+
+ QList<ProjectExplorer::IDevice::ConstPtr> m_pendingDeviceConnections;
};
} // namespace Internal
diff --git a/src/plugins/qnx/blackberrydeviceinformation.cpp b/src/plugins/qnx/blackberrydeviceinformation.cpp
index 7c466e2773..e062c22c86 100644
--- a/src/plugins/qnx/blackberrydeviceinformation.cpp
+++ b/src/plugins/qnx/blackberrydeviceinformation.cpp
@@ -62,6 +62,19 @@ void BlackBerryDeviceInformation::setDeviceTarget(const QString &deviceIp, const
start(arguments);
}
+void BlackBerryDeviceInformation::resetResults()
+{
+ m_devicePin.clear();
+ m_deviceOS.clear();
+ m_hardwareId.clear();
+ m_debugTokenAuthor.clear();
+ m_scmBundle.clear();
+ m_hostName.clear();
+ m_debugTokenValid = false;
+ m_isSimulator = false;
+ m_isProductionDevice = true;
+}
+
QString BlackBerryDeviceInformation::devicePin() const
{
return m_devicePin;
@@ -77,14 +90,66 @@ QString BlackBerryDeviceInformation::hardwareId() const
return m_hardwareId;
}
+QString BlackBerryDeviceInformation::debugTokenAuthor() const
+{
+ return m_debugTokenAuthor;
+}
+
+QString BlackBerryDeviceInformation::scmBundle() const
+{
+ return m_scmBundle;
+}
+
+QString BlackBerryDeviceInformation::hostName() const
+{
+ return m_hostName;
+}
+
+bool BlackBerryDeviceInformation::debugTokenValid() const
+{
+ return m_debugTokenValid;
+}
+
+bool BlackBerryDeviceInformation::isSimulator() const
+{
+ return m_isSimulator;
+}
+
+bool BlackBerryDeviceInformation::isProductionDevice() const
+{
+ return m_isProductionDevice;
+}
+
void BlackBerryDeviceInformation::processData(const QString &line)
{
- if (line.startsWith(QLatin1String("devicepin::")))
- m_devicePin = line.split(QLatin1String("::0x")).at(1).trimmed();
- else if (line.startsWith(QLatin1String("device_os::")))
- m_deviceOS = line.split(QLatin1String("::")).at(1).trimmed();
- else if (line.startsWith(QLatin1String("hardwareid::")))
- m_hardwareId = line.split(QLatin1String("::")).at(1).trimmed();
+ static const QString devicepin = QLatin1String("devicepin::0x");
+ static const QString device_os = QLatin1String("device_os::");
+ static const QString hardwareid = QLatin1String("hardwareid::");
+ static const QString debug_token_author = QLatin1String("debug_token_author::");
+ static const QString debug_token_valid = QLatin1String("debug_token_valid:b:");
+ static const QString simulator = QLatin1String("simulator:b:");
+ static const QString scmbundle = QLatin1String("scmbundle::");
+ static const QString hostname = QLatin1String("hostname::");
+ static const QString production_device = QLatin1String("production_device:b:");
+
+ if (line.startsWith(devicepin))
+ m_devicePin = line.mid(devicepin.size()).trimmed();
+ else if (line.startsWith(device_os))
+ m_deviceOS = line.mid(device_os.size()).trimmed();
+ else if (line.startsWith(hardwareid))
+ m_hardwareId = line.mid(hardwareid.size()).trimmed();
+ else if (line.startsWith(debug_token_author))
+ m_debugTokenAuthor = line.mid(debug_token_author.size()).trimmed();
+ else if (line.startsWith(debug_token_valid))
+ m_debugTokenValid = line.mid(debug_token_valid.size()).trimmed() == QLatin1String("true");
+ else if (line.startsWith(simulator))
+ m_isSimulator = line.mid(simulator.size()).trimmed() == QLatin1String("true");
+ else if (line.startsWith(scmbundle))
+ m_scmBundle = line.mid(scmbundle.size()).trimmed();
+ else if (line.startsWith(hostname))
+ m_hostName = line.mid(hostname.size()).trimmed();
+ else if (line.startsWith(production_device))
+ m_isProductionDevice = line.mid(production_device.size()).trimmed() == QLatin1String("true");
}
} // namespace Internal
diff --git a/src/plugins/qnx/blackberrydeviceinformation.h b/src/plugins/qnx/blackberrydeviceinformation.h
index d58e386fcb..adc4d88b84 100644
--- a/src/plugins/qnx/blackberrydeviceinformation.h
+++ b/src/plugins/qnx/blackberrydeviceinformation.h
@@ -61,13 +61,26 @@ public:
QString devicePin() const;
QString deviceOS() const;
QString hardwareId() const;
+ QString debugTokenAuthor() const;
+ bool debugTokenValid() const;
+ QString scmBundle() const;
+ QString hostName() const;
+ bool isSimulator() const;
+ bool isProductionDevice() const;
private:
QString m_devicePin;
QString m_deviceOS;
QString m_hardwareId;
+ QString m_debugTokenAuthor;
+ QString m_scmBundle;
+ QString m_hostName;
+ bool m_debugTokenValid;
+ bool m_isSimulator;
+ bool m_isProductionDevice;
void processData(const QString &line);
+ void resetResults();
};
}
diff --git a/src/plugins/qnx/blackberrydevicelistdetector.cpp b/src/plugins/qnx/blackberrydevicelistdetector.cpp
new file mode 100644
index 0000000000..1382fa7820
--- /dev/null
+++ b/src/plugins/qnx/blackberrydevicelistdetector.cpp
@@ -0,0 +1,95 @@
+/**************************************************************************
+**
+** Copyright (C) 2011 - 2013 Research In Motion
+**
+** Contact: Research In Motion (blackberry-qt@qnx.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 "blackberrydevicelistdetector.h"
+
+#include "blackberryndkprocess.h"
+
+#include <QStringList>
+
+namespace Qnx {
+namespace Internal {
+
+BlackBerryDeviceListDetector::BlackBerryDeviceListDetector(QObject *parent)
+ : QObject(parent)
+ , m_process(new QProcess(this))
+{
+ m_process->setProcessChannelMode(QProcess::MergedChannels);
+
+ connect(m_process, SIGNAL(readyRead()), this, SLOT(processReadyRead()));
+ connect(m_process, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(processFinished()));
+ connect(m_process, SIGNAL(error(QProcess::ProcessError)), this, SLOT(processFinished()));
+}
+
+void BlackBerryDeviceListDetector::detectDeviceList()
+{
+ if (m_process->state() != QProcess::NotRunning)
+ return;
+
+ const QString command = BlackBerryNdkProcess::resolveNdkToolPath(QLatin1String("blackberry-deploy"));
+ QStringList arguments;
+ arguments << QLatin1String("-devices");
+
+ m_process->start(command, arguments, QIODevice::ReadWrite | QIODevice::Unbuffered);
+}
+
+void BlackBerryDeviceListDetector::processReadyRead()
+{
+ while (m_process->canReadLine())
+ processData(readProcessLine());
+}
+
+void BlackBerryDeviceListDetector::processFinished()
+{
+ while (!m_process->atEnd())
+ processData(readProcessLine());
+ emit finished();
+}
+
+const QString BlackBerryDeviceListDetector::readProcessLine()
+{
+ // we assume that the process output is ASCII only
+ QByteArray bytes = m_process->readLine();
+ while (bytes.endsWith('\r') || bytes.endsWith('\n'))
+ bytes.chop(1);
+ return QString::fromLocal8Bit(bytes);
+}
+
+void BlackBerryDeviceListDetector::processData(const QString &line)
+{
+ // line format is: deviceName,deviceHostNameOrIP,deviceType,versionIfSimulator
+ QStringList list = line.split(QLatin1String(","));
+ if (list.count() == 4) {
+ emit deviceDetected (list[0], list[1], QLatin1String("Simulator") == list[2]);
+ }
+}
+
+} // namespace Internal
+} // namespace Qnx
diff --git a/src/plugins/qnx/blackberrycsjregistrar.h b/src/plugins/qnx/blackberrydevicelistdetector.h
index 28bba48d4a..a4445db364 100644
--- a/src/plugins/qnx/blackberrycsjregistrar.h
+++ b/src/plugins/qnx/blackberrydevicelistdetector.h
@@ -3,7 +3,6 @@
** 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.
**
@@ -29,43 +28,42 @@
**
****************************************************************************/
-#ifndef QNX_INTERNAL_BLACKBERRYCSJREGISTRAR_H
-#define QNX_INTERNAL_BLACKBERRYCSJREGISTRAR_H
+#ifndef QNX_INTERNAL_BLACKBERRYDEVICELISTDETECTOR_H
+#define QNX_INTERNAL_BLACKBERRYDEVICELISTDETECTOR_H
#include <QObject>
#include <QString>
-#include <QProcess>
+
+QT_FORWARD_DECLARE_CLASS(QProcess)
namespace Qnx {
namespace Internal {
-class BlackBerryCsjRegistrar : public QObject
+class BlackBerryDeviceListDetector : public QObject
{
-Q_OBJECT
-
+ Q_OBJECT
public:
- enum RegisterStatus
- {
- RegisterSuccess,
- Error
- };
+ explicit BlackBerryDeviceListDetector(QObject *parent = 0);
- BlackBerryCsjRegistrar(QObject *parent = 0);
-
- void tryRegister(const QStringList &csjFiles, const QString &csjPin, const QString &cskPassword);
+ void detectDeviceList();
signals:
- void finished(int status, const QString &errorString);
+ void deviceDetected(const QString &deviceName, const QString &deviceHostName,
+ bool isSimulator);
+ void finished();
private slots:
+ void processReadyRead();
void processFinished();
- void processError(QProcess::ProcessError error);
private:
+ const QString readProcessLine();
+ void processData(const QString &line);
+
QProcess *m_process;
};
} // namespace Internal
} // namespace Qnx
-#endif // QNX_INTERNAL_BLACKBERRYCSJREGISTRAR_H
+#endif // QNX_INTERNAL_BLACKBERRYDEVICELISTDETECTOR_H
diff --git a/src/plugins/qnx/blackberrydeviceprocesssupport.cpp b/src/plugins/qnx/blackberrydeviceprocesssupport.cpp
deleted file mode 100644
index bedf0cc618..0000000000
--- a/src/plugins/qnx/blackberrydeviceprocesssupport.cpp
+++ /dev/null
@@ -1,45 +0,0 @@
-/**************************************************************************
-**
-** 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 "blackberrydeviceprocesssupport.h"
-
-using namespace Qnx;
-using namespace Qnx::Internal;
-
-QString BlackBerryDeviceProcessSupport::killProcessByNameCommandLine(const QString &filePath) const
-{
- QString executable = filePath;
-
- return QString::fromLatin1("for PID in $(pidin -F \"%a %A\" | grep \"%1\" | awk '/%1/ {print $1}'); "
- "do "
- "kill $PID; sleep 1; kill -9 $PID; "
- "done").arg(executable.replace(QLatin1String("/"), QLatin1String("\\/")));
-}
diff --git a/src/plugins/qnx/blackberrykeyspage.cpp b/src/plugins/qnx/blackberrykeyspage.cpp
index 0bcfa4048b..39493bf5a0 100644
--- a/src/plugins/qnx/blackberrykeyspage.cpp
+++ b/src/plugins/qnx/blackberrykeyspage.cpp
@@ -1,8 +1,8 @@
/**************************************************************************
**
-** Copyright (C) 2011 - 2013 Research In Motion
+** Copyright (C) 2013 BlackBerry Limited. All rights reserved.
**
-** Contact: Research In Motion (blackberry-qt@qnx.com)
+** Contact: BlackBerry (qt@blackberry.com)
** Contact: KDAB (info@kdab.com)
**
** This file is part of Qt Creator.
@@ -59,7 +59,6 @@ QWidget *BlackBerryKeysPage::createPage(QWidget *parent)
void BlackBerryKeysPage::apply()
{
- m_widget->apply();
}
void BlackBerryKeysPage::finish()
diff --git a/src/plugins/qnx/blackberrykeyswidget.cpp b/src/plugins/qnx/blackberrykeyswidget.cpp
index d099dc48f6..31ded4630d 100644
--- a/src/plugins/qnx/blackberrykeyswidget.cpp
+++ b/src/plugins/qnx/blackberrykeyswidget.cpp
@@ -1,8 +1,8 @@
/**************************************************************************
**
-** Copyright (C) 2011 - 2013 Research In Motion
+** Copyright (C) 2013 BlackBerry Limited. All rights reserved.
**
-** Contact: Research In Motion (blackberry-qt@qnx.com)
+** Contact: BlackBerry (qt@blackberry.com)
** Contact: KDAB (info@kdab.com)
**
** This file is part of Qt Creator.
@@ -30,18 +30,13 @@
****************************************************************************/
#include "blackberrykeyswidget.h"
-#include "blackberryregisterkeydialog.h"
-#include "blackberryconfiguration.h"
-#include "blackberrycertificatemodel.h"
-#include "blackberryimportcertificatedialog.h"
-#include "blackberrycreatecertificatedialog.h"
+#include "blackberryconfigurationmanager.h"
#include "blackberrycertificate.h"
-#include "blackberryutils.h"
+#include "blackberrysigningutils.h"
+#include "blackberrycreatecertificatedialog.h"
#include "ui_blackberrykeyswidget.h"
-#include <QFileInfo>
-#include <QHeaderView>
-#include <QItemSelectionModel>
+#include <QInputDialog>
#include <QMessageBox>
namespace Qnx {
@@ -49,142 +44,147 @@ namespace Internal {
BlackBerryKeysWidget::BlackBerryKeysWidget(QWidget *parent) :
QWidget(parent),
- m_ui(new Ui_BlackBerryKeysWidget),
- m_model(new BlackBerryCertificateModel(this))
+ m_utils(BlackBerrySigningUtils::instance()),
+ m_ui(new Ui_BlackBerryKeysWidget)
{
m_ui->setupUi(this);
- m_ui->certificatesView->setModel(m_model);
- m_ui->certificatesView->resizeColumnsToContents();
-
- QHeaderView *headerView = m_ui->certificatesView->horizontalHeader();
- headerView->setResizeMode(QHeaderView::Stretch);
- headerView->setResizeMode(2, QHeaderView::Fixed);
-
- QItemSelectionModel *selectionModel = m_ui->certificatesView->selectionModel();
- connect(selectionModel, SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
- this, SLOT(handleSelectionChanged(QItemSelection,QItemSelection)));
-
- updateRegisterSection();
-
- connect(m_ui->registerButton, SIGNAL(clicked()), this, SLOT(registerKey()));
- connect(m_ui->unregisterButton, SIGNAL(clicked()), this, SLOT(unregisterKey()));
- connect(m_ui->createCertificate, SIGNAL(clicked()), this, SLOT(createCertificate()));
- connect(m_ui->importCertificate, SIGNAL(clicked()), this, SLOT(importCertificate()));
- connect(m_ui->deleteCertificate, SIGNAL(clicked()), this, SLOT(deleteCertificate()));
+ m_ui->keyStatus->setTextFormat(Qt::RichText);
+ m_ui->keyStatus->setTextInteractionFlags(Qt::TextBrowserInteraction);
+ m_ui->keyStatus->setOpenExternalLinks(true);
+ m_ui->openCertificateButton->setVisible(false);
+
+ connect(m_ui->createCertificateButton, SIGNAL(clicked()),
+ this, SLOT(createCertificate()));
+ connect(m_ui->clearCertificateButton, SIGNAL(clicked()),
+ this, SLOT(clearCertificate()));
+ connect(m_ui->openCertificateButton, SIGNAL(clicked()),
+ this, SLOT(loadDefaultCertificate()));
}
-void BlackBerryKeysWidget::apply()
+void BlackBerryKeysWidget::certificateLoaded(int status)
{
- BlackBerryConfiguration &configuration = BlackBerryConfiguration::instance();
-
- configuration.syncCertificates(m_model->certificates(), m_model->activeCertificate());
+ disconnect(&m_utils, SIGNAL(defaultCertificateLoaded(int)), this, SLOT(certificateLoaded(int)));
+
+ switch (status) {
+ case BlackBerryCertificate::Success:
+ m_ui->certificateAuthor->setText(m_utils.defaultCertificate()->author());
+ m_ui->openCertificateButton->setVisible(false);
+ break;
+ case BlackBerryCertificate::WrongPassword:
+ if (QMessageBox::question(this, tr("Qt Creator"),
+ tr("Invalid certificate password. Try again?"),
+ QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {
+ loadDefaultCertificate();
+ } else {
+ m_ui->certificateAuthor->clear();
+ m_ui->openCertificateButton->setVisible(true);
+ }
+ break;
+ case BlackBerryCertificate::Busy:
+ case BlackBerryCertificate::InvalidOutputFormat:
+ case BlackBerryCertificate::Error:
+ setCertificateError(tr("Error loading certificate!"));
+ m_ui->openCertificateButton->setVisible(true);
+ break;
+ }
}
-void BlackBerryKeysWidget::registerKey()
+void BlackBerryKeysWidget::createCertificate()
{
- BlackBerryRegisterKeyDialog dialog;
+ BlackBerryCreateCertificateDialog dialog;
const int result = dialog.exec();
- if (result != QDialog::Accepted)
+ if (result == QDialog::Rejected)
return;
- BlackBerryCertificate *cert = dialog.certificate();
+ BlackBerryCertificate *certificate = dialog.certificate();
- if (cert) {
- if (!m_model->insertCertificate(cert))
- QMessageBox::information(this, tr("Error"), tr("Could not insert default certificate."));
+ if (certificate) {
+ m_utils.setDefaultCertificate(certificate);
+ updateCertificateSection();
}
-
- updateRegisterSection();
}
-void BlackBerryKeysWidget::unregisterKey()
+void BlackBerryKeysWidget::clearCertificate()
{
- const QMessageBox::StandardButton answer =
- QMessageBox::question(this, tr("Unregister Key"),
- tr("Do you really want to unregister your key? This action cannot be undone."),
- QMessageBox::Yes | QMessageBox::No);
-
- if (answer & QMessageBox::No)
- return;
-
- BlackBerryConfiguration &configuration = BlackBerryConfiguration::instance();
-
- QFile f(configuration.barsignerCskPath());
- f.remove();
-
- f.setFileName(configuration.barsignerDbPath());
- f.remove();
-
- updateRegisterSection();
+ if (QMessageBox::warning(this, tr("Qt Creator"),
+ tr("This action cannot be undone. Would you like to continue?"),
+ QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {
+ m_utils.deleteDefaultCertificate();
+ updateCertificateSection();
+ }
}
-void BlackBerryKeysWidget::createCertificate()
+void BlackBerryKeysWidget::showEvent(QShowEvent *)
{
- BlackBerryCreateCertificateDialog dialog;
+ updateKeysSection();
+ updateCertificateSection();
+}
- const int result = dialog.exec();
+void BlackBerryKeysWidget::updateCertificateSection()
+{
+ if (m_utils.hasDefaultCertificate()) {
+ setCreateCertificateVisible(false);
- if (result == QDialog::Rejected)
- return;
+ BlackBerryConfigurationManager &configManager = BlackBerryConfigurationManager::instance();
- BlackBerryCertificate *cert = dialog.certificate();
+ m_ui->certificatePath->setText(configManager.defaultKeystorePath());
+ m_ui->certificateAuthor->setText(tr("Loading..."));
- if (cert) {
- if (!m_model->insertCertificate(cert))
- QMessageBox::information(this, tr("Error"), tr("Error storing certificate."));
+ loadDefaultCertificate();
+ } else {
+ setCreateCertificateVisible(true);
}
}
-void BlackBerryKeysWidget::importCertificate()
+void BlackBerryKeysWidget::updateKeysSection()
{
- BlackBerryImportCertificateDialog dialog;
-
- const int result = dialog.exec();
-
- if (result == QDialog::Rejected)
- return;
-
- BlackBerryCertificate *cert = dialog.certificate();
-
- if (cert) {
- if (!m_model->insertCertificate(cert))
- QMessageBox::information(this, tr("Error"), tr("This certificate already exists."));
+ if (m_utils.hasLegacyKeys()) {
+ m_ui->keyStatus->setText(tr("It appears you are using legacy key files. "
+ "Please refer to the "
+ "<a href=\"https://developer.blackberry.com/native/documentation"
+ "/core/com.qnx.doc.native_sdk.devguide/com.qnx.doc.native_sdk.devguide/topic/bbid_to_sa.html\">"
+ "BlackBerry website</a> to find out how to update your keys."));
+ } else if (m_utils.hasRegisteredKeys()) {
+ m_ui->keyStatus->setText(tr("Your keys are ready to be used"));
+ } else {
+ m_ui->keyStatus->setText(tr("No keys found. Please refer to the "
+ "<a href=\"https://www.blackberry.com/SignedKeys/codesigning.html\">BlackBerry website</a> "
+ "to find out how to request your keys."));
}
}
-void BlackBerryKeysWidget::deleteCertificate()
+void BlackBerryKeysWidget::loadDefaultCertificate()
{
- const int result = QMessageBox::question(this, tr("Delete Certificate"),
- tr("Are you sure you want to delete this certificate?"),
- QMessageBox::Yes | QMessageBox::No);
+ const BlackBerryCertificate *certificate = m_utils.defaultCertificate();
- if (result & QMessageBox::No)
+ if (certificate) {
+ m_ui->certificateAuthor->setText(certificate->author());
+ m_ui->openCertificateButton->setVisible(false);
return;
+ }
- m_model->removeRow(m_ui->certificatesView->selectionModel()->currentIndex().row());
+ connect(&m_utils, SIGNAL(defaultCertificateLoaded(int)), this, SLOT(certificateLoaded(int)));
+ m_utils.openDefaultCertificate();
}
-void BlackBerryKeysWidget::handleSelectionChanged(const QItemSelection &selected,
- const QItemSelection &deselected)
+void BlackBerryKeysWidget::setCertificateError(const QString &error)
{
- Q_UNUSED(deselected);
-
- m_ui->deleteCertificate->setEnabled(!selected.indexes().isEmpty());
+ m_ui->certificateAuthor->clear();
+ QMessageBox::critical(this, tr("Qt Creator"), error);
}
-void BlackBerryKeysWidget::updateRegisterSection()
+void BlackBerryKeysWidget::setCreateCertificateVisible(bool visible)
{
- if (BlackBerryUtils::hasRegisteredKeys()) {
- m_ui->registerButton->hide();
- m_ui->unregisterButton->show();
- m_ui->registeredLabel->setText(tr("Registered: Yes"));
- } else {
- m_ui->registerButton->show();
- m_ui->unregisterButton->hide();
- m_ui->registeredLabel->setText(tr("Registered: No"));
- }
+ m_ui->pathLabel->setVisible(!visible);
+ m_ui->authorLabel->setVisible(!visible);
+ m_ui->certificatePath->setVisible(!visible);
+ m_ui->certificateAuthor->setVisible(!visible);
+ m_ui->clearCertificateButton->setVisible(!visible);
+ m_ui->openCertificateButton->setVisible(!visible);
+ m_ui->noCertificateLabel->setVisible(visible);
+ m_ui->createCertificateButton->setVisible(visible);
}
} // namespace Internal
diff --git a/src/plugins/qnx/blackberrykeyswidget.h b/src/plugins/qnx/blackberrykeyswidget.h
index 9e9721f473..11008d0b54 100644
--- a/src/plugins/qnx/blackberrykeyswidget.h
+++ b/src/plugins/qnx/blackberrykeyswidget.h
@@ -1,8 +1,8 @@
/**************************************************************************
**
-** Copyright (C) 2011 - 2013 Research In Motion
+** Copyright (C) 2013 BlackBerry Limited. All rights reserved.
**
-** Contact: Research In Motion (blackberry-qt@qnx.com)
+** Contact: BlackBerry (qt@blackberry.com)
** Contact: KDAB (info@kdab.com)
**
** This file is part of Qt Creator.
@@ -35,16 +35,13 @@
#include "blackberryconfiguration.h"
#include <QWidget>
-#include <QStandardItemModel>
-
-QT_BEGIN_NAMESPACE
-class QItemSelection;
-QT_END_NAMESPACE
+#include <QString>
namespace Qnx {
namespace Internal {
-class BlackBerryCertificateModel;
+class BlackBerryCertificate;
+class BlackBerrySigningUtils;
class Ui_BlackBerryKeysWidget;
class BlackBerryKeysWidget : public QWidget
@@ -53,27 +50,24 @@ class BlackBerryKeysWidget : public QWidget
public:
explicit BlackBerryKeysWidget(QWidget *parent = 0);
- void apply();
-
private slots:
- void registerKey();
- void unregisterKey();
+ void certificateLoaded(int status);
void createCertificate();
- void importCertificate();
- void deleteCertificate();
- void handleSelectionChanged(
- const QItemSelection &selected,
- const QItemSelection &deselected);
+ void clearCertificate();
+ void loadDefaultCertificate();
+
+protected:
+ void showEvent(QShowEvent *event);
private:
- void updateRegisterSection();
+ void updateKeysSection();
+ void updateCertificateSection();
+ void setCertificateError(const QString &error);
+ void setCreateCertificateVisible(bool show);
- QString dataDir() const;
- QString cskFilePath() const;
- QString dbFilePath() const;
+ BlackBerrySigningUtils &m_utils;
Ui_BlackBerryKeysWidget *m_ui;
- BlackBerryCertificateModel *m_model;
};
} // namespace Internal
diff --git a/src/plugins/qnx/blackberrykeyswidget.ui b/src/plugins/qnx/blackberrykeyswidget.ui
index a9156c533e..da510fff6e 100644
--- a/src/plugins/qnx/blackberrykeyswidget.ui
+++ b/src/plugins/qnx/blackberrykeyswidget.ui
@@ -21,36 +21,24 @@
</property>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
- <spacer name="horizontalSpacer">
- <property name="orientation">
- <enum>Qt::Horizontal</enum>
+ <widget class="QLabel" name="keyStatus">
+ <property name="font">
+ <font>
+ <weight>50</weight>
+ <bold>false</bold>
+ </font>
</property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>658</width>
- <height>20</height>
- </size>
- </property>
- </spacer>
- </item>
- <item>
- <widget class="QLabel" name="registeredLabel">
<property name="text">
- <string>Registered: Yes</string>
+ <string>STATUS</string>
</property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="registerButton">
- <property name="text">
- <string>Register</string>
+ <property name="textFormat">
+ <enum>Qt::RichText</enum>
</property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="unregisterButton">
- <property name="text">
- <string>Unregister</string>
+ <property name="wordWrap">
+ <bool>true</bool>
+ </property>
+ <property name="textInteractionFlags">
+ <set>Qt::LinksAccessibleByKeyboard|Qt::LinksAccessibleByMouse</set>
</property>
</widget>
</item>
@@ -62,57 +50,148 @@
<property name="title">
<string>Developer Certificate</string>
</property>
- <layout class="QGridLayout" name="gridLayout">
- <item row="3" column="2">
- <spacer name="verticalSpacer">
- <property name="orientation">
- <enum>Qt::Vertical</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>20</width>
- <height>189</height>
- </size>
- </property>
- </spacer>
- </item>
- <item row="0" column="0" rowspan="4">
- <widget class="QTableView" name="certificatesView">
- <property name="selectionBehavior">
- <enum>QAbstractItemView::SelectRows</enum>
- </property>
- <attribute name="verticalHeaderVisible">
- <bool>false</bool>
- </attribute>
- </widget>
- </item>
- <item row="0" column="2">
- <widget class="QPushButton" name="createCertificate">
- <property name="text">
- <string>Create</string>
- </property>
- </widget>
- </item>
- <item row="1" column="2">
- <widget class="QPushButton" name="importCertificate">
- <property name="text">
- <string>Import</string>
- </property>
- </widget>
+ <layout class="QVBoxLayout" name="verticalLayout_2">
+ <item>
+ <layout class="QGridLayout" name="gridLayout">
+ <item row="0" column="0">
+ <widget class="QLabel" name="pathLabel">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="font">
+ <font>
+ <weight>75</weight>
+ <bold>true</bold>
+ </font>
+ </property>
+ <property name="text">
+ <string>Path:</string>
+ </property>
+ <property name="alignment">
+ <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="1">
+ <widget class="QLabel" name="certificatePath">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Expanding" vsizetype="Preferred">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text">
+ <string>PATH</string>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="0">
+ <widget class="QLabel" name="authorLabel">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="font">
+ <font>
+ <weight>75</weight>
+ <bold>true</bold>
+ </font>
+ </property>
+ <property name="text">
+ <string>Author:</string>
+ </property>
+ <property name="alignment">
+ <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="1">
+ <widget class="QLabel" name="certificateAuthor">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Expanding" vsizetype="Preferred">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text">
+ <string>LABEL</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
</item>
- <item row="2" column="2">
- <widget class="QPushButton" name="deleteCertificate">
- <property name="enabled">
- <bool>false</bool>
- </property>
- <property name="text">
- <string>Delete</string>
- </property>
- </widget>
+ <item>
+ <layout class="QHBoxLayout" name="horizontalLayout_2">
+ <item>
+ <widget class="QLabel" name="noCertificateLabel">
+ <property name="font">
+ <font>
+ <weight>50</weight>
+ <bold>false</bold>
+ </font>
+ </property>
+ <property name="text">
+ <string>No developer certificate has been found.</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="openCertificateButton">
+ <property name="text">
+ <string>Open certificate</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="clearCertificateButton">
+ <property name="text">
+ <string>Clear certificate</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="createCertificateButton">
+ <property name="text">
+ <string>Create certificate</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
</item>
</layout>
</widget>
</item>
+ <item>
+ <spacer name="verticalSpacer">
+ <property name="orientation">
+ <enum>Qt::Vertical</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>20</width>
+ <height>207</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
</layout>
</widget>
<resources/>
diff --git a/src/plugins/qnx/blackberrylogprocessrunner.cpp b/src/plugins/qnx/blackberrylogprocessrunner.cpp
new file mode 100644
index 0000000000..ecd627998a
--- /dev/null
+++ b/src/plugins/qnx/blackberrylogprocessrunner.cpp
@@ -0,0 +1,256 @@
+/**************************************************************************
+**
+** 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 "blackberrylogprocessrunner.h"
+
+#include <ssh/sshremoteprocessrunner.h>
+#include <utils/qtcassert.h>
+
+using namespace Qnx::Internal;
+
+BlackBerryLogProcessRunner::BlackBerryLogProcessRunner(QObject *parent, const QString& appId, const BlackBerryDeviceConfiguration::ConstPtr &device)
+ : QObject(parent)
+ , m_currentLogs(false)
+ , m_slog2infoFound(false)
+ , m_tailProcess(0)
+ , m_slog2infoProcess(0)
+ , m_testSlog2Process(0)
+ , m_launchDateTimeProcess(0)
+{
+ Q_ASSERT(!appId.isEmpty() && device);
+
+ m_appId = appId;
+ m_device = device;
+
+ // The BlackBerry device always uses key authentication
+ m_sshParams = m_device->sshParameters();
+ m_sshParams.authenticationType = QSsh::SshConnectionParameters::AuthenticationTypePublicKey;
+
+ m_tailCommand = QLatin1String("tail -c +1 -f /accounts/1000/appdata/") + m_appId
+ + QLatin1String("/logs/log");
+ m_slog2infoCommand = QString::fromLatin1("slog2info -w -b ") + m_appId;
+}
+
+void BlackBerryLogProcessRunner::start()
+{
+ if (!m_testSlog2Process) {
+ m_testSlog2Process = new QSsh::SshRemoteProcessRunner(this);
+ connect(m_testSlog2Process, SIGNAL(processClosed(int)), this, SLOT(handleSlog2infoFound()));
+ }
+
+ m_testSlog2Process->run("slog2info", m_sshParams);
+}
+
+void BlackBerryLogProcessRunner::handleTailOutput()
+{
+ QSsh::SshRemoteProcessRunner *process = qobject_cast<QSsh::SshRemoteProcessRunner *>(sender());
+ QTC_ASSERT(process, return);
+
+ const QString message = QString::fromLatin1(process->readAllStandardOutput());
+ // if slog2info found then m_tailProcess should only display 'launching' error logs
+ m_slog2infoFound ? output(message, Utils::StdErrFormat) : output(message, Utils::StdOutFormat);
+}
+
+void BlackBerryLogProcessRunner::handleSlog2infoOutput()
+{
+ QSsh::SshRemoteProcessRunner *process = qobject_cast<QSsh::SshRemoteProcessRunner *>(sender());
+ QTC_ASSERT(process, return);
+
+ const QString message = QString::fromLatin1(process->readAllStandardOutput());
+ const QStringList multiLine = message.split(QLatin1Char('\n'));
+ Q_FOREACH (const QString &line, multiLine) {
+ // Note: This is useless if/once slog2info -b displays only logs from recent launches
+ if (!m_launchDateTime.isNull())
+ {
+ // Check if logs are from the recent launch
+ if (!m_currentLogs) {
+ QDateTime dateTime = QDateTime::fromString(line.split(m_appId).first().mid(4).trimmed(),
+ QString::fromLatin1("dd HH:mm:ss.zzz"));
+
+ m_currentLogs = dateTime >= m_launchDateTime;
+ if (!m_currentLogs)
+ continue;
+ }
+ }
+
+ // The line could be a part of a previous log message that contains a '\n'
+ // In that case only the message body is displayed
+ if (!line.contains(m_appId) && !line.isEmpty()) {
+ emit output(line + QLatin1Char('\n'), Utils::StdOutFormat);
+ continue;
+ }
+
+ QStringList validLineBeginnings;
+ validLineBeginnings << QLatin1String("qt-msg 0 ")
+ << QLatin1String("qt-msg* 0 ")
+ << QLatin1String("default* 9000 ")
+ << QLatin1String("default 9000 ")
+ << QLatin1String(" 0 ");
+ Q_FOREACH (const QString &beginning, validLineBeginnings) {
+ if (showQtMessage(beginning, line))
+ break;
+ }
+ }
+}
+
+void BlackBerryLogProcessRunner::handleLogError()
+{
+ QSsh::SshRemoteProcessRunner *process = qobject_cast<QSsh::SshRemoteProcessRunner *>(sender());
+ QTC_ASSERT(process, return);
+
+ const QString message = QString::fromLatin1(process->readAllStandardError());
+ emit output(message, Utils::StdErrFormat);
+}
+
+void BlackBerryLogProcessRunner::handleTailProcessConnectionError()
+{
+ QSsh::SshRemoteProcessRunner *process = qobject_cast<QSsh::SshRemoteProcessRunner *>(sender());
+ QTC_ASSERT(process, return);
+
+ emit output(tr("Cannot show debug output. Error: %1").arg(process->lastConnectionErrorString()),
+ Utils::StdErrFormat);
+}
+
+void BlackBerryLogProcessRunner::handleSlog2infoProcessConnectionError()
+{
+ QSsh::SshRemoteProcessRunner *process = qobject_cast<QSsh::SshRemoteProcessRunner *>(sender());
+ QTC_ASSERT(process, return);
+
+ emit output(tr("Cannot show slog2info output. Error: %1").arg(process->lastConnectionErrorString()),
+ Utils::StdErrFormat);
+}
+
+bool BlackBerryLogProcessRunner::showQtMessage(const QString &pattern, const QString &line)
+{
+ const int index = line.indexOf(pattern);
+ if (index != -1) {
+ const QString str = line.right(line.length()-index-pattern.length()) + QLatin1Char('\n');
+ emit output(str, Utils::StdOutFormat);
+ return true;
+ }
+ return false;
+}
+
+void BlackBerryLogProcessRunner::killProcessRunner(QSsh::SshRemoteProcessRunner *processRunner, const QString &command)
+{
+ QTC_ASSERT(!command.isEmpty(), return);
+
+ ProjectExplorer::DeviceProcessSignalOperation::Ptr signalOperation =
+ m_device->signalOperation();
+ connect(signalOperation.data(), SIGNAL(finished(QString)), SIGNAL(finished()));
+ signalOperation->killProcess(command);
+
+ processRunner->cancel();
+
+ delete processRunner;
+}
+
+void BlackBerryLogProcessRunner::handleSlog2infoFound()
+{
+ QSsh::SshRemoteProcessRunner *process = qobject_cast<QSsh::SshRemoteProcessRunner *>(sender());
+ QTC_ASSERT(process, return);
+
+ m_slog2infoFound = (process->processExitCode() == 0);
+
+ readLaunchTime();
+}
+
+void BlackBerryLogProcessRunner::readLaunchTime()
+{
+ m_launchDateTimeProcess = new QSsh::SshRemoteProcessRunner(this);
+ connect(m_launchDateTimeProcess, SIGNAL(processClosed(int)),
+ this, SLOT(readApplicationLog()));
+
+ m_launchDateTimeProcess->run("date +\"%d %H:%M:%S\"", m_sshParams);
+}
+
+void BlackBerryLogProcessRunner::readApplicationLog()
+{
+ QSsh::SshRemoteProcessRunner *process = qobject_cast<QSsh::SshRemoteProcessRunner *>(sender());
+ QTC_ASSERT(process, return);
+
+ if (m_tailProcess && m_tailProcess->isProcessRunning())
+ return;
+
+ QTC_CHECK(!m_appId.isEmpty());
+
+ if (!m_tailProcess) {
+ m_tailProcess = new QSsh::SshRemoteProcessRunner(this);
+ connect(m_tailProcess, SIGNAL(readyReadStandardOutput()),
+ this, SLOT(handleTailOutput()));
+ connect(m_tailProcess, SIGNAL(readyReadStandardError()),
+ this, SLOT(handleLogError()));
+ connect(m_tailProcess, SIGNAL(connectionError()),
+ this, SLOT(handleTailProcessConnectionError()));
+ }
+
+ m_tailProcess->run(m_tailCommand.toLatin1(), m_sshParams);
+
+ if (!m_slog2infoFound || (m_slog2infoProcess && m_slog2infoProcess->isProcessRunning()))
+ return;
+
+ if (!m_slog2infoProcess) {
+ m_launchDateTime = QDateTime::fromString(QString::fromLatin1(process->readAllStandardOutput()).trimmed(),
+ QString::fromLatin1("dd HH:mm:ss"));
+ m_slog2infoProcess = new QSsh::SshRemoteProcessRunner(this);
+ connect(m_slog2infoProcess, SIGNAL(readyReadStandardOutput()),
+ this, SLOT(handleSlog2infoOutput()));
+ connect(m_slog2infoProcess, SIGNAL(readyReadStandardError()),
+ this, SLOT(handleLogError()));
+ connect(m_slog2infoProcess, SIGNAL(connectionError()),
+ this, SLOT(handleSlog2infoProcessConnectionError()));
+ }
+
+ m_slog2infoProcess->run(m_slog2infoCommand.toLatin1(), m_sshParams);
+}
+
+void BlackBerryLogProcessRunner::stop()
+{
+ if (m_testSlog2Process && m_testSlog2Process->isProcessRunning()) {
+ m_testSlog2Process->cancel();
+ delete m_testSlog2Process;
+ m_testSlog2Process = 0;
+ }
+
+ if (m_tailProcess && m_tailProcess->isProcessRunning()) {
+ killProcessRunner(m_tailProcess, m_tailCommand);
+ m_tailProcess = 0;
+ }
+
+ if (m_slog2infoFound) {
+ if (m_slog2infoProcess && m_slog2infoProcess->isProcessRunning()) {
+ killProcessRunner(m_slog2infoProcess, m_slog2infoCommand);
+ m_slog2infoProcess = 0;
+ }
+ }
+
+ emit finished();
+}
diff --git a/src/plugins/qnx/blackberrycertificatemodel.h b/src/plugins/qnx/blackberrylogprocessrunner.h
index 1e49fcfdc2..155ea5d3ba 100644
--- a/src/plugins/qnx/blackberrycertificatemodel.h
+++ b/src/plugins/qnx/blackberrylogprocessrunner.h
@@ -29,61 +29,75 @@
**
****************************************************************************/
-#ifndef BLACKBERRYCERTIFICATEMODEL_H
-#define BLACKBERRYCERTIFICATEMODEL_H
+#ifndef BLACKBERRYSLOGPROCESS_H
+#define BLACKBERRYSLOGPROCESS_H
-#include <QAbstractTableModel>
-#include <QList>
+#include "blackberrydeviceconfiguration.h"
+
+#include <utils/outputformat.h>
+#include <ssh/sshconnection.h>
+
+#include <QDateTime>
+
+#include <QObject>
+
+namespace QSsh {
+class SshRemoteProcessRunner;
+}
namespace Qnx {
namespace Internal {
-class BlackBerryCertificate;
-
-class BlackBerryCertificateModel : public QAbstractTableModel
+class BlackBerryLogProcessRunner : public QObject
{
Q_OBJECT
-
public:
- explicit BlackBerryCertificateModel(QObject *parent = 0);
- ~BlackBerryCertificateModel();
+ explicit BlackBerryLogProcessRunner(QObject *parent, const QString &appId, const BlackBerryDeviceConfiguration::ConstPtr &device);
+ void start();
- int rowCount(const QModelIndex &parent = QModelIndex()) const;
- int columnCount(const QModelIndex &parent = QModelIndex()) const;
+signals:
+ void output(const QString &msg, Utils::OutputFormat format);
+ void finished();
- QVariant data(const QModelIndex &index,
- int role = Qt::DisplayRole) const;
- QVariant headerData(int section, Qt::Orientation orientation,
- int role = Qt::DisplayRole) const;
+public slots:
+ void stop();
- bool setData(const QModelIndex &index, const QVariant &value,
- int role = Qt::EditRole);
- bool removeRows(int row, int count,
- const QModelIndex &parent = QModelIndex());
-
- bool insertCertificate(BlackBerryCertificate *certificate);
+private slots:
+ void handleSlog2infoFound();
+ void readLaunchTime();
+ void readApplicationLog();
- Qt::ItemFlags flags(const QModelIndex &index) const;
+ void handleTailOutput();
+ void handleTailProcessConnectionError();
- BlackBerryCertificate *activeCertificate() const;
- QList<BlackBerryCertificate*> certificates() const;
+ void handleSlog2infoOutput();
+ void handleSlog2infoProcessConnectionError();
-private slots:
- void load();
+ void handleLogError();
private:
- enum Columns {
- CertPath,
- CertAuthor,
- CertActive,
- ColumnCount
- };
-
- QList<BlackBerryCertificate*> m_certificates;
- BlackBerryCertificate *m_activeCertificate;
-};
+ QString m_appId;
+ QString m_tailCommand;
+ QString m_slog2infoCommand;
+
+ bool m_currentLogs;
+ bool m_slog2infoFound;
+
+ QDateTime m_launchDateTime;
+ BlackBerryDeviceConfiguration::ConstPtr m_device;
+ QSsh::SshConnectionParameters m_sshParams;
+
+ QSsh::SshRemoteProcessRunner *m_tailProcess;
+ QSsh::SshRemoteProcessRunner *m_slog2infoProcess;
+
+ QSsh::SshRemoteProcessRunner *m_testSlog2Process;
+ QSsh::SshRemoteProcessRunner *m_launchDateTimeProcess;
+
+ bool showQtMessage(const QString& pattern, const QString& line);
+ void killProcessRunner(QSsh::SshRemoteProcessRunner *processRunner, const QString& command);
+};
} // namespace Internal
} // namespace Qnx
-#endif // BLACKBERRYCERTIFICATEMODEL_H
+#endif // BLACKBERRYSLOGPROCESS_H
diff --git a/src/plugins/qnx/blackberryndkprocess.cpp b/src/plugins/qnx/blackberryndkprocess.cpp
index a148c9741b..e7939172c0 100644
--- a/src/plugins/qnx/blackberryndkprocess.cpp
+++ b/src/plugins/qnx/blackberryndkprocess.cpp
@@ -31,6 +31,7 @@
#include "blackberryndkprocess.h"
#include "blackberryconfiguration.h"
+#include "blackberryconfigurationmanager.h"
#include <utils/hostosinfo.h>
@@ -52,16 +53,24 @@ BlackBerryNdkProcess::BlackBerryNdkProcess(const QString &command, QObject *pare
this, SLOT(processError(QProcess::ProcessError)));
}
-QString BlackBerryNdkProcess::command() const
+const QString BlackBerryNdkProcess::resolveNdkToolPath(const QString &tool)
{
- QString command = BlackBerryConfiguration::instance()
- .qnxEnv().value(QLatin1String("QNX_HOST"))
- + (QLatin1String("/usr/bin/")) + m_command;
+ QString toolPath;
+ QMultiMap<QString, QString> qnxEnv = BlackBerryConfigurationManager::instance().defaultQnxEnv();
+ if (!qnxEnv.isEmpty()) {
+ toolPath = qnxEnv.value(QLatin1String("QNX_HOST"))
+ + (QLatin1String("/usr/bin/")) + tool;
+
+ if (Utils::HostOsInfo::isWindowsHost())
+ toolPath += QLatin1String(".bat");
+ }
- if (Utils::HostOsInfo::isWindowsHost())
- command += QLatin1String(".bat");
+ return toolPath;
+}
- return command;
+QString BlackBerryNdkProcess::command() const
+{
+ return resolveNdkToolPath(m_command);
}
void BlackBerryNdkProcess::start(const QStringList &arguments)
@@ -69,6 +78,8 @@ void BlackBerryNdkProcess::start(const QStringList &arguments)
if (m_process->state() != QProcess::NotRunning)
return;
+ resetResults();
+
m_process->start(command(), arguments);
}
@@ -146,5 +157,9 @@ void BlackBerryNdkProcess::processData(const QString &line)
Q_UNUSED(line);
}
+void BlackBerryNdkProcess::resetResults()
+{
+}
+
} // namespace Internal
} // namespace Qnx
diff --git a/src/plugins/qnx/blackberryndkprocess.h b/src/plugins/qnx/blackberryndkprocess.h
index f623628965..34e7351107 100644
--- a/src/plugins/qnx/blackberryndkprocess.h
+++ b/src/plugins/qnx/blackberryndkprocess.h
@@ -56,6 +56,13 @@ public:
UserStatus
};
+ /**
+ * @brief Resolves full path to an NDK cmd-line tool.
+ * @return a full-path to the NDK cmd-line tool;
+ * or empty QString when no default QNX configuration is found.
+ */
+ static const QString resolveNdkToolPath(const QString &tool);
+
signals:
void finished(int status);
@@ -74,6 +81,7 @@ private slots:
private:
int errorLineToReturnStatus(const QString &line) const;
virtual void processData(const QString &line);
+ virtual void resetResults();
QProcess *m_process;
diff --git a/src/plugins/qnx/blackberryndksettingspage.cpp b/src/plugins/qnx/blackberryndksettingspage.cpp
index 8482d400b9..5610e0de8c 100644
--- a/src/plugins/qnx/blackberryndksettingspage.cpp
+++ b/src/plugins/qnx/blackberryndksettingspage.cpp
@@ -31,6 +31,7 @@
#include "blackberryndksettingspage.h"
#include "blackberryndksettingswidget.h"
+#include "blackberryconfiguration.h"
#include "qnxconstants.h"
#include <projectexplorer/projectexplorerconstants.h>
@@ -59,6 +60,15 @@ QWidget *BlackBerryNDKSettingsPage::createPage(QWidget *parent)
void BlackBerryNDKSettingsPage::apply()
{
+ foreach (BlackBerryConfiguration* config, m_widget->activatedTargets()) {
+ if (!config->isActive())
+ config->activate();
+ }
+
+ foreach (BlackBerryConfiguration* config, m_widget->deactivatedTargets()) {
+ if (config->isActive())
+ config->deactivate();
+ }
}
void BlackBerryNDKSettingsPage::finish()
diff --git a/src/plugins/qnx/blackberryndksettingswidget.cpp b/src/plugins/qnx/blackberryndksettingswidget.cpp
index d1618d5236..862e478c99 100644
--- a/src/plugins/qnx/blackberryndksettingswidget.cpp
+++ b/src/plugins/qnx/blackberryndksettingswidget.cpp
@@ -1,8 +1,8 @@
/**************************************************************************
**
-** Copyright (C) 2011 - 2013 Research In Motion
+** Copyright (C) 2013 BlackBerry Limited. All rights reserved.
**
-** Contact: Research In Motion (blackberry-qt@qnx.com)
+** Contact: BlackBerry (qt@blackberry.com)
** Contact: KDAB (info@kdab.com)
**
** This file is part of Qt Creator.
@@ -32,39 +32,48 @@
#include "blackberryndksettingswidget.h"
#include "ui_blackberryndksettingswidget.h"
#include "qnxutils.h"
-#include "blackberryutils.h"
+#include "blackberrysigningutils.h"
#include "blackberrysetupwizard.h"
+#include "blackberryconfigurationmanager.h"
+#include "blackberryconfiguration.h"
+
#include <utils/pathchooser.h>
#include <coreplugin/icore.h>
#include <QMessageBox>
+#include <QFileDialog>
+
+#include <QStandardItemModel>
+#include <QTreeWidgetItem>
namespace Qnx {
namespace Internal {
BlackBerryNDKSettingsWidget::BlackBerryNDKSettingsWidget(QWidget *parent) :
QWidget(parent),
- m_ui(new Ui_BlackBerryNDKSettingsWidget)
+ m_ui(new Ui_BlackBerryNDKSettingsWidget),
+ m_autoDetectedNdks(0),
+ m_manualNdks(0)
{
- m_bbConfig = &BlackBerryConfiguration::instance();
+ m_bbConfigManager = &BlackBerryConfigurationManager::instance();
m_ui->setupUi(this);
- m_ui->sdkPath->setExpectedKind(Utils::PathChooser::ExistingDirectory);
- m_ui->sdkPath->setPath(m_bbConfig->ndkPath());
- m_hasValidSdkPath = QnxUtils::isValidNdkPath(m_ui->sdkPath->path());
- initInfoTable();
+ m_ui->removeNdkButton->setEnabled(false);
+ m_ui->activateNdkTargetButton->setEnabled(false);
+ m_ui->deactivateNdkTargetButton->setEnabled(false);
- connect(m_ui->wizardButton, SIGNAL(clicked()), this, SLOT(launchBlackBerrySetupWizard()));
- 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()));
-}
+ m_activatedTargets << m_bbConfigManager->activeConfigurations();
-void BlackBerryNDKSettingsWidget::setRemoveButtonVisible(bool visible)
-{
- m_ui->removeButton->setVisible(visible);
+ initNdkList();
+
+ connect(m_ui->wizardButton, SIGNAL(clicked()), this, SLOT(launchBlackBerrySetupWizard()));
+ connect(m_ui->addNdkButton, SIGNAL(clicked()), this, SLOT(addNdkTarget()));
+ connect(m_ui->removeNdkButton, SIGNAL(clicked()), this, SLOT(removeNdkTarget()));
+ connect(m_ui->activateNdkTargetButton, SIGNAL(clicked()), this, SLOT(activateNdkTarget()));
+ connect(m_ui->deactivateNdkTargetButton, SIGNAL(clicked()), this, SLOT(deactivateNdkTarget()));
+ connect(m_ui->ndksTreeWidget, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)), this, SLOT(updateInfoTable(QTreeWidgetItem*)));
}
void BlackBerryNDKSettingsWidget::setWizardMessageVisible(bool visible)
@@ -73,14 +82,25 @@ void BlackBerryNDKSettingsWidget::setWizardMessageVisible(bool visible)
m_ui->wizardButton->setVisible(visible);
}
-QString BlackBerryNDKSettingsWidget::sdkPath() const
+bool BlackBerryNDKSettingsWidget::hasActiveNdk() const
+{
+ return !m_bbConfigManager->configurations().isEmpty();
+}
+
+QList<BlackBerryConfiguration *> BlackBerryNDKSettingsWidget::activatedTargets()
+{
+ return m_activatedTargets;
+}
+
+QList<BlackBerryConfiguration *> BlackBerryNDKSettingsWidget::deactivatedTargets()
{
- return m_ui->sdkPath->path();
+ return m_deactivatedTargets;
}
void BlackBerryNDKSettingsWidget::launchBlackBerrySetupWizard() const
{
- const bool alreadyConfigured = BlackBerryUtils::hasRegisteredKeys();
+ BlackBerrySigningUtils &blackBerryUtils = BlackBerrySigningUtils::instance();
+ const bool alreadyConfigured = blackBerryUtils.hasRegisteredKeys() && blackBerryUtils.hasDefaultCertificate();
if (alreadyConfigured) {
QMessageBox::information(0, tr("Qt Creator"),
@@ -92,85 +112,171 @@ void BlackBerryNDKSettingsWidget::launchBlackBerrySetupWizard() const
wizard.exec();
}
-void BlackBerryNDKSettingsWidget::checkSdkPath()
+void BlackBerryNDKSettingsWidget::updateInfoTable(QTreeWidgetItem* currentItem)
{
- if (!m_ui->sdkPath->path().isEmpty() &&
- QnxUtils::isValidNdkPath(m_ui->sdkPath->path())) {
- m_bbConfig->setupNdkConfiguration(m_ui->sdkPath->path());
- m_hasValidSdkPath = true;
- } else {
- m_hasValidSdkPath = false;
+ if (!currentItem)
+ return;
+
+ QString envFilePath = currentItem->text(1);
+ if (envFilePath.isEmpty()) {
+ m_ui->removeNdkButton->setEnabled(false);
+ m_ui->activateNdkTargetButton->setEnabled(false);
+ m_ui->deactivateNdkTargetButton->setEnabled(false);
+ return;
+ }
+
+ BlackBerryConfiguration *config = m_bbConfigManager->configurationFromEnvFile(Utils::FileName::fromString(envFilePath));
+ if (!config)
+ return;
+
+ foreach (const NdkInstallInformation &ndkInfo, QnxUtils::installedNdks())
+ {
+ if (ndkInfo.name == config->displayName()) {
+ m_ui->baseNameLabel->setText(ndkInfo.name);
+ m_ui->ndkPathLabel->setText(ndkInfo.path);
+ m_ui->versionLabel->setText(ndkInfo.version);
+ m_ui->hostLabel->setText(ndkInfo.host);
+ m_ui->targetLabel->setText(ndkInfo.target);
+ break;
+ }
}
- emit sdkPathChanged(m_ui->sdkPath->path());
+ updateUi(currentItem, config);
}
-bool BlackBerryNDKSettingsWidget::hasValidSdkPath() const
+void BlackBerryNDKSettingsWidget::updateNdkList()
{
- return m_hasValidSdkPath;
+ foreach (BlackBerryConfiguration *config, m_bbConfigManager->configurations()) {
+ QTreeWidgetItem *parent = config->isAutoDetected() ? m_autoDetectedNdks : m_manualNdks;
+ QTreeWidgetItem *item = new QTreeWidgetItem(parent);
+ item->setText(0, config->displayName());
+ item->setText(1, config->ndkEnvFile().toString());
+ QFont font;
+ font.setBold(config->isActive());
+ item->setFont(0, font);
+ item->setFont(1, font);
+ }
+
+ if (m_autoDetectedNdks->child(0)) {
+ m_autoDetectedNdks->child(0)->setSelected(true);
+ updateInfoTable(m_autoDetectedNdks->child(0));
+ }
}
-void BlackBerryNDKSettingsWidget::updateInfoTable()
+void BlackBerryNDKSettingsWidget::addNdkTarget()
{
- QMultiMap<QString, QString> env = m_bbConfig->qnxEnv();
-
- if (env.isEmpty()) {
- // clear
- clearInfoTable();
+ QString selectedPath = QFileDialog::getOpenFileName(0, tr("Select the NDK Environment file"),
+ QString(), tr("BlackBerry Environment File (*.sh *.bat)"));
+ if (selectedPath.isEmpty() || !QFileInfo(selectedPath).exists())
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);
- }
+ BlackBerryConfiguration *config = m_bbConfigManager->configurationFromEnvFile(Utils::FileName::fromString(selectedPath));
- 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()));
+ if (!config) {
+ config = new BlackBerryConfiguration(Utils::FileName::fromString(selectedPath), false);
+ if (!m_bbConfigManager->addConfiguration(config)) {
+ delete config;
+ return;
+ }
- m_ui->removeButton->setEnabled(true);
+ QTreeWidgetItem *item = new QTreeWidgetItem(m_manualNdks);
+ item->setText(0, selectedPath.split(QDir::separator()).last());
+ item->setText(1, selectedPath);
+ updateInfoTable(item);
+ }
}
-void BlackBerryNDKSettingsWidget::clearInfoTable()
+void BlackBerryNDKSettingsWidget::removeNdkTarget()
{
- m_infoModel->clear();
- m_ui->sdkPath->setPath(QString());
- m_ui->removeButton->setEnabled(false);
-}
+ if (!m_ui->ndksTreeWidget->currentItem())
+ return;
-void BlackBerryNDKSettingsWidget::cleanConfiguration()
-{
+ QString ndk = m_ui->ndksTreeWidget->currentItem()->text(0);
+ QString envFilePath = m_ui->ndksTreeWidget->currentItem()->text(1);
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?"),
+ tr("Are you sure you want to remove:\n %1?").arg(ndk),
QMessageBox::Yes | QMessageBox::No);
- if (button == QMessageBox::Yes)
- m_bbConfig->cleanNdkConfiguration();
+ if (button == QMessageBox::Yes) {
+ BlackBerryConfiguration *config = m_bbConfigManager->configurationFromEnvFile(Utils::FileName::fromString(envFilePath));
+ if (config) {
+ m_bbConfigManager->removeConfiguration(config);
+ m_manualNdks->removeChild(m_ui->ndksTreeWidget->currentItem());
+ }
+ }
}
-void BlackBerryNDKSettingsWidget::initInfoTable()
+void BlackBerryNDKSettingsWidget::activateNdkTarget()
{
- m_infoModel = new QStandardItemModel(this);
+ if (!m_ui->ndksTreeWidget->currentItem())
+ return;
+
+ QString envFilePath = m_ui->ndksTreeWidget->currentItem()->text(1);
+
+ BlackBerryConfiguration *config = m_bbConfigManager->configurationFromEnvFile(Utils::FileName::fromString(envFilePath));
+ if (config && !m_activatedTargets.contains(config)) {
+ m_activatedTargets << config;
+ if (m_deactivatedTargets.contains(config))
+ m_deactivatedTargets.removeAt(m_deactivatedTargets.indexOf(config));
- m_ui->ndkInfosTableView->setModel(m_infoModel);
- m_ui->ndkInfosTableView->verticalHeader()->hide();
- m_ui->ndkInfosTableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ updateUi(m_ui->ndksTreeWidget->currentItem(), config);
+ }
+}
- updateInfoTable();
+void BlackBerryNDKSettingsWidget::deactivateNdkTarget()
+{
+ if (!m_ui->ndksTreeWidget->currentItem())
+ return;
+
+ QString envFilePath = m_ui->ndksTreeWidget->currentItem()->text(1);
+
+ BlackBerryConfiguration *config = m_bbConfigManager->configurationFromEnvFile(Utils::FileName::fromString(envFilePath));
+ if (config && m_activatedTargets.contains(config)) {
+ m_deactivatedTargets << config;
+ m_activatedTargets.removeAt(m_activatedTargets.indexOf(config));
+ updateUi(m_ui->ndksTreeWidget->currentItem(), config);
+ }
+}
+
+void BlackBerryNDKSettingsWidget::updateUi(QTreeWidgetItem *item, BlackBerryConfiguration *config)
+{
+ if (!item || !config)
+ return;
+
+ QFont font;
+ font.setBold(m_activatedTargets.contains(config));
+ item->setFont(0, font);
+ item->setFont(1, font);
+
+ m_ui->activateNdkTargetButton->setEnabled((!m_activatedTargets.contains(config))
+ && config->isAutoDetected());
+ m_ui->deactivateNdkTargetButton->setEnabled((m_activatedTargets.contains(config))
+ && m_activatedTargets.size() > 1
+ && config->isAutoDetected());
+ m_ui->removeNdkButton->setEnabled(!config->isAutoDetected());
+}
+
+void BlackBerryNDKSettingsWidget::initNdkList()
+{
+ m_ui->ndksTreeWidget->header()->setResizeMode(QHeaderView::Stretch);
+ m_ui->ndksTreeWidget->header()->setStretchLastSection(false);
+ m_ui->ndksTreeWidget->setHeaderItem(new QTreeWidgetItem(QStringList() << tr("NDK") << tr("NDK Environment File")));
+ m_ui->ndksTreeWidget->setTextElideMode(Qt::ElideNone);
+ m_ui->ndksTreeWidget->setColumnCount(2);
+ m_autoDetectedNdks = new QTreeWidgetItem(m_ui->ndksTreeWidget);
+ m_autoDetectedNdks->setText(0, tr("Auto-Detected"));
+ m_autoDetectedNdks->setFirstColumnSpanned(true);
+ m_autoDetectedNdks->setFlags(Qt::ItemIsEnabled);
+ m_manualNdks = new QTreeWidgetItem(m_ui->ndksTreeWidget);
+ m_manualNdks->setText(0, tr("Manual"));
+ m_manualNdks->setFirstColumnSpanned(true);
+ m_manualNdks->setFlags(Qt::ItemIsEnabled);
+
+ m_ui->ndksTreeWidget->expandAll();
+
+ updateNdkList();
}
} // namespace Internal
diff --git a/src/plugins/qnx/blackberryndksettingswidget.h b/src/plugins/qnx/blackberryndksettingswidget.h
index 5b82972e70..0ae1fa0972 100644
--- a/src/plugins/qnx/blackberryndksettingswidget.h
+++ b/src/plugins/qnx/blackberryndksettingswidget.h
@@ -32,48 +32,55 @@
#ifndef BLACKBERRYNDKSETTINGSWIDGET_H
#define BLACKBERRYNDKSETTINGSWIDGET_H
-#include "blackberryconfiguration.h"
-
#include <QWidget>
-#include <QStandardItemModel>
+QT_BEGIN_NAMESPACE
+class QStandardItemModel;
+class QTreeWidgetItem;
+QT_END_NAMESPACE
namespace Qnx {
namespace Internal {
+class BlackBerryConfiguration;
+class BlackBerryConfigurationManager;
class Ui_BlackBerryNDKSettingsWidget;
-
class BlackBerryNDKSettingsWidget : public QWidget
{
Q_OBJECT
public:
explicit BlackBerryNDKSettingsWidget(QWidget *parent = 0);
- void setRemoveButtonVisible(bool visible);
void setWizardMessageVisible(bool visible);
- QString sdkPath() const;
+ bool hasActiveNdk() const;
- bool hasValidSdkPath() const;
+ QList<BlackBerryConfiguration *> activatedTargets();
+ QList<BlackBerryConfiguration *> deactivatedTargets();
signals:
- void sdkPathChanged(const QString &newPath);
+ void kitsUpdated();
public slots:
void launchBlackBerrySetupWizard() const;
- void checkSdkPath();
- void updateInfoTable();
- void clearInfoTable();
- void cleanConfiguration();
+ void updateInfoTable(QTreeWidgetItem* currentItem);
+ void updateNdkList();
+ void addNdkTarget();
+ void removeNdkTarget();
+ void activateNdkTarget();
+ void deactivateNdkTarget();
+ void updateUi(QTreeWidgetItem* item, BlackBerryConfiguration* config);
private:
- void initInfoTable();
- Ui_BlackBerryNDKSettingsWidget *m_ui;
- BlackBerryConfiguration *m_bbConfig;
- QStandardItemModel *m_infoModel;
- bool m_hasValidSdkPath;
+ void initNdkList();
+ Ui_BlackBerryNDKSettingsWidget *m_ui;
+ BlackBerryConfigurationManager *m_bbConfigManager;
+ QTreeWidgetItem *m_autoDetectedNdks;
+ QTreeWidgetItem *m_manualNdks;
+ QList<BlackBerryConfiguration *> m_activatedTargets;
+ QList<BlackBerryConfiguration *> m_deactivatedTargets;
};
} // namespace Internal
diff --git a/src/plugins/qnx/blackberryndksettingswidget.ui b/src/plugins/qnx/blackberryndksettingswidget.ui
index a422c63240..4456b029ff 100644
--- a/src/plugins/qnx/blackberryndksettingswidget.ui
+++ b/src/plugins/qnx/blackberryndksettingswidget.ui
@@ -150,39 +150,236 @@
<item row="0" column="0">
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
- <widget class="QLabel" name="label">
- <property name="text">
- <string>BlackBerry NDK Path </string>
- </property>
+ <widget class="QTreeWidget" name="ndksTreeWidget">
+ <column>
+ <property name="text">
+ <string notr="true">1</string>
+ </property>
+ </column>
</widget>
</item>
<item>
- <widget class="Utils::PathChooser" name="sdkPath" native="true"/>
+ <layout class="QVBoxLayout" name="verticalLayout_2">
+ <item>
+ <widget class="QPushButton" name="addNdkButton">
+ <property name="text">
+ <string>Add </string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="removeNdkButton">
+ <property name="text">
+ <string>Remove</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="Line" name="line">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="activateNdkTargetButton">
+ <property name="text">
+ <string>Activate</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="deactivateNdkTargetButton">
+ <property name="text">
+ <string>Deactivate</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>
- <item row="0" column="1">
- <widget class="QPushButton" name="removeButton">
- <property name="text">
- <string>Remove</string>
- </property>
- </widget>
- </item>
- <item row="1" column="0">
- <widget class="QTableView" name="ndkInfosTableView"/>
- </item>
</layout>
</item>
+ <item>
+ <widget class="QGroupBox" name="groupBox">
+ <property name="title">
+ <string>BlackBerry NDK Information</string>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout_7">
+ <item>
+ <layout class="QHBoxLayout" name="horizontalLayout_7">
+ <item>
+ <widget class="QLabel" name="label">
+ <property name="text">
+ <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;NDK Base Name:&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="baseNameLabel">
+ <property name="text">
+ <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>
+ <layout class="QHBoxLayout" name="horizontalLayout_8">
+ <item>
+ <widget class="QLabel" name="label_2">
+ <property name="text">
+ <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;NDK Path:&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="ndkPathLabel">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <spacer name="horizontalSpacer_3">
+ <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>
+ <layout class="QHBoxLayout" name="horizontalLayout_9">
+ <item>
+ <widget class="QLabel" name="label_3">
+ <property name="text">
+ <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;Version:&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="versionLabel">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <spacer name="horizontalSpacer_4">
+ <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>
+ <layout class="QHBoxLayout" name="horizontalLayout_10">
+ <item>
+ <widget class="QLabel" name="label_4">
+ <property name="text">
+ <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;Host:&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="hostLabel">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <spacer name="horizontalSpacer_5">
+ <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>
+ <layout class="QHBoxLayout" name="horizontalLayout_11">
+ <item>
+ <widget class="QLabel" name="label_5">
+ <property name="text">
+ <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;Target:&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="targetLabel">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <spacer name="horizontalSpacer_6">
+ <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>
</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 12bd363879..0eeeef4f7f 100644
--- a/src/plugins/qnx/blackberryqtversion.cpp
+++ b/src/plugins/qnx/blackberryqtversion.cpp
@@ -39,11 +39,16 @@
#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
+#include <QFileInfo>
#include <QTextStream>
using namespace Qnx;
using namespace Qnx::Internal;
+namespace {
+const QLatin1String NndkEnvFile("ndkEnvFile");
+}
+
BlackBerryQtVersion::BlackBerryQtVersion()
: QnxAbstractQtVersion()
{
@@ -52,10 +57,17 @@ BlackBerryQtVersion::BlackBerryQtVersion()
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
+ if (!sdkPath.isEmpty()) {
+ if (QFileInfo(sdkPath).isDir()) {
+ setSdkPath(sdkPath);
+ } else {
+ m_ndkEnvFile = sdkPath;
+ setSdkPath(QFileInfo(sdkPath).absolutePath());
+ }
+
+ } else {
setDefaultSdkPath();
+ }
}
BlackBerryQtVersion::~BlackBerryQtVersion()
@@ -78,13 +90,27 @@ QString BlackBerryQtVersion::description() const
return tr("BlackBerry %1", "Qt Version is meant for BlackBerry").arg(archString());
}
+QVariantMap BlackBerryQtVersion::toMap() const
+{
+ QVariantMap result = QnxAbstractQtVersion::toMap();
+ result.insert(NndkEnvFile, m_ndkEnvFile);
+ return result;
+}
+
+void BlackBerryQtVersion::fromMap(const QVariantMap &map)
+{
+ QnxAbstractQtVersion::fromMap(map);
+ m_ndkEnvFile = map.value(NndkEnvFile).toString();
+}
+
QMultiMap<QString, QString> BlackBerryQtVersion::environment() const
{
QTC_CHECK(!sdkPath().isEmpty());
if (sdkPath().isEmpty())
return QMultiMap<QString, QString>();
- return QnxUtils::parseEnvironmentFile(QnxUtils::envFilePath(sdkPath()));
+ QString envFile = m_ndkEnvFile.isEmpty() ? QnxUtils::envFilePath(sdkPath()) : m_ndkEnvFile;
+ return QnxUtils::parseEnvironmentFile(envFile);
}
void BlackBerryQtVersion::setDefaultSdkPath()
diff --git a/src/plugins/qnx/blackberryqtversion.h b/src/plugins/qnx/blackberryqtversion.h
index 59160e1c35..fd2bf0bdc2 100644
--- a/src/plugins/qnx/blackberryqtversion.h
+++ b/src/plugins/qnx/blackberryqtversion.h
@@ -54,6 +54,9 @@ public:
QString description() const;
+ QVariantMap toMap() const;
+ void fromMap(const QVariantMap &map);
+
Core::FeatureSet availableFeatures() const;
QString platformName() const;
QString platformDisplayName() const;
@@ -63,6 +66,8 @@ public:
private:
QMultiMap<QString, QString> environment() const;
void setDefaultSdkPath();
+
+ QString m_ndkEnvFile;
};
} // namespace Internal
diff --git a/src/plugins/qnx/blackberryregisterkeydialog.cpp b/src/plugins/qnx/blackberryregisterkeydialog.cpp
deleted file mode 100644
index 64759c2b83..0000000000
--- a/src/plugins/qnx/blackberryregisterkeydialog.cpp
+++ /dev/null
@@ -1,324 +0,0 @@
-/**************************************************************************
-**
-** 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 "blackberryregisterkeydialog.h"
-#include "blackberrycsjregistrar.h"
-#include "blackberryconfiguration.h"
-#include "blackberrycertificate.h"
-#include "blackberryutils.h"
-#include "ui_blackberryregisterkeydialog.h"
-
-#include <QFileDialog>
-#include <QFileInfo>
-#include <QDir>
-#include <QPushButton>
-#include <QMessageBox>
-#include <QTextStream>
-
-#include <utils/pathchooser.h>
-
-namespace Qnx {
-namespace Internal {
-
-BlackBerryRegisterKeyDialog::BlackBerryRegisterKeyDialog(QWidget *parent,
- Qt::WindowFlags f) :
- QDialog(parent, f),
- m_ui(new Ui_BlackBerryRegisterKeyDialog),
- m_registrar(new BlackBerryCsjRegistrar(this)),
- m_certificate(0)
-{
- m_ui->setupUi(this);
- m_ui->statusLabel->clear();
-
- setupCsjPathChooser(m_ui->pbdtPath);
- setupCsjPathChooser(m_ui->rdkPath);
-
- m_cancelButton = m_ui->buttonBox->button(QDialogButtonBox::Cancel);
-
- m_okButton = m_ui->buttonBox->button(QDialogButtonBox::Ok);
-
- setBusy(false);
-
- m_okButton->setEnabled(false);
-
- QFileInfo authorP12(BlackBerryConfiguration::instance().defaultKeystorePath());
-
- if (authorP12.exists()) {
- m_ui->genCert->setEnabled(false);
- m_ui->genCert->setChecked(false);
- m_ui->keystorePassword->setEnabled(false);
- m_ui->keystorePassword2->setEnabled(false);
- } else {
- m_ui->genCert->setEnabled(true);
- m_ui->genCert->setChecked(true);
- m_ui->keystorePassword->setEnabled(true);
- m_ui->keystorePassword2->setEnabled(true);
- }
-
-
- connect(m_cancelButton, SIGNAL(clicked()),
- this, SLOT(reject()));
- connect(m_okButton, SIGNAL(clicked()),
- this, SLOT(createKey()));
- connect(m_ui->pbdtPath, SIGNAL(changed(QString)),
- this, SLOT(csjAutoComplete(QString)));
- connect(m_ui->rdkPath, SIGNAL(changed(QString)),
- this, SLOT(csjAutoComplete(QString)));
- connect(m_ui->showPins, SIGNAL(stateChanged(int)),
- this, SLOT(pinCheckBoxChanged(int)));
- connect(m_registrar, SIGNAL(finished(int,QString)),
- this, SLOT(registrarFinished(int,QString)));
- connect(m_ui->genCert, SIGNAL(stateChanged(int)),
- this, SLOT(certCheckBoxChanged(int)));
- connect(m_ui->pbdtPath, SIGNAL(changed(QString)), this, SLOT(validate()));
- connect(m_ui->rdkPath, SIGNAL(changed(QString)), this, SLOT(validate()));
- connect(m_ui->csjPin, SIGNAL(textChanged(QString)), this, SLOT(validate()));
- connect(m_ui->cskPin, SIGNAL(textChanged(QString)), this, SLOT(validate()));
- connect(m_ui->cskPin2, SIGNAL(textChanged(QString)), this, SLOT(validate()));
- connect(m_ui->keystorePassword, SIGNAL(textChanged(QString)), this, SLOT(validate()));
- connect(m_ui->keystorePassword2, SIGNAL(textChanged(QString)), this, SLOT(validate()));
-}
-
-void BlackBerryRegisterKeyDialog::csjAutoComplete(const QString &path)
-{
- Utils::PathChooser *chooser = 0;
- QString file = path;
-
- if (file.contains(QLatin1String("PBDT"))) {
- file.replace(QLatin1String("PBDT"), QLatin1String("RDK"));
- chooser = m_ui->rdkPath;
- } else if (file.contains(QLatin1String("RDK"))) {
- file.replace(QLatin1String("RDK"), QLatin1String("PBDT"));
- chooser = m_ui->pbdtPath;
- }
-
- if (!chooser)
- return;
-
- QFileInfo fileInfo(file);
-
- if (fileInfo.exists())
- chooser->setPath(file);
-}
-
-void BlackBerryRegisterKeyDialog::validate()
-{
- if (!m_ui->pbdtPath->isValid()
- || !m_ui->rdkPath->isValid()
- || m_ui->csjPin->text().isEmpty()
- || m_ui->cskPin->text().isEmpty()
- || m_ui->cskPin2->text().isEmpty()) {
- m_okButton->setEnabled(false);
- m_ui->statusLabel->clear();
- return;
- }
-
- if (m_ui->cskPin->text() != m_ui->cskPin2->text()) {
- m_okButton->setEnabled(false);
- m_ui->statusLabel->setText(tr("CSK passwords do not match."));
- return;
- }
-
- if (m_ui->genCert->isChecked()) {
- if (m_ui->keystorePassword->text().isEmpty()
- || m_ui->keystorePassword2->text().isEmpty()) {
- m_okButton->setEnabled(false);
- m_ui->statusLabel->clear();
- return;
- }
-
- if (m_ui->keystorePassword->text()
- != m_ui->keystorePassword2->text()) {
- m_ui->statusLabel->setText(tr("Keystore password does not match."));
- m_okButton->setEnabled(false);
- return;
- }
- }
-
- m_ui->statusLabel->clear();
- m_okButton->setEnabled(true);
-}
-
-void BlackBerryRegisterKeyDialog::pinCheckBoxChanged(int state)
-{
- if (state == Qt::Checked) {
- m_ui->csjPin->setEchoMode(QLineEdit::Normal);
- m_ui->cskPin->setEchoMode(QLineEdit::Normal);
- m_ui->cskPin2->setEchoMode(QLineEdit::Normal);
- m_ui->keystorePassword->setEchoMode(QLineEdit::Normal);
- m_ui->keystorePassword2->setEchoMode(QLineEdit::Normal);
- } else {
- m_ui->csjPin->setEchoMode(QLineEdit::Password);
- m_ui->cskPin->setEchoMode(QLineEdit::Password);
- m_ui->cskPin2->setEchoMode(QLineEdit::Password);
- m_ui->keystorePassword->setEchoMode(QLineEdit::Password);
- m_ui->keystorePassword2->setEchoMode(QLineEdit::Password);
- }
-}
-
-void BlackBerryRegisterKeyDialog::certCheckBoxChanged(int state)
-{
- m_ui->keystorePassword->setEnabled(state == Qt::Checked);
- m_ui->keystorePassword2->setEnabled(state == Qt::Checked);
-
- validate();
-}
-
-void BlackBerryRegisterKeyDialog::createKey()
-{
- setBusy(true);
-
- QStringList csjFiles;
- csjFiles << rdkPath() << pbdtPath();
-
- m_registrar->tryRegister(csjFiles, csjPin(), cskPin());
-}
-
-void BlackBerryRegisterKeyDialog::registrarFinished(int status,
- const QString &errorString)
-{
- if (status == BlackBerryCsjRegistrar::Error) {
- QMessageBox::critical(this, tr("Error"), errorString);
- cleanup();
- setBusy(false);
- return;
- }
-
- if (m_ui->genCert->isChecked())
- generateDeveloperCertificate();
- else
- accept();
-}
-
-void BlackBerryRegisterKeyDialog::certificateCreated(int status)
-{
- if (status == BlackBerryCertificate::Error) {
- QMessageBox::critical(this, tr("Error"), tr("Error creating developer certificate."));
- cleanup();
- m_certificate->deleteLater();
- m_certificate = 0;
- setBusy(false);
- } else {
- accept();
- }
-}
-
-QString BlackBerryRegisterKeyDialog::pbdtPath() const
-{
- return m_ui->pbdtPath->path();
-}
-
-QString BlackBerryRegisterKeyDialog::rdkPath() const
-{
- return m_ui->rdkPath->path();
-}
-
-QString BlackBerryRegisterKeyDialog::csjPin() const
-{
- return m_ui->csjPin->text();
-}
-
-QString BlackBerryRegisterKeyDialog::cskPin() const
-{
- return m_ui->cskPin->text();
-}
-
-QString BlackBerryRegisterKeyDialog::keystorePassword() const
-{
- return m_ui->keystorePassword->text();
-}
-
-QString BlackBerryRegisterKeyDialog::keystorePath() const
-{
- if (m_ui->genCert->isChecked()) {
- BlackBerryConfiguration &configuration = BlackBerryConfiguration::instance();
- return configuration.defaultKeystorePath();
- }
-
- return QString();
-}
-
-BlackBerryCertificate * BlackBerryRegisterKeyDialog::certificate() const
-{
- return m_certificate;
-}
-
-void BlackBerryRegisterKeyDialog::generateDeveloperCertificate()
-{
- m_certificate = new BlackBerryCertificate(keystorePath(),
- BlackBerryUtils::getCsjAuthor(rdkPath()), keystorePassword());
-
- connect(m_certificate, SIGNAL(finished(int)), this, SLOT(certificateCreated(int)));
-
- m_certificate->store();
-}
-
-void BlackBerryRegisterKeyDialog::cleanup() const
-{
- BlackBerryConfiguration &configuration = BlackBerryConfiguration::instance();
-
- QFile f(configuration.barsignerCskPath());
- f.remove();
-
- f.setFileName(configuration.barsignerDbPath());
- f.remove();
-
- if (m_ui->genCert->isChecked()) {
- f.setFileName(configuration.defaultKeystorePath());
- f.remove();
- }
-}
-
-void BlackBerryRegisterKeyDialog::setBusy(bool busy)
-{
- m_ui->progressBar->setVisible(busy);
- m_okButton->setEnabled(!busy);
- m_cancelButton->setEnabled(!busy);
- m_ui->rdkPath->setEnabled(!busy);
- m_ui->pbdtPath->setEnabled(!busy);
- m_ui->csjPin->setEnabled(!busy);
- m_ui->cskPin->setEnabled(!busy);
- m_ui->cskPin2->setEnabled(!busy);
- m_ui->keystorePassword->setEnabled(!busy);
- m_ui->keystorePassword2->setEnabled(!busy);
- m_ui->showPins->setEnabled(!busy);
-
-}
-
-void BlackBerryRegisterKeyDialog::setupCsjPathChooser(Utils::PathChooser *chooser)
-{
- chooser->setExpectedKind(Utils::PathChooser::File);
- chooser->setPromptDialogTitle(tr("Browse CSJ File"));
- chooser->setPromptDialogFilter(tr("CSJ files (*.csj)"));
-}
-
-} // namespace Internal
-} // namespace Qnx
diff --git a/src/plugins/qnx/blackberryregisterkeydialog.ui b/src/plugins/qnx/blackberryregisterkeydialog.ui
deleted file mode 100644
index c3f36b784c..0000000000
--- a/src/plugins/qnx/blackberryregisterkeydialog.ui
+++ /dev/null
@@ -1,360 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<ui version="4.0">
- <class>Qnx::Internal::BlackBerryRegisterKeyDialog</class>
- <widget class="QDialog" name="Qnx::Internal::BlackBerryRegisterKeyDialog">
- <property name="geometry">
- <rect>
- <x>0</x>
- <y>0</y>
- <width>583</width>
- <height>339</height>
- </rect>
- </property>
- <property name="windowTitle">
- <string>Register Key</string>
- </property>
- <layout class="QVBoxLayout" name="verticalLayout">
- <item>
- <widget class="QLabel" name="label">
- <property name="palette">
- <palette>
- <active>
- <colorrole role="Button">
- <brush brushstyle="SolidPattern">
- <color alpha="255">
- <red>255</red>
- <green>255</green>
- <blue>255</blue>
- </color>
- </brush>
- </colorrole>
- <colorrole role="Base">
- <brush brushstyle="SolidPattern">
- <color alpha="255">
- <red>255</red>
- <green>255</green>
- <blue>255</blue>
- </color>
- </brush>
- </colorrole>
- <colorrole role="Window">
- <brush brushstyle="SolidPattern">
- <color alpha="255">
- <red>255</red>
- <green>255</green>
- <blue>255</blue>
- </color>
- </brush>
- </colorrole>
- </active>
- <inactive>
- <colorrole role="Button">
- <brush brushstyle="SolidPattern">
- <color alpha="255">
- <red>255</red>
- <green>255</green>
- <blue>255</blue>
- </color>
- </brush>
- </colorrole>
- <colorrole role="Base">
- <brush brushstyle="SolidPattern">
- <color alpha="255">
- <red>255</red>
- <green>255</green>
- <blue>255</blue>
- </color>
- </brush>
- </colorrole>
- <colorrole role="Window">
- <brush brushstyle="SolidPattern">
- <color alpha="255">
- <red>255</red>
- <green>255</green>
- <blue>255</blue>
- </color>
- </brush>
- </colorrole>
- </inactive>
- <disabled>
- <colorrole role="Button">
- <brush brushstyle="SolidPattern">
- <color alpha="255">
- <red>255</red>
- <green>255</green>
- <blue>255</blue>
- </color>
- </brush>
- </colorrole>
- <colorrole role="Base">
- <brush brushstyle="SolidPattern">
- <color alpha="255">
- <red>255</red>
- <green>255</green>
- <blue>255</blue>
- </color>
- </brush>
- </colorrole>
- <colorrole role="Window">
- <brush brushstyle="SolidPattern">
- <color alpha="255">
- <red>255</red>
- <green>255</green>
- <blue>255</blue>
- </color>
- </brush>
- </colorrole>
- </disabled>
- </palette>
- </property>
- <property name="autoFillBackground">
- <bool>true</bool>
- </property>
- <property name="frameShape">
- <enum>QFrame::WinPanel</enum>
- </property>
- <property name="text">
- <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;Obtaining keys&lt;/span&gt;&lt;/p&gt;&lt;p&gt;You will need to order a pair of CSJ files from BlackBerry, by &lt;a href=&quot;https://www.blackberry.com/SignedKeys/codesigning.html&quot;&gt;&lt;span style=&quot; text-decoration: underline; color:#004f69;&quot;&gt;visiting this page.&lt;/span&gt;&lt;/a&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
- </property>
- <property name="textFormat">
- <enum>Qt::RichText</enum>
- </property>
- <property name="alignment">
- <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop</set>
- </property>
- <property name="wordWrap">
- <bool>false</bool>
- </property>
- <property name="openExternalLinks">
- <bool>true</bool>
- </property>
- <property name="textInteractionFlags">
- <set>Qt::TextBrowserInteraction</set>
- </property>
- </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>4</height>
- </size>
- </property>
- </spacer>
- </item>
- <item>
- <layout class="QGridLayout" name="gridLayout">
- <item row="0" column="0">
- <widget class="QLabel" name="label_2">
- <property name="text">
- <string>PBDT CSJ file:</string>
- </property>
- <property name="alignment">
- <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
- </property>
- </widget>
- </item>
- <item row="0" column="1" colspan="3">
- <widget class="Utils::PathChooser" name="pbdtPath" native="true"/>
- </item>
- <item row="1" column="0">
- <widget class="QLabel" name="label_3">
- <property name="text">
- <string>RDK CSJ file:</string>
- </property>
- <property name="alignment">
- <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
- </property>
- </widget>
- </item>
- <item row="1" column="1" colspan="3">
- <widget class="Utils::PathChooser" name="rdkPath" native="true"/>
- </item>
- <item row="2" column="0">
- <widget class="QLabel" name="label_4">
- <property name="text">
- <string>CSJ PIN:</string>
- </property>
- <property name="alignment">
- <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
- </property>
- </widget>
- </item>
- <item row="3" column="0">
- <widget class="QLabel" name="label_5">
- <property name="text">
- <string>CSK password:</string>
- </property>
- <property name="alignment">
- <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
- </property>
- </widget>
- </item>
- <item row="4" column="0">
- <widget class="QLabel" name="label_6">
- <property name="text">
- <string>Confirm CSK password:</string>
- </property>
- <property name="alignment">
- <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
- </property>
- </widget>
- </item>
- <item row="6" column="0" colspan="2">
- <widget class="QLabel" name="label_7">
- <property name="text">
- <string>Keystore password:</string>
- </property>
- <property name="alignment">
- <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
- </property>
- </widget>
- </item>
- <item row="7" column="0" colspan="2">
- <widget class="QLabel" name="label_8">
- <property name="text">
- <string>Confirm password:</string>
- </property>
- <property name="alignment">
- <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
- </property>
- </widget>
- </item>
- <item row="5" column="0" colspan="3">
- <widget class="QCheckBox" name="genCert">
- <property name="enabled">
- <bool>false</bool>
- </property>
- <property name="text">
- <string>Generate developer certificate automatically</string>
- </property>
- <property name="checked">
- <bool>true</bool>
- </property>
- </widget>
- </item>
- <item row="5" column="3">
- <widget class="QCheckBox" name="showPins">
- <property name="text">
- <string>Show</string>
- </property>
- </widget>
- </item>
- <item row="7" column="2">
- <widget class="QLineEdit" name="keystorePassword2">
- <property name="echoMode">
- <enum>QLineEdit::Password</enum>
- </property>
- </widget>
- </item>
- <item row="6" column="2">
- <widget class="QLineEdit" name="keystorePassword">
- <property name="echoMode">
- <enum>QLineEdit::Password</enum>
- </property>
- <property name="placeholderText">
- <string/>
- </property>
- </widget>
- </item>
- <item row="2" column="1" colspan="2">
- <widget class="QLineEdit" name="csjPin">
- <property name="maxLength">
- <number>10</number>
- </property>
- <property name="echoMode">
- <enum>QLineEdit::Password</enum>
- </property>
- <property name="placeholderText">
- <string>This is the PIN you entered when you requested the CSJ files.</string>
- </property>
- </widget>
- </item>
- <item row="3" column="1" colspan="2">
- <widget class="QLineEdit" name="cskPin">
- <property name="echoMode">
- <enum>QLineEdit::Password</enum>
- </property>
- <property name="placeholderText">
- <string/>
- </property>
- </widget>
- </item>
- <item row="4" column="1" colspan="2">
- <widget class="QLineEdit" name="cskPin2">
- <property name="echoMode">
- <enum>QLineEdit::Password</enum>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item>
- <widget class="QLabel" name="statusLabel">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="font">
- <font>
- <weight>75</weight>
- <bold>true</bold>
- </font>
- </property>
- <property name="text">
- <string>Status</string>
- </property>
- <property name="alignment">
- <set>Qt::AlignCenter</set>
- </property>
- <property name="wordWrap">
- <bool>false</bool>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QProgressBar" name="progressBar">
- <property name="maximum">
- <number>0</number>
- </property>
- <property name="value">
- <number>-1</number>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QDialogButtonBox" name="buttonBox">
- <property name="standardButtons">
- <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
- </property>
- </widget>
- </item>
- </layout>
- </widget>
- <customwidgets>
- <customwidget>
- <class>Utils::PathChooser</class>
- <extends>QWidget</extends>
- <header location="global">utils/pathchooser.h</header>
- <container>1</container>
- </customwidget>
- </customwidgets>
- <tabstops>
- <tabstop>csjPin</tabstop>
- <tabstop>cskPin</tabstop>
- <tabstop>cskPin2</tabstop>
- <tabstop>genCert</tabstop>
- <tabstop>keystorePassword</tabstop>
- <tabstop>keystorePassword2</tabstop>
- <tabstop>showPins</tabstop>
- <tabstop>buttonBox</tabstop>
- </tabstops>
- <resources/>
- <connections/>
-</ui>
diff --git a/src/plugins/qnx/blackberryruncontrol.cpp b/src/plugins/qnx/blackberryruncontrol.cpp
index a8d87b85c5..15a0766c40 100644
--- a/src/plugins/qnx/blackberryruncontrol.cpp
+++ b/src/plugins/qnx/blackberryruncontrol.cpp
@@ -32,6 +32,9 @@
#include "blackberryruncontrol.h"
#include "blackberryapplicationrunner.h"
#include "blackberryrunconfiguration.h"
+#include "blackberrydeviceconnectionmanager.h"
+
+#include <projectexplorer/target.h>
#include <QIcon>
#include <QTimer>
@@ -42,6 +45,7 @@ using namespace Qnx::Internal;
BlackBerryRunControl::BlackBerryRunControl(BlackBerryRunConfiguration *runConfiguration)
: ProjectExplorer::RunControl(runConfiguration, ProjectExplorer::NormalRunMode)
{
+ m_device = BlackBerryDeviceConfiguration::device(runConfiguration->target()->kit());
m_runner = new BlackBerryApplicationRunner(false, runConfiguration, this);
connect(m_runner, SIGNAL(started()), this, SIGNAL(started()));
@@ -53,7 +57,7 @@ BlackBerryRunControl::BlackBerryRunControl(BlackBerryRunConfiguration *runConfig
void BlackBerryRunControl::start()
{
- m_runner->start();
+ checkDeviceConnection();
}
ProjectExplorer::RunControl::StopResult BlackBerryRunControl::stop()
@@ -75,3 +79,32 @@ void BlackBerryRunControl::handleStartFailed(const QString &message)
{
appendMessage(message, Utils::StdErrFormat);
}
+
+void BlackBerryRunControl::handleDeviceConnected()
+{
+ m_runner->start();
+}
+
+void BlackBerryRunControl::displayConnectionOutput(Core::Id deviceId, const QString &output)
+{
+ if (deviceId != m_device->id())
+ return;
+
+ if (output.contains(QLatin1String("Info:")))
+ appendMessage(output, Utils::StdOutFormat);
+ else if (output.contains(QLatin1String("Error:")))
+ appendMessage(output, Utils::StdErrFormat);
+}
+
+void BlackBerryRunControl::checkDeviceConnection()
+{
+ if (!BlackBerryDeviceConnectionManager::instance()->isConnected(m_device->id())) {
+ connect(BlackBerryDeviceConnectionManager::instance(), SIGNAL(deviceConnected()),
+ this, SLOT(handleDeviceConnected()));
+ connect(BlackBerryDeviceConnectionManager::instance(), SIGNAL(connectionOutput(Core::Id,QString)),
+ this, SLOT(displayConnectionOutput(Core::Id,QString)));
+ BlackBerryDeviceConnectionManager::instance()->connectDevice(m_device->id());
+ } else {
+ m_runner->start();
+ }
+}
diff --git a/src/plugins/qnx/blackberryruncontrol.h b/src/plugins/qnx/blackberryruncontrol.h
index 540599240a..9539dd1349 100644
--- a/src/plugins/qnx/blackberryruncontrol.h
+++ b/src/plugins/qnx/blackberryruncontrol.h
@@ -32,6 +32,8 @@
#ifndef QNX_INTERNAL_BLACKBERRYRUNCONTROL_H
#define QNX_INTERNAL_BLACKBERRYRUNCONTROL_H
+#include "blackberrydeviceconfiguration.h"
+
#include <projectexplorer/runconfiguration.h>
namespace Qt4ProjectManager {
@@ -58,9 +60,13 @@ public:
private slots:
void handleStartFailed(const QString &message);
+ void handleDeviceConnected();
+ void displayConnectionOutput(Core::Id deviceId, const QString &output);
+ void checkDeviceConnection();
private:
BlackBerryApplicationRunner *m_runner;
+ BlackBerryDeviceConfiguration::ConstPtr m_device;
};
} // namespace Internal
diff --git a/src/plugins/qnx/blackberryruncontrolfactory.cpp b/src/plugins/qnx/blackberryruncontrolfactory.cpp
index 3db7911f9d..99ec7e33cb 100644
--- a/src/plugins/qnx/blackberryruncontrolfactory.cpp
+++ b/src/plugins/qnx/blackberryruncontrolfactory.cpp
@@ -101,14 +101,6 @@ ProjectExplorer::RunControl *BlackBerryRunControlFactory::create(ProjectExplorer
return 0;
}
- BlackBerryDeviceConfiguration::ConstPtr device =
- BlackBerryDeviceConfiguration::device(rc->target()->kit());
- if (!BlackBerryDeviceConnectionManager::instance()->isConnected(device->id())) {
- if (errorMessage)
- *errorMessage = tr("Device not connected");
- return 0;
- }
-
if (mode == ProjectExplorer::NormalRunMode) {
BlackBerryRunControl *runControl = new BlackBerryRunControl(rc);
m_activeRunControls[rc->key()] = runControl;
@@ -159,7 +151,7 @@ Debugger::DebuggerStartParameters BlackBerryRunControlFactory::startParameters(
if (const ProjectExplorer::Project *project = runConfig->target()->project()) {
params.projectSourceDirectory = project->projectDirectory();
if (const ProjectExplorer::BuildConfiguration *buildConfig = runConfig->target()->activeBuildConfiguration())
- params.projectBuildDirectory = buildConfig->buildDirectory();
+ params.projectBuildDirectory = buildConfig->buildDirectory().toString();
params.projectSourceFiles = project->files(ProjectExplorer::Project::ExcludeGeneratedFiles);
}
diff --git a/src/plugins/qnx/blackberrysetupwizard.cpp b/src/plugins/qnx/blackberrysetupwizard.cpp
index 2a5df8bb32..8c0427feb5 100644
--- a/src/plugins/qnx/blackberrysetupwizard.cpp
+++ b/src/plugins/qnx/blackberrysetupwizard.cpp
@@ -1,8 +1,8 @@
/**************************************************************************
**
-** Copyright (C) 2011 - 2013 Research In Motion
+** Copyright (C) 2013 BlackBerry Limited. All rights reserved.
**
-** Contact: Research In Motion (blackberry-qt@qnx.com)
+** Contact: BlackBerry (qt@blackberry.com)
** Contact: KDAB (info@kdab.com)
**
** This file is part of Qt Creator.
@@ -32,13 +32,12 @@
#include "blackberrysetupwizard.h"
#include "blackberrysetupwizardpages.h"
#include "blackberrydeviceconfiguration.h"
-#include "blackberrycsjregistrar.h"
#include "blackberrycertificate.h"
-#include "blackberryconfiguration.h"
+#include "blackberryconfigurationmanager.h"
#include "blackberrydebugtokenrequester.h"
#include "blackberrydebugtokenuploader.h"
#include "blackberrydeviceinformation.h"
-#include "blackberryutils.h"
+#include "blackberrysigningutils.h"
#include "qnxconstants.h"
#include <projectexplorer/devicesupport/devicemanager.h>
@@ -61,12 +60,13 @@ BlackBerrySetupWizard::BlackBerrySetupWizard(QWidget *parent) :
QWizard(parent),
m_ndkPage(0),
m_keysPage(0),
+ m_certificatePage(0),
m_devicePage(0),
- m_registrar(0),
m_certificate(0),
m_deviceInfo(0),
m_requester(0),
m_uploader(0),
+ m_utils(BlackBerrySigningUtils::instance()),
m_keyGenerator(0),
m_currentStep(-1),
m_stepOffset(0)
@@ -77,23 +77,22 @@ BlackBerrySetupWizard::BlackBerrySetupWizard(QWidget *parent) :
m_welcomePage = new BlackBerrySetupWizardWelcomePage(this);
m_ndkPage = new BlackBerrySetupWizardNdkPage(this);
m_keysPage = new BlackBerrySetupWizardKeysPage(this);
+ m_certificatePage = new BlackBerrySetupWizardCertificatePage(this);
m_devicePage = new BlackBerrySetupWizardDevicePage(this);
m_finishPage = new BlackBerrySetupWizardFinishPage(this);
setPage(WelcomePageId, m_welcomePage);
setPage(NdkPageId, m_ndkPage);
setPage(KeysPageId, m_keysPage);
+ setPage(CertificatePageId, m_certificatePage);
setPage(DevicePageId, m_devicePage);
setPage(FinishPageId, m_finishPage);
- m_registrar = new BlackBerryCsjRegistrar(this);
m_deviceInfo = new BlackBerryDeviceInformation(this);
m_requester = new BlackBerryDebugTokenRequester(this);
m_uploader = new BlackBerryDebugTokenUploader(this);
m_keyGenerator = new QSsh::SshKeyGenerator;
- connect(m_registrar, SIGNAL(finished(int,QString)),
- this, SLOT(registrarFinished(int,QString)));
connect(m_deviceInfo, SIGNAL(finished(int)),
this, SLOT(deviceInfoFinished(int)));
connect(m_requester, SIGNAL(finished(int)),
@@ -104,7 +103,6 @@ BlackBerrySetupWizard::BlackBerrySetupWizard(QWidget *parent) :
this, SLOT(processNextStep()));
registerStep("requestDevicePin", tr("Reading device PIN..."));
- registerStep("createKeys", tr("Registering CSJ keys..."));
registerStep("generateDeveloperCertificate", tr("Generating developer certificate..."));
registerStep("generateSshKeys", tr("Generating SSH keys..."));
registerStep("requestDebugToken", tr("Requesting a debug token for the device..."));
@@ -163,18 +161,6 @@ void BlackBerrySetupWizard::deviceInfoFinished(int status)
emit stepFinished();
}
-void BlackBerrySetupWizard::registrarFinished(int status,
- const QString &errorString)
-{
- if (status == BlackBerryCsjRegistrar::Error) {
- QMessageBox::critical(this, tr("Error"), errorString);
- reset();
- return;
- }
-
- emit stepFinished();
-}
-
void BlackBerrySetupWizard::certificateCreated(int status)
{
if (status == BlackBerryCertificate::Error) {
@@ -185,9 +171,6 @@ void BlackBerrySetupWizard::certificateCreated(int status)
return;
}
- BlackBerryConfiguration &configuration = BlackBerryConfiguration::instance();
- configuration.addCertificate(m_certificate);
-
emit stepFinished();
}
@@ -200,6 +183,7 @@ void BlackBerrySetupWizard::debugTokenArrived(int status)
emit stepFinished();
return;
case BlackBerryDebugTokenRequester::WrongCskPassword:
+ m_utils.clearCskPassword();
errorString += tr("Wrong CSK password.");
break;
case BlackBerryDebugTokenRequester::WrongKeystorePassword:
@@ -225,6 +209,8 @@ void BlackBerrySetupWizard::debugTokenArrived(int status)
errorString += tr("Failed to communicate with the inferior process.");
break;
case BlackBerryDebugTokenRequester::UnknownError:
+ default:
+ m_utils.clearCskPassword();
errorString += tr("An unknwon error has occurred.");
break;
}
@@ -297,13 +283,9 @@ void BlackBerrySetupWizard::setBusy(bool busy)
void BlackBerrySetupWizard::cleanupFiles() const
{
- BlackBerryConfiguration &configuration = BlackBerryConfiguration::instance();
+ BlackBerryConfigurationManager &configuration = BlackBerryConfigurationManager::instance();
- QFile f(configuration.barsignerCskPath());
- f.remove();
-
- f.setFileName(configuration.barsignerDbPath());
- f.remove();
+ QFile f;
f.setFileName(configuration.defaultKeystorePath());
f.remove();
@@ -327,8 +309,7 @@ void BlackBerrySetupWizard::reset()
m_currentStep = -1;
if (m_certificate) {
- BlackBerryConfiguration &configuration = BlackBerryConfiguration::instance();
- configuration.removeCertificate(m_certificate);
+ m_certificate->deleteLater();
m_certificate = 0;
}
}
@@ -343,20 +324,12 @@ void BlackBerrySetupWizard::requestDevicePin()
m_deviceInfo->setDeviceTarget(hostName(), devicePassword());
}
-void BlackBerrySetupWizard::createKeys()
-{
- QStringList csjFiles;
- csjFiles << rdkPath() << pbdtPath();
-
- m_registrar->tryRegister(csjFiles, csjPin(), password());
-}
-
void BlackBerrySetupWizard::generateDeveloperCertificate()
{
- BlackBerryConfiguration &configuration = BlackBerryConfiguration::instance();
+ BlackBerryConfigurationManager &configuration = BlackBerryConfigurationManager::instance();
m_certificate = new BlackBerryCertificate(configuration.defaultKeystorePath(),
- BlackBerryUtils::getCsjAuthor(rdkPath()), password());
+ certificateAuthor(), certificatePassword());
connect(m_certificate, SIGNAL(finished(int)), this, SLOT(certificateCreated(int)));
@@ -430,10 +403,10 @@ void BlackBerrySetupWizard::requestDebugToken()
return;
}
- BlackBerryConfiguration &configuration = BlackBerryConfiguration::instance();
+ BlackBerryConfigurationManager &configuration = BlackBerryConfigurationManager::instance();
m_requester->requestDebugToken(configuration.defaultDebugTokenPath(),
- password(), configuration.defaultKeystorePath(), password(), m_devicePin);
+ m_utils.cskPassword(), configuration.defaultKeystorePath(), certificatePassword(), m_devicePin);
}
void BlackBerrySetupWizard::uploadDebugToken()
@@ -443,7 +416,7 @@ void BlackBerrySetupWizard::uploadDebugToken()
return;
}
- BlackBerryConfiguration &configuration = BlackBerryConfiguration::instance();
+ BlackBerryConfigurationManager &configuration = BlackBerryConfigurationManager::instance();
m_uploader->uploadDebugToken(configuration.defaultDebugTokenPath(),
hostName(), devicePassword());
@@ -454,6 +427,8 @@ void BlackBerrySetupWizard::writeDeviceInformation()
DeviceManager * const deviceManager = DeviceManager::instance();
deviceManager->addDevice(device());
+ m_utils.setDefaultCertificate(m_certificate);
+
QWizard::accept();
}
@@ -477,24 +452,14 @@ QString BlackBerrySetupWizard::storeLocation() const
return Core::ICore::userResourcePath() + QLatin1String("/qnx/") + deviceName();
}
-QString BlackBerrySetupWizard::rdkPath() const
-{
- return field(QLatin1String(BlackBerrySetupWizardKeysPage::RdkPathField)).toString();
-}
-
-QString BlackBerrySetupWizard::pbdtPath() const
-{
- return field(QLatin1String(BlackBerrySetupWizardKeysPage::PbdtPathField)).toString();
-}
-
-QString BlackBerrySetupWizard::csjPin() const
+QString BlackBerrySetupWizard::certificatePassword() const
{
- return field(QLatin1String(BlackBerrySetupWizardKeysPage::CsjPinField)).toString();
+ return field(QLatin1String(BlackBerrySetupWizardCertificatePage::PasswordField)).toString();
}
-QString BlackBerrySetupWizard::password() const
+QString BlackBerrySetupWizard::certificateAuthor() const
{
- return field(QLatin1String(BlackBerrySetupWizardKeysPage::PasswordField)).toString();
+ return field(QLatin1String(BlackBerrySetupWizardCertificatePage::AuthorField)).toString();
}
QString BlackBerrySetupWizard::hostName() const
@@ -518,7 +483,7 @@ IDevice::Ptr BlackBerrySetupWizard::device()
sshParams.options = QSsh::SshIgnoreDefaultProxy;
sshParams.host = hostName();
sshParams.password = devicePassword();
- sshParams.authenticationType = QSsh::SshConnectionParameters::AuthenticationByKey;
+ sshParams.authenticationType = QSsh::SshConnectionParameters::AuthenticationTypePublicKey;
sshParams.privateKeyFile = privateKeyPath();
sshParams.userName = QLatin1String("devuser");
sshParams.timeout = 10;
@@ -530,7 +495,7 @@ IDevice::Ptr BlackBerrySetupWizard::device()
deviceName(), Core::Id(Constants::QNX_BB_OS_TYPE), machineType);
configuration->setSshParameters(sshParams);
- configuration->setDebugToken(BlackBerryConfiguration::instance().defaultDebugTokenPath());
+ configuration->setDebugToken(BlackBerryConfigurationManager::instance().defaultDebugTokenPath());
return configuration;
}
diff --git a/src/plugins/qnx/blackberrysetupwizard.h b/src/plugins/qnx/blackberrysetupwizard.h
index 263d652f79..e40530aff0 100644
--- a/src/plugins/qnx/blackberrysetupwizard.h
+++ b/src/plugins/qnx/blackberrysetupwizard.h
@@ -1,8 +1,8 @@
/**************************************************************************
**
-** Copyright (C) 2011 - 2013 Research In Motion
+** Copyright (C) 2013 BlackBerry Limited. All rights reserved.
**
-** Contact: Research In Motion (blackberry-qt@qnx.com)
+** Contact: BlackBerry (qt@blackberry.com)
** Contact: KDAB (info@kdab.com)
**
** This file is part of Qt Creator.
@@ -48,13 +48,14 @@ namespace Internal {
class BlackBerrySetupWizardWelcomePage;
class BlackBerrySetupWizardNdkPage;
class BlackBerrySetupWizardKeysPage;
+class BlackBerrySetupWizardCertificatePage;
class BlackBerrySetupWizardDevicePage;
class BlackBerrySetupWizardFinishPage;
-class BlackBerryCsjRegistrar;
class BlackBerryCertificate;
class BlackBerryDeviceInformation;
class BlackBerryDebugTokenRequester;
class BlackBerryDebugTokenUploader;
+class BlackBerrySigningUtils;
class BlackBerrySetupWizard : public QWizard
{
@@ -72,12 +73,10 @@ signals:
private slots:
void processNextStep();
void deviceInfoFinished(int status);
- void registrarFinished(int status, const QString &errorString);
void certificateCreated(int status);
void debugTokenArrived(int status);
void uploaderFinished(int status);
void requestDevicePin();
- void createKeys();
void generateDeveloperCertificate();
void generateSshKeys();
void requestDebugToken();
@@ -89,6 +88,7 @@ private:
WelcomePageId,
NdkPageId,
KeysPageId,
+ CertificatePageId,
DevicePageId,
FinishPageId
};
@@ -107,10 +107,8 @@ private:
QString publicKeyPath() const;
QString deviceName() const;
QString storeLocation() const;
- QString rdkPath() const;
- QString pbdtPath() const;
- QString csjPin() const;
- QString password() const;
+ QString certificatePassword() const;
+ QString certificateAuthor() const;
QString devicePassword() const;
QString hostName() const;
@@ -121,14 +119,15 @@ private:
BlackBerrySetupWizardWelcomePage *m_welcomePage;
BlackBerrySetupWizardNdkPage *m_ndkPage;
BlackBerrySetupWizardKeysPage *m_keysPage;
+ BlackBerrySetupWizardCertificatePage *m_certificatePage;
BlackBerrySetupWizardDevicePage *m_devicePage;
BlackBerrySetupWizardFinishPage *m_finishPage;
- BlackBerryCsjRegistrar *m_registrar;
BlackBerryCertificate *m_certificate;
BlackBerryDeviceInformation *m_deviceInfo;
BlackBerryDebugTokenRequester *m_requester;
BlackBerryDebugTokenUploader *m_uploader;
+ BlackBerrySigningUtils &m_utils;
QSsh::SshKeyGenerator *m_keyGenerator;
diff --git a/src/plugins/qnx/blackberrysetupwizardcertificatepage.ui b/src/plugins/qnx/blackberrysetupwizardcertificatepage.ui
new file mode 100644
index 0000000000..b723cbffaa
--- /dev/null
+++ b/src/plugins/qnx/blackberrysetupwizardcertificatepage.ui
@@ -0,0 +1,108 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>Qnx::Internal::BlackBerrySetupWizardCertificatePage</class>
+ <widget class="QWidget" name="Qnx::Internal::BlackBerrySetupWizardCertificatePage">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>400</width>
+ <height>223</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="QLabel" name="label_2">
+ <property name="text">
+ <string>Author:</string>
+ </property>
+ <property name="alignment">
+ <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="1">
+ <widget class="QLineEdit" name="author"/>
+ </item>
+ <item row="1" column="0">
+ <widget class="QLabel" name="label_3">
+ <property name="text">
+ <string>Password:</string>
+ </property>
+ <property name="alignment">
+ <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="1">
+ <widget class="QLineEdit" name="password">
+ <property name="echoMode">
+ <enum>QLineEdit::Password</enum>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="0">
+ <widget class="QLabel" name="label_4">
+ <property name="text">
+ <string>Confirm password:</string>
+ </property>
+ <property name="alignment">
+ <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="1">
+ <widget class="QLineEdit" name="password2">
+ <property name="echoMode">
+ <enum>QLineEdit::Password</enum>
+ </property>
+ </widget>
+ </item>
+ <item row="3" column="0">
+ <widget class="QCheckBox" name="showPassword">
+ <property name="text">
+ <string>Show password</string>
+ </property>
+ </widget>
+ </item>
+ <item row="3" column="1">
+ <widget class="QLabel" name="status">
+ <property name="font">
+ <font>
+ <weight>75</weight>
+ <bold>true</bold>
+ </font>
+ </property>
+ <property name="text">
+ <string>Status</string>
+ </property>
+ <property name="alignment">
+ <set>Qt::AlignCenter</set>
+ </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>93</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/src/plugins/qnx/blackberrysetupwizardkeyspage.ui b/src/plugins/qnx/blackberrysetupwizardkeyspage.ui
index 6a868be2f5..c5cba65fa5 100644
--- a/src/plugins/qnx/blackberrysetupwizardkeyspage.ui
+++ b/src/plugins/qnx/blackberrysetupwizardkeyspage.ui
@@ -15,7 +15,20 @@
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
- <widget class="QLabel" name="linkLabel">
+ <spacer name="verticalSpacer">
+ <property name="orientation">
+ <enum>Qt::Vertical</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>20</width>
+ <height>63</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item>
+ <widget class="QLabel" name="legacyLabel">
<property name="palette">
<palette>
<active>
@@ -114,7 +127,7 @@
<enum>QFrame::StyledPanel</enum>
</property>
<property name="text">
- <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;Obtaining keys&lt;/span&gt;&lt;/p&gt;&lt;p&gt;You will need to order a pair of CSJ files from BlackBerry, by &lt;a href=&quot;https://www.blackberry.com/SignedKeys/codesigning.html&quot;&gt;&lt;span style=&quot; text-decoration: underline; color:#004f69;&quot;&gt;visiting this page.&lt;/span&gt;&lt;/a&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
+ <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;Legacy keys detected&lt;/span&gt;&lt;/p&gt;&lt;p&gt;It appears you are using legacy key files. Please visit &lt;a href=&quot;https://developer.blackberry.com/native/documentation/core/com.qnx.doc.native_sdk.devguide/com.qnx.doc.native_sdk.devguide/topic/bbid_to_sa.html&quot;&gt;&lt;span style=&quot; text-decoration: underline; color:#004f69;&quot;&gt;this page&lt;/span&gt;&lt;/a&gt; to upgrade your keys.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
<property name="textFormat">
<enum>Qt::RichText</enum>
@@ -134,91 +147,123 @@
</widget>
</item>
<item>
- <layout class="QGridLayout" name="gridLayout">
- <item row="0" column="0">
- <widget class="QLabel" name="label_2">
- <property name="text">
- <string>PBDT CSJ file:</string>
- </property>
- <property name="alignment">
- <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
- </property>
- </widget>
- </item>
- <item row="0" column="1">
- <widget class="Utils::PathChooser" name="pbdtPath" native="true"/>
- </item>
- <item row="1" column="0">
- <widget class="QLabel" name="label_3">
- <property name="text">
- <string>RDK CSJ file:</string>
- </property>
- <property name="alignment">
- <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
- </property>
- </widget>
- </item>
- <item row="1" column="1">
- <widget class="Utils::PathChooser" name="rdkPath" native="true"/>
- </item>
- <item row="2" column="0">
- <widget class="QLabel" name="label_4">
- <property name="text">
- <string>CSJ PIN:</string>
- </property>
- <property name="alignment">
- <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
- </property>
- </widget>
- </item>
- <item row="2" column="1">
- <widget class="QLineEdit" name="csjPin">
- <property name="toolTip">
- <string>The PIN you provided on the key request website</string>
- </property>
- <property name="echoMode">
- <enum>QLineEdit::Password</enum>
- </property>
- </widget>
- </item>
- <item row="3" column="0">
- <widget class="QLabel" name="label_5">
- <property name="text">
- <string>Password:</string>
- </property>
- <property name="alignment">
- <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
- </property>
- </widget>
- </item>
- <item row="3" column="1">
- <widget class="QLineEdit" name="password">
- <property name="toolTip">
- <string>The password that will be used to access your keys and CSK files</string>
- </property>
- <property name="echoMode">
- <enum>QLineEdit::Password</enum>
- </property>
- </widget>
- </item>
- <item row="4" column="0">
- <widget class="QLabel" name="label_6">
- <property name="text">
- <string>Confirm password:</string>
- </property>
- <property name="alignment">
- <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
- </property>
- </widget>
- </item>
- <item row="4" column="1">
- <widget class="QLineEdit" name="password2">
- <property name="echoMode">
- <enum>QLineEdit::Password</enum>
- </property>
- </widget>
- </item>
- </layout>
+ <widget class="QLabel" name="linkLabel">
+ <property name="palette">
+ <palette>
+ <active>
+ <colorrole role="Button">
+ <brush brushstyle="SolidPattern">
+ <color alpha="255">
+ <red>255</red>
+ <green>255</green>
+ <blue>255</blue>
+ </color>
+ </brush>
+ </colorrole>
+ <colorrole role="Base">
+ <brush brushstyle="SolidPattern">
+ <color alpha="255">
+ <red>255</red>
+ <green>255</green>
+ <blue>255</blue>
+ </color>
+ </brush>
+ </colorrole>
+ <colorrole role="Window">
+ <brush brushstyle="SolidPattern">
+ <color alpha="255">
+ <red>255</red>
+ <green>255</green>
+ <blue>255</blue>
+ </color>
+ </brush>
+ </colorrole>
+ </active>
+ <inactive>
+ <colorrole role="Button">
+ <brush brushstyle="SolidPattern">
+ <color alpha="255">
+ <red>255</red>
+ <green>255</green>
+ <blue>255</blue>
+ </color>
+ </brush>
+ </colorrole>
+ <colorrole role="Base">
+ <brush brushstyle="SolidPattern">
+ <color alpha="255">
+ <red>255</red>
+ <green>255</green>
+ <blue>255</blue>
+ </color>
+ </brush>
+ </colorrole>
+ <colorrole role="Window">
+ <brush brushstyle="SolidPattern">
+ <color alpha="255">
+ <red>255</red>
+ <green>255</green>
+ <blue>255</blue>
+ </color>
+ </brush>
+ </colorrole>
+ </inactive>
+ <disabled>
+ <colorrole role="Button">
+ <brush brushstyle="SolidPattern">
+ <color alpha="255">
+ <red>255</red>
+ <green>255</green>
+ <blue>255</blue>
+ </color>
+ </brush>
+ </colorrole>
+ <colorrole role="Base">
+ <brush brushstyle="SolidPattern">
+ <color alpha="255">
+ <red>255</red>
+ <green>255</green>
+ <blue>255</blue>
+ </color>
+ </brush>
+ </colorrole>
+ <colorrole role="Window">
+ <brush brushstyle="SolidPattern">
+ <color alpha="255">
+ <red>255</red>
+ <green>255</green>
+ <blue>255</blue>
+ </color>
+ </brush>
+ </colorrole>
+ </disabled>
+ </palette>
+ </property>
+ <property name="autoFillBackground">
+ <bool>true</bool>
+ </property>
+ <property name="frameShape">
+ <enum>QFrame::StyledPanel</enum>
+ </property>
+ <property name="text">
+ <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;Obtaining keys&lt;/span&gt;&lt;/p&gt;&lt;p&gt;You will need to order your signing keys from BlackBerry, by &lt;a href=&quot;https://www.blackberry.com/SignedKeys/codesigning.html&quot;&gt;&lt;span style=&quot; text-decoration: underline; color:#004f69;&quot;&gt;visiting this page.&lt;/span&gt;&lt;/a&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
+ </property>
+ <property name="textFormat">
+ <enum>Qt::RichText</enum>
+ </property>
+ <property name="alignment">
+ <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop</set>
+ </property>
+ <property name="wordWrap">
+ <bool>false</bool>
+ </property>
+ <property name="openExternalLinks">
+ <bool>false</bool>
+ </property>
+ <property name="textInteractionFlags">
+ <set>Qt::TextBrowserInteraction</set>
+ </property>
+ </widget>
</item>
<item>
<widget class="QLabel" name="statusLabel">
@@ -235,7 +280,7 @@
</font>
</property>
<property name="text">
- <string>Status</string>
+ <string>Your BlackBerry signing keys have already been installed.</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
@@ -246,28 +291,20 @@
</widget>
</item>
<item>
- <spacer name="verticalSpacer">
+ <spacer name="verticalSpacer_2">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
- <height>40</height>
+ <height>62</height>
</size>
</property>
</spacer>
</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/blackberrysetupwizardpages.cpp b/src/plugins/qnx/blackberrysetupwizardpages.cpp
index bc823b206a..4284591a3c 100644
--- a/src/plugins/qnx/blackberrysetupwizardpages.cpp
+++ b/src/plugins/qnx/blackberrysetupwizardpages.cpp
@@ -1,8 +1,8 @@
/**************************************************************************
**
-** Copyright (C) 2011 - 2013 Research In Motion
+** Copyright (C) 2013 BlackBerry Limited. All rights reserved.
**
-** Contact: Research In Motion (blackberry-qt@qnx.com)
+** Contact: BlackBerry (qt@blackberry.com)
** Contact: KDAB (info@kdab.com)
**
** This file is part of Qt Creator.
@@ -32,7 +32,9 @@
#include "blackberrysetupwizardpages.h"
#include "blackberryndksettingswidget.h"
#include "blackberryconfiguration.h"
+#include "blackberrysigningutils.h"
#include "ui_blackberrysetupwizardkeyspage.h"
+#include "ui_blackberrysetupwizardcertificatepage.h"
#include "ui_blackberrysetupwizarddevicepage.h"
#include "ui_blackberrysetupwizardfinishpage.h"
@@ -83,9 +85,8 @@ BlackBerrySetupWizardNdkPage::BlackBerrySetupWizardNdkPage(QWidget *parent) :
m_widget = new BlackBerryNDKSettingsWidget(this);
m_widget->setWizardMessageVisible(false);
- m_widget->setRemoveButtonVisible(false);
- connect(m_widget, SIGNAL(sdkPathChanged(QString)), this, SIGNAL(completeChanged()));
+ connect(m_widget, SIGNAL(kitsUpdated()), this, SIGNAL(completeChanged()));
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(m_widget);
@@ -99,23 +100,17 @@ BlackBerrySetupWizardNdkPage::~BlackBerrySetupWizardNdkPage()
bool BlackBerrySetupWizardNdkPage::isComplete() const
{
- return m_widget->hasValidSdkPath();
+ return m_widget->hasActiveNdk();
}
//-----------------------------------------------------------------------------
-const char BlackBerrySetupWizardKeysPage::PbdtPathField[] = "KeysPage::PbdtPath";
-const char BlackBerrySetupWizardKeysPage::RdkPathField[] = "KeysPage::RdkPath";
-const char BlackBerrySetupWizardKeysPage::CsjPinField[] = "KeysPage::CsjPin";
-const char BlackBerrySetupWizardKeysPage::PasswordField[] = "KeysPage::Password";
-const char BlackBerrySetupWizardKeysPage::Password2Field[] = "KeysPage::Password2";
-
BlackBerrySetupWizardKeysPage::BlackBerrySetupWizardKeysPage(QWidget *parent) :
QWizardPage(parent),
m_ui(0),
m_complete(false)
{
- setTitle(tr("Register Signing Keys"));
+ setTitle(tr("Setup Signing Keys"));
initUi();
}
@@ -126,29 +121,6 @@ BlackBerrySetupWizardKeysPage::~BlackBerrySetupWizardKeysPage()
m_ui = 0;
}
-void BlackBerrySetupWizardKeysPage::validateFields()
-{
- if (!m_ui->pbdtPath->isValid()
- || !m_ui->rdkPath->isValid()
- || m_ui->csjPin->text().isEmpty()
- || m_ui->password->text().isEmpty()
- || m_ui->password2->text().isEmpty()) {
- m_ui->statusLabel->clear();
- setComplete(false);
- return;
- }
-
- if (m_ui->password->text() != m_ui->password2->text()) {
- m_ui->statusLabel->setText(tr("Passwords do not match."));
- setComplete(false);
- return;
- }
-
- m_ui->statusLabel->clear();
-
- setComplete(true);
-}
-
void BlackBerrySetupWizardKeysPage::showKeysMessage(const QString &url)
{
const QMessageBox::StandardButton button = QMessageBox::question(this,
@@ -170,67 +142,100 @@ bool BlackBerrySetupWizardKeysPage::isComplete() const
void BlackBerrySetupWizardKeysPage::initUi()
{
+ BlackBerrySigningUtils &utils = BlackBerrySigningUtils::instance();
+
m_ui = new Ui::BlackBerrySetupWizardKeysPage;
m_ui->setupUi(this);
- m_ui->statusLabel->clear();
-
- setupCsjPathChooser(m_ui->pbdtPath);
- setupCsjPathChooser(m_ui->rdkPath);
-
- connect(m_ui->pbdtPath, SIGNAL(changed(QString)),
- this, SLOT(csjAutoComplete(QString)));
- connect(m_ui->rdkPath, SIGNAL(changed(QString)),
- this, SLOT(csjAutoComplete(QString)));
- connect(m_ui->pbdtPath, SIGNAL(changed(QString)), this, SLOT(validateFields()));
- connect(m_ui->rdkPath, SIGNAL(changed(QString)), this, SLOT(validateFields()));
- connect(m_ui->csjPin, SIGNAL(textChanged(QString)), this, SLOT(validateFields()));
- connect(m_ui->password, SIGNAL(textChanged(QString)), this, SLOT(validateFields()));
- connect(m_ui->password2, SIGNAL(textChanged(QString)), this, SLOT(validateFields()));
+
+ if (utils.hasLegacyKeys()) {
+ m_ui->linkLabel->setVisible(false);
+ m_ui->legacyLabel->setVisible(true);
+ m_ui->statusLabel->setVisible(false);
+
+ setComplete(false);
+ } else if (utils.hasRegisteredKeys()) {
+ m_ui->linkLabel->setVisible(false);
+ m_ui->legacyLabel->setVisible(false);
+ m_ui->statusLabel->setVisible(true);
+
+ setComplete(true);
+ } else {
+ m_ui->linkLabel->setVisible(true);
+ m_ui->legacyLabel->setVisible(false);
+ m_ui->statusLabel->setVisible(false);
+
+ setComplete(false);
+ }
+
connect(m_ui->linkLabel, SIGNAL(linkActivated(QString)),
this, SLOT(showKeysMessage(QString)));
-
- registerField(QLatin1String(PbdtPathField) + QLatin1Char('*'),
- m_ui->pbdtPath, "path", SIGNAL(changed(QString)));
- registerField(QLatin1String(RdkPathField) + QLatin1Char('*'),
- m_ui->rdkPath, "path", SIGNAL(changed(QString)));
- registerField(QLatin1String(CsjPinField) + QLatin1Char('*'),
- m_ui->csjPin);
- registerField(QLatin1String(PasswordField) + QLatin1Char('*'),
- m_ui->password);
- registerField(QLatin1String(Password2Field) + QLatin1Char('*'),
- m_ui->password2);
+ connect(m_ui->legacyLabel, SIGNAL(linkActivated(QString)),
+ this, SLOT(showKeysMessage(QString)));
}
-void BlackBerrySetupWizardKeysPage::csjAutoComplete(const QString &path)
+void BlackBerrySetupWizardKeysPage::setComplete(bool complete)
{
- Utils::PathChooser *chooser = 0;
- QString file = path;
-
- if (file.contains(QLatin1String("PBDT"))) {
- file.replace(QLatin1String("PBDT"), QLatin1String("RDK"));
- chooser = m_ui->rdkPath;
- } else if (file.contains(QLatin1String("RDK"))) {
- file.replace(QLatin1String("RDK"), QLatin1String("PBDT"));
- chooser = m_ui->pbdtPath;
+ if (m_complete != complete) {
+ m_complete = complete;
+ m_ui->linkLabel->setVisible(!complete);
+ m_ui->statusLabel->setVisible(complete);
+ emit completeChanged();
}
+}
+
+//-----------------------------------------------------------------------------
+
+const char BlackBerrySetupWizardCertificatePage::AuthorField[] = "CertificatePage::Author";
+const char BlackBerrySetupWizardCertificatePage::PasswordField[] = "CertificatePage::Password";
+const char BlackBerrySetupWizardCertificatePage::PasswordField2[] = "CertificatePage::Password2";
+
+BlackBerrySetupWizardCertificatePage::BlackBerrySetupWizardCertificatePage(QWidget *parent)
+ : QWizardPage(parent),
+ m_ui(0),
+ m_complete(false)
+{
+ setTitle(tr("Create Developer Certificate"));
+
+ initUi();
+}
+
+bool BlackBerrySetupWizardCertificatePage::isComplete() const
+{
+ return m_complete;
+}
- if (!chooser)
+void BlackBerrySetupWizardCertificatePage::validate()
+{
+ if (m_ui->author->text().isEmpty()
+ || m_ui->password->text().isEmpty()
+ || m_ui->password2->text().isEmpty()) {
+ m_ui->status->clear();
+ setComplete(false);
return;
+ }
- QFileInfo fileInfo(file);
+ if (m_ui->password->text() != m_ui->password2->text()) {
+ m_ui->status->setText(tr("The entered passwords do not match."));
+ setComplete(false);
+ return;
+ }
- if (fileInfo.exists())
- chooser->setPath(file);
+ m_ui->status->clear();
+ setComplete(true);
}
-void BlackBerrySetupWizardKeysPage::setupCsjPathChooser(Utils::PathChooser *chooser)
+void BlackBerrySetupWizardCertificatePage::checkBoxChanged(int state)
{
- chooser->setExpectedKind(Utils::PathChooser::File);
- chooser->setPromptDialogTitle(tr("Browse CSJ File"));
- chooser->setPromptDialogFilter(tr("CSJ files (*.csj)"));
+ if (state == Qt::Checked) {
+ m_ui->password->setEchoMode(QLineEdit::Normal);
+ m_ui->password2->setEchoMode(QLineEdit::Normal);
+ } else {
+ m_ui->password->setEchoMode(QLineEdit::Password);
+ m_ui->password2->setEchoMode(QLineEdit::Password);
+ }
}
-void BlackBerrySetupWizardKeysPage::setComplete(bool complete)
+void BlackBerrySetupWizardCertificatePage::setComplete(bool complete)
{
if (m_complete != complete) {
m_complete = complete;
@@ -238,6 +243,26 @@ void BlackBerrySetupWizardKeysPage::setComplete(bool complete)
}
}
+void BlackBerrySetupWizardCertificatePage::initUi()
+{
+ m_ui = new Ui::BlackBerrySetupWizardCertificatePage;
+ m_ui->setupUi(this);
+ m_ui->status->clear();
+
+ connect(m_ui->author, SIGNAL(textChanged(QString)),
+ this, SLOT(validate()));
+ connect(m_ui->password, SIGNAL(textChanged(QString)),
+ this, SLOT(validate()));
+ connect(m_ui->password2, SIGNAL(textChanged(QString)),
+ this, SLOT(validate()));
+ connect(m_ui->showPassword, SIGNAL(stateChanged(int)),
+ this, SLOT(checkBoxChanged(int)));
+
+ registerField(QLatin1String(AuthorField) + QLatin1Char('*'), m_ui->author);
+ registerField(QLatin1String(PasswordField) + QLatin1Char('*'), m_ui->password);
+ registerField(QLatin1String(PasswordField2) + QLatin1Char('*'), m_ui->password2);
+}
+
//-----------------------------------------------------------------------------
const char BlackBerrySetupWizardDevicePage::NameField[] = "DevicePage::Name";
diff --git a/src/plugins/qnx/blackberrysetupwizardpages.h b/src/plugins/qnx/blackberrysetupwizardpages.h
index a5c2106519..ba586a3da4 100644
--- a/src/plugins/qnx/blackberrysetupwizardpages.h
+++ b/src/plugins/qnx/blackberrysetupwizardpages.h
@@ -1,8 +1,8 @@
/**************************************************************************
**
-** Copyright (C) 2011 - 2013 Research In Motion
+** Copyright (C) 2013 BlackBerry Limited. All rights reserved.
**
-** Contact: Research In Motion (blackberry-qt@qnx.com)
+** Contact: BlackBerry (qt@blackberry.com)
** Contact: KDAB (info@kdab.com)
**
** This file is part of Qt Creator.
@@ -44,11 +44,11 @@ namespace Ui {
class BlackBerrySetupWizardKeysPage;
class BlackBerrySetupWizardDevicePage;
+class BlackBerrySetupWizardCertificatePage;
class BlackBerrySetupWizardFinishPage;
} // namespace Ui
-class BlackBerryCsjRegistrar;
class BlackBerryCertificate;
class BlackBerryNDKSettingsWidget;
@@ -80,25 +80,16 @@ class BlackBerrySetupWizardKeysPage : public QWizardPage
{
Q_OBJECT
public:
- static const char PbdtPathField[];
- static const char RdkPathField[];
- static const char CsjPinField[];
- static const char PasswordField[];
- static const char Password2Field[];
-
explicit BlackBerrySetupWizardKeysPage(QWidget *parent = 0);
virtual ~BlackBerrySetupWizardKeysPage();
bool isComplete() const;
private slots:
- void csjAutoComplete(const QString &path);
- void validateFields();
void showKeysMessage(const QString &url);
private:
void initUi();
- void setupCsjPathChooser(Utils::PathChooser *chooser);
void setComplete(bool complete);
Ui::BlackBerrySetupWizardKeysPage *m_ui;
@@ -107,6 +98,33 @@ private:
//-----------------------------------------------------------------------------
+class BlackBerrySetupWizardCertificatePage : public QWizardPage
+{
+ Q_OBJECT
+public:
+ static const char AuthorField[];
+ static const char PasswordField[];
+ static const char PasswordField2[];
+
+ explicit BlackBerrySetupWizardCertificatePage(QWidget *parent = 0);
+
+ bool isComplete() const;
+
+private slots:
+ void validate();
+ void checkBoxChanged(int state);
+
+private:
+ void setComplete(bool complete);
+ void initUi();
+
+ Ui::BlackBerrySetupWizardCertificatePage *m_ui;
+
+ bool m_complete;
+};
+
+//-----------------------------------------------------------------------------
+
class BlackBerrySetupWizardDevicePage : public QWizardPage
{
Q_OBJECT
diff --git a/src/plugins/qnx/blackberrysigningutils.cpp b/src/plugins/qnx/blackberrysigningutils.cpp
new file mode 100644
index 0000000000..646205ae3e
--- /dev/null
+++ b/src/plugins/qnx/blackberrysigningutils.cpp
@@ -0,0 +1,180 @@
+/**************************************************************************
+**
+** Copyright (C) 2013 BlackBerry Limited. All rights reserved.
+**
+** Contact: BlackBerry (qt@blackberry.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 "blackberrysigningutils.h"
+#include "blackberrycertificate.h"
+#include "blackberryconfiguration.h"
+#include "blackberryconfigurationmanager.h"
+
+#include <QFileInfo>
+#include <QString>
+#include <QFile>
+#include <QTextStream>
+#include <QInputDialog>
+
+using namespace Qnx::Internal;
+
+BlackBerrySigningUtils & BlackBerrySigningUtils::instance()
+{
+ static BlackBerrySigningUtils utils;
+
+ return utils;
+}
+
+BlackBerrySigningUtils::BlackBerrySigningUtils(QObject *parent) :
+ QObject(parent),
+ m_defaultCertificate(0)
+{
+}
+
+bool BlackBerrySigningUtils::hasRegisteredKeys()
+{
+ BlackBerryConfigurationManager &configuration = BlackBerryConfigurationManager::instance();
+
+ QFileInfo cskFile(configuration.idTokenPath());
+
+ return cskFile.exists();
+}
+
+bool BlackBerrySigningUtils::hasLegacyKeys()
+{
+ BlackBerryConfigurationManager &configuration = BlackBerryConfigurationManager::instance();
+
+ QFileInfo cskFile(configuration.barsignerCskPath());
+
+ return cskFile.exists();
+}
+
+bool BlackBerrySigningUtils::hasDefaultCertificate()
+{
+ BlackBerryConfigurationManager &configuration = BlackBerryConfigurationManager::instance();
+
+ QFileInfo keystore(configuration.defaultKeystorePath());
+
+ return keystore.exists();
+}
+
+QString BlackBerrySigningUtils::cskPassword()
+{
+ if (m_cskPassword.isEmpty())
+ m_cskPassword = promptPassword(tr("Please provide your bbidtoken.csk PIN"));
+
+ return m_cskPassword;
+}
+
+QString BlackBerrySigningUtils::certificatePassword()
+{
+ if (m_certificatePassword.isEmpty())
+ m_certificatePassword = promptPassword(tr("Please enter your certificate password"));
+
+ return m_certificatePassword;
+}
+
+const BlackBerryCertificate * BlackBerrySigningUtils::defaultCertificate() const
+{
+ return m_defaultCertificate;
+}
+
+void BlackBerrySigningUtils::openDefaultCertificate()
+{
+ if (m_defaultCertificate) {
+ emit defaultCertificateLoaded(BlackBerryCertificate::Success);
+ return;
+ }
+
+ const QString password = certificatePassword();
+
+ BlackBerryConfigurationManager &configManager = BlackBerryConfigurationManager::instance();
+
+ m_defaultCertificate = new BlackBerryCertificate(configManager.defaultKeystorePath(),
+ QString(), password, this);
+
+ connect(m_defaultCertificate, SIGNAL(finished(int)), this, SLOT(certificateLoaded(int)));
+
+ m_defaultCertificate->load();
+}
+
+void BlackBerrySigningUtils::setDefaultCertificate(BlackBerryCertificate *certificate)
+{
+ if (m_defaultCertificate)
+ m_defaultCertificate->deleteLater();
+
+ certificate->setParent(this);
+ m_defaultCertificate = certificate;
+}
+
+void BlackBerrySigningUtils::clearCskPassword()
+{
+ m_cskPassword.clear();
+}
+
+void BlackBerrySigningUtils::clearCertificatePassword()
+{
+ m_certificatePassword.clear();
+}
+
+void BlackBerrySigningUtils::deleteDefaultCertificate()
+{
+ clearCertificatePassword();
+ m_defaultCertificate->deleteLater();
+ m_defaultCertificate = 0;
+
+ BlackBerryConfigurationManager &configuration = BlackBerryConfigurationManager::instance();
+
+ QFile::remove(configuration.defaultKeystorePath());
+}
+
+void BlackBerrySigningUtils::certificateLoaded(int status)
+{
+ if (status != BlackBerryCertificate::Success) {
+ m_defaultCertificate->deleteLater();
+ m_defaultCertificate = 0;
+
+ if (status == BlackBerryCertificate::WrongPassword)
+ clearCertificatePassword();
+ }
+
+ emit defaultCertificateLoaded(status);
+}
+
+QString BlackBerrySigningUtils::promptPassword(const QString &message) const
+{
+ QInputDialog dialog;
+ dialog.setWindowTitle(tr("Qt Creator"));
+ dialog.setInputMode(QInputDialog::TextInput);
+ dialog.setLabelText(message);
+ dialog.setTextEchoMode(QLineEdit::Password);
+
+ if (dialog.exec() == QDialog::Rejected)
+ return QString();
+
+ return dialog.textValue();
+}
diff --git a/src/plugins/qnx/blackberryregisterkeydialog.h b/src/plugins/qnx/blackberrysigningutils.h
index 0a8f974376..c18f202245 100644
--- a/src/plugins/qnx/blackberryregisterkeydialog.h
+++ b/src/plugins/qnx/blackberrysigningutils.h
@@ -1,8 +1,8 @@
/**************************************************************************
**
-** Copyright (C) 2011 - 2013 Research In Motion
+** Copyright (C) 2013 BlackBerry Limited. All rights reserved.
**
-** Contact: Research In Motion (blackberry-qt@qnx.com)
+** Contact: BlackBerry (qt@blackberry.com)
** Contact: KDAB (info@kdab.com)
**
** This file is part of Qt Creator.
@@ -29,69 +29,63 @@
**
****************************************************************************/
-#ifndef QNX_INTERNAL_BLACKBERRYREGISTERKEYDIALOG_H
-#define QNX_INTERNAL_BLACKBERRYREGISTERKEYDIALOG_H
+#ifndef QNX_INTERNAL_BLACKBERRYSIGNINGUTILS_H
+#define QNX_INTERNAL_BLACKBERRYSIGNINGUTILS_H
-#include <QDialog>
+#include <QtGlobal>
+#include <QObject>
QT_BEGIN_NAMESPACE
-class QPushButton;
+class QString;
QT_END_NAMESPACE
-namespace Utils {
-class PathChooser;
-}
-
namespace Qnx {
namespace Internal {
-class Ui_BlackBerryRegisterKeyDialog;
-class BlackBerryCsjRegistrar;
class BlackBerryCertificate;
-class BlackBerryRegisterKeyDialog : public QDialog
+class BlackBerrySigningUtils : public QObject
{
-Q_OBJECT
+ Q_OBJECT
public:
- explicit BlackBerryRegisterKeyDialog(QWidget *parent = 0,
- Qt::WindowFlags f = 0);
+ static BlackBerrySigningUtils &instance();
+
+ bool hasRegisteredKeys();
+ bool hasLegacyKeys();
+ bool hasDefaultCertificate();
+
+ QString cskPassword();
+ QString certificatePassword();
+
+ const BlackBerryCertificate *defaultCertificate() const;
- QString pbdtPath() const;
- QString rdkPath() const;
- QString csjPin() const;
- QString cskPin() const;
- QString keystorePassword() const;
- QString keystorePath() const;
+ void openDefaultCertificate();
+ void setDefaultCertificate(BlackBerryCertificate *certificate);
+ void clearCskPassword();
+ void clearCertificatePassword();
+ void deleteDefaultCertificate();
- BlackBerryCertificate *certificate() const;
+signals:
+ void defaultCertificateLoaded(int status);
private slots:
- void csjAutoComplete(const QString &path);
- void validate();
- void createKey();
- void pinCheckBoxChanged(int state);
- void certCheckBoxChanged(int state);
- void registrarFinished(int status, const QString &errorString);
- void certificateCreated(int status);
+ void certificateLoaded(int status);
private:
- void setupCsjPathChooser(Utils::PathChooser *chooser);
- void generateDeveloperCertificate();
- void cleanup() const;
- void setBusy(bool busy);
+ Q_DISABLE_COPY(BlackBerrySigningUtils)
- Ui_BlackBerryRegisterKeyDialog *m_ui;
+ BlackBerrySigningUtils(QObject *parent = 0);
- BlackBerryCsjRegistrar *m_registrar;
+ QString promptPassword(const QString &message) const;
- BlackBerryCertificate *m_certificate;
+ BlackBerryCertificate *m_defaultCertificate;
- QPushButton *m_okButton;
- QPushButton *m_cancelButton;
+ QString m_cskPassword;
+ QString m_certificatePassword;
};
} // namespace Internal
} // namespace Qnx
-#endif // QNX_INTERNAL_BLACKBERRYREGISTERKEYDIALOG_H
+#endif // QNX_INTERNAL_BLACKBERRYSIGNINGUTILS_H
diff --git a/src/plugins/qnx/blackberrysshkeysgenerator.cpp b/src/plugins/qnx/blackberrysshkeysgenerator.cpp
index d8f6dd0b7c..658b1c5e58 100644
--- a/src/plugins/qnx/blackberrysshkeysgenerator.cpp
+++ b/src/plugins/qnx/blackberrysshkeysgenerator.cpp
@@ -34,10 +34,11 @@
using namespace Qnx::Internal;
-BlackBerrySshKeysGenerator::BlackBerrySshKeysGenerator(QObject *parent)
- : QThread(parent)
+BlackBerrySshKeysGenerator::BlackBerrySshKeysGenerator()
+ : QThread(0)
, m_keyGen(new QSsh::SshKeyGenerator)
{
+ connect(this, SIGNAL(finished()), this, SLOT(deleteLater()));
}
BlackBerrySshKeysGenerator::~BlackBerrySshKeysGenerator()
@@ -51,15 +52,20 @@ void BlackBerrySshKeysGenerator::run()
const bool success = m_keyGen->generateKeys(QSsh::SshKeyGenerator::Rsa,
QSsh::SshKeyGenerator::Mixed, 4096,
QSsh::SshKeyGenerator::DoNotOfferEncryption);
- emit sshKeysGenerationFinished(success);
-}
+ if (success) {
+ // BB10 devices allow to use public key with no comment
+ // or a comment in username@hostname format
+ // QSsh::SshKeyGenerator class creates comments in 'QtCreator/TIMEZONE' format
+ // therefore stripping this comment out
+ QByteArray publicKey = m_keyGen->publicKey();
+ int firstSpace = publicKey.indexOf(' ');
+ if (firstSpace >= 0) {
+ int secondSpace = publicKey.indexOf(' ', firstSpace + 1);
+ if (secondSpace >= 0)
+ publicKey.truncate(secondSpace);
+ }
-QSsh::SshKeyGenerator *BlackBerrySshKeysGenerator::keyGenerator() const
-{
- return m_keyGen;
-}
-
-QString BlackBerrySshKeysGenerator::error() const
-{
- return m_keyGen->error();
+ emit sshKeysGenerationFinished(m_keyGen->privateKey(), publicKey);
+ } else
+ emit sshKeysGenerationFailed(m_keyGen->error());
}
diff --git a/src/plugins/qnx/blackberrysshkeysgenerator.h b/src/plugins/qnx/blackberrysshkeysgenerator.h
index 459a9e205f..9c66c91511 100644
--- a/src/plugins/qnx/blackberrysshkeysgenerator.h
+++ b/src/plugins/qnx/blackberrysshkeysgenerator.h
@@ -44,13 +44,12 @@ class BlackBerrySshKeysGenerator : public QThread
{
Q_OBJECT
public:
- BlackBerrySshKeysGenerator(QObject *parent = 0);
+ BlackBerrySshKeysGenerator();
~BlackBerrySshKeysGenerator();
- QSsh::SshKeyGenerator *keyGenerator() const;
- QString error() const;
signals:
- void sshKeysGenerationFinished(bool success);
+ void sshKeysGenerationFailed(const QString &error);
+ void sshKeysGenerationFinished(const QByteArray &privateKey, const QByteArray &publicKey);
private:
QSsh::SshKeyGenerator *m_keyGen;
diff --git a/src/plugins/qnx/qnx.pro b/src/plugins/qnx/qnx.pro
index 16f02fa6f2..b32df8ee21 100644
--- a/src/plugins/qnx/qnx.pro
+++ b/src/plugins/qnx/qnx.pro
@@ -61,10 +61,7 @@ SOURCES += qnxplugin.cpp \
bardescriptorpermissionsmodel.cpp \
blackberrykeyswidget.cpp \
blackberrykeyspage.cpp \
- blackberrycsjregistrar.cpp \
blackberrycertificate.cpp \
- blackberrycertificatemodel.cpp \
- blackberryregisterkeydialog.cpp \
blackberryimportcertificatedialog.cpp \
blackberrycreatecertificatedialog.cpp \
blackberrydebugtokenrequester.cpp \
@@ -72,7 +69,6 @@ SOURCES += qnxplugin.cpp \
blackberrydebugtokenuploader.cpp \
blackberrydebugtokenreader.cpp \
blackberryndkprocess.cpp \
- blackberrydeviceprocesssupport.cpp \
blackberrycheckdevmodestepfactory.cpp \
blackberrycheckdevmodestep.cpp \
blackberrycheckdevmodestepconfigwidget.cpp \
@@ -92,8 +88,13 @@ SOURCES += qnxplugin.cpp \
bardescriptoreditorabstractpanelwidget.cpp \
blackberrysetupwizard.cpp \
blackberrysetupwizardpages.cpp \
- blackberryutils.cpp \
- qnxdevicetester.cpp
+ blackberrysigningutils.cpp \
+ qnxdevicetester.cpp \
+ blackberryconfigurationmanager.cpp \
+ blackberrydevicelistdetector.cpp \
+ blackberrylogprocessrunner.cpp \
+ qnxdeviceprocesssignaloperation.cpp \
+ qnxdeviceprocesslist.cpp
HEADERS += qnxplugin.h\
qnxconstants.h \
@@ -154,10 +155,7 @@ HEADERS += qnxplugin.h\
bardescriptorpermissionsmodel.h \
blackberrykeyswidget.h \
blackberrykeyspage.h \
- blackberrycsjregistrar.h \
blackberrycertificate.h \
- blackberrycertificatemodel.h \
- blackberryregisterkeydialog.h \
blackberryimportcertificatedialog.h \
blackberrycreatecertificatedialog.h \
blackberrydebugtokenrequester.h \
@@ -165,7 +163,6 @@ HEADERS += qnxplugin.h\
blackberrydebugtokenuploader.h \
blackberrydebugtokenreader.h \
blackberryndkprocess.h \
- blackberrydeviceprocesssupport.h \
blackberrycheckdevmodestepfactory.h \
blackberrycheckdevmodestep.h \
blackberrycheckdevmodestepconfigwidget.h \
@@ -185,19 +182,22 @@ HEADERS += qnxplugin.h\
bardescriptoreditorabstractpanelwidget.h \
blackberrysetupwizard.h \
blackberrysetupwizardpages.h \
- blackberryutils.h \
- qnxdevicetester.h
+ blackberrysigningutils.h \
+ qnxdevicetester.h \
+ blackberryconfigurationmanager.h \
+ blackberrydevicelistdetector.h \
+ blackberrylogprocessrunner.h \
+ qnxdeviceprocesssignaloperation.h \
+ qnxdeviceprocesslist.h
FORMS += \
blackberrydeviceconfigurationwizardsetuppage.ui \
blackberryrunconfigurationwidget.ui \
- blackberrydeviceconfigurationwizardsshkeypage.ui \
blackberrydeployconfigurationwidget.ui \
blackberrydeviceconfigurationwidget.ui \
qnxbaseqtconfigwidget.ui \
blackberryndksettingswidget.ui \
blackberrykeyswidget.ui \
- blackberryregisterkeydialog.ui \
blackberryimportcertificatedialog.ui \
blackberrycreatecertificatedialog.ui \
blackberrydebugtokenrequestdialog.ui \
@@ -211,8 +211,11 @@ FORMS += \
bardescriptoreditorenvironmentwidget.ui \
bardescriptoreditorassetswidget.ui \
blackberrysetupwizardkeyspage.ui \
+ blackberrysetupwizardcertificatepage.ui \
blackberrysetupwizarddevicepage.ui \
- blackberrysetupwizardfinishpage.ui
+ blackberrysetupwizardfinishpage.ui \
+ blackberrydeviceconfigurationwizardconfigpage.ui \
+ blackberrydeviceconfigurationwizardquerypage.ui
include(../../private_headers.pri)
diff --git a/src/plugins/qnx/qnx.qbs b/src/plugins/qnx/qnx.qbs
index 77b34507d0..71e00e9a18 100644
--- a/src/plugins/qnx/qnx.qbs
+++ b/src/plugins/qnx/qnx.qbs
@@ -9,6 +9,7 @@ QtcPlugin {
Depends { name: "Core" }
Depends { name: "Debugger" }
Depends { name: "ProjectExplorer" }
+ Depends { name: "QmlDebug" }
Depends { name: "QtSupport" }
Depends { name: "Qt4ProjectManager" }
Depends { name: "RemoteLinux" }
@@ -16,8 +17,6 @@ QtcPlugin {
Depends { name: "QmlDebug" }
Depends { name: "Qt"; submodules: ["widgets", "xml", "network"] }
- cpp.includePaths: base.concat("../../shared")
-
files: [
"bardescriptordocument.cpp",
"bardescriptordocument.h",
@@ -66,6 +65,8 @@ QtcPlugin {
"blackberrycheckdevmodestepconfigwidget.h",
"blackberrycheckdevmodestepfactory.cpp",
"blackberrycheckdevmodestepfactory.h",
+ "blackberryconfigurationmanager.cpp",
+ "blackberryconfigurationmanager.h",
"blackberrycreatepackagestep.cpp",
"blackberrycreatepackagestep.h",
"blackberrycreatepackagestepconfigwidget.cpp",
@@ -103,16 +104,19 @@ QtcPlugin {
"blackberrydeviceconfigurationwidget.ui",
"blackberrydeviceconfigurationwizard.cpp",
"blackberrydeviceconfigurationwizard.h",
+ "blackberrydeviceconfigurationwizardconfigpage.ui",
"blackberrydeviceconfigurationwizardpages.cpp",
"blackberrydeviceconfigurationwizardpages.h",
+ "blackberrydeviceconfigurationwizardquerypage.ui",
"blackberrydeviceconfigurationwizardsetuppage.ui",
- "blackberrydeviceconfigurationwizardsshkeypage.ui",
"blackberrydeviceconnection.cpp",
"blackberrydeviceconnection.h",
"blackberrydeviceconnectionmanager.cpp",
"blackberrydeviceconnectionmanager.h",
- "blackberrydeviceprocesssupport.h",
- "blackberrydeviceprocesssupport.cpp",
+ "blackberrydevicelistdetector.cpp",
+ "blackberrydevicelistdetector.h",
+ "blackberrylogprocessrunner.cpp",
+ "blackberrylogprocessrunner.h",
"blackberryqtversion.cpp",
"blackberryqtversion.h",
"blackberryqtversionfactory.cpp",
@@ -140,8 +144,6 @@ QtcPlugin {
"blackberryndksettingspage.h",
"blackberryconfiguration.cpp",
"blackberryconfiguration.h",
- "blackberrycsjregistrar.cpp",
- "blackberrycsjregistrar.h",
"blackberrycertificate.cpp",
"blackberrycertificate.h",
"blackberrykeyspage.cpp",
@@ -149,11 +151,6 @@ QtcPlugin {
"blackberrykeyswidget.cpp",
"blackberrykeyswidget.h",
"blackberrykeyswidget.ui",
- "blackberrycertificatemodel.cpp",
- "blackberrycertificatemodel.h",
- "blackberryregisterkeydialog.cpp",
- "blackberryregisterkeydialog.h",
- "blackberryregisterkeydialog.ui",
"blackberryimportcertificatedialog.cpp",
"blackberryimportcertificatedialog.h",
"blackberryimportcertificatedialog.ui",
@@ -176,10 +173,11 @@ QtcPlugin {
"blackberrysetupwizardpages.cpp",
"blackberrysetupwizardpages.h",
"blackberrysetupwizardkeyspage.ui",
+ "blackberrysetupwizardcertificatepage.ui",
"blackberrysetupwizarddevicepage.ui",
"blackberrysetupwizardfinishpage.ui",
- "blackberryutils.cpp",
- "blackberryutils.h",
+ "blackberrysigningutils.cpp",
+ "blackberrysigningutils.h",
"pathchooserdelegate.cpp",
"pathchooserdelegate.h",
"qnx.qrc",
@@ -209,6 +207,10 @@ QtcPlugin {
"qnxdeviceconfigurationwizard.h",
"qnxdeviceconfigurationwizardpages.cpp",
"qnxdeviceconfigurationwizardpages.h",
+ "qnxdeviceprocesslist.cpp",
+ "qnxdeviceprocesslist.h",
+ "qnxdeviceprocesssignaloperation.cpp",
+ "qnxdeviceprocesssignaloperation.h",
"qnxdevicetester.cpp",
"qnxdevicetester.h",
"qnxplugin.cpp",
diff --git a/src/plugins/qnx/qnxabstractrunsupport.cpp b/src/plugins/qnx/qnxabstractrunsupport.cpp
index cb97aa36f9..151dc8f0fd 100644
--- a/src/plugins/qnx/qnxabstractrunsupport.cpp
+++ b/src/plugins/qnx/qnxabstractrunsupport.cpp
@@ -46,9 +46,10 @@ using namespace Qnx::Internal;
QnxAbstractRunSupport::QnxAbstractRunSupport(QnxRunConfiguration *runConfig, QObject *parent)
: QObject(parent)
, m_remoteExecutable(runConfig->remoteExecutableFilePath())
- , m_commandPrefix(runConfig->commandPrefix())
, m_device(DeviceKitInformation::device(runConfig->target()->kit()))
, m_state(Inactive)
+ , m_environment(runConfig->environment())
+ , m_workingDir(runConfig->workingDirectory())
{
m_runner = new DeviceApplicationRunner(this);
m_portsGatherer = new DeviceUsedPortsGatherer(this);
@@ -84,7 +85,7 @@ void QnxAbstractRunSupport::handleRemoteProcessFinished(bool)
void QnxAbstractRunSupport::setFinished()
{
if (m_state != GatheringPorts && m_state != Inactive)
- m_runner->stop(m_device->processSupport()->killProcessByNameCommandLine(executable()).toUtf8());
+ m_runner->stop();
m_state = Inactive;
}
@@ -104,11 +105,6 @@ DeviceApplicationRunner *QnxAbstractRunSupport::appRunner() const
return m_runner;
}
-QString QnxAbstractRunSupport::commandPrefix() const
-{
- return m_commandPrefix;
-}
-
const IDevice::ConstPtr QnxAbstractRunSupport::device() const
{
return m_device;
diff --git a/src/plugins/qnx/qnxabstractrunsupport.h b/src/plugins/qnx/qnxabstractrunsupport.h
index 1e37059774..73650283de 100644
--- a/src/plugins/qnx/qnxabstractrunsupport.h
+++ b/src/plugins/qnx/qnxabstractrunsupport.h
@@ -31,6 +31,7 @@
#define QNXABSTRACTRUNSUPPORT_H
#include <projectexplorer/devicesupport/idevice.h>
+#include <utils/environment.h>
#include <utils/portlist.h>
#include <QObject>
@@ -64,6 +65,8 @@ protected:
virtual void startExecution() = 0;
virtual QString executable() const;
+ Utils::Environment environment() const { return m_environment; }
+ QString workingDirectory() const { return m_workingDir; }
void setFinished();
@@ -71,7 +74,6 @@ protected:
void setState(State state);
ProjectExplorer::DeviceApplicationRunner *appRunner() const;
- QString commandPrefix() const;
const ProjectExplorer::IDevice::ConstPtr device() const;
protected slots:
@@ -90,10 +92,11 @@ private:
ProjectExplorer::DeviceUsedPortsGatherer * m_portsGatherer;
Utils::PortList m_portList;
const QString m_remoteExecutable;
- const QString m_commandPrefix;
ProjectExplorer::IDevice::ConstPtr m_device;
ProjectExplorer::DeviceApplicationRunner *m_runner;
State m_state;
+ Utils::Environment m_environment;
+ QString m_workingDir;
};
} // namespace Internal
diff --git a/src/plugins/qnx/qnxanalyzesupport.cpp b/src/plugins/qnx/qnxanalyzesupport.cpp
index 0605d02579..fe9caf70bf 100644
--- a/src/plugins/qnx/qnxanalyzesupport.cpp
+++ b/src/plugins/qnx/qnxanalyzesupport.cpp
@@ -29,11 +29,12 @@
#include "qnxanalyzesupport.h"
-#include <analyzerbase/ianalyzerengine.h>
+#include <analyzerbase/analyzerruncontrol.h>
#include <analyzerbase/analyzerstartparameters.h>
#include <projectexplorer/devicesupport/deviceapplicationrunner.h>
#include <utils/qtcassert.h>
+#include <utils/qtcprocess.h>
using namespace ProjectExplorer;
@@ -41,9 +42,9 @@ using namespace Qnx;
using namespace Qnx::Internal;
QnxAnalyzeSupport::QnxAnalyzeSupport(QnxRunConfiguration *runConfig,
- Analyzer::IAnalyzerEngine *engine)
- : QnxAbstractRunSupport(runConfig, engine)
- , m_engine(engine)
+ Analyzer::AnalyzerRunControl *runControl)
+ : QnxAbstractRunSupport(runConfig, runControl)
+ , m_runControl(runControl)
, m_qmlPort(-1)
{
const DeviceApplicationRunner *runner = appRunner();
@@ -54,7 +55,7 @@ QnxAnalyzeSupport::QnxAnalyzeSupport(QnxRunConfiguration *runConfig,
connect(runner, SIGNAL(remoteStdout(QByteArray)), SLOT(handleRemoteOutput(QByteArray)));
connect(runner, SIGNAL(remoteStderr(QByteArray)), SLOT(handleRemoteOutput(QByteArray)));
- connect(m_engine, SIGNAL(starting(const Analyzer::IAnalyzerEngine*)),
+ connect(m_runControl, SIGNAL(starting(const Analyzer::AnalyzerRunControl*)),
SLOT(handleAdapterSetupRequested()));
connect(&m_outputParser, SIGNAL(waitingForConnectionOnPort(quint16)),
SLOT(remoteIsRunning()));
@@ -78,21 +79,23 @@ void QnxAnalyzeSupport::startExecution()
setState(StartingRemoteProcess);
- const QString args = m_engine->startParameters().debuggeeArgs +
- QString::fromLatin1(" -qmljsdebugger=port:%1,block").arg(m_qmlPort);
- const QString command = QString::fromLatin1("%1 %2 %3").arg(commandPrefix(), executable(), args);
- appRunner()->start(device(), command.toUtf8());
+ const QStringList args = QStringList()
+ << Utils::QtcProcess::splitArgs(m_runControl->startParameters().debuggeeArgs)
+ << QString::fromLatin1("-qmljsdebugger=port:%1,block").arg(m_qmlPort);
+ appRunner()->setEnvironment(environment());
+ appRunner()->setWorkingDirectory(workingDirectory());
+ appRunner()->start(device(), executable(), args);
}
void QnxAnalyzeSupport::handleRemoteProcessFinished(bool success)
{
- if (m_engine || state() == Inactive)
+ if (m_runControl || state() == Inactive)
return;
if (!success)
showMessage(tr("The %1 process closed unexpectedly.").arg(executable()),
Utils::NormalMessageFormat);
- m_engine->notifyRemoteFinished(success);
+ m_runControl->notifyRemoteFinished(success);
}
void QnxAnalyzeSupport::handleProfilingFinished()
@@ -124,13 +127,13 @@ void QnxAnalyzeSupport::handleError(const QString &error)
void QnxAnalyzeSupport::remoteIsRunning()
{
- if (m_engine)
- m_engine->notifyRemoteSetupDone(m_qmlPort);
+ if (m_runControl)
+ m_runControl->notifyRemoteSetupDone(m_qmlPort);
}
void QnxAnalyzeSupport::showMessage(const QString &msg, Utils::OutputFormat format)
{
- if (state() != Inactive && m_engine)
- m_engine->logApplicationMessage(msg, format);
+ if (state() != Inactive && m_runControl)
+ m_runControl->logApplicationMessage(msg, format);
m_outputParser.processOutput(msg);
}
diff --git a/src/plugins/qnx/qnxanalyzesupport.h b/src/plugins/qnx/qnxanalyzesupport.h
index 69aa813ad8..686b61848b 100644
--- a/src/plugins/qnx/qnxanalyzesupport.h
+++ b/src/plugins/qnx/qnxanalyzesupport.h
@@ -36,7 +36,7 @@
#include <utils/outputformat.h>
#include <qmldebug/qmloutputparser.h>
-namespace Analyzer { class IAnalyzerEngine; }
+namespace Analyzer { class AnalyzerRunControl; }
namespace Qnx {
namespace Internal {
@@ -47,7 +47,7 @@ class QnxAnalyzeSupport : public QnxAbstractRunSupport
{
Q_OBJECT
public:
- QnxAnalyzeSupport(QnxRunConfiguration *runConfig, Analyzer::IAnalyzerEngine *engine);
+ QnxAnalyzeSupport(QnxRunConfiguration *runConfig, Analyzer::AnalyzerRunControl *engine);
public slots:
void handleProfilingFinished();
@@ -66,7 +66,7 @@ private:
void startExecution();
void showMessage(const QString &, Utils::OutputFormat);
- Analyzer::IAnalyzerEngine *m_engine;
+ Analyzer::AnalyzerRunControl *m_runControl;
QmlDebug::QmlOutputParser m_outputParser;
int m_qmlPort;
};
diff --git a/src/plugins/qnx/qnxdebugsupport.cpp b/src/plugins/qnx/qnxdebugsupport.cpp
index 7b76080fc7..02049fbf62 100644
--- a/src/plugins/qnx/qnxdebugsupport.cpp
+++ b/src/plugins/qnx/qnxdebugsupport.cpp
@@ -41,6 +41,7 @@
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/target.h>
#include <utils/qtcassert.h>
+#include <utils/qtcprocess.h>
using namespace ProjectExplorer;
using namespace RemoteLinux;
@@ -91,15 +92,14 @@ void QnxDebugSupport::startExecution()
if (m_useQmlDebugger)
m_engine->startParameters().processArgs += QString::fromLocal8Bit(" -qmljsdebugger=port:%1,block").arg(m_qmlPort);
- QString remoteCommandLine;
+ QStringList arguments;
if (m_useCppDebugger)
- remoteCommandLine = QString::fromLatin1("%1 %2 %3")
- .arg(commandPrefix(), executable()).arg(m_pdebugPort);
+ arguments << QString::number(m_pdebugPort);
else if (m_useQmlDebugger && !m_useCppDebugger)
- remoteCommandLine = QString::fromLatin1("%1 %2 %3")
- .arg(commandPrefix(), executable(), m_engine->startParameters().processArgs);
-
- appRunner()->start(device(), remoteCommandLine.toUtf8());
+ arguments = Utils::QtcProcess::splitArgs(m_engine->startParameters().processArgs);
+ appRunner()->setEnvironment(environment());
+ appRunner()->setWorkingDirectory(workingDirectory());
+ appRunner()->start(device(), executable(), arguments);
}
void QnxDebugSupport::handleRemoteProcessStarted()
diff --git a/src/plugins/qnx/qnxdeviceconfiguration.cpp b/src/plugins/qnx/qnxdeviceconfiguration.cpp
index 7fb16988a6..74559f3750 100644
--- a/src/plugins/qnx/qnxdeviceconfiguration.cpp
+++ b/src/plugins/qnx/qnxdeviceconfiguration.cpp
@@ -31,8 +31,10 @@
#include "qnxdeviceconfiguration.h"
#include "qnxdevicetester.h"
+#include "qnxdeviceprocesslist.h"
+#include "qnxdeviceprocesssignaloperation.h"
-#include <projectexplorer/devicesupport/sshdeviceprocesslist.h>
+#include <ssh/sshconnection.h>
#include <QRegExp>
#include <QStringList>
@@ -40,19 +42,6 @@
using namespace Qnx;
using namespace Qnx::Internal;
-class QnxDeviceProcessSupport : public RemoteLinux::LinuxDeviceProcessSupport
-{
- QString killProcessByNameCommandLine(const QString &filePath) const
- {
- QString executable = filePath;
- return QString::fromLatin1("for PID in $(ps -f -o pid,comm | grep %1 | awk '/%1/ {print $1}'); "
- "do "
- "kill $PID; sleep 1; kill -9 $PID; "
- "done").arg(executable.replace(QLatin1String("/"), QLatin1String("\\/")));
- }
-};
-
-
class QnxPortsGatheringMethod : public ProjectExplorer::PortsGatheringMethod
{
// TODO: The command is probably needlessly complicated because the parsing method
@@ -91,51 +80,6 @@ class QnxPortsGatheringMethod : public ProjectExplorer::PortsGatheringMethod
}
};
-class QnxDeviceProcessList : public ProjectExplorer::SshDeviceProcessList
-{
-public:
- QnxDeviceProcessList(const ProjectExplorer::IDevice::ConstPtr &device, QObject *parent)
- : SshDeviceProcessList(device, parent)
- {
- }
-
-private:
- QString listProcessesCommandLine() const
- {
- return QLatin1String("pidin -F \"%a %A '/%n'\"");
- }
-
- QList<ProjectExplorer::DeviceProcess> buildProcessList(const QString &listProcessesReply) const
- {
- QList<ProjectExplorer::DeviceProcess> processes;
- QStringList lines = listProcessesReply.split(QLatin1Char('\n'));
- if (lines.isEmpty())
- return processes;
-
- lines.pop_front(); // drop headers
- QRegExp re(QLatin1String("\\s*(\\d+)\\s+(.*)'(.*)'"));
-
- foreach (const QString& line, lines) {
- if (re.exactMatch(line)) {
- const QStringList captures = re.capturedTexts();
- if (captures.size() == 4) {
- const int pid = captures[1].toInt();
- const QString args = captures[2];
- const QString exe = captures[3];
- ProjectExplorer::DeviceProcess deviceProcess;
- deviceProcess.pid = pid;
- deviceProcess.exe = exe.trimmed();
- deviceProcess.cmdLine = args.trimmed();
- processes.append(deviceProcess);
- }
- }
- }
-
- qSort(processes);
- return processes;
- }
-};
-
QnxDeviceConfiguration::QnxDeviceConfiguration()
: RemoteLinux::LinuxDevice()
{
@@ -172,11 +116,6 @@ ProjectExplorer::IDevice::Ptr QnxDeviceConfiguration::clone() const
return Ptr(new QnxDeviceConfiguration(*this));
}
-ProjectExplorer::DeviceProcessSupport::Ptr QnxDeviceConfiguration::processSupport() const
-{
- return ProjectExplorer::DeviceProcessSupport::Ptr(new QnxDeviceProcessSupport);
-}
-
ProjectExplorer::PortsGatheringMethod::Ptr QnxDeviceConfiguration::portsGatheringMethod() const
{
return ProjectExplorer::PortsGatheringMethod::Ptr(new QnxPortsGatheringMethod);
@@ -187,7 +126,13 @@ ProjectExplorer::DeviceProcessList *QnxDeviceConfiguration::createProcessListMod
return new QnxDeviceProcessList(sharedFromThis(), parent);
}
-RemoteLinux::AbstractLinuxDeviceTester *QnxDeviceConfiguration::createDeviceTester() const
+ProjectExplorer::DeviceTester *QnxDeviceConfiguration::createDeviceTester() const
{
return new QnxDeviceTester;
}
+
+ProjectExplorer::DeviceProcessSignalOperation::Ptr QnxDeviceConfiguration::signalOperation() const
+{
+ return ProjectExplorer::DeviceProcessSignalOperation::Ptr(
+ new QnxDeviceProcessSignalOperation(sshParameters()));
+}
diff --git a/src/plugins/qnx/qnxdeviceconfiguration.h b/src/plugins/qnx/qnxdeviceconfiguration.h
index 1e2a9d0aef..bf713a0f92 100644
--- a/src/plugins/qnx/qnxdeviceconfiguration.h
+++ b/src/plugins/qnx/qnxdeviceconfiguration.h
@@ -50,11 +50,11 @@ public:
Origin origin = ManuallyAdded, Core::Id id = Core::Id());
ProjectExplorer::IDevice::Ptr clone() const;
- ProjectExplorer::DeviceProcessSupport::Ptr processSupport() const;
ProjectExplorer::PortsGatheringMethod::Ptr portsGatheringMethod() const;
ProjectExplorer::DeviceProcessList *createProcessListModel(QObject *parent) const;
+ ProjectExplorer::DeviceProcessSignalOperation::Ptr signalOperation() const;
- RemoteLinux::AbstractLinuxDeviceTester *createDeviceTester() const;
+ ProjectExplorer::DeviceTester *createDeviceTester() const;
QString displayType() const;
@@ -63,6 +63,10 @@ protected:
QnxDeviceConfiguration(const QString &name, Core::Id type, MachineType machineType,
Origin origin, Core::Id id);
QnxDeviceConfiguration(const QnxDeviceConfiguration &other);
+
+ QString interruptProcessByNameCommandLine(const QString &filePath) const;
+ QString killProcessByNameCommandLine(const QString &filePath) const;
+
};
} // namespace Internal
diff --git a/src/plugins/qnx/qnxdeviceconfigurationwizard.cpp b/src/plugins/qnx/qnxdeviceconfigurationwizard.cpp
index c14d69530c..01ef63389d 100644
--- a/src/plugins/qnx/qnxdeviceconfigurationwizard.cpp
+++ b/src/plugins/qnx/qnxdeviceconfigurationwizard.cpp
@@ -37,7 +37,6 @@
#include <projectexplorer/devicesupport/deviceusedportsgatherer.h>
#include <remotelinux/genericlinuxdeviceconfigurationwizardpages.h>
-#include <remotelinux/linuxdevicetestdialog.h>
#include <utils/portlist.h>
using namespace ProjectExplorer;
@@ -66,7 +65,7 @@ IDevice::Ptr QnxDeviceConfigurationWizard::device()
sshParams.port = 22;
sshParams.timeout = 10;
sshParams.authenticationType = m_setupPage->authenticationType();
- if (sshParams.authenticationType == QSsh::SshConnectionParameters::AuthenticationByPassword)
+ if (sshParams.authenticationType == QSsh::SshConnectionParameters::AuthenticationTypePassword)
sshParams.password = m_setupPage->password();
else
sshParams.privateKeyFile = m_setupPage->privateKeyFilePath();
@@ -76,8 +75,5 @@ IDevice::Ptr QnxDeviceConfigurationWizard::device()
device->setSshParameters(sshParams);
device->setFreePorts(Utils::PortList::fromString(QLatin1String("10000-10100")));
- RemoteLinux::LinuxDeviceTestDialog dlg(device, device->createDeviceTester(), this);
- dlg.exec();
-
return device;
}
diff --git a/src/plugins/qnx/qnxdeviceprocesslist.cpp b/src/plugins/qnx/qnxdeviceprocesslist.cpp
new file mode 100644
index 0000000000..7e5f5bfb8f
--- /dev/null
+++ b/src/plugins/qnx/qnxdeviceprocesslist.cpp
@@ -0,0 +1,80 @@
+/**************************************************************************
+**
+** Copyright (C) 2013 BlackBerry Limited. All rights reserved.
+**
+** Contact: BlackBerry Limited (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 "qnxdeviceprocesslist.h"
+
+#include <QRegExp>
+#include <QStringList>
+
+using namespace Qnx;
+using namespace Qnx::Internal;
+
+QnxDeviceProcessList::QnxDeviceProcessList(
+ const ProjectExplorer::IDevice::ConstPtr &device, QObject *parent)
+ : ProjectExplorer::SshDeviceProcessList(device, parent)
+{
+}
+
+QString QnxDeviceProcessList::listProcessesCommandLine() const
+{
+ return QLatin1String("pidin -F \"%a %A '/%n'\"");
+}
+
+QList<ProjectExplorer::DeviceProcessItem> QnxDeviceProcessList::buildProcessList(
+ const QString &listProcessesReply) const
+{
+ QList<ProjectExplorer::DeviceProcessItem> processes;
+ QStringList lines = listProcessesReply.split(QLatin1Char('\n'));
+ if (lines.isEmpty())
+ return processes;
+
+ lines.pop_front(); // drop headers
+ QRegExp re(QLatin1String("\\s*(\\d+)\\s+(.*)'(.*)'"));
+
+ foreach (const QString& line, lines) {
+ if (re.exactMatch(line)) {
+ const QStringList captures = re.capturedTexts();
+ if (captures.size() == 4) {
+ const int pid = captures[1].toInt();
+ const QString args = captures[2];
+ const QString exe = captures[3];
+ ProjectExplorer::DeviceProcessItem deviceProcess;
+ deviceProcess.pid = pid;
+ deviceProcess.exe = exe.trimmed();
+ deviceProcess.cmdLine = args.trimmed();
+ processes.append(deviceProcess);
+ }
+ }
+ }
+
+ qSort(processes);
+ return processes;
+}
diff --git a/src/plugins/qnx/qnxdeviceprocesslist.h b/src/plugins/qnx/qnxdeviceprocesslist.h
new file mode 100644
index 0000000000..7885daed3a
--- /dev/null
+++ b/src/plugins/qnx/qnxdeviceprocesslist.h
@@ -0,0 +1,57 @@
+/**************************************************************************
+**
+** Copyright (C) 2013 BlackBerry Limited. All rights reserved.
+**
+** Contact: BlackBerry Limited (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_QNXDEVICEPROCESSLIST_H
+#define QNX_INTERNAL_QNXDEVICEPROCESSLIST_H
+
+#include <projectexplorer/devicesupport/idevice.h>
+#include <projectexplorer/devicesupport/sshdeviceprocesslist.h>
+
+namespace Qnx {
+namespace Internal {
+
+class QnxDeviceProcessList : public ProjectExplorer::SshDeviceProcessList
+{
+ Q_OBJECT
+public:
+ explicit QnxDeviceProcessList(
+ const ProjectExplorer::IDevice::ConstPtr &device, QObject *parent = 0);
+
+private:
+ virtual QString listProcessesCommandLine() const;
+ virtual QList<ProjectExplorer::DeviceProcessItem> buildProcessList(
+ const QString &listProcessesReply) const;
+};
+
+} // namespace Internal
+} // namespace Qnx
+
+#endif // QNX_INTERNAL_QNXDEVICEPROCESSLIST_H
diff --git a/src/plugins/qnx/qnxdeviceprocesssignaloperation.cpp b/src/plugins/qnx/qnxdeviceprocesssignaloperation.cpp
new file mode 100644
index 0000000000..afbb79d125
--- /dev/null
+++ b/src/plugins/qnx/qnxdeviceprocesssignaloperation.cpp
@@ -0,0 +1,90 @@
+/**************************************************************************
+**
+** 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 "qnxdeviceprocesssignaloperation.h"
+
+using namespace Qnx;
+using namespace Qnx::Internal;
+
+QnxDeviceProcessSignalOperation::QnxDeviceProcessSignalOperation(
+ const QSsh::SshConnectionParameters sshParameters)
+ : RemoteLinux::RemoteLinuxSignalOperation(sshParameters)
+{
+}
+
+static QString signalProcessByNameBlackBerryCommandLine(const QString &filePath, int sig)
+{
+ QString executable = filePath;
+ return QString::fromLatin1("for PID in $(pidin -F \"%a %A\" | grep \"%1\" | awk '/%1/ {print $1}'); "
+ "do "
+ "kill -%2 $PID; "
+ "done").arg(executable.replace(QLatin1String("/"), QLatin1String("\\/"))).arg(sig);
+}
+
+QString QnxDeviceProcessSignalOperation::killProcessByNameCommandLine(
+ const QString &filePath) const
+{
+ return QString::fromLatin1("%1; %2").arg(signalProcessByNameBlackBerryCommandLine(filePath, 15),
+ signalProcessByNameBlackBerryCommandLine(filePath, 9));
+}
+
+QString QnxDeviceProcessSignalOperation::interruptProcessByNameCommandLine(
+ const QString &filePath) const
+{
+ return signalProcessByNameBlackBerryCommandLine(filePath, 2);
+}
+
+
+BlackBerryDeviceProcessSignalOperation::BlackBerryDeviceProcessSignalOperation(
+ const QSsh::SshConnectionParameters sshParameters)
+ : RemoteLinux::RemoteLinuxSignalOperation(sshParameters)
+{
+}
+
+static QString signalProcessByNameQnxCommandLine(const QString &filePath, int sig)
+{
+ QString executable = filePath;
+ return QString::fromLatin1("for PID in $(ps -f -o pid,comm | grep %1 | awk '/%1/ {print $1}'); "
+ "do "
+ "kill -%2 $PID; "
+ "done").arg(executable.replace(QLatin1String("/"), QLatin1String("\\/"))).arg(sig);
+}
+
+QString BlackBerryDeviceProcessSignalOperation::killProcessByNameCommandLine(const QString &filePath) const
+{
+ return QString::fromLatin1("%1; %2").arg(signalProcessByNameQnxCommandLine(filePath, 15),
+ signalProcessByNameQnxCommandLine(filePath, 9));
+}
+
+QString BlackBerryDeviceProcessSignalOperation::interruptProcessByNameCommandLine(const QString &filePath) const
+{
+ return signalProcessByNameQnxCommandLine(filePath, 2);
+}
diff --git a/src/plugins/qnx/blackberryutils.cpp b/src/plugins/qnx/qnxdeviceprocesssignaloperation.h
index dd85493c44..a3e86c8ad2 100644
--- a/src/plugins/qnx/blackberryutils.cpp
+++ b/src/plugins/qnx/qnxdeviceprocesssignaloperation.h
@@ -29,54 +29,41 @@
**
****************************************************************************/
-#include "blackberryutils.h"
-#include "blackberryconfiguration.h"
+#ifndef QNXDEVICEPROCESSSIGNALOPERATION_H
+#define QNXDEVICEPROCESSSIGNALOPERATION_H
-#include <QFileInfo>
-#include <QString>
-#include <QFile>
-#include <QTextStream>
+#include <remotelinux/remotelinuxsignaloperation.h>
-using namespace Qnx::Internal;
+namespace Qnx {
+namespace Internal {
-bool BlackBerryUtils::hasRegisteredKeys()
+class QnxDeviceProcessSignalOperation : public RemoteLinux::RemoteLinuxSignalOperation
{
- BlackBerryConfiguration &configuration = BlackBerryConfiguration::instance();
+ Q_OBJECT
+protected:
+ explicit QnxDeviceProcessSignalOperation(const QSsh::SshConnectionParameters sshParameters);
- QFileInfo cskFile(configuration.barsignerCskPath());
+private:
+ QString killProcessByNameCommandLine(const QString &filePath) const;
+ QString interruptProcessByNameCommandLine(const QString &filePath) const;
- if (!cskFile.exists())
- return false;
+ friend class QnxDeviceConfiguration;
+};
- QFileInfo dbFile(configuration.barsignerDbPath());
-
- if (!dbFile.exists())
- return false;
-
- return true;
-}
-
-QString BlackBerryUtils::getCsjAuthor(const QString &fileName)
+class BlackBerryDeviceProcessSignalOperation : public RemoteLinux::RemoteLinuxSignalOperation
{
- QFile file(fileName);
-
- QString author = QLatin1String("Unknown Author");
-
- if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
- return author;
-
- QTextStream stream(&file);
+ Q_OBJECT
+protected:
+ explicit BlackBerryDeviceProcessSignalOperation(const QSsh::SshConnectionParameters sshParameters);
- while (!stream.atEnd()) {
- QString line = stream.readLine();
+private:
+ QString killProcessByNameCommandLine(const QString &filePath) const;
+ QString interruptProcessByNameCommandLine(const QString &filePath) const;
- if (line.startsWith(QLatin1String("Company="))) {
- author = line.remove(QLatin1String("Company=")).trimmed();
- break;
- }
- }
+ friend class BlackBerryDeviceConfiguration;
+};
- file.close();
+} // namespace Internal
+} // namespace Qnx
- return author;
-}
+#endif // QNXDEVICEPROCESSSIGNALOPERATION_H
diff --git a/src/plugins/qnx/qnxdevicetester.cpp b/src/plugins/qnx/qnxdevicetester.cpp
index c7ce356483..72dd95c582 100644
--- a/src/plugins/qnx/qnxdevicetester.cpp
+++ b/src/plugins/qnx/qnxdevicetester.cpp
@@ -38,7 +38,7 @@ using namespace Qnx;
using namespace Qnx::Internal;
QnxDeviceTester::QnxDeviceTester(QObject *parent)
- : RemoteLinux::AbstractLinuxDeviceTester(parent)
+ : ProjectExplorer::DeviceTester(parent)
, m_result(TestSuccess)
, m_state(Inactive)
, m_currentCommandIndex(-1)
@@ -70,8 +70,8 @@ void QnxDeviceTester::testDevice(const ProjectExplorer::IDevice::ConstPtr &devic
connect(m_genericTester, SIGNAL(progressMessage(QString)), SIGNAL(progressMessage(QString)));
connect(m_genericTester, SIGNAL(errorMessage(QString)), SIGNAL(errorMessage(QString)));
- connect(m_genericTester, SIGNAL(finished(RemoteLinux::AbstractLinuxDeviceTester::TestResult)),
- SLOT(handleGenericTestFinished(RemoteLinux::AbstractLinuxDeviceTester::TestResult)));
+ connect(m_genericTester, SIGNAL(finished(ProjectExplorer::DeviceTester::TestResult)),
+ SLOT(handleGenericTestFinished(ProjectExplorer::DeviceTester::TestResult)));
m_state = GenericTest;
m_genericTester->testDevice(deviceConfiguration);
@@ -96,7 +96,7 @@ void QnxDeviceTester::stopTest()
setFinished();
}
-void QnxDeviceTester::handleGenericTestFinished(RemoteLinux::AbstractLinuxDeviceTester::TestResult result)
+void QnxDeviceTester::handleGenericTestFinished(TestResult result)
{
QTC_ASSERT(m_state == GenericTest, return);
diff --git a/src/plugins/qnx/qnxdevicetester.h b/src/plugins/qnx/qnxdevicetester.h
index ccec636f08..e3bff15a79 100644
--- a/src/plugins/qnx/qnxdevicetester.h
+++ b/src/plugins/qnx/qnxdevicetester.h
@@ -43,7 +43,7 @@ class SshRemoteProcessRunner;
namespace Qnx {
namespace Internal {
-class QnxDeviceTester : public RemoteLinux::AbstractLinuxDeviceTester
+class QnxDeviceTester : public ProjectExplorer::DeviceTester
{
Q_OBJECT
public:
@@ -53,7 +53,7 @@ public:
void stopTest();
private slots:
- void handleGenericTestFinished(RemoteLinux::AbstractLinuxDeviceTester::TestResult result);
+ void handleGenericTestFinished(ProjectExplorer::DeviceTester::TestResult result);
void handleProcessFinished(int exitStatus);
void handleConnectionError();
@@ -70,7 +70,7 @@ private:
RemoteLinux::GenericLinuxDeviceTester *m_genericTester;
ProjectExplorer::IDevice::ConstPtr m_deviceConfiguration;
- TestResult m_result;
+ ProjectExplorer::DeviceTester::TestResult m_result;
State m_state;
int m_currentCommandIndex;
diff --git a/src/plugins/qnx/qnxplugin.cpp b/src/plugins/qnx/qnxplugin.cpp
index 12cf97ebc9..26098b43b9 100644
--- a/src/plugins/qnx/qnxplugin.cpp
+++ b/src/plugins/qnx/qnxplugin.cpp
@@ -51,11 +51,13 @@
#include "blackberrykeyspage.h"
#include "blackberrycheckdevmodestepfactory.h"
#include "blackberrydeviceconnectionmanager.h"
+#include "blackberryconfigurationmanager.h"
#include <coreplugin/icore.h>
#include <coreplugin/mimedatabase.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/taskhub.h>
+#include <projectexplorer/kitmanager.h>
#include <QtPlugin>
@@ -68,6 +70,7 @@ QNXPlugin::QNXPlugin()
QNXPlugin::~QNXPlugin()
{
delete BlackBerryDeviceConnectionManager::instance();
+ delete &BlackBerryConfigurationManager::instance();
}
bool QNXPlugin::initialize(const QStringList &arguments, QString *errorString)
@@ -105,19 +108,21 @@ bool QNXPlugin::initialize(const QStringList &arguments, QString *errorString)
barDescriptorMimeType.addMagicMatcher(QSharedPointer<Core::IMagicMatcher>(new BarDescriptorMagicMatcher));
barDescriptorMimeType.setSubClassesOf(QStringList() << QLatin1String("application/xml"));
- if (!Core::ICore::mimeDatabase()->addMimeType(barDescriptorMimeType)) {
+ if (!Core::MimeDatabase::addMimeType(barDescriptorMimeType)) {
*errorString = tr("Could not add mime-type for bar-descriptor.xml editor.");
return false;
}
addAutoReleasedObject(new BarDescriptorEditorFactory);
+ connect(ProjectExplorer::KitManager::instance(), SIGNAL(kitsLoaded()), &BlackBerryConfigurationManager::instance(), SLOT(loadSettings()));
+
return true;
}
void QNXPlugin::extensionsInitialized()
{
- ProjectExplorer::ProjectExplorerPlugin::instance()->taskHub()->addCategory(Constants::QNX_TASK_CATEGORY_BARDESCRIPTOR,
- tr("Bar Descriptor"));
+ ProjectExplorer::TaskHub::addCategory(Constants::QNX_TASK_CATEGORY_BARDESCRIPTOR,
+ tr("Bar Descriptor"));
}
ExtensionSystem::IPlugin::ShutdownFlag QNXPlugin::aboutToShutdown()
diff --git a/src/plugins/qnx/qnxrunconfiguration.cpp b/src/plugins/qnx/qnxrunconfiguration.cpp
index 277bcfe6e1..2f5f2c3074 100644
--- a/src/plugins/qnx/qnxrunconfiguration.cpp
+++ b/src/plugins/qnx/qnxrunconfiguration.cpp
@@ -33,6 +33,7 @@
#include "qnxconstants.h"
#include <remotelinux/remotelinuxrunconfigurationwidget.h>
+#include <utils/environment.h>
#include <QLabel>
#include <QLineEdit>
@@ -60,22 +61,14 @@ void QnxRunConfiguration::setQtLibPath(const QString &path)
m_qtLibPath = path;
}
-QString QnxRunConfiguration::environmentPreparationCommand() const
+Utils::Environment QnxRunConfiguration::environment() const
{
- QString command;
- const QStringList filesToSource = QStringList() << QLatin1String("/etc/profile")
- << QLatin1String("$HOME/.profile");
- foreach (const QString &filePath, filesToSource)
- command += QString::fromLatin1("test -f %1 && . %1;").arg(filePath);
- if (!workingDirectory().isEmpty())
- command += QLatin1String("cd ") + workingDirectory() + QLatin1Char(';');
-
- if (!m_qtLibPath.isEmpty())
- command += QLatin1String("LD_LIBRARY_PATH=") + m_qtLibPath + QLatin1String(":$LD_LIBRARY_PATH");
- else
- command.chop(1); // Trailing semicolon.
-
- return command;
+ Utils::Environment env = RemoteLinuxRunConfiguration::environment();
+ if (!m_qtLibPath.isEmpty()) {
+ env.appendOrSet(QLatin1String("LD_LIBRARY_PATH"),
+ m_qtLibPath + QLatin1String(":$LD_LIBRARY_PATH"));
+ }
+ return env;
}
QWidget *QnxRunConfiguration::createConfigurationWidget()
diff --git a/src/plugins/qnx/qnxrunconfiguration.h b/src/plugins/qnx/qnxrunconfiguration.h
index 7d0f173985..18e67d62de 100644
--- a/src/plugins/qnx/qnxrunconfiguration.h
+++ b/src/plugins/qnx/qnxrunconfiguration.h
@@ -34,6 +34,8 @@
#include <remotelinux/remotelinuxrunconfiguration.h>
+namespace Utils { class Environment; }
+
namespace Qnx {
namespace Internal {
@@ -44,7 +46,7 @@ public:
QnxRunConfiguration(ProjectExplorer::Target *parent, const Core::Id id,
const QString &projectFilePath);
- QString environmentPreparationCommand() const;
+ Utils::Environment environment() const;
QWidget *createConfigurationWidget();
diff --git a/src/plugins/qnx/qnxruncontrolfactory.cpp b/src/plugins/qnx/qnxruncontrolfactory.cpp
index d80363b39f..39aa384e37 100644
--- a/src/plugins/qnx/qnxruncontrolfactory.cpp
+++ b/src/plugins/qnx/qnxruncontrolfactory.cpp
@@ -48,6 +48,7 @@
#include <analyzerbase/analyzerstartparameters.h>
#include <analyzerbase/analyzermanager.h>
#include <analyzerbase/analyzerruncontrol.h>
+#include <analyzerbase/ianalyzertool.h>
#include <projectexplorer/environmentaspect.h>
#include <projectexplorer/buildconfiguration.h>
#include <projectexplorer/project.h>
@@ -62,7 +63,7 @@ using namespace ProjectExplorer;
using namespace Qnx;
using namespace Qnx::Internal;
-DebuggerStartParameters createStartParameters(const QnxRunConfiguration *runConfig)
+static DebuggerStartParameters createDebuggerStartParameters(const QnxRunConfiguration *runConfig)
{
DebuggerStartParameters params;
Target *target = runConfig->target();
@@ -85,7 +86,7 @@ DebuggerStartParameters createStartParameters(const QnxRunConfiguration *runConf
params.displayName = runConfig->displayName();
params.remoteSetupNeeded = true;
params.closeMode = KillAtClose;
- params.processArgs = runConfig->arguments();
+ params.processArgs = runConfig->arguments().join(QLatin1String(" "));
Debugger::DebuggerRunConfigurationAspect *aspect
= runConfig->extraAspect<Debugger::DebuggerRunConfigurationAspect>();
@@ -101,7 +102,7 @@ DebuggerStartParameters createStartParameters(const QnxRunConfiguration *runConf
if (const ProjectExplorer::Project *project = runConfig->target()->project()) {
params.projectSourceDirectory = project->projectDirectory();
if (const ProjectExplorer::BuildConfiguration *buildConfig = runConfig->target()->activeBuildConfiguration())
- params.projectBuildDirectory = buildConfig->buildDirectory();
+ params.projectBuildDirectory = buildConfig->buildDirectory().toString();
params.projectSourceFiles = project->files(ProjectExplorer::Project::ExcludeGeneratedFiles);
}
@@ -113,7 +114,7 @@ DebuggerStartParameters createStartParameters(const QnxRunConfiguration *runConf
return params;
}
-AnalyzerStartParameters createAnalyzerStartParameters(const QnxRunConfiguration *runConfig, RunMode mode)
+static AnalyzerStartParameters createAnalyzerStartParameters(const QnxRunConfiguration *runConfig, RunMode mode)
{
AnalyzerStartParameters params;
Target *target = runConfig->target();
@@ -124,11 +125,10 @@ AnalyzerStartParameters createAnalyzerStartParameters(const QnxRunConfiguration
return params;
if (mode == QmlProfilerRunMode)
- params.startMode = StartQmlRemote;
+ params.startMode = StartLocal;
params.debuggee = runConfig->remoteExecutableFilePath();
- params.debuggeeArgs = runConfig->arguments();
+ params.debuggeeArgs = runConfig->arguments().join(QLatin1String(" "));
params.connParams = DeviceKitInformation::device(runConfig->target()->kit())->sshParameters();
- params.analyzerCmdPrefix = runConfig->commandPrefix();
params.displayName = runConfig->displayName();
params.sysroot = SysRootKitInformation::sysRoot(runConfig->target()->kit()).toString();
params.analyzerHost = params.connParams.host;
@@ -177,7 +177,7 @@ RunControl *QnxRunControlFactory::create(RunConfiguration *runConfig, RunMode mo
case NormalRunMode:
return new QnxRunControl(rc);
case DebugRunMode: {
- const DebuggerStartParameters params = createStartParameters(rc);
+ const DebuggerStartParameters params = createDebuggerStartParameters(rc);
DebuggerRunControl * const runControl = DebuggerPlugin::createDebugger(params, rc, errorMessage);
if (!runControl)
return 0;
@@ -188,15 +188,9 @@ RunControl *QnxRunControlFactory::create(RunConfiguration *runConfig, RunMode mo
return runControl;
}
case QmlProfilerRunMode: {
- IAnalyzerTool *tool = AnalyzerManager::toolFromRunMode(mode);
- if (!tool) {
- if (errorMessage)
- *errorMessage = tr("No analyzer tool selected.");
- return 0;
- }
const AnalyzerStartParameters params = createAnalyzerStartParameters(rc, mode);
- AnalyzerRunControl * const runControl = new AnalyzerRunControl(tool, params, runConfig);
- QnxAnalyzeSupport * const analyzeSupport = new QnxAnalyzeSupport(rc, runControl->engine());
+ AnalyzerRunControl *runControl = AnalyzerManager::createRunControl(params, runConfig);
+ QnxAnalyzeSupport * const analyzeSupport = new QnxAnalyzeSupport(rc, runControl);
connect(runControl, SIGNAL(finished()), analyzeSupport, SLOT(handleProfilingFinished()));
return runControl;
}
diff --git a/src/plugins/qnx/qnxutils.cpp b/src/plugins/qnx/qnxutils.cpp
index 64eff9cea1..dadacceb0c 100644
--- a/src/plugins/qnx/qnxutils.cpp
+++ b/src/plugins/qnx/qnxutils.cpp
@@ -100,10 +100,12 @@ QMultiMap<QString, QString> QnxUtils::parseEnvironmentFile(const QString &fileNa
QString value = line.mid(equalIndex + 1);
- // BASE_DIR variable is evaluated when souring the bbnk-env script
+ // BASE_DIR (and BASE_DIR_REPLACED in some recent internal versions) variable is
+ // evaluated when souring the bbnk-env script
// BASE_DIR="$( cd "$(dirname "${BASH_SOURCE[0]}" )" && pwd )"
// We already know the NDK path so we can set the variable value
- if (var == QLatin1String("BASE_DIR"))
+ // TODO: Do not parse bbnk-env!
+ if (var == QLatin1String("BASE_DIR") || var == QLatin1String("BASE_DIR_REPLACED"))
value = QFileInfo(fileName).dir().absolutePath();
if (Utils::HostOsInfo::isWindowsHost()) {
@@ -117,8 +119,7 @@ QMultiMap<QString, QString> QnxUtils::parseEnvironmentFile(const QString &fileNa
else
value = systemVarRegExp.cap(3);
}
- }
- else if (Utils::HostOsInfo::isAnyUnixHost()) {
+ } 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();
@@ -186,7 +187,7 @@ bool QnxUtils::isValidNdkPath(const QString &ndkPath)
return (QFileInfo(envFilePath(ndkPath)).exists());
}
-QString QnxUtils::envFilePath(const QString &ndkPath)
+QString QnxUtils::envFilePath(const QString &ndkPath, const QString &targetVersion)
{
QString envFile;
if (Utils::HostOsInfo::isWindowsHost())
@@ -195,7 +196,7 @@ QString QnxUtils::envFilePath(const QString &ndkPath)
envFile = ndkPath + QLatin1String("/bbndk-env.sh");
if (!QFileInfo(envFile).exists()) {
- QString version = ndkVersion(ndkPath);
+ QString version = targetVersion.isEmpty() ? defaultTargetVersion(ndkPath) : targetVersion;
version = version.replace(QLatin1Char('.'), QLatin1Char('_'));
if (Utils::HostOsInfo::isWindowsHost())
envFile = ndkPath + QLatin1String("/bbndk-env_") + version + QLatin1String(".bat");
@@ -261,11 +262,22 @@ QString QnxUtils::qConfigPath()
}
}
-QString QnxUtils::ndkVersion(const QString &ndkPath)
+QString QnxUtils::defaultTargetVersion(const QString &ndkPath)
+{
+ foreach (const NdkInstallInformation &ndkInfo, installedNdks()) {
+ if (!ndkInfo.path.compare(ndkPath, Utils::HostOsInfo::fileNameCaseSensitivity()))
+ return ndkInfo.version;
+ }
+
+ return QString();
+}
+
+QList<NdkInstallInformation> QnxUtils::installedNdks()
{
+ QList<NdkInstallInformation> ndkList;
QString ndkConfigPath = qConfigPath();
if (!QDir(ndkConfigPath).exists())
- return QString();
+ return ndkList;
QFileInfoList ndkfileList = QDir(ndkConfigPath).entryInfoList(QStringList() << QLatin1String("*.xml"),
QDir::Files, QDir::Time);
@@ -286,11 +298,16 @@ QString QnxUtils::ndkVersion(const QString &ndkPath)
// The file contains only one installation node
if (!childElt.isNull()) {
// The file contains only one base node
- QDomElement elt = childElt.firstChildElement(QLatin1String("base"));
- if (!elt.text().compare(ndkPath, Utils::HostOsInfo::fileNameCaseSensitivity()))
- return childElt.firstChildElement(QLatin1String("version")).text();
+ NdkInstallInformation ndkInfo;
+ ndkInfo.path = childElt.firstChildElement(QLatin1String("base")).text();
+ ndkInfo.name = childElt.firstChildElement(QLatin1String("name")).text();
+ ndkInfo.host = childElt.firstChildElement(QLatin1String("host")).text();
+ ndkInfo.target = childElt.firstChildElement(QLatin1String("target")).text();
+ ndkInfo.version = childElt.firstChildElement(QLatin1String("version")).text();
+
+ ndkList.append(ndkInfo);
}
}
- return QString();
+ return ndkList;
}
diff --git a/src/plugins/qnx/qnxutils.h b/src/plugins/qnx/qnxutils.h
index f12518fd31..7c68825359 100644
--- a/src/plugins/qnx/qnxutils.h
+++ b/src/plugins/qnx/qnxutils.h
@@ -46,6 +46,16 @@ namespace Internal {
class QnxAbstractQtVersion;
+class NdkInstallInformation
+{
+public:
+ QString path;
+ QString name;
+ QString host;
+ QString target;
+ QString version;
+};
+
class QnxUtils
{
public:
@@ -54,12 +64,13 @@ public:
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 QString envFilePath(const QString & ndkPath, const QString& targetVersion = QString());
static void prependQnxMapToEnvironment(const QMultiMap<QString, QString> &qnxMap, Utils::Environment &env);
static Utils::FileName executableWithExtension(const Utils::FileName &fileName);
static QString dataDirPath();
static QString qConfigPath();
- static QString ndkVersion(const QString& ndkPath);
+ static QString defaultTargetVersion(const QString& ndkPath);
+ static QList<NdkInstallInformation> installedNdks();
};
} // namespace Internal
diff --git a/src/plugins/qt4projectmanager/Qt4ProjectManager.pluginspec.in b/src/plugins/qt4projectmanager/Qt4ProjectManager.pluginspec.in
index 74fd5623d6..71aea43b2b 100644
--- a/src/plugins/qt4projectmanager/Qt4ProjectManager.pluginspec.in
+++ b/src/plugins/qt4projectmanager/Qt4ProjectManager.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"Qt4ProjectManager\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"Qt4ProjectManager\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/qt4projectmanager/addlibrarywizard.cpp b/src/plugins/qt4projectmanager/addlibrarywizard.cpp
index 6e2c9c240f..02c496a7ae 100644
--- a/src/plugins/qt4projectmanager/addlibrarywizard.cpp
+++ b/src/plugins/qt4projectmanager/addlibrarywizard.cpp
@@ -44,7 +44,7 @@ using namespace Qt4ProjectManager;
using namespace Qt4ProjectManager::Internal;
-const char *qt_file_dialog_filter_reg_exp =
+const char qt_file_dialog_filter_reg_exp[] =
"^(.*)\\(([a-zA-Z0-9_.*? +;#\\-\\[\\]@\\{\\}/!<>\\$%&=^~:\\|]*)\\)$";
// taken from qfiledialog.cpp
diff --git a/src/plugins/qt4projectmanager/buildconfigurationinfo.h b/src/plugins/qt4projectmanager/buildconfigurationinfo.h
deleted file mode 100644
index a784416e0a..0000000000
--- a/src/plugins/qt4projectmanager/buildconfigurationinfo.h
+++ /dev/null
@@ -1,74 +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 BUILDCONFIGURATIONINFO_H
-#define BUILDCONFIGURATIONINFO_H
-
-#include "qt4projectmanager_global.h"
-
-#include <qtsupport/baseqtversion.h>
-
-namespace Qt4ProjectManager {
-
-class QT4PROJECTMANAGER_EXPORT BuildConfigurationInfo
-{
-public:
- explicit BuildConfigurationInfo()
- : buildConfig(QtSupport::BaseQtVersion::QmakeBuildConfig(0)), importing(false)
- { }
-
- explicit BuildConfigurationInfo(QtSupport::BaseQtVersion::QmakeBuildConfigs bc,
- const QString &aa, const QString &d,
- bool importing_ = false,
- const QString &makefile_ = QString())
- : buildConfig(bc),
- additionalArguments(aa), directory(d),
- importing(importing_),
- makefile(makefile_)
- { }
-
- bool operator ==(const BuildConfigurationInfo &other) const
- {
- return buildConfig == other.buildConfig
- && additionalArguments == other.additionalArguments
- && directory == other.directory
- && importing == other.importing
- && makefile == other.makefile;
- }
-
- QtSupport::BaseQtVersion::QmakeBuildConfigs buildConfig;
- QString additionalArguments;
- QString directory;
- bool importing;
- QString makefile;
-};
-
-} // namespace Qt4ProjectManager
-
-#endif // BUILDCONFIGURATIONINFO_H
diff --git a/src/plugins/qt4projectmanager/customwidgetwizard/customwidgetwidgetswizardpage.ui b/src/plugins/qt4projectmanager/customwidgetwizard/customwidgetwidgetswizardpage.ui
index 7f48f5e36a..568467950d 100644
--- a/src/plugins/qt4projectmanager/customwidgetwizard/customwidgetwidgetswizardpage.ui
+++ b/src/plugins/qt4projectmanager/customwidgetwizard/customwidgetwidgetswizardpage.ui
@@ -94,7 +94,7 @@
<customwidget>
<class>Qt4ProjectManager::Internal::ClassList</class>
<extends>QListWidget</extends>
- <header>classlist.h</header>
+ <header location="global">qt4projectmanager/customwidgetwizard/classlist.h</header>
</customwidget>
</customwidgets>
<tabstops>
diff --git a/src/plugins/qt4projectmanager/customwidgetwizard/customwidgetwizard.cpp b/src/plugins/qt4projectmanager/customwidgetwizard/customwidgetwizard.cpp
index f53ca00ade..dbe53ec911 100644
--- a/src/plugins/qt4projectmanager/customwidgetwizard/customwidgetwizard.cpp
+++ b/src/plugins/qt4projectmanager/customwidgetwizard/customwidgetwizard.cpp
@@ -37,24 +37,21 @@
#include <qtsupport/qtsupportconstants.h>
-#include <QIcon>
+#include <QCoreApplication>
namespace Qt4ProjectManager {
namespace Internal {
-CustomWidgetWizard::CustomWidgetWizard() :
- QtWizard(QLatin1String("P.Qt4CustomWidget"),
- QLatin1String(ProjectExplorer::Constants::QT_PROJECT_WIZARD_CATEGORY),
- QLatin1String(ProjectExplorer::Constants::QT_PROJECT_WIZARD_CATEGORY_DISPLAY),
- tr("Qt Custom Designer Widget"),
- tr("Creates a Qt Custom Designer Widget or a Custom Widget Collection."),
- QIcon(QLatin1String(":/wizards/images/gui.png")))
+CustomWidgetWizard::CustomWidgetWizard()
{
-}
-
-Core::FeatureSet CustomWidgetWizard::requiredFeatures() const
-{
- return Core::Feature(QtSupport::Constants::FEATURE_QWIDGETS);
+ setId(QLatin1String("P.Qt4CustomWidget"));
+ setCategory(QLatin1String(ProjectExplorer::Constants::QT_PROJECT_WIZARD_CATEGORY));
+ setDisplayCategory(QCoreApplication::translate("ProjectExplorer",
+ ProjectExplorer::Constants::QT_PROJECT_WIZARD_CATEGORY_DISPLAY));
+ setDisplayName(tr("Qt Custom Designer Widget"));
+ setDescription(tr("Creates a Qt Custom Designer Widget or a Custom Widget Collection."));
+ setIcon(QIcon(QLatin1String(":/wizards/images/gui.png")));
+ setRequiredFeatures(Core::Feature(QtSupport::Constants::FEATURE_QWIDGETS));
}
QWizard *CustomWidgetWizard::createWizardDialog(QWidget *parent,
diff --git a/src/plugins/qt4projectmanager/customwidgetwizard/customwidgetwizard.h b/src/plugins/qt4projectmanager/customwidgetwizard/customwidgetwizard.h
index f188aaf6bc..c73e68f70c 100644
--- a/src/plugins/qt4projectmanager/customwidgetwizard/customwidgetwizard.h
+++ b/src/plugins/qt4projectmanager/customwidgetwizard/customwidgetwizard.h
@@ -41,15 +41,12 @@ class CustomWidgetWizard : public QtWizard
public:
CustomWidgetWizard();
- virtual Core::FeatureSet requiredFeatures() const;
protected:
- virtual QWizard *createWizardDialog(QWidget *parent,
+ QWizard *createWizardDialog(QWidget *parent,
const Core::WizardDialogParameters &wizardDialogParameters) const;
- virtual Core::GeneratedFiles generateFiles(const QWizard *w,
- QString *errorMessage) const;
-
+ Core::GeneratedFiles generateFiles(const QWizard *w, QString *errorMessage) const;
};
} // namespace Internal
diff --git a/src/plugins/qt4projectmanager/customwidgetwizard/customwidgetwizard.pri b/src/plugins/qt4projectmanager/customwidgetwizard/customwidgetwizard.pri
index 488f9c30fb..0a48d5b4bd 100644
--- a/src/plugins/qt4projectmanager/customwidgetwizard/customwidgetwizard.pri
+++ b/src/plugins/qt4projectmanager/customwidgetwizard/customwidgetwizard.pri
@@ -1,4 +1,3 @@
-INCLUDEPATH *= $$PWD
SOURCES += \
$$PWD/plugingenerator.cpp \
$$PWD/classlist.cpp \
diff --git a/src/plugins/qt4projectmanager/externaleditors.cpp b/src/plugins/qt4projectmanager/externaleditors.cpp
index a39e0b1bf9..27cc84a635 100644
--- a/src/plugins/qt4projectmanager/externaleditors.cpp
+++ b/src/plugins/qt4projectmanager/externaleditors.cpp
@@ -54,8 +54,7 @@ namespace Internal {
// Figure out the Qt4 project used by the file if any
static Qt4Project *qt4ProjectFor(const QString &fileName)
{
- ProjectExplorer::ProjectExplorerPlugin *pe = ProjectExplorer::ProjectExplorerPlugin::instance();
- if (ProjectExplorer::Project *baseProject = pe->session()->projectForFile(fileName))
+ if (ProjectExplorer::Project *baseProject = ProjectExplorer::SessionManager::projectForFile(fileName))
if (Qt4Project *project = qobject_cast<Qt4Project*>(baseProject))
return project;
return 0;
diff --git a/src/plugins/qt4projectmanager/librarydetailscontroller.cpp b/src/plugins/qt4projectmanager/librarydetailscontroller.cpp
index abc528e4ca..e8a4bfb6c9 100644
--- a/src/plugins/qt4projectmanager/librarydetailscontroller.cpp
+++ b/src/plugins/qt4projectmanager/librarydetailscontroller.cpp
@@ -45,6 +45,7 @@
#include <QDir>
#include <QTextStream>
+using namespace ProjectExplorer;
using namespace Qt4ProjectManager;
using namespace Qt4ProjectManager::Internal;
@@ -67,13 +68,13 @@ LibraryDetailsController::LibraryDetailsController(
m_libraryDetailsWidget(libraryDetails)
{
switch (Utils::HostOsInfo::hostOs()) {
- case Utils::HostOsInfo::HostOsMac:
+ case Utils::OsTypeMac:
m_creatorPlatform = CreatorMac;
break;
- case Utils::HostOsInfo::HostOsLinux:
+ case Utils::OsTypeLinux:
m_creatorPlatform = CreatorLinux;
break;
- case Utils::HostOsInfo::HostOsWindows:
+ case Utils::OsTypeWindows:
m_creatorPlatform = CreatorWindows;
break;
default:
@@ -83,7 +84,7 @@ LibraryDetailsController::LibraryDetailsController(
if (!Utils::HostOsInfo::isLinuxHost()) {
// project for which we are going to insert the snippet
const ProjectExplorer::Project *project =
- ProjectExplorer::ProjectExplorerPlugin::instance()->session()->projectForFile(proFile);
+ ProjectExplorer::SessionManager::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
@@ -816,8 +817,7 @@ QString PackageLibraryDetailsController::snippet() const
bool PackageLibraryDetailsController::isLinkPackageGenerated() const
{
- const ProjectExplorer::Project *project =
- ProjectExplorer::ProjectExplorerPlugin::instance()->session()->projectForFile(proFile());
+ const Project *project = SessionManager::projectForFile(proFile());
if (!project)
return false;
@@ -969,8 +969,7 @@ void InternalLibraryDetailsController::updateProFile()
m_proFileNodes.clear();
libraryDetailsWidget()->libraryComboBox->clear();
- const ProjectExplorer::Project *project =
- ProjectExplorer::ProjectExplorerPlugin::instance()->session()->projectForFile(proFile());
+ const Project *project = SessionManager::projectForFile(proFile());
if (!project)
return;
@@ -1053,14 +1052,13 @@ QString InternalLibraryDetailsController::snippet() const
const QString proRelavitePath = rootDir.relativeFilePath(proFile());
// project for which we insert the snippet
- const ProjectExplorer::Project *project =
- ProjectExplorer::ProjectExplorerPlugin::instance()->session()->projectForFile(proFile());
+ const Project *project = SessionManager::projectForFile(proFile());
// the build directory of the active build configuration
QDir rootBuildDir = rootDir; // If the project is unconfigured use the project dir
if (ProjectExplorer::Target *t = project->activeTarget())
if (ProjectExplorer::BuildConfiguration *bc = t->activeBuildConfiguration())
- rootBuildDir = bc->buildDirectory();
+ rootBuildDir = bc->buildDirectory().toString();
// the project for which we insert the snippet inside build tree
QFileInfo pfi(rootBuildDir.filePath(proRelavitePath));
diff --git a/src/plugins/qt4projectmanager/librarydetailswidget.ui b/src/plugins/qt4projectmanager/librarydetailswidget.ui
index 70f0186c78..bc18a5e18c 100644
--- a/src/plugins/qt4projectmanager/librarydetailswidget.ui
+++ b/src/plugins/qt4projectmanager/librarydetailswidget.ui
@@ -244,7 +244,7 @@
<customwidget>
<class>Qt4ProjectManager::Internal::LibraryPathChooser</class>
<extends>QWidget</extends>
- <header>addlibrarywizard.h</header>
+ <header location="global">qt4projectmanager/addlibrarywizard.h</header>
<container>1</container>
</customwidget>
</customwidgets>
diff --git a/src/plugins/qt4projectmanager/makestep.cpp b/src/plugins/qt4projectmanager/makestep.cpp
index 5536885662..bd1bfe3b49 100644
--- a/src/plugins/qt4projectmanager/makestep.cpp
+++ b/src/plugins/qt4projectmanager/makestep.cpp
@@ -173,7 +173,7 @@ bool MakeStep::init()
if (bc->subNodeBuild())
workingDirectory = bc->subNodeBuild()->buildDir();
else
- workingDirectory = bc->buildDirectory();
+ workingDirectory = bc->buildDirectory().toString();
pp->setWorkingDirectory(workingDirectory);
QString makeCmd = tc->makeCommand(bc->environment());
@@ -298,15 +298,6 @@ void MakeStep::run(QFutureInterface<bool> & fi)
AbstractProcessStep::run(fi);
}
-bool MakeStep::processSucceeded(int exitCode, QProcess::ExitStatus status)
-{
- // Symbian does retun 0, even on failed makes! So we check for fatal make errors here.
- if (outputParser() && outputParser()->hasFatalErrors())
- return false;
-
- return AbstractProcessStep::processSucceeded(exitCode, status);
-}
-
bool MakeStep::immutable() const
{
return false;
@@ -409,7 +400,7 @@ void MakeStepConfigWidget::updateDetails()
bc = qobject_cast<Qt4BuildConfiguration *>(m_makeStep->target()->activeBuildConfiguration());
if (tc && bc)
- m_ui->makeLabel->setText(tr("Override %1:").arg(tc->makeCommand(bc->environment())));
+ m_ui->makeLabel->setText(tr("Override %1:").arg(QDir::toNativeSeparators(tc->makeCommand(bc->environment()))));
else
m_ui->makeLabel->setText(tr("Make:"));
@@ -424,7 +415,7 @@ void MakeStepConfigWidget::updateDetails()
ProcessParameters param;
param.setMacroExpander(bc->macroExpander());
- param.setWorkingDirectory(bc->buildDirectory());
+ param.setWorkingDirectory(bc->buildDirectory().toString());
QString makeCmd = tc->makeCommand(bc->environment());
if (!m_makeStep->makeCommand().isEmpty())
makeCmd = m_makeStep->makeCommand();
diff --git a/src/plugins/qt4projectmanager/makestep.h b/src/plugins/qt4projectmanager/makestep.h
index b09ceecbe0..d9729cbb3a 100644
--- a/src/plugins/qt4projectmanager/makestep.h
+++ b/src/plugins/qt4projectmanager/makestep.h
@@ -85,7 +85,6 @@ public:
virtual bool init();
virtual void run(QFutureInterface<bool> &);
- bool processSucceeded(int exitCode, QProcess::ExitStatus status);
virtual ProjectExplorer::BuildStepConfigWidget *createConfigWidget();
virtual bool immutable() const;
diff --git a/src/plugins/qt4projectmanager/profileeditor.cpp b/src/plugins/qt4projectmanager/profileeditor.cpp
index 0ed797d372..ab35944aaa 100644
--- a/src/plugins/qt4projectmanager/profileeditor.cpp
+++ b/src/plugins/qt4projectmanager/profileeditor.cpp
@@ -32,6 +32,9 @@
#include "profilehighlighter.h"
#include "qt4projectmanagerconstants.h"
#include "profileeditorfactory.h"
+#include "profilecompletionassist.h"
+
+#include <extensionsystem/pluginmanager.h>
#include <texteditor/fontsettings.h>
#include <texteditor/texteditoractionhandler.h>
@@ -61,7 +64,7 @@ Core::IEditor *ProFileEditor::duplicate(QWidget *parent)
ProFileEditorWidget *ret = new ProFileEditorWidget(parent, qobject_cast<ProFileEditorWidget*>(editorWidget())->factory(),
qobject_cast<ProFileEditorWidget*>(editorWidget())->actionHandler());
ret->duplicateFrom(editorWidget());
- TextEditor::TextEditorSettings::instance()->initializeEditor(ret);
+ TextEditor::TextEditorSettings::initializeEditor(ret);
return ret->editor();
}
@@ -70,6 +73,11 @@ Core::Id ProFileEditor::id() const
return Core::Id(Constants::PROFILE_EDITOR_ID);
}
+TextEditor::CompletionAssistProvider *ProFileEditor::completionAssistProvider()
+{
+ return ExtensionSystem::PluginManager::getObject<ProFileCompletionAssistProvider>();
+}
+
//
// ProFileEditorWidget
//
@@ -161,7 +169,7 @@ ProFileEditorWidget::Link ProFileEditorWidget::findLinkAt(const QTextCursor &cur
}
}
- QDir dir(QFileInfo(editorDocument()->fileName()).absolutePath());
+ QDir dir(QFileInfo(editorDocument()->filePath()).absolutePath());
QString fileName = dir.filePath(buffer);
QFileInfo fi(fileName);
if (fi.exists()) {
@@ -190,25 +198,6 @@ void ProFileEditorWidget::contextMenuEvent(QContextMenuEvent *e)
showDefaultContextMenu(e, Constants::M_CONTEXT);
}
-void ProFileEditorWidget::setFontSettings(const TextEditor::FontSettings &fs)
-{
- TextEditor::BaseTextEditorWidget::setFontSettings(fs);
- ProFileHighlighter *highlighter = qobject_cast<ProFileHighlighter*>(baseTextDocument()->syntaxHighlighter());
- if (!highlighter)
- return;
-
- static QVector<TextEditor::TextStyle> categories;
- if (categories.isEmpty()) {
- categories << TextEditor::C_TYPE
- << TextEditor::C_KEYWORD
- << TextEditor::C_COMMENT
- << TextEditor::C_VISUAL_WHITESPACE;
- }
-
- highlighter->setFormats(fs.toTextCharFormats(categories));
- highlighter->rehighlight();
-}
-
//
// ProFileDocument
//
@@ -220,13 +209,13 @@ ProFileDocument::ProFileDocument()
QString ProFileDocument::defaultPath() const
{
- QFileInfo fi(fileName());
+ QFileInfo fi(filePath());
return fi.absolutePath();
}
QString ProFileDocument::suggestedFileName() const
{
- QFileInfo fi(fileName());
+ QFileInfo fi(filePath());
return fi.fileName();
}
diff --git a/src/plugins/qt4projectmanager/profileeditor.h b/src/plugins/qt4projectmanager/profileeditor.h
index d9e4b7b839..e8a8fb3ad0 100644
--- a/src/plugins/qt4projectmanager/profileeditor.h
+++ b/src/plugins/qt4projectmanager/profileeditor.h
@@ -55,7 +55,7 @@ public:
bool duplicateSupported() const { return true; }
Core::IEditor *duplicate(QWidget *parent);
Core::Id id() const;
- bool isTemporary() const { return false; }
+ TextEditor::CompletionAssistProvider *completionAssistProvider();
};
class ProFileEditorWidget : public TextEditor::BaseTextEditorWidget
@@ -76,9 +76,6 @@ protected:
TextEditor::BaseTextEditor *createEditor();
void contextMenuEvent(QContextMenuEvent *);
-public slots:
- virtual void setFontSettings(const TextEditor::FontSettings &);
-
private:
ProFileEditorFactory *m_factory;
TextEditor::TextEditorActionHandler *m_ah;
diff --git a/src/plugins/qt4projectmanager/profileeditorfactory.cpp b/src/plugins/qt4projectmanager/profileeditorfactory.cpp
index bb2c8323d1..21227bba9d 100644
--- a/src/plugins/qt4projectmanager/profileeditorfactory.cpp
+++ b/src/plugins/qt4projectmanager/profileeditorfactory.cpp
@@ -43,43 +43,23 @@ using namespace Qt4ProjectManager;
using namespace Qt4ProjectManager::Internal;
ProFileEditorFactory::ProFileEditorFactory(Qt4Manager *manager, TextEditor::TextEditorActionHandler *handler) :
- m_mimeTypes(QStringList() << QLatin1String(Qt4ProjectManager::Constants::PROFILE_MIMETYPE)
- << QLatin1String(Qt4ProjectManager::Constants::PROINCLUDEFILE_MIMETYPE)
- << QLatin1String(Qt4ProjectManager::Constants::PROFEATUREFILE_MIMETYPE)),
m_manager(manager),
m_actionHandler(handler)
{
- Core::FileIconProvider *iconProvider = Core::FileIconProvider::instance();
- iconProvider->registerIconOverlayForSuffix(QIcon(QLatin1String(QtSupport::Constants::ICON_QT_PROJECT)),
- QLatin1String("pro"));
- iconProvider->registerIconOverlayForSuffix(QIcon(QLatin1String(QtSupport::Constants::ICON_QT_PROJECT)),
- QLatin1String("pri"));
- iconProvider->registerIconOverlayForSuffix(QIcon(QLatin1String(QtSupport::Constants::ICON_QT_PROJECT)),
- QLatin1String("prf"));
-}
-
-ProFileEditorFactory::~ProFileEditorFactory()
-{
-}
+ setId(Qt4ProjectManager::Constants::PROFILE_EDITOR_ID);
+ setDisplayName(qApp->translate("OpenWith::Editors", Qt4ProjectManager::Constants::PROFILE_EDITOR_DISPLAY_NAME));
+ addMimeType(Qt4ProjectManager::Constants::PROFILE_MIMETYPE);
+ addMimeType(Qt4ProjectManager::Constants::PROINCLUDEFILE_MIMETYPE);
+ addMimeType(Qt4ProjectManager::Constants::PROFEATUREFILE_MIMETYPE);
-Core::Id ProFileEditorFactory::id() const
-{
- return Core::Id(Qt4ProjectManager::Constants::PROFILE_EDITOR_ID);
-}
-
-QString ProFileEditorFactory::displayName() const
-{
- return qApp->translate("OpenWith::Editors", Qt4ProjectManager::Constants::PROFILE_EDITOR_DISPLAY_NAME);
+ Core::FileIconProvider::registerIconOverlayForSuffix(QtSupport::Constants::ICON_QT_PROJECT, "pro");
+ Core::FileIconProvider::registerIconOverlayForSuffix(QtSupport::Constants::ICON_QT_PROJECT, "pri");
+ Core::FileIconProvider::registerIconOverlayForSuffix(QtSupport::Constants::ICON_QT_PROJECT, "prf");
}
Core::IEditor *ProFileEditorFactory::createEditor(QWidget *parent)
{
ProFileEditorWidget *editor = new ProFileEditorWidget(parent, this, m_actionHandler);
- TextEditor::TextEditorSettings::instance()->initializeEditor(editor);
+ TextEditor::TextEditorSettings::initializeEditor(editor);
return editor->editor();
}
-
-QStringList ProFileEditorFactory::mimeTypes() const
-{
- return m_mimeTypes;
-}
diff --git a/src/plugins/qt4projectmanager/profileeditorfactory.h b/src/plugins/qt4projectmanager/profileeditorfactory.h
index 2ad656320d..41c5e8c477 100644
--- a/src/plugins/qt4projectmanager/profileeditorfactory.h
+++ b/src/plugins/qt4projectmanager/profileeditorfactory.h
@@ -32,11 +32,7 @@
#include <coreplugin/editormanager/ieditorfactory.h>
-#include <QStringList>
-
-namespace TextEditor {
-class TextEditorActionHandler;
-}
+namespace TextEditor { class TextEditorActionHandler; }
namespace Qt4ProjectManager {
@@ -50,18 +46,12 @@ class ProFileEditorFactory : public Core::IEditorFactory
public:
ProFileEditorFactory(Qt4Manager *parent, TextEditor::TextEditorActionHandler *handler);
- ~ProFileEditorFactory();
- // IEditorFactory
- QStringList mimeTypes() const;
- Core::Id id() const;
- QString displayName() const;
Core::IEditor *createEditor(QWidget *parent);
Qt4Manager *qt4ProjectManager() const { return m_manager; }
private:
- const QStringList m_mimeTypes;
Qt4Manager *m_manager;
TextEditor::TextEditorActionHandler *m_actionHandler;
};
diff --git a/src/plugins/qt4projectmanager/profilehighlighter.cpp b/src/plugins/qt4projectmanager/profilehighlighter.cpp
index 01ef269347..11e5b1424c 100644
--- a/src/plugins/qt4projectmanager/profilehighlighter.cpp
+++ b/src/plugins/qt4projectmanager/profilehighlighter.cpp
@@ -41,8 +41,17 @@ ProFileHighlighter::ProFileHighlighter(QTextDocument *document) :
TextEditor::SyntaxHighlighter(document)
{
ProFileCompletionAssistProvider *pcap
- = ExtensionSystem::PluginManager::instance()->getObject<ProFileCompletionAssistProvider>();
+ = ExtensionSystem::PluginManager::getObject<ProFileCompletionAssistProvider>();
m_keywords = TextEditor::Keywords(pcap->variables(), pcap->functions(), QMap<QString, QStringList>());
+
+ static QVector<TextEditor::TextStyle> categories;
+ if (categories.isEmpty()) {
+ categories << TextEditor::C_TYPE
+ << TextEditor::C_KEYWORD
+ << TextEditor::C_COMMENT
+ << TextEditor::C_VISUAL_WHITESPACE;
+ }
+ setTextFormatCategories(categories);
}
void ProFileHighlighter::highlightBlock(const QString &text)
@@ -58,26 +67,26 @@ void ProFileHighlighter::highlightBlock(const QString &text)
for (;;) {
const QChar c = text.at(i);
if (inCommentMode) {
- setFormat(i, 1, m_formats[ProfileCommentFormat]);
+ setFormat(i, 1, formatForCategory(ProfileCommentFormat));
} else {
if (c.isLetter() || c == QLatin1Char('_') || c == QLatin1Char('.') || c.isDigit()) {
buf += c;
setFormat(i - buf.length()+1, buf.length(), emptyFormat);
if (!buf.isEmpty() && m_keywords.isFunction(buf))
- setFormat(i - buf.length()+1, buf.length(), m_formats[ProfileFunctionFormat]);
+ setFormat(i - buf.length()+1, buf.length(), formatForCategory(ProfileFunctionFormat));
else if (!buf.isEmpty() && m_keywords.isVariable(buf))
- setFormat(i - buf.length()+1, buf.length(), m_formats[ProfileVariableFormat]);
+ setFormat(i - buf.length()+1, buf.length(), formatForCategory(ProfileVariableFormat));
} else if (c == QLatin1Char('(')) {
if (!buf.isEmpty() && m_keywords.isFunction(buf))
- setFormat(i - buf.length(), buf.length(), m_formats[ProfileFunctionFormat]);
+ setFormat(i - buf.length(), buf.length(), formatForCategory(ProfileFunctionFormat));
buf.clear();
} else if (c == QLatin1Char('#')) {
inCommentMode = true;
- setFormat(i, 1, m_formats[ProfileCommentFormat]);
+ setFormat(i, 1, formatForCategory(ProfileCommentFormat));
buf.clear();
} else {
if (!buf.isEmpty() && m_keywords.isVariable(buf))
- setFormat(i - buf.length(), buf.length(), m_formats[ProfileVariableFormat]);
+ setFormat(i - buf.length(), buf.length(), formatForCategory(ProfileVariableFormat));
buf.clear();
}
}
@@ -86,5 +95,5 @@ void ProFileHighlighter::highlightBlock(const QString &text)
break;
}
- applyFormatToSpaces(text, m_formats[ProfileVisualWhitespaceFormat]);
+ applyFormatToSpaces(text, formatForCategory(ProfileVisualWhitespaceFormat));
}
diff --git a/src/plugins/qt4projectmanager/profilehighlighter.h b/src/plugins/qt4projectmanager/profilehighlighter.h
index 9ae775785f..a7317962fd 100644
--- a/src/plugins/qt4projectmanager/profilehighlighter.h
+++ b/src/plugins/qt4projectmanager/profilehighlighter.h
@@ -51,14 +51,7 @@ public:
ProFileHighlighter(QTextDocument *document = 0);
void highlightBlock(const QString &text);
- // Set formats from a sequence of type QTextCharFormat
- void setFormats(const QVector<QTextCharFormat> &formats)
- {
- qCopy(formats.begin(), formats.end(), m_formats);
- }
-
private:
- QTextCharFormat m_formats[NumProfileFormats];
TextEditor::Keywords m_keywords;
};
diff --git a/src/plugins/qt4projectmanager/profilehighlighterfactory.cpp b/src/plugins/qt4projectmanager/profilehighlighterfactory.cpp
new file mode 100644
index 0000000000..a4b8afa812
--- /dev/null
+++ b/src/plugins/qt4projectmanager/profilehighlighterfactory.cpp
@@ -0,0 +1,47 @@
+/****************************************************************************
+**
+** 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 "profilehighlighterfactory.h"
+#include "qt4projectmanagerconstants.h"
+#include "profilehighlighter.h"
+
+using namespace Qt4ProjectManager::Internal;
+
+ProFileHighlighterFactory::ProFileHighlighterFactory()
+{
+ setId(Qt4ProjectManager::Constants::PROFILE_EDITOR_ID);
+ addMimeType(Qt4ProjectManager::Constants::PROFILE_MIMETYPE);
+ addMimeType(Qt4ProjectManager::Constants::PROINCLUDEFILE_MIMETYPE);
+ addMimeType(Qt4ProjectManager::Constants::PROFEATUREFILE_MIMETYPE);
+}
+
+TextEditor::SyntaxHighlighter *ProFileHighlighterFactory::createHighlighter() const
+{
+ return new ProFileHighlighter;
+}
diff --git a/src/plugins/qt4projectmanager/profilehighlighterfactory.h b/src/plugins/qt4projectmanager/profilehighlighterfactory.h
new file mode 100644
index 0000000000..358a74ab2c
--- /dev/null
+++ b/src/plugins/qt4projectmanager/profilehighlighterfactory.h
@@ -0,0 +1,51 @@
+/****************************************************************************
+**
+** 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 PROFILEHIGHLIGHTERFACTORY_H
+#define PROFILEHIGHLIGHTERFACTORY_H
+
+#include <texteditor/ihighlighterfactory.h>
+
+namespace Qt4ProjectManager {
+namespace Internal {
+
+class ProFileHighlighterFactory : public TextEditor::IHighlighterFactory
+{
+ Q_OBJECT
+
+public:
+ ProFileHighlighterFactory();
+
+ virtual TextEditor::SyntaxHighlighter *createHighlighter() const;
+};
+
+} // namespace Internal
+} // namespace Qt4ProjectManager
+
+#endif // PROFILEHIGHLIGHTERFACTORY_H
diff --git a/src/plugins/qt4projectmanager/profilehoverhandler.cpp b/src/plugins/qt4projectmanager/profilehoverhandler.cpp
index 1d900c3153..5a8587ceda 100644
--- a/src/plugins/qt4projectmanager/profilehoverhandler.cpp
+++ b/src/plugins/qt4projectmanager/profilehoverhandler.cpp
@@ -47,7 +47,7 @@ ProFileHoverHandler::ProFileHoverHandler(QObject *parent)
m_manualKind(UnknownManual)
{
ProFileCompletionAssistProvider *pcap
- = ExtensionSystem::PluginManager::instance()->getObject<ProFileCompletionAssistProvider>();
+ = ExtensionSystem::PluginManager::getObject<ProFileCompletionAssistProvider>();
m_keywords = TextEditor::Keywords(pcap->variables(), pcap->functions(), QMap<QString, QStringList>());
}
@@ -149,7 +149,7 @@ void ProFileHoverHandler::identifyDocFragment(ProFileHoverHandler::ManualKind ma
if (m_manualKind == FunctionManual) {
QUrl url(QString::fromLatin1("qthelp://com.trolltech.qmake/qdoc/qmake-%1-reference.html").arg(manualName()));
- const QByteArray &html = Core::HelpManager::instance()->fileData(url);
+ const QByteArray html = Core::HelpManager::fileData(url);
Utils::HtmlDocExtractor htmlExtractor;
htmlExtractor.setMode(Utils::HtmlDocExtractor::FirstParagraph);
diff --git a/src/plugins/qt4projectmanager/qmakebuildinfo.h b/src/plugins/qt4projectmanager/qmakebuildinfo.h
new file mode 100644
index 0000000000..2e5795d945
--- /dev/null
+++ b/src/plugins/qt4projectmanager/qmakebuildinfo.h
@@ -0,0 +1,63 @@
+/****************************************************************************
+**
+** 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 QMAKEBUILDINFO_H
+#define QMAKEBUILDINFO_H
+
+#include "qt4buildconfiguration.h"
+
+#include <projectexplorer/buildinfo.h>
+#include <projectexplorer/kitmanager.h>
+#include <qtsupport/baseqtversion.h>
+#include <qtsupport/qtkitinformation.h>
+
+namespace Qt4ProjectManager {
+
+class QmakeBuildInfo : public ProjectExplorer::BuildInfo
+{
+public:
+ QmakeBuildInfo(const Qt4BuildConfigurationFactory *f) : ProjectExplorer::BuildInfo(f) { }
+
+ ProjectExplorer::BuildConfiguration::BuildType type;
+ QString additionalArguments;
+ QString makefile;
+
+ QList<ProjectExplorer::Task> reportIssues(const QString &projectPath,
+ const QString &buildDir) const
+ {
+ ProjectExplorer::Kit *k = ProjectExplorer::KitManager::find(kitId);
+ QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(k);
+ return version ? version->reportIssues(projectPath, buildDir)
+ : QList<ProjectExplorer::Task>();
+ }
+};
+
+} // namespace Qt4ProjectManager
+
+#endif // QMAKEBUILDINFO_H
diff --git a/src/plugins/qt4projectmanager/qmakekitconfigwidget.cpp b/src/plugins/qt4projectmanager/qmakekitconfigwidget.cpp
index f50a27a586..82c7943dea 100644
--- a/src/plugins/qt4projectmanager/qmakekitconfigwidget.cpp
+++ b/src/plugins/qt4projectmanager/qmakekitconfigwidget.cpp
@@ -38,15 +38,21 @@
namespace Qt4ProjectManager {
namespace Internal {
-QmakeKitConfigWidget::QmakeKitConfigWidget(ProjectExplorer::Kit *k, bool sticky) :
- ProjectExplorer::KitConfigWidget(k, sticky),
+QmakeKitConfigWidget::QmakeKitConfigWidget(ProjectExplorer::Kit *k, const ProjectExplorer::KitInformation *ki) :
+ ProjectExplorer::KitConfigWidget(k, ki),
m_lineEdit(new QLineEdit),
m_ignoreChange(false)
{
refresh(); // set up everything according to kit
+ m_lineEdit->setToolTip(toolTip());
connect(m_lineEdit, SIGNAL(textEdited(QString)), this, SLOT(mkspecWasChanged(QString)));
}
+QmakeKitConfigWidget::~QmakeKitConfigWidget()
+{
+ delete m_lineEdit;
+}
+
QWidget *QmakeKitConfigWidget::mainWidget() const
{
return m_lineEdit;
diff --git a/src/plugins/qt4projectmanager/qmakekitconfigwidget.h b/src/plugins/qt4projectmanager/qmakekitconfigwidget.h
index 99c09403c1..b5b15f69c1 100644
--- a/src/plugins/qt4projectmanager/qmakekitconfigwidget.h
+++ b/src/plugins/qt4projectmanager/qmakekitconfigwidget.h
@@ -44,7 +44,8 @@ class QmakeKitConfigWidget : public ProjectExplorer::KitConfigWidget
Q_OBJECT
public:
- explicit QmakeKitConfigWidget(ProjectExplorer::Kit *k, bool sticky);
+ QmakeKitConfigWidget(ProjectExplorer::Kit *k, const ProjectExplorer::KitInformation *ki);
+ ~QmakeKitConfigWidget();
QWidget *mainWidget() const;
QString displayName() const;
diff --git a/src/plugins/qt4projectmanager/qmakekitinformation.cpp b/src/plugins/qt4projectmanager/qmakekitinformation.cpp
index 1ed1eed8a6..fcd668c8e5 100644
--- a/src/plugins/qt4projectmanager/qmakekitinformation.cpp
+++ b/src/plugins/qt4projectmanager/qmakekitinformation.cpp
@@ -37,121 +37,108 @@
#include <qtsupport/qtkitinformation.h>
+using namespace ProjectExplorer;
+using namespace Utils;
+
namespace Qt4ProjectManager {
-namespace Internal {
-const char MKSPEC_INFORMATION[] = "QtPM4.mkSpecInformation";
-} // namespace Internal
QmakeKitInformation::QmakeKitInformation()
{
setObjectName(QLatin1String("QmakeKitInformation"));
+ setId(QmakeKitInformation::id());
+ setPriority(24000);
}
-Core::Id QmakeKitInformation::dataId() const
-{
- static Core::Id id = Core::Id(Internal::MKSPEC_INFORMATION);
- return id;
-}
-
-unsigned int QmakeKitInformation::priority() const
-{
- return 24000;
-}
-
-QVariant QmakeKitInformation::defaultValue(ProjectExplorer::Kit *k) const
+QVariant QmakeKitInformation::defaultValue(Kit *k) const
{
Q_UNUSED(k);
return QString();
}
-QList<ProjectExplorer::Task> QmakeKitInformation::validate(const ProjectExplorer::Kit *k) const
+QList<Task> QmakeKitInformation::validate(const Kit *k) const
{
- QList<ProjectExplorer::Task> result;
+ QList<Task> result;
QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(k);
- Utils::FileName mkspec = QmakeKitInformation::mkspec(k);
+ FileName mkspec = QmakeKitInformation::mkspec(k);
if (!version && !mkspec.isEmpty())
- result << ProjectExplorer::Task(ProjectExplorer::Task::Warning,
- tr("No Qt version set, so mkspec is ignored."),
- Utils::FileName(), -1,
- Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM));
+ result << Task(Task::Warning, tr("No Qt version set, so mkspec is ignored."),
+ FileName(), -1, Constants::TASK_CATEGORY_BUILDSYSTEM);
if (version && !version->hasMkspec(mkspec))
- result << ProjectExplorer::Task(ProjectExplorer::Task::Error,
- tr("Mkspec not found for Qt version."),
- Utils::FileName(), -1,
- Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM));
+ result << Task(Task::Error, tr("Mkspec not found for Qt version."),
+ FileName(), -1, Constants::TASK_CATEGORY_BUILDSYSTEM);
return result;
}
-void QmakeKitInformation::setup(ProjectExplorer::Kit *k)
+void QmakeKitInformation::setup(Kit *k)
{
QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(k);
if (!version)
return;
- Utils::FileName spec = QmakeKitInformation::mkspec(k);
+ FileName spec = QmakeKitInformation::mkspec(k);
if (spec.isEmpty())
spec = version->mkspec();
- ProjectExplorer::ToolChain *tc = ProjectExplorer::ToolChainKitInformation::toolChain(k);
+ ToolChain *tc = ToolChainKitInformation::toolChain(k);
if (!tc || (!tc->suggestedMkspecList().empty() && !tc->suggestedMkspecList().contains(spec))) {
- QList<ProjectExplorer::ToolChain *> tcList = ProjectExplorer::ToolChainManager::instance()->toolChains();
- ProjectExplorer::ToolChain *possibleTc = 0;
- foreach (ProjectExplorer::ToolChain *current, tcList) {
+ ToolChain *possibleTc = 0;
+ foreach (ToolChain *current, ToolChainManager::toolChains()) {
if (version->qtAbis().contains(current->targetAbi())) {
possibleTc = current;
if (current->suggestedMkspecList().contains(spec))
break;
}
}
- ProjectExplorer::ToolChainKitInformation::setToolChain(k, possibleTc);
+ ToolChainKitInformation::setToolChain(k, possibleTc);
}
}
-ProjectExplorer::KitConfigWidget *
-QmakeKitInformation::createConfigWidget(ProjectExplorer::Kit *k) const
+KitConfigWidget *QmakeKitInformation::createConfigWidget(Kit *k) const
{
- return new Internal::QmakeKitConfigWidget(k, isSticky(k));
+ return new Internal::QmakeKitConfigWidget(k, this);
}
-ProjectExplorer::KitInformation::ItemList QmakeKitInformation::toUserOutput(const ProjectExplorer::Kit *k) const
+KitInformation::ItemList QmakeKitInformation::toUserOutput(const Kit *k) const
{
return ItemList() << qMakePair(tr("mkspec"), mkspec(k).toUserOutput());
}
-Utils::FileName QmakeKitInformation::mkspec(const ProjectExplorer::Kit *k)
+Core::Id QmakeKitInformation::id()
+{
+ return "QtPM4.mkSpecInformation";
+}
+
+FileName QmakeKitInformation::mkspec(const Kit *k)
{
if (!k)
- return Utils::FileName();
- return Utils::FileName::fromString(k->value(Core::Id(Internal::MKSPEC_INFORMATION)).toString());
+ return FileName();
+ return FileName::fromString(k->value(QmakeKitInformation::id()).toString());
}
-Utils::FileName QmakeKitInformation::effectiveMkspec(const ProjectExplorer::Kit *k)
+FileName QmakeKitInformation::effectiveMkspec(const Kit *k)
{
if (!k)
- return Utils::FileName();
- Utils::FileName spec = mkspec(k);
+ return FileName();
+ FileName spec = mkspec(k);
if (spec.isEmpty())
return defaultMkspec(k);
return spec;
}
-void QmakeKitInformation::setMkspec(ProjectExplorer::Kit *k, const Utils::FileName &fn)
+void QmakeKitInformation::setMkspec(Kit *k, const FileName &fn)
{
- if (fn == defaultMkspec(k))
- k->setValue(Core::Id(Internal::MKSPEC_INFORMATION), QString());
- else
- k->setValue(Core::Id(Internal::MKSPEC_INFORMATION), fn.toString());
+ k->setValue(QmakeKitInformation::id(), fn == defaultMkspec(k) ? QString() : fn.toString());
}
-Utils::FileName QmakeKitInformation::defaultMkspec(const ProjectExplorer::Kit *k)
+FileName QmakeKitInformation::defaultMkspec(const Kit *k)
{
QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(k);
if (!version) // No version, so no qmake
- return Utils::FileName();
+ return FileName();
- return version->mkspecFor(ProjectExplorer::ToolChainKitInformation::toolChain(k));
+ return version->mkspecFor(ToolChainKitInformation::toolChain(k));
}
} // namespace Qt4ProjectManager
diff --git a/src/plugins/qt4projectmanager/qmakekitinformation.h b/src/plugins/qt4projectmanager/qmakekitinformation.h
index 5450e0d644..c2e86e1913 100644
--- a/src/plugins/qt4projectmanager/qmakekitinformation.h
+++ b/src/plugins/qt4projectmanager/qmakekitinformation.h
@@ -43,10 +43,6 @@ class QT4PROJECTMANAGER_EXPORT QmakeKitInformation : public ProjectExplorer::Kit
public:
QmakeKitInformation();
- Core::Id dataId() const;
-
- unsigned int priority() const; // the higher the closer to the top.
-
QVariant defaultValue(ProjectExplorer::Kit *k) const;
QList<ProjectExplorer::Task> validate(const ProjectExplorer::Kit *k) const;
@@ -56,11 +52,11 @@ public:
ItemList toUserOutput(const ProjectExplorer::Kit *k) const;
+ static Core::Id id();
static void setMkspec(ProjectExplorer::Kit *k, const Utils::FileName &fn);
static Utils::FileName mkspec(const ProjectExplorer::Kit *k);
static Utils::FileName effectiveMkspec(const ProjectExplorer::Kit *k);
static Utils::FileName defaultMkspec(const ProjectExplorer::Kit *k);
-
};
} // namespace Qt4ProjectManager
diff --git a/src/plugins/qt4projectmanager/qmakeprojectimporter.cpp b/src/plugins/qt4projectmanager/qmakeprojectimporter.cpp
new file mode 100644
index 0000000000..953e2daed0
--- /dev/null
+++ b/src/plugins/qt4projectmanager/qmakeprojectimporter.cpp
@@ -0,0 +1,254 @@
+/****************************************************************************
+**
+** 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 "qmakeprojectimporter.h"
+
+#include "qmakebuildinfo.h"
+#include "qmakekitinformation.h"
+#include "qt4buildconfiguration.h"
+#include "qt4project.h"
+
+#include <coreplugin/icore.h>
+#include <coreplugin/idocument.h>
+#include <projectexplorer/kitmanager.h>
+#include <projectexplorer/target.h>
+#include <qtsupport/qtkitinformation.h>
+#include <qtsupport/qtsupportconstants.h>
+#include <qtsupport/qtversionfactory.h>
+#include <qtsupport/qtversionmanager.h>
+#include <utils/qtcprocess.h>
+
+#include <QDir>
+#include <QFileInfo>
+#include <QStringList>
+
+#include <QMessageBox>
+
+static const Core::Id QT_IS_TEMPORARY("Qmake.TempQt");
+
+namespace Qt4ProjectManager {
+namespace Internal {
+
+QmakeProjectImporter::QmakeProjectImporter(const QString &path) :
+ ProjectExplorer::ProjectImporter(path)
+{ }
+
+QList<ProjectExplorer::BuildInfo *> QmakeProjectImporter::import(const Utils::FileName &importPath,
+ bool silent)
+{
+ QList<ProjectExplorer::BuildInfo *> result;
+ QFileInfo fi = importPath.toFileInfo();
+ if (!fi.exists() && !fi.isDir())
+ return result;
+
+ QStringList makefiles = QDir(importPath.toString()).entryList(QStringList(QLatin1String("Makefile*")));
+
+ QtSupport::BaseQtVersion *version = 0;
+ bool temporaryVersion = false;
+
+ foreach (const QString &file, makefiles) {
+ // find interesting makefiles
+ QString makefile = importPath.toString() + QLatin1Char('/') + file;
+ Utils::FileName qmakeBinary = QtSupport::QtVersionManager::findQMakeBinaryFromMakefile(makefile);
+ QFileInfo qmakeFi = qmakeBinary.toFileInfo();
+ Utils::FileName canonicalQmakeBinary = Utils::FileName::fromString(qmakeFi.canonicalFilePath());
+ if (canonicalQmakeBinary.isEmpty())
+ continue;
+ if (QtSupport::QtVersionManager::makefileIsFor(makefile, projectFilePath()) != QtSupport::QtVersionManager::SameProject)
+ continue;
+
+ // Find version:
+ foreach (QtSupport::BaseQtVersion *v, QtSupport::QtVersionManager::versions()) {
+ QFileInfo vfi = v->qmakeCommand().toFileInfo();
+ Utils::FileName current = Utils::FileName::fromString(vfi.canonicalFilePath());
+ if (current == canonicalQmakeBinary) {
+ version = v;
+ break;
+ }
+ }
+
+ // Create a new version if not found:
+ if (!version) {
+ // Do not use the canonical path here...
+ version = QtSupport::QtVersionFactory::createQtVersionFromQMakePath(qmakeBinary);
+ if (!version)
+ continue;
+
+ setIsUpdating(true);
+ QtSupport::QtVersionManager::addVersion(version);
+ setIsUpdating(false);
+ temporaryVersion = true;
+ }
+
+ // find qmake arguments and mkspec
+ QPair<QtSupport::BaseQtVersion::QmakeBuildConfigs, QString> makefileBuildConfig =
+ QtSupport::QtVersionManager::scanMakeFile(makefile, version->defaultBuildConfig());
+
+ QString additionalArguments = makefileBuildConfig.second;
+ Utils::FileName parsedSpec =
+ Qt4BuildConfiguration::extractSpecFromArguments(&additionalArguments, importPath.toString(), version);
+ Utils::FileName versionSpec = version->mkspec();
+ if (parsedSpec.isEmpty() || parsedSpec == Utils::FileName::fromString(QLatin1String("default")))
+ parsedSpec = versionSpec;
+
+ QString specArgument;
+ // Compare mkspecs and add to additional arguments
+ if (parsedSpec != versionSpec)
+ specArgument = QLatin1String("-spec ") + Utils::QtcProcess::quoteArg(parsedSpec.toUserOutput());
+ Utils::QtcProcess::addArgs(&specArgument, additionalArguments);
+
+ // Find kits (can be more than one, e.g. (Linux-)Desktop and embedded linux):
+ QList<ProjectExplorer::Kit *> kitList;
+ foreach (ProjectExplorer::Kit *k, ProjectExplorer::KitManager::kits()) {
+ QtSupport::BaseQtVersion *kitVersion = QtSupport::QtKitInformation::qtVersion(k);
+ Utils::FileName kitSpec = QmakeKitInformation::mkspec(k);
+ ProjectExplorer::ToolChain *tc = ProjectExplorer::ToolChainKitInformation::toolChain(k);
+ if (kitSpec.isEmpty() && kitVersion)
+ kitSpec = kitVersion->mkspecFor(tc);
+
+ if (kitVersion == version
+ && kitSpec == parsedSpec)
+ kitList.append(k);
+ }
+ if (kitList.isEmpty())
+ kitList.append(createTemporaryKit(version, temporaryVersion, parsedSpec));
+
+ foreach (ProjectExplorer::Kit *k, kitList) {
+ addProject(k);
+
+ Qt4BuildConfigurationFactory *factory
+ = qobject_cast<Qt4BuildConfigurationFactory *>(
+ ProjectExplorer::IBuildConfigurationFactory::find(k, projectFilePath()));
+
+ if (!factory)
+ continue;
+
+ // create info:
+ QmakeBuildInfo *info = new QmakeBuildInfo(factory);
+ if (makefileBuildConfig.first | QtSupport::BaseQtVersion::DebugBuild) {
+ info->type = ProjectExplorer::BuildConfiguration::Debug;
+ info->displayName = QCoreApplication::translate("Qt4ProjectManager::Internal::QmakeProjectImporter", "Debug");
+ } else {
+ info->type = ProjectExplorer::BuildConfiguration::Release;
+ info->displayName = QCoreApplication::translate("Qt4ProjectManager::Internal::QmakeProjectImporter", "Release");
+ }
+ info->kitId = k->id();
+ info->buildDirectory = Utils::FileName::fromString(fi.absoluteFilePath());
+ info->additionalArguments = additionalArguments;
+ info->makefile = makefile;
+
+ result << info;
+ }
+ }
+
+ if (result.isEmpty() && !silent)
+ QMessageBox::critical(Core::ICore::mainWindow(),
+ QCoreApplication::translate("Qt4ProjectManager::Internal::QmakeProjectImporter", "No Build Found"),
+ QCoreApplication::translate("Qt4ProjectManager::Internal::QmakeProjectImporter", "No build found in %1 matching project %2.")
+ .arg(importPath.toUserOutput()).arg(projectFilePath()));
+
+ return result;
+}
+
+QStringList QmakeProjectImporter::importCandidates(const Utils::FileName &projectPath)
+{
+ QStringList candidates;
+
+ QFileInfo pfi = projectPath.toFileInfo();
+ const QString prefix = pfi.baseName();
+ candidates << pfi.absolutePath();
+
+ QList<ProjectExplorer::Kit *> kitList = ProjectExplorer::KitManager::kits();
+ foreach (ProjectExplorer::Kit *k, kitList) {
+ QFileInfo fi(Qt4Project::shadowBuildDirectory(projectPath.toString(), k, QString()));
+ const QString baseDir = fi.absolutePath();
+
+ foreach (const QString &dir, QDir(baseDir).entryList()) {
+ const QString path = baseDir + QLatin1Char('/') + dir;
+ if (dir.startsWith(prefix) && !candidates.contains(path))
+ candidates << path;
+ }
+ }
+ return candidates;
+}
+
+ProjectExplorer::Target *QmakeProjectImporter::preferredTarget(const QList<ProjectExplorer::Target *> &possibleTargets)
+{
+ // Select active target
+ // a) The default target
+ // b) Simulator target
+ // c) Desktop target
+ // d) the first target
+ ProjectExplorer::Target *activeTarget = possibleTargets.isEmpty() ? 0 : possibleTargets.at(0);
+ int activeTargetPriority = 0;
+ foreach (ProjectExplorer::Target *t, possibleTargets) {
+ QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(t->kit());
+ if (t->kit() == ProjectExplorer::KitManager::defaultKit()) {
+ activeTarget = t;
+ activeTargetPriority = 3;
+ } else if (activeTargetPriority < 2 && version && version->type() == QLatin1String(QtSupport::Constants::SIMULATORQT)) {
+ activeTarget = t;
+ activeTargetPriority = 2;
+ } else if (activeTargetPriority < 1 && version && version->type() == QLatin1String(QtSupport::Constants::DESKTOPQT)) {
+ activeTarget = t;
+ activeTargetPriority = 1;
+ }
+ }
+ return activeTarget;
+}
+
+void QmakeProjectImporter::cleanupKit(ProjectExplorer::Kit *k)
+{
+ QtSupport::BaseQtVersion *version = QtSupport::QtVersionManager::version(k->value(QT_IS_TEMPORARY, -1).toInt());
+ if (version)
+ QtSupport::QtVersionManager::removeVersion(version);
+}
+
+ProjectExplorer::Kit *QmakeProjectImporter::createTemporaryKit(QtSupport::BaseQtVersion *version,
+ bool temporaryVersion,
+ const Utils::FileName &parsedSpec)
+{
+ ProjectExplorer::Kit *k = new ProjectExplorer::Kit;
+ QtSupport::QtKitInformation::setQtVersion(k, version);
+ ProjectExplorer::ToolChainKitInformation::setToolChain(k, version->preferredToolChain(parsedSpec));
+ QmakeKitInformation::setMkspec(k, parsedSpec);
+
+ markTemporary(k);
+ if (temporaryVersion)
+ k->setValue(QT_IS_TEMPORARY, version->uniqueId());
+
+ k->setDisplayName(version->displayName());
+ setIsUpdating(true);
+ ProjectExplorer::KitManager::registerKit(k);
+ setIsUpdating(false);
+ return k;
+}
+
+} // namespace Internal
+} // namespace Qt4ProjectManager
diff --git a/src/plugins/qt4projectmanager/qmakeprojectimporter.h b/src/plugins/qt4projectmanager/qmakeprojectimporter.h
new file mode 100644
index 0000000000..4ab5be811d
--- /dev/null
+++ b/src/plugins/qt4projectmanager/qmakeprojectimporter.h
@@ -0,0 +1,64 @@
+/****************************************************************************
+**
+** 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 QMAKEPROJECTIMPORTER_H
+#define QMAKEPROJECTIMPORTER_H
+
+#include <projectexplorer/projectimporter.h>
+
+namespace QtSupport { class BaseQtVersion; }
+
+namespace Qt4ProjectManager {
+
+class Qt4Project;
+
+namespace Internal {
+
+// Documentation inside.
+class QmakeProjectImporter : public ProjectExplorer::ProjectImporter
+{
+public:
+ QmakeProjectImporter(const QString &path);
+
+ QList<ProjectExplorer::BuildInfo *> import(const Utils::FileName &importPath, bool silent = false);
+ QStringList importCandidates(const Utils::FileName &projectFilePath);
+ ProjectExplorer::Target *preferredTarget(const QList<ProjectExplorer::Target *> &possibleTargets);
+
+ void cleanupKit(ProjectExplorer::Kit *k);
+
+private:
+ ProjectExplorer::Kit *createTemporaryKit(QtSupport::BaseQtVersion *version,
+ bool temporaryVersion,
+ const Utils::FileName &parsedSpec);
+};
+
+} // namespace Internal
+} // namespace Qt4ProjectManager
+
+#endif // QMAKEPROJECTIMPORTER_H
diff --git a/src/plugins/qt4projectmanager/qmakerunconfigurationfactory.cpp b/src/plugins/qt4projectmanager/qmakerunconfigurationfactory.cpp
index 7a578cf1ed..73abdded5e 100644
--- a/src/plugins/qt4projectmanager/qmakerunconfigurationfactory.cpp
+++ b/src/plugins/qt4projectmanager/qmakerunconfigurationfactory.cpp
@@ -43,7 +43,7 @@ QmakeRunConfigurationFactory *QmakeRunConfigurationFactory::find(ProjectExplorer
return 0;
QList<QmakeRunConfigurationFactory *> factories
- = ExtensionSystem::PluginManager::instance()->getObjects<QmakeRunConfigurationFactory>();
+ = ExtensionSystem::PluginManager::getObjects<QmakeRunConfigurationFactory>();
foreach (QmakeRunConfigurationFactory *factory, factories) {
if (factory->canHandle(t))
return factory;
diff --git a/src/plugins/qt4projectmanager/qmakestep.cpp b/src/plugins/qt4projectmanager/qmakestep.cpp
index c8b677e002..c0e55fd5f2 100644
--- a/src/plugins/qt4projectmanager/qmakestep.cpp
+++ b/src/plugins/qt4projectmanager/qmakestep.cpp
@@ -122,9 +122,9 @@ QString QMakeStep::allArguments(bool shorted)
if (bc->subNodeBuild())
arguments << QDir::toNativeSeparators(bc->subNodeBuild()->path());
else if (shorted)
- arguments << QDir::toNativeSeparators(QFileInfo(project()->document()->fileName()).fileName());
+ arguments << QDir::toNativeSeparators(QFileInfo(project()->projectFilePath()).fileName());
else
- arguments << QDir::toNativeSeparators(project()->document()->fileName());
+ arguments << QDir::toNativeSeparators(project()->projectFilePath());
arguments << QLatin1String("-r");
bool userProvidedMkspec = false;
@@ -248,7 +248,7 @@ bool QMakeStep::init()
if (qt4bc->subNodeBuild())
workingDirectory = qt4bc->subNodeBuild()->buildDir();
else
- workingDirectory = qt4bc->buildDirectory();
+ workingDirectory = qt4bc->buildDirectory().toString();
FileName program = qtVersion->qmakeCommand();
@@ -649,11 +649,10 @@ void QMakeStepConfigWidget::recompileMessageBoxFinished(int button)
return;
QList<ProjectExplorer::BuildStepList *> stepLists;
- const Core::Id clean = Core::Id(ProjectExplorer::Constants::BUILDSTEPS_CLEAN);
- const Core::Id build = Core::Id(ProjectExplorer::Constants::BUILDSTEPS_BUILD);
+ const Core::Id clean = ProjectExplorer::Constants::BUILDSTEPS_CLEAN;
+ const Core::Id build = ProjectExplorer::Constants::BUILDSTEPS_BUILD;
stepLists << bc->stepList(clean) << bc->stepList(build);
- ProjectExplorer::BuildManager *bm = ProjectExplorerPlugin::instance()->buildManager();
- bm->buildLists(stepLists, QStringList() << ProjectExplorerPlugin::displayNameForStepId(clean)
+ BuildManager::buildLists(stepLists, QStringList() << ProjectExplorerPlugin::displayNameForStepId(clean)
<< ProjectExplorerPlugin::displayNameForStepId(build));
}
}
diff --git a/src/plugins/qt4projectmanager/qt-desktop/qt4runconfiguration.h b/src/plugins/qt4projectmanager/qt-desktop/qt4runconfiguration.h
index 41044dba9c..1527a4b524 100644
--- a/src/plugins/qt4projectmanager/qt-desktop/qt4runconfiguration.h
+++ b/src/plugins/qt4projectmanager/qt-desktop/qt4runconfiguration.h
@@ -30,7 +30,7 @@
#ifndef QT4RUNCONFIGURATION_H
#define QT4RUNCONFIGURATION_H
-#include "qmakerunconfigurationfactory.h"
+#include <qt4projectmanager/qmakerunconfigurationfactory.h>
#include <projectexplorer/localapplicationrunconfiguration.h>
diff --git a/src/plugins/qt4projectmanager/qt4buildconfiguration.cpp b/src/plugins/qt4projectmanager/qt4buildconfiguration.cpp
index 8c728f8723..c3a1b9959f 100644
--- a/src/plugins/qt4projectmanager/qt4buildconfiguration.cpp
+++ b/src/plugins/qt4projectmanager/qt4buildconfiguration.cpp
@@ -29,16 +29,19 @@
#include "qt4buildconfiguration.h"
+#include "qmakebuildinfo.h"
#include "qt4project.h"
#include "qt4projectconfigwidget.h"
#include "qt4projectmanagerconstants.h"
#include "qt4nodes.h"
#include "qmakestep.h"
#include "makestep.h"
-#include "buildconfigurationinfo.h"
#include <utils/qtcprocess.h>
+#include <utils/qtcassert.h>
#include <limits>
+#include <coreplugin/icore.h>
+#include <coreplugin/mimedatabase.h>
#include <projectexplorer/buildsteplist.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/target.h>
@@ -47,12 +50,27 @@
#include <qtsupport/qtkitinformation.h>
#include <qtsupport/qtversionmanager.h>
#include <qt4projectmanager/qmakekitinformation.h>
+#include <utils/qtcassert.h>
#include <QDebug>
#include <QInputDialog>
namespace Qt4ProjectManager {
+// --------------------------------------------------------------------
+// Helpers:
+// --------------------------------------------------------------------
+
+static Utils::FileName defaultBuildDirectory(bool supportsShadowBuild,
+ const QString &projectPath,
+ const ProjectExplorer::Kit *k,
+ const QString &suffix)
+{
+ if (supportsShadowBuild)
+ return Utils::FileName::fromString(Qt4Project::shadowBuildDirectory(projectPath, k, suffix));
+ return Utils::FileName::fromString(ProjectExplorer::Project::projectDirectory(projectPath));
+}
+
using namespace Internal;
using namespace ProjectExplorer;
using namespace QtSupport;
@@ -60,7 +78,6 @@ using namespace Utils;
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 };
@@ -91,7 +108,6 @@ Qt4BuildConfiguration::Qt4BuildConfiguration(Target *target, Qt4BuildConfigurati
BuildConfiguration(target, source),
m_shadowBuild(source->m_shadowBuild),
m_isEnabled(false),
- m_buildDirectory(source->m_buildDirectory),
m_qmakeBuildConfiguration(source->m_qmakeBuildConfiguration),
m_subNodeBuild(0), // temporary value, so not copied
m_fileNodeBuild(0)
@@ -108,7 +124,6 @@ QVariantMap Qt4BuildConfiguration::toMap() const
{
QVariantMap map(BuildConfiguration::toMap());
map.insert(QLatin1String(USE_SHADOW_BUILD_KEY), m_shadowBuild);
- map.insert(QLatin1String(BUILD_DIRECTORY_KEY), m_buildDirectory);
map.insert(QLatin1String(BUILD_CONFIGURATION_KEY), int(m_qmakeBuildConfiguration));
return map;
}
@@ -120,9 +135,7 @@ bool Qt4BuildConfiguration::fromMap(const QVariantMap &map)
m_shadowBuild = map.value(QLatin1String(USE_SHADOW_BUILD_KEY), true).toBool();
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());
@@ -137,8 +150,6 @@ bool Qt4BuildConfiguration::fromMap(const QVariantMap &map)
void Qt4BuildConfiguration::ctor()
{
connect(this, SIGNAL(environmentChanged()),
- this, SLOT(emitBuildDirectoryChanged()));
- connect(this, SIGNAL(environmentChanged()),
this, SLOT(emitProFileEvaluateNeeded()));
connect(target(), SIGNAL(kitChanged()),
this, SLOT(kitChanged()));
@@ -152,7 +163,7 @@ void Qt4BuildConfiguration::kitChanged()
// For that reason the Qt4BuildConfiguration is also connected
// to the toolchain and qtversion managers
emitProFileEvaluateNeeded();
- emitBuildDirectoryChanged();
+ updateShadowBuild();
m_lastKitState = newState;
}
}
@@ -169,14 +180,14 @@ void Qt4BuildConfiguration::qtVersionsChanged(const QList<int> &,const QList<int
emitProFileEvaluateNeeded();
}
-void Qt4BuildConfiguration::emitBuildDirectoryChanged()
+void Qt4BuildConfiguration::updateShadowBuild()
{
// We also emit buildDirectoryChanged if the the Qt version's supportShadowBuild changed
- if (buildDirectory() != m_lastEmmitedBuildDirectory
- || supportsShadowBuilds() != m_qtVersionSupportsShadowBuilds) {
- m_lastEmmitedBuildDirectory = buildDirectory();
- m_qtVersionSupportsShadowBuilds = supportsShadowBuilds();
- emit buildDirectoryChanged();
+ bool currentShadowBuild = supportsShadowBuilds();
+ if (currentShadowBuild != m_qtVersionSupportsShadowBuilds) {
+ if (!currentShadowBuild)
+ setBuildDirectory(Utils::FileName::fromString(target()->project()->projectDirectory()));
+ m_qtVersionSupportsShadowBuilds = currentShadowBuild;
}
}
@@ -188,32 +199,10 @@ NamedWidget *Qt4BuildConfiguration::createConfigWidget()
QString Qt4BuildConfiguration::defaultShadowBuildDirectory() const
{
// todo displayName isn't ideal
- return Qt4Project::shadowBuildDirectory(target()->project()->document()->fileName(),
+ return Qt4Project::shadowBuildDirectory(target()->project()->projectFilePath(),
target()->kit(), displayName());
}
-/// returns the unexpanded build directory
-QString Qt4BuildConfiguration::rawBuildDirectory() const
-{
- QString workingDirectory;
- if (m_shadowBuild) {
- if (!m_buildDirectory.isEmpty())
- workingDirectory = m_buildDirectory;
- else
- workingDirectory = defaultShadowBuildDirectory();
- }
- if (workingDirectory.isEmpty())
- workingDirectory = target()->project()->projectDirectory();
- return workingDirectory;
-}
-
-/// Returns the build directory.
-QString Qt4BuildConfiguration::buildDirectory() const
-{
- QString path = QDir::cleanPath(environment().expandVariables(rawBuildDirectory()));
- return QDir::cleanPath(QDir(target()->project()->projectDirectory()).absoluteFilePath(path));
-}
-
bool Qt4BuildConfiguration::supportsShadowBuilds()
{
BaseQtVersion *version = QtKitInformation::qtVersion(target()->kit());
@@ -253,32 +242,19 @@ void Qt4BuildConfiguration::setFileNodeBuild(FileNode *node)
/// note, even if shadowBuild() returns true, it might be using the
/// source directory as the shadow build directory, thus it
/// still is a in-source build
-bool Qt4BuildConfiguration::shadowBuild() const
+bool Qt4BuildConfiguration::isShadowBuild() const
{
- return m_shadowBuild;
+ return buildDirectory().toString() != target()->project()->projectDirectory();
}
-/// returns the shadow build directory if set
-/// \note buildDirectory() is probably the function you want to call
-QString Qt4BuildConfiguration::shadowBuildDirectory() const
+void Qt4BuildConfiguration::setBuildDirectory(const FileName &directory)
{
- if (m_buildDirectory.isEmpty())
- return defaultShadowBuildDirectory();
- return m_buildDirectory;
-}
-
-void Qt4BuildConfiguration::setShadowBuildAndDirectory(bool shadowBuild, const QString &buildDirectory)
-{
- BaseQtVersion *version = QtKitInformation::qtVersion(target()->kit());
- QString directoryToSet = buildDirectory;
- bool toSet = (shadowBuild && version && version->isValid() && version->supportsShadowBuilds());
- if (m_shadowBuild == toSet && m_buildDirectory == directoryToSet)
+ if (directory == buildDirectory())
return;
-
- m_shadowBuild = toSet;
- m_buildDirectory = directoryToSet;
-
- emitBuildDirectoryChanged();
+ BuildConfiguration::setBuildDirectory(directory);
+ QTC_CHECK(supportsShadowBuilds()
+ || (!supportsShadowBuilds()
+ && buildDirectory().toString() == target()->project()->projectDirectory()));
emitProFileEvaluateNeeded();
}
@@ -299,7 +275,6 @@ void Qt4BuildConfiguration::setQMakeBuildConfiguration(BaseQtVersion::QmakeBuild
m_qmakeBuildConfiguration = config;
emit qmakeBuildConfigurationChanged();
- emitBuildDirectoryChanged();
emitProFileEvaluateNeeded();
}
@@ -551,8 +526,8 @@ Qt4BuildConfigurationFactory::Qt4BuildConfigurationFactory(QObject *parent) :
{
update();
- QtVersionManager *vm = QtVersionManager::instance();
- connect(vm, SIGNAL(qtVersionsChanged(QList<int>,QList<int>,QList<int>)),
+ connect(QtVersionManager::instance(),
+ SIGNAL(qtVersionsChanged(QList<int>,QList<int>,QList<int>)),
this, SLOT(update()));
}
@@ -572,69 +547,121 @@ bool Qt4BuildConfigurationFactory::canHandle(const Target *t) const
return qobject_cast<Qt4Project *>(t->project());
}
-QList<Core::Id> Qt4BuildConfigurationFactory::availableCreationIds(const Target *parent) const
+QmakeBuildInfo *Qt4BuildConfigurationFactory::createBuildInfo(const Kit *k,
+ const QString &projectPath,
+ BuildConfiguration::BuildType type) const
{
- if (!canHandle(parent))
- return QList<Core::Id>();
- return QList<Core::Id>() << Core::Id(QT4_BC_ID);
+ QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(k);
+ QmakeBuildInfo *info = new QmakeBuildInfo(this);
+ if (type == BuildConfiguration::Release)
+ //: The name of the release build configuration created by default for a qmake project.
+ info->displayName = tr("Release");
+ else
+ //: The name of the debug build configuration created by default for a qmake project.
+ info->displayName = tr("Debug");
+ info->typeName = tr("Build");
+ // Leave info->buildDirectory unset;
+ info->kitId = k->id();
+ info->supportsShadowBuild = (version && version->supportsShadowBuilds());
+ info->buildDirectory
+ = defaultBuildDirectory(info->supportsShadowBuild, projectPath, k, info->displayName);
+ info->type = type;
+ return info;
}
-QString Qt4BuildConfigurationFactory::displayNameForId(const Core::Id id) const
+bool Qt4BuildConfigurationFactory::canCreate(const Target *parent) const
{
- if (id == QT4_BC_ID)
- return tr("Qmake based build");
- return QString();
+ return canHandle(parent);
}
-bool Qt4BuildConfigurationFactory::canCreate(const Target *parent, const Core::Id id) const
+QList<BuildInfo *> Qt4BuildConfigurationFactory::availableBuilds(const Target *parent) const
{
- if (!canHandle(parent))
- return false;
- return id == QT4_BC_ID;
+ QList<ProjectExplorer::BuildInfo *> result;
+ QTC_ASSERT(canCreate(parent), return result);
+
+ QmakeBuildInfo *info = createBuildInfo(parent->kit(), parent->project()->projectFilePath(),
+ BuildConfiguration::Debug);
+ info->displayName.clear(); // ask for a name
+ info->buildDirectory.clear(); // This depends on the displayName
+ result << info;
+
+ return result;
}
-BuildConfiguration *Qt4BuildConfigurationFactory::create(Target *parent, const Core::Id id, const QString &name)
+bool Qt4BuildConfigurationFactory::canSetup(const Kit *k, const QString &projectPath) const
{
- if (!canCreate(parent, id))
- return 0;
+ return k && QtSupport::QtKitInformation::qtVersion(k)
+ && Core::MimeDatabase::findByFile(QFileInfo(projectPath))
+ .matchesType(QLatin1String(Constants::PROFILE_MIMETYPE));
+}
- BaseQtVersion *version = QtKitInformation::qtVersion(parent->kit());
- Q_ASSERT(version);
-
- bool ok = true;
- QString buildConfigurationName = name;
- if (buildConfigurationName.isNull())
- buildConfigurationName = QInputDialog::getText(0,
- tr("New Configuration"),
- tr("New configuration name:"),
- QLineEdit::Normal,
- version->displayName(), &ok);
- buildConfigurationName = buildConfigurationName.trimmed();
- if (!ok || buildConfigurationName.isEmpty())
- return 0;
+QList<BuildInfo *> Qt4BuildConfigurationFactory::availableSetups(const Kit *k, const QString &projectPath) const
+{
+ QList<ProjectExplorer::BuildInfo *> result;
+ QTC_ASSERT(canSetup(k, projectPath), return result);
+
+ result << createBuildInfo(k, projectPath, ProjectExplorer::BuildConfiguration::Debug);
+ result << createBuildInfo(k, projectPath, ProjectExplorer::BuildConfiguration::Release);
+
+ return result;
+}
+
+BuildConfiguration *Qt4BuildConfigurationFactory::create(Target *parent, const BuildInfo *info) const
+{
+ QTC_ASSERT(canCreate(parent), return 0);
+ QTC_ASSERT(info->factory() == this, return 0);
+ QTC_ASSERT(info->kitId == parent->kit()->id(), return 0);
+ QTC_ASSERT(!info->displayName.isEmpty(), return 0);
+
+ const QmakeBuildInfo *qmakeInfo = static_cast<const QmakeBuildInfo *>(info);
+
+ BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(parent->kit());
+ QTC_ASSERT(version, return 0);
+
+ BaseQtVersion::QmakeBuildConfigs config = version->defaultBuildConfig();
+ if (qmakeInfo->type == BuildConfiguration::Release)
+ config &= ~QtSupport::BaseQtVersion::DebugBuild;
+ else
+ config |= QtSupport::BaseQtVersion::DebugBuild;
+
+ Qt4BuildConfiguration *bc = new Qt4BuildConfiguration(parent);
+ bc->setDefaultDisplayName(info->displayName);
+ bc->setDisplayName(info->displayName);
+
+ 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);
+
+ QMakeStep *qmakeStep = new QMakeStep(buildSteps);
+ buildSteps->insertStep(0, qmakeStep);
+
+ MakeStep *makeStep = new MakeStep(buildSteps);
+ buildSteps->insertStep(1, makeStep);
+
+ MakeStep *cleanStep = new MakeStep(cleanSteps);
+ cleanStep->setClean(true);
+ cleanStep->setUserArguments(QLatin1String("clean"));
+ cleanSteps->insertStep(0, cleanStep);
+
+ QString additionalArguments = qmakeInfo->additionalArguments;
- //: Debug build configuration. We recommend not translating it.
- QString defaultFirstName = tr("%1 Debug").arg(version->displayName()).trimmed();
- QString customFirstName;
- if (buildConfigurationName != version->displayName())
- customFirstName = tr("%1 Debug").arg(buildConfigurationName).trimmed();
-
- //: Release build configuration. We recommend not translating it.
- QString defaultSecondName = tr("%1 Release").arg(version->displayName()).trimmed();
- QString customSecondName;
- if (buildConfigurationName != version->displayName())
- customSecondName = tr("%1 Release").arg(buildConfigurationName).trimmed();
-
- BaseQtVersion::QmakeBuildConfigs config = version->defaultBuildConfig() | QtSupport::BaseQtVersion::DebugBuild;
- BuildConfiguration *bc
- = Qt4BuildConfiguration::setup(parent, defaultFirstName, customFirstName,
- config, QString(), QString(), false);
-
- config = config ^ BaseQtVersion::DebugBuild;
- parent->addBuildConfiguration(
- Qt4BuildConfiguration::setup(parent, defaultSecondName, customSecondName,
- config,
- QString(), QString(), false));
+ bool enableQmlDebugger
+ = Qt4BuildConfiguration::removeQMLInspectorFromArguments(&additionalArguments);
+ if (!additionalArguments.isEmpty())
+ qmakeStep->setUserArguments(additionalArguments);
+ qmakeStep->setLinkQmlDebuggingLibrary(enableQmlDebugger);
+
+ bc->setQMakeBuildConfiguration(config);
+
+ Utils::FileName directory = qmakeInfo->buildDirectory;
+ if (directory.isEmpty()) {
+ directory = defaultBuildDirectory(qmakeInfo->supportsShadowBuild,
+ parent->project()->projectFilePath(),
+ parent->kit(), info->displayName);
+ }
+
+ bc->setBuildDirectory(directory);
return bc;
}
@@ -669,35 +696,6 @@ BuildConfiguration *Qt4BuildConfigurationFactory::restore(Target *parent, const
return 0;
}
-QList<BuildConfigurationInfo> Qt4BuildConfigurationFactory::availableBuildConfigurations(const Kit *k,
- const QString &proFilePath)
-{
- QList<BuildConfigurationInfo> infoList;
-
- BaseQtVersion *version = QtKitInformation::qtVersion(k);
- if (!version || !version->isValid())
- return infoList;
- 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 ^ BaseQtVersion::DebugBuild;
- info.directory = Qt4Project::shadowBuildDirectory(proFilePath, k, buildConfigurationDisplayName(info));
- infoList.append(info);
- return infoList;
-}
-
-// Return name of a build configuration.
-QString Qt4BuildConfigurationFactory::buildConfigurationDisplayName(const BuildConfigurationInfo &info)
-{
- 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.
- tr("Release");
-}
-
BuildConfiguration::BuildType Qt4BuildConfiguration::buildType() const
{
if (qmakeBuildConfiguration() & BaseQtVersion::DebugBuild)
@@ -706,48 +704,6 @@ BuildConfiguration::BuildType Qt4BuildConfiguration::buildType() const
return Release;
}
-Qt4BuildConfiguration *Qt4BuildConfiguration::setup(Target *t, QString defaultDisplayName,
- QString displayName,
- BaseQtVersion::QmakeBuildConfigs qmakeBuildConfiguration,
- QString additionalArguments, QString directory,
- bool importing)
-{
- // Add the build configuration.
- Qt4BuildConfiguration *bc = new Qt4BuildConfiguration(t);
- bc->setDefaultDisplayName(defaultDisplayName);
- bc->setDisplayName(displayName);
-
- 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);
-
- QMakeStep *qmakeStep = new QMakeStep(buildSteps);
- buildSteps->insertStep(0, qmakeStep);
-
- MakeStep *makeStep = new MakeStep(buildSteps);
- buildSteps->insertStep(1, makeStep);
-
- MakeStep *cleanStep = new MakeStep(cleanSteps);
- cleanStep->setClean(true);
- cleanStep->setUserArguments(QLatin1String("clean"));
- cleanSteps->insertStep(0, cleanStep);
-
- bool enableQmlDebugger
- = Qt4BuildConfiguration::removeQMLInspectorFromArguments(&additionalArguments);
- if (!additionalArguments.isEmpty())
- qmakeStep->setUserArguments(additionalArguments);
- if (importing)
- qmakeStep->setLinkQmlDebuggingLibrary(enableQmlDebugger);
-
- bc->setQMakeBuildConfiguration(qmakeBuildConfiguration);
-
- if (!directory.isEmpty())
- bc->setShadowBuildAndDirectory(directory != t->project()->projectDirectory(), directory);
-
- return bc;
-}
-
Qt4BuildConfiguration::LastKitState::LastKitState()
{
@@ -775,6 +731,4 @@ 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 1076541a72..a78d47d15d 100644
--- a/src/plugins/qt4projectmanager/qt4buildconfiguration.h
+++ b/src/plugins/qt4projectmanager/qt4buildconfiguration.h
@@ -39,26 +39,24 @@ namespace ProjectExplorer { class FileNode; }
namespace Qt4ProjectManager {
+class QmakeBuildInfo;
class QMakeStep;
class MakeStep;
class Qt4BuildConfigurationFactory;
class Qt4ProFileNode;
-class BuildConfigurationInfo;
+
+namespace Internal { class Qt4ProjectConfigWidget; }
class QT4PROJECTMANAGER_EXPORT Qt4BuildConfiguration : public ProjectExplorer::BuildConfiguration
{
Q_OBJECT
- friend class Qt4BuildConfigurationFactory;
public:
explicit Qt4BuildConfiguration(ProjectExplorer::Target *target);
~Qt4BuildConfiguration();
ProjectExplorer::NamedWidget *createConfigWidget();
- QString buildDirectory() const;
- bool shadowBuild() const;
- QString shadowBuildDirectory() const;
- void setShadowBuildAndDirectory(bool shadowBuild, const QString &buildDirectory);
+ bool isShadowBuild() const;
void setSubNodeBuild(Qt4ProjectManager::Qt4ProFileNode *node);
Qt4ProjectManager::Qt4ProFileNode *subNodeBuild() const;
@@ -103,13 +101,6 @@ public:
BuildType buildType() const;
- static Qt4BuildConfiguration *setup(ProjectExplorer::Target *t,
- QString defaultDisplayName,
- QString displayName,
- QtSupport::BaseQtVersion::QmakeBuildConfigs qmakeBuildConfiguration,
- QString additionalArguments,
- QString directory,
- bool importing);
/// returns whether the Qt version in the profile supports shadow building (also true for no Qt version)
bool supportsShadowBuilds();
@@ -120,12 +111,12 @@ signals:
/// emitted for setQMakeBuildConfig, not emitted for Qt version changes, even
/// if those change the qmakebuildconfig
void qmakeBuildConfigurationChanged();
+ void shadowBuildChanged();
private slots:
void kitChanged();
void toolChainUpdated(ProjectExplorer::ToolChain *tc);
void qtVersionsChanged(const QList<int> &, const QList<int> &, const QList<int> &changed);
- void emitBuildDirectoryChanged();
protected:
Qt4BuildConfiguration(ProjectExplorer::Target *target, Qt4BuildConfiguration *source);
@@ -134,8 +125,9 @@ protected:
private:
void ctor();
- QString rawBuildDirectory() const;
QString defaultShadowBuildDirectory() const;
+ void setBuildDirectory(const Utils::FileName &directory);
+ void updateShadowBuild();
class LastKitState
{
@@ -154,12 +146,13 @@ private:
bool m_shadowBuild;
bool m_isEnabled;
- QString m_buildDirectory;
- QString m_lastEmmitedBuildDirectory;
bool m_qtVersionSupportsShadowBuilds;
QtSupport::BaseQtVersion::QmakeBuildConfigs m_qmakeBuildConfiguration;
Qt4ProjectManager::Qt4ProFileNode *m_subNodeBuild;
ProjectExplorer::FileNode *m_fileNodeBuild;
+
+ friend class Internal::Qt4ProjectConfigWidget;
+ friend class Qt4BuildConfigurationFactory;
};
class QT4PROJECTMANAGER_EXPORT Qt4BuildConfigurationFactory : public ProjectExplorer::IBuildConfigurationFactory
@@ -170,24 +163,26 @@ public:
explicit Qt4BuildConfigurationFactory(QObject *parent = 0);
~Qt4BuildConfigurationFactory();
- QList<Core::Id> availableCreationIds(const ProjectExplorer::Target *parent) const;
- QString displayNameForId(const Core::Id id) const;
+ bool canCreate(const ProjectExplorer::Target *parent) const;
+ QList<ProjectExplorer::BuildInfo *> availableBuilds(const ProjectExplorer::Target *parent) const;
+ bool canSetup(const ProjectExplorer::Kit *k, const QString &projectPath) const;
+ QList<ProjectExplorer::BuildInfo *> availableSetups(const ProjectExplorer::Kit *k,
+ const QString &projectPath) const;
+ ProjectExplorer::BuildConfiguration *create(ProjectExplorer::Target *parent,
+ const ProjectExplorer::BuildInfo *info) const;
- bool canCreate(const ProjectExplorer::Target *parent, const Core::Id id) const;
- ProjectExplorer::BuildConfiguration *create(ProjectExplorer::Target *parent, const Core::Id id, const QString &name = QString());
bool canClone(const ProjectExplorer::Target *parent, ProjectExplorer::BuildConfiguration *source) const;
ProjectExplorer::BuildConfiguration *clone(ProjectExplorer::Target *parent, ProjectExplorer::BuildConfiguration *source);
bool canRestore(const ProjectExplorer::Target *parent, const QVariantMap &map) const;
ProjectExplorer::BuildConfiguration *restore(ProjectExplorer::Target *parent, const QVariantMap &map);
- static QList<BuildConfigurationInfo> availableBuildConfigurations(const ProjectExplorer::Kit *k, const QString &proFilePath);
- static QString buildConfigurationDisplayName(const BuildConfigurationInfo &info);
-
private slots:
void update();
private:
bool canHandle(const ProjectExplorer::Target *t) const;
+ QmakeBuildInfo *createBuildInfo(const ProjectExplorer::Kit *k, const QString &projectPath,
+ ProjectExplorer::BuildConfiguration::BuildType type) const;
};
} // namespace Qt4ProjectManager
diff --git a/src/plugins/qt4projectmanager/qt4nodes.cpp b/src/plugins/qt4projectmanager/qt4nodes.cpp
index 8d2efbe0ba..8fc2f68b56 100644
--- a/src/plugins/qt4projectmanager/qt4nodes.cpp
+++ b/src/plugins/qt4projectmanager/qt4nodes.cpp
@@ -31,7 +31,6 @@
#include "qt4project.h"
#include "qt4projectmanager.h"
#include "qt4projectmanagerconstants.h"
-#include "qtuicodemodelsupport.h"
#include "qt4buildconfiguration.h"
#include "qmakerunconfigurationfactory.h"
@@ -50,8 +49,10 @@
#include <projectexplorer/target.h>
#include <qtsupport/profilereader.h>
#include <qtsupport/qtkitinformation.h>
+#include <qtsupport/uicodemodelsupport.h>
#include <cpptools/cppmodelmanagerinterface.h>
+#include <cpptools/cpptoolsconstants.h>
#include <utils/hostosinfo.h>
#include <utils/stringutils.h>
@@ -172,7 +173,7 @@ using namespace Qt4ProjectManager::Internal;
Qt4PriFile::Qt4PriFile(Qt4ProjectManager::Qt4PriFileNode *qt4PriFile)
: IDocument(qt4PriFile), m_priFile(qt4PriFile)
{
-
+ setFilePath(m_priFile->path());
}
bool Qt4PriFile::save(QString *errorString, const QString &fileName, bool autoSave)
@@ -183,18 +184,6 @@ bool Qt4PriFile::save(QString *errorString, const QString &fileName, bool autoSa
return false;
}
-void Qt4PriFile::rename(const QString &newName)
-{
- // Can't happen
- Q_ASSERT(false);
- Q_UNUSED(newName);
-}
-
-QString Qt4PriFile::fileName() const
-{
- return m_priFile->path();
-}
-
QString Qt4PriFile::defaultPath() const
{
return QString();
@@ -568,7 +557,7 @@ QSet<Utils::FileName> Qt4PriFileNode::recursiveEnumerate(const QString &folder)
foreach (const QFileInfo &file, dir.entryInfoList()) {
if (file.isDir() && !file.isSymLink())
result += recursiveEnumerate(file.absoluteFilePath());
- else
+ else if (!Core::EditorManager::isAutoSaveFile(file.fileName()))
result += Utils::FileName(file);
}
} else if (fi.exists()) {
@@ -588,7 +577,7 @@ void Qt4PriFileNode::update(ProFile *includeFileExact, QtSupport::ProFileReader
InternalNode contents;
ProjectExplorer::Target *t = m_project->activeTarget();
- ProjectExplorer::Kit *k = t ? t->kit() : ProjectExplorer::KitManager::instance()->defaultKit();
+ ProjectExplorer::Kit *k = t ? t->kit() : ProjectExplorer::KitManager::defaultKit();
QtSupport::BaseQtVersion *qtVersion = QtSupport::QtKitInformation::qtVersion(k);
// Figure out DEPLOYMENT and INSTALL folders
@@ -610,6 +599,7 @@ void Qt4PriFileNode::update(ProFile *includeFileExact, QtSupport::ProFileReader
folders[i] = QDir::cleanPath(projectDir + QLatin1Char('/') + folders.at(i));
}
+ folders.removeDuplicates();
m_recursiveEnumerateFiles.clear();
// Remove non existing items and non folders
@@ -631,7 +621,6 @@ void Qt4PriFileNode::update(ProFile *includeFileExact, QtSupport::ProFileReader
}
}
- folders.removeDuplicates();
watchFolders(folders.toSet());
foreach (const QString &folder, folders) {
@@ -649,6 +638,7 @@ void Qt4PriFileNode::update(ProFile *includeFileExact, QtSupport::ProFileReader
const QVector<Qt4NodeStaticData::FileTypeData> &fileTypes = qt4NodeStaticData()->fileTypeData;
// update files
+ QFileInfo tmpFi;
for (int i = 0; i < fileTypes.size(); ++i) {
FileType type = fileTypes.at(i).type;
QStringList qmakeVariables = varNames(type);
@@ -658,14 +648,20 @@ void Qt4PriFileNode::update(ProFile *includeFileExact, QtSupport::ProFileReader
if (includeFileExact) {
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);
+ foreach (const QString &t, tmp) {
+ tmpFi.setFile(t);
+ if (tmpFi.isFile())
+ newFilePaths += Utils::FileName::fromString(t);
+ }
}
if (includeFileCumlative) {
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);
+ foreach (const QString &t, tmp) {
+ tmpFi.setFile(t);
+ if (tmpFi.isFile())
+ newFilePaths += Utils::FileName::fromString(t);
+ }
}
}
@@ -673,6 +669,7 @@ void Qt4PriFileNode::update(ProFile *includeFileExact, QtSupport::ProFileReader
m_recursiveEnumerateFiles.subtract(newFilePaths);
}
+
for (int i = 0; i < fileTypes.size(); ++i) {
FileType type = fileTypes.at(i).type;
QSet<Utils::FileName> newFilePaths = filterFilesProVariables(type, foundFiles[type]);
@@ -921,7 +918,7 @@ bool Qt4PriFileNode::addSubProjects(const QStringList &proFilePaths)
uniqueProFilePaths.append(simplifyProFilePath(proFile));
QStringList failedFiles;
- changeFiles(ProjectExplorer::ProjectFileType, uniqueProFilePaths, &failedFiles, AddToProFile);
+ changeFiles(QLatin1String(Constants::PROFILE_MIMETYPE), uniqueProFilePaths, &failedFiles, AddToProFile);
return failedFiles.isEmpty();
}
@@ -929,20 +926,19 @@ bool Qt4PriFileNode::addSubProjects(const QStringList &proFilePaths)
bool Qt4PriFileNode::removeSubProjects(const QStringList &proFilePaths)
{
QStringList failedOriginalFiles;
- changeFiles(ProjectExplorer::ProjectFileType, proFilePaths, &failedOriginalFiles, RemoveFromProFile);
+ changeFiles(QLatin1String(Constants::PROFILE_MIMETYPE), proFilePaths, &failedOriginalFiles, RemoveFromProFile);
QStringList simplifiedProFiles;
foreach (const QString &proFile, failedOriginalFiles)
simplifiedProFiles.append(simplifyProFilePath(proFile));
QStringList failedSimplifiedFiles;
- changeFiles(ProjectExplorer::ProjectFileType, simplifiedProFiles, &failedSimplifiedFiles, RemoveFromProFile);
+ changeFiles(QLatin1String(Constants::PROFILE_MIMETYPE), simplifiedProFiles, &failedSimplifiedFiles, RemoveFromProFile);
return failedSimplifiedFiles.isEmpty();
}
-bool Qt4PriFileNode::addFiles(const FileType fileType, const QStringList &filePaths,
- QStringList *notAdded)
+bool Qt4PriFileNode::addFiles(const QStringList &filePaths, QStringList *notAdded)
{
// If a file is already referenced in the .pro file then we don't add them.
// That ignores scopes and which variable was used to reference the file
@@ -953,68 +949,99 @@ bool Qt4PriFileNode::addFiles(const FileType fileType, const QStringList &filePa
accept(&visitor);
const QStringList &allFiles = visitor.filePaths();
- QStringList qrcFiles; // the list of qrc files referenced from ui files
- if (fileType == ProjectExplorer::FormType) {
- foreach (const QString &formFile, filePaths) {
- QStringList resourceFiles = formResources(formFile);
- foreach (const QString &resourceFile, resourceFiles)
- if (!qrcFiles.contains(resourceFile))
- qrcFiles.append(resourceFile);
- }
+ typedef QMap<QString, QStringList> TypeFileMap;
+ // Split into lists by file type and bulk-add them.
+ TypeFileMap typeFileMap;
+ foreach (const QString file, filePaths) {
+ const Core::MimeType mt = Core::MimeDatabase::findByFile(file);
+ typeFileMap[mt.type()] << file;
}
- QStringList uniqueQrcFiles;
- foreach (const QString &file, qrcFiles) {
- if (!allFiles.contains(file))
- uniqueQrcFiles.append(file);
- }
+ QStringList failedFiles;
+ foreach (const QString &type, typeFileMap.keys()) {
+ const QStringList typeFiles = typeFileMap.value(type);
+ QStringList qrcFiles; // the list of qrc files referenced from ui files
+ if (type == QLatin1String(ProjectExplorer::Constants::RESOURCE_MIMETYPE)) {
+ foreach (const QString &formFile, typeFiles) {
+ QStringList resourceFiles = formResources(formFile);
+ foreach (const QString &resourceFile, resourceFiles)
+ if (!qrcFiles.contains(resourceFile))
+ qrcFiles.append(resourceFile);
+ }
+ }
- QStringList uniqueFilePaths;
- foreach (const QString &file, filePaths) {
- if (!allFiles.contains(file))
- uniqueFilePaths.append(file);
- }
+ QStringList uniqueQrcFiles;
+ foreach (const QString &file, qrcFiles) {
+ if (!allFiles.contains(file))
+ uniqueQrcFiles.append(file);
+ }
- QStringList failedFiles;
- changeFiles(fileType, uniqueFilePaths, &failedFiles, AddToProFile);
- if (notAdded)
- *notAdded = failedFiles;
- changeFiles(ProjectExplorer::ResourceType, uniqueQrcFiles, &failedFiles, AddToProFile);
- if (notAdded)
- *notAdded += failedFiles;
+ QStringList uniqueFilePaths;
+ foreach (const QString &file, typeFiles) {
+ if (!allFiles.contains(file))
+ uniqueFilePaths.append(file);
+ }
+
+ changeFiles(type, uniqueFilePaths, &failedFiles, AddToProFile);
+ if (notAdded)
+ *notAdded += failedFiles;
+ changeFiles(QLatin1String(ProjectExplorer::Constants::RESOURCE_MIMETYPE), uniqueQrcFiles, &failedFiles, AddToProFile);
+ if (notAdded)
+ *notAdded += failedFiles;
+ }
return failedFiles.isEmpty();
}
-bool Qt4PriFileNode::removeFiles(const FileType fileType, const QStringList &filePaths,
+bool Qt4PriFileNode::removeFiles(const QStringList &filePaths,
QStringList *notRemoved)
{
QStringList failedFiles;
- changeFiles(fileType, filePaths, &failedFiles, RemoveFromProFile);
- if (notRemoved)
- *notRemoved = failedFiles;
+ typedef QMap<QString, QStringList> TypeFileMap;
+ // Split into lists by file type and bulk-add them.
+ TypeFileMap typeFileMap;
+ foreach (const QString file, filePaths) {
+ const Core::MimeType mt = Core::MimeDatabase::findByFile(file);
+ typeFileMap[mt.type()] << file;
+ }
+ foreach (const QString &type, typeFileMap.keys()) {
+ const QStringList typeFiles = typeFileMap.value(type);
+ changeFiles(type, typeFiles, &failedFiles, RemoveFromProFile);
+ if (notRemoved)
+ *notRemoved = failedFiles;
+ }
return failedFiles.isEmpty();
}
-bool Qt4PriFileNode::deleteFiles(const FileType fileType, const QStringList &filePaths)
+bool Qt4PriFileNode::deleteFiles(const QStringList &filePaths)
{
QStringList failedFiles;
- changeFiles(fileType, filePaths, &failedFiles, RemoveFromProFile);
+ typedef QMap<QString, QStringList> TypeFileMap;
+ // Split into lists by file type and bulk-add them.
+ TypeFileMap typeFileMap;
+ foreach (const QString file, filePaths) {
+ const Core::MimeType mt = Core::MimeDatabase::findByFile(file);
+ typeFileMap[mt.type()] << file;
+ }
+ foreach (const QString &type, typeFileMap.keys()) {
+ const QStringList typeFiles = typeFileMap.value(type);
+ changeFiles(type, typeFiles, &failedFiles, RemoveFromProFile);
+ }
return true;
}
-bool Qt4PriFileNode::renameFile(const FileType fileType, const QString &filePath,
- const QString &newFilePath)
+bool Qt4PriFileNode::renameFile(const QString &filePath, const QString &newFilePath)
{
if (newFilePath.isEmpty())
return false;
bool changeProFileOptional = deploysFolder(QFileInfo(filePath).absolutePath());
-
+ const Core::MimeType mt = Core::MimeDatabase::findByFile(newFilePath);
QStringList dummy;
- changeFiles(fileType, QStringList() << filePath, &dummy, RemoveFromProFile);
+
+ changeFiles(mt.type(), QStringList() << filePath, &dummy, RemoveFromProFile);
if (!dummy.isEmpty() && !changeProFileOptional)
return false;
- changeFiles(fileType, QStringList() << newFilePath, &dummy, AddToProFile);
+ changeFiles(mt.type(), QStringList() << newFilePath, &dummy, AddToProFile);
if (!dummy.isEmpty() && !changeProFileOptional)
return false;
return true;
@@ -1029,25 +1056,19 @@ bool Qt4PriFileNode::priFileWritable(const QString &path)
bool Qt4PriFileNode::saveModifiedEditors()
{
- QList<Core::IDocument*> modifiedDocuments;
-
- foreach (Core::IEditor *editor, Core::ICore::editorManager()->editorsForFileName(m_projectFilePath)) {
- if (Core::IDocument *editorDocument = editor->document()) {
- if (editorDocument->isModified())
- modifiedDocuments << editorDocument;
- }
- }
+ Core::IDocument *document
+ = Core::EditorManager::documentModel()->documentForFilePath(m_projectFilePath);
+ if (!document || !document->isModified())
+ return true;
- if (!modifiedDocuments.isEmpty()) {
- bool cancelled;
- Core::DocumentManager::saveModifiedDocuments(modifiedDocuments, &cancelled,
- tr("There are unsaved changes for project file %1.").arg(m_projectFilePath));
- if (cancelled)
- return false;
- // force instant reload of ourselves
- QtSupport::ProFileCacheManager::instance()->discardFile(m_projectFilePath);
- m_project->qt4ProjectManager()->notifyChanged(m_projectFilePath);
- }
+ bool cancelled;
+ Core::DocumentManager::saveModifiedDocuments(QList<Core::IDocument *>() << document, &cancelled,
+ tr("There are unsaved changes for project file %1.").arg(m_projectFilePath));
+ if (cancelled)
+ return false;
+ // force instant reload of ourselves
+ QtSupport::ProFileCacheManager::instance()->discardFile(m_projectFilePath);
+ m_project->qt4ProjectManager()->notifyChanged(m_projectFilePath);
return true;
}
@@ -1086,7 +1107,7 @@ QStringList Qt4PriFileNode::formResources(const QString &formFile) const
return resourceFiles;
}
-void Qt4PriFileNode::changeFiles(const FileType fileType,
+void Qt4PriFileNode::changeFiles(const QString &mimeType,
const QStringList &filePaths,
QStringList *notChanged,
ChangeType change)
@@ -1104,8 +1125,7 @@ void Qt4PriFileNode::changeFiles(const FileType fileType,
QFileInfo fi(m_projectFilePath);
if (!fi.isWritable()) {
// Try via vcs manager
- Core::VcsManager *vcsManager = Core::ICore::vcsManager();
- Core::IVersionControl *versionControl = vcsManager->findVersionControlForDirectory(fi.absolutePath());
+ Core::IVersionControl *versionControl = Core::VcsManager::findVersionControlForDirectory(fi.absolutePath());
if (!versionControl || versionControl->vcsOpen(m_projectFilePath)) {
bool makeWritable = QFile::setPermissions(m_projectFilePath, fi.permissions() | QFile::WriteUser);
if (!makeWritable) {
@@ -1137,16 +1157,14 @@ void Qt4PriFileNode::changeFiles(const FileType fileType,
includeFile = parser.parsedProBlock(contents, m_projectFilePath, 1);
}
- const QStringList vars = varNames(fileType);
QDir priFileDir = QDir(m_qt4ProFileNode->m_projectDir);
if (change == AddToProFile) {
// Use the first variable for adding.
- // Yes, that's broken for adding objective c sources or other stuff.
- ProWriter::addFiles(includeFile, &lines, priFileDir, filePaths, vars.first());
+ ProWriter::addFiles(includeFile, &lines, priFileDir, filePaths, varNameForAdding(mimeType));
notChanged->clear();
} else { // RemoveFromProFile
- *notChanged = ProWriter::removeFiles(includeFile, &lines, priFileDir, filePaths, vars);
+ *notChanged = ProWriter::removeFiles(includeFile, &lines, priFileDir, filePaths, varNamesForRemoving());
}
// save file
@@ -1160,12 +1178,11 @@ void Qt4PriFileNode::changeFiles(const FileType fileType,
// We manually tell each editor to reload it's file.
// (The .pro files are notified by the file system watcher.)
QStringList errorStrings;
- foreach (Core::IEditor *editor, Core::ICore::editorManager()->editorsForFileName(m_projectFilePath)) {
- if (Core::IDocument *editorDocument= editor->document()) {
- QString errorString;
- if (!editorDocument->reload(&errorString, Core::IDocument::FlagReload, Core::IDocument::TypeContents))
- errorStrings << errorString;
- }
+ Core::IDocument *document = Core::EditorManager::documentModel()->documentForFilePath(m_projectFilePath);
+ if (document) {
+ QString errorString;
+ if (!document->reload(&errorString, Core::IDocument::FlagReload, Core::IDocument::TypeContents))
+ errorStrings << errorString;
}
if (!errorStrings.isEmpty())
QMessageBox::warning(Core::ICore::mainWindow(), tr("File Error"),
@@ -1217,6 +1234,62 @@ QStringList Qt4PriFileNode::varNames(ProjectExplorer::FileType type)
return vars;
}
+//!
+//! \brief Qt4PriFileNode::varNames
+//! \param mimeType
+//! \return the qmake variable name for the mime type
+//! Note: Only used for adding.
+//!
+QString Qt4PriFileNode::varNameForAdding(const QString &mimeType)
+{
+ if (mimeType == QLatin1String(ProjectExplorer::Constants::CPP_HEADER_MIMETYPE)
+ || mimeType == QLatin1String(ProjectExplorer::Constants::C_HEADER_MIMETYPE)) {
+ return QLatin1String("HEADERS");
+ }
+
+ if (mimeType == QLatin1String(ProjectExplorer::Constants::CPP_SOURCE_MIMETYPE)
+ || mimeType == QLatin1String(ProjectExplorer::Constants::C_SOURCE_MIMETYPE)) {
+ return QLatin1String("SOURCES");
+ }
+
+ if (mimeType == QLatin1String(CppTools::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE))
+ return QLatin1String("OBJECTIVE_SOURCES");
+
+ if (mimeType == QLatin1String(ProjectExplorer::Constants::RESOURCE_MIMETYPE))
+ return QLatin1String("RESOURCES");
+
+ if (mimeType == QLatin1String(ProjectExplorer::Constants::FORM_MIMETYPE))
+ return QLatin1String("FORMS");
+
+ if (mimeType == QLatin1String(ProjectExplorer::Constants::QML_MIMETYPE))
+ return QLatin1String("OTHER_FILES");
+
+ if (mimeType == QLatin1String(Constants::PROFILE_MIMETYPE))
+ return QLatin1String("SUBDIRS");
+
+ return QLatin1String("OTHER_FILES");
+}
+
+//!
+//! \brief Qt4PriFileNode::varNamesForRemoving
+//! \return all qmake variables which are displayed in the project tree
+//! Note: Only used for removing.
+//!
+QStringList Qt4PriFileNode::varNamesForRemoving()
+{
+ QStringList vars;
+ vars << QLatin1String("HEADERS");
+ vars << QLatin1String("OBJECTIVE_HEADERS");
+ vars << QLatin1String("SOURCES");
+ vars << QLatin1String("OBJECTIVE_SOURCES");
+ vars << QLatin1String("RESOURCES");
+ vars << QLatin1String("FORMS");
+ vars << QLatin1String("OTHER_FILES");
+ vars << QLatin1String("SUBDIRS");
+ vars << QLatin1String("OTHER_FILES");
+ vars << QLatin1String("ICON");
+ return vars;
+}
QStringList Qt4PriFileNode::dynamicVarNames(QtSupport::ProFileReader *readerExact, QtSupport::ProFileReader *readerCumulative,
QtSupport::BaseQtVersion *qtVersion)
@@ -1249,7 +1322,7 @@ QStringList Qt4PriFileNode::dynamicVarNames(QtSupport::ProFileReader *readerExac
result << (var + files);
}
}
-
+ result.removeDuplicates();
return result;
}
@@ -1403,23 +1476,12 @@ Qt4ProFileNode::Qt4ProFileNode(Qt4Project *project,
if (parent)
setParent(parent);
- connect(ProjectExplorer::ProjectExplorerPlugin::instance()->buildManager(), SIGNAL(buildStateChanged(ProjectExplorer::Project*)),
- this, SLOT(buildStateChanged(ProjectExplorer::Project*)));
-
connect(&m_parseFutureWatcher, SIGNAL(finished()),
this, SLOT(applyAsyncEvaluate()));
}
Qt4ProFileNode::~Qt4ProFileNode()
{
- CppTools::CppModelManagerInterface *modelManager
- = CppTools::CppModelManagerInterface::instance();
- QMap<QString, Internal::Qt4UiCodeModelSupport *>::const_iterator it, end;
- end = m_uiCodeModelSupport.constEnd();
- for (it = m_uiCodeModelSupport.constBegin(); it != end; ++it) {
- modelManager->removeEditorSupport(it.value());
- delete it.value();
- }
m_parseFutureWatcher.waitForFinished();
if (m_readerExact) {
// Oh we need to clean up
@@ -1437,13 +1499,6 @@ bool Qt4ProFileNode::isParent(Qt4ProFileNode *node)
return false;
}
-void Qt4ProFileNode::buildStateChanged(ProjectExplorer::Project *project)
-{
- if (project == m_project
- && !ProjectExplorer::ProjectExplorerPlugin::instance()->buildManager()->isBuilding(m_project))
- updateCodeModelSupportFromBuild();
-}
-
bool Qt4ProFileNode::hasBuildTargets() const
{
return hasBuildTargets(projectType());
@@ -1476,9 +1531,9 @@ QString Qt4ProFileNode::singleVariableValue(const Qt4Variable var) const
return values.isEmpty() ? QString() : values.first();
}
-QStringList Qt4ProFileNode::uiFiles() const
+QHash<QString, QString> Qt4ProFileNode::uiFiles() const
{
- return m_uiHeaderFiles;
+ return m_uiFiles;
}
void Qt4ProFileNode::emitProFileUpdatedRecursive()
@@ -1689,7 +1744,7 @@ void Qt4ProFileNode::applyEvaluate(EvalResult evalResult, bool async)
QStringList subProjectsNotToDeploy;
if (evalResult == EvalOk) {
if (m_projectType == SubDirsTemplate) {
- newProjectFilesExact = subDirsPaths(m_readerExact, &subProjectsNotToDeploy);
+ newProjectFilesExact = subDirsPaths(m_readerExact, &subProjectsNotToDeploy, false);
exactSubdirs = newProjectFilesExact.toSet();
}
foreach (ProFile *includeFile, m_readerExact->includeFiles()) {
@@ -1706,7 +1761,7 @@ void Qt4ProFileNode::applyEvaluate(EvalResult evalResult, bool async)
QHash<QString, ProFile*> includeFilesCumlative;
ProFile *fileForCurrentProjectCumlative = 0;
if (m_projectType == SubDirsTemplate)
- newProjectFilesCumlative = subDirsPaths(m_readerCumulative);
+ newProjectFilesCumlative = subDirsPaths(m_readerCumulative, 0, true);
foreach (ProFile *includeFile, m_readerCumulative->includeFiles()) {
if (includeFile->fileName() == m_projectFilePath) {
fileForCurrentProjectCumlative = includeFile;
@@ -1908,6 +1963,7 @@ void Qt4ProFileNode::applyEvaluate(EvalResult evalResult, bool async)
newVarValues[StaticLibExtensionVar] = m_readerExact->values(QLatin1String("QMAKE_EXTENSION_STATICLIB"));
newVarValues[ShLibExtensionVar] = m_readerExact->values(QLatin1String("QMAKE_EXTENSION_SHLIB"));
newVarValues[AndroidArchVar] = m_readerExact->values(QLatin1String("ANDROID_TARGET_ARCH"));
+ newVarValues[AndroidDeploySettingsFile] = m_readerExact->values(QLatin1String("ANDROID_DEPLOYMENT_SETTINGS_FILE"));
m_isDeployable = false;
if (m_projectType == ApplicationTemplate) {
@@ -1933,7 +1989,7 @@ void Qt4ProFileNode::applyEvaluate(EvalResult evalResult, bool async)
setParseInProgress(false);
- createUiCodeModelSupport();
+ updateUiFiles();
m_project->destroyProFileReader(m_readerExact);
m_project->destroyProFileReader(m_readerCumulative);
@@ -2011,7 +2067,8 @@ QStringList Qt4ProFileNode::libDirectories(QtSupport::ProFileReader *reader) con
return result;
}
-QStringList Qt4ProFileNode::subDirsPaths(QtSupport::ProFileReader *reader, QStringList *subProjectsNotToDeploy) const
+QStringList Qt4ProFileNode::subDirsPaths(QtSupport::ProFileReader *reader, QStringList *subProjectsNotToDeploy,
+ bool silent) const
{
QStringList subProjectPaths;
@@ -2054,8 +2111,9 @@ QStringList Qt4ProFileNode::subDirsPaths(QtSupport::ProFileReader *reader, QStri
subProjectsNotToDeploy->append(realFile);
}
} else {
- m_project->proFileParseError(tr("Could not find .pro file for sub dir '%1' in '%2'")
- .arg(subDirVar).arg(realDir));
+ if (!silent)
+ m_project->proFileParseError(tr("Could not find .pro file for sub dir '%1' in '%2'")
+ .arg(subDirVar).arg(realDir));
}
}
@@ -2192,27 +2250,7 @@ QString Qt4ProFileNode::buildDir(Qt4BuildConfiguration *bc) const
bc = static_cast<Qt4BuildConfiguration *>(m_project->activeTarget()->activeBuildConfiguration());
if (!bc)
return QString();
- return QDir::cleanPath(QDir(bc->buildDirectory()).absoluteFilePath(relativeDir));
-}
-
-void Qt4ProFileNode::updateCodeModelSupportFromBuild()
-{
- 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,
- const QString &contents)
-{
- const QMap<QString, Internal::Qt4UiCodeModelSupport *>::const_iterator it =
- m_uiCodeModelSupport.constFind(uiFileName);
- if (it != m_uiCodeModelSupport.constEnd())
- it.value()->updateFromEditor(contents);
- foreach (ProjectExplorer::ProjectNode *pro, subProjectNodes())
- if (Qt4ProFileNode *qt4proFileNode = qobject_cast<Qt4ProFileNode *>(pro))
- qt4proFileNode->updateCodeModelSupportFromEditor(uiFileName, contents);
+ return QDir::cleanPath(QDir(bc->buildDirectory().toString()).absoluteFilePath(relativeDir));
}
QString Qt4ProFileNode::uiDirectory() const
@@ -2232,18 +2270,9 @@ QString Qt4ProFileNode::uiHeaderFile(const QString &uiDir, const QString &formFi
return QDir::cleanPath(uiHeaderFilePath);
}
-void Qt4ProFileNode::createUiCodeModelSupport()
+void Qt4ProFileNode::updateUiFiles()
{
-// qDebug()<<"creatUiCodeModelSupport()";
- CppTools::CppModelManagerInterface *modelManager
- = CppTools::CppModelManagerInterface::instance();
-
- // First move all to
- QMap<QString, Internal::Qt4UiCodeModelSupport *> oldCodeModelSupport;
- oldCodeModelSupport = m_uiCodeModelSupport;
- m_uiCodeModelSupport.clear();
-
- m_uiHeaderFiles.clear();
+ m_uiFiles.clear();
// Only those two project types can have ui files for us
if (m_projectType == ApplicationTemplate || m_projectType == LibraryTemplate) {
@@ -2254,30 +2283,7 @@ void Qt4ProFileNode::createUiCodeModelSupport()
// Find the UiDir, there can only ever be one
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()) {
-// qDebug()<<"updated old codemodelsupport";
- Internal::Qt4UiCodeModelSupport *cms = it.value();
- cms->setFileName(uiHeaderFilePath);
- m_uiCodeModelSupport.insert(it.key(), cms);
- oldCodeModelSupport.erase(it);
- } else {
-// qDebug()<<"adding new codemodelsupport";
- Internal::Qt4UiCodeModelSupport *cms = new Internal::Qt4UiCodeModelSupport(modelManager, m_project, uiFile->path(), uiHeaderFilePath);
- m_uiCodeModelSupport.insert(uiFile->path(), cms);
- modelManager->addEditorSupport(cms);
- }
- }
- }
- // Remove old
- QMap<QString, Internal::Qt4UiCodeModelSupport *>::const_iterator it, end;
- end = oldCodeModelSupport.constEnd();
- for (it = oldCodeModelSupport.constBegin(); it!=end; ++it) {
- modelManager->removeEditorSupport(it.value());
- delete it.value();
+ foreach (const ProjectExplorer::FileNode *uiFile, uiFiles)
+ m_uiFiles.insert(uiFile->path(), uiHeaderFile(uiDir, uiFile->path()));
}
}
diff --git a/src/plugins/qt4projectmanager/qt4nodes.h b/src/plugins/qt4projectmanager/qt4nodes.h
index 58ba3bdb89..d4b255bcf3 100644
--- a/src/plugins/qt4projectmanager/qt4nodes.h
+++ b/src/plugins/qt4projectmanager/qt4nodes.h
@@ -34,6 +34,7 @@
#include <coreplugin/idocument.h>
#include <projectexplorer/projectnodes.h>
+#include <qtsupport/uicodemodelsupport.h>
#include <QHash>
#include <QStringList>
@@ -104,7 +105,8 @@ enum Qt4Variable {
TargetVersionExtVar,
StaticLibExtensionVar,
ShLibExtensionVar,
- AndroidArchVar
+ AndroidArchVar,
+ AndroidDeploySettingsFile
};
// Import base classes into namespace
@@ -126,7 +128,6 @@ using ProjectExplorer::ProjectFileType;
using ProjectExplorer::FileType;
namespace Internal {
-class Qt4UiCodeModelSupport;
class Qt4PriFile;
struct InternalNode;
}
@@ -153,14 +154,10 @@ public:
bool addSubProjects(const QStringList &proFilePaths);
bool removeSubProjects(const QStringList &proFilePaths);
- bool addFiles(const FileType fileType, const QStringList &filePaths,
- QStringList *notAdded = 0);
- bool removeFiles(const FileType fileType, const QStringList &filePaths,
- QStringList *notRemoved = 0);
- bool deleteFiles(const FileType fileType,
- const QStringList &filePaths);
- bool renameFile(const FileType fileType,
- const QString &filePath, const QString &newFilePath);
+ bool addFiles(const QStringList &filePaths, QStringList *notAdded = 0);
+ bool removeFiles(const QStringList &filePaths, QStringList *notRemoved = 0);
+ bool deleteFiles(const QStringList &filePaths);
+ bool renameFile(const QString &filePath, const QString &newFilePath);
bool folderChanged(const QString &changedFolder, const QSet<Utils::FileName> &newFiles);
@@ -175,7 +172,9 @@ public:
static QSet<Utils::FileName> recursiveEnumerate(const QString &folder);
protected:
void setIncludedInExactParse(bool b);
- static QStringList varNames(FileType type);
+ static QStringList varNames(ProjectExplorer::FileType type);
+ static QStringList varNamesForRemoving();
+ static QString varNameForAdding(const QString &mimeType);
static QStringList dynamicVarNames(QtSupport::ProFileReader *readerExact, QtSupport::ProFileReader *readerCumulative, QtSupport::BaseQtVersion *qtVersion);
static QSet<Utils::FileName> filterFilesProVariables(ProjectExplorer::FileType fileType, const QSet<Utils::FileName> &files);
static QSet<Utils::FileName> filterFilesRecursiveEnumerata(ProjectExplorer::FileType fileType, const QSet<Utils::FileName> &files);
@@ -185,7 +184,7 @@ protected:
RemoveFromProFile
};
- void changeFiles(const FileType fileType,
+ void changeFiles(const QString &mimeType,
const QStringList &filePaths,
QStringList *notChanged,
ChangeType change);
@@ -207,7 +206,7 @@ private:
QString m_projectFilePath;
QString m_projectDir;
- QMap<QString, Internal::Qt4UiCodeModelSupport *> m_uiCodeModelSupport;
+ QMap<QString, QtSupport::UiCodeModelSupport *> m_uiCodeModelSupport;
Internal::Qt4PriFile *m_qt4PriFile;
// Memory is cheap...
@@ -230,8 +229,6 @@ class Qt4PriFile : public Core::IDocument
public:
Qt4PriFile(Qt4PriFileNode *qt4PriFile);
virtual bool save(QString *errorString, const QString &fileName, bool autoSave);
- virtual QString fileName() const;
- virtual void rename(const QString &newName);
virtual QString defaultPath() const;
virtual QString suggestedFileName() const;
@@ -374,15 +371,12 @@ public:
return !m_subProjectsNotToDeploy.contains(filePath);
}
- void updateCodeModelSupportFromBuild();
- void updateCodeModelSupportFromEditor(const QString &uiFileName, const QString &contents);
-
QString sourceDir() const;
QString buildDir(Qt4BuildConfiguration *bc = 0) const;
QString uiDirectory() const;
static QString uiHeaderFile(const QString &uiDir, const QString &formFile);
- QStringList uiFiles() const;
+ QHash<QString, QString> uiFiles() const;
const Qt4ProFileNode *findProFileFor(const QString &string) const;
TargetInformation targetInformation() const;
@@ -414,7 +408,6 @@ public slots:
void asyncUpdate();
private slots:
- void buildStateChanged(ProjectExplorer::Project*);
void applyAsyncEvaluate();
private:
@@ -427,7 +420,7 @@ private:
typedef QHash<Qt4Variable, QStringList> Qt4VariablesHash;
- void createUiCodeModelSupport();
+ void updateUiFiles();
QStringList fileListForVar(QtSupport::ProFileReader *readerExact, QtSupport::ProFileReader *readerCumulative,
const QString &varName, const QString &projectDir, const QString &buildDir) const;
@@ -435,7 +428,7 @@ private:
QString mocDirPath(QtSupport::ProFileReader *reader) const;
QStringList includePaths(QtSupport::ProFileReader *reader) const;
QStringList libDirectories(QtSupport::ProFileReader *reader) const;
- QStringList subDirsPaths(QtSupport::ProFileReader *reader, QStringList *subProjectsNotToDeploy = 0) const;
+ QStringList subDirsPaths(QtSupport::ProFileReader *reader, QStringList *subProjectsNotToDeploy, bool silent) const;
TargetInformation targetInformation(QtSupport::ProFileReader *reader) const;
void setupInstallsList(const QtSupport::ProFileReader *reader);
@@ -455,7 +448,7 @@ private:
InstallsList m_installsList;
friend class Qt4NodeHierarchy;
- QStringList m_uiHeaderFiles;
+ QHash<QString, QString> m_uiFiles; // ui-file path, ui header path
// Async stuff
QFutureWatcher<EvalResult> m_parseFutureWatcher;
diff --git a/src/plugins/qt4projectmanager/qt4project.cpp b/src/plugins/qt4projectmanager/qt4project.cpp
index a6e04bf8ea..2e48fcc904 100644
--- a/src/plugins/qt4projectmanager/qt4project.cpp
+++ b/src/plugins/qt4projectmanager/qt4project.cpp
@@ -30,17 +30,17 @@
#include "qt4project.h"
#include "qt4projectmanager.h"
+#include "qmakeprojectimporter.h"
+#include "qmakebuildinfo.h"
#include "qmakestep.h"
#include "qt4nodes.h"
#include "qt4projectmanagerconstants.h"
#include "qt4buildconfiguration.h"
#include "findqt4profiles.h"
-#include "buildconfigurationinfo.h"
#include "qt4projectmanager/wizards/abstractmobileapp.h"
#include "qt4projectmanager/wizards/qtquickapp.h"
#include "qt4projectmanager/wizards/html5app.h"
-#include <coreplugin/icore.h>
#include <coreplugin/icontext.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <coreplugin/documentmanager.h>
@@ -57,6 +57,7 @@
#include <proparser/qmakevfs.h>
#include <qtsupport/profilereader.h>
#include <qtsupport/qtkitinformation.h>
+#include <qtsupport/uicodemodelsupport.h>
#include <QDebug>
#include <QDir>
@@ -107,6 +108,7 @@ void updateBoilerPlateCodeFiles(const AbstractMobileApp *app, const QString &pro
}
}
}
+
} // namespace
namespace Qt4ProjectManager {
@@ -120,8 +122,6 @@ public:
Qt4ProjectFile(const QString &filePath, QObject *parent = 0);
bool save(QString *errorString, const QString &fileName, bool autoSave);
- QString fileName() const;
- virtual void rename(const QString &newName);
QString defaultPath() const;
QString suggestedFileName() const;
@@ -135,7 +135,6 @@ public:
private:
const QString m_mimeType;
- QString m_filePath;
};
/// Watches folders for Qt4PriFile nodes
@@ -270,9 +269,9 @@ void ProjectFilesVisitor::visitFolderNode(FolderNode *folderNode)
namespace Internal {
Qt4ProjectFile::Qt4ProjectFile(const QString &filePath, QObject *parent)
: Core::IDocument(parent),
- m_mimeType(QLatin1String(Qt4ProjectManager::Constants::PROFILE_MIMETYPE)),
- m_filePath(filePath)
+ m_mimeType(QLatin1String(Qt4ProjectManager::Constants::PROFILE_MIMETYPE))
{
+ setFilePath(filePath);
}
bool Qt4ProjectFile::save(QString *, const QString &, bool)
@@ -281,18 +280,6 @@ bool Qt4ProjectFile::save(QString *, const QString &, bool)
return false;
}
-void Qt4ProjectFile::rename(const QString &newName)
-{
- // Can't happen
- Q_UNUSED(newName);
- Q_ASSERT(false);
-}
-
-QString Qt4ProjectFile::fileName() const
-{
- return m_filePath;
-}
-
QString Qt4ProjectFile::defaultPath() const
{
return QString();
@@ -363,8 +350,7 @@ Qt4Project::Qt4Project(Qt4Manager *manager, const QString& fileName) :
m_asyncUpdateTimer.setInterval(3000);
connect(&m_asyncUpdateTimer, SIGNAL(timeout()), this, SLOT(asyncUpdate()));
- connect(ProjectExplorerPlugin::instance()->buildManager(),
- SIGNAL(buildQueueFinished(bool)),
+ connect(BuildManager::instance(), SIGNAL(buildQueueFinished(bool)),
SLOT(buildFinished(bool)));
}
@@ -395,32 +381,6 @@ 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))
@@ -438,7 +398,7 @@ bool Qt4Project::fromMap(const QVariantMap &map)
m_manager->registerProject(this);
- m_rootProjectNode = new Qt4ProFileNode(this, m_fileInfo->fileName(), this);
+ m_rootProjectNode = new Qt4ProFileNode(this, m_fileInfo->filePath(), this);
m_rootProjectNode->registerWatcher(m_nodesWatcher);
update();
@@ -466,7 +426,7 @@ bool Qt4Project::fromMap(const QVariantMap &map)
QtQuickApp qtQuickApp;
const Html5App html5App;
- foreach (Qt4ProFileNode *node, applicationProFiles()) {
+ foreach (Qt4ProFileNode *node, applicationProFiles(Qt4Project::ExactAndCumulativeParse)) {
const QString path = node->path();
qtQuickApp.setComponentSet(QtQuickApp::QtQuick10Components);
@@ -525,7 +485,7 @@ void Qt4Project::updateCppCodeModel()
if (ProjectExplorer::Target *target = activeTarget())
k = target->kit();
else
- k = KitManager::instance()->defaultKit();
+ k = KitManager::defaultKit();
qtVersion = QtSupport::QtKitInformation::qtVersion(k);
CppTools::CppModelManagerInterface *modelmanager =
@@ -547,6 +507,7 @@ void Qt4Project::updateCppCodeModel()
qtVersionForPart = ProjectPart::Qt5;
}
+ QHash<QString, QString> uiCodeModelData;
QStringList allFiles;
foreach (Qt4ProFileNode *pro, proFiles) {
ProjectPart::Ptr part(new ProjectPart);
@@ -594,16 +555,22 @@ void Qt4Project::updateCppCodeModel()
allFiles << file;
part->files << ProjectFile(file, ProjectFile::CXXHeader);
}
- foreach (const QString &file, pro->uiFiles()) {
- allFiles << file;
- part->files << ProjectFile(file, ProjectFile::CXXHeader);
+
+ // Ui Files:
+ QHash<QString, QString> uiData = pro->uiFiles();
+ for (QHash<QString, QString>::const_iterator i = uiData.constBegin(); i != uiData.constEnd(); ++i) {
+ allFiles << i.value();
+ part->files << ProjectFile(i.value(), ProjectFile::CXXHeader);
}
+ uiCodeModelData.unite(uiData);
part->files.prepend(ProjectFile(CppTools::CppModelManagerInterface::configurationFileName(),
ProjectFile::CXXSource));
foreach (const QString &file, pro->variableValue(ObjCSourceVar)) {
allFiles << file;
- part->files << ProjectFile(file, ProjectFile::ObjCSource);
+ // Although the enum constant is called ObjCSourceVar, it actually is ObjC++ source
+ // code, as qmake does not handle C (and ObjC).
+ part->files << ProjectFile(file, ProjectFile::ObjCXXSource);
}
foreach (const QString &file, pro->variableValue(ObjCHeaderVar)) {
allFiles << file;
@@ -615,6 +582,9 @@ void Qt4Project::updateCppCodeModel()
setProjectLanguage(ProjectExplorer::Constants::LANG_CXX, !allFiles.isEmpty());
+ // Also update Ui Code Model Support:
+ QtSupport::UiCodeModelManager::update(this, uiCodeModelData);
+
m_codeModelFuture = modelmanager->updateProjectInfo(pinfo);
}
@@ -683,8 +653,8 @@ void Qt4Project::update()
void Qt4Project::updateRunConfigurations()
{
- foreach (Target *t, targets())
- t->updateDefaultRunConfigurations();
+ if (activeTarget())
+ activeTarget()->updateDefaultRunConfigurations();
}
void Qt4Project::scheduleAsyncUpdate(Qt4ProFileNode *node)
@@ -861,11 +831,9 @@ void Qt4Project::asyncUpdate()
Q_ASSERT(!m_asyncUpdateFutureInterface);
m_asyncUpdateFutureInterface = new QFutureInterface<void>();
- Core::ProgressManager *progressManager = Core::ICore::progressManager();
-
m_asyncUpdateFutureInterface->setProgressRange(0, 0);
- progressManager->addTask(m_asyncUpdateFutureInterface->future(), tr("Evaluating"),
- QLatin1String(Constants::PROFILE_EVALUATE));
+ Core::ProgressManager::addTask(m_asyncUpdateFutureInterface->future(), tr("Evaluating"),
+ Constants::PROFILE_EVALUATE);
if (debug)
qDebug()<<" adding task";
@@ -914,7 +882,7 @@ bool Qt4Project::supportsKit(Kit *k, QString *errorMessage) const
QString Qt4Project::displayName() const
{
- return QFileInfo(document()->fileName()).completeBaseName();
+ return QFileInfo(projectFilePath()).completeBaseName();
}
Core::Id Qt4Project::id() const
@@ -972,7 +940,7 @@ QString Qt4Project::generatedUiHeader(const QString &formFile) const
void Qt4Project::proFileParseError(const QString &errorMessage)
{
- Core::ICore::messageManager()->printToOutputPane(errorMessage, Core::MessageManager::NoModeSwitch);
+ Core::MessageManager::write(errorMessage);
}
QtSupport::ProFileReader *Qt4Project::createProFileReader(const Qt4ProFileNode *qt4ProFileNode, Qt4BuildConfiguration *bc)
@@ -995,7 +963,7 @@ QtSupport::ProFileReader *Qt4Project::createProFileReader(const Qt4ProFileNode *
else
qmakeArgs = bc->configCommandLineArguments();
} else {
- k = KitManager::instance()->defaultKit();
+ k = KitManager::defaultKit();
}
QtSupport::BaseQtVersion *qtVersion = QtSupport::QtKitInformation::qtVersion(k);
@@ -1035,7 +1003,7 @@ void Qt4Project::destroyProFileReader(QtSupport::ProFileReader *reader)
{
delete reader;
if (!--m_qmakeGlobalsRefCnt) {
- QString dir = QFileInfo(m_fileInfo->fileName()).absolutePath();
+ QString dir = QFileInfo(m_fileInfo->filePath()).absolutePath();
if (!dir.endsWith(QLatin1Char('/')))
dir += QLatin1Char('/');
QtSupport::ProFileCacheManager::instance()->discardFiles(dir);
@@ -1072,44 +1040,46 @@ bool Qt4Project::parseInProgress(const QString &proFilePath) const
return node && node->parseInProgress();
}
-void Qt4Project::collectAllfProFiles(QList<Qt4ProFileNode *> &list, Qt4ProFileNode *node)
+void Qt4Project::collectAllfProFiles(QList<Qt4ProFileNode *> &list, Qt4ProFileNode *node, Parsing parse)
{
- list.append(node);
+ if (parse == ExactAndCumulativeParse || node->includedInExactParse())
+ list.append(node);
foreach (ProjectNode *n, node->subProjectNodes()) {
Qt4ProFileNode *qt4ProFileNode = qobject_cast<Qt4ProFileNode *>(n);
if (qt4ProFileNode)
- collectAllfProFiles(list, qt4ProFileNode);
+ collectAllfProFiles(list, qt4ProFileNode, parse);
}
}
-void Qt4Project::collectApplicationProFiles(QList<Qt4ProFileNode *> &list, Qt4ProFileNode *node)
+void Qt4Project::collectApplicationProFiles(QList<Qt4ProFileNode *> &list, Qt4ProFileNode *node, Parsing parse)
{
if (node->projectType() == ApplicationTemplate
|| node->projectType() == ScriptTemplate) {
- list.append(node);
+ if (parse == ExactAndCumulativeParse || node->includedInExactParse())
+ list.append(node);
}
foreach (ProjectNode *n, node->subProjectNodes()) {
Qt4ProFileNode *qt4ProFileNode = qobject_cast<Qt4ProFileNode *>(n);
if (qt4ProFileNode)
- collectApplicationProFiles(list, qt4ProFileNode);
+ collectApplicationProFiles(list, qt4ProFileNode, parse);
}
}
-QList<Qt4ProFileNode *> Qt4Project::allProFiles() const
+QList<Qt4ProFileNode *> Qt4Project::allProFiles(Parsing parse) const
{
QList<Qt4ProFileNode *> list;
if (!rootProjectNode())
return list;
- collectAllfProFiles(list, rootQt4ProjectNode());
+ collectAllfProFiles(list, rootQt4ProjectNode(), parse);
return list;
}
-QList<Qt4ProFileNode *> Qt4Project::applicationProFiles() const
+QList<Qt4ProFileNode *> Qt4Project::applicationProFiles(Parsing parse) const
{
QList<Qt4ProFileNode *> list;
if (!rootProjectNode())
return list;
- collectApplicationProFiles(list, rootQt4ProjectNode());
+ collectApplicationProFiles(list, rootQt4ProjectNode(), parse);
return list;
}
@@ -1125,10 +1095,10 @@ bool Qt4Project::hasApplicationProFile(const QString &path) const
return false;
}
-QStringList Qt4Project::applicationProFilePathes(const QString &prepend) const
+QStringList Qt4Project::applicationProFilePathes(const QString &prepend, Parsing parse) const
{
QStringList proFiles;
- foreach (Qt4ProFileNode *node, applicationProFiles())
+ foreach (Qt4ProFileNode *node, applicationProFiles(parse))
proFiles.append(prepend + node->path());
return proFiles;
}
@@ -1394,7 +1364,8 @@ bool Qt4Project::needsConfiguration() const
void Qt4Project::configureAsExampleProject(const QStringList &platforms)
{
- QList<Kit *> kits = ProjectExplorer::KitManager::instance()->kits();
+ QList<const BuildInfo *> infoList;
+ QList<Kit *> kits = ProjectExplorer::KitManager::kits();
foreach (Kit *k, kits) {
QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(k);
if (!version)
@@ -1402,12 +1373,14 @@ void Qt4Project::configureAsExampleProject(const QStringList &platforms)
if (!platforms.isEmpty() && !platforms.contains(version->platformName()))
continue;
- QList<BuildConfigurationInfo> infoList
- = Qt4BuildConfigurationFactory::availableBuildConfigurations(k, document()->fileName());
- if (infoList.isEmpty())
+ IBuildConfigurationFactory *factory = IBuildConfigurationFactory::find(k, projectFilePath());
+ if (!factory)
continue;
- addTarget(createTarget(k, infoList));
+ foreach (BuildInfo *info, factory->availableSetups(k, projectFilePath()))
+ infoList << info;
}
+ setup(infoList);
+ qDeleteAll(infoList);
ProjectExplorer::ProjectExplorerPlugin::instance()->requestProjectModeUpdate(this);
}
@@ -1461,16 +1434,6 @@ QString Qt4Project::buildNameFor(const Kit *k)
return k->fileSystemFriendlyName();
}
-Target *Qt4Project::createTarget(Kit *k, const QList<BuildConfigurationInfo> &infoList)
-{
- if (target(k))
- return 0;
-
- Target *t = new Target(this, k);
- setupTarget(t, infoList);
- return t;
-}
-
void Qt4Project::updateBuildSystemData()
{
Target * const target = activeTarget();
@@ -1658,6 +1621,12 @@ void Qt4Project::emitBuildDirectoryInitialized()
{
emit buildDirectoryInitialized();
}
+
+ProjectImporter *Qt4Project::createProjectImporter() const
+{
+ return new QmakeProjectImporter(projectFilePath());
+}
+
} // namespace Qt4ProjectManager
#include "qt4project.moc"
diff --git a/src/plugins/qt4projectmanager/qt4project.h b/src/plugins/qt4projectmanager/qt4project.h
index a4bb93b1b3..751a22c01c 100644
--- a/src/plugins/qt4projectmanager/qt4project.h
+++ b/src/plugins/qt4projectmanager/qt4project.h
@@ -49,7 +49,6 @@ namespace ProjectExplorer { class DeploymentData; }
namespace QtSupport { class ProFileReader; }
namespace Qt4ProjectManager {
-class BuildConfigurationInfo;
class MakeStep;
class QMakeStep;
class Qt4BuildConfiguration;
@@ -93,10 +92,11 @@ public:
virtual QStringList files(FilesMode fileMode) const;
virtual QString generatedUiHeader(const QString &formFile) const;
- QList<Qt4ProFileNode *> allProFiles() const;
- QList<Qt4ProFileNode *> applicationProFiles() const;
+ enum Parsing {ExactParse, ExactAndCumulativeParse };
+ QList<Qt4ProFileNode *> allProFiles(Parsing parse = ExactParse) const;
+ QList<Qt4ProFileNode *> applicationProFiles(Parsing parse = ExactParse) const;
bool hasApplicationProFile(const QString &path) const;
- QStringList applicationProFilePathes(const QString &prepend = QString()) const;
+ QStringList applicationProFilePathes(const QString &prepend = QString(), Parsing parse = ExactParse) const;
void notifyChanged(const QString &name);
@@ -138,10 +138,10 @@ public:
/// used by the default implementation of shadowBuildDirectory
static QString buildNameFor(const ProjectExplorer::Kit *k);
- ProjectExplorer::Target *createTarget(ProjectExplorer::Kit *k, const QList<BuildConfigurationInfo> &infoList);
-
void emitBuildDirectoryInitialized();
+ ProjectExplorer::ProjectImporter *createProjectImporter() const;
+
signals:
void proFileUpdated(Qt4ProjectManager::Qt4ProFileNode *node, bool, bool);
void buildDirectoryInitialized();
@@ -154,8 +154,6 @@ 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();
@@ -170,15 +168,13 @@ private:
void updateCppCodeModel();
void updateQmlJSCodeModel();
- static void collectAllfProFiles(QList<Qt4ProFileNode *> &list, Qt4ProFileNode *node);
- static void collectApplicationProFiles(QList<Qt4ProFileNode *> &list, Qt4ProFileNode *node);
+ static void collectAllfProFiles(QList<Qt4ProFileNode *> &list, Qt4ProFileNode *node, Parsing parse);
+ static void collectApplicationProFiles(QList<Qt4ProFileNode *> &list, Qt4ProFileNode *node, Parsing parse);
static void findProFile(const QString& fileName, Qt4ProFileNode *root, QList<Qt4ProFileNode *> &list);
static bool hasSubNode(Qt4PriFileNode *root, const QString &path);
static bool equalFileList(const QStringList &a, const QStringList &b);
- static QString qmakeVarName(ProjectExplorer::FileType type);
-
void updateBuildSystemData();
void collectData(const Qt4ProFileNode *node, ProjectExplorer::DeploymentData &deploymentData);
void collectApplicationData(const Qt4ProFileNode *node,
diff --git a/src/plugins/qt4projectmanager/qt4projectconfigwidget.cpp b/src/plugins/qt4projectmanager/qt4projectconfigwidget.cpp
index 2140e8f600..4c6e41636c 100644
--- a/src/plugins/qt4projectmanager/qt4projectconfigwidget.cpp
+++ b/src/plugins/qt4projectmanager/qt4projectconfigwidget.cpp
@@ -48,6 +48,11 @@ Qt4ProjectConfigWidget::Qt4ProjectConfigWidget(Qt4BuildConfiguration *bc)
m_buildConfiguration(bc),
m_ignoreChange(false)
{
+ m_defaultShadowBuildDir
+ = Qt4Project::shadowBuildDirectory(bc->target()->project()->projectFilePath(),
+ bc->target()->kit(),
+ Utils::FileUtils::fileSystemFriendlyName(bc->displayName()));
+
QVBoxLayout *vbox = new QVBoxLayout(this);
vbox->setMargin(0);
m_detailsContainer = new Utils::DetailsWidget(this);
@@ -62,6 +67,21 @@ Qt4ProjectConfigWidget::Qt4ProjectConfigWidget(Qt4BuildConfiguration *bc)
m_ui->shadowBuildDirEdit->setPromptDialogTitle(tr("Shadow Build Directory"));
m_ui->shadowBuildDirEdit->setExpectedKind(Utils::PathChooser::ExistingDirectory);
+ m_ui->shadowBuildDirEdit->setEnvironment(bc->environment());
+ m_ui->shadowBuildDirEdit->setBaseDirectory(bc->target()->project()->projectDirectory());
+ bool isShadowBuild = bc->isShadowBuild();
+ if (isShadowBuild) {
+ m_ui->shadowBuildDirEdit->setPath(bc->rawBuildDirectory().toString());
+ m_ui->inSourceBuildDirEdit->setVisible(false);
+ } else {
+ m_ui->shadowBuildDirEdit->setPath(m_defaultShadowBuildDir);
+ m_ui->shadowBuildDirEdit->setVisible(false);
+ }
+ m_ui->inSourceBuildDirEdit->setPath(bc->target()->project()->projectDirectory());
+ m_ui->inSourceBuildDirEdit->setReadOnly(true);
+ m_ui->inSourceBuildDirEdit->setEnabled(false);
+
+ m_ui->shadowBuildCheckBox->setChecked(isShadowBuild);
connect(m_ui->shadowBuildCheckBox, SIGNAL(clicked(bool)),
this, SLOT(shadowBuildClicked(bool)));
@@ -79,18 +99,15 @@ Qt4ProjectConfigWidget::Qt4ProjectConfigWidget(Qt4BuildConfiguration *bc)
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()));
- m_ui->shadowBuildDirEdit->setBaseDirectory(m_buildConfiguration->target()->project()->projectDirectory());
-
- buildDirectoryChanged();
-
setDisplayName(tr("General"));
+
+ updateDetails();
+ updateProblemLabel();
}
Qt4ProjectConfigWidget::~Qt4ProjectConfigWidget()
@@ -102,7 +119,7 @@ void Qt4ProjectConfigWidget::updateDetails()
{
m_detailsContainer->setSummaryText(
tr("building in <b>%1</b>")
- .arg(QDir::toNativeSeparators(m_buildConfiguration->buildDirectory())));
+ .arg(m_buildConfiguration->buildDirectory().toUserOutput()));
}
void Qt4ProjectConfigWidget::setProblemLabel(const QString &text)
@@ -121,12 +138,16 @@ void Qt4ProjectConfigWidget::buildDirectoryChanged()
{
if (m_ignoreChange)
return;
- m_ui->shadowBuildDirEdit->setPath(m_buildConfiguration->shadowBuildDirectory());
- bool shadowBuild = m_buildConfiguration->shadowBuild();
- m_ui->shadowBuildCheckBox->setChecked(shadowBuild);
+
+ bool shadowBuild = m_ui->shadowBuildCheckBox->isChecked();
+ m_ui->inSourceBuildDirEdit->setVisible(!shadowBuild);
+
+ m_ui->shadowBuildDirEdit->setVisible(shadowBuild);
m_ui->shadowBuildDirEdit->setEnabled(shadowBuild);
m_browseButton->setEnabled(shadowBuild);
+ m_ui->shadowBuildDirEdit->setPath(m_buildConfiguration->rawBuildDirectory().toString());
+
updateDetails();
updateProblemLabel();
}
@@ -142,10 +163,15 @@ void Qt4ProjectConfigWidget::shadowBuildClicked(bool checked)
{
m_ui->shadowBuildDirEdit->setEnabled(checked);
m_browseButton->setEnabled(checked);
- bool b = m_ui->shadowBuildCheckBox->isChecked();
+
+ m_ui->shadowBuildDirEdit->setVisible(checked);
+ m_ui->inSourceBuildDirEdit->setVisible(!checked);
m_ignoreChange = true;
- m_buildConfiguration->setShadowBuildAndDirectory(b, m_ui->shadowBuildDirEdit->rawPath());
+ if (checked)
+ m_buildConfiguration->setBuildDirectory(Utils::FileName::fromString(m_ui->shadowBuildDirEdit->rawPath()));
+ else
+ m_buildConfiguration->setBuildDirectory(Utils::FileName::fromString(m_ui->inSourceBuildDirEdit->rawPath()));
m_ignoreChange = false;
updateDetails();
@@ -154,24 +180,19 @@ void Qt4ProjectConfigWidget::shadowBuildClicked(bool checked)
void Qt4ProjectConfigWidget::shadowBuildEdited()
{
- if (m_buildConfiguration->shadowBuildDirectory() == m_ui->shadowBuildDirEdit->rawPath())
+ if (m_buildConfiguration->rawBuildDirectory().toString() == m_ui->shadowBuildDirEdit->rawPath())
return;
+
m_ignoreChange = true;
- m_buildConfiguration->setShadowBuildAndDirectory(m_buildConfiguration->shadowBuild(), m_ui->shadowBuildDirEdit->rawPath());
+ m_buildConfiguration->setBuildDirectory(Utils::FileName::fromString(m_ui->shadowBuildDirEdit->rawPath()));
m_ignoreChange = false;
-
- // if the directory already exists
- // check if we have a build in there and
- // offer to import it
- updateProblemLabel();
- updateDetails();
}
void Qt4ProjectConfigWidget::updateProblemLabel()
{
m_ui->shadowBuildDirEdit->triggerChanged();
ProjectExplorer::Kit *k = m_buildConfiguration->target()->kit();
- const QString proFileName = m_buildConfiguration->target()->project()->document()->fileName();
+ const QString proFileName = m_buildConfiguration->target()->project()->projectFilePath();
// Check for Qt version:
QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(k);
@@ -191,7 +212,7 @@ void Qt4ProjectConfigWidget::updateProblemLabel()
bool allGood = false;
// we only show if we actually have a qmake and makestep
if (m_buildConfiguration->qmakeStep() && m_buildConfiguration->makeStep()) {
- QString makefile = m_buildConfiguration->buildDirectory() + QLatin1Char('/');
+ QString makefile = m_buildConfiguration->buildDirectory().toString() + QLatin1Char('/');
if (m_buildConfiguration->makefile().isEmpty())
makefile.append(QLatin1String("Makefile"));
else
@@ -214,16 +235,16 @@ void Qt4ProjectConfigWidget::updateProblemLabel()
}
QString shadowBuildWarning;
- if (!version->supportsShadowBuilds() && m_buildConfiguration->shadowBuild()) {
+ if (!version->supportsShadowBuilds() && m_buildConfiguration->isShadowBuild()) {
shadowBuildWarning = tr("The Qt version %1 does not support shadow builds, building might fail.")
.arg(version->displayName())
+ QLatin1String("<br>");
}
if (allGood) {
- QString buildDirectory = m_buildConfiguration->target()->project()->projectDirectory();;
- if (m_buildConfiguration->shadowBuild())
- buildDirectory = m_buildConfiguration->buildDirectory();
+ QString buildDirectory = m_buildConfiguration->target()->project()->projectDirectory();
+ if (m_buildConfiguration->isShadowBuild())
+ buildDirectory = m_buildConfiguration->buildDirectory().toString();
QList<ProjectExplorer::Task> issues;
issues = version->reportIssues(proFileName, buildDirectory);
qSort(issues);
@@ -255,12 +276,12 @@ void Qt4ProjectConfigWidget::updateProblemLabel()
} else if (targetMismatch) {
setProblemLabel(shadowBuildWarning + tr("A build for a different project exists in %1, which will be overwritten.",
"%1 build directory")
- .arg(QDir::toNativeSeparators(m_buildConfiguration->buildDirectory())));
+ .arg(m_buildConfiguration->buildDirectory().toUserOutput()));
return;
} else if (incompatibleBuild) {
setProblemLabel(shadowBuildWarning +tr("An incompatible build exists in %1, which will be overwritten.",
"%1 build directory")
- .arg(QDir::toNativeSeparators(m_buildConfiguration->buildDirectory())));
+ .arg(m_buildConfiguration->buildDirectory().toUserOutput()));
return;
} else if (!shadowBuildWarning.isEmpty()) {
setProblemLabel(shadowBuildWarning);
diff --git a/src/plugins/qt4projectmanager/qt4projectconfigwidget.h b/src/plugins/qt4projectmanager/qt4projectconfigwidget.h
index 01dcdf38b8..327d75c8c2 100644
--- a/src/plugins/qt4projectmanager/qt4projectconfigwidget.h
+++ b/src/plugins/qt4projectmanager/qt4projectconfigwidget.h
@@ -75,6 +75,7 @@ private:
QAbstractButton *m_browseButton;
Qt4BuildConfiguration *m_buildConfiguration;
Utils::DetailsWidget *m_detailsContainer;
+ QString m_defaultShadowBuildDir;
bool m_ignoreChange;
};
diff --git a/src/plugins/qt4projectmanager/qt4projectconfigwidget.ui b/src/plugins/qt4projectmanager/qt4projectconfigwidget.ui
index 35f7acd185..3ec29088cd 100644
--- a/src/plugins/qt4projectmanager/qt4projectconfigwidget.ui
+++ b/src/plugins/qt4projectmanager/qt4projectconfigwidget.ui
@@ -11,6 +11,20 @@
</rect>
</property>
<layout class="QGridLayout" name="gridLayout">
+ <item row="0" column="0">
+ <widget class="QLabel" name="shadowBuildLabel">
+ <property name="text">
+ <string>Shadow build:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="1">
+ <widget class="QCheckBox" name="shadowBuildCheckBox">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
<item row="1" column="0">
<widget class="QLabel" name="buildDirLabel">
<property name="sizePolicy">
@@ -24,6 +38,23 @@
</property>
</widget>
</item>
+ <item row="1" column="1">
+ <layout class="QHBoxLayout" name="horizontalLayout">
+ <item>
+ <widget class="Utils::PathChooser" name="shadowBuildDirEdit" native="true">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Expanding" vsizetype="Preferred">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="Utils::PathChooser" name="inSourceBuildDirEdit" native="true"/>
+ </item>
+ </layout>
+ </item>
<item row="2" column="1">
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
@@ -51,30 +82,6 @@
</item>
</layout>
</item>
- <item row="0" column="0">
- <widget class="QLabel" name="shadowBuildLabel">
- <property name="text">
- <string>Shadow build:</string>
- </property>
- </widget>
- </item>
- <item row="1" column="1">
- <widget class="Utils::PathChooser" name="shadowBuildDirEdit" native="true">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Expanding" vsizetype="Preferred">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- </widget>
- </item>
- <item row="0" column="1">
- <widget class="QCheckBox" name="shadowBuildCheckBox">
- <property name="text">
- <string/>
- </property>
- </widget>
- </item>
</layout>
</widget>
<customwidgets>
diff --git a/src/plugins/qt4projectmanager/qt4projectmanager.cpp b/src/plugins/qt4projectmanager/qt4projectmanager.cpp
index b3d2c3d0d9..54ce6f8bce 100644
--- a/src/plugins/qt4projectmanager/qt4projectmanager.cpp
+++ b/src/plugins/qt4projectmanager/qt4projectmanager.cpp
@@ -51,17 +51,10 @@
#include <QVariant>
#include <QMessageBox>
+using namespace ProjectExplorer;
using namespace Qt4ProjectManager;
using namespace Qt4ProjectManager::Internal;
-using ProjectExplorer::BuildStep;
-using ProjectExplorer::FileType;
-using ProjectExplorer::HeaderType;
-using ProjectExplorer::SourceType;
-using ProjectExplorer::FormType;
-using ProjectExplorer::ResourceType;
-using ProjectExplorer::UnknownFileType;
-
// Known file types of a Qt 4 project
static const char *qt4FileTypes[] = {
"CppHeaderFiles",
@@ -70,27 +63,11 @@ static const char *qt4FileTypes[] = {
"Qt4ResourceFiles"
};
-// Test for form editor (loosely coupled)
-static inline bool isFormWindowEditor(const QObject *o)
-{
- return o && !qstrcmp(o->metaObject()->className(), "Designer::FormWindowEditor");
-}
-
-// Return contents of form editor (loosely coupled)
-static inline QString formWindowEditorContents(const QObject *editor)
-{
- const QVariant contentV = editor->property("contents");
- QTC_ASSERT(contentV.isValid(), return QString());
- return contentV.toString();
-}
-
Qt4Manager::Qt4Manager(Qt4ProjectManagerPlugin *plugin)
: m_plugin(plugin),
m_contextNode(0),
m_contextProject(0),
- m_contextFile(0),
- m_lastEditor(0),
- m_dirty(false)
+ m_contextFile(0)
{
}
@@ -114,61 +91,6 @@ void Qt4Manager::notifyChanged(const QString &name)
pro->notifyChanged(name);
}
-void Qt4Manager::init()
-{
- connect(Core::EditorManager::instance(), SIGNAL(editorAboutToClose(Core::IEditor*)),
- this, SLOT(editorAboutToClose(Core::IEditor*)));
-
- connect(Core::EditorManager::instance(), SIGNAL(currentEditorChanged(Core::IEditor*)),
- this, SLOT(editorChanged(Core::IEditor*)));
-}
-
-void Qt4Manager::editorChanged(Core::IEditor *editor)
-{
- // Handle old editor
- if (isFormWindowEditor(m_lastEditor)) {
- disconnect(m_lastEditor, SIGNAL(changed()), this, SLOT(uiEditorContentsChanged()));
-
- if (m_dirty) {
- const QString contents = formWindowEditorContents(m_lastEditor);
- foreach (Qt4Project *project, m_projects)
- project->rootQt4ProjectNode()->updateCodeModelSupportFromEditor(m_lastEditor->document()->fileName(), contents);
- m_dirty = false;
- }
- }
-
- m_lastEditor = editor;
-
- // Handle new editor
- if (isFormWindowEditor(m_lastEditor))
- connect(m_lastEditor, SIGNAL(changed()), this, SLOT(uiEditorContentsChanged()));
-}
-
-void Qt4Manager::editorAboutToClose(Core::IEditor *editor)
-{
- if (m_lastEditor == editor) {
- // Oh no our editor is going to be closed
- // get the content first
- if (isFormWindowEditor(m_lastEditor)) {
- disconnect(m_lastEditor, SIGNAL(changed()), this, SLOT(uiEditorContentsChanged()));
- if (m_dirty) {
- const QString contents = formWindowEditorContents(m_lastEditor);
- foreach (Qt4Project *project, m_projects)
- project->rootQt4ProjectNode()->updateCodeModelSupportFromEditor(m_lastEditor->document()->fileName(), contents);
- m_dirty = false;
- }
- }
- m_lastEditor = 0;
- }
-}
-
-void Qt4Manager::uiEditorContentsChanged()
-{
- // cast sender, get filename
- if (!m_dirty && isFormWindowEditor(sender()))
- m_dirty = true;
-}
-
QString Qt4Manager::mimeType() const
{
return QLatin1String(Qt4ProjectManager::Constants::PROFILE_MIMETYPE);
@@ -186,11 +108,6 @@ ProjectExplorer::Project *Qt4Manager::openProject(const QString &fileName, QStri
return new Qt4Project(this, fileName);
}
-ProjectExplorer::ProjectExplorerPlugin *Qt4Manager::projectExplorer() const
-{
- return ProjectExplorer::ProjectExplorerPlugin::instance();
-}
-
ProjectExplorer::Node *Qt4Manager::contextNode() const
{
return m_contextNode;
@@ -226,7 +143,7 @@ void Qt4Manager::addLibrary()
ProFileEditorWidget *editor =
qobject_cast<ProFileEditorWidget*>(Core::EditorManager::currentEditor()->widget());
if (editor)
- addLibrary(editor->editorDocument()->fileName(), editor);
+ addLibrary(editor->editorDocument()->filePath(), editor);
}
void Qt4Manager::addLibraryContextMenu()
@@ -269,7 +186,7 @@ void Qt4Manager::addLibrary(const QString &fileName, ProFileEditorWidget *editor
void Qt4Manager::runQMake()
{
- runQMake(projectExplorer()->startupProject(), 0);
+ runQMake(SessionManager::startupProject(), 0);
}
void Qt4Manager::runQMakeContextMenu()
@@ -300,7 +217,7 @@ void Qt4Manager::runQMake(ProjectExplorer::Project *p, ProjectExplorer::Node *no
if (Qt4ProFileNode *profile = qobject_cast<Qt4ProFileNode *>(node))
bc->setSubNodeBuild(profile);
- projectExplorer()->buildManager()->appendStep(qs, tr("QMake"));
+ BuildManager::appendStep(qs, tr("QMake"));
bc->setSubNodeBuild(0);
}
@@ -326,15 +243,13 @@ void Qt4Manager::buildFileContextMenu()
void Qt4Manager::buildFile()
{
- if (Core::IEditor *currentEditor = Core::EditorManager::currentEditor()) {
- QString file = currentEditor->document()->fileName();
- ProjectExplorer::SessionManager *session = projectExplorer()->session();
- ProjectExplorer::FileNode *node = qobject_cast<FileNode *>(session->nodeForFile(file));
- ProjectExplorer::Project *project = session->projectForFile(file);
+ if (Core::IDocument *currentDocument= Core::EditorManager::currentDocument()) {
+ QString file = currentDocument->filePath();
+ FileNode *node = qobject_cast<FileNode *>(SessionManager::nodeForFile(file));
+ Project *project = SessionManager::projectForFile(file);
if (project && node)
handleSubDirContextMenu(BUILD, true, project, node->projectNode(), node);
-
}
}
@@ -367,23 +282,23 @@ void Qt4Manager::handleSubDirContextMenu(Qt4Manager::Action action, bool isFileB
if (isFileBuild)
bc->setFileNodeBuild(contextFile);
- if (projectExplorer()->saveModifiedFiles()) {
- const Core::Id buildStep = Core::Id(ProjectExplorer::Constants::BUILDSTEPS_BUILD);
- const Core::Id cleanStep = Core::Id(ProjectExplorer::Constants::BUILDSTEPS_CLEAN);
+ if (ProjectExplorerPlugin::instance()->saveModifiedFiles()) {
+ const Core::Id buildStep = ProjectExplorer::Constants::BUILDSTEPS_BUILD;
+ const Core::Id cleanStep = ProjectExplorer::Constants::BUILDSTEPS_CLEAN;
if (action == BUILD) {
- const QString name = ProjectExplorer::ProjectExplorerPlugin::displayNameForStepId(buildStep);
- projectExplorer()->buildManager()->buildList(bc->stepList(buildStep), name);
+ const QString name = ProjectExplorerPlugin::displayNameForStepId(buildStep);
+ BuildManager::buildList(bc->stepList(buildStep), name);
} else if (action == CLEAN) {
- const QString name = ProjectExplorer::ProjectExplorerPlugin::displayNameForStepId(cleanStep);
- projectExplorer()->buildManager()->buildList(bc->stepList(cleanStep), name);
+ const QString name = ProjectExplorerPlugin::displayNameForStepId(cleanStep);
+ BuildManager::buildList(bc->stepList(cleanStep), name);
} else if (action == REBUILD) {
QStringList names;
- names << ProjectExplorer::ProjectExplorerPlugin::displayNameForStepId(cleanStep)
- << ProjectExplorer::ProjectExplorerPlugin::displayNameForStepId(buildStep);
+ names << ProjectExplorerPlugin::displayNameForStepId(cleanStep)
+ << ProjectExplorerPlugin::displayNameForStepId(buildStep);
QList<ProjectExplorer::BuildStepList *> stepLists;
stepLists << bc->stepList(cleanStep) << bc->stepList(buildStep);
- projectExplorer()->buildManager()->buildLists(stepLists, names);
+ BuildManager::buildLists(stepLists, names);
}
}
diff --git a/src/plugins/qt4projectmanager/qt4projectmanager.h b/src/plugins/qt4projectmanager/qt4projectmanager.h
index 14f309a4c0..9040c63238 100644
--- a/src/plugins/qt4projectmanager/qt4projectmanager.h
+++ b/src/plugins/qt4projectmanager/qt4projectmanager.h
@@ -40,16 +40,10 @@ namespace ExtensionSystem { class PluginManager; }
namespace ProjectExplorer {
class Project;
-class ProjectExplorerPlugin;
class Node;
class ToolChain;
}
-namespace QtSupport {
-class QtVersionManager;
-class BaseQtVersion;
-}
-
namespace Qt4ProjectManager {
namespace Internal {
@@ -68,14 +62,10 @@ public:
Qt4Manager(Internal::Qt4ProjectManagerPlugin *plugin);
~Qt4Manager();
- void init();
-
void registerProject(Qt4Project *project);
void unregisterProject(Qt4Project *project);
void notifyChanged(const QString &name);
- ProjectExplorer::ProjectExplorerPlugin *projectExplorer() const;
-
virtual QString mimeType() const;
ProjectExplorer::Project *openProject(const QString &fileName, QString *errorString);
@@ -103,11 +93,6 @@ public slots:
void buildFileContextMenu();
void buildFile();
-private slots:
- void editorAboutToClose(Core::IEditor *editor);
- void uiEditorContentsChanged();
- void editorChanged(Core::IEditor*);
-
private:
QList<Qt4Project *> m_projects;
void handleSubDirContextMenu(Action action, bool isFileBuild);
@@ -122,9 +107,6 @@ private:
ProjectExplorer::Node *m_contextNode;
ProjectExplorer::Project *m_contextProject;
ProjectExplorer::FileNode *m_contextFile;
-
- Core::IEditor *m_lastEditor;
- bool m_dirty;
};
} // namespace Qt4ProjectManager
diff --git a/src/plugins/qt4projectmanager/qt4projectmanager.pro b/src/plugins/qt4projectmanager/qt4projectmanager.pro
index 928abf0165..a336ae54a0 100644
--- a/src/plugins/qt4projectmanager/qt4projectmanager.pro
+++ b/src/plugins/qt4projectmanager/qt4projectmanager.pro
@@ -5,8 +5,10 @@ DEFINES += \
QT4PROJECTMANAGER_LIBRARY
HEADERS += \
+ qmakebuildinfo.h \
qmakekitinformation.h \
qmakekitconfigwidget.h \
+ qmakeprojectimporter.h \
qmakerunconfigurationfactory.h \
qt4projectmanagerplugin.h \
qt4projectmanager.h \
@@ -14,6 +16,7 @@ HEADERS += \
qt4nodes.h \
profileeditor.h \
profilehighlighter.h \
+ profilehighlighterfactory.h \
profileeditorfactory.h \
profilehoverhandler.h \
wizards/qtprojectparameters.h \
@@ -36,8 +39,6 @@ HEADERS += \
wizards/modulespage.h \
wizards/filespage.h \
wizards/qtwizard.h \
- wizards/targetsetuppage.h \
- wizards/importwidget.h \
wizards/qtquickapp.h \
wizards/qtquickappwizard.h \
wizards/qtquickappwizardpages.h \
@@ -53,7 +54,6 @@ HEADERS += \
qmakestep.h \
qtmodulesinfo.h \
qt4projectconfigwidget.h \
- qtuicodemodelsupport.h \
externaleditors.h \
qt4buildconfiguration.h \
qmakeparser.h \
@@ -61,16 +61,14 @@ HEADERS += \
librarydetailscontroller.h \
findqt4profiles.h \
qt4projectmanager_global.h \
- qt4targetsetupwidget.h \
- buildconfigurationinfo.h \
winceqtversionfactory.h \
winceqtversion.h \
- profilecompletionassist.h \
- unconfiguredprojectpanel.h
+ profilecompletionassist.h
SOURCES += \
qmakekitconfigwidget.cpp \
qmakekitinformation.cpp \
+ qmakeprojectimporter.cpp \
qmakerunconfigurationfactory.cpp \
qt4projectmanagerplugin.cpp \
qt4projectmanager.cpp \
@@ -78,6 +76,7 @@ SOURCES += \
qt4nodes.cpp \
profileeditor.cpp \
profilehighlighter.cpp \
+ profilehighlighterfactory.cpp \
profileeditorfactory.cpp \
profilehoverhandler.cpp \
wizards/qtprojectparameters.cpp \
@@ -100,8 +99,6 @@ SOURCES += \
wizards/modulespage.cpp \
wizards/filespage.cpp \
wizards/qtwizard.cpp \
- wizards/targetsetuppage.cpp \
- wizards/importwidget.cpp \
wizards/qtquickapp.cpp \
wizards/qtquickappwizard.cpp \
wizards/qtquickappwizardpages.cpp \
@@ -116,18 +113,15 @@ SOURCES += \
qmakestep.cpp \
qtmodulesinfo.cpp \
qt4projectconfigwidget.cpp \
- qtuicodemodelsupport.cpp \
externaleditors.cpp \
qt4buildconfiguration.cpp \
qmakeparser.cpp \
addlibrarywizard.cpp \
librarydetailscontroller.cpp \
findqt4profiles.cpp \
- qt4targetsetupwidget.cpp \
winceqtversionfactory.cpp \
winceqtversion.cpp \
- profilecompletionassist.cpp \
- unconfiguredprojectpanel.cpp
+ profilecompletionassist.cpp
FORMS += makestep.ui \
qmakestep.ui \
diff --git a/src/plugins/qt4projectmanager/qt4projectmanager.qbs b/src/plugins/qt4projectmanager/qt4projectmanager.qbs
index 557fe9495f..83f8c5bde2 100644
--- a/src/plugins/qt4projectmanager/qt4projectmanager.qbs
+++ b/src/plugins/qt4projectmanager/qt4projectmanager.qbs
@@ -16,190 +16,141 @@ QtcPlugin {
Depends { name: "TextEditor" }
Depends { name: "QmlJSTools" }
- cpp.includePaths: base.concat([
- "customwidgetwizard",
- "../../shared",
- ])
-
pluginRecommends: [
"Designer"
]
- files: [
- "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",
- "profilecompletionassist.h",
- "profileeditor.cpp",
- "profileeditor.h",
- "profileeditorfactory.cpp",
- "profileeditorfactory.h",
- "profilehighlighter.cpp",
- "profilehighlighter.h",
- "profilehoverhandler.cpp",
- "profilehoverhandler.h",
- "qmakeparser.cpp",
- "qmakeparser.h",
- "qmakekitconfigwidget.cpp",
- "qmakekitconfigwidget.h",
- "qmakekitinformation.cpp",
- "qmakekitinformation.h",
- "qmakeparser.cpp",
- "qmakeparser.h",
- "qmakerunconfigurationfactory.cpp",
- "qmakerunconfigurationfactory.h",
- "qmakestep.cpp",
- "qmakestep.h",
- "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",
- "qt4projectmanagerplugin.h",
- "qt4targetsetupwidget.cpp",
- "qt4targetsetupwidget.h",
- "qtmodulesinfo.cpp",
- "qtmodulesinfo.h",
- "qtuicodemodelsupport.cpp",
- "qtuicodemodelsupport.h",
- "unconfiguredprojectpanel.cpp",
- "unconfiguredprojectpanel.h",
- "winceqtversion.cpp",
- "winceqtversion.h",
- "winceqtversionfactory.cpp",
- "winceqtversionfactory.h",
- "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",
- "customwidgetwizard/customwidgetwizarddialog.h",
- "customwidgetwizard/filenamingparameters.h",
- "customwidgetwizard/plugingenerator.cpp",
- "customwidgetwizard/plugingenerator.h",
- "customwidgetwizard/pluginoptions.h",
- "images/headers.png",
- "images/run_qmake.png",
- "images/run_qmake_small.png",
- "images/sources.png",
- "images/unknown.png",
- "qt-desktop/desktopqtversion.cpp",
- "qt-desktop/desktopqtversion.h",
- "qt-desktop/desktopqtversionfactory.cpp",
- "qt-desktop/desktopqtversionfactory.h",
- "qt-desktop/qt4runconfiguration.cpp",
- "qt-desktop/qt4runconfiguration.h",
- "qt-desktop/simulatorqtversion.cpp",
- "qt-desktop/simulatorqtversion.h",
- "qt-desktop/simulatorqtversionfactory.cpp",
- "qt-desktop/simulatorqtversionfactory.h",
- "wizards/abstractmobileapp.cpp",
- "wizards/abstractmobileapp.h",
- "wizards/abstractmobileappwizard.cpp",
- "wizards/abstractmobileappwizard.h",
- "wizards/consoleappwizard.cpp",
- "wizards/consoleappwizard.h",
- "wizards/consoleappwizarddialog.cpp",
- "wizards/consoleappwizarddialog.h",
- "wizards/emptyprojectwizard.cpp",
- "wizards/emptyprojectwizard.h",
- "wizards/emptyprojectwizarddialog.cpp",
- "wizards/emptyprojectwizarddialog.h",
- "wizards/filespage.cpp",
- "wizards/filespage.h",
- "wizards/guiappwizard.cpp",
- "wizards/guiappwizard.h",
- "wizards/guiappwizarddialog.cpp",
- "wizards/guiappwizarddialog.h",
- "wizards/html5app.cpp",
- "wizards/html5app.h",
- "wizards/html5appwizard.cpp",
- "wizards/html5appwizard.h",
- "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",
- "wizards/librarywizarddialog.cpp",
- "wizards/librarywizarddialog.h",
- "wizards/mobileapp.cpp",
- "wizards/mobileapp.h",
- "wizards/mobileappwizardgenericoptionspage.ui",
- "wizards/mobileappwizardharmattanoptionspage.ui",
- "wizards/mobileappwizardmaemooptionspage.ui",
- "wizards/mobileappwizardpages.cpp",
- "wizards/mobileappwizardpages.h",
- "wizards/mobilelibraryparameters.cpp",
- "wizards/mobilelibraryparameters.h",
- "wizards/mobilelibrarywizardoptionpage.cpp",
- "wizards/mobilelibrarywizardoptionpage.h",
- "wizards/mobilelibrarywizardoptionpage.ui",
- "wizards/modulespage.cpp",
- "wizards/modulespage.h",
- "wizards/qtprojectparameters.cpp",
- "wizards/qtprojectparameters.h",
- "wizards/qtquickapp.cpp",
- "wizards/qtquickapp.h",
- "wizards/qtquickappwizard.cpp",
- "wizards/qtquickappwizard.h",
- "wizards/qtquickappwizardpages.cpp",
- "wizards/qtquickappwizardpages.h",
- "wizards/qtquickcomponentsetoptionspage.ui",
- "wizards/qtwizard.cpp",
- "wizards/qtwizard.h",
- "wizards/subdirsprojectwizard.cpp",
- "wizards/subdirsprojectwizard.h",
- "wizards/subdirsprojectwizarddialog.cpp",
- "wizards/subdirsprojectwizarddialog.h",
- "wizards/targetsetuppage.cpp",
- "wizards/targetsetuppage.h",
- "wizards/testwizard.cpp",
- "wizards/testwizard.h",
- "wizards/testwizarddialog.cpp",
- "wizards/testwizarddialog.h",
- "wizards/testwizardpage.cpp",
- "wizards/testwizardpage.h",
- "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",
- ]
+ Group {
+ name: "General"
+ files: [
+ "addlibrarywizard.cpp", "addlibrarywizard.h",
+ "externaleditors.cpp", "externaleditors.h",
+ "findqt4profiles.cpp", "findqt4profiles.h",
+ "librarydetailscontroller.cpp", "librarydetailscontroller.h",
+ "librarydetailswidget.ui",
+ "makestep.cpp", "makestep.h", "makestep.ui",
+ "profilecompletionassist.cpp", "profilecompletionassist.h",
+ "profileeditor.cpp", "profileeditor.h",
+ "profileeditorfactory.cpp", "profileeditorfactory.h",
+ "profilehighlighter.cpp", "profilehighlighter.h",
+ "profilehighlighterfactory.cpp", "profilehighlighterfactory.h",
+ "profilehoverhandler.cpp", "profilehoverhandler.h",
+ "qmakebuildinfo.h",
+ "qmakeparser.cpp", "qmakeparser.h",
+ "qmakekitconfigwidget.cpp", "qmakekitconfigwidget.h",
+ "qmakekitinformation.cpp", "qmakekitinformation.h",
+ "qmakeparser.cpp", "qmakeparser.h",
+ "qmakeprojectimporter.cpp", "qmakeprojectimporter.h",
+ "qmakerunconfigurationfactory.cpp", "qmakerunconfigurationfactory.h",
+ "qmakestep.cpp", "qmakestep.h", "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", "qt4projectmanagerplugin.h",
+ "qtmodulesinfo.cpp", "qtmodulesinfo.h",
+ "winceqtversion.cpp", "winceqtversion.h",
+ "winceqtversionfactory.cpp", "winceqtversionfactory.h"
+ ]
+ }
+
+ Group {
+ name: "Custom Widget Wizard"
+ prefix: "customwidgetwizard/"
+ files: [
+ "classdefinition.cpp", "classdefinition.h", "classdefinition.ui",
+ "classlist.cpp", "classlist.h",
+ "customwidgetpluginwizardpage.cpp", "customwidgetpluginwizardpage.h", "customwidgetpluginwizardpage.ui",
+ "customwidgetwidgetswizardpage.cpp", "customwidgetwidgetswizardpage.h", "customwidgetwidgetswizardpage.ui",
+ "customwidgetwizard.cpp", "customwidgetwizard.h",
+ "customwidgetwizarddialog.cpp", "customwidgetwizarddialog.h",
+ "filenamingparameters.h",
+ "plugingenerator.cpp", "plugingenerator.h",
+ "pluginoptions.h"
+ ]
+ }
+
+ Group {
+ name: "Images"
+ prefix: "images/"
+ files: [
+ "headers.png",
+ "run_qmake.png",
+ "run_qmake_small.png",
+ "sources.png",
+ "unknown.png",
+ ]
+ }
+
+ Group {
+ name: "Qt/Desktop"
+ prefix: "qt-desktop/"
+ files: [
+ "desktopqtversion.cpp", "desktopqtversion.h",
+ "desktopqtversionfactory.cpp", "desktopqtversionfactory.h",
+ "qt4runconfiguration.cpp", "qt4runconfiguration.h",
+ "simulatorqtversion.cpp", "simulatorqtversion.h",
+ "simulatorqtversionfactory.cpp", "simulatorqtversionfactory.h"
+ ]
+ }
+
+ Group {
+ name: "Wizards"
+ prefix: "wizards/"
+ files: [
+ "abstractmobileapp.cpp", "abstractmobileapp.h",
+ "abstractmobileappwizard.cpp", "abstractmobileappwizard.h",
+ "consoleappwizard.cpp", "consoleappwizard.h",
+ "consoleappwizarddialog.cpp", "consoleappwizarddialog.h",
+ "emptyprojectwizard.cpp", "emptyprojectwizard.h",
+ "emptyprojectwizarddialog.cpp", "emptyprojectwizarddialog.h",
+ "filespage.cpp", "filespage.h",
+ "guiappwizard.cpp", "guiappwizard.h",
+ "guiappwizarddialog.cpp", "guiappwizarddialog.h",
+ "html5app.cpp", "html5app.h",
+ "html5appwizard.cpp", "html5appwizard.h",
+ "html5appwizardpages.cpp", "html5appwizardpages.h",
+ "html5appwizardsourcespage.ui",
+ "libraryparameters.cpp", "libraryparameters.h",
+ "librarywizard.cpp", "librarywizard.h",
+ "librarywizarddialog.cpp", "librarywizarddialog.h",
+ "mobileapp.cpp", "mobileapp.h",
+ "mobileappwizardgenericoptionspage.ui",
+ "mobileappwizardharmattanoptionspage.ui",
+ "mobileappwizardmaemooptionspage.ui",
+ "mobileappwizardpages.cpp", "mobileappwizardpages.h",
+ "mobilelibraryparameters.cpp", "mobilelibraryparameters.h",
+ "mobilelibrarywizardoptionpage.cpp", "mobilelibrarywizardoptionpage.h", "mobilelibrarywizardoptionpage.ui",
+ "modulespage.cpp", "modulespage.h",
+ "qtprojectparameters.cpp", "qtprojectparameters.h",
+ "qtquickapp.cpp", "qtquickapp.h",
+ "qtquickappwizard.cpp", "qtquickappwizard.h",
+ "qtquickappwizardpages.cpp", "qtquickappwizardpages.h",
+ "qtquickcomponentsetoptionspage.ui",
+ "qtwizard.cpp", "qtwizard.h",
+ "subdirsprojectwizard.cpp", "subdirsprojectwizard.h",
+ "subdirsprojectwizarddialog.cpp", "subdirsprojectwizarddialog.h",
+ "testwizard.cpp", "testwizard.h",
+ "testwizarddialog.cpp", "testwizarddialog.h",
+ "testwizardpage.cpp", "testwizardpage.h",
+ "testwizardpage.ui",
+ "wizards.qrc"
+ ]
+ }
+
+ Group {
+ name: "Wizard Images"
+ prefix: "wizards/images/"
+ files: [
+ "console.png",
+ "gui.png",
+ "html5app.png",
+ "lib.png",
+ "qtquickapp.png",
+ ]
+ }
}
diff --git a/src/plugins/qt4projectmanager/qt4projectmanagerconstants.h b/src/plugins/qt4projectmanager/qt4projectmanagerconstants.h
index 85c8d377d6..2845852eb8 100644
--- a/src/plugins/qt4projectmanager/qt4projectmanagerconstants.h
+++ b/src/plugins/qt4projectmanager/qt4projectmanagerconstants.h
@@ -45,7 +45,7 @@ const char M_CONTEXT[] = "ProFileEditor.ContextMenu";
const char PROJECT_ID[] = "Qt4.Qt4Project";
const char PROFILE_EDITOR_ID[] = "Qt4.proFileEditor";
const char PROFILE_EDITOR_DISPLAY_NAME[] = QT_TRANSLATE_NOOP("OpenWith::Editors", ".pro File Editor");
-const char PROFILE_MIMETYPE [] = "application/vnd.qt.qmakeprofile";
+const char PROFILE_MIMETYPE[] = "application/vnd.qt.qmakeprofile";
const char PROINCLUDEFILE_MIMETYPE [] = "application/vnd.qt.qmakeproincludefile";
const char PROFEATUREFILE_MIMETYPE [] = "application/vnd.qt.qmakeprofeaturefile";
const char CPP_SOURCE_MIMETYPE[] = "text/x-c++src";
@@ -80,7 +80,6 @@ const char SHADOWBUILD_TARGETFEATURE_ID[] = "Qt4ProjectManager.TargetFeature.Sha
// Tool chains:
const char GCCE_TOOLCHAIN_ID[] = "Qt4ProjectManager.ToolChain.GCCE";
const char MAEMO_TOOLCHAIN_ID[] = "Qt4ProjectManager.ToolChain.Maemo";
-const char RVCT_TOOLCHAIN_ID[] = "Qt4ProjectManager.ToolChain.RVCT";
// ICONS
const char ICON_QTQUICK_APP[] = ":/wizards/images/qtquickapp.png";
@@ -91,9 +90,6 @@ const char QMAKEVAR_QMLJSDEBUGGER_PATH[] = "QMLJSDEBUGGER_PATH";
const char QMAKEVAR_QUICK1_DEBUG[] = "CONFIG+=declarative_debug";
const char QMAKEVAR_QUICK2_DEBUG[] = "CONFIG+=qml_debug";
-// Unconfigured Panel
-const char UNCONFIGURED_PANEL_PAGE_ID[] = "UnconfiguredPanel";
-
} // namespace Constants
} // namespace Qt4ProjectManager
diff --git a/src/plugins/qt4projectmanager/qt4projectmanagerplugin.cpp b/src/plugins/qt4projectmanager/qt4projectmanagerplugin.cpp
index d0c4930761..d23d8045a6 100644
--- a/src/plugins/qt4projectmanager/qt4projectmanagerplugin.cpp
+++ b/src/plugins/qt4projectmanager/qt4projectmanagerplugin.cpp
@@ -53,8 +53,8 @@
#include "qt-desktop/desktopqtversionfactory.h"
#include "qt-desktop/simulatorqtversionfactory.h"
#include "winceqtversionfactory.h"
-#include "unconfiguredprojectpanel.h"
#include "qmakekitinformation.h"
+#include "profilehighlighterfactory.h"
#include <coreplugin/icore.h>
#include <projectexplorer/buildmanager.h>
@@ -80,7 +80,7 @@
using namespace Qt4ProjectManager::Internal;
using namespace Qt4ProjectManager;
-using ProjectExplorer::Project;
+using namespace ProjectExplorer;
Qt4ProjectManagerPlugin::Qt4ProjectManagerPlugin()
: m_previousStartupProject(0), m_previousTarget(0)
@@ -105,7 +105,7 @@ bool Qt4ProjectManagerPlugin::initialize(const QStringList &arguments, QString *
const Core::Context projectContext(Qt4ProjectManager::Constants::PROJECT_ID);
Core::Context projecTreeContext(ProjectExplorer::Constants::C_PROJECT_TREE);
- if (!Core::ICore::mimeDatabase()->addMimeTypes(QLatin1String(":qt4projectmanager/Qt4ProjectManager.mimetypes.xml"), errorMessage))
+ if (!Core::MimeDatabase::addMimeTypes(QLatin1String(":qt4projectmanager/Qt4ProjectManager.mimetypes.xml"), errorMessage))
return false;
m_projectExplorer = ProjectExplorer::ProjectExplorerPlugin::instance();
@@ -121,7 +121,7 @@ bool Qt4ProjectManagerPlugin::initialize(const QStringList &arguments, QString *
m_proFileEditorFactory = new ProFileEditorFactory(m_qt4ProjectManager, editorHandler);
- ProjectExplorer::KitManager::instance()->registerKitInformation(new QmakeKitInformation);
+ ProjectExplorer::KitManager::registerKitInformation(new QmakeKitInformation);
addObject(m_proFileEditorFactory);
@@ -155,7 +155,7 @@ bool Qt4ProjectManagerPlugin::initialize(const QStringList &arguments, QString *
addAutoReleasedObject(new ProFileCompletionAssistProvider);
addAutoReleasedObject(new ProFileHoverHandler(this));
- addAutoReleasedObject(new UnconfiguredProjectPanel);
+ addAutoReleasedObject(new ProFileHighlighterFactory);
//menus
Core::ActionContainer *mbuild =
@@ -255,9 +255,9 @@ bool Qt4ProjectManagerPlugin::initialize(const QStringList &arguments, QString *
mbuild->addAction(command, ProjectExplorer::Constants::G_BUILD_BUILD);
connect(m_buildFileAction, SIGNAL(triggered()), m_qt4ProjectManager, SLOT(buildFile()));
- connect(m_projectExplorer->buildManager(), SIGNAL(buildStateChanged(ProjectExplorer::Project*)),
+ connect(BuildManager::instance(), SIGNAL(buildStateChanged(ProjectExplorer::Project*)),
this, SLOT(buildStateChanged(ProjectExplorer::Project*)));
- connect(m_projectExplorer->session(), SIGNAL(startupProjectChanged(ProjectExplorer::Project*)),
+ connect(SessionManager::instance(), SIGNAL(startupProjectChanged(ProjectExplorer::Project*)),
this, SLOT(startupProjectChanged()));
connect(m_projectExplorer, SIGNAL(currentNodeChanged(ProjectExplorer::Node*,ProjectExplorer::Project*)),
this, SLOT(updateContextActions(ProjectExplorer::Node*,ProjectExplorer::Project*)));
@@ -296,9 +296,7 @@ bool Qt4ProjectManagerPlugin::initialize(const QStringList &arguments, QString *
}
void Qt4ProjectManagerPlugin::extensionsInitialized()
-{
- m_qt4ProjectManager->init();
-}
+{ }
void Qt4ProjectManagerPlugin::startupProjectChanged()
{
@@ -306,7 +304,7 @@ void Qt4ProjectManagerPlugin::startupProjectChanged()
disconnect(m_previousStartupProject, SIGNAL(activeTargetChanged(ProjectExplorer::Target*)),
this, SLOT(activeTargetChanged()));
- m_previousStartupProject = qobject_cast<Qt4Project *>(m_projectExplorer->session()->startupProject());
+ m_previousStartupProject = qobject_cast<Qt4Project *>(SessionManager::startupProject());
if (m_previousStartupProject)
connect(m_previousStartupProject, SIGNAL(activeTargetChanged(ProjectExplorer::Target*)),
@@ -333,7 +331,7 @@ void Qt4ProjectManagerPlugin::activeTargetChanged()
void Qt4ProjectManagerPlugin::updateRunQMakeAction()
{
bool enable = true;
- if (m_projectExplorer->buildManager()->isBuilding(m_projectExplorer->currentProject()))
+ if (BuildManager::isBuilding(m_projectExplorer->currentProject()))
enable = false;
Qt4Project *pro = qobject_cast<Qt4Project *>(m_projectExplorer->currentProject());
if (!pro
@@ -374,7 +372,7 @@ void Qt4ProjectManagerPlugin::updateContextActions(ProjectExplorer::Node *node,
Qt4BuildConfiguration *buildConfiguration = (qt4Project && qt4Project->activeTarget()) ?
static_cast<Qt4BuildConfiguration *>(qt4Project->activeTarget()->activeBuildConfiguration()) : 0;
bool isProjectNode = qt4Project && proFileNode && buildConfiguration;
- bool isBuilding = m_projectExplorer->buildManager()->isBuilding(project);
+ bool isBuilding = BuildManager::isBuilding(project);
bool enabled = subProjectActionsVisible && !isBuilding;
m_buildSubProjectAction->setVisible(subProjectActionsVisible);
@@ -415,18 +413,16 @@ void Qt4ProjectManagerPlugin::updateBuildFileAction()
bool visible = false;
bool enabled = false;
- QString file;
- if (Core::IEditor *currentEditor = Core::EditorManager::currentEditor()) {
- file = currentEditor->document()->fileName();
- ProjectExplorer::SessionManager *session = m_projectExplorer->session();
- ProjectExplorer::Node *node = session->nodeForFile(file);
- ProjectExplorer::Project *project = session->projectForFile(file);
+ if (Core::IDocument *currentDocument= Core::EditorManager::currentDocument()) {
+ QString file = currentDocument->filePath();
+ Node *node = SessionManager::nodeForFile(file);
+ Project *project = SessionManager::projectForFile(file);
m_buildFileAction->setParameter(QFileInfo(file).fileName());
visible = qobject_cast<Qt4Project *>(project)
&& node
&& qobject_cast<Qt4ProFileNode *>(node->projectNode());
- enabled = !m_projectExplorer->buildManager()->isBuilding(project);
+ enabled = !BuildManager::isBuilding(project);
}
m_buildFileAction->setVisible(visible);
m_buildFileAction->setEnabled(enabled);
diff --git a/src/plugins/qt4projectmanager/qtuicodemodelsupport.cpp b/src/plugins/qt4projectmanager/qtuicodemodelsupport.cpp
deleted file mode 100644
index 50836e6227..0000000000
--- a/src/plugins/qt4projectmanager/qtuicodemodelsupport.cpp
+++ /dev/null
@@ -1,74 +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 "qtuicodemodelsupport.h"
-#include "qt4buildconfiguration.h"
-
-#include "qt4project.h"
-#include <projectexplorer/target.h>
-#include <qtsupport/qtkitinformation.h>
-
-using namespace Qt4ProjectManager;
-using namespace Internal;
-
-Qt4UiCodeModelSupport::Qt4UiCodeModelSupport(CppTools::CppModelManagerInterface *modelmanager,
- Qt4Project *project,
- const QString &source,
- const QString &uiHeaderFile)
- : CppTools::UiCodeModelSupport(modelmanager, source, uiHeaderFile),
- m_project(project)
-{ }
-
-Qt4UiCodeModelSupport::~Qt4UiCodeModelSupport()
-{ }
-
-QString Qt4UiCodeModelSupport::uicCommand() const
-{
- QtSupport::BaseQtVersion *version;
- if (m_project->needsConfiguration()) {
- version = QtSupport::QtKitInformation::qtVersion(ProjectExplorer::KitManager::instance()->defaultKit());
- } else {
- ProjectExplorer::Target *target = m_project->activeTarget();
- version = QtSupport::QtKitInformation::qtVersion(target->kit());
- }
- return version ? version->uicCommand() : QString();
-}
-
-QStringList Qt4UiCodeModelSupport::environment() const
-{
- if (m_project->needsConfiguration()) {
- return Utils::Environment::systemEnvironment().toStringList();
- } else {
- ProjectExplorer::Target *target = m_project->activeTarget();
- if (!target)
- return QStringList();
- ProjectExplorer::BuildConfiguration *bc = target->activeBuildConfiguration();
- return bc ? bc->environment().toStringList() : QStringList();
- }
-}
diff --git a/src/plugins/qt4projectmanager/wizards/abstractmobileappwizard.cpp b/src/plugins/qt4projectmanager/wizards/abstractmobileappwizard.cpp
index a6c5d62a8e..8b94e4cdf6 100644
--- a/src/plugins/qt4projectmanager/wizards/abstractmobileappwizard.cpp
+++ b/src/plugins/qt4projectmanager/wizards/abstractmobileappwizard.cpp
@@ -30,7 +30,7 @@
#include "abstractmobileappwizard.h"
#include "mobileappwizardpages.h"
-#include "targetsetuppage.h"
+#include "../qmakeprojectimporter.h"
#include <extensionsystem/pluginmanager.h>
#include <qt4projectmanager/qt4project.h>
@@ -38,9 +38,12 @@
#include <qtsupport/qtsupportconstants.h>
#include <qtsupport/qtkitinformation.h>
#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/targetsetuppage.h>
#include <projectexplorer/customwizard/customwizard.h>
#include <coreplugin/editormanager/editormanager.h>
+using namespace ProjectExplorer;
+
namespace Qt4ProjectManager {
AbstractMobileAppWizardDialog::AbstractMobileAppWizardDialog(QWidget *parent,
@@ -62,7 +65,8 @@ AbstractMobileAppWizardDialog::AbstractMobileAppWizardDialog(QWidget *parent,
.value<QList<Core::Id> >())
{
if (!parameters.extraValues().contains(QLatin1String(ProjectExplorer::Constants::PROJECT_KIT_IDS))) {
- m_targetsPage = new TargetSetupPage;
+ m_targetsPage = new ProjectExplorer::TargetSetupPage;
+ m_targetsPage->setProjectImporter(new Internal::QmakeProjectImporter(path()));
QString platform = selectedPlatform();
if (platform.isEmpty()) {
m_targetsPage->setPreferredKitMatcher(
@@ -118,7 +122,7 @@ void AbstractMobileAppWizardDialog::addMobilePages()
m_targetItem->setNextShownItem(0);
}
-TargetSetupPage *AbstractMobileAppWizardDialog::targetsPage() const
+ProjectExplorer::TargetSetupPage *AbstractMobileAppWizardDialog::targetsPage() const
{
return m_targetsPage;
}
@@ -208,13 +212,10 @@ bool AbstractMobileAppWizardDialog::isQtPlatformSelected(const QString &platform
{
QList<Core::Id> selectedKitsList = selectedKits();
- QtSupport::QtPlatformKitMatcher matcher(platform);
- QList<ProjectExplorer::Kit *> kitsList
- = ProjectExplorer::KitManager::instance()->kits(&matcher);
- foreach (ProjectExplorer::Kit *k, kitsList) {
+ foreach (Kit *k, KitManager::matchingKits(QtSupport::QtPlatformKitMatcher(platform)))
if (selectedKitsList.contains(k->id()))
return true;
- }
+
return false;
}
@@ -227,8 +228,8 @@ QList<Core::Id> AbstractMobileAppWizardDialog::selectedKits() const
-AbstractMobileAppWizard::AbstractMobileAppWizard(const Core::BaseFileWizardParameters &params,
- QObject *parent) : Core::BaseFileWizard(params, parent)
+AbstractMobileAppWizard::AbstractMobileAppWizard(QObject *parent)
+ : Core::BaseFileWizard(parent)
{ }
QWizard *AbstractMobileAppWizard::createWizardDialog(QWidget *parent,
@@ -296,7 +297,7 @@ void AbstractMobileAppWizard::useProjectPath(const QString &projectName,
app()->setProjectName(projectName);
app()->setProjectPath(projectPath);
if (wizardDialog()->m_targetsPage)
- wizardDialog()->m_targetsPage->setProFilePath(app()->path(AbstractMobileApp::AppPro));
+ wizardDialog()->m_targetsPage->setProjectPath(app()->path(AbstractMobileApp::AppPro));
projectPathChanged(app()->path(AbstractMobileApp::AppPro));
}
diff --git a/src/plugins/qt4projectmanager/wizards/abstractmobileappwizard.h b/src/plugins/qt4projectmanager/wizards/abstractmobileappwizard.h
index 63f81cf918..cfb2a997f8 100644
--- a/src/plugins/qt4projectmanager/wizards/abstractmobileappwizard.h
+++ b/src/plugins/qt4projectmanager/wizards/abstractmobileappwizard.h
@@ -33,6 +33,8 @@
#include <qt4projectmanager/qt4projectmanager_global.h>
#include <projectexplorer/baseprojectwizarddialog.h>
+namespace ProjectExplorer { class TargetSetupPage; }
+
namespace QtSupport {
class QtVersionNumber;
class QtVersionManager;
@@ -41,7 +43,6 @@ class QtVersionManager;
namespace Qt4ProjectManager {
class AbstractMobileApp;
-class TargetSetupPage;
namespace Internal {
class MobileAppWizardGenericOptionsPage;
@@ -61,7 +62,7 @@ protected:
void addMobilePages();
public:
- TargetSetupPage *targetsPage() const;
+ ProjectExplorer::TargetSetupPage *targetsPage() const;
protected:
int addPageWithTitle(QWizardPage *page, const QString &title);
@@ -80,7 +81,7 @@ private:
Internal::MobileAppWizardGenericOptionsPage *m_genericOptionsPage;
Internal::MobileAppWizardMaemoOptionsPage *m_maemoOptionsPage;
Internal::MobileAppWizardHarmattanOptionsPage *m_harmattanOptionsPage;
- TargetSetupPage *m_targetsPage;
+ ProjectExplorer::TargetSetupPage *m_targetsPage;
int m_genericOptionsPageId;
int m_maemoOptionsPageId;
@@ -101,8 +102,7 @@ class QT4PROJECTMANAGER_EXPORT AbstractMobileAppWizard : public Core::BaseFileWi
{
Q_OBJECT
protected:
- explicit AbstractMobileAppWizard(const Core::BaseFileWizardParameters &params,
- QObject *parent = 0);
+ explicit AbstractMobileAppWizard(QObject *parent = 0);
private slots:
void useProjectPath(const QString &projectName, const QString &projectPath);
diff --git a/src/plugins/qt4projectmanager/wizards/consoleappwizard.cpp b/src/plugins/qt4projectmanager/wizards/consoleappwizard.cpp
index ad2fbb7536..d694117074 100644
--- a/src/plugins/qt4projectmanager/wizards/consoleappwizard.cpp
+++ b/src/plugins/qt4projectmanager/wizards/consoleappwizard.cpp
@@ -35,7 +35,7 @@
#include <cpptools/abstracteditorsupport.h>
#include <qtsupport/qtsupportconstants.h>
-#include <QIcon>
+#include <QCoreApplication>
#include <QFileInfo>
#include <QTextStream>
@@ -53,14 +53,16 @@ namespace Qt4ProjectManager {
namespace Internal {
ConsoleAppWizard::ConsoleAppWizard()
- : QtWizard(QLatin1String("E.Qt4Core"),
- QLatin1String(ProjectExplorer::Constants::QT_APPLICATION_WIZARD_CATEGORY),
- QLatin1String(ProjectExplorer::Constants::QT_APPLICATION_WIZARD_CATEGORY_DISPLAY),
- tr("Qt Console Application"),
- tr("Creates a project containing a single main.cpp file with a stub implementation.\n\n"
- "Preselects a desktop Qt for building the application if available."),
- QIcon(QLatin1String(":/wizards/images/console.png")))
{
+ setId(QLatin1String("E.Qt4Core"));
+ setCategory(QLatin1String(ProjectExplorer::Constants::QT_APPLICATION_WIZARD_CATEGORY));
+ setDisplayCategory(QCoreApplication::translate("ProjectExplorer",
+ ProjectExplorer::Constants::QT_APPLICATION_WIZARD_CATEGORY_DISPLAY));
+ setDisplayName(tr("Qt Console Application"));
+ setDescription(tr("Creates a project containing a single main.cpp file with a stub implementation.\n\n"
+ "Preselects a desktop Qt for building the application if available."));
+ setIcon(QIcon(QLatin1String(":/wizards/images/console.png")));
+ setRequiredFeatures(Core::Feature(QtSupport::Constants::FEATURE_QT_CONSOLE));
}
QWizard *ConsoleAppWizard::createWizardDialog(QWidget *parent,
@@ -102,10 +104,5 @@ Core::GeneratedFiles
return Core::GeneratedFiles() << source << profile;
}
-Core::FeatureSet ConsoleAppWizard::requiredFeatures() const
-{
- return Core::Feature(QtSupport::Constants::FEATURE_QT_CONSOLE);
-}
-
} // namespace Internal
} // namespace Qt4ProjectManager
diff --git a/src/plugins/qt4projectmanager/wizards/consoleappwizard.h b/src/plugins/qt4projectmanager/wizards/consoleappwizard.h
index d42936a3b7..1c2faa409a 100644
--- a/src/plugins/qt4projectmanager/wizards/consoleappwizard.h
+++ b/src/plugins/qt4projectmanager/wizards/consoleappwizard.h
@@ -45,13 +45,11 @@ public:
ConsoleAppWizard();
protected:
- virtual QWizard *createWizardDialog(QWidget *parent,
+ QWizard *createWizardDialog(QWidget *parent,
const Core::WizardDialogParameters &wizardDialogParameters) const;
- virtual Core::GeneratedFiles generateFiles(const QWizard *w,
+ Core::GeneratedFiles generateFiles(const QWizard *w,
QString *errorMessage) const;
-
- virtual Core::FeatureSet requiredFeatures() const;
};
} // namespace Internal
diff --git a/src/plugins/qt4projectmanager/wizards/emptyprojectwizard.cpp b/src/plugins/qt4projectmanager/wizards/emptyprojectwizard.cpp
index dc93713ee6..3da4e01751 100644
--- a/src/plugins/qt4projectmanager/wizards/emptyprojectwizard.cpp
+++ b/src/plugins/qt4projectmanager/wizards/emptyprojectwizard.cpp
@@ -34,25 +34,22 @@
#include <projectexplorer/projectexplorerconstants.h>
#include <qtsupport/qtsupportconstants.h>
-#include <QIcon>
+#include <QCoreApplication>
namespace Qt4ProjectManager {
namespace Internal {
EmptyProjectWizard::EmptyProjectWizard()
- : QtWizard(QLatin1String("U.Qt4Empty"),
- QLatin1String(ProjectExplorer::Constants::QT_PROJECT_WIZARD_CATEGORY),
- QLatin1String(ProjectExplorer::Constants::QT_PROJECT_WIZARD_CATEGORY_DISPLAY),
- tr("Empty Qt Project"),
- tr("Creates a qmake-based project without any files. This allows you to create "
- "an application without any default classes."),
- QIcon(QLatin1String(":/wizards/images/gui.png")))
{
-}
-
-Core::FeatureSet EmptyProjectWizard::requiredFeatures() const
-{
- return Core::Feature(QtSupport::Constants::FEATURE_QT);
+ setId(QLatin1String("U.Qt4Empty"));
+ setCategory(QLatin1String(ProjectExplorer::Constants::QT_PROJECT_WIZARD_CATEGORY));
+ setDisplayCategory(QCoreApplication::translate("ProjectExplorer",
+ ProjectExplorer::Constants::QT_PROJECT_WIZARD_CATEGORY_DISPLAY));
+ setDisplayName(tr("Empty Qt Project"));
+ setDescription(tr("Creates a qmake-based project without any files. This allows you to create "
+ "an application without any default classes."));
+ setIcon(QIcon(QLatin1String(":/wizards/images/gui.png")));
+ setRequiredFeatures(Core::Feature(QtSupport::Constants::FEATURE_QT));
}
QWizard *EmptyProjectWizard::createWizardDialog(QWidget *parent,
diff --git a/src/plugins/qt4projectmanager/wizards/emptyprojectwizard.h b/src/plugins/qt4projectmanager/wizards/emptyprojectwizard.h
index 25479e3da4..e0d4fb9ce1 100644
--- a/src/plugins/qt4projectmanager/wizards/emptyprojectwizard.h
+++ b/src/plugins/qt4projectmanager/wizards/emptyprojectwizard.h
@@ -41,14 +41,12 @@ class EmptyProjectWizard : public QtWizard
public:
EmptyProjectWizard();
- virtual Core::FeatureSet requiredFeatures() const;
-protected:
- virtual QWizard *createWizardDialog(QWidget *parent,
+private:
+ QWizard *createWizardDialog(QWidget *parent,
const Core::WizardDialogParameters &wizardDialogParameters) const;
- virtual Core::GeneratedFiles generateFiles(const QWizard *w,
- QString *errorMessage) const;
+ Core::GeneratedFiles generateFiles(const QWizard *w, QString *errorMessage) const;
};
} // namespace Internal
diff --git a/src/plugins/qt4projectmanager/wizards/guiappwizard.cpp b/src/plugins/qt4projectmanager/wizards/guiappwizard.cpp
index 2b90f2887b..53b0defe69 100644
--- a/src/plugins/qt4projectmanager/wizards/guiappwizard.cpp
+++ b/src/plugins/qt4projectmanager/wizards/guiappwizard.cpp
@@ -40,13 +40,12 @@
#include <utils/fileutils.h>
+#include <QCoreApplication>
#include <QDir>
#include <QTextStream>
#include <QFileInfo>
#include <QSharedPointer>
-#include <QIcon>
-
static const char mainSourceFileC[] = "main";
static const char mainSourceShowC[] = " w.show();\n";
static const char mainSourceMobilityShowC[] = " w.show();\n";
@@ -73,34 +72,19 @@ static inline QStringList baseClasses()
namespace Qt4ProjectManager {
namespace Internal {
-GuiAppWizard::GuiAppWizard()
- : QtWizard(QLatin1String("C.Qt4Gui"),
- QLatin1String(ProjectExplorer::Constants::QT_APPLICATION_WIZARD_CATEGORY),
- QLatin1String(ProjectExplorer::Constants::QT_APPLICATION_WIZARD_CATEGORY_DISPLAY),
- tr("Qt Gui Application"),
- tr("Creates a Qt application for the desktop. "
- "Includes a Qt Designer-based main window.\n\n"
- "Preselects a desktop Qt for building the application if available."),
- QIcon(QLatin1String(":/wizards/images/gui.png"))),
- m_createMobileProject(false)
-{
-}
-
-Core::FeatureSet GuiAppWizard::requiredFeatures() const
-{
- return Core::Feature(QtSupport::Constants::FEATURE_QWIDGETS);
-}
-
-GuiAppWizard::GuiAppWizard(const QString &id,
- const QString &category,
- const QString &displayCategory,
- const QString &name,
- const QString &description,
- const QIcon &icon,
- bool createMobile)
- : QtWizard(id, category, displayCategory, name, description, icon),
- m_createMobileProject(createMobile)
+GuiAppWizard::GuiAppWizard(bool isMobile)
{
+ setId(QLatin1String("C.Qt4Gui"));
+ setCategory(QLatin1String(ProjectExplorer::Constants::QT_APPLICATION_WIZARD_CATEGORY));
+ setDisplayCategory(QCoreApplication::translate("ProjectExplorer",
+ ProjectExplorer::Constants::QT_APPLICATION_WIZARD_CATEGORY_DISPLAY));
+ setDisplayName(tr("Qt Gui Application"));
+ setDescription(tr("Creates a Qt application for the desktop. "
+ "Includes a Qt Designer-based main window.\n\n"
+ "Preselects a desktop Qt for building the application if available."));
+ setIcon(QIcon(QLatin1String(":/wizards/images/gui.png")));
+ setRequiredFeatures(Core::Feature(QtSupport::Constants::FEATURE_QWIDGETS));
+ m_createMobileProject = isMobile;
}
QWizard *GuiAppWizard::createWizardDialog(QWidget *parent,
diff --git a/src/plugins/qt4projectmanager/wizards/guiappwizard.h b/src/plugins/qt4projectmanager/wizards/guiappwizard.h
index 196eb23399..80214d4de9 100644
--- a/src/plugins/qt4projectmanager/wizards/guiappwizard.h
+++ b/src/plugins/qt4projectmanager/wizards/guiappwizard.h
@@ -42,22 +42,13 @@ class GuiAppWizard : public QtWizard
Q_OBJECT
public:
- GuiAppWizard();
- virtual Core::FeatureSet requiredFeatures() const;
+ GuiAppWizard(bool isMobile = false);
-protected:
- GuiAppWizard(const QString &id,
- const QString &category,
- const QString &displayCategory,
- const QString &name,
- const QString &description,
- const QIcon &icon,
- bool createMobile);
- virtual QWizard *createWizardDialog(QWidget *parent,
+private:
+ QWizard *createWizardDialog(QWidget *parent,
const Core::WizardDialogParameters &wizardDialogParameters) const;
- virtual Core::GeneratedFiles generateFiles(const QWizard *w,
- QString *errorMessage) const;
+ Core::GeneratedFiles generateFiles(const QWizard *w, QString *errorMessage) const;
private:
static bool parametrizeTemplate(const QString &templatePath, const QString &templateName,
diff --git a/src/plugins/qt4projectmanager/wizards/html5appwizard.cpp b/src/plugins/qt4projectmanager/wizards/html5appwizard.cpp
index ac53c77a28..854377dd17 100644
--- a/src/plugins/qt4projectmanager/wizards/html5appwizard.cpp
+++ b/src/plugins/qt4projectmanager/wizards/html5appwizard.cpp
@@ -31,11 +31,11 @@
#include "html5app.h"
#include "html5appwizardpages.h"
-#include "targetsetuppage.h"
-#include "qt4projectmanagerconstants.h"
+#include <qt4projectmanager/qt4projectmanagerconstants.h>
#include <qtsupport/baseqtversion.h>
#include <projectexplorer/projectexplorerconstants.h>
+#include <projectexplorer/targetsetuppage.h>
#include <qtsupport/qtsupportconstants.h>
#include <limits>
@@ -79,9 +79,20 @@ class Html5AppWizardPrivate
};
Html5AppWizard::Html5AppWizard()
- : AbstractMobileAppWizard(parameters())
- , d(new Html5AppWizardPrivate)
+ : d(new Html5AppWizardPrivate)
{
+ setWizardKind(ProjectWizard);
+ setIcon(QIcon(QLatin1String(Constants::ICON_HTML5_APP)));
+ setDisplayName(tr("HTML5 Application"));
+ setId(QLatin1String("QA.HTML5A Application"));
+ setDescription(tr("Creates an HTML5 application project that can contain "
+ "both HTML5 and C++ code and includes a WebKit view.\n\n"
+ "You can build the application and deploy it on desktop and "
+ "mobile target platforms."));
+ setCategory(QLatin1String(ProjectExplorer::Constants::QT_APPLICATION_WIZARD_CATEGORY));
+ setDisplayCategory(QLatin1String(ProjectExplorer::Constants::QT_APPLICATION_WIZARD_CATEGORY_DISPLAY));
+ setRequiredFeatures(Core::Feature(QtSupport::Constants::FEATURE_QT_WEBKIT));
+
d->app = new Html5App;
d->wizardDialog = 0;
}
@@ -92,26 +103,6 @@ Html5AppWizard::~Html5AppWizard()
delete d;
}
-Core::FeatureSet Html5AppWizard::requiredFeatures() const
-{
- return Core::Feature(QtSupport::Constants::FEATURE_QT_WEBKIT);
-}
-
-Core::BaseFileWizardParameters Html5AppWizard::parameters()
-{
- Core::BaseFileWizardParameters parameters(ProjectWizard);
- parameters.setIcon(QIcon(QLatin1String(Constants::ICON_HTML5_APP)));
- parameters.setDisplayName(tr("HTML5 Application"));
- parameters.setId(QLatin1String("QA.HTML5A Application"));
- parameters.setDescription(tr("Creates an HTML5 application project that can contain "
- "both HTML5 and C++ code and includes a WebKit view.\n\n"
- "You can build the application and deploy it on desktop and "
- "mobile target platforms."));
- parameters.setCategory(QLatin1String(ProjectExplorer::Constants::QT_APPLICATION_WIZARD_CATEGORY));
- parameters.setDisplayCategory(QLatin1String(ProjectExplorer::Constants::QT_APPLICATION_WIZARD_CATEGORY_DISPLAY));
- return parameters;
-}
-
AbstractMobileAppWizardDialog *Html5AppWizard::createWizardDialogInternal(QWidget *parent,
const Core::WizardDialogParameters &parameters) const
{
@@ -124,7 +115,7 @@ AbstractMobileAppWizardDialog *Html5AppWizard::createWizardDialogInternal(QWidge
void Html5AppWizard::projectPathChanged(const QString &path) const
{
if (d->wizardDialog->targetsPage())
- d->wizardDialog->targetsPage()->setProFilePath(path);
+ d->wizardDialog->targetsPage()->setProjectPath(path);
}
void Html5AppWizard::prepareGenerateFiles(const QWizard *w,
diff --git a/src/plugins/qt4projectmanager/wizards/html5appwizard.h b/src/plugins/qt4projectmanager/wizards/html5appwizard.h
index fcd4d57bdb..908a1aece6 100644
--- a/src/plugins/qt4projectmanager/wizards/html5appwizard.h
+++ b/src/plugins/qt4projectmanager/wizards/html5appwizard.h
@@ -41,15 +41,12 @@ class Html5AppWizard : public AbstractMobileAppWizard
public:
Html5AppWizard();
- virtual ~Html5AppWizard();
- virtual Core::FeatureSet requiredFeatures() const;
+ ~Html5AppWizard();
protected:
QString fileToOpenPostGeneration() const;
private:
- static Core::BaseFileWizardParameters parameters();
-
virtual AbstractMobileApp *app() const;
virtual AbstractMobileAppWizardDialog *wizardDialog() const;
virtual AbstractMobileAppWizardDialog *createWizardDialogInternal(QWidget *parent,
diff --git a/src/plugins/qt4projectmanager/wizards/librarywizard.cpp b/src/plugins/qt4projectmanager/wizards/librarywizard.cpp
index af83637b55..4a5a9b2302 100644
--- a/src/plugins/qt4projectmanager/wizards/librarywizard.cpp
+++ b/src/plugins/qt4projectmanager/wizards/librarywizard.cpp
@@ -37,24 +37,25 @@
#include <QFileInfo>
#include <QTextStream>
-#include <QIcon>
+#include <QCoreApplication>
static const char sharedHeaderPostfixC[] = "_global";
namespace Qt4ProjectManager {
-
namespace Internal {
LibraryWizard::LibraryWizard()
- : QtWizard(QLatin1String("H.Qt4Library"),
- QLatin1String(ProjectExplorer::Constants::LIBRARIES_WIZARD_CATEGORY),
- QLatin1String(ProjectExplorer::Constants::LIBRARIES_WIZARD_CATEGORY_DISPLAY),
- tr("C++ Library"),
- tr("Creates a C++ library based on qmake. This can be used to create:<ul>"
- "<li>a shared C++ library for use with <tt>QPluginLoader</tt> and runtime (Plugins)</li>"
- "<li>a shared or static C++ library for use with another project at linktime</li></ul>"),
- QIcon(QLatin1String(":/wizards/images/lib.png")))
{
+ setId(QLatin1String("H.Qt4Library"));
+ setCategory(QLatin1String(ProjectExplorer::Constants::LIBRARIES_WIZARD_CATEGORY));
+ setDisplayCategory(QCoreApplication::translate("ProjectExplorer",
+ ProjectExplorer::Constants::LIBRARIES_WIZARD_CATEGORY_DISPLAY));
+ setDisplayName(tr("C++ Library"));
+ setDescription(tr("Creates a C++ library based on qmake. This can be used to create:<ul>"
+ "<li>a shared C++ library for use with <tt>QPluginLoader</tt> and runtime (Plugins)</li>"
+ "<li>a shared or static C++ library for use with another project at linktime</li></ul>"));
+ setIcon(QIcon(QLatin1String(":/wizards/images/lib.png")));
+ setRequiredFeatures(Core::Feature(QtSupport::Constants::FEATURE_QT));
}
QWizard *LibraryWizard::createWizardDialog(QWidget *parent, const Core::WizardDialogParameters &wizardDialogParameters) const
@@ -152,10 +153,5 @@ Core::GeneratedFiles LibraryWizard::generateFiles(const QWizard *w,
return rc;
}
-Core::FeatureSet LibraryWizard::requiredFeatures() const
-{
- return Core::Feature(QtSupport::Constants::FEATURE_QT);
-}
-
} // namespace Internal
} // namespace Qt4ProjectManager
diff --git a/src/plugins/qt4projectmanager/wizards/librarywizard.h b/src/plugins/qt4projectmanager/wizards/librarywizard.h
index 17e3c8fad4..0b4c4eb630 100644
--- a/src/plugins/qt4projectmanager/wizards/librarywizard.h
+++ b/src/plugins/qt4projectmanager/wizards/librarywizard.h
@@ -36,9 +36,6 @@
namespace Qt4ProjectManager {
namespace Internal {
-struct LibraryParameters;
-class ModulesPage;
-
class LibraryWizard : public QtWizard
{
Q_OBJECT
@@ -47,12 +44,10 @@ public:
LibraryWizard();
protected:
- virtual QWizard *createWizardDialog(QWidget *parent,
+ QWizard *createWizardDialog(QWidget *parent,
const Core::WizardDialogParameters &wizardDialogParameters) const;
- virtual Core::GeneratedFiles generateFiles(const QWizard *w,
- QString *errorMessage) const;
- virtual Core::FeatureSet requiredFeatures() const;
+ Core::GeneratedFiles generateFiles(const QWizard *w, QString *errorMessage) const;
};
} // namespace Internal
diff --git a/src/plugins/qt4projectmanager/wizards/librarywizarddialog.cpp b/src/plugins/qt4projectmanager/wizards/librarywizarddialog.cpp
index 01b1143c03..b7816ccfe4 100644
--- a/src/plugins/qt4projectmanager/wizards/librarywizarddialog.cpp
+++ b/src/plugins/qt4projectmanager/wizards/librarywizarddialog.cpp
@@ -60,6 +60,7 @@ static const PluginBaseClasses pluginBaseClasses[] =
{
{ "QAccessiblePlugin", "QtGui", "QtCore", "accessible", "QAccessibleFactoryInterface" },
{ "QDecorationPlugin", "QtGui", "QtCore", 0, 0 }, // Qt 4 only.
+ { "QGenericPlugin", "QtGui", "QtCore", "generic", "QGenericPluginFactoryInterface" },
{ "QIconEnginePluginV2", "QtGui", "QtCore", "imageformats", 0 }, // Qt 4 only.
{ "QIconEnginePlugin", "QtGui", "QtCore", "imageformats", "QIconEngineFactoryInterface" },
{ "QImageIOPlugin", "QtGui", "QtCore", "imageformats", "QImageIOHandlerFactoryInterface" },
@@ -69,7 +70,7 @@ static const PluginBaseClasses pluginBaseClasses[] =
{ "QTextCodecPlugin", "QtCore", 0, "codecs", 0 } // Qt 4 only.
};
-enum { defaultPluginBaseClass = 6 };
+enum { defaultPluginBaseClass = 2 };
static const PluginBaseClasses *findPluginBaseClass(const QString &name)
{
diff --git a/src/plugins/qt4projectmanager/wizards/modulespage.cpp b/src/plugins/qt4projectmanager/wizards/modulespage.cpp
index 65a791dc58..5c772618bf 100644
--- a/src/plugins/qt4projectmanager/wizards/modulespage.cpp
+++ b/src/plugins/qt4projectmanager/wizards/modulespage.cpp
@@ -29,7 +29,7 @@
#include "modulespage.h"
-#include "qtmodulesinfo.h"
+#include <qt4projectmanager/qtmodulesinfo.h>
#include <QDebug>
diff --git a/src/plugins/qt4projectmanager/wizards/qtquickappwizard.cpp b/src/plugins/qt4projectmanager/wizards/qtquickappwizard.cpp
index 57c95752fb..281dc8f906 100644
--- a/src/plugins/qt4projectmanager/wizards/qtquickappwizard.cpp
+++ b/src/plugins/qt4projectmanager/wizards/qtquickappwizard.cpp
@@ -31,12 +31,12 @@
#include "qtquickapp.h"
#include "qtquickappwizardpages.h"
-#include "targetsetuppage.h"
-#include "qt4projectmanagerconstants.h"
+#include "../qt4projectmanagerconstants.h"
#include <qtsupport/qtsupportconstants.h>
#include <qtsupport/baseqtversion.h>
#include <projectexplorer/projectexplorerconstants.h>
+#include <projectexplorer/targetsetuppage.h>
#include <QIcon>
#include <QDebug>
@@ -105,17 +105,14 @@ class QtQuickAppWizardPrivate
};
QtQuickAppWizard::QtQuickAppWizard()
- : AbstractMobileAppWizard(baseParameters())
- , d(new QtQuickAppWizardPrivate)
+ : d(new QtQuickAppWizardPrivate)
{
- d->app = new QtQuickApp;
- d->wizardDialog = 0;
-}
+ setWizardKind(ProjectWizard);
+ setIcon(QIcon(QLatin1String(Qt4ProjectManager::Constants::ICON_QTQUICK_APP)));
+ setId(QLatin1String("D.QMLA Application"));
+ setCategory(QLatin1String(ProjectExplorer::Constants::QT_APPLICATION_WIZARD_CATEGORY));
+ setDisplayCategory(QLatin1String(ProjectExplorer::Constants::QT_APPLICATION_WIZARD_CATEGORY_DISPLAY));
-QtQuickAppWizard::QtQuickAppWizard(const Core::BaseFileWizardParameters &params, QObject *parent)
- : AbstractMobileAppWizard(params, parent)
- , d(new QtQuickAppWizardPrivate)
-{
d->app = new QtQuickApp;
d->wizardDialog = 0;
}
@@ -128,83 +125,68 @@ QtQuickAppWizard::~QtQuickAppWizard()
void QtQuickAppWizard::createInstances(ExtensionSystem::IPlugin *plugin)
{
- Core::BaseFileWizardParameters base = baseParameters();
- QList<Core::BaseFileWizardParameters> list;
- Core::BaseFileWizardParameters parameter;
-
const QString basicDescription = tr("Creates a Qt Quick 1 application project that can contain "
"both QML and C++ code and includes a QDeclarativeView.\n\n");
const QString basicDescription2 = tr("Creates a Qt Quick 2 application project that can contain "
"both QML and C++ code and includes a QQuickView.\n\n");
- Core::FeatureSet basicFeatures;
- basicFeatures = Core::Feature(QtSupport::Constants::FEATURE_QT_QUICK_1);
+ Core::FeatureSet basicFeatures = Core::Feature(QtSupport::Constants::FEATURE_QT_QUICK_1);
- parameter = base;
- parameter.setDisplayName(tr("Qt Quick 1 Application (Built-in Types)"));
- parameter.setDescription(basicDescription + tr("The built-in QML types in the QtQuick 1 namespace allow "
+ QtQuickAppWizard *wizard = new QtQuickAppWizard;
+ wizard->setQtQuickKind(QtQuick1_1);
+ wizard->setDisplayName(tr("Qt Quick 1 Application (Built-in Types)"));
+ wizard->setDescription(basicDescription + tr("The built-in QML types in the QtQuick 1 namespace allow "
"you to write cross-platform applications with "
"a custom look and feel.\n\nRequires <b>Qt 4.7.0</b> or newer."));
- parameter.setRequiredFeatures(basicFeatures);
- list << parameter;
+ wizard->setRequiredFeatures(basicFeatures);
+ plugin->addAutoReleasedObject(wizard);
- parameter = base;
- parameter.setDisplayName(tr("Qt Quick 2 Application (Built-in Types)"));
- parameter.setDescription(basicDescription2 + tr("The built-in QML types in the QtQuick 2 namespace allow "
+
+ wizard = new QtQuickAppWizard;
+ wizard->setQtQuickKind(QtQuick2_0);
+ wizard->setDisplayName(tr("Qt Quick 2 Application (Built-in Types)"));
+ wizard->setDescription(basicDescription2 + tr("The built-in QML types in the QtQuick 2 namespace allow "
"you to write cross-platform applications with "
"a custom look and feel.\n\nRequires <b>Qt 5.0</b> or newer."));
- parameter.setRequiredFeatures(Core::Feature(QtSupport::Constants::FEATURE_QT_QUICK_2));
- list << parameter;
+ wizard->setRequiredFeatures(Core::Feature(QtSupport::Constants::FEATURE_QT_QUICK_2));
+ plugin->addAutoReleasedObject(wizard);
+
- parameter = base;
- parameter.setDisplayName(tr("Qt Quick 1 Application for MeeGo Harmattan"));
- parameter.setDescription(basicDescription + tr("The Qt Quick Components for MeeGo Harmattan are "
+ wizard = new QtQuickAppWizard;
+ wizard->setQtQuickKind(MeegoComponents);
+ wizard->setDisplayName(tr("Qt Quick 1 Application for MeeGo Harmattan"));
+ wizard->setDescription(basicDescription + tr("The Qt Quick Components for MeeGo Harmattan are "
"a set of ready-made components that are designed "
"with specific native appearance for the MeeGo Harmattan "
"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)
+ wizard->setRequiredFeatures(basicFeatures | Core::Feature(QtSupport::Constants::FEATURE_QTQUICK_COMPONENTS_MEEGO)
| Core::Feature(QtSupport::Constants::FEATURE_QT_QUICK_1_1));
- list << parameter;
+ plugin->addAutoReleasedObject(wizard);
- parameter = base;
- parameter.setDisplayName(tr("Qt Quick 1 Application (from Existing QML File)"));
- parameter.setDescription(basicDescription + tr("Creates a deployable Qt Quick application from "
+
+ wizard = new QtQuickAppWizard;
+ wizard->setQtQuickKind(ImportQml);
+ wizard->setDisplayName(tr("Qt Quick 1 Application (from Existing QML File)"));
+ wizard->setDescription(basicDescription + tr("Creates a deployable Qt Quick application from "
"existing QML files. All files and directories that "
"reside in the same directory as the main .qml file "
"are deployed. You can modify the contents of the "
"directory any time before deploying.\n\nRequires <b>Qt 4.7.0</b> or newer."));
- parameter.setRequiredFeatures(basicFeatures);
- list << parameter;
+ wizard->setRequiredFeatures(basicFeatures);
+ plugin->addAutoReleasedObject(wizard);
+
- parameter = base;
- parameter.setDisplayName(tr("Qt Quick 2 Application (from Existing QML File)"));
- parameter.setDescription(basicDescription2 + tr("Creates a deployable Qt Quick application from "
+ wizard = new QtQuickAppWizard;
+ wizard->setQtQuickKind(ImportQml2);
+ wizard->setDisplayName(tr("Qt Quick 2 Application (from Existing QML File)"));
+ wizard->setDescription(basicDescription2 + tr("Creates a deployable Qt Quick application from "
"existing QML files. All files and directories that "
"reside in the same directory as the main .qml file "
"are deployed. You can modify the contents of the "
"directory any time before deploying.\n\nRequires <b>Qt 5.0</b> or newer."));
- parameter.setRequiredFeatures(Core::Feature(QtSupport::Constants::FEATURE_QT_QUICK_2));
- list << parameter;
-
- QList<QtQuickAppWizard*> wizardList = Core::createMultipleBaseFileWizardInstances<QtQuickAppWizard>(list, plugin);
-
- Q_ASSERT(wizardList.count() == 5);
-
- for (int i = 0; i < wizardList.count(); i++) {
- wizardList.at(i)->setQtQuickKind(Kind(i));
- }
-}
-
-Core::BaseFileWizardParameters QtQuickAppWizard::baseParameters()
-{
- Core::BaseFileWizardParameters parameters(ProjectWizard);
- 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(QLatin1String(ProjectExplorer::Constants::QT_APPLICATION_WIZARD_CATEGORY_DISPLAY));
-
- return parameters;
+ wizard->setRequiredFeatures(Core::Feature(QtSupport::Constants::FEATURE_QT_QUICK_2));
+ plugin->addAutoReleasedObject(wizard);
}
AbstractMobileAppWizardDialog *QtQuickAppWizard::createWizardDialogInternal(QWidget *parent,
@@ -244,7 +226,7 @@ AbstractMobileAppWizardDialog *QtQuickAppWizard::createWizardDialogInternal(QWid
void QtQuickAppWizard::projectPathChanged(const QString &path) const
{
if (d->wizardDialog->targetsPage())
- d->wizardDialog->targetsPage()->setProFilePath(path);
+ d->wizardDialog->targetsPage()->setProjectPath(path);
}
void QtQuickAppWizard::prepareGenerateFiles(const QWizard *w,
diff --git a/src/plugins/qt4projectmanager/wizards/qtquickappwizard.h b/src/plugins/qt4projectmanager/wizards/qtquickappwizard.h
index f29a2bdcaa..2f8eaf45bb 100644
--- a/src/plugins/qt4projectmanager/wizards/qtquickappwizard.h
+++ b/src/plugins/qt4projectmanager/wizards/qtquickappwizard.h
@@ -38,8 +38,8 @@ namespace Internal {
class QtQuickAppWizard : public AbstractMobileAppWizard
{
Q_OBJECT
-public:
+public:
enum Kind {
QtQuick1_1 = 0,
QtQuick2_0 = 1,
@@ -49,16 +49,14 @@ public:
};
QtQuickAppWizard();
- explicit QtQuickAppWizard(const Core::BaseFileWizardParameters &params, QObject *parent = 0);
- virtual ~QtQuickAppWizard();
+ ~QtQuickAppWizard();
+
static void createInstances(ExtensionSystem::IPlugin *plugin);
protected:
QString fileToOpenPostGeneration() const;
private:
- static Core::BaseFileWizardParameters baseParameters();
-
virtual AbstractMobileApp *app() const;
virtual AbstractMobileAppWizardDialog *wizardDialog() const;
virtual AbstractMobileAppWizardDialog *createWizardDialogInternal(QWidget *parent,
diff --git a/src/plugins/qt4projectmanager/wizards/qtwizard.cpp b/src/plugins/qt4projectmanager/wizards/qtwizard.cpp
index de4813e262..78d4a6a3cb 100644
--- a/src/plugins/qt4projectmanager/wizards/qtwizard.cpp
+++ b/src/plugins/qt4projectmanager/wizards/qtwizard.cpp
@@ -29,17 +29,18 @@
#include "qtwizard.h"
-#include "qt4project.h"
-#include "qt4projectmanager.h"
-#include "qt4projectmanagerconstants.h"
#include "modulespage.h"
-#include "targetsetuppage.h"
+
+#include <qt4projectmanager/qt4project.h>
+#include <qt4projectmanager/qt4projectmanager.h>
+#include <qt4projectmanager/qt4projectmanagerconstants.h>
#include <coreplugin/icore.h>
#include <cpptools/cpptoolsconstants.h>
#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/targetsetuppage.h>
#include <qtsupport/qtkitinformation.h>
#include <qtsupport/qtsupportconstants.h>
@@ -48,41 +49,14 @@
#include <QCoreApplication>
#include <QVariant>
+using namespace ProjectExplorer;
using namespace Qt4ProjectManager;
using namespace Qt4ProjectManager::Internal;
-static Core::BaseFileWizardParameters
- wizardParameters(const QString &id,
- const QString &category,
- const QString &displayCategory,
- const QString &name,
- const QString &description,
- const QIcon &icon)
-{
- Core::BaseFileWizardParameters rc(Core::IWizard::ProjectWizard);
- rc.setCategory(category);
- rc.setDisplayCategory(QCoreApplication::translate("ProjectExplorer",
- displayCategory.toLatin1()));
- rc.setIcon(icon);
- rc.setDisplayName(name);
- rc.setId(id);
- rc.setDescription(description);
- return rc;
-}
-
// -------------------- QtWizard
-QtWizard::QtWizard(const QString &id,
- const QString &category,
- const QString &displayCategory,
- const QString &name,
- const QString &description, const QIcon &icon) :
- Core::BaseFileWizard(wizardParameters(id,
- category,
- displayCategory,
- name,
- description,
- icon))
+QtWizard::QtWizard()
{
+ setWizardKind(Core::IWizard::ProjectWizard);
}
QString QtWizard::sourceSuffix()
@@ -154,14 +128,12 @@ bool QtWizard::showModulesPageForLibraries()
}
// ------------ CustomQt4ProjectWizard
-CustomQt4ProjectWizard::CustomQt4ProjectWizard(const Core::BaseFileWizardParameters& baseFileParameters,
- QObject *parent) :
- ProjectExplorer::CustomProjectWizard(baseFileParameters, parent)
+CustomQt4ProjectWizard::CustomQt4ProjectWizard()
{
}
- QWizard *CustomQt4ProjectWizard::createWizardDialog(QWidget *parent,
- const Core::WizardDialogParameters &wizardDialogParameters) const
+QWizard *CustomQt4ProjectWizard::createWizardDialog
+ (QWidget *parent, const Core::WizardDialogParameters &wizardDialogParameters) const
{
BaseQt4ProjectWizardDialog *wizard = new BaseQt4ProjectWizardDialog(false, parent, wizardDialogParameters);
@@ -240,7 +212,7 @@ int BaseQt4ProjectWizardDialog::addModulesPage(int id)
int BaseQt4ProjectWizardDialog::addTargetSetupPage(bool mobile, int id)
{
- m_targetSetupPage = new TargetSetupPage;
+ m_targetSetupPage = new ProjectExplorer::TargetSetupPage;
const QString platform = selectedPlatform();
Core::FeatureSet features = mobile ? Core::FeatureSet(QtSupport::Constants::FEATURE_MOBILE)
: Core::FeatureSet(QtSupport::Constants::FEATURE_DESKTOP);
@@ -322,13 +294,10 @@ bool BaseQt4ProjectWizardDialog::isQtPlatformSelected(const QString &platform) c
{
QList<Core::Id> selectedKitList = selectedKits();
- QtSupport::QtPlatformKitMatcher matcher(platform);
- QList<ProjectExplorer::Kit *> kitList
- = ProjectExplorer::KitManager::instance()->kits(&matcher);
- foreach (ProjectExplorer::Kit *k, kitList) {
+ foreach (Kit *k, KitManager::matchingKits(QtSupport::QtPlatformKitMatcher(platform)))
if (selectedKitList.contains(k->id()))
return true;
- }
+
return false;
}
@@ -354,5 +323,5 @@ void BaseQt4ProjectWizardDialog::generateProfileName(const QString &name, const
QDir::cleanPath(path + QLatin1Char('/') + name + QLatin1Char('/')
+ name + QLatin1String(".pro"));
- m_targetSetupPage->setProFilePath(proFile);
+ m_targetSetupPage->setProjectPath(proFile);
}
diff --git a/src/plugins/qt4projectmanager/wizards/qtwizard.h b/src/plugins/qt4projectmanager/wizards/qtwizard.h
index 35b095de96..bb78c12d6c 100644
--- a/src/plugins/qt4projectmanager/wizards/qtwizard.h
+++ b/src/plugins/qt4projectmanager/wizards/qtwizard.h
@@ -34,12 +34,14 @@
#include <projectexplorer/baseprojectwizarddialog.h>
#include <projectexplorer/customwizard/customwizard.h>
-namespace ProjectExplorer { class Kit; }
+namespace ProjectExplorer {
+class Kit;
+class TargetSetupPage;
+} // namespace ProjectExplorer
namespace Qt4ProjectManager {
class Qt4Project;
-class TargetSetupPage;
namespace Internal {
@@ -58,15 +60,9 @@ class QtWizard : public Core::BaseFileWizard
Q_OBJECT
protected:
- QtWizard(const QString &id,
- const QString &category,
- const QString &displayCategory,
- const QString &name,
- const QString &description,
- const QIcon &icon);
+ QtWizard();
public:
-
static QString templateDir();
static QString sourceSuffix();
@@ -88,17 +84,18 @@ private:
};
// A custom wizard with an additional Qt 4 target page
-class CustomQt4ProjectWizard : public ProjectExplorer::CustomProjectWizard {
+class CustomQt4ProjectWizard : public ProjectExplorer::CustomProjectWizard
+{
Q_OBJECT
+
public:
- explicit CustomQt4ProjectWizard(const Core::BaseFileWizardParameters& baseFileParameters,
- QObject *parent = 0);
+ CustomQt4ProjectWizard();
- virtual QWizard *createWizardDialog(QWidget *parent,
- const Core::WizardDialogParameters &wizardDialogParameters) const;
static void registerSelf();
-protected:
+private:
+ QWizard *createWizardDialog(QWidget *parent,
+ const Core::WizardDialogParameters &wizardDialogParameters) const;
virtual bool postGenerateFiles(const QWizard *, const Core::GeneratedFiles &l, QString *errorMessage);
private:
@@ -147,7 +144,7 @@ private:
inline void init(bool showModulesPage);
ModulesPage *m_modulesPage;
- TargetSetupPage *m_targetSetupPage;
+ ProjectExplorer::TargetSetupPage *m_targetSetupPage;
QStringList m_selectedModules;
QStringList m_deselectedModules;
QList<Core::Id> m_profileIds;
diff --git a/src/plugins/qt4projectmanager/wizards/subdirsprojectwizard.cpp b/src/plugins/qt4projectmanager/wizards/subdirsprojectwizard.cpp
index a07de9c632..816b60e3ef 100644
--- a/src/plugins/qt4projectmanager/wizards/subdirsprojectwizard.cpp
+++ b/src/plugins/qt4projectmanager/wizards/subdirsprojectwizard.cpp
@@ -35,20 +35,22 @@
#include <coreplugin/icore.h>
#include <qtsupport/qtsupportconstants.h>
-#include <QIcon>
+#include <QCoreApplication>
namespace Qt4ProjectManager {
namespace Internal {
SubdirsProjectWizard::SubdirsProjectWizard()
- : QtWizard(QLatin1String("U.Qt4Subdirs"),
- QLatin1String(ProjectExplorer::Constants::QT_PROJECT_WIZARD_CATEGORY),
- QLatin1String(ProjectExplorer::Constants::QT_PROJECT_WIZARD_CATEGORY_DISPLAY),
- tr("Subdirs Project"),
- tr("Creates a qmake-based subdirs project. This allows you to group "
- "your projects in a tree structure."),
- QIcon(QLatin1String(":/wizards/images/gui.png")))
{
+ setId(QLatin1String("U.Qt4Subdirs"));
+ setCategory(QLatin1String(ProjectExplorer::Constants::QT_PROJECT_WIZARD_CATEGORY));
+ setDisplayCategory(QCoreApplication::translate("ProjectExplorer",
+ ProjectExplorer::Constants::QT_PROJECT_WIZARD_CATEGORY_DISPLAY));
+ setDisplayName(tr("Subdirs Project"));
+ setDescription(tr("Creates a qmake-based subdirs project. This allows you to group "
+ "your projects in a tree structure."));
+ setIcon(QIcon(QLatin1String(":/wizards/images/gui.png")));
+ setRequiredFeatures(Core::Feature(QtSupport::Constants::FEATURE_QT));
}
QWizard *SubdirsProjectWizard::createWizardDialog(QWidget *parent,
@@ -97,10 +99,5 @@ bool SubdirsProjectWizard::postGenerateFiles(const QWizard *w, const Core::Gener
return true;
}
-Core::FeatureSet SubdirsProjectWizard::requiredFeatures() const
-{
- return Core::Feature(QtSupport::Constants::FEATURE_QT);
-}
-
} // namespace Internal
} // namespace Qt4ProjectManager
diff --git a/src/plugins/qt4projectmanager/wizards/subdirsprojectwizard.h b/src/plugins/qt4projectmanager/wizards/subdirsprojectwizard.h
index d8eab03ca0..c17ca2a8c3 100644
--- a/src/plugins/qt4projectmanager/wizards/subdirsprojectwizard.h
+++ b/src/plugins/qt4projectmanager/wizards/subdirsprojectwizard.h
@@ -42,14 +42,12 @@ class SubdirsProjectWizard : public QtWizard
public:
SubdirsProjectWizard();
-protected:
- virtual QWizard *createWizardDialog(QWidget *parent,
+private:
+ QWizard *createWizardDialog(QWidget *parent,
const Core::WizardDialogParameters &wizardDialogParameters) const;
- virtual Core::GeneratedFiles generateFiles(const QWizard *w,
- QString *errorMessage) const;
- virtual bool postGenerateFiles(const QWizard *, const Core::GeneratedFiles &l, QString *errorMessage);
- virtual Core::FeatureSet requiredFeatures() const;
+ Core::GeneratedFiles generateFiles(const QWizard *w, QString *errorMessage) const;
+ bool postGenerateFiles(const QWizard *, const Core::GeneratedFiles &l, QString *errorMessage);
};
} // namespace Internal
diff --git a/src/plugins/qt4projectmanager/wizards/targetsetuppage.cpp b/src/plugins/qt4projectmanager/wizards/targetsetuppage.cpp
deleted file mode 100644
index a39b7c2413..0000000000
--- a/src/plugins/qt4projectmanager/wizards/targetsetuppage.cpp
+++ /dev/null
@@ -1,723 +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 "targetsetuppage.h"
-#include "importwidget.h"
-#include "../qt4targetsetupwidget.h"
-
-#include "buildconfigurationinfo.h"
-#include "qt4buildconfiguration.h"
-#include "qt4project.h"
-#include "qmakekitinformation.h"
-
-#include <coreplugin/icore.h>
-#include <projectexplorer/projectexplorerconstants.h>
-#include <projectexplorer/target.h>
-#include <qtsupport/qtkitinformation.h>
-#include <qtsupport/qtsupportconstants.h>
-#include <qtsupport/qtversionfactory.h>
-#include <qtsupport/qtversionmanager.h>
-#include <utils/qtcprocess.h>
-
-#include <QLabel>
-#include <QMessageBox>
-#include <QScrollArea>
-#include <QVBoxLayout>
-
-namespace Qt4ProjectManager {
-namespace Internal {
-
-static const Core::Id QT_IS_TEMPORARY("Qt4PM.TempQt");
-static const Core::Id KIT_IS_TEMPORARY("Qt4PM.TempKit");
-static const Core::Id KIT_TEMPORARY_NAME("Qt4PM.TempName");
-static const Core::Id KIT_FINAL_NAME("Qt4PM.FinalName");
-static const Core::Id TEMPORARY_OF_PROJECTS("Qt4PM.TempProject");
-
-class TargetSetupPageUi
-{
-public:
- QWidget *centralWidget;
- QWidget *scrollAreaWidget;
- QScrollArea *scrollArea;
- QLabel *headerLabel;
- QLabel *descriptionLabel;
- QLabel *noValidKitLabel;
- QLabel *optionHintLabel;
-
- 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);
- headerLabel->setVisible(false);
-
- noValidKitLabel = new QLabel(setupTargetPage);
- noValidKitLabel->setWordWrap(true);
- noValidKitLabel->setText(TargetSetupPage::tr("<span style=\" font-weight:600;\">No valid kits found.</span>"));
-
-
- optionHintLabel = new QLabel(setupTargetPage);
- optionHintLabel->setWordWrap(true);
- optionHintLabel->setText(TargetSetupPage::tr(
- "Please add a kit in the <a href=\"buildandrun\">options</a> "
- "or via the maintenance tool of the SDK."));
- optionHintLabel->setTextInteractionFlags(Qt::TextBrowserInteraction);
- optionHintLabel->setVisible(false);
-
- centralWidget = new QWidget(setupTargetPage);
- QSizePolicy policy(QSizePolicy::Preferred, QSizePolicy::Fixed);
- policy.setHorizontalStretch(0);
- policy.setVerticalStretch(0);
- policy.setHeightForWidth(centralWidget->sizePolicy().hasHeightForWidth());
- centralWidget->setSizePolicy(policy);
-
- scrollAreaWidget = new QWidget(setupTargetPage);
- scrollArea = new QScrollArea(scrollAreaWidget);
- scrollArea->setWidgetResizable(true);
-
- QWidget *scrollAreaWidgetContents;
- scrollAreaWidgetContents = new QWidget();
- scrollAreaWidgetContents->setGeometry(QRect(0, 0, 230, 81));
- scrollArea->setWidget(scrollAreaWidgetContents);
-
- QVBoxLayout *verticalLayout = new QVBoxLayout(scrollAreaWidget);
- verticalLayout->setSpacing(0);
- verticalLayout->setContentsMargins(0, 0, 0, 0);
- verticalLayout->addWidget(scrollArea);
-
- QVBoxLayout *verticalLayout_2 = new QVBoxLayout(setupTargetPage);
- verticalLayout_2->addWidget(headerLabel);
- verticalLayout_2->addWidget(noValidKitLabel);
- verticalLayout_2->addWidget(descriptionLabel);
- verticalLayout_2->addWidget(optionHintLabel);
- verticalLayout_2->addWidget(centralWidget);
- verticalLayout_2->addWidget(scrollAreaWidget);
-
- QVBoxLayout *verticalLayout_3 = new QVBoxLayout(q);
- verticalLayout_3->setContentsMargins(0, 0, 0, -1);
- verticalLayout_3->addWidget(setupTargetPage);
-
- QObject::connect(optionHintLabel, SIGNAL(linkActivated(QString)),
- q, SLOT(openOptions()));
- }
-};
-
-} // namespace Internal
-
-using namespace Internal;
-
-TargetSetupPage::TargetSetupPage(QWidget *parent) :
- QWizardPage(parent),
- m_requiredMatcher(0),
- m_preferredMatcher(0),
- m_baseLayout(0),
- m_importSearch(false),
- m_ignoreUpdates(false),
- m_firstWidget(0),
- m_ui(new TargetSetupPageUi),
- m_importWidget(new Internal::ImportWidget(this)),
- m_spacer(new QSpacerItem(0,0, QSizePolicy::Minimum, QSizePolicy::MinimumExpanding)),
- m_forceOptionHint(false)
-{
- setObjectName(QLatin1String("TargetSetupPage"));
- setWindowTitle(tr("Select Kits for Your Project"));
- m_ui->setupUi(this);
-
- QSizePolicy policy(QSizePolicy::Preferred, QSizePolicy::Preferred);
- policy.setHorizontalStretch(0);
- policy.setVerticalStretch(0);
- policy.setHeightForWidth(sizePolicy().hasHeightForWidth());
- setSizePolicy(policy);
-
- QWidget *centralWidget = new QWidget(this);
- m_ui->scrollArea->setWidget(centralWidget);
- centralWidget->setLayout(new QVBoxLayout);
- m_ui->centralWidget->setLayout(new QVBoxLayout);
- m_ui->centralWidget->layout()->setMargin(0);
-
- setUseScrollArea(true);
- setImportSearch(false);
-
- setTitle(tr("Kit Selection"));
-
- ProjectExplorer::KitManager *km = ProjectExplorer::KitManager::instance();
- connect(km, SIGNAL(kitAdded(ProjectExplorer::Kit*)),
- this, SLOT(handleKitAddition(ProjectExplorer::Kit*)));
- connect(km, SIGNAL(kitRemoved(ProjectExplorer::Kit*)),
- this, SLOT(handleKitRemoval(ProjectExplorer::Kit*)));
- connect(km, SIGNAL(kitUpdated(ProjectExplorer::Kit*)),
- this, SLOT(handleKitUpdate(ProjectExplorer::Kit*)));
- connect(m_importWidget, SIGNAL(importFrom(Utils::FileName)),
- this, SLOT(import(Utils::FileName)));
-}
-
-void TargetSetupPage::initializePage()
-{
- reset();
-
- setupWidgets();
- setupImports();
- selectAtLeastOneKit();
-}
-
-void TargetSetupPage::setRequiredKitMatcher(ProjectExplorer::KitMatcher *matcher)
-{
- m_requiredMatcher = matcher;
-}
-
-QList<Core::Id> TargetSetupPage::selectedKits() const
-{
- QList<Core::Id> result;
- QMap<Core::Id, Qt4TargetSetupWidget *>::const_iterator it, end;
- it = m_widgets.constBegin();
- end = m_widgets.constEnd();
-
- for ( ; it != end; ++it) {
- if (isKitSelected(it.key()))
- result << it.key();
- }
- return result;
-}
-
-void TargetSetupPage::setPreferredKitMatcher(ProjectExplorer::KitMatcher *matcher)
-{
- m_preferredMatcher = matcher;
-}
-
-TargetSetupPage::~TargetSetupPage()
-{
- reset();
- delete m_ui;
- delete m_preferredMatcher;
- delete m_requiredMatcher;
-}
-
-bool TargetSetupPage::isKitSelected(Core::Id id) const
-{
- Qt4TargetSetupWidget *widget = m_widgets.value(id);
- return widget && widget->isKitSelected();
-}
-
-void TargetSetupPage::setKitSelected(Core::Id id, bool selected)
-{
- Qt4TargetSetupWidget *widget = m_widgets.value(id);
- if (widget)
- widget->setKitSelected(selected);
-}
-
-bool TargetSetupPage::isComplete() const
-{
- foreach (Qt4TargetSetupWidget *widget, m_widgets.values())
- if (widget->isKitSelected())
- return true;
- return false;
-}
-
-void TargetSetupPage::setImportSearch(bool b)
-{
- m_importSearch = b;
- m_importWidget->setVisible(b);
-}
-
-void TargetSetupPage::setupWidgets()
-{
- // Known profiles:
- foreach (ProjectExplorer::Kit *k, ProjectExplorer::KitManager::instance()->kits(m_requiredMatcher))
- addWidget(k);
-
- // Setup import widget:
- m_baseLayout->addWidget(m_importWidget);
- Utils::FileName path = Utils::FileName::fromString(m_proFilePath);
- path = path.parentDir(); // base dir
- path = path.parentDir(); // parent dir
- m_importWidget->setCurrentDirectory(path);
-
- updateVisibility();
-}
-
-void TargetSetupPage::reset()
-{
- foreach (Qt4TargetSetupWidget *widget, m_widgets.values()) {
- ProjectExplorer::Kit *k = widget->kit();
- if (!k)
- continue;
- removeProject(k, m_proFilePath);
- delete widget;
- }
-
- m_widgets.clear();
- m_firstWidget = 0;
-}
-
-ProjectExplorer::Kit *TargetSetupPage::createTemporaryKit(QtSupport::BaseQtVersion *version,
- bool temporaryVersion,
- const Utils::FileName &parsedSpec)
-{
- ProjectExplorer::Kit *k = new ProjectExplorer::Kit;
- QtSupport::QtKitInformation::setQtVersion(k, version);
- ProjectExplorer::ToolChainKitInformation::setToolChain(k, version->preferredToolChain(parsedSpec));
- QmakeKitInformation::setMkspec(k, parsedSpec);
-
- k->setDisplayName(tr("%1 - temporary").arg(version->displayName()));
- k->setValue(KIT_TEMPORARY_NAME, k->displayName());
- k->setValue(KIT_FINAL_NAME, version->displayName());
- k->setValue(KIT_IS_TEMPORARY, true);
- if (temporaryVersion)
- k->setValue(QT_IS_TEMPORARY, version->uniqueId());
-
- m_ignoreUpdates = true;
- ProjectExplorer::KitManager::instance()->registerKit(k);
- m_ignoreUpdates = false;
-
- return k;
-}
-
-void TargetSetupPage::cleanKit(ProjectExplorer::Kit *k)
-{
- m_ignoreUpdates = true;
- k->removeKey(KIT_IS_TEMPORARY);
- k->removeKey(QT_IS_TEMPORARY);
- k->removeKey(TEMPORARY_OF_PROJECTS);
- const QString tempName = k->value(KIT_TEMPORARY_NAME).toString();
- if (!tempName.isNull() && k->displayName() == tempName)
- k->setDisplayName(k->value(KIT_FINAL_NAME).toString());
- k->removeKey(KIT_TEMPORARY_NAME);
- k->removeKey(KIT_FINAL_NAME);
- m_ignoreUpdates = false;
-}
-
-void TargetSetupPage::makeQtPersistent(ProjectExplorer::Kit *k)
-{
- m_ignoreUpdates = true;
- k->removeKey(QT_IS_TEMPORARY);
- m_ignoreUpdates = false;
-}
-
-void TargetSetupPage::addProject(ProjectExplorer::Kit *k, const QString &path)
-{
- if (!k->hasValue(KIT_IS_TEMPORARY))
- return;
-
- QStringList projects = k->value(TEMPORARY_OF_PROJECTS, QStringList()).toStringList();
- if (!projects.contains(path)) {
- projects.append(path);
- m_ignoreUpdates = true;
- k->setValue(TEMPORARY_OF_PROJECTS, projects);
- m_ignoreUpdates = false;
- }
-}
-
-void TargetSetupPage::removeProject(ProjectExplorer::Kit *k, const QString &path)
-{
- if (!k->hasValue(KIT_IS_TEMPORARY) || path.isEmpty())
- return;
-
- QStringList projects = k->value(TEMPORARY_OF_PROJECTS, QStringList()).toStringList();
- if (projects.contains(path)) {
- projects.removeOne(path);
- m_ignoreUpdates = true;
- if (projects.isEmpty())
- ProjectExplorer::KitManager::instance()->deregisterKit(k);
- else
- k->setValue(TEMPORARY_OF_PROJECTS, projects);
- m_ignoreUpdates = false;
- }
-}
-
-void TargetSetupPage::setProFilePath(const QString &path)
-{
- m_proFilePath = path;
- if (!m_proFilePath.isEmpty())
- m_ui->headerLabel->setText(tr("Qt Creator can use the following kits for project <b>%1</b>:",
- "%1: Project name").arg(QFileInfo(m_proFilePath).baseName()));
- m_ui->headerLabel->setVisible(!m_proFilePath.isEmpty());
-
- if (m_widgets.isEmpty())
- return;
-
- reset();
- setupWidgets();
-}
-
-void TargetSetupPage::setNoteText(const QString &text)
-{
- m_ui->descriptionLabel->setText(text);
- m_ui->descriptionLabel->setVisible(!text.isEmpty());
-}
-
-void TargetSetupPage::showOptionsHint(bool show)
-{
- m_forceOptionHint = show;
- updateVisibility();
-}
-
-void TargetSetupPage::import(const Utils::FileName &path)
-{
- import(path, false);
-}
-
-void TargetSetupPage::import(const Utils::FileName &path, const bool silent)
-{
- QFileInfo fi = path.toFileInfo();
- if (!fi.exists() && !fi.isDir())
- return;
-
- QStringList makefiles = QDir(path.toString()).entryList(QStringList(QLatin1String("Makefile*")));
-
- QtSupport::BaseQtVersion *version = 0;
- bool temporaryVersion = false;
-
- QtSupport::QtVersionManager *vm = QtSupport::QtVersionManager::instance();
- ProjectExplorer::KitManager *km = ProjectExplorer::KitManager::instance();
- bool found = false;
-
- foreach (const QString &file, makefiles) {
- // find interesting makefiles
- QString makefile = path.toString() + QLatin1Char('/') + file;
- Utils::FileName qmakeBinary = QtSupport::QtVersionManager::findQMakeBinaryFromMakefile(makefile);
- QFileInfo fi = qmakeBinary.toFileInfo();
- Utils::FileName canonicalQmakeBinary = Utils::FileName::fromString(fi.canonicalFilePath());
- if (canonicalQmakeBinary.isEmpty())
- continue;
- if (QtSupport::QtVersionManager::makefileIsFor(makefile, m_proFilePath) != QtSupport::QtVersionManager::SameProject)
- continue;
-
- // Find version:
- foreach (QtSupport::BaseQtVersion *v, vm->versions()) {
- QFileInfo vfi = v->qmakeCommand().toFileInfo();
- Utils::FileName current = Utils::FileName::fromString(vfi.canonicalFilePath());
- if (current == canonicalQmakeBinary) {
- version = v;
- break;
- }
- }
-
- // Create a new version if not found:
- if (!version) {
- // Do not use the canonical path here...
- version = QtSupport::QtVersionFactory::createQtVersionFromQMakePath(qmakeBinary);
- if (!version)
- continue;
-
- vm->addVersion(version);
- temporaryVersion = true;
- }
-
- // find qmake arguments and mkspec
- QPair<QtSupport::BaseQtVersion::QmakeBuildConfigs, QString> makefileBuildConfig =
- QtSupport::QtVersionManager::scanMakeFile(makefile, version->defaultBuildConfig());
-
- QString additionalArguments = makefileBuildConfig.second;
- Utils::FileName parsedSpec =
- Qt4BuildConfiguration::extractSpecFromArguments(&additionalArguments, path.toString(), version);
- Utils::FileName versionSpec = version->mkspec();
- if (parsedSpec.isEmpty() || parsedSpec == Utils::FileName::fromString(QLatin1String("default")))
- parsedSpec = versionSpec;
-
- QString specArgument;
- // Compare mkspecs and add to additional arguments
- if (parsedSpec != versionSpec)
- specArgument = QLatin1String("-spec ") + Utils::QtcProcess::quoteArg(parsedSpec.toUserOutput());
- Utils::QtcProcess::addArgs(&specArgument, additionalArguments);
-
- // Find profiles (can be more than one, e.g. (Linux-)Desktop and embedded linux):
- QList<ProjectExplorer::Kit *> kitList;
- foreach (ProjectExplorer::Kit *k, km->kits()) {
- QtSupport::BaseQtVersion *profileVersion = QtSupport::QtKitInformation::qtVersion(k);
- Utils::FileName profileSpec = QmakeKitInformation::mkspec(k);
- ProjectExplorer::ToolChain *tc = ProjectExplorer::ToolChainKitInformation::toolChain(k);
- if (profileSpec.isEmpty() && profileVersion)
- profileSpec = profileVersion->mkspecFor(tc);
-
- if (profileVersion == version
- && profileSpec == parsedSpec)
- kitList.append(k);
- }
- if (kitList.isEmpty())
- kitList.append(createTemporaryKit(version, temporaryVersion, parsedSpec));
-
- foreach (ProjectExplorer::Kit *k, kitList) {
- addProject(k, m_proFilePath);
-
- // Create widget:
- Qt4TargetSetupWidget *widget = m_widgets.value(k->id(), 0);
- if (!widget)
- addWidget(k);
- widget = m_widgets.value(k->id(), 0);
- if (!widget)
- continue;
-
- // create info:
- BuildConfigurationInfo info = BuildConfigurationInfo(makefileBuildConfig.first,
- specArgument,
- path.toString(),
- true,
- file);
-
- widget->addBuildConfigurationInfo(info, true);
- widget->setKitSelected(true);
- found = true;
- }
- }
-
- updateVisibility();
-
- if (!found && !silent)
- QMessageBox::critical(this,
- tr("No Build Found"),
- tr("No build found in %1 matching project %2.").arg(path.toUserOutput()).arg(m_proFilePath));
-}
-
-void TargetSetupPage::handleQtUpdate(const QList<int> &add, const QList<int> &rm, const QList<int> &mod)
-{
- Q_UNUSED(add);
- // Update kit to no longer claim a Qt version is temporary once it is modified/removed.
- foreach (ProjectExplorer::Kit *k, ProjectExplorer::KitManager::instance()->kits()) {
- if (!k->hasValue(QT_IS_TEMPORARY))
- continue;
- int qtVersion = k->value(QT_IS_TEMPORARY, -1).toInt();
- if (rm.contains(qtVersion) || mod.contains(qtVersion))
- makeQtPersistent(k);
- }
-}
-
-void TargetSetupPage::setupImports()
-{
- if (!m_importSearch || m_proFilePath.isEmpty())
- return;
-
- QFileInfo pfi(m_proFilePath);
- const QString prefix = pfi.baseName();
- QStringList toImport;
- toImport << pfi.absolutePath();
-
- QList<ProjectExplorer::Kit *> kitList = ProjectExplorer::KitManager::instance()->kits();
- foreach (ProjectExplorer::Kit *k, kitList) {
- QFileInfo fi(Qt4Project::shadowBuildDirectory(m_proFilePath, k, QString()));
- const QString baseDir = fi.absolutePath();
-
- foreach (const QString &dir, QDir(baseDir).entryList()) {
- const QString path = baseDir + QLatin1Char('/') + dir;
- if (dir.startsWith(prefix) && !toImport.contains(path))
- toImport << path;
-
- }
- }
- foreach (const QString &path, toImport)
- import(Utils::FileName::fromString(path), true);
-}
-
-void TargetSetupPage::handleKitAddition(ProjectExplorer::Kit *k)
-{
- if (m_ignoreUpdates)
- return;
-
- Q_ASSERT(!m_widgets.contains(k->id()));
- addWidget(k);
- updateVisibility();
-}
-
-void TargetSetupPage::handleKitRemoval(ProjectExplorer::Kit *k)
-{
- QtSupport::QtVersionManager *vm = QtSupport::QtVersionManager::instance();
- QtSupport::BaseQtVersion *version = vm->version(k->value(QT_IS_TEMPORARY, -1).toInt());
- if (version)
- vm->removeVersion(version);
-
- if (m_ignoreUpdates)
- return;
-
- removeWidget(k);
- updateVisibility();
-}
-
-void TargetSetupPage::handleKitUpdate(ProjectExplorer::Kit *k)
-{
- if (m_ignoreUpdates)
- return;
-
- cleanKit(k);
- Qt4TargetSetupWidget *widget = m_widgets.value(k->id());
-
- bool acceptable = true;
- if (m_requiredMatcher && !m_requiredMatcher->matches(k))
- acceptable = false;
-
- if (widget && !acceptable)
- removeWidget(k);
- else if (!widget && acceptable)
- addWidget(k);
-
- updateVisibility();
-}
-
-void TargetSetupPage::selectAtLeastOneKit()
-{
- bool atLeastOneKitSelected = false;
- foreach (Qt4TargetSetupWidget *w, m_widgets.values()) {
- if (w->isKitSelected()) {
- atLeastOneKitSelected = true;
- break;
- }
- }
-
- if (!atLeastOneKitSelected) {
- Qt4TargetSetupWidget *widget = m_firstWidget;
- ProjectExplorer::Kit *defaultKit = ProjectExplorer::KitManager::instance()->defaultKit();
- if (defaultKit)
- widget = m_widgets.value(defaultKit->id(), m_firstWidget);
- if (widget)
- widget->setKitSelected(true);
- m_firstWidget = 0;
- }
- emit completeChanged(); // Is this necessary?
-}
-
-void TargetSetupPage::updateVisibility()
-{
- // Always show the widgets, the import widget always makes sense to show.
- m_ui->scrollAreaWidget->setVisible(m_baseLayout == m_ui->scrollArea->widget()->layout());
- m_ui->centralWidget->setVisible(m_baseLayout == m_ui->centralWidget->layout());
-
- bool hasKits = !m_widgets.isEmpty();
- m_ui->noValidKitLabel->setVisible(!hasKits);
- m_ui->optionHintLabel->setVisible(m_forceOptionHint || !hasKits);
-
- emit completeChanged();
-}
-
-void TargetSetupPage::openOptions()
-{
- Core::ICore::instance()->showOptionsDialog(ProjectExplorer::Constants::PROJECTEXPLORER_SETTINGS_CATEGORY,
- ProjectExplorer::Constants::KITS_SETTINGS_PAGE_ID,
- this);
-}
-
-void TargetSetupPage::removeWidget(ProjectExplorer::Kit *k)
-{
- Qt4TargetSetupWidget *widget = m_widgets.value(k->id());
- if (!widget)
- return;
- if (widget == m_firstWidget)
- m_firstWidget = 0;
- widget->deleteLater();
- m_widgets.remove(k->id());
-}
-
-Qt4TargetSetupWidget *TargetSetupPage::addWidget(ProjectExplorer::Kit *k)
-{
- if (m_requiredMatcher && !m_requiredMatcher->matches(k))
- return 0;
-
- QList<BuildConfigurationInfo> infoList = Qt4BuildConfigurationFactory::availableBuildConfigurations(k, m_proFilePath);
- Qt4TargetSetupWidget *widget = infoList.isEmpty() ? 0 : new Qt4TargetSetupWidget(k, m_proFilePath, infoList);
- if (!widget)
- return 0;
-
- m_baseLayout->removeWidget(m_importWidget);
- m_baseLayout->removeItem(m_spacer);
-
- widget->setKitSelected(m_preferredMatcher && m_preferredMatcher->matches(k));
- m_widgets.insert(k->id(), widget);
- m_baseLayout->addWidget(widget);
-
- m_baseLayout->addWidget(m_importWidget);
- m_baseLayout->addItem(m_spacer);
-
- connect(widget, SIGNAL(selectedToggled()),
- this, SIGNAL(completeChanged()));
-
- if (!m_firstWidget)
- m_firstWidget = widget;
-
- return widget;
-}
-
-class KitBuildInfo
-{
-public:
- KitBuildInfo(ProjectExplorer::Kit *k, const QList<BuildConfigurationInfo> &il) :
- kit(k), infoList(il)
- { }
-
- ProjectExplorer::Kit *kit;
- QList<BuildConfigurationInfo> infoList;
-};
-
-bool TargetSetupPage::setupProject(Qt4ProjectManager::Qt4Project *project)
-{
- QList<KitBuildInfo> toRegister;
- foreach (Qt4TargetSetupWidget *widget, m_widgets.values()) {
- if (!widget->isKitSelected())
- continue;
-
- ProjectExplorer::Kit *k = widget->kit();
- cleanKit(k);
- toRegister.append(KitBuildInfo(k, widget->selectedBuildConfigurationInfoList()));
- widget->clearKit();
- }
- reset();
-
- // only register kits after we are done cleaning up
- foreach (const KitBuildInfo &data, toRegister)
- project->addTarget(project->createTarget(data.kit, data.infoList));
-
- // Select active target
- // a) Simulator target
- // b) Desktop target
- // c) the first target
- ProjectExplorer::Target *activeTarget = 0;
- QList<ProjectExplorer::Target *> targets = project->targets();
- foreach (ProjectExplorer::Target *t, targets) {
- QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(t->kit());
- if (version && version->type() == QLatin1String(QtSupport::Constants::SIMULATORQT))
- activeTarget = t;
- else if (!activeTarget && version && version->type() == QLatin1String(QtSupport::Constants::DESKTOPQT))
- activeTarget = t;
- }
- if (!activeTarget && !targets.isEmpty())
- activeTarget = targets.first();
- if (activeTarget)
- project->setActiveTarget(activeTarget);
-
- return true;
-}
-
-void TargetSetupPage::setUseScrollArea(bool b)
-{
- m_baseLayout = b ? m_ui->scrollArea->widget()->layout() : m_ui->centralWidget->layout();
- m_ui->scrollAreaWidget->setVisible(b);
- m_ui->centralWidget->setVisible(!b);
-}
-
-} // namespace Qt4ProjectManager
diff --git a/src/plugins/qt4projectmanager/wizards/testwizard.cpp b/src/plugins/qt4projectmanager/wizards/testwizard.cpp
index 4d2758dff8..e9472028c3 100644
--- a/src/plugins/qt4projectmanager/wizards/testwizard.cpp
+++ b/src/plugins/qt4projectmanager/wizards/testwizard.cpp
@@ -36,24 +36,26 @@
#include <utils/qtcassert.h>
+#include <QCoreApplication>
#include <QTextStream>
#include <QFileInfo>
-#include <QIcon>
-
namespace Qt4ProjectManager {
namespace Internal {
-TestWizard::TestWizard() :
- QtWizard(QLatin1String("L.Qt4Test"),
- QLatin1String(ProjectExplorer::Constants::QT_PROJECT_WIZARD_CATEGORY),
- QLatin1String(ProjectExplorer::Constants::QT_PROJECT_WIZARD_CATEGORY_DISPLAY),
- tr("Qt Unit Test"),
- tr("Creates a QTestLib-based unit test for a feature or a class. "
- "Unit tests allow you to verify that the code is fit for use "
- "and that there are no regressions."),
- QIcon(QLatin1String(":/wizards/images/console.png")))
+TestWizard::TestWizard()
{
+ setId(QLatin1String("L.Qt4Test"));
+ setCategory(QLatin1String(ProjectExplorer::Constants::QT_PROJECT_WIZARD_CATEGORY));
+ setDisplayCategory(QCoreApplication::translate("ProjectExplorer",
+ ProjectExplorer::Constants::QT_PROJECT_WIZARD_CATEGORY_DISPLAY));
+ setDisplayName(tr("Qt Unit Test"));
+ setDescription(tr("Creates a QTestLib-based unit test for a feature or a class. "
+ "Unit tests allow you to verify that the code is fit for use "
+ "and that there are no regressions."));
+ setIcon(QIcon(QLatin1String(":/wizards/images/console.png")));
+ setRequiredFeatures(Core::Feature(QtSupport::Constants::FEATURE_QT_CONSOLE) |
+ Core::Feature(QtSupport::Constants::FEATURE_QT));
}
QWizard *TestWizard::createWizardDialog(QWidget *parent,
@@ -181,11 +183,5 @@ Core::GeneratedFiles TestWizard::generateFiles(const QWizard *w, QString *errorM
return Core::GeneratedFiles() << source << profile;
}
-Core::FeatureSet TestWizard::requiredFeatures() const
-{
- return Core::Feature(QtSupport::Constants::FEATURE_QT_CONSOLE) |
- Core::Feature(QtSupport::Constants::FEATURE_QT);
-}
-
} // namespace Internal
} // namespace Qt4ProjectManager
diff --git a/src/plugins/qt4projectmanager/wizards/testwizard.h b/src/plugins/qt4projectmanager/wizards/testwizard.h
index 80659b0186..f8ffa99bf3 100644
--- a/src/plugins/qt4projectmanager/wizards/testwizard.h
+++ b/src/plugins/qt4projectmanager/wizards/testwizard.h
@@ -41,14 +41,12 @@ class TestWizard : public QtWizard
public:
TestWizard();
- virtual Core::FeatureSet requiredFeatures() const;
protected:
- virtual QWizard *createWizardDialog(QWidget *parent,
+ QWizard *createWizardDialog(QWidget *parent,
const Core::WizardDialogParameters &wizardDialogParameters) const;
- virtual Core::GeneratedFiles generateFiles(const QWizard *w,
- QString *errorMessage) const;
+ Core::GeneratedFiles generateFiles(const QWizard *w, QString *errorMessage) const;
};
} // namespace Internal
diff --git a/src/plugins/qtsupport/QtSupport.pluginspec.in b/src/plugins/qtsupport/QtSupport.pluginspec.in
index 42db1d4a2f..133f76afc1 100644
--- a/src/plugins/qtsupport/QtSupport.pluginspec.in
+++ b/src/plugins/qtsupport/QtSupport.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"QtSupport\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"QtSupport\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/qtsupport/baseqtversion.cpp b/src/plugins/qtsupport/baseqtversion.cpp
index e2062e2145..d1d9cd6625 100644
--- a/src/plugins/qtsupport/baseqtversion.cpp
+++ b/src/plugins/qtsupport/baseqtversion.cpp
@@ -59,12 +59,12 @@
#include <QCoreApplication>
#include <QProcess>
+using namespace Core;
using namespace QtSupport;
using namespace QtSupport::Internal;
+using namespace ProjectExplorer;
using namespace Utils;
-static const char QTVERSIONID[] = "Id";
-static const char QTVERSIONNAME[] = "Name";
static const char QTVERSIONAUTODETECTED[] = "isAutodetected";
static const char QTVERSIONAUTODETECTIONSOURCE []= "autodetectionSource";
static const char QTVERSIONQMAKEPATH[] = "QMakePath";
@@ -133,7 +133,7 @@ bool QtVersionNumber::operator >=(const QtVersionNumber &b) const
///////////////
int BaseQtVersion::getUniqueId()
{
- return QtVersionManager::instance()->getUniqueId();
+ return QtVersionManager::getUniqueId();
}
BaseQtVersion::BaseQtVersion(const FileName &qmakeCommand, bool isAutodetected, const QString &autodetectionSource)
@@ -170,6 +170,7 @@ BaseQtVersion::BaseQtVersion()
m_mkspecReadUpToDate(false),
m_defaultConfigIsDebug(true),
m_defaultConfigIsDebugAndRelease(true),
+ m_frameworkBuild(false),
m_versionInfoUpToDate(false),
m_installed(true),
m_hasExamples(false),
@@ -231,23 +232,23 @@ QString BaseQtVersion::defaultDisplayName(const QString &versionString, const Fi
QCoreApplication::translate("QtVersion", "Qt %1 (%2)").arg(versionString, location);
}
-Core::FeatureSet BaseQtVersion::availableFeatures() const
+FeatureSet BaseQtVersion::availableFeatures() const
{
- Core::FeatureSet features = Core::FeatureSet(Constants::FEATURE_QWIDGETS)
- | Core::FeatureSet(Constants::FEATURE_QT)
- | Core::FeatureSet(Constants::FEATURE_QT_WEBKIT)
- | Core::FeatureSet(Constants::FEATURE_QT_CONSOLE);
+ FeatureSet features = FeatureSet(Constants::FEATURE_QWIDGETS)
+ | FeatureSet(Constants::FEATURE_QT)
+ | FeatureSet(Constants::FEATURE_QT_WEBKIT)
+ | FeatureSet(Constants::FEATURE_QT_CONSOLE);
if (qtVersion() >= QtVersionNumber(4, 7, 0)) {
- features |= Core::FeatureSet(Constants::FEATURE_QT_QUICK);
- features |= Core::FeatureSet(Constants::FEATURE_QT_QUICK_1);
+ features |= FeatureSet(Constants::FEATURE_QT_QUICK);
+ features |= FeatureSet(Constants::FEATURE_QT_QUICK_1);
}
if (qtVersion() >= QtVersionNumber(4, 7, 1))
- features |= Core::FeatureSet(Constants::FEATURE_QT_QUICK_1_1);
+ features |= FeatureSet(Constants::FEATURE_QT_QUICK_1_1);
if (qtVersion() >= QtVersionNumber(5, 0, 0))
- features |= Core::FeatureSet(Constants::FEATURE_QT_QUICK_2);
+ features |= FeatureSet(Constants::FEATURE_QT_QUICK_2);
if (qtVersion() >= QtVersionNumber(5, 1, 0))
- features |= Core::FeatureSet(Constants::FEATURE_QT_QUICK_CONTROLS);
+ features |= FeatureSet(Constants::FEATURE_QT_QUICK_CONTROLS);
return features;
}
@@ -269,25 +270,25 @@ bool BaseQtVersion::supportsPlatform(const QString &platform) const
return platform == platformName();
}
-QList<ProjectExplorer::Task> BaseQtVersion::validateKit(const ProjectExplorer::Kit *k)
+QList<Task> BaseQtVersion::validateKit(const Kit *k)
{
- QList<ProjectExplorer::Task> result;
+ QList<Task> result;
BaseQtVersion *version = QtKitInformation::qtVersion(k);
Q_ASSERT(version == this);
- const QList<ProjectExplorer::Abi> qtAbis = version->qtAbis();
+ const QList<Abi> qtAbis = version->qtAbis();
if (qtAbis.isEmpty()) // No need to test if Qt does not know anyway...
return result;
- ProjectExplorer::ToolChain *tc = ProjectExplorer::ToolChainKitInformation::toolChain(k);
+ ToolChain *tc = ToolChainKitInformation::toolChain(k);
if (tc) {
- ProjectExplorer::Abi targetAbi = tc->targetAbi();
+ Abi targetAbi = tc->targetAbi();
bool fuzzyMatch = false;
bool fullMatch = false;
QString qtAbiString;
- foreach (const ProjectExplorer::Abi &qtAbi, qtAbis) {
+ foreach (const Abi &qtAbi, qtAbis) {
if (!qtAbiString.isEmpty())
qtAbiString.append(QLatin1Char(' '));
qtAbiString.append(qtAbi.toString());
@@ -308,9 +309,8 @@ QList<ProjectExplorer::Task> BaseQtVersion::validateKit(const ProjectExplorer::K
"The compiler '%1' (%2) may not produce code compatible with the Qt version '%3' (%4).");
message = message.arg(tc->displayName(), targetAbi.toString(),
version->displayName(), qtAbiString);
- result << ProjectExplorer::Task(fuzzyMatch ? ProjectExplorer::Task::Warning : ProjectExplorer::Task::Error,
- message, FileName(), -1,
- Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM));
+ result << Task(fuzzyMatch ? Task::Warning : Task::Error, message, FileName(), -1,
+ ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM);
}
}
return result;
@@ -318,29 +318,34 @@ QList<ProjectExplorer::Task> BaseQtVersion::validateKit(const ProjectExplorer::K
FileName BaseQtVersion::headerPath() const
{
- return Utils::FileName::fromUserInput(qmakeProperty("QT_INSTALL_HEADERS"));
+ return FileName::fromUserInput(qmakeProperty("QT_INSTALL_HEADERS"));
}
FileName BaseQtVersion::docsPath() const
{
- return Utils::FileName::fromUserInput(qmakeProperty("QT_INSTALL_DOCS"));
+ return FileName::fromUserInput(qmakeProperty("QT_INSTALL_DOCS"));
}
FileName BaseQtVersion::libraryPath() const
{
- return Utils::FileName::fromUserInput(qmakeProperty("QT_INSTALL_LIBS"));
+ return FileName::fromUserInput(qmakeProperty("QT_INSTALL_LIBS"));
+}
+
+FileName BaseQtVersion::pluginPath() const
+{
+ return FileName::fromUserInput(qmakeProperty("QT_INSTALL_PLUGINS"));
}
FileName BaseQtVersion::binPath() const
{
- return Utils::FileName::fromUserInput(qmakeProperty("QT_HOST_BINS"));
+ return FileName::fromUserInput(qmakeProperty("QT_HOST_BINS"));
}
-Utils::FileName BaseQtVersion::mkspecsPath() const
+FileName BaseQtVersion::mkspecsPath() const
{
- Utils::FileName result = Utils::FileName::fromUserInput(qmakeProperty("QT_HOST_DATA"));
+ FileName result = FileName::fromUserInput(qmakeProperty("QT_HOST_DATA"));
if (result.isEmpty())
- result = Utils::FileName::fromUserInput(qmakeProperty("QMAKE_MKSPECS"));
+ result = FileName::fromUserInput(qmakeProperty("QMAKE_MKSPECS"));
else
result.appendPath(QLatin1String("mkspecs"));
return result;
@@ -360,6 +365,7 @@ QString BaseQtVersion::qtLibInfix() const
bool BaseQtVersion::isFrameworkBuild() const
{
+ ensureMkSpecParsed();
return m_frameworkBuild;
}
@@ -380,24 +386,33 @@ void BaseQtVersion::setId(int id)
void BaseQtVersion::fromMap(const QVariantMap &map)
{
- m_id = map.value(QLatin1String(QTVERSIONID)).toInt();
+ m_id = map.value(QLatin1String(Constants::QTVERSIONID)).toInt();
if (m_id == -1) // this happens on adding from installer, see updateFromInstaller => get a new unique id
- m_id = QtVersionManager::instance()->getUniqueId();
- m_displayName = map.value(QLatin1String(QTVERSIONNAME)).toString();
+ m_id = QtVersionManager::getUniqueId();
+ m_displayName = map.value(QLatin1String(Constants::QTVERSIONNAME)).toString();
m_isAutodetected = map.value(QLatin1String(QTVERSIONAUTODETECTED)).toBool();
if (m_isAutodetected)
m_autodetectionSource = map.value(QLatin1String(QTVERSIONAUTODETECTIONSOURCE)).toString();
QString string = map.value(QLatin1String(QTVERSIONQMAKEPATH)).toString();
if (string.startsWith(QLatin1Char('~')))
string.remove(0, 1).prepend(QDir::homePath());
+
+ QFileInfo fi(string);
+ if (BuildableHelperLibrary::isQtChooser(fi)) {
+ // we don't want to treat qtchooser as a normal qmake
+ // see e.g. QTCREATORBUG-9841, also this lead to users changing what
+ // qtchooser forwards too behind our backs, which will inadvertly lead to bugs
+ string = BuildableHelperLibrary::qtChooserToQmakePath(fi.symLinkTarget());
+ }
+
ctor(FileName::fromString(string));
}
QVariantMap BaseQtVersion::toMap() const
{
QVariantMap result;
- result.insert(QLatin1String(QTVERSIONID), uniqueId());
- result.insert(QLatin1String(QTVERSIONNAME), displayName());
+ result.insert(QLatin1String(Constants::QTVERSIONID), uniqueId());
+ result.insert(QLatin1String(Constants::QTVERSIONNAME), displayName());
result.insert(QLatin1String(QTVERSIONAUTODETECTED), isAutodetected());
if (isAutodetected())
result.insert(QLatin1String(QTVERSIONAUTODETECTIONSOURCE), autodetectionSource());
@@ -449,12 +464,11 @@ QStringList BaseQtVersion::warningReason() const
return ret;
}
-ProjectExplorer::ToolChain *BaseQtVersion::preferredToolChain(const FileName &ms) const
+ToolChain *BaseQtVersion::preferredToolChain(const FileName &ms) const
{
const FileName spec = ms.isEmpty() ? mkspec() : ms;
- QList<ProjectExplorer::ToolChain *> tcList = ProjectExplorer::ToolChainManager::instance()->toolChains();
- ProjectExplorer::ToolChain *possibleTc = 0;
- foreach (ProjectExplorer::ToolChain *tc, tcList) {
+ ToolChain *possibleTc = 0;
+ foreach (ToolChain *tc, ToolChainManager::toolChains()) {
if (!qtAbis().contains(tc->targetAbi()))
continue;
if (tc->suggestedMkspecList().contains(spec))
@@ -470,7 +484,7 @@ FileName BaseQtVersion::qmakeCommand() const
return m_qmakeCommand;
}
-QList<ProjectExplorer::Abi> BaseQtVersion::qtAbis() const
+QList<Abi> BaseQtVersion::qtAbis() const
{
if (!m_hasQtAbis) {
m_qtAbis = detectQtAbis();
@@ -487,6 +501,8 @@ bool BaseQtVersion::equals(BaseQtVersion *other)
return false;
if (displayName() != other->displayName())
return false;
+ if (isValid() != other->isValid())
+ return false;
return true;
}
@@ -535,9 +551,9 @@ QString BaseQtVersion::toHtml(bool verbose) const
} else {
str << "<tr><td><b>" << QCoreApplication::translate("BaseQtVersion", "ABI:")
<< "</b></td>";
- const QList<ProjectExplorer::Abi> abis = qtAbis();
+ const QList<Abi> abis = qtAbis();
if (abis.isEmpty()) {
- str << "<td>" << ProjectExplorer::Abi().toString() << "</td></tr>";
+ str << "<td>" << Abi().toString() << "</td></tr>";
} else {
for (int i = 0; i < abis.size(); ++i) {
if (i)
@@ -606,25 +622,7 @@ void BaseQtVersion::updateSourcePath() const
if (!m_sourcePath.isEmpty())
return;
updateVersionInfo();
- const QString installData = qmakeProperty("QT_INSTALL_PREFIX");
- QString sourcePath = installData;
- QFile qmakeCache(installData + QLatin1String("/.qmake.cache"));
- if (qmakeCache.exists()) {
- qmakeCache.open(QIODevice::ReadOnly | QIODevice::Text);
- QTextStream stream(&qmakeCache);
- while (!stream.atEnd()) {
- QString line = stream.readLine().trimmed();
- if (line.startsWith(QLatin1String("QT_SOURCE_TREE"))) {
- sourcePath = line.split(QLatin1Char('=')).at(1).trimmed();
- if (sourcePath.startsWith(QLatin1String("$$quote("))) {
- sourcePath.remove(0, 8);
- sourcePath.chop(1);
- }
- break;
- }
- }
- }
- m_sourcePath = FileName::fromUserInput(sourcePath);
+ m_sourcePath = sourcePath(m_versionInfo);
}
FileName BaseQtVersion::sourcePath() const
@@ -848,9 +846,9 @@ FileName BaseQtVersion::mkspec() const
return m_mkspec;
}
-FileName BaseQtVersion::mkspecFor(ProjectExplorer::ToolChain *tc) const
+FileName BaseQtVersion::mkspecFor(ToolChain *tc) const
{
- Utils::FileName versionSpec = mkspec();
+ FileName versionSpec = mkspec();
if (!tc)
return versionSpec;
@@ -1052,15 +1050,15 @@ QString BaseQtVersion::examplesPath() const
return qmakeProperty("QT_INSTALL_EXAMPLES");
}
-QList<ProjectExplorer::HeaderPath> BaseQtVersion::systemHeaderPathes(const ProjectExplorer::Kit *k) const
+QList<HeaderPath> BaseQtVersion::systemHeaderPathes(const Kit *k) const
{
Q_UNUSED(k);
- QList<ProjectExplorer::HeaderPath> result;
- result.append(ProjectExplorer::HeaderPath(mkspecPath().toString(), ProjectExplorer::HeaderPath::GlobalHeaderPath));
+ QList<HeaderPath> result;
+ result.append(HeaderPath(mkspecPath().toString(), HeaderPath::GlobalHeaderPath));
return result;
}
-void BaseQtVersion::addToEnvironment(const ProjectExplorer::Kit *k, Environment &env) const
+void BaseQtVersion::addToEnvironment(const Kit *k, Environment &env) const
{
Q_UNUSED(k);
env.set(QLatin1String("QTDIR"), QDir::toNativeSeparators(qmakeProperty("QT_HOST_DATA")));
@@ -1072,9 +1070,9 @@ void BaseQtVersion::addToEnvironment(const ProjectExplorer::Kit *k, Environment
// 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
+Environment BaseQtVersion::qmakeRunEnvironment() const
{
- return Utils::Environment::systemEnvironment();
+ return Environment::systemEnvironment();
}
bool BaseQtVersion::hasGdbDebuggingHelper() const
@@ -1131,8 +1129,7 @@ Environment BaseQtVersion::qmlToolsEnvironment() const
// add preferred tool chain, as that is how the tools are built, compare QtVersion::buildDebuggingHelperLibrary
if (!qtAbis().isEmpty()) {
- QList<ProjectExplorer::ToolChain *> alltc =
- ProjectExplorer::ToolChainManager::instance()->findToolChains(qtAbis().at(0));
+ QList<ToolChain *> alltc = ToolChainManager::findToolChains(qtAbis().at(0));
if (!alltc.isEmpty())
alltc.first()->addToEnvironment(environment);
}
@@ -1199,9 +1196,9 @@ bool BaseQtVersion::supportsShadowBuilds() const
return true;
}
-QList<ProjectExplorer::Task> BaseQtVersion::reportIssuesImpl(const QString &proFile, const QString &buildDir) const
+QList<Task> BaseQtVersion::reportIssuesImpl(const QString &proFile, const QString &buildDir) const
{
- QList<ProjectExplorer::Task> results;
+ QList<Task> results;
QString tmpBuildDir = QDir(buildDir).absolutePath();
if (!tmpBuildDir.endsWith(QLatin1Char('/')))
@@ -1210,8 +1207,8 @@ 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, FileName(), -1,
- Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM)));
+ results.append(Task(Task::Error, msg, FileName(), -1,
+ ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM));
}
QFileInfo qmakeInfo = qmakeCommand().toFileInfo();
@@ -1220,8 +1217,8 @@ 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, FileName(), -1,
- Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM)));
+ results.append(Task(Task::Error, msg, FileName(), -1,
+ ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM));
}
QString sourcePath = QFileInfo(proFile).absolutePath();
@@ -1231,23 +1228,22 @@ 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, FileName(), -1,
- Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM)));
+ results.append(Task(Task::Warning, msg, FileName(), -1,
+ 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, FileName(), -1,
- Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM)));
+ results.append(Task(Task::Warning, msg, FileName(), -1,
+ ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM));
}
return results;
}
-QList<ProjectExplorer::Task>
-BaseQtVersion::reportIssues(const QString &proFile, const QString &buildDir) const
+QList<Task> BaseQtVersion::reportIssues(const QString &proFile, const QString &buildDir) const
{
- QList<ProjectExplorer::Task> results = reportIssuesImpl(proFile, buildDir);
+ QList<Task> results = reportIssuesImpl(proFile, buildDir);
qSort(results);
return results;
}
@@ -1308,9 +1304,9 @@ bool BaseQtVersion::queryQMakeVariables(const FileName &binary, const Environmen
// Try running qmake with all kinds of tool chains set up in the environment.
// This is required to make non-static qmakes work on windows where every tool chain
// tries to be incompatible with any other.
- QList<ProjectExplorer::Abi> abiList = ProjectExplorer::Abi::abisOfBinary(binary);
- QList<ProjectExplorer::ToolChain *> tcList = ProjectExplorer::ToolChainManager::instance()->toolChains();
- foreach (ProjectExplorer::ToolChain *tc, tcList) {
+ QList<Abi> abiList = Abi::abisOfBinary(binary);
+ QList<ToolChain *> tcList = ToolChainManager::toolChains();
+ foreach (ToolChain *tc, tcList) {
if (!abiList.contains(tc->targetAbi()))
continue;
Environment realEnv = env;
@@ -1434,7 +1430,30 @@ FileName BaseQtVersion::mkspecFromVersionInfo(const QHash<QString, QString> &ver
return mkspecFullPath;
}
-bool BaseQtVersion::isQmlDebuggingSupported(ProjectExplorer::Kit *k, QString *reason)
+FileName BaseQtVersion::sourcePath(const QHash<QString, QString> &versionInfo)
+{
+ const QString installData = qmakeProperty(versionInfo, "QT_INSTALL_PREFIX");
+ QString sourcePath = installData;
+ QFile qmakeCache(installData + QLatin1String("/.qmake.cache"));
+ if (qmakeCache.exists()) {
+ qmakeCache.open(QIODevice::ReadOnly | QIODevice::Text);
+ QTextStream stream(&qmakeCache);
+ while (!stream.atEnd()) {
+ QString line = stream.readLine().trimmed();
+ if (line.startsWith(QLatin1String("QT_SOURCE_TREE"))) {
+ sourcePath = line.split(QLatin1Char('=')).at(1).trimmed();
+ if (sourcePath.startsWith(QLatin1String("$$quote("))) {
+ sourcePath.remove(0, 8);
+ sourcePath.chop(1);
+ }
+ break;
+ }
+ }
+ }
+ return FileName::fromUserInput(sourcePath);
+}
+
+bool BaseQtVersion::isQmlDebuggingSupported(Kit *k, QString *reason)
{
QTC_ASSERT(k, return false);
BaseQtVersion *version = QtKitInformation::qtVersion(k);
@@ -1452,8 +1471,8 @@ bool BaseQtVersion::isQmlDebuggingSupported(QString *reason) const
return true;
if (!qtAbis().isEmpty()) {
- ProjectExplorer::Abi abi = qtAbis().first();
- if (abi.osFlavor() == ProjectExplorer::Abi::MaemoLinuxFlavor) {
+ Abi abi = qtAbis().first();
+ if (abi.osFlavor() == Abi::MaemoLinuxFlavor) {
if (reason)
reason->clear();
// *reason = QCoreApplication::translate("BaseQtVersion", "Qml debugging on device not yet supported.");
@@ -1479,17 +1498,17 @@ bool BaseQtVersion::isQmlDebuggingSupported(QString *reason) const
return false;
}
-void BaseQtVersion::buildDebuggingHelper(ProjectExplorer::Kit *k, int tools)
+void BaseQtVersion::buildDebuggingHelper(Kit *k, int tools)
{
BaseQtVersion *version = QtKitInformation::qtVersion(k);
- ProjectExplorer::ToolChain *tc = ProjectExplorer::ToolChainKitInformation::toolChain(k);
+ ToolChain *tc = ToolChainKitInformation::toolChain(k);
if (!k || !version || !tc)
return;
version->buildDebuggingHelper(tc, tools);
}
-void BaseQtVersion::buildDebuggingHelper(ProjectExplorer::ToolChain *tc, int tools)
+void BaseQtVersion::buildDebuggingHelper(ToolChain *tc, int tools)
{
QTC_ASSERT(tc, return);
DebuggingHelperBuildTask *buildTask =
@@ -1500,8 +1519,7 @@ void BaseQtVersion::buildDebuggingHelper(ProjectExplorer::ToolChain *tc, int too
QFuture<void> task = QtConcurrent::run(&QtSupport::DebuggingHelperBuildTask::run, buildTask);
const QString taskName = QCoreApplication::translate("BaseQtVersion", "Building helpers");
- Core::ICore::progressManager()->addTask(task, taskName,
- QLatin1String("Qt::BuildHelpers"));
+ ProgressManager::addTask(task, taskName, "Qt::BuildHelpers");
}
FileName BaseQtVersion::qtCorePath(const QHash<QString,QString> &versionInfo, const QString &versionString)
@@ -1549,7 +1567,7 @@ FileName BaseQtVersion::qtCorePath(const QHash<QString,QString> &versionInfo, co
return FileName();
}
-QList<ProjectExplorer::Abi> BaseQtVersion::qtAbisFromLibrary(const FileName &coreLibrary)
+QList<Abi> BaseQtVersion::qtAbisFromLibrary(const FileName &coreLibrary)
{
- return ProjectExplorer::Abi::abisOfBinary(coreLibrary);
+ return Abi::abisOfBinary(coreLibrary);
}
diff --git a/src/plugins/qtsupport/baseqtversion.h b/src/plugins/qtsupport/baseqtversion.h
index c0d14e419a..6093488f04 100644
--- a/src/plugins/qtsupport/baseqtversion.h
+++ b/src/plugins/qtsupport/baseqtversion.h
@@ -129,7 +129,7 @@ public:
virtual Utils::Environment qmakeRunEnvironment() const;
virtual Utils::FileName sourcePath() const;
- // used by QtUiCodeModelSupport
+ // used by UiCodeModelSupport
virtual QString uicCommand() const;
virtual QString designerCommand() const;
virtual QString linguistCommand() const;
@@ -185,6 +185,7 @@ public:
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);
+ static Utils::FileName sourcePath(const QHash<QString, QString> &versionInfo);
static bool isQmlDebuggingSupported(ProjectExplorer::Kit *k, QString *reason = 0);
bool isQmlDebuggingSupported(QString *reason = 0) const;
@@ -223,6 +224,7 @@ public:
Utils::FileName headerPath() const;
Utils::FileName docsPath() const;
Utils::FileName libraryPath() const;
+ Utils::FileName pluginPath() const;
Utils::FileName binPath() const;
Utils::FileName mkspecsPath() const;
diff --git a/src/plugins/qtsupport/debugginghelper.cpp b/src/plugins/qtsupport/debugginghelper.cpp
index 3c0bebbbce..442b59cf88 100644
--- a/src/plugins/qtsupport/debugginghelper.cpp
+++ b/src/plugins/qtsupport/debugginghelper.cpp
@@ -61,7 +61,7 @@ QStringList DebuggingHelperLibrary::debuggingHelperLibraryDirectories(const QStr
static QString sourcePath()
{
- return Core::ICore::resourcePath() + QLatin1String("/dumper/");
+ return Core::ICore::resourcePath() + QLatin1String("/debugger/");
}
static QStringList sourceFileNames()
diff --git a/src/plugins/qtsupport/debugginghelperbuildtask.cpp b/src/plugins/qtsupport/debugginghelperbuildtask.cpp
index 5a53d2b3f5..9886945f7e 100644
--- a/src/plugins/qtsupport/debugginghelperbuildtask.cpp
+++ b/src/plugins/qtsupport/debugginghelperbuildtask.cpp
@@ -59,7 +59,7 @@ DebuggingHelperBuildTask::DebuggingHelperBuildTask(const BaseQtVersion *version,
// Print result in application ouptut
connect(this, SIGNAL(logOutput(QString,Core::MessageManager::PrintToOutputPaneFlags)),
- Core::MessageManager::instance(), SLOT(printToOutputPane(QString,Core::MessageManager::PrintToOutputPaneFlags)),
+ Core::MessageManager::instance(), SLOT(write(QString,Core::MessageManager::PrintToOutputPaneFlags)),
Qt::QueuedConnection);
//
@@ -101,9 +101,8 @@ DebuggingHelperBuildTask::DebuggingHelperBuildTask(const BaseQtVersion *version,
// explicitly set 32 or 64 bit in case Qt is compiled with both
if (toolChain->targetAbi().wordWidth() == 32)
m_qmakeArguments << QLatin1String("CONFIG+=x86");
- else if (toolChain->targetAbi().wordWidth() == 64) {
+ else if (toolChain->targetAbi().wordWidth() == 64)
m_qmakeArguments << QLatin1String("CONFIG+=x86_64");
- }
}
m_makeCommand = toolChain->makeCommand(m_environment);
m_mkspec = version->mkspec();
diff --git a/src/plugins/qtsupport/exampleslistmodel.cpp b/src/plugins/qtsupport/exampleslistmodel.cpp
index cdd79af3b8..6eda6cab25 100644
--- a/src/plugins/qtsupport/exampleslistmodel.cpp
+++ b/src/plugins/qtsupport/exampleslistmodel.cpp
@@ -79,8 +79,7 @@ public:
int findHighestQtVersion()
{
- QtVersionManager *versionManager = QtVersionManager::instance();
- QList <BaseQtVersion *> qtVersions = versionManager->validVersions();
+ QList<BaseQtVersion *> qtVersions = QtVersionManager::validVersions();
BaseQtVersion *newVersion = 0;
@@ -115,9 +114,8 @@ public:
clear();
// prioritize default qt version
- QtVersionManager *versionManager = QtVersionManager::instance();
- QList <BaseQtVersion *> qtVersions = versionManager->validVersions();
- ProjectExplorer::Kit *defaultKit = ProjectExplorer::KitManager::instance()->defaultKit();
+ QList<BaseQtVersion *> qtVersions = QtVersionManager::validVersions();
+ ProjectExplorer::Kit *defaultKit = ProjectExplorer::KitManager::defaultKit();
BaseQtVersion *defaultVersion = QtKitInformation::qtVersion(defaultKit);
if (defaultVersion && qtVersions.contains(defaultVersion))
qtVersions.move(qtVersions.indexOf(defaultVersion), 0);
@@ -542,9 +540,8 @@ QStringList ExamplesListModel::exampleSources(QString *examplesInstallPath, QStr
const QStringList pattern(QLatin1String("*.xml"));
// prioritize default qt version
- QtVersionManager *versionManager = QtVersionManager::instance();
- QList <BaseQtVersion *> qtVersions = versionManager->validVersions();
- ProjectExplorer::Kit *defaultKit = ProjectExplorer::KitManager::instance()->defaultKit();
+ QList<BaseQtVersion *> qtVersions = QtVersionManager::validVersions();
+ ProjectExplorer::Kit *defaultKit = ProjectExplorer::KitManager::defaultKit();
BaseQtVersion *defaultVersion = QtKitInformation::qtVersion(defaultKit);
if (defaultVersion && qtVersions.contains(defaultVersion))
qtVersions.move(qtVersions.indexOf(defaultVersion), 0);
diff --git a/src/plugins/qtsupport/gettingstartedwelcomepage.cpp b/src/plugins/qtsupport/gettingstartedwelcomepage.cpp
index 0ad1763da3..71286c838e 100644
--- a/src/plugins/qtsupport/gettingstartedwelcomepage.cpp
+++ b/src/plugins/qtsupport/gettingstartedwelcomepage.cpp
@@ -61,9 +61,9 @@
#include <QPushButton>
#include <QMessageBox>
#include <QApplication>
-#include <QDeclarativeImageProvider>
-#include <QDeclarativeEngine>
-#include <QDeclarativeContext>
+#include <QQuickImageProvider>
+#include <QQmlEngine>
+#include <QQmlContext>
#include <QDesktopServices>
using namespace Utils;
@@ -71,6 +71,17 @@ using namespace Utils;
namespace QtSupport {
namespace Internal {
+class ExampleDialog : public QDialog
+{
+ Q_OBJECT
+ public:
+ enum ResultCode { Copy = QDialog::Accepted + 1, Keep };
+ ExampleDialog(QWidget *parent = 0) : QDialog(parent) {};
+ private slots:
+ void handleCopyClicked() { done(Copy); };
+ void handleKeepClicked() { done(Keep); };
+};
+
const char C_FALLBACK_ROOT[] = "ProjectsFallbackRoot";
QPointer<ExamplesListModel> &examplesModelStatic()
@@ -137,7 +148,7 @@ public slots:
if (Core::HelpManager::instance()) {
QMutexLocker dataLock(&m_dataMutex);
- m_fetchedData = Core::HelpManager::instance()->fileData(url);
+ m_fetchedData = Core::HelpManager::fileData(url);
}
m_waitcondition.wakeAll();
}
@@ -159,11 +170,11 @@ public:
bool m_shutdown;
};
-class HelpImageProvider : public QDeclarativeImageProvider
+class HelpImageProvider : public QQuickImageProvider
{
public:
HelpImageProvider()
- : QDeclarativeImageProvider(QDeclarativeImageProvider::Image)
+ : QQuickImageProvider(QQuickImageProvider::Image)
{
}
@@ -220,7 +231,7 @@ int GettingStartedWelcomePage::priority() const
return 4;
}
-void GettingStartedWelcomePage::facilitateQml(QDeclarativeEngine *engine)
+void GettingStartedWelcomePage::facilitateQml(QQmlEngine *engine)
{
m_engine = engine;
}
@@ -277,7 +288,7 @@ QUrl ExamplesWelcomePage::pageLocation() const
return QUrl::fromLocalFile(resourcePath + QLatin1String("/welcomescreen/tutorials.qml"));
}
-void ExamplesWelcomePage::facilitateQml(QDeclarativeEngine *engine)
+void ExamplesWelcomePage::facilitateQml(QQmlEngine *engine)
{
m_engine = engine;
m_engine->addImageProvider(QLatin1String("helpimage"), new HelpImageProvider);
@@ -288,7 +299,7 @@ void ExamplesWelcomePage::facilitateQml(QDeclarativeEngine *engine)
proxy->sort(0);
proxy->setFilterCaseSensitivity(Qt::CaseInsensitive);
- QDeclarativeContext *rootContenxt = m_engine->rootContext();
+ QQmlContext *rootContenxt = m_engine->rootContext();
if (m_showExamples) {
proxy->setShowTutorialsOnly(false);
rootContenxt->setContextProperty(QLatin1String("examplesModel"), proxy);
@@ -306,12 +317,12 @@ ExamplesWelcomePage::Id ExamplesWelcomePage::id() const
void ExamplesWelcomePage::openSplitHelp(const QUrl &help)
{
- Core::ICore::helpManager()->handleHelpRequest(help.toString()+QLatin1String("?view=split"));
+ Core::HelpManager::handleHelpRequest(help.toString()+QLatin1String("?view=split"));
}
void ExamplesWelcomePage::openHelp(const QUrl &help)
{
- Core::ICore::helpManager()->handleHelpRequest(help.toString());
+ Core::HelpManager::handleHelpRequest(help.toString());
}
void ExamplesWelcomePage::openUrl(const QUrl &url)
@@ -327,7 +338,7 @@ QStringList ExamplesWelcomePage::tagList() const
QString ExamplesWelcomePage::copyToAlternativeLocation(const QFileInfo& proFileInfo, QStringList &filesToOpen, const QStringList& dependencies)
{
const QString projectDir = proFileInfo.canonicalPath();
- QDialog d(Core::ICore::mainWindow());
+ ExampleDialog d(Core::ICore::mainWindow());
QGridLayout *lay = new QGridLayout(&d);
QLabel *descrLbl = new QLabel;
d.setWindowTitle(tr("Copy Project to writable Location?"));
@@ -355,14 +366,15 @@ QString ExamplesWelcomePage::copyToAlternativeLocation(const QFileInfo& proFileI
lay->addWidget(txt, 1, 0);
lay->addWidget(chooser, 1, 1);
QDialogButtonBox *bb = new QDialogButtonBox;
- connect(bb, SIGNAL(accepted()), &d, SLOT(accept()));
- connect(bb, SIGNAL(rejected()), &d, SLOT(reject()));
QPushButton *copyBtn = bb->addButton(tr("&Copy Project and Open"), QDialogButtonBox::AcceptRole);
+ connect(copyBtn, SIGNAL(released()), &d, SLOT(handleCopyClicked()));
copyBtn->setDefault(true);
- bb->addButton(tr("&Keep Project and Open"), QDialogButtonBox::RejectRole);
+ QPushButton *keepBtn = bb->addButton(tr("&Keep Project and Open"), QDialogButtonBox::RejectRole);
+ connect(keepBtn, SIGNAL(released()), &d, SLOT(handleKeepClicked()));
lay->addWidget(bb, 2, 0, 1, 2);
connect(chooser, SIGNAL(validChanged(bool)), copyBtn, SLOT(setEnabled(bool)));
- if (d.exec() == QDialog::Accepted) {
+ int code = d.exec();
+ if (code == ExampleDialog::Copy) {
QString exampleDirName = proFileInfo.dir().dirName();
QString destBaseDir = chooser->path();
settings->setValue(QString::fromLatin1(C_FALLBACK_ROOT), destBaseDir);
@@ -402,6 +414,8 @@ QString ExamplesWelcomePage::copyToAlternativeLocation(const QFileInfo& proFileI
}
}
+ if (code == ExampleDialog::Keep)
+ return proFileInfo.absoluteFilePath();
return QString();
}
@@ -433,7 +447,7 @@ void ExamplesWelcomePage::openProject(const QString &projectFile, const QStringL
project->configureAsExampleProject(platforms);
Core::ModeManager::activateMode(Core::Constants::MODE_EDIT);
if (help.isValid())
- Core::ICore::helpManager()->handleHelpRequest(help.toString() + QLatin1String("?view=split"));
+ Core::HelpManager::handleHelpRequest(help.toString() + QLatin1String("?view=split"));
}
if (!errorMessage.isEmpty())
QMessageBox::critical(Core::ICore::mainWindow(), tr("Failed to Open Project"), errorMessage);
diff --git a/src/plugins/qtsupport/gettingstartedwelcomepage.h b/src/plugins/qtsupport/gettingstartedwelcomepage.h
index b35a4cd6d5..515cac9b5d 100644
--- a/src/plugins/qtsupport/gettingstartedwelcomepage.h
+++ b/src/plugins/qtsupport/gettingstartedwelcomepage.h
@@ -35,7 +35,7 @@
#include <QStringList>
QT_BEGIN_NAMESPACE
-class QDeclarativeEngine;
+class QQmlEngine;
class QFileInfo;
QT_END_NAMESPACE
@@ -54,11 +54,11 @@ public:
QUrl pageLocation() const;
QString title() const;
int priority() const;
- void facilitateQml(QDeclarativeEngine *);
+ void facilitateQml(QQmlEngine *);
Id id() const;
private:
- QDeclarativeEngine *m_engine;
+ QQmlEngine *m_engine;
};
@@ -74,7 +74,7 @@ public:
QString title() const;
int priority() const;
bool hasSearchBar() const;
- void facilitateQml(QDeclarativeEngine *);
+ void facilitateQml(QQmlEngine *);
Id id() const;
Q_INVOKABLE QStringList tagList() const;
Q_INVOKABLE void openUrl(const QUrl &url);
@@ -92,7 +92,7 @@ public slots:
private:
ExamplesListModel *examplesModel() const;
QString copyToAlternativeLocation(const QFileInfo &fileInfo, QStringList &filesToOpen, const QStringList &dependencies);
- QDeclarativeEngine *m_engine;
+ QQmlEngine *m_engine;
bool m_showExamples;
};
diff --git a/src/plugins/qtsupport/profilereader.cpp b/src/plugins/qtsupport/profilereader.cpp
index 747c4f14ff..02646a9de9 100644
--- a/src/plugins/qtsupport/profilereader.cpp
+++ b/src/plugins/qtsupport/profilereader.cpp
@@ -49,7 +49,7 @@ ProMessageHandler::ProMessageHandler(bool verbose)
: m_verbose(verbose)
{
QObject::connect(this, SIGNAL(errorFound(QString,Core::MessageManager::PrintToOutputPaneFlags)),
- Core::ICore::messageManager(), SLOT(printToOutputPane(QString,Core::MessageManager::PrintToOutputPaneFlags)),
+ Core::MessageManager::instance(), SLOT(write(QString,Core::MessageManager::PrintToOutputPaneFlags)),
Qt::QueuedConnection);
}
diff --git a/src/plugins/qtsupport/profilereader.h b/src/plugins/qtsupport/profilereader.h
index 3bd8a914b8..d2d5367a16 100644
--- a/src/plugins/qtsupport/profilereader.h
+++ b/src/plugins/qtsupport/profilereader.h
@@ -31,9 +31,9 @@
#define PROFILEREADER_H
#include "qtsupport_global.h"
-#include "proparser/profileevaluator.h"
#include <coreplugin/messagemanager.h>
+#include <proparser/profileevaluator.h>
#include <QObject>
#include <QMap>
diff --git a/src/plugins/qtsupport/qmldumptool.cpp b/src/plugins/qtsupport/qmldumptool.cpp
index 78db436fde..5edc01b33a 100644
--- a/src/plugins/qtsupport/qmldumptool.cpp
+++ b/src/plugins/qtsupport/qmldumptool.cpp
@@ -49,8 +49,7 @@
namespace {
using namespace QtSupport;
-using QtSupport::DebuggingHelperBuildTask;
-using ProjectExplorer::ToolChain;
+using namespace ProjectExplorer;
class QmlDumpBuildTask;
@@ -81,7 +80,7 @@ public:
m_buildTask->run(future);
}
- void updateProjectWhenDone(QPointer<ProjectExplorer::Project> project, bool preferDebug)
+ void updateProjectWhenDone(QPointer<Project> project, bool preferDebug)
{
foreach (const ProjectToUpdate &update, m_projectsToUpdate) {
if (update.project == project)
@@ -102,7 +101,7 @@ public:
private slots:
void finish(int qtId, const QString &output, DebuggingHelperBuildTask::Tools tools)
{
- BaseQtVersion *version = QtVersionManager::instance()->version(qtId);
+ BaseQtVersion *version = QtVersionManager::version(qtId);
QTC_ASSERT(tools == DebuggingHelperBuildTask::QmlDump, return);
QString errorMessage;
@@ -146,7 +145,7 @@ private slots:
private:
class ProjectToUpdate {
public:
- QPointer<ProjectExplorer::Project> project;
+ QPointer<Project> project;
bool preferDebug;
};
@@ -313,8 +312,8 @@ QStringList QmlDumpTool::installDirectories(const QString &qtInstallData)
return directories;
}
-void QmlDumpTool::pathAndEnvironment(ProjectExplorer::Project *project, BaseQtVersion *version,
- ProjectExplorer::ToolChain *toolChain,
+void QmlDumpTool::pathAndEnvironment(Project *project, BaseQtVersion *version,
+ ToolChain *toolChain,
bool preferDebug, QString *dumperPath, Utils::Environment *env)
{
QString path;
@@ -328,8 +327,7 @@ void QmlDumpTool::pathAndEnvironment(ProjectExplorer::Project *project, BaseQtVe
buildTask->updateProjectWhenDone(project, preferDebug);
QFuture<void> task = QtConcurrent::run(&QmlDumpBuildTask::run, buildTask);
const QString taskName = QmlDumpBuildTask::tr("Building helper");
- Core::ICore::progressManager()->addTask(task, taskName,
- QLatin1String("Qt4ProjectManager::BuildHelpers"));
+ Core::ProgressManager::addTask(task, taskName, "Qt4ProjectManager::BuildHelpers");
}
return;
}
diff --git a/src/plugins/qtsupport/qtkitconfigwidget.cpp b/src/plugins/qtsupport/qtkitconfigwidget.cpp
index ca6013f68e..d38d8c0bf9 100644
--- a/src/plugins/qtsupport/qtkitconfigwidget.cpp
+++ b/src/plugins/qtsupport/qtkitconfigwidget.cpp
@@ -44,30 +44,36 @@
namespace QtSupport {
namespace Internal {
-QtKitConfigWidget::QtKitConfigWidget(ProjectExplorer::Kit *k, bool sticky) :
- KitConfigWidget(k, sticky)
+QtKitConfigWidget::QtKitConfigWidget(ProjectExplorer::Kit *k, const ProjectExplorer::KitInformation *ki) :
+ KitConfigWidget(k, ki)
{
m_combo = new QComboBox;
m_combo->addItem(tr("None"), -1);
- QtVersionManager *mgr = QtVersionManager::instance();
- QList<BaseQtVersion *> versions = mgr->validVersions();
QList<int> versionIds;
- foreach (BaseQtVersion *v, versions)
+ foreach (BaseQtVersion *v, QtVersionManager::versions())
versionIds.append(v->uniqueId());
versionsChanged(versionIds, QList<int>(), QList<int>());
m_manageButton = new QPushButton(tr("Manage..."));
refresh();
+ m_combo->setToolTip(toolTip());
+
connect(m_combo, SIGNAL(currentIndexChanged(int)), this, SLOT(currentWasChanged(int)));
- connect(mgr, SIGNAL(qtVersionsChanged(QList<int>,QList<int>,QList<int>)),
+ connect(QtVersionManager::instance(), SIGNAL(qtVersionsChanged(QList<int>,QList<int>,QList<int>)),
this, SLOT(versionsChanged(QList<int>,QList<int>,QList<int>)));
connect(m_manageButton, SIGNAL(clicked()), this, SLOT(manageQtVersions()));
}
+QtKitConfigWidget::~QtKitConfigWidget()
+{
+ delete m_combo;
+ delete m_manageButton;
+}
+
QString QtKitConfigWidget::displayName() const
{
return tr("Qt version:");
@@ -100,28 +106,34 @@ QWidget *QtKitConfigWidget::buttonWidget() const
return m_manageButton;
}
+static QString itemNameFor(const BaseQtVersion *v)
+{
+ QTC_CHECK(v);
+ QString name = v->displayName();
+ if (!v->isValid())
+ name = QCoreApplication::translate("QtSupport::Internal::QtKitConfigWidget", "%1 (invalid)").arg(v->displayName());
+ return name;
+}
+
void QtKitConfigWidget::versionsChanged(const QList<int> &added, const QList<int> &removed,
const QList<int> &changed)
{
- QtVersionManager *mgr = QtVersionManager::instance();
-
foreach (const int id, added) {
- BaseQtVersion *v = mgr->version(id);
+ BaseQtVersion *v = QtVersionManager::version(id);
QTC_CHECK(v);
QTC_CHECK(findQtVersion(id) < 0);
- m_combo->addItem(v->displayName(), id);
+ m_combo->addItem(itemNameFor(v), id);
}
foreach (const int id, removed) {
int pos = findQtVersion(id);
- QTC_CHECK(pos >= 0);
- m_combo->removeItem(pos);
-
+ if (pos >= 0) // We do not include invalid Qt versions, so do not try to remove those.
+ m_combo->removeItem(pos);
}
foreach (const int id, changed) {
- BaseQtVersion *v = mgr->version(id);
+ BaseQtVersion *v = QtVersionManager::version(id);
int pos = findQtVersion(id);
QTC_CHECK(pos >= 0);
- m_combo->setItemText(pos, v->displayName());
+ m_combo->setItemText(pos, itemNameFor(v));
}
}
diff --git a/src/plugins/qtsupport/qtkitconfigwidget.h b/src/plugins/qtsupport/qtkitconfigwidget.h
index 9ecae415a3..2107d6d291 100644
--- a/src/plugins/qtsupport/qtkitconfigwidget.h
+++ b/src/plugins/qtsupport/qtkitconfigwidget.h
@@ -45,7 +45,8 @@ class QtKitConfigWidget : public ProjectExplorer::KitConfigWidget
Q_OBJECT
public:
- explicit QtKitConfigWidget(ProjectExplorer::Kit *k, bool sticky);
+ QtKitConfigWidget(ProjectExplorer::Kit *k, const ProjectExplorer::KitInformation *ki);
+ ~QtKitConfigWidget();
QString displayName() const;
diff --git a/src/plugins/qtsupport/qtkitinformation.cpp b/src/plugins/qtsupport/qtkitinformation.cpp
index 501cab6261..b630ec79e8 100644
--- a/src/plugins/qtsupport/qtkitinformation.cpp
+++ b/src/plugins/qtsupport/qtkitinformation.cpp
@@ -34,45 +34,32 @@
#include "qtversionmanager.h"
#include "qtparser.h"
-#include <utils/environment.h>
+#include <utils/buildablehelperlibrary.h>
#include <utils/qtcassert.h>
namespace QtSupport {
-namespace Internal {
-const char QT_INFORMATION[] = "QtSupport.QtInformation";
-} // namespace Internal
QtKitInformation::QtKitInformation()
{
setObjectName(QLatin1String("QtKitInformation"));
+ setId(QtKitInformation::id());
+ setPriority(26000);
+
connect(ProjectExplorer::KitManager::instance(), SIGNAL(kitsLoaded()),
this, SLOT(kitsWereLoaded()));
}
-Core::Id QtKitInformation::dataId() const
-{
- static Core::Id id = Core::Id(Internal::QT_INFORMATION);
- return id;
-}
-
-unsigned int QtKitInformation::priority() const
-{
- return 26000;
-}
-
QVariant QtKitInformation::defaultValue(ProjectExplorer::Kit *k) const
{
Q_UNUSED(k);
- QtVersionManager *mgr = QtVersionManager::instance();
// find "Qt in PATH":
- Utils::FileName qmake = Utils::FileName::fromString(Utils::Environment::systemEnvironment()
- .searchInPath(QLatin1String("qmake")));
+ Utils::FileName qmake = Utils::BuildableHelperLibrary::findSystemQt(Utils::Environment::systemEnvironment());
if (qmake.isEmpty())
return -1;
- QList<BaseQtVersion *> versionList = mgr->versions();
+ QList<BaseQtVersion *> versionList = QtVersionManager::versions();
BaseQtVersion *fallBack = 0;
foreach (BaseQtVersion *v, versionList) {
if (qmake == v->qmakeCommand())
@@ -89,7 +76,7 @@ QVariant QtKitInformation::defaultValue(ProjectExplorer::Kit *k) const
QList<ProjectExplorer::Task> QtKitInformation::validate(const ProjectExplorer::Kit *k) const
{
QList<ProjectExplorer::Task> result;
- QTC_ASSERT(QtVersionManager::instance()->isLoaded(), return result);
+ QTC_ASSERT(QtVersionManager::isLoaded(), return result);
BaseQtVersion *version = qtVersion(k);
if (!version)
return result;
@@ -98,7 +85,7 @@ QList<ProjectExplorer::Task> QtKitInformation::validate(const ProjectExplorer::K
void QtKitInformation::fix(ProjectExplorer::Kit *k)
{
- QTC_ASSERT(QtVersionManager::instance()->isLoaded(), return);
+ QTC_ASSERT(QtVersionManager::isLoaded(), return);
BaseQtVersion *version = qtVersion(k);
if (!version && qtVersionId(k) >= 0) {
qWarning("Qt version is no longer known, removing from kit \"%s\".", qPrintable(k->displayName()));
@@ -108,7 +95,7 @@ void QtKitInformation::fix(ProjectExplorer::Kit *k)
ProjectExplorer::KitConfigWidget *QtKitInformation::createConfigWidget(ProjectExplorer::Kit *k) const
{
- return new Internal::QtKitConfigWidget(k, isSticky(k));
+ return new Internal::QtKitConfigWidget(k, this);
}
QString QtKitInformation::displayNamePostfix(const ProjectExplorer::Kit *k) const
@@ -138,13 +125,18 @@ ProjectExplorer::IOutputParser *QtKitInformation::createOutputParser(const Proje
return 0;
}
+Core::Id QtKitInformation::id()
+{
+ return "QtSupport.QtInformation";
+}
+
int QtKitInformation::qtVersionId(const ProjectExplorer::Kit *k)
{
if (!k)
return -1;
int id = -1;
- QVariant data = k->value(Core::Id(Internal::QT_INFORMATION), -1);
+ QVariant data = k->value(QtKitInformation::id(), -1);
if (data.type() == QVariant::Int) {
bool ok;
id = data.toInt(&ok);
@@ -152,7 +144,7 @@ int QtKitInformation::qtVersionId(const ProjectExplorer::Kit *k)
id = -1;
} else {
QString source = data.toString();
- foreach (BaseQtVersion *v, QtVersionManager::instance()->versions()) {
+ foreach (BaseQtVersion *v, QtVersionManager::versions()) {
if (v->autodetectionSource() != source)
continue;
id = v->uniqueId();
@@ -164,12 +156,12 @@ int QtKitInformation::qtVersionId(const ProjectExplorer::Kit *k)
void QtKitInformation::setQtVersionId(ProjectExplorer::Kit *k, const int id)
{
- k->setValue(Core::Id(Internal::QT_INFORMATION), id);
+ k->setValue(QtKitInformation::id(), id);
}
BaseQtVersion *QtKitInformation::qtVersion(const ProjectExplorer::Kit *k)
{
- return QtVersionManager::instance()->version(qtVersionId(k));
+ return QtVersionManager::version(qtVersionId(k));
}
void QtKitInformation::setQtVersion(ProjectExplorer::Kit *k, const BaseQtVersion *v)
@@ -202,14 +194,17 @@ void QtKitInformation::qtVersionsChanged(const QList<int> &addedIds,
{
Q_UNUSED(addedIds);
Q_UNUSED(removedIds);
- foreach (ProjectExplorer::Kit *k, ProjectExplorer::KitManager::instance()->kits())
- if (changedIds.contains(qtVersionId(k)))
+ foreach (ProjectExplorer::Kit *k, ProjectExplorer::KitManager::kits()) {
+ if (changedIds.contains(qtVersionId(k))) {
+ k->validate(); // Qt version may have become (in)valid
notifyAboutUpdate(k);
+ }
+ }
}
void QtKitInformation::kitsWereLoaded()
{
- foreach (ProjectExplorer::Kit *k, ProjectExplorer::KitManager::instance()->kits())
+ foreach (ProjectExplorer::Kit *k, ProjectExplorer::KitManager::kits())
fix(k);
connect(QtVersionManager::instance(), SIGNAL(qtVersionsChanged(QList<int>,QList<int>,QList<int>)),
diff --git a/src/plugins/qtsupport/qtkitinformation.h b/src/plugins/qtsupport/qtkitinformation.h
index 8a4391a107..a8f1503b60 100644
--- a/src/plugins/qtsupport/qtkitinformation.h
+++ b/src/plugins/qtsupport/qtkitinformation.h
@@ -46,10 +46,6 @@ class QTSUPPORT_EXPORT QtKitInformation : public ProjectExplorer::KitInformation
public:
QtKitInformation();
- Core::Id dataId() const;
-
- unsigned int priority() const; // the higher the closer to the top.
-
QVariant defaultValue(ProjectExplorer::Kit *k) const;
QList<ProjectExplorer::Task> validate(const ProjectExplorer::Kit *k) const;
@@ -64,6 +60,7 @@ public:
void addToEnvironment(const ProjectExplorer::Kit *k, Utils::Environment &env) const;
ProjectExplorer::IOutputParser *createOutputParser(const ProjectExplorer::Kit *k) const;
+ static Core::Id id();
static int qtVersionId(const ProjectExplorer::Kit *k);
static void setQtVersionId(ProjectExplorer::Kit *k, const int id);
static BaseQtVersion *qtVersion(const ProjectExplorer::Kit *k);
diff --git a/src/plugins/qtsupport/qtoptionspage.cpp b/src/plugins/qtsupport/qtoptionspage.cpp
index a9e7024dfd..525fdb9864 100644
--- a/src/plugins/qtsupport/qtoptionspage.cpp
+++ b/src/plugins/qtsupport/qtoptionspage.cpp
@@ -40,13 +40,12 @@
#include "qmldebugginglibrary.h"
#include "qmlobservertool.h"
-#include <coreplugin/icore.h>
#include <coreplugin/progressmanager/progressmanager.h>
-#include <utils/qtcassert.h>
-#include <utils/pathchooser.h>
#include <projectexplorer/toolchainmanager.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <utils/hostosinfo.h>
+#include <utils/pathchooser.h>
+#include <utils/qtcassert.h>
#include <utils/runextensions.h>
#include <QDir>
@@ -55,12 +54,14 @@
#include <QTextBrowser>
#include <QDesktopServices>
-enum ModelRoles { VersionIdRole = Qt::UserRole, ToolChainIdRole, BuildLogRole, BuildRunningRole};
-
-using namespace QtSupport;
-using namespace QtSupport::Internal;
+using namespace ProjectExplorer;
using namespace Utils;
+namespace QtSupport {
+namespace Internal {
+
+enum ModelRoles { VersionIdRole = Qt::UserRole, ToolChainIdRole, BuildLogRole, BuildRunningRole};
+
///
// QtOptionsPage
///
@@ -116,7 +117,7 @@ QtOptionsPageWidget::QtOptionsPageWidget(QWidget *parent)
{
QWidget *versionInfoWidget = new QWidget();
m_versionUi->setupUi(versionInfoWidget);
- m_versionUi->editPathPushButton->setText(QCoreApplication::translate("Utils::PathChooser", Utils::PathChooser::browseButtonLabel));
+ m_versionUi->editPathPushButton->setText(QCoreApplication::translate("Utils::PathChooser", PathChooser::browseButtonLabel));
QWidget *debuggingHelperDetailsWidget = new QWidget();
m_debuggingHelperUi->setupUi(debuggingHelperDetailsWidget);
@@ -131,7 +132,7 @@ QtOptionsPageWidget::QtOptionsPageWidget(QWidget *parent)
this, SLOT(setInfoWidgetVisibility()));
m_ui->versionInfoWidget->setWidget(versionInfoWidget);
- m_ui->versionInfoWidget->setState(Utils::DetailsWidget::NoSummary);
+ m_ui->versionInfoWidget->setState(DetailsWidget::NoSummary);
m_ui->debuggingHelperWidget->setWidget(debuggingHelperDetailsWidget);
connect(m_ui->debuggingHelperWidget, SIGNAL(expanded(bool)),
@@ -151,8 +152,7 @@ QtOptionsPageWidget::QtOptionsPageWidget(QWidget *parent)
m_manualItem->setFlags(Qt::ItemIsEnabled);
QList<int> additions;
- QList<BaseQtVersion *> versions = QtVersionManager::instance()->versions();
- foreach (BaseQtVersion *v, versions)
+ foreach (BaseQtVersion *v, QtVersionManager::versions())
additions.append(v->uniqueId());
updateQtVersions(additions, QList<int>(), QList<int>());
@@ -319,7 +319,7 @@ void QtOptionsPageWidget::selectedToolChainChanged(int comboIndex)
item->setData(0, ToolChainIdRole, toolChainId);
}
-void QtOptionsPageWidget::qtVersionsDumpUpdated(const Utils::FileName &qmakeCommand)
+void QtOptionsPageWidget::qtVersionsDumpUpdated(const FileName &qmakeCommand)
{
foreach (BaseQtVersion *version, m_versions) {
if (version->qmakeCommand() == qmakeCommand)
@@ -364,9 +364,9 @@ QtOptionsPageWidget::ValidityInfo QtOptionsPageWidget::validInformation(const Ba
// Do we have tool chain issues?
QStringList missingToolChains;
int abiCount = 0;
- foreach (const ProjectExplorer::Abi &a, version->qtAbis()) {
- if (ProjectExplorer::ToolChainManager::instance()->findToolChains(a).isEmpty())
- missingToolChains.append(a.toString());
+ foreach (const Abi &abi, version->qtAbis()) {
+ if (ToolChainManager::findToolChains(abi).isEmpty())
+ missingToolChains.append(abi.toString());
++abiCount;
}
@@ -398,25 +398,22 @@ QtOptionsPageWidget::ValidityInfo QtOptionsPageWidget::validInformation(const Ba
return info;
}
-QList<ProjectExplorer::ToolChain*> QtOptionsPageWidget::toolChains(const BaseQtVersion *version)
+QList<ToolChain*> QtOptionsPageWidget::toolChains(const BaseQtVersion *version)
{
- QHash<QString,ProjectExplorer::ToolChain*> toolChains;
+ QHash<QString,ToolChain*> toolChains;
if (!version)
return toolChains.values();
- foreach (const ProjectExplorer::Abi &a, version->qtAbis()) {
- foreach (ProjectExplorer::ToolChain *tc,
- ProjectExplorer::ToolChainManager::instance()->findToolChains(a)) {
+ foreach (const Abi &a, version->qtAbis())
+ foreach (ToolChain *tc, ToolChainManager::findToolChains(a))
toolChains.insert(tc->id(), tc);
- }
- }
return toolChains.values();
}
QString QtOptionsPageWidget::defaultToolChainId(const BaseQtVersion *version)
{
- QList<ProjectExplorer::ToolChain*> possibleToolChains = toolChains(version);
+ QList<ToolChain*> possibleToolChains = toolChains(version);
if (!possibleToolChains.isEmpty())
return possibleToolChains.first()->id();
return QString();
@@ -448,8 +445,7 @@ void QtOptionsPageWidget::buildDebuggingHelper(DebuggingHelperBuildTask::Tools t
// Run a debugging helper build task in the background.
QString toolChainId = m_debuggingHelperUi->toolChainComboBox->itemData(
m_debuggingHelperUi->toolChainComboBox->currentIndex()).toString();
- ProjectExplorer::ToolChainManager *tcMgr = ProjectExplorer::ToolChainManager::instance();
- ProjectExplorer::ToolChain *toolChain = tcMgr->findToolChain(toolChainId);
+ ToolChain *toolChain = ToolChainManager::findToolChain(toolChainId);
if (!toolChain)
return;
@@ -462,8 +458,7 @@ void QtOptionsPageWidget::buildDebuggingHelper(DebuggingHelperBuildTask::Tools t
QFuture<void> task = QtConcurrent::run(&DebuggingHelperBuildTask::run, buildTask);
const QString taskName = tr("Building helpers");
- Core::ICore::progressManager()->addTask(task, taskName,
- QLatin1String("Qt4ProjectManager::BuildHelpers"));
+ Core::ProgressManager::addTask(task, taskName, "Qt4ProjectManager::BuildHelpers");
}
void QtOptionsPageWidget::buildGdbHelper()
{
@@ -531,8 +526,6 @@ void QtOptionsPageWidget::showDebuggingBuildLog(const QTreeWidgetItem *currentIt
void QtOptionsPageWidget::updateQtVersions(const QList<int> &additions, const QList<int> &removals,
const QList<int> &changes)
{
- QtVersionManager *vm = QtVersionManager::instance();
-
QList<QTreeWidgetItem *> toRemove;
QList<int> toAdd = additions;
@@ -568,7 +561,7 @@ void QtOptionsPageWidget::updateQtVersions(const QList<int> &additions, const QL
// Add changed/added items:
foreach (int a, toAdd) {
- BaseQtVersion *version = vm->version(a)->clone();
+ BaseQtVersion *version = QtVersionManager::version(a)->clone();
m_versions.append(version);
QTreeWidgetItem *item = new QTreeWidgetItem;
@@ -607,15 +600,15 @@ QtOptionsPageWidget::~QtOptionsPageWidget()
static QString filterForQmakeFileDialog()
{
QString filter = QLatin1String("qmake (");
- const QStringList commands = Utils::BuildableHelperLibrary::possibleQMakeCommands();
+ const QStringList commands = BuildableHelperLibrary::possibleQMakeCommands();
for (int i = 0; i < commands.size(); ++i) {
if (i)
filter += QLatin1Char(' ');
- if (Utils::HostOsInfo::isMacHost())
+ if (HostOsInfo::isMacHost())
// work around QTBUG-7739 that prohibits filters that don't start with *
filter += QLatin1Char('*');
filter += commands.at(i);
- if (Utils::HostOsInfo::isAnyUnixHost() && !Utils::HostOsInfo::isMacHost())
+ if (HostOsInfo::isAnyUnixHost() && !HostOsInfo::isMacHost())
// kde bug, we need at least one wildcard character
// see QTCREATORBUG-7771
filter += QLatin1Char('*');
@@ -626,7 +619,7 @@ static QString filterForQmakeFileDialog()
void QtOptionsPageWidget::addQtDir()
{
- Utils::FileName qtVersion = Utils::FileName::fromString(
+ FileName qtVersion = FileName::fromString(
QFileDialog::getOpenFileName(this,
tr("Select a qmake Executable"),
QString(),
@@ -635,6 +628,12 @@ void QtOptionsPageWidget::addQtDir()
QFileDialog::DontResolveSymlinks));
if (qtVersion.isNull())
return;
+
+ QFileInfo fi(qtVersion.toString());
+ // should add all qt versions here ?
+ if (BuildableHelperLibrary::isQtChooser(fi))
+ qtVersion = FileName::fromString(BuildableHelperLibrary::qtChooserToQmakePath(fi.symLinkTarget()));
+
BaseQtVersion *version = 0;
foreach (BaseQtVersion *v, m_versions) {
if (v->qmakeCommand() == qtVersion) {
@@ -691,7 +690,7 @@ void QtOptionsPageWidget::editPath()
{
BaseQtVersion *current = currentVersion();
QString dir = currentVersion()->qmakeCommand().toFileInfo().absolutePath();
- Utils::FileName qtVersion = Utils::FileName::fromString(
+ FileName qtVersion = FileName::fromString(
QFileDialog::getOpenFileName(this,
tr("Select a qmake executable"),
dir,
@@ -734,7 +733,7 @@ void QtOptionsPageWidget::updateDebuggingHelperUi()
BaseQtVersion *version = currentVersion();
const QTreeWidgetItem *currentItem = m_ui->qtdirList->currentItem();
- QList<ProjectExplorer::ToolChain*> toolchains = toolChains(currentVersion());
+ QList<ToolChain*> toolchains = toolChains(currentVersion());
if (!version || !version->isValid() || toolchains.isEmpty()) {
m_ui->debuggingHelperWidget->setVisible(false);
@@ -884,7 +883,7 @@ void QtOptionsPageWidget::updateDebuggingHelperUi()
m_debuggingHelperUi->qmlObserverBuildButton->setEnabled(canBuildQmlObserver
& !isBuildingQmlObserver);
- QList<ProjectExplorer::ToolChain*> toolchains = toolChains(currentVersion());
+ QList<ToolChain*> toolchains = toolChains(currentVersion());
QString selectedToolChainId = currentItem->data(0, ToolChainIdRole).toString();
m_debuggingHelperUi->toolChainComboBox->clear();
for (int i = 0; i < toolchains.size(); ++i) {
@@ -1026,7 +1025,7 @@ void QtOptionsPageWidget::updateWidgets()
const bool enabled = version != 0;
const bool isAutodetected = enabled && version->isAutodetected();
m_ui->delButton->setEnabled(enabled && !isAutodetected);
- m_versionUi->nameEdit->setEnabled(enabled && !isAutodetected);
+ m_versionUi->nameEdit->setEnabled(enabled);
m_versionUi->editPathPushButton->setEnabled(enabled && !isAutodetected);
}
@@ -1054,8 +1053,7 @@ void QtOptionsPageWidget::apply()
disconnect(QtVersionManager::instance(), SIGNAL(qtVersionsChanged(QList<int>,QList<int>,QList<int>)),
this, SLOT(updateQtVersions(QList<int>,QList<int>,QList<int>)));
- QtVersionManager *vm = QtVersionManager::instance();
- vm->setNewQtVersions(versions());
+ QtVersionManager::setNewQtVersions(versions());
connect(QtVersionManager::instance(), SIGNAL(qtVersionsChanged(QList<int>,QList<int>,QList<int>)),
this, SLOT(updateQtVersions(QList<int>,QList<int>,QList<int>)));
@@ -1120,3 +1118,6 @@ QString QtOptionsPageWidget::searchKeywords() const
rc.remove(QLatin1Char('&'));
return rc;
}
+
+} // namespace Internal
+} // namespace QtSupport
diff --git a/src/plugins/qtsupport/qtparser.cpp b/src/plugins/qtsupport/qtparser.cpp
index 3e64cc4efc..42bab6995f 100644
--- a/src/plugins/qtsupport/qtparser.cpp
+++ b/src/plugins/qtsupport/qtparser.cpp
@@ -57,7 +57,7 @@ void QtParser::stdError(const QString &line)
m_mocRegExp.cap(5).trimmed(),
Utils::FileName::fromUserInput(m_mocRegExp.cap(1)) /* filename */,
lineno,
- Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_COMPILE));
+ ProjectExplorer::Constants::TASK_CATEGORY_COMPILE);
if (m_mocRegExp.cap(4).compare(QLatin1String("Warning"), Qt::CaseInsensitive) == 0)
task.type = Task::Warning;
emit addTask(task);
@@ -121,7 +121,7 @@ void QtSupportPlugin::testQtOutputParser_data()
<< (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)))
+ ProjectExplorer::Constants::TASK_CATEGORY_COMPILE))
<< QString();
QTest::newRow("moc warning")
<< QString::fromLatin1("..\\untitled\\errorfile.h:0: Warning: No relevant classes found. No output generated.")
@@ -130,7 +130,7 @@ void QtSupportPlugin::testQtOutputParser_data()
<< (QList<ProjectExplorer::Task>() << Task(Task::Warning,
QLatin1String("No relevant classes found. No output generated."),
Utils::FileName::fromUserInput(QLatin1String("..\\untitled\\errorfile.h")), 0,
- Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_COMPILE)))
+ ProjectExplorer::Constants::TASK_CATEGORY_COMPILE))
<< QString();
QTest::newRow("moc warning 2")
<< QString::fromLatin1("c:\\code\\test.h(96): Warning: Property declaration ) has no READ accessor function. The property will be invalid.")
@@ -139,7 +139,7 @@ void QtSupportPlugin::testQtOutputParser_data()
<< (QList<ProjectExplorer::Task>() << Task(Task::Warning,
QLatin1String("Property declaration ) has no READ accessor function. The property will be invalid."),
Utils::FileName::fromUserInput(QLatin1String("c:\\code\\test.h")), 96,
- Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_COMPILE)))
+ ProjectExplorer::Constants::TASK_CATEGORY_COMPILE))
<< QString();
QTest::newRow("ninja with moc")
<< QString::fromLatin1("E:/sandbox/creator/loaden/src/libs/utils/iwelcomepage.h(54): Error: Undefined interface")
@@ -148,7 +148,7 @@ void QtSupportPlugin::testQtOutputParser_data()
<< (QList<ProjectExplorer::Task>() << Task(Task::Error,
QLatin1String("Undefined interface"),
Utils::FileName::fromUserInput(QLatin1String("E:/sandbox/creator/loaden/src/libs/utils/iwelcomepage.h")), 54,
- Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_COMPILE)))
+ ProjectExplorer::Constants::TASK_CATEGORY_COMPILE))
<< QString();
}
diff --git a/src/plugins/qtsupport/qtsupport.pro b/src/plugins/qtsupport/qtsupport.pro
index 9229d5376a..af48b82a6f 100644
--- a/src/plugins/qtsupport/qtsupport.pro
+++ b/src/plugins/qtsupport/qtsupport.pro
@@ -1,5 +1,5 @@
DEFINES += QTSUPPORT_LIBRARY
-QT += network declarative
+QT += network
include(../../qtcreatorplugin.pri)
@@ -14,6 +14,7 @@ HEADERS += \
qtoutputformatter.h \
qtversionmanager.h \
qtversionfactory.h \
+ uicodemodelsupport.h \
baseqtversion.h \
qmldumptool.h \
qmlobservertool.h \
@@ -26,7 +27,6 @@ HEADERS += \
qtsupportconstants.h \
profilereader.h \
qtparser.h \
- gettingstartedwelcomepage.h \
exampleslistmodel.h \
screenshotcropper.h \
qtconfigwidget.h \
@@ -39,6 +39,7 @@ SOURCES += \
qtoutputformatter.cpp \
qtversionmanager.cpp \
qtversionfactory.cpp \
+ uicodemodelsupport.cpp \
baseqtversion.cpp \
qmldumptool.cpp \
qmlobservertool.cpp \
@@ -50,11 +51,16 @@ SOURCES += \
debugginghelperbuildtask.cpp \
profilereader.cpp \
qtparser.cpp \
- gettingstartedwelcomepage.cpp \
exampleslistmodel.cpp \
screenshotcropper.cpp \
qtconfigwidget.cpp
+greaterThan(QT_MAJOR_VERSION, 4) {
+ QT += quick
+ HEADERS += gettingstartedwelcomepage.h
+ SOURCES += gettingstartedwelcomepage.cpp
+}
+
FORMS += \
showbuildlog.ui \
qtversioninfo.ui \
diff --git a/src/plugins/qtsupport/qtsupport.qbs b/src/plugins/qtsupport/qtsupport.qbs
index b9bbe2f796..d6142bdcfc 100644
--- a/src/plugins/qtsupport/qtsupport.qbs
+++ b/src/plugins/qtsupport/qtsupport.qbs
@@ -1,19 +1,21 @@
import qbs.base 1.0
+import "../../../qbs/functions.js" as QtcFunctions
import "../QtcPlugin.qbs" as QtcPlugin
QtcPlugin {
name: "QtSupport"
- Depends { name: "Qt"; submodules: ["widgets", "declarative"] }
+ Depends { name: "Qt"; submodules: ["widgets"]; }
+ Depends { name: "Qt.quick"; condition: QtcFunctions.versionIsAtLeast(Qt.core.version, "5.1"); }
Depends { name: "Core" }
Depends { name: "ProjectExplorer" }
Depends { name: "TextEditor" }
Depends { name: "QmlJS" }
+ Depends { name: "CppTools" }
cpp.includePaths: base.concat([
"../../shared",
- "../../shared/proparser"
])
cpp.defines: base.concat([
@@ -70,8 +72,6 @@ QtcPlugin {
"debugginghelperbuildtask.h",
"exampleslistmodel.cpp",
"exampleslistmodel.h",
- "gettingstartedwelcomepage.cpp",
- "gettingstartedwelcomepage.h",
"profilereader.cpp",
"profilereader.h",
"qmldebugginglibrary.cpp",
@@ -104,14 +104,25 @@ QtcPlugin {
"screenshotcropper.cpp",
"screenshotcropper.h",
"showbuildlog.ui",
+ "uicodemodelsupport.cpp",
+ "uicodemodelsupport.h",
"images/forms.png",
"images/qml.png",
"images/qt_project.png",
"images/qt_qrc.png",
]
+ Group {
+ name: "Getting Started Welcome Page"
+ condition: QtcFunctions.versionIsAtLeast(Qt.core.version, "5.1")
+ files: [
+ "gettingstartedwelcomepage.cpp",
+ "gettingstartedwelcomepage.h"
+ ]
+ }
+
+
Export {
- Depends { name: "cpp" }
cpp.includePaths: "../../shared"
cpp.defines: [
"QMAKE_AS_LIBRARY",
diff --git a/src/plugins/qtsupport/qtsupport_dependencies.pri b/src/plugins/qtsupport/qtsupport_dependencies.pri
index fb03eb1c12..88d89ae173 100644
--- a/src/plugins/qtsupport/qtsupport_dependencies.pri
+++ b/src/plugins/qtsupport/qtsupport_dependencies.pri
@@ -4,6 +4,7 @@ QTC_LIB_DEPENDS += \
utils
QTC_PLUGIN_DEPENDS += \
coreplugin \
+ cpptools \
projectexplorer \
texteditor
DEFINES *= \
diff --git a/src/plugins/qtsupport/qtsupportconstants.h b/src/plugins/qtsupport/qtsupportconstants.h
index e3bc352ea3..386709e1fa 100644
--- a/src/plugins/qtsupport/qtsupportconstants.h
+++ b/src/plugins/qtsupport/qtsupportconstants.h
@@ -43,6 +43,10 @@ const char DESKTOPQT[] = "Qt4ProjectManager.QtVersion.Desktop";
const char SIMULATORQT[] = "Qt4ProjectManager.QtVersion.Simulator";
const char WINCEQT[] = "Qt4ProjectManager.QtVersion.WinCE";
+// BaseQtVersion settings
+static const char QTVERSIONID[] = "Id";
+static const char QTVERSIONNAME[] = "Name";
+
//Qt Features
const char FEATURE_QT[] = "QtSupport.Wizards.FeatureQt";
const char FEATURE_QWIDGETS[] = "QtSupport.Wizards.FeatureQWidgets";
diff --git a/src/plugins/qtsupport/qtsupportplugin.cpp b/src/plugins/qtsupport/qtsupportplugin.cpp
index 964d969c19..1f03e63cf8 100644
--- a/src/plugins/qtsupport/qtsupportplugin.cpp
+++ b/src/plugins/qtsupport/qtsupportplugin.cpp
@@ -34,11 +34,10 @@
#include "qtkitinformation.h"
#include "qtversionmanager.h"
#include "qtfeatureprovider.h"
+#include "uicodemodelsupport.h"
#include "profilereader.h"
-#include "gettingstartedwelcomepage.h"
-
#include <coreplugin/icore.h>
#include <coreplugin/mimedatabase.h>
#include <coreplugin/variablemanager.h>
@@ -46,11 +45,16 @@
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/target.h>
+#if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
+#include "gettingstartedwelcomepage.h"
+#endif
+
#include <QtPlugin>
static const char kHostBins[] = "CurrentProject:QT_HOST_BINS";
static const char kInstallBins[] = "CurrentProject:QT_INSTALL_BINS";
+using namespace Core;
using namespace QtSupport;
using namespace QtSupport::Internal;
@@ -62,50 +66,49 @@ bool QtSupportPlugin::initialize(const QStringList &arguments, QString *errorMes
ProFileEvaluator::initialize();
new ProFileCacheManager(this);
- if (!Core::ICore::mimeDatabase()->addMimeTypes(QLatin1String(":qtsupport/QtSupport.mimetypes.xml"), errorMessage))
+ if (!MimeDatabase::addMimeTypes(QLatin1String(":qtsupport/QtSupport.mimetypes.xml"), errorMessage))
return false;
- QtVersionManager *mgr = new QtVersionManager;
- addAutoReleasedObject(mgr);
+
+ addAutoReleasedObject(new QtVersionManager);
+ addAutoReleasedObject(new UiCodeModelManager);
QtFeatureProvider *featureMgr = new QtFeatureProvider;
addAutoReleasedObject(featureMgr);
addAutoReleasedObject(new QtOptionsPage);
+#if (QT_VERSION >= QT_VERSION_CHECK(5, 1, 0))
ExamplesWelcomePage *welcomePage;
welcomePage = new ExamplesWelcomePage;
addAutoReleasedObject(welcomePage);
-
- welcomePage = new ExamplesWelcomePage;
welcomePage->setShowExamples(true);
- addAutoReleasedObject(welcomePage);
GettingStartedWelcomePage *gettingStartedWelcomePage = new GettingStartedWelcomePage;
addAutoReleasedObject(gettingStartedWelcomePage);
-
+#endif
addAutoReleasedObject(new CustomExecutableRunConfigurationFactory);
- ProjectExplorer::KitManager::instance()->registerKitInformation(new QtKitInformation);
+ ProjectExplorer::KitManager::registerKitInformation(new QtKitInformation);
return true;
}
void QtSupportPlugin::extensionsInitialized()
{
- Core::VariableManager::registerVariable(kHostBins,
+ VariableManager::registerVariable(kHostBins,
tr("Full path to the host bin directory of the current project's Qt version."));
- Core::VariableManager::registerVariable(kInstallBins,
+ VariableManager::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(Core::VariableManager::instance(), SIGNAL(variableUpdateRequested(QByteArray)),
+ connect(VariableManager::instance(), SIGNAL(variableUpdateRequested(QByteArray)),
this, SLOT(updateVariable(QByteArray)));
- QtVersionManager::instance()->extensionsInitialized();
+ QtVersionManager::extensionsInitialized();
}
bool QtSupportPlugin::delayedInitialize()
{
- return QtVersionManager::instance()->delayedInitialize();
+ return QtVersionManager::delayedInitialize();
}
void QtSupportPlugin::updateVariable(const QByteArray &variable)
@@ -115,18 +118,18 @@ void QtSupportPlugin::updateVariable(const QByteArray &variable)
ProjectExplorer::Project *project = ProjectExplorer::ProjectExplorerPlugin::currentProject();
if (!project || !project->activeTarget()) {
- Core::VariableManager::instance()->remove(variable);
+ VariableManager::remove(variable);
return;
}
const BaseQtVersion *qtVersion = QtKitInformation::qtVersion(project->activeTarget()->kit());
if (!qtVersion) {
- Core::VariableManager::instance()->remove(variable);
+ VariableManager::remove(variable);
return;
}
QString value = qtVersion->qmakeProperty(variable == kHostBins ? "QT_HOST_BINS" : "QT_INSTALL_BINS");
- Core::VariableManager::instance()->insert(variable, value);
+ VariableManager::insert(variable, value);
}
Q_EXPORT_PLUGIN(QtSupportPlugin)
diff --git a/src/plugins/qtsupport/qtversioninfo.ui b/src/plugins/qtsupport/qtversioninfo.ui
index 9df6f277aa..e99125c1c5 100644
--- a/src/plugins/qtsupport/qtversioninfo.ui
+++ b/src/plugins/qtsupport/qtversioninfo.ui
@@ -6,11 +6,29 @@
<rect>
<x>0</x>
<y>0</y>
- <width>392</width>
- <height>87</height>
+ <width>208</width>
+ <height>60</height>
</rect>
</property>
<layout class="QFormLayout" name="formLayout">
+ <property name="horizontalSpacing">
+ <number>0</number>
+ </property>
+ <property name="verticalSpacing">
+ <number>0</number>
+ </property>
+ <property name="leftMargin">
+ <number>0</number>
+ </property>
+ <property name="topMargin">
+ <number>0</number>
+ </property>
+ <property name="rightMargin">
+ <number>0</number>
+ </property>
+ <property name="bottomMargin">
+ <number>0</number>
+ </property>
<item row="0" column="0">
<widget class="QLabel" name="versionNameLabel">
<property name="text">
diff --git a/src/plugins/qtsupport/qtversionmanager.cpp b/src/plugins/qtsupport/qtversionmanager.cpp
index 517ba82387..0e761bb67a 100644
--- a/src/plugins/qtsupport/qtversionmanager.cpp
+++ b/src/plugins/qtsupport/qtversionmanager.cpp
@@ -33,9 +33,7 @@
#include "qtversionfactory.h"
#include "baseqtversion.h"
#include "qtfeatureprovider.h"
-
-// only for legay restore
-#include <projectexplorer/gcctoolchain.h>
+#include "qtsupportconstants.h"
#include <qtsupport/debugginghelper.h>
@@ -61,46 +59,40 @@
#include <QStringList>
#include <QTimer>
-using namespace QtSupport;
-using namespace QtSupport::Internal;
+using namespace Utils;
-static const char QTVERSION_DATA_KEY[] = "QtVersion.";
-static const char QTVERSION_TYPE_KEY[] = "QtVersion.Type";
-static const char QTVERSION_FILE_VERSION_KEY[] = "Version";
-static const char QTVERSION_FILENAME[] = "/qtcreator/qtversion.xml";
-static const char QTVERSION_LEGACY_FILENAME[] = "/qtversion.xml"; // TODO: pre 2.6, remove later
+namespace QtSupport {
-// legacy settings
-static const char QtVersionsSectionName[] = "QtVersions";
+using namespace Internal;
-enum { debug = 0 };
+const char QTVERSION_DATA_KEY[] = "QtVersion.";
+const char QTVERSION_TYPE_KEY[] = "QtVersion.Type";
+const char QTVERSION_FILE_VERSION_KEY[] = "Version";
+const char QTVERSION_FILENAME[] = "/qtcreator/qtversion.xml";
+const char QTVERSION_LEGACY_FILENAME[] = "/qtversion.xml"; // TODO: pre 2.6, remove later
-template<class T>
-static T *createToolChain(const QString &id)
-{
- QList<ProjectExplorer::ToolChainFactory *> factories =
- ExtensionSystem::PluginManager::getObjects<ProjectExplorer::ToolChainFactory>();
- foreach (ProjectExplorer::ToolChainFactory *f, factories) {
- if (f->id() == id) {
- Q_ASSERT(f->canCreate());
- return static_cast<T *>(f->create());
- }
- }
- return 0;
-}
+static QMap<int, BaseQtVersion *> m_versions;
+static int m_idcount = 0;
+// managed by QtProjectManagerPlugin
+static QtVersionManager *m_instance = 0;
+static FileSystemWatcher *m_configFileWatcher = 0;
+static QTimer *m_fileWatcherTimer = 0;
+static PersistentSettingsWriter *m_writer = 0;
+
+enum { debug = 0 };
-static Utils::FileName globalSettingsFileName()
+static FileName globalSettingsFileName()
{
QSettings *globalSettings = ExtensionSystem::PluginManager::globalSettings();
- return Utils::FileName::fromString(QFileInfo(globalSettings->fileName()).absolutePath()
+ return FileName::fromString(QFileInfo(globalSettings->fileName()).absolutePath()
+ QLatin1String(QTVERSION_FILENAME));
}
-static Utils::FileName settingsFileName(const QString &path)
+static FileName settingsFileName(const QString &path)
{
QSettings *settings = ExtensionSystem::PluginManager::settings();
QFileInfo settingsLocation(settings->fileName());
- return Utils::FileName::fromString(settingsLocation.absolutePath() + path);
+ return FileName::fromString(settingsLocation.absolutePath() + path);
}
@@ -113,17 +105,16 @@ bool qtVersionNumberCompare(BaseQtVersion *a, BaseQtVersion *b)
// --------------------------------------------------------------------------
// QtVersionManager
// --------------------------------------------------------------------------
-QtVersionManager *QtVersionManager::m_self = 0;
-QtVersionManager::QtVersionManager() :
- m_configFileWatcher(0),
- m_fileWatcherTimer(new QTimer(this)),
- m_writer(0)
+QtVersionManager::QtVersionManager()
{
- m_self = this;
+ m_instance = this;
+ m_configFileWatcher = 0;
+ m_fileWatcherTimer = new QTimer(this);
+ m_writer = 0;
m_idcount = 1;
- qRegisterMetaType<Utils::FileName>();
+ qRegisterMetaType<FileName>();
// Give the file a bit of time to settle before reading it...
m_fileWatcherTimer->setInterval(2000);
@@ -133,7 +124,7 @@ QtVersionManager::QtVersionManager() :
void QtVersionManager::extensionsInitialized()
{
bool success = restoreQtVersions();
- updateFromInstaller(false);
+ m_instance->updateFromInstaller(false);
if (!success) {
// We did neither restore our settings or upgraded
// in that case figure out if there's a qt in path
@@ -141,17 +132,17 @@ void QtVersionManager::extensionsInitialized()
findSystemQt();
}
- emit qtVersionsLoaded();
- emit qtVersionsChanged(m_versions.keys(), QList<int>(), QList<int>());
+ emit m_instance->qtVersionsLoaded();
+ emit m_instance->qtVersionsChanged(m_versions.keys(), QList<int>(), QList<int>());
saveQtVersions();
- const Utils::FileName configFileName = globalSettingsFileName();
+ const FileName configFileName = globalSettingsFileName();
if (configFileName.toFileInfo().exists()) {
- m_configFileWatcher = new Utils::FileSystemWatcher(this);
+ m_configFileWatcher = new FileSystemWatcher(m_instance);
connect(m_configFileWatcher, SIGNAL(fileChanged(QString)),
m_fileWatcherTimer, SLOT(start()));
m_configFileWatcher->addFile(configFileName.toString(),
- Utils::FileSystemWatcher::WatchModifiedDate);
+ FileSystemWatcher::WatchModifiedDate);
} // exists
}
@@ -161,7 +152,7 @@ bool QtVersionManager::delayedInitialize()
return true;
}
-bool QtVersionManager::isLoaded() const
+bool QtVersionManager::isLoaded()
{
return m_writer;
}
@@ -173,21 +164,21 @@ QtVersionManager::~QtVersionManager()
m_versions.clear();
}
-QtVersionManager *QtVersionManager::instance()
+QObject *QtVersionManager::instance()
{
- return m_self;
+ return m_instance;
}
bool QtVersionManager::restoreQtVersions()
{
QTC_ASSERT(!m_writer, return false);
- m_writer = new Utils::PersistentSettingsWriter(settingsFileName(QLatin1String(QTVERSION_FILENAME)),
+ m_writer = new PersistentSettingsWriter(settingsFileName(QLatin1String(QTVERSION_FILENAME)),
QLatin1String("QtCreatorQtVersions"));
QList<QtVersionFactory *> factories = ExtensionSystem::PluginManager::getObjects<QtVersionFactory>();
- Utils::PersistentSettingsReader reader;
- Utils::FileName filename = settingsFileName(QLatin1String(QTVERSION_FILENAME));
+ PersistentSettingsReader reader;
+ FileName filename = settingsFileName(QLatin1String(QTVERSION_FILENAME));
// Read Qt Creator 2.5 qtversions.xml once:
if (!filename.toFileInfo().exists())
@@ -246,11 +237,11 @@ void QtVersionManager::updateFromInstaller(bool emitSignal)
{
m_fileWatcherTimer->stop();
- const Utils::FileName path = globalSettingsFileName();
+ const FileName path = globalSettingsFileName();
// Handle overwritting of data:
if (m_configFileWatcher) {
m_configFileWatcher->removeFile(path.toString());
- m_configFileWatcher->addFile(path.toString(), Utils::FileSystemWatcher::WatchModifiedDate);
+ m_configFileWatcher->addFile(path.toString(), FileSystemWatcher::WatchModifiedDate);
}
QList<int> added;
@@ -258,7 +249,7 @@ void QtVersionManager::updateFromInstaller(bool emitSignal)
QList<int> changed;
QList<QtVersionFactory *> factories = ExtensionSystem::PluginManager::getObjects<QtVersionFactory>();
- Utils::PersistentSettingsReader reader;
+ PersistentSettingsReader reader;
QVariantMap data;
if (reader.load(path))
data = reader.restoreValues();
@@ -309,7 +300,9 @@ void QtVersionManager::updateFromInstaller(bool emitSignal)
if (debug)
qDebug() << " Qt version found with same autodetection source" << autoDetectionSource << " => Migrating id:" << id;
m_versions.remove(id);
- qtversionMap[QLatin1String("Id")] = id;
+ qtversionMap[QLatin1String(Constants::QTVERSIONID)] = id;
+ qtversionMap[QLatin1String(Constants::QTVERSIONNAME)] = v->displayName();
+ delete v;
if (BaseQtVersion *qtv = factory->restore(type, qtversionMap)) {
Q_ASSERT(qtv->isAutodetected());
@@ -347,7 +340,7 @@ void QtVersionManager::updateFromInstaller(bool emitSignal)
qDebug() << "";
}
}
- foreach (BaseQtVersion *qtVersion, QtVersionManager::instance()->versions()) {
+ foreach (BaseQtVersion *qtVersion, QtVersionManager::versions()) {
if (qtVersion->autodetectionSource().startsWith(QLatin1String("SDK."))) {
if (!sdkVersions.contains(qtVersion->autodetectionSource())) {
if (debug)
@@ -394,7 +387,7 @@ void QtVersionManager::saveQtVersions()
void QtVersionManager::findSystemQt()
{
- Utils::FileName systemQMakePath = QtSupport::DebuggingHelperLibrary::findSystemQt(Utils::Environment::systemEnvironment());
+ FileName systemQMakePath = QtSupport::DebuggingHelperLibrary::findSystemQt(Environment::systemEnvironment());
if (systemQMakePath.isNull())
return;
@@ -415,7 +408,7 @@ void QtVersionManager::addVersion(BaseQtVersion *version)
int uniqueId = version->uniqueId();
m_versions.insert(uniqueId, version);
- emit qtVersionsChanged(QList<int>() << uniqueId, QList<int>(), QList<int>());
+ emit m_instance->qtVersionsChanged(QList<int>() << uniqueId, QList<int>(), QList<int>());
saveQtVersions();
}
@@ -423,15 +416,13 @@ void QtVersionManager::removeVersion(BaseQtVersion *version)
{
QTC_ASSERT(version != 0, return);
m_versions.remove(version->uniqueId());
- emit qtVersionsChanged(QList<int>(), QList<int>() << version->uniqueId(), QList<int>());
+ emit m_instance->qtVersionsChanged(QList<int>(), QList<int>() << version->uniqueId(), QList<int>());
saveQtVersions();
delete version;
}
void QtVersionManager::updateDocumentation()
{
- Core::HelpManager *helpManager = Core::HelpManager::instance();
- Q_ASSERT(helpManager);
QStringList files;
foreach (BaseQtVersion *v, m_versions) {
const QStringList docPaths = QStringList() << v->documentationPath() + QLatin1Char('/')
@@ -443,10 +434,10 @@ void QtVersionManager::updateDocumentation()
files << docPath + helpFile;
}
}
- helpManager->registerDocumentation(files);
+ Core::HelpManager::registerDocumentation(files);
}
-void QtVersionManager::updateDumpFor(const Utils::FileName &qmakeCommand)
+void QtVersionManager::updateDumpFor(const FileName &qmakeCommand)
{
foreach (BaseQtVersion *v, versions()) {
if (v->qmakeCommand() == qmakeCommand)
@@ -460,7 +451,7 @@ int QtVersionManager::getUniqueId()
return m_idcount++;
}
-QList<BaseQtVersion *> QtVersionManager::versions() const
+QList<BaseQtVersion *> QtVersionManager::versions()
{
QList<BaseQtVersion *> versions;
QTC_ASSERT(isLoaded(), return versions);
@@ -470,7 +461,7 @@ QList<BaseQtVersion *> QtVersionManager::versions() const
return versions;
}
-QList<BaseQtVersion *> QtVersionManager::validVersions() const
+QList<BaseQtVersion *> QtVersionManager::validVersions()
{
QList<BaseQtVersion *> results;
QTC_ASSERT(isLoaded(), return results);
@@ -482,13 +473,13 @@ QList<BaseQtVersion *> QtVersionManager::validVersions() const
return results;
}
-bool QtVersionManager::isValidId(int id) const
+bool QtVersionManager::isValidId(int id)
{
QTC_ASSERT(isLoaded(), return false);
return m_versions.contains(id);
}
-Core::FeatureSet QtVersionManager::availableFeatures(const QString &platformName) const
+Core::FeatureSet QtVersionManager::availableFeatures(const QString &platformName)
{
Core::FeatureSet features;
foreach (BaseQtVersion *const qtVersion, validVersions()) {
@@ -499,7 +490,7 @@ Core::FeatureSet QtVersionManager::availableFeatures(const QString &platformName
return features;
}
-QStringList QtVersionManager::availablePlatforms() const
+QStringList QtVersionManager::availablePlatforms()
{
QStringList platforms;
foreach (BaseQtVersion *const qtVersion, validVersions()) {
@@ -510,7 +501,7 @@ QStringList QtVersionManager::availablePlatforms() const
return platforms;
}
-QString QtVersionManager::displayNameForPlatform(const QString &string) const
+QString QtVersionManager::displayNameForPlatform(const QString &string)
{
foreach (BaseQtVersion *const qtVersion, validVersions()) {
if (qtVersion->platformName() == string)
@@ -519,7 +510,7 @@ QString QtVersionManager::displayNameForPlatform(const QString &string) const
return QString();
}
-BaseQtVersion *QtVersionManager::version(int id) const
+BaseQtVersion *QtVersionManager::version(int id)
{
QTC_ASSERT(isLoaded(), return 0);
QMap<int, BaseQtVersion *>::const_iterator it = m_versions.find(id);
@@ -602,14 +593,14 @@ void QtVersionManager::setNewQtVersions(QList<BaseQtVersion *> newVersions)
saveQtVersions();
if (!changedVersions.isEmpty() || !addedVersions.isEmpty() || !removedVersions.isEmpty())
- emit qtVersionsChanged(addedVersions, removedVersions, changedVersions);
+ emit m_instance->qtVersionsChanged(addedVersions, removedVersions, changedVersions);
}
// Returns the version that was used to build the project in that directory
// That is returns the directory
// To find out whether we already have a qtversion for that directory call
// QtVersion *QtVersionManager::qtVersionForDirectory(const QString directory);
-Utils::FileName QtVersionManager::findQMakeBinaryFromMakefile(const QString &makefile)
+FileName QtVersionManager::findQMakeBinaryFromMakefile(const QString &makefile)
{
bool debugAdding = false;
QFile fi(makefile);
@@ -623,21 +614,21 @@ Utils::FileName QtVersionManager::findQMakeBinaryFromMakefile(const QString &mak
qDebug()<<"#~~ QMAKE is:"<<r1.cap(1).trimmed();
QFileInfo qmake(r1.cap(1).trimmed());
QString qmakePath = qmake.filePath();
- if (Utils::HostOsInfo::isWindowsHost()
+ if (HostOsInfo::isWindowsHost()
&& !qmakePath.endsWith(QLatin1String(".exe"))) {
qmakePath.append(QLatin1String(".exe"));
}
// Is qmake still installed?
QFileInfo fi(qmakePath);
if (fi.exists())
- return Utils::FileName(fi);
+ return FileName(fi);
}
}
}
- return Utils::FileName();
+ return FileName();
}
-BaseQtVersion *QtVersionManager::qtVersionForQMakeBinary(const Utils::FileName &qmakePath)
+BaseQtVersion *QtVersionManager::qtVersionForQMakeBinary(const FileName &qmakePath)
{
foreach (BaseQtVersion *version, versions()) {
if (version->qmakeCommand() == qmakePath) {
@@ -707,11 +698,11 @@ QPair<BaseQtVersion::QmakeBuildConfigs, QString> QtVersionManager::scanMakeFile(
dumpQMakeAssignments(assignments);
foreach (const QMakeAssignment &qa, assignments)
- Utils::QtcProcess::addArg(&result2, qa.variable + qa.op + qa.value);
+ QtcProcess::addArg(&result2, qa.variable + qa.op + qa.value);
if (!afterAssignments.isEmpty()) {
- Utils::QtcProcess::addArg(&result2, QLatin1String("-after"));
+ QtcProcess::addArg(&result2, QLatin1String("-after"));
foreach (const QMakeAssignment &qa, afterAssignments)
- Utils::QtcProcess::addArg(&result2, qa.variable + qa.op + qa.value);
+ QtcProcess::addArg(&result2, qa.variable + qa.op + qa.value);
}
}
@@ -758,7 +749,7 @@ void QtVersionManager::parseArgs(const QString &args, QList<QMakeAssignment> *as
bool after = false;
bool ignoreNext = false;
*additionalArguments = args;
- Utils::QtcProcess::ArgIterator ait(additionalArguments);
+ QtcProcess::ArgIterator ait(additionalArguments);
while (ait.next()) {
if (ignoreNext) {
// Ignoring
@@ -842,15 +833,17 @@ BaseQtVersion::QmakeBuildConfigs QtVersionManager::qmakeBuildConfigFromCmdArgs(Q
Core::FeatureSet QtFeatureProvider::availableFeatures(const QString &platformName) const
{
- return QtVersionManager::instance()->availableFeatures(platformName);
+ return QtVersionManager::availableFeatures(platformName);
}
QStringList QtFeatureProvider::availablePlatforms() const
{
- return QtVersionManager::instance()->availablePlatforms();
+ return QtVersionManager::availablePlatforms();
}
QString QtFeatureProvider::displayNameForPlatform(const QString &string) const
{
- return QtVersionManager::instance()->displayNameForPlatform(string);
+ return QtVersionManager::displayNameForPlatform(string);
}
+
+} // namespace QtVersion
diff --git a/src/plugins/qtsupport/qtversionmanager.h b/src/plugins/qtsupport/qtversionmanager.h
index ed87a4f589..8b80ff80fe 100644
--- a/src/plugins/qtsupport/qtversionmanager.h
+++ b/src/plugins/qtsupport/qtversionmanager.h
@@ -62,40 +62,39 @@ class QTSUPPORT_EXPORT QtVersionManager : public QObject
friend class BaseQtVersion;
friend class Internal::QtOptionsPageWidget;
public:
- static QtVersionManager *instance();
+ static QObject *instance();
QtVersionManager();
~QtVersionManager();
- void extensionsInitialized();
- bool delayedInitialize();
+ static void extensionsInitialized();
+ static bool delayedInitialize();
- bool isLoaded() const;
+ static bool isLoaded();
// This will *always* return at least one (Qt in Path), even if that is
// unconfigured.
- QList<BaseQtVersion *> versions() const;
- QList<BaseQtVersion *> validVersions() const;
+ static QList<BaseQtVersion *> versions();
+ static QList<BaseQtVersion *> validVersions();
// Note: DO NOT STORE THIS POINTER!
// The QtVersionManager will delete it at random times and you will
// need to get a new pointer by calling this method again!
- BaseQtVersion *version(int id) const;
+ static BaseQtVersion *version(int id);
- BaseQtVersion *qtVersionForQMakeBinary(const Utils::FileName &qmakePath);
+ static BaseQtVersion *qtVersionForQMakeBinary(const Utils::FileName &qmakePath);
- void addVersion(BaseQtVersion *version);
- void removeVersion(BaseQtVersion *version);
+ static void addVersion(BaseQtVersion *version);
+ static void removeVersion(BaseQtVersion *version);
- // Static Methods
enum MakefileCompatible { CouldNotParse, DifferentProject, SameProject };
static MakefileCompatible makefileIsFor(const QString &makefile, const QString &proFile);
static QPair<BaseQtVersion::QmakeBuildConfigs, QString> scanMakeFile(const QString &makefile,
BaseQtVersion::QmakeBuildConfigs defaultBuildConfig);
static Utils::FileName findQMakeBinaryFromMakefile(const QString &directory);
- bool isValidId(int id) const;
+ static bool isValidId(int id);
- Core::FeatureSet availableFeatures(const QString &platformName) const;
- QStringList availablePlatforms() const;
- QString displayNameForPlatform(const QString &string) const;
+ static Core::FeatureSet availableFeatures(const QString &platformName);
+ static QStringList availablePlatforms();
+ static QString displayNameForPlatform(const QString &string);
signals:
// content of BaseQtVersion objects with qmake path might have changed
@@ -120,27 +119,18 @@ private:
QString *additionalArguments);
static BaseQtVersion::QmakeBuildConfigs qmakeBuildConfigFromCmdArgs(QList<QMakeAssignment> *assignments,
BaseQtVersion::QmakeBuildConfigs defaultBuildConfig);
- bool restoreQtVersions();
- void findSystemQt();
- void saveQtVersions();
- void updateDocumentation();
+ static bool restoreQtVersions();
+ static void findSystemQt();
+ static void saveQtVersions();
+ static void updateDocumentation();
// Used by QtOptionsPage
- void setNewQtVersions(QList<BaseQtVersion *> newVersions);
+ static void setNewQtVersions(QList<BaseQtVersion *> newVersions);
// Used by QtVersion
- int getUniqueId();
- void addNewVersionsFromInstaller();
+ static int getUniqueId();
+ static void addNewVersionsFromInstaller();
static int indexOfVersionInList(const BaseQtVersion * const version, const QList<BaseQtVersion *> &list);
- void updateUniqueIdToIndexMap();
-
- QMap<int, BaseQtVersion *> m_versions;
- int m_idcount;
- // managed by QtProjectManagerPlugin
- static QtVersionManager *m_self;
-
- Utils::FileSystemWatcher *m_configFileWatcher;
- QTimer *m_fileWatcherTimer;
- Utils::PersistentSettingsWriter *m_writer;
+ static void updateUniqueIdToIndexMap();
};
} // namespace QtSupport
diff --git a/src/plugins/qtsupport/uicodemodelsupport.cpp b/src/plugins/qtsupport/uicodemodelsupport.cpp
new file mode 100644
index 0000000000..3cd2cf51a8
--- /dev/null
+++ b/src/plugins/qtsupport/uicodemodelsupport.cpp
@@ -0,0 +1,451 @@
+/****************************************************************************
+**
+** 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 "uicodemodelsupport.h"
+
+#include "qtkitinformation.h"
+
+#include <coreplugin/editormanager/editormanager.h>
+#include <coreplugin/editormanager/ieditor.h>
+#include <cpptools/cppmodelmanagerinterface.h>
+#include <projectexplorer/buildconfiguration.h>
+#include <projectexplorer/buildmanager.h>
+#include <projectexplorer/project.h>
+#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/session.h>
+#include <projectexplorer/target.h>
+#include <utils/qtcassert.h>
+
+#include <QFile>
+#include <QFileInfo>
+
+enum { debug = 0 };
+
+using namespace ProjectExplorer;
+using namespace CPlusPlus;
+
+// Test for form editor (loosely coupled)
+static inline bool isFormWindowDocument(const QObject *o)
+{
+ return o && !qstrcmp(o->metaObject()->className(), "Designer::Internal::FormWindowFile");
+}
+
+// Return contents of form editor (loosely coupled)
+static inline QString formWindowEditorContents(const QObject *editor)
+{
+ const QVariant contentV = editor->property("contents");
+ QTC_ASSERT(contentV.isValid(), return QString());
+ return contentV.toString();
+}
+
+namespace QtSupport {
+
+UiCodeModelSupport::UiCodeModelSupport(CppTools::CppModelManagerInterface *modelmanager,
+ ProjectExplorer::Project *project,
+ const QString &uiFile,
+ const QString &uiHeaderFile)
+ : CppTools::AbstractEditorSupport(modelmanager),
+ m_project(project),
+ m_uiFileName(uiFile),
+ m_headerFileName(uiHeaderFile),
+ m_state(BARE)
+{
+ if (debug)
+ qDebug()<<"ctor UiCodeModelSupport for"<<m_uiFileName<<uiHeaderFile;
+ connect(&m_process, SIGNAL(finished(int)),
+ this, SLOT(finishProcess()));
+}
+
+UiCodeModelSupport::~UiCodeModelSupport()
+{
+ if (debug)
+ qDebug()<<"dtor ~UiCodeModelSupport for"<<m_uiFileName;
+}
+
+void UiCodeModelSupport::init() const
+{
+ if (m_state != BARE)
+ return;
+ QDateTime sourceTime = QFileInfo(m_uiFileName).lastModified();
+ QFileInfo uiHeaderFileInfo(m_headerFileName);
+ QDateTime uiHeaderTime = uiHeaderFileInfo.exists() ? uiHeaderFileInfo.lastModified() : QDateTime();
+ if (uiHeaderTime.isValid() && (uiHeaderTime > sourceTime)) {
+ QFile file(m_headerFileName);
+ if (file.open(QFile::ReadOnly | QFile::Text)) {
+ if (debug)
+ qDebug()<<"ui*h file is more recent then source file, using information from ui*h file"<<m_headerFileName;
+ QTextStream stream(&file);
+ m_contents = stream.readAll().toUtf8();
+ m_cacheTime = uiHeaderTime;
+ m_state = FINISHED;
+ return;
+ }
+ }
+
+ if (debug)
+ qDebug()<<"ui*h file not found, or not recent enough, trying to create it on the fly";
+ QFile file(m_uiFileName);
+ if (file.open(QFile::ReadOnly | QFile::Text)) {
+ QTextStream stream(&file);
+ const QString contents = stream.readAll();
+ if (runUic(contents)) {
+ if (debug)
+ qDebug()<<"created on the fly";
+ return;
+ } else {
+ // uic run was unsuccesfull
+ if (debug)
+ qDebug()<<"uic run wasn't succesfull";
+ m_cacheTime = QDateTime ();
+ m_contents.clear();
+ m_state = FINISHED;
+ return;
+ }
+ } else {
+ if (debug)
+ qDebug()<<"Could open "<<m_uiFileName<<"needed for the cpp model";
+ m_contents.clear();
+ m_state = FINISHED;
+ }
+}
+
+QByteArray UiCodeModelSupport::contents() const
+{
+ // Check the common case first
+ if (m_state == FINISHED)
+ return m_contents;
+ if (m_state == BARE)
+ init();
+ if (m_state == RUNNING)
+ finishProcess();
+
+ return m_contents;
+}
+
+QString UiCodeModelSupport::uiFileName() const
+{
+ return m_uiFileName;
+}
+
+QString UiCodeModelSupport::fileName() const
+{
+ return m_headerFileName;
+}
+
+void UiCodeModelSupport::setHeaderFileName(const QString &name)
+{
+ if (m_headerFileName == name && m_cacheTime.isValid())
+ return;
+
+ if (m_state == RUNNING)
+ finishProcess();
+
+ if (debug)
+ qDebug() << "UiCodeModelSupport::setFileName"<<name;
+
+ m_headerFileName = name;
+ m_contents.clear();
+ m_cacheTime = QDateTime();
+ m_state = BARE;
+}
+
+bool UiCodeModelSupport::runUic(const QString &ui) const
+{
+ const QString uic = uicCommand();
+ if (uic.isEmpty())
+ return false;
+ m_process.setEnvironment(environment());
+
+ if (debug)
+ qDebug() << "UiCodeModelSupport::runUic " << uic << " on " << ui.size() << " bytes";
+ m_process.start(uic, QStringList(), QIODevice::ReadWrite);
+ if (!m_process.waitForStarted())
+ return false;
+ m_process.write(ui.toUtf8());
+ if (!m_process.waitForBytesWritten(3000))
+ goto error;
+ m_process.closeWriteChannel();
+ m_state = RUNNING;
+ return true;
+
+error:
+ if (debug)
+ qDebug() << "failed" << m_process.readAllStandardError();
+ m_process.kill();
+ m_state = FINISHED;
+ return false;
+}
+
+void UiCodeModelSupport::updateFromEditor(const QString &formEditorContents)
+{
+ if (m_state == BARE)
+ init();
+ if (m_state == RUNNING)
+ finishProcess();
+ if (runUic(formEditorContents))
+ if (finishProcess())
+ updateDocument();
+}
+
+void UiCodeModelSupport::updateFromBuild()
+{
+ if (debug)
+ qDebug()<<"UiCodeModelSupport::updateFromBuild() for file"<<m_uiFileName;
+ if (m_state == BARE)
+ init();
+ if (m_state == RUNNING)
+ finishProcess();
+ // This is mostly a fall back for the cases when uic couldn't be run
+ // it pays special attention to the case where a ui_*h was newly created
+ QDateTime sourceTime = QFileInfo(m_uiFileName).lastModified();
+ if (m_cacheTime.isValid() && m_cacheTime >= sourceTime) {
+ if (debug)
+ qDebug()<<"Cache is still more recent then source";
+ return;
+ } else {
+ QFileInfo fi(m_headerFileName);
+ QDateTime uiHeaderTime = fi.exists() ? fi.lastModified() : QDateTime();
+ if (uiHeaderTime.isValid() && (uiHeaderTime > sourceTime)) {
+ if (m_cacheTime >= uiHeaderTime)
+ return;
+ if (debug)
+ qDebug()<<"found ui*h updating from it";
+
+ QFile file(m_headerFileName);
+ if (file.open(QFile::ReadOnly | QFile::Text)) {
+ QTextStream stream(&file);
+ m_contents = stream.readAll().toUtf8();
+ m_cacheTime = uiHeaderTime;
+ updateDocument();
+ return;
+ }
+ }
+ if (debug)
+ qDebug()<<"ui*h not found or not more recent then source not changing anything";
+ }
+}
+
+QString UiCodeModelSupport::uicCommand() const
+{
+ QtSupport::BaseQtVersion *version;
+ if (m_project->needsConfiguration()) {
+ version = QtSupport::QtKitInformation::qtVersion(ProjectExplorer::KitManager::defaultKit());
+ } else {
+ ProjectExplorer::Target *target = m_project->activeTarget();
+ version = QtSupport::QtKitInformation::qtVersion(target->kit());
+ }
+ return version ? version->uicCommand() : QString();
+}
+
+QStringList UiCodeModelSupport::environment() const
+{
+ if (m_project->needsConfiguration()) {
+ return Utils::Environment::systemEnvironment().toStringList();
+ } else {
+ ProjectExplorer::Target *target = m_project->activeTarget();
+ if (!target)
+ return QStringList();
+ ProjectExplorer::BuildConfiguration *bc = target->activeBuildConfiguration();
+ return bc ? bc->environment().toStringList() : QStringList();
+ }
+}
+
+bool UiCodeModelSupport::finishProcess() const
+{
+ if (m_state != RUNNING)
+ return false;
+ if (!m_process.waitForFinished(3000)
+ && m_process.exitStatus() != QProcess::NormalExit
+ && m_process.exitCode() != 0) {
+ if (m_state != RUNNING) // waitForFinished can recurse into finishProcess
+ return false;
+
+ if (debug)
+ qDebug() << "failed" << m_process.readAllStandardError();
+ m_process.kill();
+ m_state = FINISHED;
+ return false;
+ }
+
+ if (m_state != RUNNING) // waitForFinished can recurse into finishProcess
+ return true;
+
+ // As far as I can discover in the UIC sources, it writes out local 8-bit encoding. The
+ // conversion below is to normalize both the encoding, and the line terminators.
+ QString normalized = QString::fromLocal8Bit(m_process.readAllStandardOutput());
+ m_contents = normalized.toUtf8();
+ m_cacheTime = QDateTime::currentDateTime();
+ if (debug)
+ qDebug() << "ok" << m_contents.size() << "bytes.";
+ m_state = FINISHED;
+ return true;
+}
+
+UiCodeModelManager *UiCodeModelManager::m_instance = 0;
+
+UiCodeModelManager::UiCodeModelManager() :
+ m_lastEditor(0),
+ m_dirty(false)
+{
+ m_instance = this;
+ connect(BuildManager::instance(), SIGNAL(buildStateChanged(ProjectExplorer::Project*)),
+ this, SLOT(buildStateHasChanged(ProjectExplorer::Project*)));
+ connect(SessionManager::instance(),
+ SIGNAL(projectRemoved(ProjectExplorer::Project*)),
+ this, SLOT(projectWasRemoved(ProjectExplorer::Project*)));
+
+ connect(Core::EditorManager::instance(), SIGNAL(editorAboutToClose(Core::IEditor*)),
+ this, SLOT(editorIsAboutToClose(Core::IEditor*)));
+ connect(Core::EditorManager::instance(), SIGNAL(currentEditorChanged(Core::IEditor*)),
+ this, SLOT(editorWasChanged(Core::IEditor*)));
+}
+
+UiCodeModelManager::~UiCodeModelManager()
+{
+ m_instance = 0;
+}
+
+static UiCodeModelSupport *findUiFile(const QList<UiCodeModelSupport *> &range, const QString &uiFile)
+{
+ foreach (UiCodeModelSupport *support, range) {
+ if (support->uiFileName() == uiFile)
+ return support;
+ }
+ return 0;
+}
+
+void UiCodeModelManager::update(ProjectExplorer::Project *project, QHash<QString, QString> uiHeaders)
+{
+ CppTools::CppModelManagerInterface *mm = CppTools::CppModelManagerInterface::instance();
+
+ // Find support to add/update:
+ QList<UiCodeModelSupport *> oldSupport = m_instance->m_projectUiSupport.value(project);
+ QList<UiCodeModelSupport *> newSupport;
+ QHash<QString, QString>::const_iterator it;
+ for (it = uiHeaders.constBegin(); it != uiHeaders.constEnd(); ++it) {
+ if (UiCodeModelSupport *support = findUiFile(oldSupport, it.key())) {
+ support->setHeaderFileName(it.value());
+ oldSupport.removeOne(support);
+ newSupport.append(support);
+ } else {
+ UiCodeModelSupport *cms = new UiCodeModelSupport(mm, project, it.key(), it.value());
+ newSupport.append(cms);
+ mm->addExtraEditorSupport(cms);
+ }
+ }
+
+ // Remove old:
+ foreach (UiCodeModelSupport *support, oldSupport) {
+ mm->removeExtraEditorSupport(support);
+ delete support;
+ }
+
+ // Update state:
+ m_instance->m_projectUiSupport.insert(project, newSupport);
+}
+
+void UiCodeModelManager::updateContents(const QString &uiFileName, const QString &contents)
+{
+ QHash<Project *, QList<UiCodeModelSupport *> >::iterator i;
+ for (i = m_instance->m_projectUiSupport.begin();
+ i != m_instance->m_projectUiSupport.end(); ++i) {
+ foreach (UiCodeModelSupport *support, i.value()) {
+ if (support->uiFileName() == uiFileName)
+ support->updateFromEditor(contents);
+ }
+ }
+}
+
+void UiCodeModelManager::buildStateHasChanged(Project *project)
+{
+ if (BuildManager::isBuilding(project))
+ return;
+
+ QList<UiCodeModelSupport *> projectSupport = m_projectUiSupport.value(project);
+ foreach (UiCodeModelSupport *const i, projectSupport)
+ i->updateFromBuild();
+}
+
+void UiCodeModelManager::projectWasRemoved(Project *project)
+{
+ CppTools::CppModelManagerInterface *mm = CppTools::CppModelManagerInterface::instance();
+
+ QList<UiCodeModelSupport *> projectSupport = m_projectUiSupport.value(project);
+ foreach (UiCodeModelSupport *const i, projectSupport) {
+ mm->removeExtraEditorSupport(i);
+ delete i;
+ }
+
+ m_projectUiSupport.remove(project);
+}
+
+void UiCodeModelManager::editorIsAboutToClose(Core::IEditor *editor)
+{
+ if (m_lastEditor == editor) {
+ // Oh no our editor is going to be closed
+ // get the content first
+ if (isFormWindowDocument(m_lastEditor->document())) {
+ disconnect(m_lastEditor->document(), SIGNAL(changed()), this, SLOT(uiDocumentContentsHasChanged()));
+ if (m_dirty) {
+ updateContents(m_lastEditor->document()->filePath(),
+ formWindowEditorContents(m_lastEditor));
+ m_dirty = false;
+ }
+ }
+ m_lastEditor = 0;
+ }
+}
+
+void UiCodeModelManager::editorWasChanged(Core::IEditor *editor)
+{
+ // Handle old editor
+ if (m_lastEditor && isFormWindowDocument(m_lastEditor->document())) {
+ disconnect(m_lastEditor->document(), SIGNAL(changed()), this, SLOT(uiDocumentContentsHasChanged()));
+
+ if (m_dirty) {
+ updateContents(m_lastEditor->document()->filePath(),
+ formWindowEditorContents(m_lastEditor));
+ m_dirty = false;
+ }
+ }
+
+ m_lastEditor = editor;
+
+ // Handle new editor
+ if (m_lastEditor && isFormWindowDocument(m_lastEditor->document()))
+ connect(m_lastEditor->document(), SIGNAL(changed()), this, SLOT(uiDocumentContentsHasChanged()));
+}
+
+void UiCodeModelManager::uiDocumentContentsHasChanged()
+{
+ QTC_ASSERT(isFormWindowDocument(sender()), return);
+ m_dirty = true;
+}
+
+} // namespace QtSupport
diff --git a/src/plugins/cpptools/uicodecompletionsupport.h b/src/plugins/qtsupport/uicodemodelsupport.h
index df56b544de..881bcd7dc0 100644
--- a/src/plugins/cpptools/uicodecompletionsupport.h
+++ b/src/plugins/qtsupport/uicodemodelsupport.h
@@ -27,51 +27,99 @@
**
****************************************************************************/
+#ifndef UICODEMODELSUPPORT_H
+#define UICODEMODELSUPPORT_H
-#ifndef UICODECOMPLETIONSUPPORT_H
-#define UICODECOMPLETIONSUPPORT_H
+#include "qtsupport_global.h"
-#include "cpptools_global.h"
-#include "abstracteditorsupport.h"
-#include "cppmodelmanagerinterface.h"
+#include <cpptools/abstracteditorsupport.h>
#include <QDateTime>
+#include <QHash>
#include <QProcess>
+#include <QSet>
-namespace CppTools {
+namespace Core { class IEditor; }
+namespace CPlusPlus { class CppModelManagerInterface; }
+namespace ProjectExplorer { class Project; }
-class CPPTOOLS_EXPORT UiCodeModelSupport : public AbstractEditorSupport
+namespace QtSupport {
+
+namespace Internal { class QtSupportPlugin; }
+
+class UiCodeModelSupport : public CppTools::AbstractEditorSupport
{
Q_OBJECT
+
public:
UiCodeModelSupport(CppTools::CppModelManagerInterface *modelmanager,
+ ProjectExplorer::Project *project,
const QString &sourceFile,
const QString &uiHeaderFile);
~UiCodeModelSupport();
- void setFileName(const QString &name);
- void setSourceName(const QString &name);
- virtual QByteArray contents() const;
- virtual QString fileName() const;
+
+ void setHeaderFileName(const QString &name);
+ /// \returns the contents encoded in UTF-8.
+ QByteArray contents() const;
+ QString uiFileName() const; // The .ui-file
+ QString fileName() const; // The header file
+ QString headerFileName() const { return fileName(); }
void updateFromEditor(const QString &formEditorContents);
void updateFromBuild();
-protected:
- virtual QString uicCommand() const = 0;
- virtual QStringList environment() const = 0;
+
private:
+ QString uicCommand() const;
+ QStringList environment() const;
+
+private slots:
+ bool finishProcess() const;
+
+private:
+ ProjectExplorer::Project *m_project;
enum State { BARE, RUNNING, FINISHED };
void init() const;
bool runUic(const QString &ui) const;
- Q_SLOT bool finishProcess() const;
mutable QProcess m_process;
- QString m_sourceName;
- QString m_fileName;
+ QString m_uiFileName;
+ QString m_headerFileName;
mutable State m_state;
mutable QByteArray m_contents;
mutable QDateTime m_cacheTime;
static QList<UiCodeModelSupport *> m_waitingForStart;
};
-} // CppTools
+class QTSUPPORT_EXPORT UiCodeModelManager : public QObject
+{
+ Q_OBJECT
+
+public:
+ // This needs to be called by the project *before* the C++ code model is updated!
+ static void update(ProjectExplorer::Project *project,
+ QHash<QString, QString> uiHeaders);
+
+private slots:
+ void buildStateHasChanged(ProjectExplorer::Project *project);
+ void projectWasRemoved(ProjectExplorer::Project *project);
+ void editorIsAboutToClose(Core::IEditor *editor);
+ void editorWasChanged(Core::IEditor *editor);
+ void uiDocumentContentsHasChanged();
+
+private:
+ UiCodeModelManager();
+ ~UiCodeModelManager();
+
+ static void updateContents(const QString &uiFileName, const QString &contents);
+
+ QHash<ProjectExplorer::Project *, QList<UiCodeModelSupport *> > m_projectUiSupport;
+ Core::IEditor *m_lastEditor;
+ bool m_dirty;
+
+ static UiCodeModelManager *m_instance;
+
+ friend class Internal::QtSupportPlugin;
+};
+
+} // QtSupport
-#endif // UICODECOMPLETIONSUPPORT_H
+#endif // UICODEMODELSUPPORT_H
diff --git a/src/plugins/remotelinux/RemoteLinux.pluginspec.in b/src/plugins/remotelinux/RemoteLinux.pluginspec.in
index aa084bc08c..d74934adab 100644
--- a/src/plugins/remotelinux/RemoteLinux.pluginspec.in
+++ b/src/plugins/remotelinux/RemoteLinux.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"RemoteLinux\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"RemoteLinux\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/remotelinux/abstractpackagingstep.cpp b/src/plugins/remotelinux/abstractpackagingstep.cpp
index 688663ead8..ee3952747a 100644
--- a/src/plugins/remotelinux/abstractpackagingstep.cpp
+++ b/src/plugins/remotelinux/abstractpackagingstep.cpp
@@ -117,7 +117,7 @@ QString AbstractPackagingStep::cachedPackageDirectory() const
QString AbstractPackagingStep::packageDirectory() const
{
return d->currentBuildConfiguration
- ? d->currentBuildConfiguration->buildDirectory() : QString();
+ ? d->currentBuildConfiguration->buildDirectory().toString() : QString();
}
bool AbstractPackagingStep::isPackagingNeeded() const
@@ -170,7 +170,7 @@ void AbstractPackagingStep::raiseError(const QString &errorMessage)
{
emit addOutput(errorMessage, BuildStep::ErrorOutput);
emit addTask(Task(Task::Error, errorMessage, Utils::FileName(), -1,
- Core::Id(Constants::TASK_CATEGORY_BUILDSYSTEM)));
+ Constants::TASK_CATEGORY_DEPLOYMENT));
}
} // namespace RemoteLinux
diff --git a/src/plugins/remotelinux/abstractremotelinuxdeployservice.cpp b/src/plugins/remotelinux/abstractremotelinuxdeployservice.cpp
index 0cd603b625..8c916a311b 100644
--- a/src/plugins/remotelinux/abstractremotelinuxdeployservice.cpp
+++ b/src/plugins/remotelinux/abstractremotelinuxdeployservice.cpp
@@ -267,7 +267,7 @@ void AbstractRemoteLinuxDeployService::handleDeviceSetupDone(bool success)
}
d->state = Connecting;
- d->connection = SshConnectionManager::instance().acquireConnection(deviceConfiguration()->sshParameters());
+ d->connection = QSsh::acquireConnection(deviceConfiguration()->sshParameters());
connect(d->connection, SIGNAL(error(QSsh::SshError)),
SLOT(handleConnectionFailure()));
if (d->connection->state() == SshConnection::Connected) {
@@ -328,7 +328,7 @@ void AbstractRemoteLinuxDeployService::setFinished()
d->state = Inactive;
if (d->connection) {
disconnect(d->connection, 0, this, 0);
- SshConnectionManager::instance().releaseConnection(d->connection);
+ QSsh::releaseConnection(d->connection);
d->connection = 0;
}
d->stopRequested = false;
diff --git a/src/plugins/remotelinux/abstractremotelinuxdeploystep.cpp b/src/plugins/remotelinux/abstractremotelinuxdeploystep.cpp
index a52db4941e..86d40e9d02 100644
--- a/src/plugins/remotelinux/abstractremotelinuxdeploystep.cpp
+++ b/src/plugins/remotelinux/abstractremotelinuxdeploystep.cpp
@@ -132,7 +132,7 @@ void AbstractRemoteLinuxDeployStep::handleErrorMessage(const QString &message)
{
emit addOutput(message, ErrorMessageOutput);
emit addTask(Task(Task::Error, message, Utils::FileName(), -1,
- Core::Id(Constants::TASK_CATEGORY_BUILDSYSTEM)));
+ Constants::TASK_CATEGORY_DEPLOYMENT));
d->hasError = true;
}
@@ -140,7 +140,7 @@ void AbstractRemoteLinuxDeployStep::handleWarningMessage(const QString &message)
{
emit addOutput(message, ErrorMessageOutput);
emit addTask(Task(Task::Warning, message, Utils::FileName(), -1,
- Core::Id(Constants::TASK_CATEGORY_BUILDSYSTEM)));
+ Constants::TASK_CATEGORY_DEPLOYMENT));
}
void AbstractRemoteLinuxDeployStep::handleFinished()
diff --git a/src/plugins/remotelinux/abstractremotelinuxrunsupport.cpp b/src/plugins/remotelinux/abstractremotelinuxrunsupport.cpp
index 6424cb80c8..b36c8390ed 100644
--- a/src/plugins/remotelinux/abstractremotelinuxrunsupport.cpp
+++ b/src/plugins/remotelinux/abstractremotelinuxrunsupport.cpp
@@ -34,7 +34,7 @@
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/devicesupport/deviceapplicationrunner.h>
#include <projectexplorer/devicesupport/deviceusedportsgatherer.h>
-
+#include <utils/environment.h>
#include <utils/portlist.h>
using namespace ProjectExplorer;
@@ -50,7 +50,8 @@ public:
device(DeviceKitInformation::device(runConfig->target()->kit())),
remoteFilePath(runConfig->remoteExecutableFilePath()),
arguments(runConfig->arguments()),
- commandPrefix(runConfig->commandPrefix())
+ environment(runConfig->environment()),
+ workingDir(runConfig->workingDirectory())
{
}
@@ -60,8 +61,9 @@ public:
const ProjectExplorer::IDevice::ConstPtr device;
Utils::PortList portList;
const QString remoteFilePath;
- const QString arguments;
- const QString commandPrefix;
+ const QStringList arguments;
+ const Utils::Environment environment;
+ const QString workingDir;
};
} // namespace Internal
@@ -138,11 +140,8 @@ void AbstractRemoteLinuxRunSupport::setFinished()
{
if (d->state == Inactive)
return;
- if (d->state == Running) {
- const QString stopCommand
- = d->device->processSupport()->killProcessByNameCommandLine(d->remoteFilePath);
- d->appRunner.stop(stopCommand.toUtf8());
- }
+ if (d->state == Running)
+ d->appRunner.stop();
d->state = Inactive;
}
@@ -156,19 +155,24 @@ bool AbstractRemoteLinuxRunSupport::setPort(int &port)
return true;
}
-QString AbstractRemoteLinuxRunSupport::arguments() const
+QStringList AbstractRemoteLinuxRunSupport::arguments() const
{
return d->arguments;
}
-QString AbstractRemoteLinuxRunSupport::commandPrefix() const
+QString AbstractRemoteLinuxRunSupport::remoteFilePath() const
{
- return d->commandPrefix;
+ return d->remoteFilePath;
}
-QString AbstractRemoteLinuxRunSupport::remoteFilePath() const
+Utils::Environment AbstractRemoteLinuxRunSupport::environment() const
{
- return d->remoteFilePath;
+ return d->environment;
+}
+
+QString AbstractRemoteLinuxRunSupport::workingDirectory() const
+{
+ return d->workingDir;
}
const IDevice::ConstPtr AbstractRemoteLinuxRunSupport::device() const
diff --git a/src/plugins/remotelinux/abstractremotelinuxrunsupport.h b/src/plugins/remotelinux/abstractremotelinuxrunsupport.h
index a7a954681b..c052a7a3c3 100644
--- a/src/plugins/remotelinux/abstractremotelinuxrunsupport.h
+++ b/src/plugins/remotelinux/abstractremotelinuxrunsupport.h
@@ -41,6 +41,8 @@ class DeviceApplicationHelperAction;
class DeviceApplicationRunner;
}
+namespace Utils { class Environment; }
+
namespace RemoteLinux {
class RemoteLinuxRunConfiguration;
@@ -79,9 +81,10 @@ protected:
void setFinished();
bool setPort(int &port);
- QString arguments() const;
- QString commandPrefix() const;
+ QStringList arguments() const;
QString remoteFilePath() const;
+ Utils::Environment environment() const;
+ QString workingDirectory() const;
const ProjectExplorer::IDevice::ConstPtr device() const;
void reset();
diff --git a/src/plugins/remotelinux/genericdirectuploadstep.cpp b/src/plugins/remotelinux/genericdirectuploadstep.cpp
index 70e991cffd..9fe297cd53 100644
--- a/src/plugins/remotelinux/genericdirectuploadstep.cpp
+++ b/src/plugins/remotelinux/genericdirectuploadstep.cpp
@@ -149,7 +149,7 @@ bool GenericDirectUploadStep::incrementalDeployment() const
Core::Id GenericDirectUploadStep::stepId()
{
- return Core::Id("RemoteLinux.DirectUploadStep");
+ return "RemoteLinux.DirectUploadStep";
}
QString GenericDirectUploadStep::displayName()
diff --git a/src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.cpp b/src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.cpp
index 9c94f21a70..34959f4a1c 100644
--- a/src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.cpp
+++ b/src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.cpp
@@ -60,6 +60,7 @@ GenericLinuxDeviceConfigurationWidget::GenericLinuxDeviceConfigurationWidget(
connect(m_ui->showPasswordCheckBox, SIGNAL(toggled(bool)), this, SLOT(showPassword(bool)));
connect(m_ui->portsLineEdit, SIGNAL(editingFinished()), this, SLOT(handleFreePortsChanged()));
connect(m_ui->createKeyButton, SIGNAL(clicked()), SLOT(createNewKey()));
+ connect(m_ui->gdbServerLineEdit, SIGNAL(editingFinished()), SLOT(gdbServerEditingFinished()));
initGui();
}
@@ -74,8 +75,8 @@ void GenericLinuxDeviceConfigurationWidget::authenticationTypeChanged()
SshConnectionParameters sshParams = device()->sshParameters();
const bool usePassword = m_ui->passwordButton->isChecked();
sshParams.authenticationType = usePassword
- ? SshConnectionParameters::AuthenticationByPassword
- : SshConnectionParameters::AuthenticationByKey;
+ ? SshConnectionParameters::AuthenticationTypeTryAllPasswordBasedMethods
+ : SshConnectionParameters::AuthenticationTypePublicKey;
device()->setSshParameters(sshParams);
m_ui->pwdLineEdit->setEnabled(usePassword);
m_ui->passwordLabel->setEnabled(usePassword);
@@ -125,6 +126,11 @@ void GenericLinuxDeviceConfigurationWidget::keyFileEditingFinished()
device()->setSshParameters(sshParams);
}
+void GenericLinuxDeviceConfigurationWidget::gdbServerEditingFinished()
+{
+ device()->setDebugServerPath(m_ui->gdbServerLineEdit->text());
+}
+
void GenericLinuxDeviceConfigurationWidget::handleFreePortsChanged()
{
device()->setFreePorts(PortList::fromString(m_ui->portsLineEdit->text()));
@@ -159,6 +165,7 @@ void GenericLinuxDeviceConfigurationWidget::updateDeviceFromUi()
passwordEditingFinished();
keyFileEditingFinished();
handleFreePortsChanged();
+ gdbServerEditingFinished();
}
void GenericLinuxDeviceConfigurationWidget::updatePortsWarningLabel()
@@ -183,7 +190,7 @@ void GenericLinuxDeviceConfigurationWidget::initGui()
const SshConnectionParameters &sshParams = device()->sshParameters();
- if (sshParams.authenticationType == SshConnectionParameters::AuthenticationByPassword)
+ if (sshParams.authenticationType != SshConnectionParameters::AuthenticationTypePublicKey)
m_ui->passwordButton->setChecked(true);
else
m_ui->keyButton->setChecked(true);
@@ -199,5 +206,6 @@ void GenericLinuxDeviceConfigurationWidget::initGui()
m_ui->pwdLineEdit->setText(sshParams.password);
m_ui->keyFileLineEdit->setPath(sshParams.privateKeyFile);
m_ui->showPasswordCheckBox->setChecked(false);
+ m_ui->gdbServerLineEdit->setText(device()->debugServerPath());
updatePortsWarningLabel();
}
diff --git a/src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.h b/src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.h
index 420f4a761d..db0a6777d2 100644
--- a/src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.h
+++ b/src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.h
@@ -58,6 +58,7 @@ private slots:
void userNameEditingFinished();
void passwordEditingFinished();
void keyFileEditingFinished();
+ void gdbServerEditingFinished();
void showPassword(bool showClearText);
void handleFreePortsChanged();
void setPrivateKey(const QString &path);
diff --git a/src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.ui b/src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.ui
index a1b2dbea5c..1d935a9c2c 100644
--- a/src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.ui
+++ b/src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.ui
@@ -7,7 +7,7 @@
<x>0</x>
<y>0</y>
<width>393</width>
- <height>206</height>
+ <height>321</height>
</rect>
</property>
<property name="windowTitle">
@@ -17,7 +17,16 @@
<property name="fieldGrowthPolicy">
<enum>QFormLayout::FieldsStayAtSizeHint</enum>
</property>
- <property name="margin">
+ <property name="leftMargin">
+ <number>0</number>
+ </property>
+ <property name="topMargin">
+ <number>0</number>
+ </property>
+ <property name="rightMargin">
+ <number>0</number>
+ </property>
+ <property name="bottomMargin">
<number>0</number>
</property>
<item row="1" column="0">
@@ -30,7 +39,16 @@
<item row="1" column="1">
<widget class="QWidget" name="authTypeButtonsWidget" native="true">
<layout class="QHBoxLayout" name="horizontalLayout_3">
- <property name="margin">
+ <property name="leftMargin">
+ <number>0</number>
+ </property>
+ <property name="topMargin">
+ <number>0</number>
+ </property>
+ <property name="rightMargin">
+ <number>0</number>
+ </property>
+ <property name="bottomMargin">
<number>0</number>
</property>
<item>
@@ -233,6 +251,20 @@
<item row="0" column="1">
<widget class="QLabel" name="machineTypeValueLabel"/>
</item>
+ <item row="7" column="0">
+ <widget class="QLabel" name="gdbServerLabel">
+ <property name="text">
+ <string>GDB server executable:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="7" column="1">
+ <widget class="QLineEdit" name="gdbServerLineEdit">
+ <property name="placeholderText">
+ <string>Leave empty to look up executable in $PATH</string>
+ </property>
+ </widget>
+ </item>
</layout>
<zorder>passwordLabel</zorder>
<zorder>authTypeButtonsWidget</zorder>
@@ -244,6 +276,8 @@
<zorder>keyLabel</zorder>
<zorder>machineTypeLabel</zorder>
<zorder>machineTypeValueLabel</zorder>
+ <zorder>gdbServerLabel</zorder>
+ <zorder>gdbServerLineEdit</zorder>
</widget>
<customwidgets>
<customwidget>
diff --git a/src/plugins/remotelinux/genericlinuxdeviceconfigurationwizard.cpp b/src/plugins/remotelinux/genericlinuxdeviceconfigurationwizard.cpp
index add6ab5909..8ad502a052 100644
--- a/src/plugins/remotelinux/genericlinuxdeviceconfigurationwizard.cpp
+++ b/src/plugins/remotelinux/genericlinuxdeviceconfigurationwizard.cpp
@@ -31,8 +31,6 @@
#include "genericlinuxdeviceconfigurationwizardpages.h"
#include "linuxdevice.h"
-#include "linuxdevicetestdialog.h"
-#include "linuxdevicetester.h"
#include "remotelinux_constants.h"
#include <utils/portlist.h>
@@ -83,7 +81,7 @@ IDevice::Ptr GenericLinuxDeviceConfigurationWizard::device()
sshParams.port = 22;
sshParams.timeout = 10;
sshParams.authenticationType = d->setupPage.authenticationType();
- if (sshParams.authenticationType == SshConnectionParameters::AuthenticationByPassword)
+ if (sshParams.authenticationType != SshConnectionParameters::AuthenticationTypePublicKey)
sshParams.password = d->setupPage.password();
else
sshParams.privateKeyFile = d->setupPage.privateKeyFilePath();
@@ -91,10 +89,6 @@ IDevice::Ptr GenericLinuxDeviceConfigurationWizard::device()
Core::Id(Constants::GenericLinuxOsType), IDevice::Hardware);
device->setFreePorts(Utils::PortList::fromString(QLatin1String("10000-10100")));
device->setSshParameters(sshParams);
- // Might be called after accept.
- QWidget *parent = isVisible() ? this : static_cast<QWidget *>(0);
- LinuxDeviceTestDialog dlg(device, new GenericLinuxDeviceTester(this), parent);
- dlg.exec();
return device;
}
diff --git a/src/plugins/remotelinux/genericlinuxdeviceconfigurationwizardpages.cpp b/src/plugins/remotelinux/genericlinuxdeviceconfigurationwizardpages.cpp
index d187773a19..a64c3ba05e 100644
--- a/src/plugins/remotelinux/genericlinuxdeviceconfigurationwizardpages.cpp
+++ b/src/plugins/remotelinux/genericlinuxdeviceconfigurationwizardpages.cpp
@@ -86,7 +86,7 @@ void GenericLinuxDeviceConfigurationWizardSetupPage::initializePage()
bool GenericLinuxDeviceConfigurationWizardSetupPage::isComplete() const
{
return !configurationName().isEmpty() && !hostName().isEmpty() && !userName().isEmpty()
- && (authenticationType() == SshConnectionParameters::AuthenticationByPassword
+ && (authenticationType() != SshConnectionParameters::AuthenticationTypePublicKey
|| d->ui.privateKeyPathChooser->isValid());
}
@@ -108,8 +108,8 @@ QString GenericLinuxDeviceConfigurationWizardSetupPage::userName() const
SshConnectionParameters::AuthenticationType GenericLinuxDeviceConfigurationWizardSetupPage::authenticationType() const
{
return d->ui.passwordButton->isChecked()
- ? SshConnectionParameters::AuthenticationByPassword
- : SshConnectionParameters::AuthenticationByKey;
+ ? SshConnectionParameters::AuthenticationTypeTryAllPasswordBasedMethods
+ : SshConnectionParameters::AuthenticationTypePublicKey;
}
QString GenericLinuxDeviceConfigurationWizardSetupPage::password() const
@@ -144,8 +144,8 @@ QString GenericLinuxDeviceConfigurationWizardSetupPage::defaultPassWord() const
void GenericLinuxDeviceConfigurationWizardSetupPage::handleAuthTypeChanged()
{
- d->ui.passwordLineEdit->setEnabled(authenticationType() == SshConnectionParameters::AuthenticationByPassword);
- d->ui.privateKeyPathChooser->setEnabled(authenticationType() == SshConnectionParameters::AuthenticationByKey);
+ d->ui.passwordLineEdit->setEnabled(authenticationType() != SshConnectionParameters::AuthenticationTypePublicKey);
+ d->ui.privateKeyPathChooser->setEnabled(!d->ui.passwordLineEdit->isEnabled());
emit completeChanged();
}
diff --git a/src/plugins/remotelinux/linuxdevice.cpp b/src/plugins/remotelinux/linuxdevice.cpp
index 8c530ac3ac..b68f6c0c9c 100644
--- a/src/plugins/remotelinux/linuxdevice.cpp
+++ b/src/plugins/remotelinux/linuxdevice.cpp
@@ -30,14 +30,19 @@
#include "linuxdevice.h"
#include "genericlinuxdeviceconfigurationwidget.h"
-#include "linuxdevicetestdialog.h"
+#include "linuxdeviceprocess.h"
+#include "linuxdevicetester.h"
#include "publickeydeploymentdialog.h"
#include "remotelinux_constants.h"
+#include "remotelinuxsignaloperation.h"
#include <coreplugin/id.h>
#include <projectexplorer/devicesupport/sshdeviceprocesslist.h>
+#include <ssh/sshremoteprocessrunner.h>
#include <utils/qtcassert.h>
+#include <QTimer>
+
using namespace ProjectExplorer;
namespace RemoteLinux {
@@ -72,9 +77,9 @@ private:
"done").arg(QLatin1String(Delimiter0)).arg(QLatin1String(Delimiter1));
}
- QList<DeviceProcess> buildProcessList(const QString &listProcessesReply) const
+ QList<DeviceProcessItem> buildProcessList(const QString &listProcessesReply) const
{
- QList<DeviceProcess> processes;
+ QList<DeviceProcessItem> processes;
const QStringList lines = listProcessesReply.split(QString::fromLatin1(Delimiter0)
+ QString::fromLatin1(Delimiter1), QString::SkipEmptyParts);
foreach (const QString &line, lines) {
@@ -104,7 +109,7 @@ private:
+ QLatin1Char(']');
}
- DeviceProcess process;
+ DeviceProcessItem process;
process.pid = pid;
process.cmdLine = command;
process.exe = elements.at(3);
@@ -116,23 +121,6 @@ private:
}
};
-
-QString LinuxDeviceProcessSupport::killProcessByPidCommandLine(int pid) const
-{
- return QLatin1String("kill -9 ") + QString::number(pid);
-}
-
-QString LinuxDeviceProcessSupport::killProcessByNameCommandLine(const QString &filePath) const
-{
- return QString::fromLatin1("cd /proc; for pid in `ls -d [0123456789]*`; "
- "do "
- "if [ \"`readlink /proc/$pid/exe`\" = \"%1\" ]; then "
- " kill $pid; sleep 1; kill -9 $pid; "
- "fi; "
- "done").arg(filePath);
-}
-
-
class LinuxPortsGatheringMethod : public ProjectExplorer::PortsGatheringMethod
{
QByteArray commandLine(QAbstractSocket::NetworkLayerProtocol protocol) const
@@ -192,30 +180,25 @@ ProjectExplorer::IDeviceWidget *LinuxDevice::createWidget()
QList<Core::Id> LinuxDevice::actionIds() const
{
- return QList<Core::Id>() << Core::Id(Constants::GenericTestDeviceActionId)
- << Core::Id(Constants::GenericDeployKeyToDeviceActionId);
+ return QList<Core::Id>() << Core::Id(Constants::GenericDeployKeyToDeviceActionId);
}
QString LinuxDevice::displayNameForActionId(Core::Id actionId) const
{
QTC_ASSERT(actionIds().contains(actionId), return QString());
- if (actionId == Constants::GenericTestDeviceActionId)
- return tr("Test");
if (actionId == Constants::GenericDeployKeyToDeviceActionId)
return tr("Deploy Public Key...");
return QString(); // Can't happen.
}
-void LinuxDevice::executeAction(Core::Id actionId, QWidget *parent) const
+void LinuxDevice::executeAction(Core::Id actionId, QWidget *parent)
{
QTC_ASSERT(actionIds().contains(actionId), return);
QDialog *d = 0;
const LinuxDevice::ConstPtr device = sharedFromThis().staticCast<const LinuxDevice>();
- if (actionId == Constants::GenericTestDeviceActionId)
- d = new LinuxDeviceTestDialog(device, createDeviceTester(), parent);
- else if (actionId == Constants::GenericDeployKeyToDeviceActionId)
+ if (actionId == Constants::GenericDeployKeyToDeviceActionId)
d = PublicKeyDeploymentDialog::createDialog(device, parent);
if (d)
d->exec();
@@ -244,9 +227,9 @@ ProjectExplorer::IDevice::Ptr LinuxDevice::clone() const
return Ptr(new LinuxDevice(*this));
}
-DeviceProcessSupport::Ptr LinuxDevice::processSupport() const
+DeviceProcess *LinuxDevice::createProcess(QObject *parent) const
{
- return DeviceProcessSupport::Ptr(new LinuxDeviceProcessSupport);
+ return new LinuxDeviceProcess(sharedFromThis(), parent);
}
bool LinuxDevice::canAutoDetectPorts() const
@@ -264,9 +247,14 @@ DeviceProcessList *LinuxDevice::createProcessListModel(QObject *parent) const
return new LinuxDeviceProcessList(sharedFromThis(), parent);
}
-AbstractLinuxDeviceTester *LinuxDevice::createDeviceTester() const
+DeviceTester *LinuxDevice::createDeviceTester() const
{
return new GenericLinuxDeviceTester;
}
+DeviceProcessSignalOperation::Ptr LinuxDevice::signalOperation() const
+{
+ return DeviceProcessSignalOperation::Ptr(new RemoteLinuxSignalOperation(sshParameters()));
+}
+
} // namespace RemoteLinux
diff --git a/src/plugins/remotelinux/linuxdevice.h b/src/plugins/remotelinux/linuxdevice.h
index 0ec84cd44e..8f9d9b1c64 100644
--- a/src/plugins/remotelinux/linuxdevice.h
+++ b/src/plugins/remotelinux/linuxdevice.h
@@ -41,14 +41,6 @@ namespace Utils { class PortList; }
namespace RemoteLinux {
namespace Internal { class LinuxDevicePrivate; }
-class AbstractLinuxDeviceTester;
-
-class REMOTELINUX_EXPORT LinuxDeviceProcessSupport : public ProjectExplorer::DeviceProcessSupport
-{
-public:
- QString killProcessByPidCommandLine(int pid) const;
- QString killProcessByNameCommandLine(const QString &filePath) const;
-};
class REMOTELINUX_EXPORT LinuxDevice : public ProjectExplorer::IDevice
{
@@ -66,15 +58,18 @@ public:
ProjectExplorer::IDeviceWidget *createWidget();
QList<Core::Id> actionIds() const;
QString displayNameForActionId(Core::Id actionId) const;
- void executeAction(Core::Id actionId, QWidget *parent) const;
+ void executeAction(Core::Id actionId, QWidget *parent);
ProjectExplorer::IDevice::Ptr clone() const;
- ProjectExplorer::DeviceProcessSupport::Ptr processSupport() const;
+ bool canCreateProcess() const { return true; }
+ ProjectExplorer::DeviceProcess *createProcess(QObject *parent) const;
bool canAutoDetectPorts() const;
ProjectExplorer::PortsGatheringMethod::Ptr portsGatheringMethod() const;
bool canCreateProcessModel() const { return true; }
ProjectExplorer::DeviceProcessList *createProcessListModel(QObject *parent) const;
- virtual AbstractLinuxDeviceTester *createDeviceTester() const;
+ bool hasDeviceTester() const { return true; }
+ ProjectExplorer::DeviceTester *createDeviceTester() const;
+ ProjectExplorer::DeviceProcessSignalOperation::Ptr signalOperation() const;
protected:
LinuxDevice() {}
diff --git a/src/plugins/remotelinux/linuxdeviceprocess.cpp b/src/plugins/remotelinux/linuxdeviceprocess.cpp
new file mode 100644
index 0000000000..2dd8e792a7
--- /dev/null
+++ b/src/plugins/remotelinux/linuxdeviceprocess.cpp
@@ -0,0 +1,84 @@
+/****************************************************************************
+**
+** 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 "linuxdeviceprocess.h"
+
+#include <utils/environment.h>
+#include <utils/qtcprocess.h>
+
+namespace RemoteLinux {
+
+static QString quote(const QString &s) { return Utils::QtcProcess::quoteArgUnix(s); }
+
+LinuxDeviceProcess::LinuxDeviceProcess(const QSharedPointer<const ProjectExplorer::IDevice> &device,
+ QObject *parent)
+ : ProjectExplorer::SshDeviceProcess(device, parent)
+{
+ setEnvironment(Utils::Environment(Utils::OsTypeLinux));
+}
+
+void LinuxDeviceProcess::setRcFilesToSource(const QStringList &filePaths)
+{
+ m_rcFilesToSource = filePaths;
+}
+
+void LinuxDeviceProcess::setWorkingDirectory(const QString &directory)
+{
+ m_workingDir = directory;
+}
+
+QString LinuxDeviceProcess::fullCommandLine() const
+{
+ QString fullCommandLine;
+ foreach (const QString &filePath, rcFilesToSource())
+ fullCommandLine += QString::fromLatin1("test -f %1 && source %1;").arg(filePath);
+ if (!m_workingDir.isEmpty()) {
+ fullCommandLine.append(QLatin1String("cd ")).append(quote(m_workingDir))
+ .append(QLatin1String(" && "));
+ }
+ const QString envString = environment().toStringList().join(QLatin1String(" "));
+ if (!envString.isEmpty())
+ fullCommandLine.append(QLatin1Char(' ')).append(envString);
+ if (!fullCommandLine.isEmpty())
+ fullCommandLine += QLatin1Char(' ');
+ fullCommandLine.append(quote(executable()));
+ if (!arguments().isEmpty()) {
+ fullCommandLine.append(QLatin1Char(' '));
+ fullCommandLine.append(Utils::QtcProcess::joinArgsUnix(arguments()));
+ }
+ return fullCommandLine;
+}
+
+QStringList LinuxDeviceProcess::rcFilesToSource() const
+{
+ if (!m_rcFilesToSource.isEmpty())
+ return m_rcFilesToSource;
+ return QStringList() << QLatin1String("/etc/profile") << QLatin1String("$HOME/.profile");
+}
+
+} // namespace RemoteLinux
diff --git a/src/plugins/remotelinux/linuxdeviceprocess.h b/src/plugins/remotelinux/linuxdeviceprocess.h
new file mode 100644
index 0000000000..c42e1e7c97
--- /dev/null
+++ b/src/plugins/remotelinux/linuxdeviceprocess.h
@@ -0,0 +1,64 @@
+/****************************************************************************
+**
+** 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 QTC_LINUXDEVICEPROCESS_H
+#define QTC_LINUXDEVICEPROCESS_H
+
+#include "remotelinux_export.h"
+
+#include <projectexplorer/devicesupport/sshdeviceprocess.h>
+
+#include <QStringList>
+
+namespace RemoteLinux {
+
+class REMOTELINUX_EXPORT LinuxDeviceProcess : public ProjectExplorer::SshDeviceProcess
+{
+ Q_OBJECT
+public:
+ explicit LinuxDeviceProcess(const QSharedPointer<const ProjectExplorer::IDevice> &device,
+ QObject *parent = 0);
+
+ // Files to source before executing the command (if they exist). Overrides the default.
+ void setRcFilesToSource(const QStringList &filePaths);
+
+ void setWorkingDirectory(const QString &directory);
+
+private:
+ QString fullCommandLine() const;
+
+ QStringList rcFilesToSource() const;
+
+ QStringList m_rcFilesToSource;
+ QString m_workingDir;
+};
+
+} // namespace RemoteLinux
+
+#endif // Include guard.
diff --git a/src/plugins/remotelinux/linuxdevicetester.cpp b/src/plugins/remotelinux/linuxdevicetester.cpp
index 9f2fa97143..7b30be03a9 100644
--- a/src/plugins/remotelinux/linuxdevicetester.cpp
+++ b/src/plugins/remotelinux/linuxdevicetester.cpp
@@ -61,13 +61,8 @@ public:
using namespace Internal;
-AbstractLinuxDeviceTester::AbstractLinuxDeviceTester(QObject *parent) : QObject(parent)
-{
-}
-
-
GenericLinuxDeviceTester::GenericLinuxDeviceTester(QObject *parent)
- : AbstractLinuxDeviceTester(parent), d(new GenericLinuxDeviceTesterPrivate)
+ : DeviceTester(parent), d(new GenericLinuxDeviceTesterPrivate)
{
}
diff --git a/src/plugins/remotelinux/linuxdevicetester.h b/src/plugins/remotelinux/linuxdevicetester.h
index 4ecd8b9af1..8c3070b0bf 100644
--- a/src/plugins/remotelinux/linuxdevicetester.h
+++ b/src/plugins/remotelinux/linuxdevicetester.h
@@ -44,27 +44,7 @@ namespace Internal {
class GenericLinuxDeviceTesterPrivate;
}
-class REMOTELINUX_EXPORT AbstractLinuxDeviceTester : public QObject
-{
- Q_OBJECT
-
-public:
- enum TestResult { TestSuccess, TestFailure };
-
- virtual void testDevice(const ProjectExplorer::IDevice::ConstPtr &deviceConfiguration) = 0;
- virtual void stopTest() = 0;
-
-signals:
- void progressMessage(const QString &message);
- void errorMessage(const QString &message);
- void finished(RemoteLinux::AbstractLinuxDeviceTester::TestResult result);
-
-protected:
- explicit AbstractLinuxDeviceTester(QObject *parent = 0);
-};
-
-
-class REMOTELINUX_EXPORT GenericLinuxDeviceTester : public AbstractLinuxDeviceTester
+class REMOTELINUX_EXPORT GenericLinuxDeviceTester : public ProjectExplorer::DeviceTester
{
Q_OBJECT
@@ -85,7 +65,7 @@ private slots:
void handlePortListReady();
private:
- void setFinished(TestResult result);
+ void setFinished(ProjectExplorer::DeviceTester::TestResult result);
Internal::GenericLinuxDeviceTesterPrivate * const d;
};
diff --git a/src/plugins/remotelinux/remotelinux.pro b/src/plugins/remotelinux/remotelinux.pro
index 311cb6d127..b6d76fc30f 100644
--- a/src/plugins/remotelinux/remotelinux.pro
+++ b/src/plugins/remotelinux/remotelinux.pro
@@ -35,7 +35,6 @@ HEADERS += \
packageuploader.h \
linuxdevicetester.h \
remotelinux_constants.h \
- linuxdevicetestdialog.h \
remotelinuxenvironmentreader.h \
sshkeydeployer.h \
typespecificdeviceconfigurationlistmodel.h \
@@ -48,7 +47,9 @@ HEADERS += \
remotelinuxcheckforfreediskspacestep.h \
remotelinuxdeploymentdatamodel.h \
remotelinuxanalyzesupport.h \
- abstractremotelinuxrunsupport.h
+ abstractremotelinuxrunsupport.h \
+ linuxdeviceprocess.h \
+ remotelinuxsignaloperation.h
SOURCES += \
embeddedlinuxqtversion.cpp \
@@ -81,7 +82,6 @@ SOURCES += \
remotelinuxpackageinstaller.cpp \
packageuploader.cpp \
linuxdevicetester.cpp \
- linuxdevicetestdialog.cpp \
remotelinuxenvironmentreader.cpp \
sshkeydeployer.cpp \
typespecificdeviceconfigurationlistmodel.cpp \
@@ -94,11 +94,12 @@ SOURCES += \
remotelinuxcheckforfreediskspacestep.cpp \
remotelinuxdeploymentdatamodel.cpp \
remotelinuxanalyzesupport.cpp \
- abstractremotelinuxrunsupport.cpp
+ abstractremotelinuxrunsupport.cpp \
+ linuxdeviceprocess.cpp \
+ remotelinuxsignaloperation.cpp
FORMS += \
genericlinuxdeviceconfigurationwizardsetuppage.ui \
- linuxdevicetestdialog.ui \
remotelinuxdeployconfigurationwidget.ui \
genericlinuxdeviceconfigurationwidget.ui \
remotelinuxcheckforfreediskspacestepwidget.ui
diff --git a/src/plugins/remotelinux/remotelinux.qbs b/src/plugins/remotelinux/remotelinux.qbs
index e241c1617d..536e9bfcc8 100644
--- a/src/plugins/remotelinux/remotelinux.qbs
+++ b/src/plugins/remotelinux/remotelinux.qbs
@@ -47,9 +47,8 @@ QtcPlugin {
"genericremotelinuxdeploystepfactory.h",
"linuxdevice.cpp",
"linuxdevice.h",
- "linuxdevicetestdialog.cpp",
- "linuxdevicetestdialog.h",
- "linuxdevicetestdialog.ui",
+ "linuxdeviceprocess.cpp",
+ "linuxdeviceprocess.h",
"linuxdevicetester.cpp",
"linuxdevicetester.h",
"packageuploader.cpp",
@@ -101,6 +100,8 @@ QtcPlugin {
"remotelinuxruncontrol.h",
"remotelinuxruncontrolfactory.cpp",
"remotelinuxruncontrolfactory.h",
+ "remotelinuxsignaloperation.cpp",
+ "remotelinuxsignaloperation.h",
"remotelinuxutils.cpp",
"remotelinuxutils.h",
"sshkeydeployer.cpp",
diff --git a/src/plugins/remotelinux/remotelinux_constants.h b/src/plugins/remotelinux/remotelinux_constants.h
index 0cfdfa5200..42041f3ce5 100644
--- a/src/plugins/remotelinux/remotelinux_constants.h
+++ b/src/plugins/remotelinux/remotelinux_constants.h
@@ -34,7 +34,6 @@ namespace Constants {
const char GenericLinuxOsType[] = "GenericLinuxOsType";
-const char GenericTestDeviceActionId[] = "RemoteLinux.GenericTestDeviceAction";
const char GenericDeployKeyToDeviceActionId[] = "RemoteLinux.GenericDeployKeyToDeviceAction";
const char EMBEDDED_LINUX_QT[] = "RemoteLinux.EmbeddedLinuxQt";
diff --git a/src/plugins/remotelinux/remotelinuxanalyzesupport.cpp b/src/plugins/remotelinux/remotelinuxanalyzesupport.cpp
index 40125ce206..48680b861f 100644
--- a/src/plugins/remotelinux/remotelinuxanalyzesupport.cpp
+++ b/src/plugins/remotelinux/remotelinuxanalyzesupport.cpp
@@ -31,7 +31,7 @@
#include "remotelinuxrunconfiguration.h"
-#include <analyzerbase/ianalyzerengine.h>
+#include <analyzerbase/analyzerruncontrol.h>
#include <projectexplorer/buildconfiguration.h>
#include <projectexplorer/project.h>
@@ -55,14 +55,14 @@ namespace Internal {
class RemoteLinuxAnalyzeSupportPrivate
{
public:
- RemoteLinuxAnalyzeSupportPrivate(IAnalyzerEngine *engine, RunMode runMode)
- : engine(engine),
+ RemoteLinuxAnalyzeSupportPrivate(AnalyzerRunControl *rc, RunMode runMode)
+ : runControl(rc),
qmlProfiling(runMode == QmlProfilerRunMode),
qmlPort(-1)
{
}
- const QPointer<IAnalyzerEngine> engine;
+ const QPointer<AnalyzerRunControl> runControl;
bool qmlProfiling;
int qmlPort;
@@ -78,9 +78,9 @@ AnalyzerStartParameters RemoteLinuxAnalyzeSupport::startParameters(const RemoteL
{
AnalyzerStartParameters params;
if (runMode == QmlProfilerRunMode)
- params.startMode = StartQmlRemote;
+ params.startMode = StartLocal;
+ params.runMode = runMode;
params.connParams = DeviceKitInformation::device(runConfig->target()->kit())->sshParameters();
- params.analyzerCmdPrefix = runConfig->commandPrefix();
params.displayName = runConfig->displayName();
params.sysroot = SysRootKitInformation::sysRoot(runConfig->target()->kit()).toString();
params.analyzerHost = params.connParams.host;
@@ -89,11 +89,11 @@ AnalyzerStartParameters RemoteLinuxAnalyzeSupport::startParameters(const RemoteL
}
RemoteLinuxAnalyzeSupport::RemoteLinuxAnalyzeSupport(RemoteLinuxRunConfiguration *runConfig,
- IAnalyzerEngine *engine, RunMode runMode)
+ AnalyzerRunControl *engine, RunMode runMode)
: AbstractRemoteLinuxRunSupport(runConfig, engine),
d(new RemoteLinuxAnalyzeSupportPrivate(engine, runMode))
{
- connect(d->engine, SIGNAL(starting(const Analyzer::IAnalyzerEngine*)),
+ connect(d->runControl, SIGNAL(starting(const Analyzer::AnalyzerRunControl*)),
SLOT(handleRemoteSetupRequested()));
connect(&d->outputParser, SIGNAL(waitingForConnectionOnPort(quint16)),
SLOT(remoteIsRunning()));
@@ -106,16 +106,13 @@ RemoteLinuxAnalyzeSupport::~RemoteLinuxAnalyzeSupport()
void RemoteLinuxAnalyzeSupport::showMessage(const QString &msg, Utils::OutputFormat format)
{
- if (state() != Inactive && d->engine)
- d->engine->logApplicationMessage(msg, format);
+ if (state() != Inactive && d->runControl)
+ d->runControl->logApplicationMessage(msg, format);
d->outputParser.processOutput(msg);
}
void RemoteLinuxAnalyzeSupport::handleRemoteSetupRequested()
{
- if (d->engine->mode() != Analyzer::StartQmlRemote)
- return;
-
QTC_ASSERT(state() == Inactive, return);
showMessage(tr("Checking available ports...\n"), Utils::NormalMessageFormat);
@@ -142,11 +139,11 @@ void RemoteLinuxAnalyzeSupport::startExecution()
connect(runner, SIGNAL(reportProgress(QString)), SLOT(handleProgressReport(QString)));
connect(runner, SIGNAL(reportError(QString)), SLOT(handleAppRunnerError(QString)));
- const QString args = arguments()
- + QString::fromLocal8Bit(" -qmljsdebugger=port:%1,block").arg(d->qmlPort);
- const QString remoteCommandLine =
- QString::fromLatin1("%1 %2 %3").arg(commandPrefix()).arg(remoteFilePath()).arg(args);
- runner->start(device(), remoteCommandLine.toUtf8());
+ const QStringList args = arguments()
+ << QString::fromLocal8Bit("-qmljsdebugger=port:%1,block").arg(d->qmlPort);
+ runner->setWorkingDirectory(workingDirectory());
+ runner->setEnvironment(environment());
+ runner->start(device(), remoteFilePath(), args);
}
void RemoteLinuxAnalyzeSupport::handleAppRunnerError(const QString &error)
@@ -163,19 +160,17 @@ void RemoteLinuxAnalyzeSupport::handleAppRunnerFinished(bool success)
reset();
if (!success)
showMessage(tr("Failure running remote process."), Utils::NormalMessageFormat);
- d->engine->notifyRemoteFinished(success);
+ d->runControl->notifyRemoteFinished(success);
}
void RemoteLinuxAnalyzeSupport::handleProfilingFinished()
{
- if (d->engine->mode() != Analyzer::StartQmlRemote)
- return;
setFinished();
}
void RemoteLinuxAnalyzeSupport::remoteIsRunning()
{
- d->engine->notifyRemoteSetupDone(d->qmlPort);
+ d->runControl->notifyRemoteSetupDone(d->qmlPort);
}
void RemoteLinuxAnalyzeSupport::handleRemoteOutput(const QByteArray &output)
@@ -189,7 +184,7 @@ void RemoteLinuxAnalyzeSupport::handleRemoteErrorOutput(const QByteArray &output
{
QTC_ASSERT(state() != GatheringPorts, return);
- if (!d->engine)
+ if (!d->runControl)
return;
showMessage(QString::fromUtf8(output), Utils::StdErrFormat);
diff --git a/src/plugins/remotelinux/remotelinuxanalyzesupport.h b/src/plugins/remotelinux/remotelinuxanalyzesupport.h
index 98f713828c..de9b7ab397 100644
--- a/src/plugins/remotelinux/remotelinuxanalyzesupport.h
+++ b/src/plugins/remotelinux/remotelinuxanalyzesupport.h
@@ -37,7 +37,7 @@
namespace Analyzer {
class AnalyzerStartParameters;
-class IAnalyzerEngine;
+class AnalyzerRunControl;
}
namespace RemoteLinux {
@@ -53,7 +53,7 @@ public:
ProjectExplorer::RunMode runMode);
RemoteLinuxAnalyzeSupport(RemoteLinuxRunConfiguration *runConfig,
- Analyzer::IAnalyzerEngine *engine, ProjectExplorer::RunMode runMode);
+ Analyzer::AnalyzerRunControl *engine, ProjectExplorer::RunMode runMode);
~RemoteLinuxAnalyzeSupport();
protected:
diff --git a/src/plugins/remotelinux/remotelinuxcheckforfreediskspacestep.cpp b/src/plugins/remotelinux/remotelinuxcheckforfreediskspacestep.cpp
index ab0675bdb9..564062db94 100644
--- a/src/plugins/remotelinux/remotelinuxcheckforfreediskspacestep.cpp
+++ b/src/plugins/remotelinux/remotelinuxcheckforfreediskspacestep.cpp
@@ -176,7 +176,7 @@ AbstractRemoteLinuxDeployService *RemoteLinuxCheckForFreeDiskSpaceStep::deploySe
Core::Id RemoteLinuxCheckForFreeDiskSpaceStep::stepId()
{
- return Core::Id("RemoteLinux.CheckForFreeDiskSpaceStep");
+ return "RemoteLinux.CheckForFreeDiskSpaceStep";
}
QString RemoteLinuxCheckForFreeDiskSpaceStep::stepDisplayName()
diff --git a/src/plugins/remotelinux/remotelinuxcustomcommanddeploymentstep.cpp b/src/plugins/remotelinux/remotelinuxcustomcommanddeploymentstep.cpp
index f0e288caf4..50eb359a38 100644
--- a/src/plugins/remotelinux/remotelinuxcustomcommanddeploymentstep.cpp
+++ b/src/plugins/remotelinux/remotelinuxcustomcommanddeploymentstep.cpp
@@ -184,7 +184,7 @@ RemoteLinuxCustomCommandDeployService *GenericRemoteLinuxCustomCommandDeployment
Core::Id GenericRemoteLinuxCustomCommandDeploymentStep::stepId()
{
- return Core::Id("RemoteLinux.GenericRemoteLinuxCustomCommandDeploymentStep");
+ return "RemoteLinux.GenericRemoteLinuxCustomCommandDeploymentStep";
}
QString GenericRemoteLinuxCustomCommandDeploymentStep::stepDisplayName()
diff --git a/src/plugins/remotelinux/remotelinuxdebugsupport.cpp b/src/plugins/remotelinux/remotelinuxdebugsupport.cpp
index 2ccecb0e5f..030df3661e 100644
--- a/src/plugins/remotelinux/remotelinuxdebugsupport.cpp
+++ b/src/plugins/remotelinux/remotelinuxdebugsupport.cpp
@@ -98,7 +98,7 @@ DebuggerStartParameters LinuxDeviceDebugSupport::startParameters(const RemoteLin
}
if (aspect->useCppDebugger()) {
params.languages |= CppLanguage;
- params.processArgs = runConfig->arguments();
+ params.processArgs = runConfig->arguments().join(QLatin1String(" "));
params.startMode = AttachToRemoteServer;
params.executable = runConfig->localExecutableFilePath();
params.remoteChannel = device->sshParameters().host + QLatin1String(":-1");
@@ -111,7 +111,7 @@ DebuggerStartParameters LinuxDeviceDebugSupport::startParameters(const RemoteLin
if (const Project *project = target->project()) {
params.projectSourceDirectory = project->projectDirectory();
if (const BuildConfiguration *buildConfig = target->activeBuildConfiguration())
- params.projectBuildDirectory = buildConfig->buildDirectory();
+ params.projectBuildDirectory = buildConfig->buildDirectory().toString();
params.projectSourceFiles = project->files(Project::ExcludeGeneratedFiles);
}
@@ -162,17 +162,25 @@ void LinuxDeviceDebugSupport::startExecution()
connect(runner, SIGNAL(remoteStdout(QByteArray)), SLOT(handleRemoteOutput(QByteArray)));
if (d->qmlDebugging && !d->cppDebugging)
connect(runner, SIGNAL(remoteProcessStarted()), SLOT(handleRemoteProcessStarted()));
- QString args = arguments();
- if (d->qmlDebugging)
- args += QString::fromLocal8Bit(" -qmljsdebugger=port:%1,block").arg(d->qmlPort);
- const QString remoteCommandLine = (d->qmlDebugging && !d->cppDebugging)
- ? QString::fromLatin1("%1 %2 %3").arg(commandPrefix()).arg(remoteFilePath()).arg(args)
- : QString::fromLatin1("%1 gdbserver :%2 %3 %4").arg(commandPrefix())
- .arg(d->gdbServerPort).arg(remoteFilePath()).arg(args);
+
+ QStringList args = arguments();
+ QString command;
+ if (d->qmlDebugging && !d->cppDebugging) {
+ command = remoteFilePath();
+ } else {
+ command = device()->debugServerPath();
+ if (command.isEmpty())
+ command = QLatin1String("gdbserver");
+ args.prepend(remoteFilePath());
+ args.prepend(QString::fromLatin1(":%1").arg(d->gdbServerPort));
+ }
+
connect(runner, SIGNAL(finished(bool)), SLOT(handleAppRunnerFinished(bool)));
connect(runner, SIGNAL(reportProgress(QString)), SLOT(handleProgressReport(QString)));
connect(runner, SIGNAL(reportError(QString)), SLOT(handleAppRunnerError(QString)));
- runner->start(device(), remoteCommandLine.toUtf8());
+ runner->setEnvironment(environment());
+ runner->setWorkingDirectory(workingDirectory());
+ runner->start(device(), command, args);
}
void LinuxDeviceDebugSupport::handleAppRunnerError(const QString &error)
diff --git a/src/plugins/remotelinux/remotelinuxdeployconfigurationfactory.cpp b/src/plugins/remotelinux/remotelinuxdeployconfigurationfactory.cpp
index 9e07ce27fe..ede7d7efd9 100644
--- a/src/plugins/remotelinux/remotelinuxdeployconfigurationfactory.cpp
+++ b/src/plugins/remotelinux/remotelinuxdeployconfigurationfactory.cpp
@@ -126,7 +126,7 @@ DeployConfiguration *RemoteLinuxDeployConfigurationFactory::clone(Target *parent
Core::Id RemoteLinuxDeployConfigurationFactory::genericDeployConfigurationId()
{
- return Core::Id("DeployToGenericLinux");
+ return "DeployToGenericLinux";
}
} // namespace Internal
diff --git a/src/plugins/remotelinux/remotelinuxenvironmentaspect.cpp b/src/plugins/remotelinux/remotelinuxenvironmentaspect.cpp
index 70b3da4884..11679b42aa 100644
--- a/src/plugins/remotelinux/remotelinuxenvironmentaspect.cpp
+++ b/src/plugins/remotelinux/remotelinuxenvironmentaspect.cpp
@@ -41,9 +41,9 @@ RemoteLinuxEnvironmentAspect::RemoteLinuxEnvironmentAspect(ProjectExplorer::RunC
ProjectExplorer::EnvironmentAspect(rc)
{ }
-RemoteLinuxEnvironmentAspect *RemoteLinuxEnvironmentAspect::clone(ProjectExplorer::RunConfiguration *parent) const
+RemoteLinuxEnvironmentAspect *RemoteLinuxEnvironmentAspect::create(ProjectExplorer::RunConfiguration *parent) const
{
- return new RemoteLinuxEnvironmentAspect(this, parent);
+ return new RemoteLinuxEnvironmentAspect(parent);
}
ProjectExplorer::RunConfigWidget *RemoteLinuxEnvironmentAspect::createConfigurationWidget()
@@ -101,10 +101,5 @@ QString RemoteLinuxEnvironmentAspect::userEnvironmentChangesAsString() const
return env.mid(0, env.size() - 1);
}
-RemoteLinuxEnvironmentAspect::RemoteLinuxEnvironmentAspect(const RemoteLinuxEnvironmentAspect *other,
- ProjectExplorer::RunConfiguration *parent) :
- ProjectExplorer::EnvironmentAspect(other, parent)
-{ }
-
} // namespace RemoteLinux
diff --git a/src/plugins/remotelinux/remotelinuxenvironmentaspect.h b/src/plugins/remotelinux/remotelinuxenvironmentaspect.h
index c177034360..ae1ac201c7 100644
--- a/src/plugins/remotelinux/remotelinuxenvironmentaspect.h
+++ b/src/plugins/remotelinux/remotelinuxenvironmentaspect.h
@@ -46,7 +46,7 @@ class REMOTELINUX_EXPORT RemoteLinuxEnvironmentAspect : public ProjectExplorer::
public:
RemoteLinuxEnvironmentAspect(ProjectExplorer::RunConfiguration *rc);
- RemoteLinuxEnvironmentAspect *clone(ProjectExplorer::RunConfiguration *parent) const;
+ RemoteLinuxEnvironmentAspect *create(ProjectExplorer::RunConfiguration *parent) const;
ProjectExplorer::RunConfigWidget *createConfigurationWidget();
QList<int> possibleBaseEnvironments() const;
@@ -66,8 +66,6 @@ private:
RemoteBaseEnvironment = 1
};
- RemoteLinuxEnvironmentAspect(const RemoteLinuxEnvironmentAspect *other, ProjectExplorer::RunConfiguration *parent);
-
Utils::Environment m_remoteEnvironment;
};
diff --git a/src/plugins/remotelinux/remotelinuxenvironmentaspectwidget.cpp b/src/plugins/remotelinux/remotelinuxenvironmentaspectwidget.cpp
index 69c0b57cc9..222c06f9ac 100644
--- a/src/plugins/remotelinux/remotelinuxenvironmentaspectwidget.cpp
+++ b/src/plugins/remotelinux/remotelinuxenvironmentaspectwidget.cpp
@@ -70,7 +70,7 @@ void RemoteLinuxEnvironmentAspectWidget::fetchEnvironment()
disconnect(button, SIGNAL(clicked()), this, SLOT(fetchEnvironment()));
connect(button, SIGNAL(clicked()), this, SLOT(stopFetchEnvironment()));
button->setText(tr("Cancel Fetch Operation"));
- deviceEnvReader->start(aspect()->runConfiguration()->environmentPreparationCommand());
+ deviceEnvReader->start();
}
void RemoteLinuxEnvironmentAspectWidget::fetchEnvironmentFinished()
diff --git a/src/plugins/remotelinux/remotelinuxenvironmentreader.cpp b/src/plugins/remotelinux/remotelinuxenvironmentreader.cpp
index 92101bed6f..2ffa21bdac 100644
--- a/src/plugins/remotelinux/remotelinuxenvironmentreader.cpp
+++ b/src/plugins/remotelinux/remotelinuxenvironmentreader.cpp
@@ -28,7 +28,7 @@
****************************************************************************/
#include "remotelinuxenvironmentreader.h"
-#include <ssh/sshremoteprocessrunner.h>
+#include <projectexplorer/devicesupport/deviceprocess.h>
#include <projectexplorer/devicesupport/idevice.h>
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/runconfiguration.h>
@@ -42,77 +42,73 @@ namespace Internal {
RemoteLinuxEnvironmentReader::RemoteLinuxEnvironmentReader(RunConfiguration *config, QObject *parent)
: QObject(parent)
, m_stop(false)
+ , m_env(Utils::OsTypeLinux)
, m_kit(config->target()->kit())
- , m_remoteProcessRunner(0)
+ , m_deviceProcess(0)
{
connect(config->target(), SIGNAL(kitChanged()),
this, SLOT(handleCurrentDeviceConfigChanged()));
}
-void RemoteLinuxEnvironmentReader::start(const QString &environmentSetupCommand)
+void RemoteLinuxEnvironmentReader::start()
{
IDevice::ConstPtr device = DeviceKitInformation::device(m_kit);
if (!device)
return;
m_stop = false;
- if (!m_remoteProcessRunner)
- m_remoteProcessRunner = new QSsh::SshRemoteProcessRunner(this);
- connect(m_remoteProcessRunner, SIGNAL(connectionError()), SLOT(handleConnectionFailure()));
- connect(m_remoteProcessRunner, SIGNAL(processClosed(int)), SLOT(remoteProcessFinished(int)));
- const QByteArray remoteCall
- = QString(environmentSetupCommand + QLatin1String("; env")).toUtf8();
- m_remoteProcessRunner->run(remoteCall, device->sshParameters());
+ m_deviceProcess = device->createProcess(this);
+ connect(m_deviceProcess, SIGNAL(error(QProcess::ProcessError)), SLOT(handleError()));
+ connect(m_deviceProcess, SIGNAL(finished()), SLOT(remoteProcessFinished()));
+ m_deviceProcess->start(QLatin1String("env"));
}
void RemoteLinuxEnvironmentReader::stop()
{
m_stop = true;
- if (m_remoteProcessRunner)
- disconnect(m_remoteProcessRunner, 0, this, 0);
+ destroyProcess();
}
-void RemoteLinuxEnvironmentReader::handleConnectionFailure()
+void RemoteLinuxEnvironmentReader::handleError()
{
if (m_stop)
return;
- disconnect(m_remoteProcessRunner, 0, this, 0);
- emit error(tr("Connection error: %1").arg(m_remoteProcessRunner->lastConnectionErrorString()));
- emit finished();
+ emit error(tr("Error: %1").arg(m_deviceProcess->errorString()));
+ setFinished();
}
void RemoteLinuxEnvironmentReader::handleCurrentDeviceConfigChanged()
{
- if (m_remoteProcessRunner)
- disconnect(m_remoteProcessRunner, 0, this, 0);
m_env.clear();
setFinished();
}
-void RemoteLinuxEnvironmentReader::remoteProcessFinished(int exitCode)
+void RemoteLinuxEnvironmentReader::remoteProcessFinished()
{
- Q_ASSERT(exitCode == QSsh::SshRemoteProcess::FailedToStart
- || exitCode == QSsh::SshRemoteProcess::CrashExit
- || exitCode == QSsh::SshRemoteProcess::NormalExit);
-
if (m_stop)
return;
- disconnect(m_remoteProcessRunner, 0, this, 0);
m_env.clear();
- if (exitCode == QSsh::SshRemoteProcess::NormalExit) {
- QString remoteOutput = QString::fromUtf8(m_remoteProcessRunner->readAllStandardOutput());
+ QString errorMessage;
+ if (m_deviceProcess->exitStatus() != QProcess::NormalExit) {
+ errorMessage = m_deviceProcess->errorString();
+ } else if (m_deviceProcess->exitCode() != 0) {
+ errorMessage = tr("Process exited with code %1.")
+ .arg(m_deviceProcess->exitCode());
+ }
+ if (!errorMessage.isEmpty()) {
+ errorMessage = tr("Error running 'env': %1").arg(errorMessage);
+ const QString remoteStderr
+ = QString::fromUtf8(m_deviceProcess->readAllStandardError()).trimmed();
+ if (!remoteStderr.isEmpty())
+ errorMessage += tr("\nRemote stderr was: '%1'").arg(remoteStderr);
+ emit error(errorMessage);
+ } else {
+ QString remoteOutput = QString::fromUtf8(m_deviceProcess->readAllStandardOutput());
if (!remoteOutput.isEmpty()) {
m_env = Utils::Environment(remoteOutput.split(QLatin1Char('\n'),
- QString::SkipEmptyParts));
+ QString::SkipEmptyParts), Utils::OsTypeLinux);
}
- } else {
- QString errorMsg = tr("Error running remote process: %1")
- .arg(m_remoteProcessRunner->processErrorString());
- QString remoteStderr = QString::fromUtf8(m_remoteProcessRunner->readAllStandardError());
- if (!remoteStderr.isEmpty())
- errorMsg += tr("\nRemote stderr was: '%1'").arg(remoteStderr);
- emit error(errorMsg);
}
setFinished();
}
@@ -123,5 +119,16 @@ void RemoteLinuxEnvironmentReader::setFinished()
emit finished();
}
+void RemoteLinuxEnvironmentReader::destroyProcess()
+{
+ if (!m_deviceProcess)
+ return;
+ m_deviceProcess->disconnect(this);
+ if (m_deviceProcess->state() != QProcess::NotRunning)
+ m_deviceProcess->terminate();
+ m_deviceProcess->deleteLater();
+ m_deviceProcess = 0;
+}
+
} // namespace Internal
} // namespace RemoteLinux
diff --git a/src/plugins/remotelinux/remotelinuxenvironmentreader.h b/src/plugins/remotelinux/remotelinuxenvironmentreader.h
index 7ee4c506ee..f8cb02f73f 100644
--- a/src/plugins/remotelinux/remotelinuxenvironmentreader.h
+++ b/src/plugins/remotelinux/remotelinuxenvironmentreader.h
@@ -35,12 +35,11 @@
#include <QObject>
namespace ProjectExplorer {
-class RunConfiguration;
+class DeviceProcess;
class Kit;
+class RunConfiguration;
}
-namespace QSsh { class SshRemoteProcessRunner; }
-
namespace RemoteLinux {
namespace Internal {
@@ -51,7 +50,7 @@ class RemoteLinuxEnvironmentReader : public QObject
public:
RemoteLinuxEnvironmentReader(ProjectExplorer::RunConfiguration *config, QObject *parent = 0);
- void start(const QString &environmentSetupCommand);
+ void start();
void stop();
Utils::Environment remoteEnvironment() const { return m_env; }
@@ -61,18 +60,18 @@ signals:
void error(const QString &error);
private slots:
- void handleConnectionFailure();
+ void handleError();
void handleCurrentDeviceConfigChanged();
-
- void remoteProcessFinished(int exitCode);
+ void remoteProcessFinished();
private:
void setFinished();
+ void destroyProcess();
bool m_stop;
Utils::Environment m_env;
ProjectExplorer::Kit *m_kit;
- QSsh::SshRemoteProcessRunner *m_remoteProcessRunner;
+ ProjectExplorer::DeviceProcess *m_deviceProcess;
};
} // namespace Internal
diff --git a/src/plugins/remotelinux/remotelinuxrunconfiguration.cpp b/src/plugins/remotelinux/remotelinuxrunconfiguration.cpp
index b691b790aa..5b872ecde7 100644
--- a/src/plugins/remotelinux/remotelinuxrunconfiguration.cpp
+++ b/src/plugins/remotelinux/remotelinuxrunconfiguration.cpp
@@ -38,9 +38,9 @@
#include <projectexplorer/project.h>
#include <projectexplorer/target.h>
#include <qtsupport/qtoutputformatter.h>
+#include <utils/qtcprocess.h>
using namespace ProjectExplorer;
-using namespace QSsh;
using namespace Utils;
namespace RemoteLinux {
@@ -74,7 +74,7 @@ public:
QString projectFilePath;
QString gdbPath;
- QString arguments;
+ QStringList arguments;
QString disabledReason;
bool useAlternateRemoteExecutable;
QString alternateRemoteExecutable;
@@ -143,6 +143,7 @@ OutputFormatter *RemoteLinuxRunConfiguration::createOutputFormatter() const
return new QtSupport::QtOutputFormatter(target()->project());
}
+
QVariantMap RemoteLinuxRunConfiguration::toMap() const
{
QVariantMap map(RunConfiguration::toMap());
@@ -160,7 +161,7 @@ bool RemoteLinuxRunConfiguration::fromMap(const QVariantMap &map)
if (!RunConfiguration::fromMap(map))
return false;
- d->arguments = map.value(QLatin1String(ArgumentsKey)).toString();
+ d->arguments = map.value(QLatin1String(ArgumentsKey)).toStringList();
const QDir dir = QDir(target()->project()->projectDirectory());
d->projectFilePath
= QDir::cleanPath(dir.filePath(map.value(QLatin1String(ProFileKey)).toString()));
@@ -182,31 +183,21 @@ QString RemoteLinuxRunConfiguration::defaultDisplayName()
return tr("Run on Remote Device");
}
-QString RemoteLinuxRunConfiguration::arguments() const
+QStringList RemoteLinuxRunConfiguration::arguments() const
{
return d->arguments;
}
-QString RemoteLinuxRunConfiguration::environmentPreparationCommand() const
-{
- QString command;
- const QStringList filesToSource = QStringList() << QLatin1String("/etc/profile")
- << QLatin1String("$HOME/.profile");
- foreach (const QString &filePath, filesToSource)
- command += QString::fromLatin1("test -f %1 && source %1;").arg(filePath);
- if (!workingDirectory().isEmpty())
- command += QLatin1String("cd ") + workingDirectory();
- else
- command.chop(1); // Trailing semicolon.
- return command;
-}
-
-QString RemoteLinuxRunConfiguration::commandPrefix() const
+Environment RemoteLinuxRunConfiguration::environment() const
{
RemoteLinuxEnvironmentAspect *aspect = extraAspect<RemoteLinuxEnvironmentAspect>();
- QTC_ASSERT(aspect, return QString());
- return QString::fromLatin1("%1; DISPLAY=:0.0 %2")
- .arg(environmentPreparationCommand(), aspect->userEnvironmentChangesAsString());
+ QTC_ASSERT(aspect, return Environment());
+ Environment env(OsTypeLinux);
+ env.modify(aspect->userEnvironmentChanges());
+ const QString displayKey = QLatin1String("DISPLAY");
+ if (!env.hasKey(displayKey))
+ env.appendOrSet(displayKey, QLatin1String(":0.0"));
+ return env;
}
QString RemoteLinuxRunConfiguration::localExecutableFilePath() const
@@ -229,7 +220,7 @@ QString RemoteLinuxRunConfiguration::remoteExecutableFilePath() const
void RemoteLinuxRunConfiguration::setArguments(const QString &args)
{
- d->arguments = args;
+ d->arguments = QtcProcess::splitArgs(args); // TODO: Widget should be list-based.
}
QString RemoteLinuxRunConfiguration::workingDirectory() const
diff --git a/src/plugins/remotelinux/remotelinuxrunconfiguration.h b/src/plugins/remotelinux/remotelinuxrunconfiguration.h
index 1419164b62..af2fdca6df 100644
--- a/src/plugins/remotelinux/remotelinuxrunconfiguration.h
+++ b/src/plugins/remotelinux/remotelinuxrunconfiguration.h
@@ -34,7 +34,12 @@
#include <projectexplorer/runconfiguration.h>
-namespace Utils { class PortList; }
+#include <QStringList>
+
+namespace Utils {
+class Environment;
+class PortList;
+}
namespace RemoteLinux {
class RemoteLinuxRunConfigurationWidget;
@@ -62,13 +67,12 @@ public:
QWidget *createConfigurationWidget();
Utils::OutputFormatter *createOutputFormatter() const;
- virtual QString environmentPreparationCommand() const;
- virtual QString commandPrefix() const;
+ virtual Utils::Environment environment() const;
QString localExecutableFilePath() const;
QString defaultRemoteExecutableFilePath() const;
QString remoteExecutableFilePath() const;
- QString arguments() const;
+ QStringList arguments() const;
void setArguments(const QString &args);
QString workingDirectory() const;
void setWorkingDirectory(const QString &wd);
diff --git a/src/plugins/remotelinux/remotelinuxrunconfigurationwidget.cpp b/src/plugins/remotelinux/remotelinuxrunconfigurationwidget.cpp
index 2b744daa2e..964715838e 100644
--- a/src/plugins/remotelinux/remotelinuxrunconfigurationwidget.cpp
+++ b/src/plugins/remotelinux/remotelinuxrunconfigurationwidget.cpp
@@ -148,7 +148,7 @@ void RemoteLinuxRunConfigurationWidget::addGenericWidgets(QVBoxLayout *mainLayou
altRemoteExeLayout->addWidget(&d->useAlternateCommandBox);
d->genericWidgetsLayout.addRow(tr("Alternate executable on device:"), altRemoteExeWidget);
- d->argsLineEdit.setText(d->runConfiguration->arguments());
+ d->argsLineEdit.setText(d->runConfiguration->arguments().join(QLatin1String(" ")));
d->genericWidgetsLayout.addRow(tr("Arguments:"), &d->argsLineEdit);
d->workingDirLineEdit.setPlaceholderText(tr("<default>"));
diff --git a/src/plugins/remotelinux/remotelinuxruncontrol.cpp b/src/plugins/remotelinux/remotelinuxruncontrol.cpp
index 93b3f69ec5..1d9e281315 100644
--- a/src/plugins/remotelinux/remotelinuxruncontrol.cpp
+++ b/src/plugins/remotelinux/remotelinuxruncontrol.cpp
@@ -34,6 +34,7 @@
#include <projectexplorer/devicesupport/deviceapplicationrunner.h>
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/target.h>
+#include <utils/environment.h>
#include <QString>
#include <QIcon>
@@ -49,8 +50,9 @@ public:
ProjectExplorer::DeviceApplicationRunner runner;
IDevice::ConstPtr device;
QString remoteExecutable;
- QString arguments;
- QString prefix;
+ QStringList arguments;
+ Utils::Environment environment;
+ QString workingDir;
};
RemoteLinuxRunControl::RemoteLinuxRunControl(RunConfiguration *rc)
@@ -61,7 +63,8 @@ RemoteLinuxRunControl::RemoteLinuxRunControl(RunConfiguration *rc)
const RemoteLinuxRunConfiguration * const lrc = qobject_cast<RemoteLinuxRunConfiguration *>(rc);
d->remoteExecutable = lrc->remoteExecutableFilePath();
d->arguments = lrc->arguments();
- d->prefix = lrc->commandPrefix();
+ d->environment = lrc->environment();
+ d->workingDir = lrc->workingDirectory();
}
RemoteLinuxRunControl::~RemoteLinuxRunControl()
@@ -80,16 +83,14 @@ void RemoteLinuxRunControl::start()
connect(&d->runner, SIGNAL(remoteStdout(QByteArray)), SLOT(handleRemoteOutput(QByteArray)));
connect(&d->runner, SIGNAL(finished(bool)), SLOT(handleRunnerFinished()));
connect(&d->runner, SIGNAL(reportProgress(QString)), SLOT(handleProgressReport(QString)));
- const QString commandLine = QString::fromLatin1("%1 %2 %3")
- .arg(d->prefix, d->remoteExecutable, d->arguments);
- d->runner.start(d->device, commandLine.toUtf8());
+ d->runner.setEnvironment(d->environment);
+ d->runner.setWorkingDirectory(d->workingDir);
+ d->runner.start(d->device, d->remoteExecutable, d->arguments);
}
RunControl::StopResult RemoteLinuxRunControl::stop()
{
- const QString stopCommandLine
- = d->device->processSupport()->killProcessByNameCommandLine(d->remoteExecutable);
- d->runner.stop(stopCommandLine.toUtf8());
+ d->runner.stop();
return AsynchronousStop;
}
diff --git a/src/plugins/remotelinux/remotelinuxruncontrolfactory.cpp b/src/plugins/remotelinux/remotelinuxruncontrolfactory.cpp
index 3792e39e08..6372b8cae0 100644
--- a/src/plugins/remotelinux/remotelinuxruncontrolfactory.cpp
+++ b/src/plugins/remotelinux/remotelinuxruncontrolfactory.cpp
@@ -40,6 +40,7 @@
#include <analyzerbase/analyzerstartparameters.h>
#include <analyzerbase/analyzermanager.h>
#include <analyzerbase/analyzerruncontrol.h>
+#include <analyzerbase/ianalyzertool.h>
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/target.h>
#include <utils/portlist.h>
@@ -106,16 +107,10 @@ RunControl *RemoteLinuxRunControlFactory::create(RunConfiguration *runConfig, Ru
return runControl;
}
case QmlProfilerRunMode: {
- IAnalyzerTool *tool = AnalyzerManager::toolFromRunMode(mode);
- if (!tool) {
- if (errorMessage)
- *errorMessage = tr("No analyzer tool selected.");
- return 0;
- }
AnalyzerStartParameters params = RemoteLinuxAnalyzeSupport::startParameters(rc, mode);
- AnalyzerRunControl * const runControl = new AnalyzerRunControl(tool, params, runConfig);
+ AnalyzerRunControl *runControl = AnalyzerManager::createRunControl(params, runConfig);
RemoteLinuxAnalyzeSupport * const analyzeSupport =
- new RemoteLinuxAnalyzeSupport(rc, runControl->engine(), mode);
+ new RemoteLinuxAnalyzeSupport(rc, runControl, mode);
connect(runControl, SIGNAL(finished()), analyzeSupport, SLOT(handleProfilingFinished()));
return runControl;
}
diff --git a/src/plugins/remotelinux/remotelinuxsignaloperation.cpp b/src/plugins/remotelinux/remotelinuxsignaloperation.cpp
new file mode 100644
index 0000000000..bdfb67a787
--- /dev/null
+++ b/src/plugins/remotelinux/remotelinuxsignaloperation.cpp
@@ -0,0 +1,133 @@
+/****************************************************************************
+**
+** 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 "remotelinuxsignaloperation.h"
+
+#include <ssh/sshremoteprocessrunner.h>
+#include <ssh/sshconnection.h>
+#include <utils/qtcassert.h>
+
+using namespace RemoteLinux;
+using namespace ProjectExplorer;
+
+RemoteLinuxSignalOperation::RemoteLinuxSignalOperation(
+ const QSsh::SshConnectionParameters sshParameters)
+ : DeviceProcessSignalOperation()
+ , m_sshParameters(sshParameters)
+ , m_runner(0)
+{}
+
+RemoteLinuxSignalOperation::~RemoteLinuxSignalOperation()
+{
+ if (m_runner) {
+ connect(m_runner, SIGNAL(processClosed(int)), m_runner, SLOT(deleteLater()));
+ connect(m_runner, SIGNAL(connectionError()), m_runner, SLOT(deleteLater()));
+ }
+}
+
+static QString signalProcessByPidCommandLine(int pid, int signal)
+{
+ return QString::fromLatin1("kill -%1 %2").arg(signal).arg(pid);
+}
+
+void RemoteLinuxSignalOperation::run(const QString command)
+{
+ QTC_ASSERT(!m_runner, return);
+ m_runner = new QSsh::SshRemoteProcessRunner();
+ connect(m_runner, SIGNAL(processClosed(int)), SLOT(runnerProcessFinished()));
+ connect(m_runner, SIGNAL(connectionError()), SLOT(runnerConnectionError()));
+ m_runner->run(command.toLatin1(), m_sshParameters);
+}
+
+void RemoteLinuxSignalOperation::finish()
+{
+ delete m_runner;
+ m_runner = 0;
+ emit finished(m_errorMessage);
+}
+
+static QString signalProcessByNameCommandLine(const QString &filePath, int signal)
+{
+ return QString::fromLatin1(
+ "cd /proc; for pid in `ls -d [0123456789]*`; "
+ "do "
+ "if [ \"`readlink /proc/$pid/exe`\" = \"%1\" ]; then "
+ " kill %2 $pid;"
+ "fi; "
+ "done").arg(filePath).arg(signal);
+}
+
+QString RemoteLinuxSignalOperation::killProcessByNameCommandLine(const QString &filePath) const
+{
+ return QString::fromLatin1("%1; %2").arg(signalProcessByNameCommandLine(filePath, 15),
+ signalProcessByNameCommandLine(filePath, 9));
+}
+
+QString RemoteLinuxSignalOperation::interruptProcessByNameCommandLine(const QString &filePath) const
+{
+ return signalProcessByNameCommandLine(filePath, 2);
+}
+
+void RemoteLinuxSignalOperation::killProcess(int pid)
+{
+ run(signalProcessByPidCommandLine(pid, 9));
+}
+
+void RemoteLinuxSignalOperation::killProcess(const QString &filePath)
+{
+ run(killProcessByNameCommandLine(filePath));
+}
+
+void RemoteLinuxSignalOperation::interruptProcess(int pid)
+{
+ run(signalProcessByPidCommandLine(pid, 2));
+}
+
+void RemoteLinuxSignalOperation::interruptProcess(const QString &filePath)
+{
+ run(interruptProcessByNameCommandLine(filePath));
+}
+
+void RemoteLinuxSignalOperation::runnerProcessFinished()
+{
+ m_errorMessage.clear();
+ if (m_runner->processExitStatus() != QSsh::SshRemoteProcess::NormalExit) {
+ m_errorMessage = m_runner->processErrorString();
+ } else if (m_runner->processExitCode() != 0) {
+ m_errorMessage = tr("Exit code is %1. stderr: ").arg(m_runner->processExitCode())
+ + QString::fromLatin1(m_runner->readAllStandardError());
+ }
+ finish();
+}
+
+void RemoteLinuxSignalOperation::runnerConnectionError()
+{
+ m_errorMessage = m_runner->lastConnectionErrorString();
+ finish();
+}
diff --git a/src/plugins/remotelinux/remotelinuxsignaloperation.h b/src/plugins/remotelinux/remotelinuxsignaloperation.h
new file mode 100644
index 0000000000..4e2d9da94b
--- /dev/null
+++ b/src/plugins/remotelinux/remotelinuxsignaloperation.h
@@ -0,0 +1,78 @@
+/****************************************************************************
+**
+** 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 REMOTELINUXSIGNALOPERATION_H
+#define REMOTELINUXSIGNALOPERATION_H
+
+#include "remotelinux_export.h"
+
+#include <projectexplorer/devicesupport/idevice.h>
+#include <ssh/sshconnection.h>
+
+namespace QSsh {
+class SshConnectionParameters;
+class SshRemoteProcessRunner;
+}
+
+namespace RemoteLinux {
+
+class REMOTELINUX_EXPORT RemoteLinuxSignalOperation
+ : public ProjectExplorer::DeviceProcessSignalOperation
+{
+ Q_OBJECT
+public:
+ virtual ~RemoteLinuxSignalOperation();
+
+ void killProcess(int pid);
+ void killProcess(const QString &filePath);
+ void interruptProcess(int pid);
+ void interruptProcess(const QString &filePath);
+
+protected:
+ RemoteLinuxSignalOperation(const QSsh::SshConnectionParameters sshParameters);
+
+private slots:
+ void runnerProcessFinished();
+ void runnerConnectionError();
+
+private:
+ virtual QString killProcessByNameCommandLine(const QString &filePath) const;
+ virtual QString interruptProcessByNameCommandLine(const QString &filePath) const;
+ void run(const QString command);
+ void finish();
+
+ const QSsh::SshConnectionParameters m_sshParameters;
+ QSsh::SshRemoteProcessRunner *m_runner;
+
+ friend class LinuxDevice;
+};
+
+}
+
+#endif // REMOTELINUXSIGNALOPERATION_H
diff --git a/src/plugins/remotelinux/tarpackagecreationstep.cpp b/src/plugins/remotelinux/tarpackagecreationstep.cpp
index ebcab8d8f3..d055c95547 100644
--- a/src/plugins/remotelinux/tarpackagecreationstep.cpp
+++ b/src/plugins/remotelinux/tarpackagecreationstep.cpp
@@ -197,7 +197,7 @@ bool TarPackageCreationStep::appendFile(QFile &tarFile, const QFileInfo &fileInf
emit addOutput(tr("Adding file '%1' to tarball...").arg(nativePath), MessageOutput);
// TODO: Wasteful. Work with fixed-size buffer.
- while (!file.atEnd() && !file.error() != QFile::NoError && !tarFile.error() != QFile::NoError) {
+ while (!file.atEnd() && file.error() == QFile::NoError && tarFile.error() == QFile::NoError) {
const QByteArray data = file.read(chunkSize);
tarFile.write(data);
if (fi.isCanceled())
@@ -298,7 +298,7 @@ BuildStepConfigWidget *TarPackageCreationStep::createConfigWidget()
Core::Id TarPackageCreationStep::stepId()
{
- return Core::Id("MaemoTarPackageCreationStep");
+ return "MaemoTarPackageCreationStep";
}
QString TarPackageCreationStep::displayName()
diff --git a/src/plugins/remotelinux/uploadandinstalltarpackagestep.cpp b/src/plugins/remotelinux/uploadandinstalltarpackagestep.cpp
index 81ca05f2c3..d1c94e56b8 100644
--- a/src/plugins/remotelinux/uploadandinstalltarpackagestep.cpp
+++ b/src/plugins/remotelinux/uploadandinstalltarpackagestep.cpp
@@ -103,7 +103,7 @@ BuildStepConfigWidget *UploadAndInstallTarPackageStep::createConfigWidget()
Core::Id UploadAndInstallTarPackageStep::stepId()
{
- return Core::Id("MaemoUploadAndInstallTarPackageStep");
+ return "MaemoUploadAndInstallTarPackageStep";
}
QString UploadAndInstallTarPackageStep::displayName()
diff --git a/src/plugins/resourceeditor/ResourceEditor.pluginspec.in b/src/plugins/resourceeditor/ResourceEditor.pluginspec.in
index 5a88cc126d..79f6076c9e 100644
--- a/src/plugins/resourceeditor/ResourceEditor.pluginspec.in
+++ b/src/plugins/resourceeditor/ResourceEditor.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"ResourceEditor\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"ResourceEditor\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/resourceeditor/qrceditor/qrceditor.cpp b/src/plugins/resourceeditor/qrceditor/qrceditor.cpp
index f15a62b957..5fba4a2da8 100644
--- a/src/plugins/resourceeditor/qrceditor/qrceditor.cpp
+++ b/src/plugins/resourceeditor/qrceditor/qrceditor.cpp
@@ -49,7 +49,7 @@ QrcEditor::QrcEditor(QWidget *parent)
layout->setSpacing(0);
layout->setMargin(0);
m_ui.centralWidget->setLayout(layout);
- m_treeview->setFrameStyle(QFrame::NoFrame);;
+ m_treeview->setFrameStyle(QFrame::NoFrame);
layout->addWidget(m_treeview);
connect(m_ui.removeButton, SIGNAL(clicked()), this, SLOT(onRemove()));
diff --git a/src/plugins/resourceeditor/qrceditor/resourcefile.cpp b/src/plugins/resourceeditor/qrceditor/resourcefile.cpp
index 06b4fb2011..781242124a 100644
--- a/src/plugins/resourceeditor/qrceditor/resourcefile.cpp
+++ b/src/plugins/resourceeditor/qrceditor/resourcefile.cpp
@@ -760,7 +760,7 @@ QVariant ResourceModel::data(const QModelIndex &index, int role) const
if (iconFileExtension(path))
file->icon = QIcon(path);
else
- file->icon = Core::FileIconProvider::instance()->icon(QFileInfo(path));
+ file->icon = Core::FileIconProvider::icon(path);
}
if (!file->icon.isNull())
result = file->icon;
@@ -968,8 +968,7 @@ void ResourceModel::addFiles(int prefixIndex, const QStringList &fileNames, int
firstFile = cnt;
lastFile = cnt + unique_list.count() - 1;
- Core::ICore::vcsManager()->promptToAdd(QFileInfo(m_resource_file.fileName()).absolutePath(),
- fileNames);
+ Core::VcsManager::promptToAdd(QFileInfo(m_resource_file.fileName()).absolutePath(), fileNames);
}
diff --git a/src/plugins/resourceeditor/qrceditor/test/main.cpp b/src/plugins/resourceeditor/qrceditor/test/main.cpp
index 09706a0305..0e68ad6adb 100644
--- a/src/plugins/resourceeditor/qrceditor/test/main.cpp
+++ b/src/plugins/resourceeditor/qrceditor/test/main.cpp
@@ -27,9 +27,10 @@
**
****************************************************************************/
-#include "qrceditor.h"
#include "mainwindow.h"
+#include <resourceeditor/qrceditor/qrceditor.h>
+
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
diff --git a/src/plugins/resourceeditor/qrceditor/test/mainwindow.cpp b/src/plugins/resourceeditor/qrceditor/test/mainwindow.cpp
index ceb9e25efa..3bec292e92 100644
--- a/src/plugins/resourceeditor/qrceditor/test/mainwindow.cpp
+++ b/src/plugins/resourceeditor/qrceditor/test/mainwindow.cpp
@@ -28,7 +28,7 @@
****************************************************************************/
#include "mainwindow.h"
-#include "qrceditor.h"
+#include <resourceeditor/qrceditor/qrceditor.h>
#include <QAction>
#include <QDebug>
diff --git a/src/plugins/resourceeditor/resourceeditor.pro b/src/plugins/resourceeditor/resourceeditor.pro
index d10ddc591b..b71135955d 100644
--- a/src/plugins/resourceeditor/resourceeditor.pro
+++ b/src/plugins/resourceeditor/resourceeditor.pro
@@ -1,8 +1,6 @@
include(../../qtcreatorplugin.pri)
include(qrceditor/qrceditor.pri)
-INCLUDEPATH += $$PWD/../../tools/utils
-
HEADERS += resourceeditorfactory.h \
resourceeditorplugin.h \
resourcewizard.h \
diff --git a/src/plugins/resourceeditor/resourceeditor.qbs b/src/plugins/resourceeditor/resourceeditor.qbs
index 35bf10acfb..479b4b6552 100644
--- a/src/plugins/resourceeditor/resourceeditor.qbs
+++ b/src/plugins/resourceeditor/resourceeditor.qbs
@@ -9,27 +9,26 @@ QtcPlugin {
Depends { name: "Find" }
Depends { name: "Qt"; submodules: ["widgets", "xml"] }
- cpp.includePaths: base.concat("qrceditor")
+ Group {
+ name: "General"
+ files: [
+ "resourceeditor.qrc",
+ "resourceeditorconstants.h",
+ "resourceeditorfactory.cpp", "resourceeditorfactory.h",
+ "resourceeditorplugin.cpp", "resourceeditorplugin.h",
+ "resourceeditorw.cpp", "resourceeditorw.h",
+ "resourcewizard.cpp", "resourcewizard.h",
+ ]
+ }
- files: [
- "resourceeditor.qrc",
- "resourceeditorconstants.h",
- "resourceeditorfactory.cpp",
- "resourceeditorfactory.h",
- "resourceeditorplugin.cpp",
- "resourceeditorplugin.h",
- "resourceeditorw.cpp",
- "resourceeditorw.h",
- "resourcewizard.cpp",
- "resourcewizard.h",
- "qrceditor/qrceditor.cpp",
- "qrceditor/qrceditor.h",
- "qrceditor/qrceditor.ui",
- "qrceditor/resourcefile.cpp",
- "qrceditor/resourcefile_p.h",
- "qrceditor/resourceview.cpp",
- "qrceditor/resourceview.h",
- "qrceditor/undocommands.cpp",
- "qrceditor/undocommands_p.h",
- ]
+ Group {
+ name: "QRC Editor"
+ prefix: "qrceditor/"
+ files: [
+ "qrceditor.cpp", "qrceditor.h", "qrceditor.ui",
+ "resourcefile.cpp", "resourcefile_p.h",
+ "resourceview.cpp", "resourceview.h",
+ "undocommands.cpp", "undocommands_p.h",
+ ]
+ }
}
diff --git a/src/plugins/resourceeditor/resourceeditorfactory.cpp b/src/plugins/resourceeditor/resourceeditorfactory.cpp
index 7adc6de66c..e4dae1909e 100644
--- a/src/plugins/resourceeditor/resourceeditorfactory.cpp
+++ b/src/plugins/resourceeditor/resourceeditorfactory.cpp
@@ -44,22 +44,13 @@ using namespace ResourceEditor::Constants;
ResourceEditorFactory::ResourceEditorFactory(ResourceEditorPlugin *plugin) :
Core::IEditorFactory(plugin),
- m_mimeTypes(QStringList(QLatin1String(C_RESOURCE_MIMETYPE))),
m_plugin(plugin)
{
- Core::FileIconProvider *iconProvider = Core::FileIconProvider::instance();
- iconProvider->registerIconOverlayForSuffix(QIcon(QLatin1String(":/resourceeditor/images/qt_qrc.png")),
- QLatin1String("qrc"));
-}
-
-Core::Id ResourceEditorFactory::id() const
-{
- return Core::Id(RESOURCEEDITOR_ID);
-}
+ setId(RESOURCEEDITOR_ID);
+ setMimeTypes(QStringList(QLatin1String(C_RESOURCE_MIMETYPE)));
+ setDisplayName(qApp->translate("OpenWith::Editors", C_RESOURCEEDITOR_DISPLAY_NAME));
-QString ResourceEditorFactory::displayName() const
-{
- return qApp->translate("OpenWith::Editors", C_RESOURCEEDITOR_DISPLAY_NAME);
+ Core::FileIconProvider::registerIconOverlayForSuffix(":/resourceeditor/images/qt_qrc.png", "qrc");
}
Core::IEditor *ResourceEditorFactory::createEditor(QWidget *parent)
@@ -67,8 +58,3 @@ Core::IEditor *ResourceEditorFactory::createEditor(QWidget *parent)
Core::Context context(ResourceEditor::Constants::C_RESOURCEEDITOR);
return new ResourceEditorW(context, m_plugin, parent);
}
-
-QStringList ResourceEditorFactory::mimeTypes() const
-{
- return m_mimeTypes;
-}
diff --git a/src/plugins/resourceeditor/resourceeditorfactory.h b/src/plugins/resourceeditor/resourceeditorfactory.h
index e1f84e437a..f0878be78f 100644
--- a/src/plugins/resourceeditor/resourceeditorfactory.h
+++ b/src/plugins/resourceeditor/resourceeditorfactory.h
@@ -47,15 +47,9 @@ class ResourceEditorFactory : public Core::IEditorFactory
public:
explicit ResourceEditorFactory(ResourceEditorPlugin *plugin);
- virtual QStringList mimeTypes() const;
-
- // IEditorFactory
- Core::Id id() const;
- QString displayName() const;
Core::IEditor *createEditor(QWidget *parent);
private:
- const QStringList m_mimeTypes;
ResourceEditorPlugin *m_plugin;
};
diff --git a/src/plugins/resourceeditor/resourceeditorplugin.cpp b/src/plugins/resourceeditor/resourceeditorplugin.cpp
index fda1eeb80a..4fd92ebeb8 100644
--- a/src/plugins/resourceeditor/resourceeditorplugin.cpp
+++ b/src/plugins/resourceeditor/resourceeditorplugin.cpp
@@ -67,20 +67,19 @@ ResourceEditorPlugin::~ResourceEditorPlugin()
bool ResourceEditorPlugin::initialize(const QStringList &arguments, QString *errorMessage)
{
Q_UNUSED(arguments)
- if (!Core::ICore::mimeDatabase()->addMimeTypes(QLatin1String(":/resourceeditor/ResourceEditor.mimetypes.xml"), errorMessage))
+ if (!Core::MimeDatabase::addMimeTypes(QLatin1String(":/resourceeditor/ResourceEditor.mimetypes.xml"), errorMessage))
return false;
m_editor = new ResourceEditorFactory(this);
addObject(m_editor);
- Core::BaseFileWizardParameters wizardParameters(Core::IWizard::FileWizard);
- wizardParameters.setDescription(tr("Creates a Qt Resource file (.qrc) that you can add to a Qt Widget Project."));
- wizardParameters.setDisplayName(tr("Qt Resource file"));
- wizardParameters.setId(QLatin1String("F.Resource"));
- wizardParameters.setCategory(QLatin1String(Core::Constants::WIZARD_CATEGORY_QT));
- wizardParameters.setDisplayCategory(QCoreApplication::translate("Core", Core::Constants::WIZARD_TR_CATEGORY_QT));
+ m_wizard = new ResourceWizard(this);
+ m_wizard->setDescription(tr("Creates a Qt Resource file (.qrc) that you can add to a Qt Widget Project."));
+ m_wizard->setDisplayName(tr("Qt Resource file"));
+ m_wizard->setId(QLatin1String("F.Resource"));
+ m_wizard->setCategory(QLatin1String(Core::Constants::WIZARD_CATEGORY_QT));
+ m_wizard->setDisplayCategory(QCoreApplication::translate("Core", Core::Constants::WIZARD_TR_CATEGORY_QT));
- m_wizard = new ResourceWizard(wizardParameters, this);
addObject(m_wizard);
errorMessage->clear();
diff --git a/src/plugins/resourceeditor/resourceeditorw.cpp b/src/plugins/resourceeditor/resourceeditorw.cpp
index 1b49ad1e3c..f81f7b2a82 100644
--- a/src/plugins/resourceeditor/resourceeditorw.cpp
+++ b/src/plugins/resourceeditor/resourceeditorw.cpp
@@ -31,7 +31,7 @@
#include "resourceeditorplugin.h"
#include "resourceeditorconstants.h"
-#include <qrceditor.h>
+#include <resourceeditor/qrceditor/qrceditor.h>
#include <aggregation/aggregate.h>
#include <coreplugin/icore.h>
@@ -63,8 +63,10 @@ enum { debugResourceEditorW = 0 };
ResourceEditorDocument::ResourceEditorDocument(ResourceEditorW *parent) :
IDocument(parent),
m_mimeType(QLatin1String(ResourceEditor::Constants::C_RESOURCE_MIMETYPE)),
+ m_blockDirtyChanged(false),
m_parent(parent)
{
+ setFilePath(parent->m_resourceEditor->fileName());
if (debugResourceEditorW)
qDebug() << "ResourceEditorFile::ResourceEditorFile()";
}
@@ -82,7 +84,6 @@ ResourceEditorW::ResourceEditorW(const Core::Context &context,
m_resourceDocument(new ResourceEditorDocument(this)),
m_plugin(plugin),
m_shouldAutoSave(false),
- m_diskIo(false),
m_contextMenu(new QMenu),
m_toolBar(new QToolBar)
{
@@ -112,7 +113,7 @@ ResourceEditorW::ResourceEditorW(const Core::Context &context,
Core::DocumentManager::instance(), SLOT(slotExecuteOpenWithMenuAction(QAction*)),
Qt::QueuedConnection);
- connect(m_resourceEditor, SIGNAL(dirtyChanged(bool)), this, SLOT(dirtyChanged(bool)));
+ connect(m_resourceEditor, SIGNAL(dirtyChanged(bool)), m_resourceDocument, SLOT(dirtyChanged(bool)));
connect(m_resourceEditor, SIGNAL(undoStackChanged(bool,bool)),
this, SLOT(onUndoStackChanged(bool,bool)));
connect(m_resourceEditor, SIGNAL(showContextMenu(QPoint,QString)),
@@ -121,7 +122,6 @@ ResourceEditorW::ResourceEditorW(const Core::Context &context,
this, SLOT(openFile(QString)));
connect(m_resourceEditor->commandHistory(), SIGNAL(indexChanged(int)),
this, SLOT(setShouldAutoSave()));
- connect(m_resourceDocument, SIGNAL(changed()), this, SIGNAL(changed()));
if (debugResourceEditorW)
qDebug() << "ResourceEditorW::ResourceEditorW()";
}
@@ -134,47 +134,26 @@ ResourceEditorW::~ResourceEditorW()
delete m_toolBar;
}
-bool ResourceEditorW::createNew(const QString &contents)
-{
- Utils::TempFileSaver saver;
- saver.write(contents.toUtf8());
- if (!saver.finalize(Core::ICore::mainWindow()))
- return false;
-
- const bool rc = m_resourceEditor->load(saver.fileName());
- m_resourceEditor->setFileName(QString());
- m_shouldAutoSave = false;
- if (debugResourceEditorW)
- qDebug() << "ResourceEditorW::createNew: " << contents << " (" << saver.fileName() << ") returns " << rc;
- return rc;
-}
-
bool ResourceEditorW::open(QString *errorString, const QString &fileName, const QString &realFileName)
{
if (debugResourceEditorW)
qDebug() << "ResourceEditorW::open: " << fileName;
- if (fileName.isEmpty()) {
- setDisplayName(tr("untitled"));
+ if (fileName.isEmpty())
return true;
- }
- const QFileInfo fi(fileName);
-
- m_diskIo = true;
+ m_resourceDocument->setBlockDirtyChanged(true);
if (!m_resourceEditor->load(realFileName)) {
*errorString = m_resourceEditor->errorMessage();
- m_diskIo = false;
+ m_resourceDocument->setBlockDirtyChanged(false);
return false;
}
- m_resourceEditor->setFileName(fileName);
+ m_resourceDocument->setFilePath(fileName);
+ m_resourceDocument->setBlockDirtyChanged(false);
m_resourceEditor->setDirty(fileName != realFileName);
- setDisplayName(fi.fileName());
m_shouldAutoSave = false;
- m_diskIo = false;
- emit changed();
return true;
}
@@ -183,17 +162,17 @@ bool ResourceEditorDocument::save(QString *errorString, const QString &name, boo
if (debugResourceEditorW)
qDebug(">ResourceEditorW::save: %s", qPrintable(name));
- const QString oldFileName = fileName();
+ const QString oldFileName = filePath();
const QString actualName = name.isEmpty() ? oldFileName : name;
if (actualName.isEmpty())
return false;
- m_parent->m_diskIo = true;
+ m_blockDirtyChanged = true;
m_parent->m_resourceEditor->setFileName(actualName);
if (!m_parent->m_resourceEditor->save()) {
*errorString = m_parent->m_resourceEditor->errorMessage();
m_parent->m_resourceEditor->setFileName(oldFileName);
- m_parent->m_diskIo = false;
+ m_blockDirtyChanged = false;
return false;
}
@@ -201,23 +180,41 @@ bool ResourceEditorDocument::save(QString *errorString, const QString &name, boo
if (autoSave) {
m_parent->m_resourceEditor->setFileName(oldFileName);
m_parent->m_resourceEditor->setDirty(true);
- m_parent->m_diskIo = false;
+ m_blockDirtyChanged = false;
return true;
}
- m_parent->setDisplayName(QFileInfo(actualName).fileName());
- m_parent->m_diskIo = false;
+ setFilePath(actualName);
+ m_blockDirtyChanged = false;
emit changed();
return true;
}
-void ResourceEditorDocument::rename(const QString &newName)
+bool ResourceEditorDocument::setContents(const QByteArray &contents)
{
- const QString oldName = m_parent->m_resourceEditor->fileName();
- m_parent->m_resourceEditor->setFileName(newName);
- emit fileNameChanged(oldName, newName); // TODO Are there other cases where the ressource file name changes?
- emit changed();
+ Utils::TempFileSaver saver;
+ saver.write(contents);
+ if (!saver.finalize(Core::ICore::mainWindow()))
+ return false;
+
+ const bool rc = m_parent->m_resourceEditor->load(saver.fileName());
+ m_parent->m_shouldAutoSave = false;
+ if (debugResourceEditorW)
+ qDebug() << "ResourceEditorW::createNew: " << contents << " (" << saver.fileName() << ") returns " << rc;
+ return rc;
+}
+
+void ResourceEditorDocument::setFilePath(const QString &newName)
+{
+ if (newName != m_parent->m_resourceEditor->fileName())
+ m_parent->m_resourceEditor->setFileName(newName);
+ IDocument::setFilePath(newName);
+}
+
+void ResourceEditorDocument::setBlockDirtyChanged(bool value)
+{
+ m_blockDirtyChanged = value;
}
Core::Id ResourceEditorW::id() const
@@ -230,11 +227,6 @@ QWidget *ResourceEditorW::toolBar()
return m_toolBar;
}
-QString ResourceEditorDocument::fileName() const
-{
- return m_parent->m_resourceEditor->fileName();
-}
-
bool ResourceEditorDocument::shouldAutoSave() const
{
return m_parent->m_shouldAutoSave;
@@ -258,7 +250,7 @@ bool ResourceEditorDocument::reload(QString *errorString, ReloadFlag flag, Chang
emit changed();
} else {
emit aboutToReload();
- QString fn = m_parent->m_resourceEditor->fileName();
+ QString fn = filePath();
const bool success = m_parent->open(errorString, fn, fn);
emit reloadFinished(success);
return success;
@@ -281,9 +273,9 @@ QString ResourceEditorDocument::suggestedFileName() const
return m_parent->m_suggestedName;
}
-void ResourceEditorW::dirtyChanged(bool dirty)
+void ResourceEditorDocument::dirtyChanged(bool dirty)
{
- if (m_diskIo)
+ if (m_blockDirtyChanged)
return; // We emit changed() afterwards, unless it was an autosave
if (debugResourceEditorW)
diff --git a/src/plugins/resourceeditor/resourceeditorw.h b/src/plugins/resourceeditor/resourceeditorw.h
index 22d71f69c8..5c1abbda2b 100644
--- a/src/plugins/resourceeditor/resourceeditorw.h
+++ b/src/plugins/resourceeditor/resourceeditorw.h
@@ -55,18 +55,23 @@ public:
//IDocument
bool save(QString *errorString, const QString &fileName, bool autoSave);
- QString fileName() const;
+ bool setContents(const QByteArray &contents);
bool shouldAutoSave() const;
bool isModified() const;
bool isSaveAsAllowed() const;
bool reload(QString *errorString, ReloadFlag flag, ChangeType type);
QString defaultPath() const;
QString suggestedFileName() const;
- virtual QString mimeType() const;
- virtual void rename(const QString &newName);
+ QString mimeType() const;
+ void setFilePath(const QString &newName);
+ void setBlockDirtyChanged(bool value);
+
+public slots:
+ void dirtyChanged(bool);
private:
const QString m_mimeType;
+ bool m_blockDirtyChanged;
ResourceEditorW *m_parent;
};
@@ -81,19 +86,14 @@ public:
~ResourceEditorW();
// IEditor
- bool createNew(const QString &contents);
bool open(QString *errorString, const QString &fileName, const QString &realFileName);
Core::IDocument *document() { return m_resourceDocument; }
Core::Id id() const;
- QString displayName() const { return m_displayName; }
- void setDisplayName(const QString &title) { m_displayName = title; emit changed(); }
QWidget *toolBar();
void setSuggestedFileName(const QString &fileName);
- bool isTemporary() const { return false; }
private slots:
- void dirtyChanged(bool);
void onUndoStackChanged(bool canUndo, bool canRedo);
void setShouldAutoSave(bool sad = true) { m_shouldAutoSave = sad; }
void showContextMenu(const QPoint &globalPoint, const QString &fileName);
@@ -111,7 +111,6 @@ private:
ResourceEditorDocument *m_resourceDocument;
ResourceEditorPlugin *m_plugin;
bool m_shouldAutoSave;
- bool m_diskIo;
QMenu *m_contextMenu;
QMenu *m_openWithMenu;
QString m_currentFileName;
diff --git a/src/plugins/resourceeditor/resourcewizard.cpp b/src/plugins/resourceeditor/resourcewizard.cpp
index 6a08ccb855..f471dc46ac 100644
--- a/src/plugins/resourceeditor/resourcewizard.cpp
+++ b/src/plugins/resourceeditor/resourcewizard.cpp
@@ -34,8 +34,8 @@
using namespace ResourceEditor;
using namespace ResourceEditor::Internal;
-ResourceWizard::ResourceWizard(const BaseFileWizardParameters &parameters, QObject *parent)
- : Core::StandardFileWizard(parameters, parent)
+ResourceWizard::ResourceWizard(QObject *parent)
+ : Core::StandardFileWizard(parent)
{
}
diff --git a/src/plugins/resourceeditor/resourcewizard.h b/src/plugins/resourceeditor/resourcewizard.h
index 9f79611f54..af5e33f11c 100644
--- a/src/plugins/resourceeditor/resourcewizard.h
+++ b/src/plugins/resourceeditor/resourcewizard.h
@@ -40,8 +40,7 @@ class ResourceWizard : public Core::StandardFileWizard
Q_OBJECT
public:
- typedef Core::BaseFileWizardParameters BaseFileWizardParameters;
- explicit ResourceWizard(const BaseFileWizardParameters &parameters, QObject *parent);
+ explicit ResourceWizard(QObject *parent);
protected:
virtual Core::GeneratedFiles
diff --git a/src/plugins/subversion/Subversion.pluginspec.in b/src/plugins/subversion/Subversion.pluginspec.in
index b9dfeaaeb3..284edc8174 100644
--- a/src/plugins/subversion/Subversion.pluginspec.in
+++ b/src/plugins/subversion/Subversion.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"Subversion\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"Subversion\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/subversion/annotationhighlighter.cpp b/src/plugins/subversion/annotationhighlighter.cpp
index 8671bdb7a2..f80b9f66ac 100644
--- a/src/plugins/subversion/annotationhighlighter.cpp
+++ b/src/plugins/subversion/annotationhighlighter.cpp
@@ -33,9 +33,8 @@ using namespace Subversion;
using namespace Subversion::Internal;
SubversionAnnotationHighlighter::SubversionAnnotationHighlighter(const ChangeNumbers &changeNumbers,
- const QColor &bg,
QTextDocument *document) :
- VcsBase::BaseAnnotationHighlighter(changeNumbers, bg, document),
+ VcsBase::BaseAnnotationHighlighter(changeNumbers, document),
m_blank(QLatin1Char(' '))
{
}
diff --git a/src/plugins/subversion/annotationhighlighter.h b/src/plugins/subversion/annotationhighlighter.h
index 683e820215..8d1e785dca 100644
--- a/src/plugins/subversion/annotationhighlighter.h
+++ b/src/plugins/subversion/annotationhighlighter.h
@@ -40,7 +40,7 @@ class SubversionAnnotationHighlighter : public VcsBase::BaseAnnotationHighlighte
{
Q_OBJECT
public:
- explicit SubversionAnnotationHighlighter(const ChangeNumbers &changeNumbers, const QColor &bg,
+ explicit SubversionAnnotationHighlighter(const ChangeNumbers &changeNumbers,
QTextDocument *document = 0);
private:
diff --git a/src/plugins/subversion/checkoutwizard.cpp b/src/plugins/subversion/checkoutwizard.cpp
index 81c801af1b..ed69c29e37 100644
--- a/src/plugins/subversion/checkoutwizard.cpp
+++ b/src/plugins/subversion/checkoutwizard.cpp
@@ -32,7 +32,7 @@
#include "subversionplugin.h"
#include <coreplugin/iversioncontrol.h>
-#include <vcsbase/checkoutjobs.h>
+#include <vcsbase/command.h>
#include <vcsbase/vcsbaseconstants.h>
#include <vcsbase/vcsconfigurationpage.h>
#include <utils/qtcassert.h>
@@ -42,25 +42,12 @@
namespace Subversion {
namespace Internal {
-CheckoutWizard::CheckoutWizard(QObject *parent) :
- VcsBase::BaseCheckoutWizard(parent)
+CheckoutWizard::CheckoutWizard()
{
setId(QLatin1String(VcsBase::Constants::VCS_ID_SUBVERSION));
-}
-
-QIcon CheckoutWizard::icon() const
-{
- return QIcon(QLatin1String(":/subversion/images/subversion.png"));
-}
-
-QString CheckoutWizard::description() const
-{
- return tr("Checks out a Subversion repository and tries to load the contained project.");
-}
-
-QString CheckoutWizard::displayName() const
-{
- return tr("Subversion Checkout");
+ setIcon(QIcon(QLatin1String(":/subversion/images/subversion.png")));
+ setDescription(tr("Checks out a Subversion repository and tries to load the contained project."));
+ setDisplayName(tr("Subversion Checkout"));
}
QList<QWizardPage*> CheckoutWizard::createParameterPages(const QString &path)
@@ -75,12 +62,12 @@ QList<QWizardPage*> CheckoutWizard::createParameterPages(const QString &path)
return rc;
}
-QSharedPointer<VcsBase::AbstractCheckoutJob> CheckoutWizard::createJob(const QList<QWizardPage*> &parameterPages,
- QString *checkoutPath)
+VcsBase::Command *CheckoutWizard::createCommand(const QList<QWizardPage*> &parameterPages,
+ QString *checkoutPath)
{
// Collect parameters for the checkout command.
const CheckoutWizardPage *cwp = qobject_cast<const CheckoutWizardPage *>(parameterPages.front());
- QTC_ASSERT(cwp, return QSharedPointer<VcsBase::AbstractCheckoutJob>());
+ QTC_ASSERT(cwp, return 0);
const SubversionSettings settings = SubversionPlugin::instance()->settings();
const QString binary = settings.binaryPath();
const QString directory = cwp->directory();
@@ -93,9 +80,10 @@ QSharedPointer<VcsBase::AbstractCheckoutJob> CheckoutWizard::createJob(const QLi
const QString pwd = settings.stringValue(SubversionSettings::passwordKey);
args = SubversionPlugin::addAuthenticationOptions(args, user, pwd);
}
- VcsBase::ProcessCheckoutJob *job = new VcsBase::ProcessCheckoutJob;
- job->addStep(binary, args, workingDirectory);
- return QSharedPointer<VcsBase::AbstractCheckoutJob>(job);
+ VcsBase::Command *command = new VcsBase::Command(binary, workingDirectory,
+ QProcessEnvironment::systemEnvironment());
+ command->addJob(args, -1);
+ return command;
}
} // namespace Internal
diff --git a/src/plugins/subversion/checkoutwizard.h b/src/plugins/subversion/checkoutwizard.h
index 7bd41dac09..e5b6f93825 100644
--- a/src/plugins/subversion/checkoutwizard.h
+++ b/src/plugins/subversion/checkoutwizard.h
@@ -38,19 +38,15 @@ namespace Internal {
class CheckoutWizard : public VcsBase::BaseCheckoutWizard
{
Q_OBJECT
-public:
- explicit CheckoutWizard(QObject *parent = 0);
- // IWizard
- QIcon icon() const;
- QString description() const;
- QString displayName() const;
+public:
+ CheckoutWizard();
-protected:
+private:
// BaseCheckoutWizard
QList<QWizardPage*> createParameterPages(const QString &path);
- QSharedPointer<VcsBase::AbstractCheckoutJob> createJob(const QList<QWizardPage*> &parameterPage,
- QString *checkoutPath);
+ VcsBase::Command *createCommand(const QList<QWizardPage*> &parameterPage,
+ QString *checkoutPath);
};
} // namespace Internal
diff --git a/src/plugins/subversion/subversioneditor.cpp b/src/plugins/subversion/subversioneditor.cpp
index 569268686e..a64b401486 100644
--- a/src/plugins/subversion/subversioneditor.cpp
+++ b/src/plugins/subversion/subversioneditor.cpp
@@ -109,10 +109,9 @@ QString SubversionEditor::changeUnderCursor(const QTextCursor &c) const
return QString();
}
-VcsBase::BaseAnnotationHighlighter *SubversionEditor::createAnnotationHighlighter(const QSet<QString> &changes,
- const QColor &bg) const
+VcsBase::BaseAnnotationHighlighter *SubversionEditor::createAnnotationHighlighter(const QSet<QString> &changes) const
{
- return new SubversionAnnotationHighlighter(changes, bg);
+ return new SubversionAnnotationHighlighter(changes);
}
QStringList SubversionEditor::annotationPreviousVersions(const QString &v) const
diff --git a/src/plugins/subversion/subversioneditor.h b/src/plugins/subversion/subversioneditor.h
index ee883255a5..f59e5138fb 100644
--- a/src/plugins/subversion/subversioneditor.h
+++ b/src/plugins/subversion/subversioneditor.h
@@ -48,7 +48,7 @@ public:
private:
QSet<QString> annotationChanges() const;
QString changeUnderCursor(const QTextCursor &) const;
- VcsBase::BaseAnnotationHighlighter *createAnnotationHighlighter(const QSet<QString> &changes, const QColor &bg) const;
+ VcsBase::BaseAnnotationHighlighter *createAnnotationHighlighter(const QSet<QString> &changes) const;
QStringList annotationPreviousVersions(const QString &) const;
mutable QRegExp m_changeNumberPattern;
diff --git a/src/plugins/subversion/subversionplugin.cpp b/src/plugins/subversion/subversionplugin.cpp
index 5d03160596..7e3d7fd161 100644
--- a/src/plugins/subversion/subversionplugin.cpp
+++ b/src/plugins/subversion/subversionplugin.cpp
@@ -93,7 +93,6 @@ static const char CMD_ID_DIFF_CURRENT[] = "Subversion.DiffCurrent";
static const char CMD_ID_COMMIT_ALL[] = "Subversion.CommitAll";
static const char CMD_ID_REVERT_ALL[] = "Subversion.RevertAll";
static const char CMD_ID_COMMIT_CURRENT[] = "Subversion.CommitCurrent";
-static const char CMD_ID_SEPARATOR2[] = "Subversion.Separator2";
static const char CMD_ID_FILELOG_CURRENT[] = "Subversion.FilelogCurrent";
static const char CMD_ID_ANNOTATE_CURRENT[] = "Subversion.AnnotateCurrent";
static const char CMD_ID_STATUS[] = "Subversion.Status";
@@ -248,7 +247,7 @@ bool SubversionPlugin::initialize(const QStringList & /*arguments */, QString *e
m_subversionPluginInstance = this;
- if (!Core::ICore::mimeDatabase()->addMimeTypes(QLatin1String(":/trolltech.subversion/Subversion.mimetypes.xml"), errorMessage))
+ if (!Core::MimeDatabase::addMimeTypes(QLatin1String(":/trolltech.subversion/Subversion.mimetypes.xml"), errorMessage))
return false;
m_settings.readSettings(Core::ICore::settings());
@@ -458,7 +457,7 @@ bool SubversionPlugin::submitEditorAboutToClose()
// Submit editor closing. Make it write out the commit message
// and retrieve files
- const QFileInfo editorFile(editorDocument->fileName());
+ const QFileInfo editorFile(editorDocument->filePath());
const QFileInfo changeFile(m_commitMessageFileName);
if (editorFile.absoluteFilePath() != changeFile.absoluteFilePath())
return true; // Oops?!
@@ -573,7 +572,8 @@ void SubversionPlugin::svnDiff(const Subversion::Internal::SubversionDiffParamet
QStringList args(QLatin1String("diff"));
Version v = svnVersion();
- if (v.majorVersion >= 1 && v.minorVersion >= 7) // --internal-diff is new in v1.7.0
+ if (v.majorVersion > 1
+ || (v.majorVersion == 1 && v.minorVersion >= 7)) // --internal-diff is new in v1.7.0
args.append(QLatin1String("--internal-diff"));
args.append(p.arguments);
args << p.files;
@@ -588,7 +588,7 @@ void SubversionPlugin::svnDiff(const Subversion::Internal::SubversionDiffParamet
const QString tag = VcsBase::VcsBaseEditorWidget::editorTag(VcsBase::DiffOutput, p.workingDir, p.files);
// Show in the same editor if diff has been executed before
if (Core::IEditor *existingEditor = VcsBase::VcsBaseEditorWidget::locateEditorByTag(tag)) {
- existingEditor->createNew(response.stdOut);
+ existingEditor->document()->setContents(response.stdOut.toUtf8());
Core::EditorManager::activateEditor(existingEditor);
setDiffBaseDirectory(existingEditor, p.workingDir);
return;
@@ -724,7 +724,8 @@ void SubversionPlugin::diffProject()
{
const VcsBase::VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasProject(), return);
- svnDiff(state.currentProjectTopLevel(), state.relativeCurrentProject(), state.currentProjectName());
+ svnDiff(state.currentProjectTopLevel(), QStringList(state.relativeCurrentProject()),
+ state.currentProjectName());
}
void SubversionPlugin::diffCurrentFile()
@@ -820,7 +821,7 @@ void SubversionPlugin::filelogCurrentFile()
{
const VcsBase::VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasFile(), return);
- filelog(state.currentFileTopLevel(), QStringList(state.relativeCurrentFile()), true);
+ filelog(state.currentFileTopLevel(), state.relativeCurrentFile(), true);
}
void SubversionPlugin::logProject()
@@ -858,13 +859,13 @@ void SubversionPlugin::updateRepository()
svnUpdate(state.topLevel());
}
-void SubversionPlugin::svnStatus(const QString &workingDir, const QStringList &relativePaths)
+void SubversionPlugin::svnStatus(const QString &workingDir, const QString &relativePath)
{
const VcsBase::VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasTopLevel(), return);
QStringList args(QLatin1String("status"));
- if (!relativePaths.isEmpty())
- args.append(relativePaths);
+ if (!relativePath.isEmpty())
+ args.append(relativePath);
VcsBase::VcsBaseOutputWindow *outwin = VcsBase::VcsBaseOutputWindow::instance();
outwin->setRepository(workingDir);
runSvn(workingDir, args, m_settings.timeOutMs(),
@@ -873,7 +874,7 @@ void SubversionPlugin::svnStatus(const QString &workingDir, const QStringList &r
}
void SubversionPlugin::filelog(const QString &workingDir,
- const QStringList &files,
+ const QString &file,
bool enableAnnotationContextMenu)
{
// no need for temp file
@@ -882,7 +883,7 @@ void SubversionPlugin::filelog(const QString &workingDir,
args << QLatin1String("-l")
<< QString::number(m_settings.intValue(SubversionSettings::logCountKey));
}
- foreach (const QString &file, files)
+ if (!file.isEmpty())
args.append(QDir::toNativeSeparators(file));
// subversion stores log in UTF-8 and returns it back in user system locale.
@@ -896,14 +897,15 @@ void SubversionPlugin::filelog(const QString &workingDir,
// Re-use an existing view if possible to support
// the common usage pattern of continuously changing and diffing a file
- const QString id = VcsBase::VcsBaseEditorWidget::getTitleId(workingDir, files);
- const QString tag = VcsBase::VcsBaseEditorWidget::editorTag(VcsBase::LogOutput, workingDir, files);
+ const QString id = VcsBase::VcsBaseEditorWidget::getTitleId(workingDir, QStringList(file));
+ const QString tag = VcsBase::VcsBaseEditorWidget::editorTag(VcsBase::LogOutput, workingDir,
+ QStringList(file));
if (Core::IEditor *editor = VcsBase::VcsBaseEditorWidget::locateEditorByTag(tag)) {
- editor->createNew(response.stdOut);
+ editor->document()->setContents(response.stdOut.toUtf8());
Core::EditorManager::activateEditor(editor);
} else {
const QString title = QString::fromLatin1("svn log %1").arg(id);
- const QString source = VcsBase::VcsBaseEditorWidget::getSource(workingDir, files);
+ const QString source = VcsBase::VcsBaseEditorWidget::getSource(workingDir, file);
Core::IEditor *newEditor = showOutputInEditor(title, response.stdOut, VcsBase::LogOutput, source, /*codec*/0);
VcsBase::VcsBaseEditorWidget::tagEditor(newEditor, tag);
if (enableAnnotationContextMenu)
@@ -918,12 +920,12 @@ void SubversionPlugin::updateProject()
svnUpdate(state.currentProjectTopLevel(), state.relativeCurrentProject());
}
-void SubversionPlugin::svnUpdate(const QString &workingDir, const QStringList &relativePaths)
+void SubversionPlugin::svnUpdate(const QString &workingDir, const QString &relativePath)
{
QStringList args(QLatin1String("update"));
args.push_back(QLatin1String(nonInteractiveOptionC));
- if (!relativePaths.isEmpty())
- args.append(relativePaths);
+ if (!relativePath.isEmpty())
+ args.append(relativePath);
const SubversionResponse response =
runSvn(workingDir, args, 10 * m_settings.timeOutMs(),
SshPasswordPrompt|ShowStdOutInLogWindow);
@@ -976,7 +978,7 @@ void SubversionPlugin::vcsAnnotate(const QString &workingDir, const QString &fil
const QString id = VcsBase::VcsBaseEditorWidget::getTitleId(workingDir, files, revision);
const QString tag = VcsBase::VcsBaseEditorWidget::editorTag(VcsBase::AnnotateOutput, workingDir, files);
if (Core::IEditor *editor = VcsBase::VcsBaseEditorWidget::locateEditorByTag(tag)) {
- editor->createNew(response.stdOut);
+ editor->document()->setContents(response.stdOut.toUtf8());
VcsBase::VcsBaseEditorWidget::gotoLineOfEditor(editor, lineNumber);
Core::EditorManager::activateEditor(editor);
} else {
@@ -1042,7 +1044,7 @@ void SubversionPlugin::describe(const QString &source, const QString &changeNr)
const QString id = diffArg + source;
const QString tag = VcsBase::VcsBaseEditorWidget::editorTag(VcsBase::DiffOutput, source, QStringList(), changeNr);
if (Core::IEditor *editor = VcsBase::VcsBaseEditorWidget::locateEditorByTag(tag)) {
- editor->createNew(description);
+ editor->document()->setContents(description.toUtf8());
Core::EditorManager::activateEditor(editor);
} else {
const QString title = QString::fromLatin1("svn describe %1#%2").arg(fi.fileName(), changeNr);
@@ -1072,7 +1074,7 @@ void SubversionPlugin::slotDescribe()
void SubversionPlugin::submitCurrentLog()
{
m_submitActionTriggered = true;
- Core::EditorManager::instance()->closeEditors(QList<Core::IEditor*>()
+ Core::EditorManager::closeEditors(QList<Core::IEditor*>()
<< Core::EditorManager::currentEditor());
}
@@ -1118,7 +1120,7 @@ SubversionPlugin::Version SubversionPlugin::svnVersion()
args << QLatin1String("--version") << QLatin1String("-q");
const Utils::SynchronousProcessResponse response =
VcsBase::VcsBasePlugin::runVcs(QDir().absolutePath(), m_settings.binaryPath(),
- args, m_settings.timeOutMs(), 0);
+ args, m_settings.timeOutMs());
if (response.result == Utils::SynchronousProcessResponse::Finished &&
response.exitCode == 0) {
m_svnVersionBinary = m_settings.binaryPath();
@@ -1152,8 +1154,8 @@ SubversionResponse SubversionPlugin::runSvn(const QString &workingDir,
const QStringList completeArguments = SubversionPlugin::addAuthenticationOptions(arguments, userName, password);
const Utils::SynchronousProcessResponse sp_resp =
- VcsBase::VcsBasePlugin::runVcs(workingDir, executable,
- completeArguments, timeOut, flags, outputCodec);
+ VcsBase::VcsBasePlugin::runVcs(workingDir, executable, completeArguments, timeOut,
+ flags, outputCodec);
response.error = sp_resp.result != Utils::SynchronousProcessResponse::Finished;
if (response.error)
@@ -1174,7 +1176,7 @@ Core::IEditor *SubversionPlugin::showOutputInEditor(const QString &title, const
qDebug() << "SubversionPlugin::showOutputInEditor" << title << id.name()
<< "Size= " << output.size() << " Type=" << editorType << debugCodec(codec);
QString s = title;
- Core::IEditor *editor = Core::EditorManager::openEditorWithContents(id, &s, output);
+ Core::IEditor *editor = Core::EditorManager::openEditorWithContents(id, &s, output.toUtf8());
connect(editor, SIGNAL(annotateRevisionRequested(QString,QString,int)),
this, SLOT(annotateVersion(QString,QString,int)));
SubversionEditor *e = qobject_cast<SubversionEditor*>(editor->widget());
diff --git a/src/plugins/subversion/subversionplugin.h b/src/plugins/subversion/subversionplugin.h
index b92e5309af..f0664cc5c6 100644
--- a/src/plugins/subversion/subversionplugin.h
+++ b/src/plugins/subversion/subversionplugin.h
@@ -169,10 +169,10 @@ private:
unsigned flags, QTextCodec *outputCodec = 0);
void filelog(const QString &workingDir,
- const QStringList &file = QStringList(),
+ const QString &file = QString(),
bool enableAnnotationContextMenu = false);
- void svnStatus(const QString &workingDir, const QStringList &relativePath = QStringList());
- void svnUpdate(const QString &workingDir, const QStringList &relativePaths = QStringList());
+ void svnStatus(const QString &workingDir, const QString &relativePath = QString());
+ void svnUpdate(const QString &workingDir, const QString &relativePath = QString());
bool checkSVNSubDir(const QDir &directory, const QString &fileName = QString()) const;
void startCommit(const QString &workingDir, const QStringList &files = QStringList());
bool commit(const QString &messageFile, const QStringList &subVersionFileList);
diff --git a/src/plugins/subversion/subversionsubmiteditor.cpp b/src/plugins/subversion/subversionsubmiteditor.cpp
index 14c2961021..a7c6c12485 100644
--- a/src/plugins/subversion/subversionsubmiteditor.cpp
+++ b/src/plugins/subversion/subversionsubmiteditor.cpp
@@ -30,6 +30,7 @@
#include "subversionsubmiteditor.h"
+#include <coreplugin/idocument.h>
#include <vcsbase/submiteditorwidget.h>
#include <vcsbase/submitfilemodel.h>
@@ -39,7 +40,7 @@ SubversionSubmitEditor::SubversionSubmitEditor(const VcsBase::VcsBaseSubmitEdito
QWidget *parentWidget) :
VcsBase::VcsBaseSubmitEditor(parameters, new VcsBase::SubmitEditorWidget(parentWidget))
{
- setDisplayName(tr("Subversion Submit"));
+ document()->setDisplayName(tr("Subversion Submit"));
setDescriptionMandatory(false);
}
diff --git a/src/plugins/tasklist/TaskList.pluginspec.in b/src/plugins/tasklist/TaskList.pluginspec.in
index be61e89a96..5aa48b0c6b 100644
--- a/src/plugins/tasklist/TaskList.pluginspec.in
+++ b/src/plugins/tasklist/TaskList.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"TaskList\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"TaskList\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/tasklist/stopmonitoringhandler.cpp b/src/plugins/tasklist/stopmonitoringhandler.cpp
index c5a42dcd53..35a7ec2513 100644
--- a/src/plugins/tasklist/stopmonitoringhandler.cpp
+++ b/src/plugins/tasklist/stopmonitoringhandler.cpp
@@ -54,7 +54,7 @@ void StopMonitoringHandler::handle(const ProjectExplorer::Task &task)
{
QTC_ASSERT(canHandle(task), return);
Q_UNUSED(task);
- TaskList::TaskListPlugin::instance()->stopMonitoring();
+ TaskList::TaskListPlugin::stopMonitoring();
}
QAction *StopMonitoringHandler::createAction(QObject *parent) const
diff --git a/src/plugins/tasklist/taskfile.cpp b/src/plugins/tasklist/taskfile.cpp
index cd0aaeaf14..53243a814b 100644
--- a/src/plugins/tasklist/taskfile.cpp
+++ b/src/plugins/tasklist/taskfile.cpp
@@ -38,8 +38,7 @@ using namespace TaskList::Internal;
// TaskFile
// --------------------------------------------------------------------------
-TaskFile::TaskFile(QObject *parent) : Core::IDocument(parent),
- m_context(0)
+TaskFile::TaskFile(QObject *parent) : Core::IDocument(parent)
{ }
TaskFile::~TaskFile()
@@ -53,11 +52,6 @@ bool TaskFile::save(QString *errorString, const QString &fileName, bool autoSave
return false;
}
-QString TaskFile::fileName() const
-{
- return m_fileName;
-}
-
QString TaskFile::defaultPath() const
{
return QString();
@@ -100,27 +94,21 @@ bool TaskFile::reload(QString *errorString, ReloadFlag flag, ChangeType type)
deleteLater();
return true;
}
- return open(errorString, m_fileName);
-}
-
-void TaskFile::rename(const QString &newName)
-{
- Q_UNUSED(newName);
+ return open(errorString, filePath());
}
bool TaskFile::open(QString *errorString, const QString &fileName)
{
- m_fileName = fileName;
- return TaskList::TaskListPlugin::instance()->loadFile(errorString, m_context, m_fileName);
+ setFilePath(fileName);
+ return TaskList::TaskListPlugin::loadFile(errorString, m_baseDir, fileName);
}
-ProjectExplorer::Project *TaskFile::context() const
+QString TaskFile::baseDir() const
{
- return m_context;
+ return m_baseDir;
}
-void TaskFile::setContext(ProjectExplorer::Project *context)
+void TaskFile::setBaseDir(const QString &base)
{
- m_context = context;
+ m_baseDir = base;
}
-
diff --git a/src/plugins/tasklist/taskfile.h b/src/plugins/tasklist/taskfile.h
index a0f917531d..05781d2355 100644
--- a/src/plugins/tasklist/taskfile.h
+++ b/src/plugins/tasklist/taskfile.h
@@ -46,7 +46,6 @@ public:
~TaskFile();
bool save(QString *errorString, const QString &fileName, bool autoSave);
- QString fileName() const;
QString defaultPath() const;
QString suggestedFileName() const;
@@ -57,16 +56,14 @@ public:
ReloadBehavior reloadBehavior(ChangeTrigger state, ChangeType type) const;
bool reload(QString *errorString, ReloadFlag flag, ChangeType type);
- void rename(const QString &newName);
bool open(QString *errorString, const QString &fileName);
- ProjectExplorer::Project *context() const;
- void setContext(ProjectExplorer::Project *context);
+ QString baseDir() const;
+ void setBaseDir(const QString &base);
private:
- QString m_fileName;
- ProjectExplorer::Project *m_context;
+ QString m_baseDir;
};
} // namespace Internal
diff --git a/src/plugins/tasklist/taskfilefactory.cpp b/src/plugins/tasklist/taskfilefactory.cpp
index 7fc761f040..08ee642538 100644
--- a/src/plugins/tasklist/taskfilefactory.cpp
+++ b/src/plugins/tasklist/taskfilefactory.cpp
@@ -32,8 +32,8 @@
#include "taskfile.h"
#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/project.h>
#include <coreplugin/icore.h>
-#include <coreplugin/id.h>
#include <coreplugin/documentmanager.h>
#include <QMessageBox>
@@ -45,38 +45,23 @@ using namespace TaskList::Internal;
// --------------------------------------------------------------------------
TaskFileFactory::TaskFileFactory(QObject * parent) :
- Core::IDocumentFactory(parent),
- m_mimeTypes(QStringList() << QLatin1String("text/x-tasklist"))
-{ }
-
-TaskFileFactory::~TaskFileFactory()
-{ }
-
-QStringList TaskFileFactory::mimeTypes() const
-{
- return m_mimeTypes;
-}
-
-Core::Id TaskFileFactory::id() const
-{
- return Core::Id("ProjectExplorer.TaskFileFactory");
-}
-
-QString TaskFileFactory::displayName() const
+ Core::IDocumentFactory(parent)
{
- return tr("Task file reader");
+ setId("ProjectExplorer.TaskFileFactory");
+ setDisplayName(tr("Task file reader"));
+ addMimeType(QLatin1String("text/x-tasklist"));
}
Core::IDocument *TaskFileFactory::open(const QString &fileName)
{
- ProjectExplorer::Project *context = ProjectExplorer::ProjectExplorerPlugin::currentProject();
- return open(context, fileName);
+ ProjectExplorer::Project *project = ProjectExplorer::ProjectExplorerPlugin::currentProject();
+ return open(project ? project->projectDirectory() : QString(), fileName);
}
-Core::IDocument *TaskFileFactory::open(ProjectExplorer::Project *context, const QString &fileName)
+Core::IDocument *TaskFileFactory::open(const QString &base, const QString &fileName)
{
TaskFile *file = new TaskFile(this);
- file->setContext(context);
+ file->setBaseDir(base);
QString errorString;
if (!file->open(&errorString, fileName)) {
diff --git a/src/plugins/tasklist/taskfilefactory.h b/src/plugins/tasklist/taskfilefactory.h
index 3a28ecb986..587c53ace0 100644
--- a/src/plugins/tasklist/taskfilefactory.h
+++ b/src/plugins/tasklist/taskfilefactory.h
@@ -33,11 +33,7 @@
#include <coreplugin/idocumentfactory.h>
#include <coreplugin/idocument.h>
-#include <QStringList>
-
-namespace ProjectExplorer {
-class Project;
-} // namespace ProjectExplorer
+namespace ProjectExplorer { class Project; }
namespace TaskList {
namespace Internal {
@@ -45,22 +41,16 @@ namespace Internal {
class TaskFileFactory : public Core::IDocumentFactory
{
Q_OBJECT
+
public:
TaskFileFactory(QObject *parent = 0);
- ~TaskFileFactory();
-
- QStringList mimeTypes() const;
-
- Core::Id id() const;
- QString displayName() const;
Core::IDocument *open(const QString &fileName);
- Core::IDocument *open(ProjectExplorer::Project *context, const QString &fileName);
+ Core::IDocument *open(const QString &base, const QString &fileName);
void closeAllFiles();
private:
- QStringList m_mimeTypes;
QList<Core::IDocument *> m_openFiles;
};
diff --git a/src/plugins/tasklist/tasklist.pro b/src/plugins/tasklist/tasklist.pro
index c4d89e9be9..29696e9882 100644
--- a/src/plugins/tasklist/tasklist.pro
+++ b/src/plugins/tasklist/tasklist.pro
@@ -1,7 +1,6 @@
include(../../qtcreatorplugin.pri)
HEADERS += tasklistplugin.h \
- tasklist_export.h \
tasklistconstants.h \
stopmonitoringhandler.h \
taskfile.h \
diff --git a/src/plugins/tasklist/tasklist.qbs b/src/plugins/tasklist/tasklist.qbs
index 06fe2e39da..f6b68ed869 100644
--- a/src/plugins/tasklist/tasklist.qbs
+++ b/src/plugins/tasklist/tasklist.qbs
@@ -20,7 +20,6 @@ QtcPlugin {
"taskfilefactory.cpp",
"taskfilefactory.h",
"tasklist.qrc",
- "tasklist_export.h",
"tasklistconstants.h",
"tasklistplugin.cpp",
"tasklistplugin.h",
diff --git a/src/plugins/tasklist/tasklist_export.h b/src/plugins/tasklist/tasklist_export.h
deleted file mode 100644
index 52626584cd..0000000000
--- a/src/plugins/tasklist/tasklist_export.h
+++ /dev/null
@@ -1,41 +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 TASKLIST_TASKLIST_EXPORT_H
-#define TASKLIST_TASKLIST_EXPORT_H
-
-#include <qglobal.h>
-
-#if defined(TASKLIST_LIBRARY)
-# define TASKLIST_EXPORT Q_DECL_EXPORT
-#else
-# define TASKLIST_EXPORT Q_DECL_IMPORT
-#endif
-
-#endif // TASKLIST_TASKLIST_EXPORT_H
diff --git a/src/plugins/tasklist/tasklistplugin.cpp b/src/plugins/tasklist/tasklistplugin.cpp
index 18ed2c3068..cc408202b4 100644
--- a/src/plugins/tasklist/tasklistplugin.cpp
+++ b/src/plugins/tasklist/tasklistplugin.cpp
@@ -36,8 +36,9 @@
#include <coreplugin/icore.h>
#include <coreplugin/mimedatabase.h>
-#include <extensionsystem/pluginmanager.h>
+#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/project.h>
+#include <projectexplorer/session.h>
#include <projectexplorer/task.h>
#include <projectexplorer/taskhub.h>
@@ -45,188 +46,178 @@
#include <QStringList>
#include <QtPlugin>
-namespace {
+using namespace ProjectExplorer;
+using namespace TaskList::Internal;
-ProjectExplorer::Task::TaskType typeFrom(const QString &typeName)
+static const char SESSION_FILE_KEY[] = "TaskList.File";
+static const char SESSION_BASE_KEY[] = "TaskList.BaseDir";
+
+namespace TaskList {
+
+static Task::TaskType typeFrom(const QString &typeName)
{
- ProjectExplorer::Task::TaskType type = ProjectExplorer::Task::Unknown;
+ Task::TaskType type = Task::Unknown;
QString tmp = typeName.toLower();
if (tmp.startsWith(QLatin1String("warn")))
- type = ProjectExplorer::Task::Warning;
+ type = Task::Warning;
else if (tmp.startsWith(QLatin1String("err")))
- type = ProjectExplorer::Task::Error;
+ type = Task::Error;
return type;
}
-} // namespace
-
-using namespace TaskList;
-
-TaskListPlugin *TaskListPlugin::m_instance = 0;
-
-// --------------------------------------------------------------------------
-// TaskListPluginPrivate
-// --------------------------------------------------------------------------
+static QStringList parseRawLine(const QByteArray &raw)
+{
+ QStringList result;
+ QString line = QString::fromUtf8(raw.constData());
+ if (line.startsWith(QLatin1Char('#')))
+ return result;
-class Internal::TaskListPluginPrivate {
-public:
- bool parseTaskFile(QString *errorString, ProjectExplorer::Project *context, const QString &name)
- {
- QFile tf(name);
- if (!tf.open(QIODevice::ReadOnly)) {
- *errorString = TaskListPlugin::tr("Cannot open task file %1: %2").arg(
- QDir::toNativeSeparators(name), tf.errorString());
- return false;
- }
+ return line.split(QLatin1Char('\t'));
+}
- while (!tf.atEnd())
- {
- QStringList chunks = parseRawLine(tf.readLine());
- if (chunks.isEmpty())
+static QString unescape(const QString &input)
+{
+ QString result;
+ for (int i = 0; i < input.count(); ++i) {
+ if (input.at(i) == QLatin1Char('\\')) {
+ if (i == input.count() - 1)
+ continue;
+ if (input.at(i + 1) == QLatin1Char('n')) {
+ result.append(QLatin1Char('\n'));
+ ++i;
+ continue;
+ } else if (input.at(i + 1) == QLatin1Char('t')) {
+ result.append(QLatin1Char('\t'));
+ ++i;
+ continue;
+ } else if (input.at(i + 1) == QLatin1Char('\\')) {
+ result.append(QLatin1Char('\\'));
+ ++i;
continue;
-
- QString description;
- QString file;
- ProjectExplorer::Task::TaskType type = ProjectExplorer::Task::Unknown;
- int line = -1;
-
- if (chunks.count() == 1) {
- description = chunks.at(0);
- } else if (chunks.count() == 2) {
- type = typeFrom(chunks.at(0));
- description = chunks.at(1);
- } else if (chunks.count() == 3) {
- file = chunks.at(0);
- type = typeFrom(chunks.at(1));
- description = chunks.at(2);
- } else if (chunks.count() >= 4) {
- file = chunks.at(0);
- bool ok;
- line = chunks.at(1).toInt(&ok);
- if (!ok)
- line = -1;
- type = typeFrom(chunks.at(2));
- description = chunks.at(3);
- }
- if (!file.isEmpty()) {
- file = QDir::fromNativeSeparators(file);
- QFileInfo fi(file);
- if (fi.isRelative() && context) {
- QString fullPath = context->projectDirectory() + QLatin1Char('/') + file;
- fi.setFile(fullPath);
- file = fi.absoluteFilePath();
- }
}
- description = unescape(description);
-
- hub->addTask(ProjectExplorer::Task(type, description,
- Utils::FileName::fromUserInput(file), line,
- Core::Id(Constants::TASKLISTTASK_ID)));
+ continue;
}
- return true;
+ result.append(input.at(i));
}
+ return result;
+}
- QStringList parseRawLine(const QByteArray &raw)
- {
- QStringList result;
- QString line = QString::fromUtf8(raw.constData());
- if (line.startsWith(QLatin1Char('#')))
- return result;
-
- return line.split(QLatin1Char('\t'));
+static bool parseTaskFile(QString *errorString, const QString &base, const QString &name)
+{
+ QFile tf(name);
+ if (!tf.open(QIODevice::ReadOnly)) {
+ *errorString = TaskListPlugin::tr("Cannot open task file %1: %2").arg(
+ QDir::toNativeSeparators(name), tf.errorString());
+ return false;
}
- QString unescape(const QString &input) const
- {
- QString result;
- for (int i = 0; i < input.count(); ++i) {
- if (input.at(i) == QLatin1Char('\\')) {
- if (i == input.count() - 1)
- continue;
- if (input.at(i + 1) == QLatin1Char('n')) {
- result.append(QLatin1Char('\n'));
- ++i;
- continue;
- } else if (input.at(i + 1) == QLatin1Char('t')) {
- result.append(QLatin1Char('\t'));
- ++i;
- continue;
- } else if (input.at(i + 1) == QLatin1Char('\\')) {
- result.append(QLatin1Char('\\'));
- ++i;
- continue;
- }
- continue;
+ while (!tf.atEnd()) {
+ QStringList chunks = parseRawLine(tf.readLine());
+ if (chunks.isEmpty())
+ continue;
+
+ QString description;
+ QString file;
+ Task::TaskType type = Task::Unknown;
+ int line = -1;
+
+ if (chunks.count() == 1) {
+ description = chunks.at(0);
+ } else if (chunks.count() == 2) {
+ type = typeFrom(chunks.at(0));
+ description = chunks.at(1);
+ } else if (chunks.count() == 3) {
+ file = chunks.at(0);
+ type = typeFrom(chunks.at(1));
+ description = chunks.at(2);
+ } else if (chunks.count() >= 4) {
+ file = chunks.at(0);
+ bool ok;
+ line = chunks.at(1).toInt(&ok);
+ if (!ok)
+ line = -1;
+ type = typeFrom(chunks.at(2));
+ description = chunks.at(3);
+ }
+ if (!file.isEmpty()) {
+ file = QDir::fromNativeSeparators(file);
+ QFileInfo fi(file);
+ if (fi.isRelative() && !base.isEmpty()) {
+ QString fullPath = base + QLatin1Char('/') + file;
+ fi.setFile(fullPath);
+ file = fi.absoluteFilePath();
}
- result.append(input.at(i));
}
- return result;
- }
+ description = unescape(description);
- ProjectExplorer::TaskHub *hub;
- TaskFileFactory *fileFactory;
-};
+ TaskHub::addTask(type, description, Constants::TASKLISTTASK_ID,
+ Utils::FileName::fromUserInput(file), line);
+ }
+ return true;
+}
// --------------------------------------------------------------------------
// TaskListPlugin
// --------------------------------------------------------------------------
-TaskListPlugin::TaskListPlugin() :
- d(new Internal::TaskListPluginPrivate)
-{
- m_instance = this;
-}
-
-TaskListPlugin::~TaskListPlugin()
-{
- delete d;
-}
-
-TaskListPlugin *TaskListPlugin::instance()
-{
- return m_instance;
-}
+static TaskFileFactory *m_fileFactory = 0;
bool TaskListPlugin::initialize(const QStringList &arguments, QString *errorMessage)
{
Q_UNUSED(arguments)
- d->hub = ExtensionSystem::PluginManager::getObject<ProjectExplorer::TaskHub>();
-
//: Category under which tasklist tasks are listed in Issues view
- d->hub->addCategory(Core::Id(Constants::TASKLISTTASK_ID), tr("My Tasks"));
+ TaskHub::addCategory(Constants::TASKLISTTASK_ID, tr("My Tasks"));
- if (!Core::ICore::mimeDatabase()->addMimeTypes(QLatin1String(":tasklist/TaskList.mimetypes.xml"), errorMessage))
+ if (!Core::MimeDatabase::addMimeTypes(QLatin1String(":tasklist/TaskList.mimetypes.xml"), errorMessage))
return false;
- d->fileFactory = new Internal::TaskFileFactory(this);
- addAutoReleasedObject(d->fileFactory);
- addAutoReleasedObject(new Internal::StopMonitoringHandler);
+ m_fileFactory = new TaskFileFactory(this);
+ addAutoReleasedObject(m_fileFactory);
+ addAutoReleasedObject(new StopMonitoringHandler);
+
+ connect(SessionManager::instance(), SIGNAL(sessionLoaded(QString)),
+ this, SLOT(loadDataFromSession()));
+
return true;
}
-void TaskListPlugin::extensionsInitialized()
-{ }
-
-bool TaskListPlugin::loadFile(QString *errorString, ProjectExplorer::Project *context, const QString &fileName)
+bool TaskListPlugin::loadFile(QString *errorString, const QString &context, const QString &fileName)
{
clearTasks();
- return d->parseTaskFile(errorString, context, fileName);
-}
-bool TaskListPlugin::monitorFile(ProjectExplorer::Project *context, const QString &fileName)
-{
- return d->fileFactory->open(context, fileName);
+ bool result = parseTaskFile(errorString, context, fileName);
+ if (result) {
+ SessionManager::setValue(QLatin1String(SESSION_BASE_KEY), context);
+ SessionManager::setValue(QLatin1String(SESSION_FILE_KEY), fileName);
+ } else {
+ stopMonitoring();
+ }
+
+ return result;
}
void TaskListPlugin::stopMonitoring()
{
- d->fileFactory->closeAllFiles();
+ SessionManager::setValue(QLatin1String(SESSION_BASE_KEY), QString());
+ SessionManager::setValue(QLatin1String(SESSION_FILE_KEY), QString());
+
+ m_fileFactory->closeAllFiles();
}
void TaskListPlugin::clearTasks()
{
- d->hub->clearTasks(Core::Id(Constants::TASKLISTTASK_ID));
+ TaskHub::clearTasks(Constants::TASKLISTTASK_ID);
+}
+
+void TaskListPlugin::loadDataFromSession()
+{
+ const QString fileName = SessionManager::value(QLatin1String(SESSION_FILE_KEY)).toString();
+ if (fileName.isEmpty())
+ return;
+ m_fileFactory->open(SessionManager::value(QLatin1String(SESSION_BASE_KEY)).toString(), fileName);
}
-Q_EXPORT_PLUGIN(TaskListPlugin)
+} // namespace TaskList
+
+Q_EXPORT_PLUGIN(TaskList::TaskListPlugin)
diff --git a/src/plugins/tasklist/tasklistplugin.h b/src/plugins/tasklist/tasklistplugin.h
index e22ffd33b2..7439bbfcb3 100644
--- a/src/plugins/tasklist/tasklistplugin.h
+++ b/src/plugins/tasklist/tasklistplugin.h
@@ -32,14 +32,9 @@
#include <extensionsystem/iplugin.h>
-namespace ProjectExplorer {
-class Project;
-} // namespace ProjectExplorer
+namespace ProjectExplorer { class Project; }
namespace TaskList {
-namespace Internal {
-class TaskListPluginPrivate;
-} // namespace
class TaskListPlugin : public ExtensionSystem::IPlugin
{
@@ -47,24 +42,16 @@ class TaskListPlugin : public ExtensionSystem::IPlugin
Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QtCreatorPlugin" FILE "TaskList.json")
public:
- TaskListPlugin();
- ~TaskListPlugin();
-
- static TaskListPlugin *instance();
-
bool initialize(const QStringList &arguments, QString *errorMessage);
+ void extensionsInitialized() {}
- void extensionsInitialized();
-
- bool loadFile(QString *errorString, ProjectExplorer::Project *context, const QString &fileName);
- bool monitorFile(ProjectExplorer::Project *context, const QString &fileName);
+ static bool loadFile(QString *errorString, const QString &context, const QString &fileName);
- void stopMonitoring();
- void clearTasks();
+ static void stopMonitoring();
+ static void clearTasks();
-private:
- static TaskListPlugin *m_instance;
- Internal::TaskListPluginPrivate * const d;
+public slots:
+ void loadDataFromSession();
};
} // namespace TaskList
diff --git a/src/plugins/texteditor/TextEditor.pluginspec.in b/src/plugins/texteditor/TextEditor.pluginspec.in
index 3868c8eb46..ec6cf350ab 100644
--- a/src/plugins/texteditor/TextEditor.pluginspec.in
+++ b/src/plugins/texteditor/TextEditor.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"TextEditor\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"TextEditor\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/texteditor/autocompleter.cpp b/src/plugins/texteditor/autocompleter.cpp
index 37d251e536..3b89850868 100644
--- a/src/plugins/texteditor/autocompleter.cpp
+++ b/src/plugins/texteditor/autocompleter.cpp
@@ -122,8 +122,7 @@ QString AutoCompleter::autoComplete(QTextCursor &cursor, const QString &textToIn
str += QLatin1String("}") + QString(QChar::ParagraphSeparator);
else
str += QString(QChar::ParagraphSeparator) + QLatin1String("}");
- }
- else {
+ } else {
str += QLatin1String("}");
}
return str;
diff --git a/src/plugins/texteditor/basefilefind.cpp b/src/plugins/texteditor/basefilefind.cpp
index 250eae2ddc..0dc48d4d97 100644
--- a/src/plugins/texteditor/basefilefind.cpp
+++ b/src/plugins/texteditor/basefilefind.cpp
@@ -71,6 +71,7 @@ public:
} // namespace Internal
} // namespace TextEditor
+using namespace Core;
using namespace Utils;
using namespace Find;
using namespace TextEditor;
@@ -163,7 +164,7 @@ void BaseFileFind::runSearch(Find::SearchResult *search)
connect(search, SIGNAL(countChanged(int)), label, SLOT(updateCount(int)));
CountingLabel *statusLabel = new CountingLabel;
connect(search, SIGNAL(countChanged(int)), statusLabel, SLOT(updateCount(int)));
- Find::SearchResultWindow::instance()->popup(Core::IOutputPane::Flags(Core::IOutputPane::ModeSwitch | Core::IOutputPane::WithFocus));
+ Find::SearchResultWindow::instance()->popup(IOutputPane::Flags(IOutputPane::ModeSwitch|IOutputPane::WithFocus));
QFutureWatcher<FileSearchResultList> *watcher = new QFutureWatcher<FileSearchResultList>();
d->m_watchers.insert(watcher, search);
watcher->setPendingResultsLimit(1);
@@ -173,17 +174,15 @@ void BaseFileFind::runSearch(Find::SearchResult *search)
watcher->setFuture(Utils::findInFilesRegExp(parameters.text,
files(parameters.nameFilters, parameters.additionalParameters),
textDocumentFlagsForFindFlags(parameters.flags),
- ITextEditor::openedTextEditorsContents()));
+ ITextEditor::openedTextDocumentContents()));
} else {
watcher->setFuture(Utils::findInFiles(parameters.text,
files(parameters.nameFilters, parameters.additionalParameters),
textDocumentFlagsForFindFlags(parameters.flags),
- ITextEditor::openedTextEditorsContents()));
+ ITextEditor::openedTextDocumentContents()));
}
- Core::FutureProgress *progress =
- Core::ICore::progressManager()->addTask(watcher->future(),
- tr("Search"),
- QLatin1String(Constants::TASK_SEARCH));
+ FutureProgress *progress =
+ ProgressManager::addTask(watcher->future(), tr("Search"), Constants::TASK_SEARCH);
progress->setWidget(label);
progress->setStatusBarWidget(statusLabel);
connect(progress, SIGNAL(clicked()), search, SLOT(popup()));
@@ -205,7 +204,7 @@ void BaseFileFind::doReplace(const QString &text,
{
QStringList files = replaceAll(text, items, preserveCase);
if (!files.isEmpty()) {
- Core::DocumentManager::notifyFilesChangedInternally(files);
+ DocumentManager::notifyFilesChangedInternally(files);
Find::SearchResultWindow::instance()->hide();
}
}
@@ -308,13 +307,13 @@ void BaseFileFind::updateComboEntries(QComboBox *combo, bool onTop)
void BaseFileFind::openEditor(const Find::SearchResultItem &item)
{
SearchResult *result = qobject_cast<SearchResult *>(sender());
- Core::IEditor *openedEditor = 0;
+ IEditor *openedEditor = 0;
if (item.path.size() > 0) {
- openedEditor = Core::EditorManager::openEditorAt(QDir::fromNativeSeparators(item.path.first()),
+ openedEditor = EditorManager::openEditorAt(QDir::fromNativeSeparators(item.path.first()),
item.lineNumber,
item.textMarkPos);
} else {
- openedEditor = Core::EditorManager::openEditor(QDir::fromNativeSeparators(item.text));
+ openedEditor = EditorManager::openEditor(QDir::fromNativeSeparators(item.text));
}
if (d->m_currentFindSupport)
d->m_currentFindSupport->clearResults();
@@ -377,8 +376,7 @@ QStringList BaseFileFind::replaceAll(const QString &text,
// Query the user for permissions
if (!roFiles.isEmpty()) {
- Core::Internal::ReadOnlyFilesDialog roDialog(roFiles.toList(),
- Core::ICore::instance()->mainWindow());
+ Core::Internal::ReadOnlyFilesDialog roDialog(roFiles.toList(), ICore::mainWindow());
roDialog.setShowFailWarning(true, tr("Aborting replace."));
if (roDialog.exec() == Core::Internal::ReadOnlyFilesDialog::RO_Cancel)
return QStringList();
diff --git a/src/plugins/texteditor/basefilefind.h b/src/plugins/texteditor/basefilefind.h
index 8d84d42b7e..f1a5861f7b 100644
--- a/src/plugins/texteditor/basefilefind.h
+++ b/src/plugins/texteditor/basefilefind.h
@@ -40,14 +40,12 @@ class QLabel;
class QComboBox;
QT_END_NAMESPACE
-namespace Utils {
-class FileIterator;
-}
+namespace Utils { class FileIterator; }
namespace Find {
class SearchResult;
-struct SearchResultItem;
+class SearchResultItem;
class IFindSupport;
-}
+} // namespace Find
namespace TextEditor {
namespace Internal {
diff --git a/src/plugins/texteditor/basehoverhandler.cpp b/src/plugins/texteditor/basehoverhandler.cpp
index e7a37ec0e4..8acdc55811 100644
--- a/src/plugins/texteditor/basehoverhandler.cpp
+++ b/src/plugins/texteditor/basehoverhandler.cpp
@@ -43,7 +43,7 @@ using namespace Core;
BaseHoverHandler::BaseHoverHandler(QObject *parent) : QObject(parent), m_diagnosticTooltip(false)
{
// Listen for editor opened events in order to connect to tooltip/helpid requests
- connect(ICore::editorManager(), SIGNAL(editorOpened(Core::IEditor*)),
+ connect(Core::EditorManager::instance(), SIGNAL(editorOpened(Core::IEditor*)),
this, SLOT(editorOpened(Core::IEditor*)));
}
@@ -84,7 +84,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 (!Utils::ToolTip::instance()->isVisible() || !lastHelpItemIdentified().isValid())
+ if (!Utils::ToolTip::isVisible() || !lastHelpItemIdentified().isValid())
process(editor, pos);
if (lastHelpItemIdentified().isValid())
@@ -157,9 +157,9 @@ void BaseHoverHandler::decorateToolTip()
void BaseHoverHandler::operateTooltip(ITextEditor *editor, const QPoint &point)
{
if (m_toolTip.isEmpty())
- Utils::ToolTip::instance()->hide();
+ Utils::ToolTip::hide();
else
- Utils::ToolTip::instance()->show(point, Utils::TextContent(m_toolTip), editor->widget());
+ Utils::ToolTip::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 21a4e2ead1..239041311c 100644
--- a/src/plugins/texteditor/basetextdocument.cpp
+++ b/src/plugins/texteditor/basetextdocument.cpp
@@ -51,13 +51,14 @@
#include <coreplugin/progressmanager/progressmanager.h>
#include <utils/qtcassert.h>
+using namespace Core;
+
namespace TextEditor {
class BaseTextDocumentPrivate
{
public:
explicit BaseTextDocumentPrivate(BaseTextDocument *q);
- QString m_fileName;
QString m_defaultPath;
QString m_suggestedFileName;
QString m_mimeType;
@@ -159,11 +160,6 @@ const ExtraEncodingSettings &BaseTextDocument::extraEncodingSettings() const
return d->m_extraEncodingSettings;
}
-QString BaseTextDocument::fileName() const
-{
- return d->m_fileName;
-}
-
bool BaseTextDocument::isSaveAsAllowed() const
{
return true;
@@ -214,7 +210,7 @@ ITextMarkable *BaseTextDocument::documentMarker() const
* If \a autoSave is true, the cursor will be restored and some signals suppressed
* and we do not clean up the text file (cleanWhitespace(), ensureFinalNewLine()).
*/
-bool BaseTextDocument::save(QString *errorString, const QString &fileName, bool autoSave)
+bool BaseTextDocument::save(QString *errorString, const QString &saveFileName, bool autoSave)
{
QTextCursor cursor(d->m_document);
@@ -228,7 +224,7 @@ bool BaseTextDocument::save(QString *errorString, const QString &fileName, bool
// When saving the current editor, make sure to maintain the cursor and scroll bar
// positions for undo
- Core::IEditor *currentEditor = Core::EditorManager::currentEditor();
+ IEditor *currentEditor = EditorManager::currentEditor();
if (BaseTextEditor *editable = qobject_cast<BaseTextEditor*>(currentEditor)) {
if (editable->document() == this) {
editorWidget = editable->editorWidget();
@@ -252,9 +248,9 @@ bool BaseTextDocument::save(QString *errorString, const QString &fileName, bool
cursor.endEditBlock();
}
- QString fName = d->m_fileName;
- if (!fileName.isEmpty())
- fName = fileName;
+ QString fName = filePath();
+ if (!saveFileName.isEmpty())
+ fName = saveFileName;
// check if UTF8-BOM has to be added or removed
Utils::TextFileFormat saveFormat = format();
@@ -294,33 +290,41 @@ bool BaseTextDocument::save(QString *errorString, const QString &fileName, bool
// inform about the new filename
const QFileInfo fi(fName);
- const QString oldFileName = d->m_fileName;
- d->m_fileName = QDir::cleanPath(fi.absoluteFilePath());
d->m_document->setModified(false);
- emit fileNameChanged(oldFileName, d->m_fileName);
- emit titleChanged(fi.fileName());
+ setFilePath(QDir::cleanPath(fi.absoluteFilePath()));
emit changed();
return true;
}
+bool BaseTextDocument::setContents(const QByteArray &contents)
+{
+ if (contents.size() > EditorManager::maxTextFileSize()) {
+ document()->setPlainText(BaseTextEditorWidget::msgTextTooLarge(contents.size()));
+ document()->setModified(false);
+ return false;
+ }
+ document()->setPlainText(QString::fromUtf8(contents));
+ document()->setModified(false);
+ return true;
+}
+
bool BaseTextDocument::shouldAutoSave() const
{
return d->m_autoSaveRevision != d->m_document->revision();
}
-void BaseTextDocument::rename(const QString &newName)
+void BaseTextDocument::setFilePath(const QString &newName)
{
+ if (newName == filePath())
+ return;
const QFileInfo fi(newName);
- const QString oldFileName = d->m_fileName;
- d->m_fileName = QDir::cleanPath(fi.absoluteFilePath());
- emit fileNameChanged(oldFileName, d->m_fileName);
+ IDocument::setFilePath(QDir::cleanPath(fi.absoluteFilePath()));
emit titleChanged(fi.fileName());
- emit changed();
}
bool BaseTextDocument::isFileReadOnly() const
{
- if (d->m_fileName.isEmpty()) //have no corresponding file, so editing is ok
+ if (filePath().isEmpty()) //have no corresponding file, so editing is ok
return false;
return d->m_fileIsReadOnly;
}
@@ -333,8 +337,8 @@ bool BaseTextDocument::isModified() const
void BaseTextDocument::checkPermissions()
{
bool previousReadOnly = d->m_fileIsReadOnly;
- if (!d->m_fileName.isEmpty()) {
- const QFileInfo fi(d->m_fileName);
+ if (!filePath().isEmpty()) {
+ const QFileInfo fi(filePath());
d->m_fileIsReadOnly = !fi.isWritable();
} else {
d->m_fileIsReadOnly = false;
@@ -345,7 +349,6 @@ void BaseTextDocument::checkPermissions()
bool BaseTextDocument::open(QString *errorString, const QString &fileName, const QString &realFileName)
{
- QString title = tr("untitled");
QStringList content;
ReadResult readResult = Utils::TextFileFormat::ReadIOError;
@@ -353,9 +356,6 @@ bool BaseTextDocument::open(QString *errorString, const QString &fileName, const
if (!fileName.isEmpty()) {
const QFileInfo fi(fileName);
d->m_fileIsReadOnly = !fi.isWritable();
- d->m_fileName = QDir::cleanPath(fi.absoluteFilePath());
-
- title = fi.fileName();
readResult = read(realFileName, &content, errorString);
d->m_document->setModified(false);
@@ -367,8 +367,7 @@ bool BaseTextDocument::open(QString *errorString, const QString &fileName, const
} else {
QFutureInterface<void> interface;
interface.setProgressRange(0, chunks);
- Core::ICore::progressManager()->addTask(
- interface.future(), tr("Opening file"), QLatin1String(Constants::TASK_OPEN_FILE));
+ ProgressManager::addTask(interface.future(), tr("Opening file"), Constants::TASK_OPEN_FILE);
interface.reportStarted();
d->m_document->setUndoRedoEnabled(false);
QTextCursor c(d->m_document);
@@ -388,8 +387,7 @@ bool BaseTextDocument::open(QString *errorString, const QString &fileName, const
QTC_ASSERT(documentLayout, return true);
documentLayout->lastSaveRevision = d->m_autoSaveRevision = d->m_document->revision();
d->m_document->setModified(fileName != realFileName);
- emit titleChanged(title);
- emit changed();
+ setFilePath(QDir::cleanPath(fi.absoluteFilePath()));
}
return readResult == Utils::TextFileFormat::ReadSuccess
|| readResult == Utils::TextFileFormat::ReadEncodingError;
@@ -411,7 +409,7 @@ bool BaseTextDocument::reload(QString *errorString)
if (documentLayout)
marks = documentLayout->documentClosing(); // removes text marks non-permanently
- bool success = open(errorString, d->m_fileName, d->m_fileName);
+ bool success = open(errorString, filePath(), filePath());
if (documentLayout)
documentLayout->documentReloaded(marks); // readds text marks
diff --git a/src/plugins/texteditor/basetextdocument.h b/src/plugins/texteditor/basetextdocument.h
index 3e9e90688b..a8f8f2ca7a 100644
--- a/src/plugins/texteditor/basetextdocument.h
+++ b/src/plugins/texteditor/basetextdocument.h
@@ -75,20 +75,20 @@ public:
ITextMarkable *documentMarker() const;
// IDocument implementation.
- virtual bool save(QString *errorString, const QString &fileName, bool autoSave);
- virtual QString fileName() const;
- virtual bool shouldAutoSave() const;
- virtual bool isFileReadOnly() const;
- virtual bool isModified() const;
- virtual bool isSaveAsAllowed() const;
- virtual void checkPermissions();
+ bool save(QString *errorString, const QString &fileName, bool autoSave);
+ bool setContents(const QByteArray &contents);
+ bool shouldAutoSave() const;
+ bool isFileReadOnly() const;
+ bool isModified() const;
+ bool isSaveAsAllowed() const;
+ void checkPermissions();
bool reload(QString *errorString, ReloadFlag flag, ChangeType type);
- virtual QString mimeType() const;
+ QString mimeType() const;
void setMimeType(const QString &mt);
- virtual void rename(const QString &newName);
+ void setFilePath(const QString &newName);
- virtual QString defaultPath() const;
- virtual QString suggestedFileName() const;
+ QString defaultPath() const;
+ QString suggestedFileName() const;
void setDefaultPath(const QString &defaultPath);
void setSuggestedFileName(const QString &suggestedFileName);
diff --git a/src/plugins/texteditor/basetextdocumentlayout.cpp b/src/plugins/texteditor/basetextdocumentlayout.cpp
index 263c78eb1a..f8bccb4e4c 100644
--- a/src/plugins/texteditor/basetextdocumentlayout.cpp
+++ b/src/plugins/texteditor/basetextdocumentlayout.cpp
@@ -680,10 +680,8 @@ void BaseTextDocumentLayout::setFolded(const QTextBlock &block, bool folded)
{
if (folded)
userData(block)->setFolded(true);
- else {
- if (TextBlockUserData *userData = testUserData(block))
- return userData->setFolded(false);
- }
+ else if (TextBlockUserData *userData = testUserData(block))
+ return userData->setFolded(false);
}
void BaseTextDocumentLayout::requestExtraAreaUpdate()
diff --git a/src/plugins/texteditor/basetexteditor.cpp b/src/plugins/texteditor/basetexteditor.cpp
index 7fdb2c9534..504404b979 100644
--- a/src/plugins/texteditor/basetexteditor.cpp
+++ b/src/plugins/texteditor/basetexteditor.cpp
@@ -35,20 +35,20 @@
#include "behaviorsettings.h"
#include "codecselector.h"
#include "completionsettings.h"
+#include "snippets/snippet.h"
#include "tabsettings.h"
#include "typingsettings.h"
#include "icodestylepreferences.h"
#include "syntaxhighlighter.h"
#include "indenter.h"
#include "autocompleter.h"
-#include "snippet.h"
-#include "codeassistant.h"
-#include "defaultassistinterface.h"
#include "convenience.h"
#include "texteditorsettings.h"
#include "texteditoroverlay.h"
#include "circularclipboard.h"
#include "circularclipboardassist.h"
+#include <texteditor/codeassist/codeassistant.h>
+#include <texteditor/codeassist/defaultassistinterface.h>
#include <aggregation/aggregate.h>
#include <coreplugin/actionmanager/actionmanager.h>
@@ -335,7 +335,7 @@ void BaseTextEditorWidgetPrivate::print(QPrinter *printer)
{
QTextDocument *doc = q->document();
- QString title = q->displayName();
+ QString title = m_document->displayName();
if (title.isEmpty())
printer->setDocName(title);
@@ -499,7 +499,9 @@ BaseTextEditor *BaseTextEditorWidget::editor() const
connect(this, SIGNAL(textChanged()),
d->m_editor, SIGNAL(contentsChanged()));
connect(this, SIGNAL(changed()),
- d->m_editor, SIGNAL(changed()));
+ d->m_editor->document(), SIGNAL(changed()));
+ connect(qobject_cast<BaseTextDocument *>(d->m_editor->document()),SIGNAL(mimeTypeChanged()),
+ d->m_codeAssistant.data(), SLOT(reconfigure()));
}
return d->m_editor;
}
@@ -520,7 +522,7 @@ void BaseTextEditorWidget::selectEncoding()
break; }
case CodecSelector::Save:
doc->setCodec(codecSelector.selectedCodec());
- Core::EditorManager::instance()->saveEditor(editor());
+ Core::EditorManager::saveEditor(editor());
updateTextCodecLabel();
break;
case CodecSelector::Cancel:
@@ -539,25 +541,13 @@ QString BaseTextEditorWidget::msgTextTooLarge(quint64 size)
arg(size >> 20);
}
-bool BaseTextEditorWidget::createNew(const QString &contents)
-{
- if (contents.size() > Core::EditorManager::maxTextFileSize()) {
- setPlainText(msgTextTooLarge(contents.size()));
- document()->setModified(false);
- return false;
- }
- setPlainText(contents);
- document()->setModified(false);
- return true;
-}
-
void BaseTextEditorWidget::updateCannotDecodeInfo()
{
setReadOnly(d->m_document->hasDecodingError());
if (d->m_document->hasDecodingError()) {
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())));
+ .arg(d->m_document->displayName()).arg(QString::fromLatin1(d->m_document->codec()->name())));
info.setCustomButtonInfo(tr("Select Encoding"), this, SLOT(selectEncoding()));
d->m_document->infoBar()->addInfo(info);
} else {
@@ -1436,55 +1426,44 @@ 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) {
+ } else if (e == QKeySequence::SelectNextChar) {
op = QTextCursor::Right;
mode = QTextCursor::KeepAnchor;
- }
- else if (e == QKeySequence::SelectPreviousChar) {
+ } else if (e == QKeySequence::SelectPreviousChar) {
op = QTextCursor::Left;
mode = QTextCursor::KeepAnchor;
- }
- else if (e == QKeySequence::SelectNextWord) {
+ } else if (e == QKeySequence::SelectNextWord) {
op = QTextCursor::WordRight;
mode = QTextCursor::KeepAnchor;
- }
- else if (e == QKeySequence::SelectPreviousWord) {
+ } else if (e == QKeySequence::SelectPreviousWord) {
op = QTextCursor::WordLeft;
mode = QTextCursor::KeepAnchor;
- }
- else if (e == QKeySequence::SelectStartOfLine) {
+ } else if (e == QKeySequence::SelectStartOfLine) {
op = QTextCursor::StartOfLine;
mode = QTextCursor::KeepAnchor;
- }
- else if (e == QKeySequence::SelectEndOfLine) {
+ } else if (e == QKeySequence::SelectEndOfLine) {
op = QTextCursor::EndOfLine;
mode = QTextCursor::KeepAnchor;
- }
- else if (e == QKeySequence::SelectStartOfBlock) {
+ } else if (e == QKeySequence::SelectStartOfBlock) {
op = QTextCursor::StartOfBlock;
mode = QTextCursor::KeepAnchor;
- }
- else if (e == QKeySequence::SelectEndOfBlock) {
+ } else if (e == QKeySequence::SelectEndOfBlock) {
op = QTextCursor::EndOfBlock;
mode = QTextCursor::KeepAnchor;
- }
- else if (e == QKeySequence::SelectStartOfDocument) {
+ } else if (e == QKeySequence::SelectStartOfDocument) {
op = QTextCursor::Start;
mode = QTextCursor::KeepAnchor;
- }
- else if (e == QKeySequence::SelectEndOfDocument) {
+ } else if (e == QKeySequence::SelectEndOfDocument) {
op = QTextCursor::End;
mode = QTextCursor::KeepAnchor;
- }
- else if (e == QKeySequence::SelectPreviousLine) {
+ } else if (e == QKeySequence::SelectPreviousLine) {
op = QTextCursor::Up;
mode = QTextCursor::KeepAnchor;
- }
- else if (e == QKeySequence::SelectNextLine) {
+ } else if (e == QKeySequence::SelectNextLine) {
op = QTextCursor::Down;
mode = QTextCursor::KeepAnchor;
{
@@ -1495,41 +1474,29 @@ bool BaseTextEditorWidget::cursorMoveKeyEvent(QKeyEvent *e)
&& line.lineNumber() == block.layout()->lineCount() - 1)
op = QTextCursor::End;
}
- }
- else if (e == QKeySequence::MoveToNextWord) {
+ } else if (e == QKeySequence::MoveToNextWord) {
op = QTextCursor::WordRight;
- }
- else if (e == QKeySequence::MoveToPreviousWord) {
+ } else if (e == QKeySequence::MoveToPreviousWord) {
op = QTextCursor::WordLeft;
- }
- else if (e == QKeySequence::MoveToEndOfBlock) {
+ } else if (e == QKeySequence::MoveToEndOfBlock) {
op = QTextCursor::EndOfBlock;
- }
- else if (e == QKeySequence::MoveToStartOfBlock) {
+ } else if (e == QKeySequence::MoveToStartOfBlock) {
op = QTextCursor::StartOfBlock;
- }
- else if (e == QKeySequence::MoveToNextLine) {
+ } else if (e == QKeySequence::MoveToNextLine) {
op = QTextCursor::Down;
- }
- else if (e == QKeySequence::MoveToPreviousLine) {
+ } else if (e == QKeySequence::MoveToPreviousLine) {
op = QTextCursor::Up;
- }
- else if (e == QKeySequence::MoveToPreviousLine) {
+ } else if (e == QKeySequence::MoveToPreviousLine) {
op = QTextCursor::Up;
- }
- else if (e == QKeySequence::MoveToStartOfLine) {
+ } else if (e == QKeySequence::MoveToStartOfLine) {
op = QTextCursor::StartOfLine;
- }
- else if (e == QKeySequence::MoveToEndOfLine) {
+ } else if (e == QKeySequence::MoveToEndOfLine) {
op = QTextCursor::EndOfLine;
- }
- else if (e == QKeySequence::MoveToStartOfDocument) {
+ } else if (e == QKeySequence::MoveToStartOfDocument) {
op = QTextCursor::Start;
- }
- else if (e == QKeySequence::MoveToEndOfDocument) {
+ } else if (e == QKeySequence::MoveToEndOfDocument) {
op = QTextCursor::End;
- }
- else {
+ } else {
return false;
}
@@ -1579,7 +1546,7 @@ void BaseTextEditorWidget::keyPressEvent(QKeyEvent *e)
{
if (!isModifier(e))
viewport()->setCursor(Qt::BlankCursor);
- ToolTip::instance()->hide();
+ ToolTip::hide();
d->m_moveLineUndoHack = false;
d->clearVisibleFoldedBlock();
@@ -1593,6 +1560,7 @@ void BaseTextEditorWidget::keyPressEvent(QKeyEvent *e)
&& d->m_snippetOverlay->isVisible()) {
e->accept();
d->m_snippetOverlay->hide();
+ d->m_snippetOverlay->mangle();
d->m_snippetOverlay->clear();
QTextCursor cursor = textCursor();
cursor.clearSelection();
@@ -1632,6 +1600,7 @@ void BaseTextEditorWidget::keyPressEvent(QKeyEvent *e)
if (d->m_snippetOverlay->isVisible()) {
e->accept();
d->m_snippetOverlay->hide();
+ d->m_snippetOverlay->mangle();
d->m_snippetOverlay->clear();
QTextCursor cursor = textCursor();
cursor.movePosition(QTextCursor::EndOfBlock);
@@ -1877,9 +1846,7 @@ void BaseTextEditorWidget::keyPressEvent(QKeyEvent *e)
}
if (ro || e->text().isEmpty() || !e->text().at(0).isPrint()) {
- if (cursorMoveKeyEvent(e))
- ;
- else {
+ if (!cursorMoveKeyEvent(e)) {
QTextCursor cursor = textCursor();
bool cursorWithinSnippet = false;
if (d->m_snippetOverlay->isVisible()
@@ -1942,8 +1909,6 @@ void BaseTextEditorWidget::keyPressEvent(QKeyEvent *e)
if (!electricChar.isNull() && d->m_autoCompleter->contextAllowsElectricCharacters(cursor))
indent(document(), cursor, electricChar);
if (!autoText.isEmpty()) {
- if (d->m_document->typingSettings().m_autoIndent)
- reindent(document(), cursor);
cursor.setPosition(autoText.length() == 1 ? cursor.position() : cursor.anchor());
}
@@ -1968,57 +1933,20 @@ void BaseTextEditorWidget::keyPressEvent(QKeyEvent *e)
void BaseTextEditorWidget::insertCodeSnippet(const QTextCursor &cursor_arg, const QString &snippet)
{
- if ((snippet.count(Snippet::kVariableDelimiter) % 2) != 0) {
- qWarning() << "invalid snippet";
- return;
- }
-
- QList<QTextEdit::ExtraSelection> selections;
+ Snippet::ParsedSnippet data = Snippet::parse(snippet);
QTextCursor cursor = cursor_arg;
cursor.beginEditBlock();
cursor.removeSelectedText();
const int startCursorPosition = cursor.position();
- int pos = 0;
- QMap<int, int> positions;
-
- while (pos < snippet.size()) {
- if (snippet.at(pos) != Snippet::kVariableDelimiter) {
- const int start = pos;
- do { ++pos; }
- while (pos < snippet.size() && snippet.at(pos) != Snippet::kVariableDelimiter);
- cursor.insertText(snippet.mid(start, pos - start));
- } else {
- // the start of a place holder.
- const int start = ++pos;
- for (; pos < snippet.size(); ++pos) {
- if (snippet.at(pos) == Snippet::kVariableDelimiter)
- break;
- }
-
- Q_ASSERT(pos < snippet.size());
- Q_ASSERT(snippet.at(pos) == Snippet::kVariableDelimiter);
-
- const QString textToInsert = snippet.mid(start, pos - start);
-
- int cursorPosition = cursor.position();
- cursor.insertText(textToInsert);
-
- if (textToInsert.isEmpty())
- positions.insert(cursorPosition, 0);
- else
- positions.insert(cursorPosition, textToInsert.length());
-
- ++pos;
- }
- }
+ cursor.insertText(data.text);
+ QList<QTextEdit::ExtraSelection> selections;
- QMapIterator<int,int> it(positions);
- while (it.hasNext()) {
- it.next();
- int length = it.value();
- int position = it.key();
+ QList<NameMangler *> manglers;
+ for (int i = 0; i < data.ranges.count(); ++i) {
+ int position = data.ranges.at(i).start + startCursorPosition;
+ int length = data.ranges.at(i).length;
QTextCursor tc(document());
tc.setPosition(position);
@@ -2027,6 +1955,7 @@ void BaseTextEditorWidget::insertCodeSnippet(const QTextCursor &cursor_arg, cons
selection.cursor = tc;
selection.format = (length ? d->m_occurrencesFormat : d->m_occurrenceRenameFormat);
selections.append(selection);
+ manglers << data.ranges.at(i).mangler;
}
cursor.setPosition(startCursorPosition, QTextCursor::KeepAnchor);
@@ -2034,8 +1963,9 @@ void BaseTextEditorWidget::insertCodeSnippet(const QTextCursor &cursor_arg, cons
cursor.endEditBlock();
setExtraSelections(BaseTextEditorWidget::SnippetPlaceholderSelection, selections);
+ d->m_snippetOverlay->setNameMangler(manglers);
- if (! selections.isEmpty()) {
+ if (!selections.isEmpty()) {
const QTextEdit::ExtraSelection &selection = selections.first();
cursor = textCursor();
@@ -2047,7 +1977,6 @@ void BaseTextEditorWidget::insertCodeSnippet(const QTextCursor &cursor_arg, cons
}
setTextCursor(cursor);
}
-
}
void BaseTextEditorWidget::universalHelper()
@@ -2153,7 +2082,6 @@ void BaseTextEditorWidget::duplicateFrom(BaseTextEditorWidget *widget)
{
if (this == widget)
return;
- setDisplayName(widget->displayName());
d->m_revisionsVisible = widget->d->m_revisionsVisible;
if (d->m_document == widget->d->m_document)
return;
@@ -2161,17 +2089,6 @@ void BaseTextEditorWidget::duplicateFrom(BaseTextEditorWidget *widget)
d->m_document = widget->d->m_document;
}
-QString BaseTextEditorWidget::displayName() const
-{
- return d->m_displayName;
-}
-
-void BaseTextEditorWidget::setDisplayName(const QString &title)
-{
- d->m_displayName = title;
- emit changed();
-}
-
QSharedPointer<BaseTextDocument> BaseTextEditorWidget::baseTextDocument() const
{
return d->m_document;
@@ -2584,8 +2501,6 @@ void BaseTextEditorWidgetPrivate::setupDocumentSignals(const QSharedPointer<Base
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.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(reloadFinished(bool)), q, SLOT(documentReloadFinished(bool)));
q->slotUpdateExtraAreaWidth();
@@ -2605,6 +2520,7 @@ bool BaseTextEditorWidgetPrivate::snippetCheckCursor(const QTextCursor &cursor)
|| !m_snippetOverlay->hasCursorInSelection(end)
|| m_snippetOverlay->hasFirstSelectionBeginMoved()) {
m_snippetOverlay->setVisible(false);
+ m_snippetOverlay->mangle();
m_snippetOverlay->clear();
return false;
}
@@ -2681,8 +2597,7 @@ bool BaseTextEditorWidget::viewportEvent(QEvent *event)
RefactorMarker refactorMarker = d->m_refactorOverlay->markerAt(pos);
if (refactorMarker.isValid() && !refactorMarker.tooltip.isEmpty()) {
- ToolTip::instance()->show(he->globalPos(),
- TextContent(refactorMarker.tooltip),
+ ToolTip::show(he->globalPos(), TextContent(refactorMarker.tooltip),
viewport(),
refactorMarker.rect);
return true;
@@ -4027,9 +3942,9 @@ void BaseTextEditorWidget::slotModificationChanged(bool m)
void BaseTextEditorWidget::slotUpdateRequest(const QRect &r, int dy)
{
- if (dy)
+ if (dy) {
d->m_extraArea->scroll(0, dy);
- else if (r.width() > 4) { // wider than cursor width, not just cursor blinking
+ } else if (r.width() > 4) { // wider than cursor width, not just cursor blinking
d->m_extraArea->update(0, r.y(), d->m_extraArea->width(), r.height());
if (!d->m_searchExpr.isEmpty()) {
const int m = d->m_searchResultOverlay->dropShadowWidth();
@@ -4087,7 +4002,7 @@ void BaseTextEditorWidget::slotCursorPositionChanged()
<< "indent:" << BaseTextDocumentLayout::userData(textCursor().block())->foldingIndent();
#endif
if (!d->m_contentsChanged && d->m_lastCursorChangeWasInteresting) {
- Core::EditorManager::instance()->addCurrentPositionToNavigationHistory(editor(), d->m_tempNavigationState);
+ Core::EditorManager::addCurrentPositionToNavigationHistory(editor(), d->m_tempNavigationState);
d->m_lastCursorChangeWasInteresting = false;
} else if (d->m_contentsChanged) {
saveCurrentCursorPositionForNavigation();
@@ -4253,11 +4168,11 @@ void BaseTextEditorWidget::mouseMoveEvent(QMouseEvent *e)
static bool handleForwardBackwardMouseButtons(QMouseEvent *e)
{
if (e->button() == Qt::XButton1) {
- Core::EditorManager::instance()->goBackInNavigationHistory();
+ Core::EditorManager::goBackInNavigationHistory();
return true;
}
if (e->button() == Qt::XButton2) {
- Core::EditorManager::instance()->goForwardInNavigationHistory();
+ Core::EditorManager::goForwardInNavigationHistory();
return true;
}
@@ -4307,7 +4222,7 @@ void BaseTextEditorWidget::mouseReleaseEvent(QMouseEvent *e)
&& e->button() == Qt::LeftButton
) {
- Core::EditorManager::instance()->addCurrentPositionToNavigationHistory();
+ Core::EditorManager::addCurrentPositionToNavigationHistory();
bool inNextSplit = ((e->modifiers() & Qt::AltModifier) && !alwaysOpenLinksInNextSplit())
|| (alwaysOpenLinksInNextSplit() && !(e->modifiers() & Qt::AltModifier));
if (openLink(findLinkAt(cursorForPosition(e->pos())), inNextSplit)) {
@@ -4349,8 +4264,8 @@ void BaseTextEditorWidget::keyReleaseEvent(QKeyEvent *e)
clearLink();
} else if (e->key() == Qt::Key_Shift
&& d->m_behaviorSettings.m_constrainHoverTooltips
- && ToolTip::instance()->isVisible()) {
- ToolTip::instance()->hide();
+ && ToolTip::isVisible()) {
+ ToolTip::hide();
} else if (e->key() == Qt::Key_Alt
&& d->m_maybeFakeTooltipEvent) {
d->m_maybeFakeTooltipEvent = false;
@@ -4643,7 +4558,7 @@ void BaseTextEditorWidget::onCodeStylePreferencesDestroyed()
{
if (sender() != d->m_codeStylePreferences)
return;
- ICodeStylePreferences *prefs = TextEditorSettings::instance()->codeStyle(languageSettingsId());
+ ICodeStylePreferences *prefs = TextEditorSettings::codeStyle(languageSettingsId());
if (prefs == d->m_codeStylePreferences)
prefs = 0;
// avoid failing disconnects, m_codeStylePreferences has already been reduced to QObject
@@ -4785,6 +4700,7 @@ void BaseTextEditorWidget::handleBackspaceKey()
handled = true;
} else {
if (cursorWithinSnippet) {
+ d->m_snippetOverlay->mangle();
d->m_snippetOverlay->clear();
cursorWithinSnippet = false;
}
@@ -4817,6 +4733,7 @@ void BaseTextEditorWidget::handleBackspaceKey()
cursor.deletePreviousChar();
} else {
if (cursorWithinSnippet) {
+ d->m_snippetOverlay->mangle();
d->m_snippetOverlay->clear();
cursorWithinSnippet = false;
}
@@ -4896,11 +4813,10 @@ bool BaseTextEditorWidget::openLink(const Link &link, bool inNextSplit)
if (!link.hasValidTarget())
return false;
- Core::EditorManager *editorManager = Core::EditorManager::instance();
if (inNextSplit) {
- editorManager->gotoOtherSplit();
- } else if (baseTextDocument()->fileName() == link.targetFileName) {
- editorManager->addCurrentPositionToNavigationHistory();
+ Core::EditorManager::gotoOtherSplit();
+ } else if (baseTextDocument()->filePath() == link.targetFileName) {
+ Core::EditorManager::addCurrentPositionToNavigationHistory();
gotoLine(link.targetLine, link.targetColumn);
setFocus();
return true;
@@ -5406,6 +5322,7 @@ void BaseTextEditorWidget::setExtraSelections(ExtraSelectionKind kind, const QLi
}
d->m_overlay->setVisible(!d->m_overlay->isEmpty());
} else if (kind == SnippetPlaceholderSelection) {
+ d->m_snippetOverlay->mangle();
d->m_snippetOverlay->clear();
foreach (const QTextEdit::ExtraSelection &selection, d->m_extraSelections[kind]) {
d->m_snippetOverlay->addOverlaySelection(selection.cursor,
@@ -5467,7 +5384,7 @@ QString BaseTextEditorWidget::extraSelectionTooltip(int pos) const
}
// the blocks list must be sorted
-void BaseTextEditorWidget::setIfdefedOutBlocks(const QList<BaseTextEditorWidget::BlockRange> &blocks)
+void BaseTextEditorWidget::setIfdefedOutBlocks(const QList<BlockRange> &blocks)
{
QTextDocument *doc = document();
BaseTextDocumentLayout *documentLayout = qobject_cast<BaseTextDocumentLayout*>(doc->documentLayout());
@@ -5484,11 +5401,12 @@ 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
cleared = BaseTextDocumentLayout::clearIfdefedOut(block);
- if (block.contains(range.last))
+ if (block.contains(range.last()))
++rangeNumber;
} else {
cleared = BaseTextDocumentLayout::clearIfdefedOut(block);
@@ -5724,6 +5642,12 @@ void BaseTextEditorWidget::setFontSettings(const TextEditor::FontSettings &fs)
slotUpdateExtraAreaWidth(); // Adjust to new font width
updateCurrentLineHighlight(); // Make sure it takes the new color
+
+ SyntaxHighlighter *highlighter = baseTextDocument()->syntaxHighlighter();
+ if (highlighter) {
+ highlighter->setFontSettings(fs);
+ highlighter->rehighlight();
+ }
}
void BaseTextEditorWidget::setTabSettings(const TabSettings &ts)
@@ -5863,17 +5787,6 @@ void BaseTextEditorWidget::unfoldAll()
centerCursor();
}
-void BaseTextEditorWidget::setTextCodec(QTextCodec *codec)
-{
- baseTextDocument()->setCodec(codec);
-}
-
-QTextCodec *BaseTextEditorWidget::textCodec() const
-{
- // TODO: Fix all QTextCodec usages to be const *.
- return const_cast<QTextCodec *>(baseTextDocument()->codec());
-}
-
void BaseTextEditorWidget::setReadOnly(bool b)
{
QPlainTextEdit::setReadOnly(b);
@@ -5889,6 +5802,7 @@ void BaseTextEditorWidget::cut()
return;
}
QPlainTextEdit::cut();
+ collectToCircularClipboard();
}
void BaseTextEditorWidget::selectAll()
@@ -5903,14 +5817,18 @@ void BaseTextEditorWidget::copy()
return;
QPlainTextEdit::copy();
+ collectToCircularClipboard();
+}
+void BaseTextEditorWidget::collectToCircularClipboard()
+{
const QMimeData *mimeData = QApplication::clipboard()->mimeData();
- if (mimeData) {
- CircularClipboard *circularClipBoard = CircularClipboard::instance();
- circularClipBoard->collect(duplicateMimeData(mimeData));
- // We want the latest copied content to be the first one to appear on circular paste.
- circularClipBoard->toLastCollect();
- }
+ if (!mimeData)
+ return;
+ CircularClipboard *circularClipBoard = CircularClipboard::instance();
+ circularClipBoard->collect(duplicateMimeData(mimeData));
+ // We want the latest copied content to be the first one to appear on circular paste.
+ circularClipBoard->toLastCollect();
}
void BaseTextEditorWidget::paste()
@@ -6089,6 +6007,7 @@ void BaseTextEditorWidget::insertFromMimeData(const QMimeData *source)
if (d->m_snippetOverlay->isVisible() && lines.count() > 1) {
d->m_snippetOverlay->hide();
+ d->m_snippetOverlay->mangle();
d->m_snippetOverlay->clear();
}
@@ -6105,6 +6024,7 @@ void BaseTextEditorWidget::insertFromMimeData(const QMimeData *source)
if (d->m_snippetOverlay->isVisible() && (text.contains(QLatin1Char('\n'))
|| text.contains(QLatin1Char('\t')))) {
d->m_snippetOverlay->hide();
+ d->m_snippetOverlay->mangle();
d->m_snippetOverlay->clear();
}
@@ -6395,6 +6315,11 @@ const CommentDefinition *BaseTextEditor::commentDefinition() const
return 0;
}
+CompletionAssistProvider *BaseTextEditor::completionAssistProvider()
+{
+ return 0;
+}
+
void BaseTextEditor::updateCursorPosition()
{
const QTextCursor cursor = m_editorWidget->textCursor();
@@ -6724,7 +6649,7 @@ IAssistInterface *BaseTextEditorWidget::createAssistInterface(AssistKind kind,
AssistReason reason) const
{
Q_UNUSED(kind);
- return new DefaultAssistInterface(document(), position(), d->m_document->fileName(), reason);
+ return new DefaultAssistInterface(document(), position(), d->m_document->filePath(), reason);
}
QString TextEditor::BaseTextEditorWidget::foldReplacementText(const QTextBlock &) const
diff --git a/src/plugins/texteditor/basetexteditor.h b/src/plugins/texteditor/basetexteditor.h
index ce99441e20..2f7ee2ee93 100644
--- a/src/plugins/texteditor/basetexteditor.h
+++ b/src/plugins/texteditor/basetexteditor.h
@@ -58,6 +58,7 @@ class IAssistMonitorInterface;
class IAssistInterface;
class IAssistProvider;
class ICodeStylePreferences;
+class CompletionAssistProvider;
typedef QList<RefactorMarker> RefactorMarkers;
namespace Internal {
@@ -136,11 +137,9 @@ public:
// EditorInterface
Core::IDocument *editorDocument() const;
- bool createNew(const QString &contents);
virtual bool open(QString *errorString, const QString &fileName, const QString &realFileName);
QByteArray saveState() const;
bool restoreState(const QByteArray &state);
- QString displayName() const;
void gotoLine(int line, int column = 0);
@@ -213,9 +212,6 @@ public:
void setActionHack(QObject *hack);
QObject *actionHack() const;
- void setTextCodec(QTextCodec *codec);
- QTextCodec *textCodec() const;
-
void setReadOnly(bool b);
void setTextCursor(const QTextCursor &cursor);
@@ -244,9 +240,9 @@ public:
AssistReason assistReason) const;
QMimeData *duplicateMimeData(const QMimeData *source) const;
-public slots:
- void setDisplayName(const QString &title);
+ static QString msgTextTooLarge(quint64 size);
+public slots:
virtual void copy();
virtual void paste();
virtual void cut();
@@ -355,11 +351,11 @@ protected:
virtual bool selectionVisible(int blockNumber) const;
virtual bool replacementVisible(int blockNumber) const;
virtual QColor replacementPenColor(int blockNumber) const;
- static QString msgTextTooLarge(quint64 size);
private:
void maybeSelectLine();
void updateCannotDecodeInfo();
+ void collectToCircularClipboard();
public:
void duplicateFrom(BaseTextEditorWidget *editor);
@@ -434,18 +430,6 @@ signals:
void refactorMarkerClicked(const TextEditor::RefactorMarker &marker);
public:
-
- struct BlockRange
- {
- BlockRange() : first(0), last(-1) {}
- BlockRange(int first_position, int last_position)
- : first(first_position), last(last_position)
- {}
- int first;
- int last;
- inline bool isNull() const { return last < first; }
- };
-
// the blocks list must be sorted
void setIfdefedOutBlocks(const QList<BlockRange> &blocks);
@@ -615,10 +599,7 @@ public:
// IEditor
Core::IDocument *document() { return m_editorWidget->editorDocument(); }
- bool createNew(const QString &contents) { return m_editorWidget->createNew(contents); }
bool open(QString *errorString, const QString &fileName, const QString &realFileName);
- QString displayName() const { return m_editorWidget->displayName(); }
- void setDisplayName(const QString &title) { m_editorWidget->setDisplayName(title); emit changed(); }
QByteArray saveState() const { return m_editorWidget->saveState(); }
bool restoreState(const QByteArray &state) { return m_editorWidget->restoreState(state); }
@@ -646,9 +627,6 @@ public:
QString contextHelpId() const; // from IContext
- void setTextCodec(QTextCodec *codec, TextCodecReason = TextCodecOtherReason) { m_editorWidget->setTextCodec(codec); }
- QTextCodec *textCodec() const { return m_editorWidget->textCodec(); }
-
// ITextEditor
void remove(int length);
void insert(const QString &string);
@@ -657,6 +635,8 @@ public:
void select(int toPos);
const Utils::CommentDefinition *commentDefinition() const;
+ virtual CompletionAssistProvider *completionAssistProvider();
+
private slots:
void updateCursorPosition();
void openGotoLocator();
diff --git a/src/plugins/texteditor/basetexteditor_p.h b/src/plugins/texteditor/basetexteditor_p.h
index 7771a5e68c..e21677de32 100644
--- a/src/plugins/texteditor/basetexteditor_p.h
+++ b/src/plugins/texteditor/basetexteditor_p.h
@@ -123,7 +123,6 @@ public:
QByteArray m_tempState;
QByteArray m_tempNavigationState;
- QString m_displayName;
bool m_parenthesesMatchingEnabled;
QTimer *m_updateTimer;
diff --git a/src/plugins/texteditor/basetextmark.cpp b/src/plugins/texteditor/basetextmark.cpp
index 23622a4893..dbef43c04c 100644
--- a/src/plugins/texteditor/basetextmark.cpp
+++ b/src/plugins/texteditor/basetextmark.cpp
@@ -38,39 +38,41 @@
#include <extensionsystem/pluginmanager.h>
#include <utils/qtcassert.h>
-using namespace TextEditor;
-using namespace TextEditor::Internal;
+using namespace Core;
+using namespace Utils;
+
+namespace TextEditor {
+namespace Internal {
BaseTextMarkRegistry::BaseTextMarkRegistry(QObject *parent)
: QObject(parent)
{
- Core::EditorManager *em = Core::EditorManager::instance();
- connect(em, SIGNAL(editorOpened(Core::IEditor*)),
+ connect(EditorManager::instance(), SIGNAL(editorOpened(Core::IEditor*)),
SLOT(editorOpened(Core::IEditor*)));
- Core::DocumentManager *dm = Core::DocumentManager::instance();
- connect(dm, SIGNAL(allDocumentsRenamed(QString,QString)),
+ connect(DocumentManager::instance(), SIGNAL(allDocumentsRenamed(QString,QString)),
this, SLOT(allDocumentsRenamed(QString,QString)));
- connect(dm, SIGNAL(documentRenamed(Core::IDocument*,QString,QString)),
+ connect(DocumentManager::instance(), SIGNAL(documentRenamed(Core::IDocument*,QString,QString)),
this, SLOT(documentRenamed(Core::IDocument*,QString,QString)));
}
void BaseTextMarkRegistry::add(BaseTextMark *mark)
{
- m_marks[Utils::FileName::fromString(mark->fileName())].insert(mark);
- Core::EditorManager *em = Core::EditorManager::instance();
- foreach (Core::IEditor *editor, em->editorsForFileName(mark->fileName())) {
- if (ITextEditor *textEditor = qobject_cast<ITextEditor *>(editor)) {
- ITextMarkable *markableInterface = textEditor->markableInterface();
- if (markableInterface->addMark(mark))
- break;
- }
+ m_marks[FileName::fromString(mark->fileName())].insert(mark);
+ DocumentModel *documentModel = EditorManager::documentModel();
+ IDocument *document = documentModel->documentForFilePath(mark->fileName());
+ if (!document)
+ return;
+ // TODO: markableInterface should be moved to ITextEditorDocument
+ if (ITextEditor *textEditor
+ = qobject_cast<ITextEditor *>(documentModel->editorsForDocument(document).first())) {
+ textEditor->markableInterface()->addMark(mark);
}
}
bool BaseTextMarkRegistry::remove(BaseTextMark *mark)
{
- return m_marks[Utils::FileName::fromString(mark->fileName())].remove(mark);
+ return m_marks[FileName::fromString(mark->fileName())].remove(mark);
}
void BaseTextMarkRegistry::editorOpened(Core::IEditor *editor)
@@ -78,24 +80,24 @@ void BaseTextMarkRegistry::editorOpened(Core::IEditor *editor)
ITextEditor *textEditor = qobject_cast<ITextEditor *>(editor);
if (!textEditor)
return;
- if (!m_marks.contains(Utils::FileName::fromString(editor->document()->fileName())))
+ if (!m_marks.contains(FileName::fromString(editor->document()->filePath())))
return;
- foreach (BaseTextMark *mark, m_marks.value(Utils::FileName::fromString(editor->document()->fileName()))) {
+ foreach (BaseTextMark *mark, m_marks.value(FileName::fromString(editor->document()->filePath()))) {
ITextMarkable *markableInterface = textEditor->markableInterface();
markableInterface->addMark(mark);
}
}
-void BaseTextMarkRegistry::documentRenamed(Core::IDocument *document, const
+void BaseTextMarkRegistry::documentRenamed(IDocument *document, const
QString &oldName, const QString &newName)
{
TextEditor::BaseTextDocument *baseTextDocument
= qobject_cast<TextEditor::BaseTextDocument *>(document);
if (!document)
return;
- Utils::FileName oldFileName = Utils::FileName::fromString(oldName);
- Utils::FileName newFileName = Utils::FileName::fromString(newName);
+ FileName oldFileName = FileName::fromString(oldName);
+ FileName newFileName = FileName::fromString(newName);
if (!m_marks.contains(oldFileName))
return;
@@ -113,8 +115,8 @@ void BaseTextMarkRegistry::documentRenamed(Core::IDocument *document, const
void BaseTextMarkRegistry::allDocumentsRenamed(const QString &oldName, const QString &newName)
{
- Utils::FileName oldFileName = Utils::FileName::fromString(oldName);
- Utils::FileName newFileName = Utils::FileName::fromString(newName);
+ FileName oldFileName = FileName::fromString(oldName);
+ FileName newFileName = FileName::fromString(newName);
if (!m_marks.contains(oldFileName))
return;
@@ -127,6 +129,8 @@ void BaseTextMarkRegistry::allDocumentsRenamed(const QString &oldName, const QSt
mark->updateFileName(newName);
}
+} // namespace Internal
+
BaseTextMark::BaseTextMark(const QString &fileName, int lineNumber)
: ITextMark(lineNumber), m_fileName(fileName)
{
@@ -152,3 +156,5 @@ void BaseTextMark::updateFileName(const QString &fileName)
{
m_fileName = fileName;
}
+
+} // namespace TextEditor
diff --git a/src/plugins/texteditor/behaviorsettingspage.cpp b/src/plugins/texteditor/behaviorsettingspage.cpp
index eac693c00b..a5a7001f0a 100644
--- a/src/plugins/texteditor/behaviorsettingspage.cpp
+++ b/src/plugins/texteditor/behaviorsettingspage.cpp
@@ -98,7 +98,7 @@ BehaviorSettingsPage::BehaviorSettingsPage(const BehaviorSettingsPageParameters
// global tab preferences for all other languages
d->m_codeStyle = new SimpleCodeStylePreferences(this);
d->m_codeStyle->setDisplayName(tr("Global", "Settings"));
- d->m_codeStyle->setId(QLatin1String(Constants::GLOBAL_SETTINGS_ID));
+ d->m_codeStyle->setId(Constants::GLOBAL_SETTINGS_ID);
// default pool for all other languages
d->m_defaultCodeStylePool = new CodeStylePool(0, this); // Any language
@@ -222,8 +222,7 @@ void BehaviorSettingsPage::settingsToUI()
d->m_page->behaviorWidget->setAssignedStorageSettings(d->m_storageSettings);
d->m_page->behaviorWidget->setAssignedBehaviorSettings(d->m_behaviorSettings);
d->m_page->behaviorWidget->setAssignedExtraEncodingSettings(d->m_extraEncodingSettings);
- d->m_page->behaviorWidget->setAssignedCodec(
- Core::EditorManager::instance()->defaultTextCodec());
+ d->m_page->behaviorWidget->setAssignedCodec(Core::EditorManager::defaultTextCodec());
}
void BehaviorSettingsPage::finish()
diff --git a/src/plugins/texteditor/codeassist/basicproposalitemlistmodel.cpp b/src/plugins/texteditor/codeassist/basicproposalitemlistmodel.cpp
index b6c479b9c8..ae2ece571c 100644
--- a/src/plugins/texteditor/codeassist/basicproposalitemlistmodel.cpp
+++ b/src/plugins/texteditor/codeassist/basicproposalitemlistmodel.cpp
@@ -29,8 +29,8 @@
#include "basicproposalitemlistmodel.h"
#include "basicproposalitem.h"
-#include "texteditorsettings.h"
-#include "completionsettings.h"
+#include <texteditor/texteditorsettings.h>
+#include <texteditor/completionsettings.h>
#include <QDebug>
#include <QRegExp>
@@ -53,16 +53,28 @@ const int kMaxPrefixFilter = 100;
struct ContentLessThan
{
+ ContentLessThan(const QString &prefix)
+ : m_prefix(prefix)
+ {}
+
bool operator()(const BasicProposalItem *a, const BasicProposalItem *b)
{
- // If order is different, show higher ones first.
- if (a->order() != b->order())
- return a->order() > b->order();
-
// The order is case-insensitive in principle, but case-sensitive when this
// would otherwise mean equality
const QString &lowera = a->text().toLower();
const QString &lowerb = b->text().toLower();
+ const QString &lowerprefix = m_prefix.toLower();
+
+ // All continuations should go before all fuzzy matches
+ if (int diff = lowera.startsWith(lowerprefix) - lowerb.startsWith(lowerprefix))
+ return diff > 0;
+ if (int diff = a->text().startsWith(m_prefix) - b->text().startsWith(m_prefix))
+ return diff > 0;
+
+ // If order is different, show higher ones first.
+ if (a->order() != b->order())
+ return a->order() > b->order();
+
if (lowera == lowerb)
return lessThan(a->text(), b->text());
else
@@ -113,6 +125,9 @@ struct ContentLessThan
return a < b;
}
};
+
+private:
+ QString m_prefix;
};
} // Anonymous
@@ -210,7 +225,7 @@ void BasicProposalItemListModel::filter(const QString &prefix)
* It also implements the fully and first-letter-only case sensitivity.
*/
const TextEditor::CaseSensitivity caseSensitivity =
- TextEditorSettings::instance()->completionSettings().m_caseSensitivity;
+ TextEditorSettings::completionSettings().m_caseSensitivity;
QString keyRegExp;
keyRegExp += QLatin1Char('^');
@@ -263,9 +278,9 @@ bool BasicProposalItemListModel::isSortable(const QString &prefix) const
return false;
}
-void BasicProposalItemListModel::sort()
+void BasicProposalItemListModel::sort(const QString &prefix)
{
- qStableSort(m_currentItems.begin(), m_currentItems.end(), ContentLessThan());
+ qStableSort(m_currentItems.begin(), m_currentItems.end(), ContentLessThan(prefix));
}
int BasicProposalItemListModel::persistentId(int index) const
diff --git a/src/plugins/texteditor/codeassist/basicproposalitemlistmodel.h b/src/plugins/texteditor/codeassist/basicproposalitemlistmodel.h
index 9de70b4374..5205c8901a 100644
--- a/src/plugins/texteditor/codeassist/basicproposalitemlistmodel.h
+++ b/src/plugins/texteditor/codeassist/basicproposalitemlistmodel.h
@@ -58,7 +58,7 @@ public:
virtual void removeDuplicates();
virtual void filter(const QString &prefix);
virtual bool isSortable(const QString &prefix) const;
- virtual void sort();
+ virtual void sort(const QString &prefix);
virtual bool supportsPrefixExpansion() const;
virtual QString proposalPrefix() const;
virtual bool keepPerfectMatch(AssistReason reason) const;
diff --git a/src/plugins/texteditor/codeassist/codeassistant.cpp b/src/plugins/texteditor/codeassist/codeassistant.cpp
index 8a57304e87..753c8e7945 100644
--- a/src/plugins/texteditor/codeassist/codeassistant.cpp
+++ b/src/plugins/texteditor/codeassist/codeassistant.cpp
@@ -40,6 +40,7 @@
#include <texteditor/basetexteditor.h>
#include <texteditor/texteditorsettings.h>
#include <texteditor/completionsettings.h>
+#include <coreplugin/editormanager/editormanager.h>
#include <extensionsystem/pluginmanager.h>
#include <utils/qtcassert.h>
@@ -79,6 +80,7 @@ public:
virtual ~CodeAssistantPrivate();
void configure(BaseTextEditor *textEditor);
+ void reconfigure();
bool isConfigured() const;
void invoke(AssistKind kind, IAssistProvider *provider = 0);
@@ -112,11 +114,13 @@ private slots:
void finalizeProposal();
void automaticProposalTimeout();
void updateCompletionSettings(const TextEditor::CompletionSettings &settings);
+ void explicitlyAborted();
+ void clearAbortedPosition();
private:
CodeAssistant *m_q;
BaseTextEditor *m_textEditor;
- QList<CompletionAssistProvider *> m_completionProviders;
+ CompletionAssistProvider *m_completionProvider;
QList<QuickFixAssistProvider *> m_quickFixProviders;
Internal::ProcessorRunner *m_requestRunner;
CompletionAssistProvider *m_requestProvider;
@@ -126,6 +130,7 @@ private:
bool m_receivedContentWhileWaiting;
QTimer m_automaticProposalTimer;
CompletionSettings m_settings;
+ int m_abortedBasePosition;
static const QChar m_null;
};
@@ -141,11 +146,13 @@ static const int AutomaticProposalTimerInterval = 400;
CodeAssistantPrivate::CodeAssistantPrivate(CodeAssistant *assistant)
: m_q(assistant)
, m_textEditor(0)
+ , m_completionProvider(0)
, m_requestRunner(0)
, m_requestProvider(0)
, m_proposalWidget(0)
, m_receivedContentWhileWaiting(false)
- , m_settings(TextEditorSettings::instance()->completionSettings())
+ , m_settings(TextEditorSettings::completionSettings())
+ , m_abortedBasePosition(-1)
{
m_automaticProposalTimer.setSingleShot(true);
m_automaticProposalTimer.setInterval(AutomaticProposalTimerInterval);
@@ -155,6 +162,8 @@ CodeAssistantPrivate::CodeAssistantPrivate(CodeAssistant *assistant)
SIGNAL(completionSettingsChanged(TextEditor::CompletionSettings)),
this,
SLOT(updateCompletionSettings(TextEditor::CompletionSettings)));
+ connect(Core::EditorManager::instance(), SIGNAL(currentEditorChanged(Core::IEditor*)),
+ this, SLOT(clearAbortedPosition()));
}
CodeAssistantPrivate::~CodeAssistantPrivate()
@@ -169,9 +178,7 @@ void CodeAssistantPrivate::configure(BaseTextEditor *textEditor)
// completion and quick-fix provider (getting rid of the list).
m_textEditor = textEditor;
- m_completionProviders =
- ExtensionSystem::PluginManager::getObjects<CompletionAssistProvider>();
- filterEditorSpecificProviders(&m_completionProviders, m_textEditor->id());
+ m_completionProvider = textEditor->completionAssistProvider();
m_quickFixProviders =
ExtensionSystem::PluginManager::getObjects<QuickFixAssistProvider>();
filterEditorSpecificProviders(&m_quickFixProviders, m_textEditor->id());
@@ -179,6 +186,12 @@ void CodeAssistantPrivate::configure(BaseTextEditor *textEditor)
m_textEditor->editorWidget()->installEventFilter(this);
}
+void CodeAssistantPrivate::reconfigure()
+{
+ if (isConfigured())
+ m_completionProvider = m_textEditor->completionAssistProvider();
+}
+
bool CodeAssistantPrivate::isConfigured() const
{
return m_textEditor != 0;
@@ -229,12 +242,10 @@ void CodeAssistantPrivate::requestProposal(AssistReason reason,
QTC_ASSERT(!isWaitingForProposal(), return);
if (!provider) {
- if (kind == Completion) {
- if (!m_completionProviders.isEmpty())
- provider = m_completionProviders.at(0);
- } else if (!m_quickFixProviders.isEmpty()) {
+ if (kind == Completion)
+ provider = m_completionProvider;
+ else if (!m_quickFixProviders.isEmpty())
provider = m_quickFixProviders.at(0);
- }
if (!provider)
return;
@@ -303,33 +314,41 @@ void CodeAssistantPrivate::displayProposal(IAssistProposal *newProposal, AssistR
destroyContext();
}
- if (m_textEditor->position() < proposalCandidate->basePosition())
+ int basePosition = proposalCandidate->basePosition();
+ if (m_textEditor->position() < basePosition)
+ return;
+
+ if (m_abortedBasePosition == basePosition && reason != ExplicitlyInvoked)
return;
+ clearAbortedPosition();
m_proposal.reset(proposalCandidate.take());
if (m_proposal->isCorrective())
m_proposal->makeCorrection(m_textEditor);
+ basePosition = m_proposal->basePosition();
m_proposalWidget = m_proposal->createWidget();
connect(m_proposalWidget, SIGNAL(destroyed()), this, SLOT(finalizeProposal()));
connect(m_proposalWidget, SIGNAL(prefixExpanded(QString)),
this, SLOT(handlePrefixExpansion(QString)));
connect(m_proposalWidget, SIGNAL(proposalItemActivated(IAssistProposalItem*)),
this, SLOT(processProposalItem(IAssistProposalItem*)));
+ connect(m_proposalWidget, SIGNAL(explicitlyAborted()),
+ this, SLOT(explicitlyAborted()));
m_proposalWidget->setAssistant(m_q);
m_proposalWidget->setReason(reason);
m_proposalWidget->setKind(m_assistKind);
m_proposalWidget->setUnderlyingWidget(m_textEditor->widget());
m_proposalWidget->setModel(m_proposal->model());
- m_proposalWidget->setDisplayRect(m_textEditor->cursorRect(m_proposal->basePosition()));
+ m_proposalWidget->setDisplayRect(m_textEditor->cursorRect(basePosition));
if (m_receivedContentWhileWaiting)
m_proposalWidget->setIsSynchronized(false);
else
m_proposalWidget->setIsSynchronized(true);
m_proposalWidget->showProposal(m_textEditor->textDocument()->textAt(
- m_proposal->basePosition(),
- m_textEditor->position() - m_proposal->basePosition()));
+ basePosition,
+ m_textEditor->position() - basePosition));
}
void CodeAssistantPrivate::processProposalItem(IAssistProposalItem *proposalItem)
@@ -357,6 +376,7 @@ void CodeAssistantPrivate::finalizeRequest()
void CodeAssistantPrivate::finalizeProposal()
{
+ stopAutomaticProposalTimer();
m_proposal.reset();
m_proposalWidget = 0;
if (m_receivedContentWhileWaiting)
@@ -381,23 +401,22 @@ void CodeAssistantPrivate::invalidateCurrentRequestData()
CompletionAssistProvider *CodeAssistantPrivate::identifyActivationSequence()
{
- for (int i = 0; i < m_completionProviders.size(); ++i) {
- CompletionAssistProvider *provider = m_completionProviders.at(i);
- const int length = provider->activationCharSequenceLength();
- if (length == 0)
- continue;
- QString sequence = m_textEditor->textDocument()->textAt(m_textEditor->position() - length, length);
- // In pretty much all cases the sequence will have the appropriate length. Only in the
- // case of typing the very first characters in the document for providers that request a
- // length greater than 1 (currently only C++, which specifies 3), the sequence needs to
- // be preprended so it has the expected length.
- const int lengthDiff = length - sequence.length();
- for (int j = 0; j < lengthDiff; ++j)
- sequence.prepend(m_null);
- if (provider->isActivationCharSequence(sequence))
- return provider;
- }
- return 0;
+ if (!m_completionProvider)
+ return 0;
+
+ const int length = m_completionProvider->activationCharSequenceLength();
+ if (length == 0)
+ return 0;
+ QString sequence = m_textEditor->textDocument()->textAt(m_textEditor->position() - length,
+ length);
+ // In pretty much all cases the sequence will have the appropriate length. Only in the
+ // case of typing the very first characters in the document for providers that request a
+ // length greater than 1 (currently only C++, which specifies 3), the sequence needs to
+ // be prepended so it has the expected length.
+ const int lengthDiff = length - sequence.length();
+ for (int j = 0; j < lengthDiff; ++j)
+ sequence.prepend(m_null);
+ return m_completionProvider->isActivationCharSequence(sequence) ? m_completionProvider : 0;
}
void CodeAssistantPrivate::notifyChange()
@@ -461,6 +480,17 @@ void CodeAssistantPrivate::updateCompletionSettings(const TextEditor::Completion
m_settings = settings;
}
+void CodeAssistantPrivate::explicitlyAborted()
+{
+ QTC_ASSERT(m_proposal, return);
+ m_abortedBasePosition = m_proposal->basePosition();
+}
+
+void CodeAssistantPrivate::clearAbortedPosition()
+{
+ m_abortedBasePosition = -1;
+}
+
bool CodeAssistantPrivate::eventFilter(QObject *o, QEvent *e)
{
Q_UNUSED(o);
@@ -531,4 +561,9 @@ void CodeAssistant::invoke(AssistKind kind, IAssistProvider *provider)
d->invoke(kind, provider);
}
+void CodeAssistant::reconfigure()
+{
+ d->reconfigure();
+}
+
#include "codeassistant.moc"
diff --git a/src/plugins/texteditor/codeassist/codeassistant.h b/src/plugins/texteditor/codeassist/codeassistant.h
index 5041ff9cfb..70a588c478 100644
--- a/src/plugins/texteditor/codeassist/codeassistant.h
+++ b/src/plugins/texteditor/codeassist/codeassistant.h
@@ -62,6 +62,9 @@ public:
signals:
void finished();
+public slots:
+ void reconfigure();
+
private:
CodeAssistantPrivate *d;
};
diff --git a/src/plugins/texteditor/codeassist/functionhintproposalwidget.cpp b/src/plugins/texteditor/codeassist/functionhintproposalwidget.cpp
index 84bcaa8357..e0023976c0 100644
--- a/src/plugins/texteditor/codeassist/functionhintproposalwidget.cpp
+++ b/src/plugins/texteditor/codeassist/functionhintproposalwidget.cpp
@@ -190,12 +190,16 @@ 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;
+ e->accept();
+ }
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;
+ e->accept();
+ }
if (d->m_model->size() > 1) {
QKeyEvent *ke = static_cast<QKeyEvent*>(e);
if (ke->key() == Qt::Key_Up) {
@@ -211,6 +215,7 @@ bool FunctionHintProposalWidget::eventFilter(QObject *obj, QEvent *e)
case QEvent::KeyRelease:
if (static_cast<QKeyEvent*>(e)->key() == Qt::Key_Escape && d->m_escapePressed) {
abort();
+ emit explicitlyAborted();
return false;
}
d->m_assistant->notifyChange();
diff --git a/src/plugins/texteditor/codeassist/genericproposalwidget.cpp b/src/plugins/texteditor/codeassist/genericproposalwidget.cpp
index 6422ffb10c..22b7d15880 100644
--- a/src/plugins/texteditor/codeassist/genericproposalwidget.cpp
+++ b/src/plugins/texteditor/codeassist/genericproposalwidget.cpp
@@ -82,8 +82,7 @@ bool isPerfectMatch(const QString &prefix, const IGenericProposalModel *model)
for (int i = 0; i < model->size(); ++i) {
const QString &current = cleanText(model->text(i));
if (!current.isEmpty()) {
- TextEditor::CaseSensitivity cs =
- TextEditor::TextEditorSettings::instance()->completionSettings().m_caseSensitivity;
+ CaseSensitivity cs = TextEditorSettings::completionSettings().m_caseSensitivity;
if (cs == TextEditor::CaseSensitive) {
if (prefix == current)
return true;
@@ -448,7 +447,7 @@ bool GenericProposalWidget::updateAndCheck(const QString &prefix)
return false;
}
if (d->m_model->isSortable(prefix))
- d->m_model->sort();
+ d->m_model->sort(prefix);
d->m_completionListView->reset();
// Try to find the previosly explicit selection (if any). If we can find the item set it
@@ -468,7 +467,7 @@ bool GenericProposalWidget::updateAndCheck(const QString &prefix)
d->m_explicitlySelected = false;
}
- if (TextEditorSettings::instance()->completionSettings().m_partiallyComplete
+ if (TextEditorSettings::completionSettings().m_partiallyComplete
&& d->m_kind == Completion
&& d->m_justInvoked
&& d->m_isSynchronized) {
@@ -571,6 +570,8 @@ bool GenericProposalWidget::eventFilter(QObject *o, QEvent *e)
switch (ke->key()) {
case Qt::Key_Escape:
abort();
+ emit explicitlyAborted();
+ e->accept();
return true;
case Qt::Key_N:
diff --git a/src/plugins/texteditor/codeassist/iassistinterface.cpp b/src/plugins/texteditor/codeassist/iassistinterface.cpp
index dc4e23063b..51fe2a615a 100644
--- a/src/plugins/texteditor/codeassist/iassistinterface.cpp
+++ b/src/plugins/texteditor/codeassist/iassistinterface.cpp
@@ -75,13 +75,13 @@ IAssistInterface::~IAssistInterface()
*/
/*!
- \fn const Core::IDocument *TextEditor::IAssistInterface::file() const
+ \fn QString TextEditor::IAssistInterface::fileName() const
Returns the file associated.
*/
/*!
- \fn QTextDocument *TextEditor::IAssistInterface::document() const
+ \fn QTextDocument *TextEditor::IAssistInterface::textDocument() const
Returns the document.
*/
diff --git a/src/plugins/texteditor/codeassist/iassistproposalwidget.cpp b/src/plugins/texteditor/codeassist/iassistproposalwidget.cpp
index 1524d349e1..6f68661fb2 100644
--- a/src/plugins/texteditor/codeassist/iassistproposalwidget.cpp
+++ b/src/plugins/texteditor/codeassist/iassistproposalwidget.cpp
@@ -79,7 +79,7 @@ IAssistProposalWidget::~IAssistProposalWidget()
*/
/*!
- \fn void TextEditor::IAssistProposalWidget::setModel(IAssistModel *model)
+ \fn void TextEditor::IAssistProposalWidget::setModel(IAssistProposalModel *model)
Sets the model.
*/
diff --git a/src/plugins/texteditor/codeassist/iassistproposalwidget.h b/src/plugins/texteditor/codeassist/iassistproposalwidget.h
index ed25929e6a..e97ac8062a 100644
--- a/src/plugins/texteditor/codeassist/iassistproposalwidget.h
+++ b/src/plugins/texteditor/codeassist/iassistproposalwidget.h
@@ -65,6 +65,7 @@ public:
signals:
void prefixExpanded(const QString &newPrefix);
void proposalItemActivated(IAssistProposalItem *proposalItem);
+ void explicitlyAborted();
};
} // TextEditor
diff --git a/src/plugins/texteditor/codeassist/iassistprovider.cpp b/src/plugins/texteditor/codeassist/iassistprovider.cpp
index 14a0f581ec..2dac112c7f 100644
--- a/src/plugins/texteditor/codeassist/iassistprovider.cpp
+++ b/src/plugins/texteditor/codeassist/iassistprovider.cpp
@@ -50,7 +50,7 @@ using namespace TextEditor;
*/
/*!
- \fn bool TextEditor::IAssistProvider::supportsEditor(const QString &editorId) const
+ \fn bool TextEditor::IAssistProvider::supportsEditor(const Core::Id &editorId) const
Returns whether this provider supports the editor which has the \a editorId.
*/
diff --git a/src/plugins/texteditor/codeassist/igenericproposalmodel.h b/src/plugins/texteditor/codeassist/igenericproposalmodel.h
index 9a4b60470c..71a4bfde31 100644
--- a/src/plugins/texteditor/codeassist/igenericproposalmodel.h
+++ b/src/plugins/texteditor/codeassist/igenericproposalmodel.h
@@ -53,7 +53,7 @@ public:
virtual void removeDuplicates() = 0;
virtual void filter(const QString &prefix) = 0;
virtual bool isSortable(const QString &prefix) const = 0;
- virtual void sort() = 0;
+ virtual void sort(const QString &prefix) = 0;
virtual bool supportsPrefixExpansion() const = 0;
virtual QString proposalPrefix() const = 0;
virtual bool keepPerfectMatch(AssistReason reason) const = 0;
diff --git a/src/plugins/texteditor/codeassist/keywordscompletionassist.cpp b/src/plugins/texteditor/codeassist/keywordscompletionassist.cpp
index 0540fb3de6..e58f395f1b 100644
--- a/src/plugins/texteditor/codeassist/keywordscompletionassist.cpp
+++ b/src/plugins/texteditor/codeassist/keywordscompletionassist.cpp
@@ -33,9 +33,9 @@
#include <texteditor/codeassist/genericproposal.h>
#include <texteditor/codeassist/functionhintproposal.h>
#include <texteditor/codeassist/basicproposalitemlistmodel.h>
-#include "completionsettings.h"
-#include "texteditorsettings.h"
-#include "basetexteditor.h"
+#include <texteditor/completionsettings.h>
+#include <texteditor/texteditorsettings.h>
+#include <texteditor/basetexteditor.h>
using namespace TextEditor;
@@ -102,7 +102,7 @@ bool KeywordsAssistProposalItem::prematurelyApplies(const QChar &c) const
void KeywordsAssistProposalItem::applyContextualContent(TextEditor::BaseTextEditor *editor,
int basePosition) const
{
- const CompletionSettings &settings = TextEditorSettings::instance()->completionSettings();
+ const CompletionSettings &settings = TextEditorSettings::completionSettings();
int replaceLength = editor->position() - basePosition;
QString toInsert = text();
diff --git a/src/plugins/texteditor/codecselector.cpp b/src/plugins/texteditor/codecselector.cpp
index a8fcff2e14..dd4ab7f02e 100644
--- a/src/plugins/texteditor/codecselector.cpp
+++ b/src/plugins/texteditor/codecselector.cpp
@@ -74,7 +74,7 @@ CodecSelector::CodecSelector(QWidget *parent, BaseTextDocument *doc)
QString decodingErrorHint;
if (m_hasDecodingError)
decodingErrorHint = tr("\nThe following encodings are likely to fit:");
- m_label->setText(tr("Select encoding for \"%1\".%2").arg(QFileInfo(doc->fileName()).fileName()).arg(decodingErrorHint));
+ m_label->setText(tr("Select encoding for \"%1\".%2").arg(QFileInfo(doc->filePath()).fileName()).arg(decodingErrorHint));
m_listWidget = new CodecListWidget(this);
diff --git a/src/plugins/texteditor/codestyleeditor.cpp b/src/plugins/texteditor/codestyleeditor.cpp
index 92fe407021..101eb6f4ce 100644
--- a/src/plugins/texteditor/codestyleeditor.cpp
+++ b/src/plugins/texteditor/codestyleeditor.cpp
@@ -54,8 +54,7 @@ CodeStyleEditor::CodeStyleEditor(ICodeStylePreferencesFactory *factory,
CodeStyleSelectorWidget *selector = new CodeStyleSelectorWidget(factory, this);
selector->setCodeStyle(codeStyle);
m_preview = new SnippetEditorWidget(this);
- TextEditor::TextEditorSettings *settings = TextEditorSettings::instance();
- m_preview->setFontSettings(settings->fontSettings());
+ m_preview->setFontSettings(TextEditorSettings::fontSettings());
DisplaySettings displaySettings = m_preview->displaySettings();
displaySettings.m_visualizeWhitespace = true;
m_preview->setDisplaySettings(displaySettings);
diff --git a/src/plugins/texteditor/codestylepool.cpp b/src/plugins/texteditor/codestylepool.cpp
index d3c255906e..009b1e5454 100644
--- a/src/plugins/texteditor/codestylepool.cpp
+++ b/src/plugins/texteditor/codestylepool.cpp
@@ -55,13 +55,13 @@ public:
{}
~CodeStylePoolPrivate();
- QString generateUniqueId(const QString &id) const;
+ QByteArray generateUniqueId(const QByteArray &id) const;
ICodeStylePreferencesFactory *m_factory;
QList<ICodeStylePreferences *> m_pool;
QList<ICodeStylePreferences *> m_builtInPool;
QList<ICodeStylePreferences *> m_customPool;
- QMap<QString, ICodeStylePreferences *> m_idToCodeStyle;
+ QMap<QByteArray, ICodeStylePreferences *> m_idToCodeStyle;
QString m_settingsPath;
};
@@ -70,23 +70,23 @@ CodeStylePoolPrivate::~CodeStylePoolPrivate()
delete m_factory;
}
-QString CodeStylePoolPrivate::generateUniqueId(const QString &id) const
+QByteArray CodeStylePoolPrivate::generateUniqueId(const QByteArray &id) const
{
if (!id.isEmpty() && !m_idToCodeStyle.contains(id))
return id;
int idx = id.size();
while (idx > 0) {
- if (!id.at(idx - 1).isDigit())
+ if (!isdigit(id.at(idx - 1)))
break;
idx--;
}
- const QString baseName = id.left(idx);
- QString newName = baseName.isEmpty() ? QLatin1String("codestyle") : baseName;
+ const QByteArray baseName = id.left(idx);
+ QByteArray newName = baseName.isEmpty() ? "codestyle" : baseName;
int i = 2;
while (m_idToCodeStyle.contains(newName))
- newName = baseName + QString::number(i++);
+ newName = baseName + QByteArray::number(i++);
return newName;
}
@@ -119,10 +119,10 @@ QString CodeStylePool::settingsDir() const
return customCodeStylesPath().append(suffix);
}
-Utils::FileName CodeStylePool::settingsPath(const QString &id) const
+Utils::FileName CodeStylePool::settingsPath(const QByteArray &id) const
{
Utils::FileName path = Utils::FileName::fromString(settingsDir());
- path.appendPath(id + QLatin1String(".xml"));
+ path.appendPath(QString::fromUtf8(id + ".xml"));
return path;
}
@@ -147,7 +147,7 @@ ICodeStylePreferences *CodeStylePool::cloneCodeStyle(ICodeStylePreferences *orig
originalCodeStyle->value(), originalCodeStyle->displayName());
}
-ICodeStylePreferences *CodeStylePool::createCodeStyle(const QString &id, const TabSettings &tabSettings,
+ICodeStylePreferences *CodeStylePool::createCodeStyle(const QByteArray &id, const TabSettings &tabSettings,
const QVariant &codeStyleData, const QString &displayName)
{
if (!d->m_factory)
@@ -168,7 +168,7 @@ ICodeStylePreferences *CodeStylePool::createCodeStyle(const QString &id, const T
void CodeStylePool::addCodeStyle(ICodeStylePreferences *codeStyle)
{
- const QString newId = d->generateUniqueId(codeStyle->id());
+ const QByteArray newId = d->generateUniqueId(codeStyle->id());
codeStyle->setId(newId);
d->m_pool.append(codeStyle);
@@ -206,7 +206,7 @@ void CodeStylePool::removeCodeStyle(ICodeStylePreferences *codeStyle)
delete codeStyle;
}
-ICodeStylePreferences *CodeStylePool::codeStyle(const QString &id) const
+ICodeStylePreferences *CodeStylePool::codeStyle(const QByteArray &id) const
{
return d->m_idToCodeStyle.value(id);
}
@@ -218,7 +218,7 @@ void CodeStylePool::loadCustomCodeStyles()
for (int i = 0; i < codeStyleFiles.count(); i++) {
const QString codeStyleFile = codeStyleFiles.at(i);
// filter out styles which id is the same as one of built-in styles
- if (!d->m_idToCodeStyle.contains(QFileInfo(codeStyleFile).completeBaseName()))
+ if (!d->m_idToCodeStyle.contains(QFileInfo(codeStyleFile).completeBaseName().toUtf8()))
loadCodeStyle(Utils::FileName::fromString(dir.absoluteFilePath(codeStyleFile)));
}
}
@@ -238,7 +238,7 @@ ICodeStylePreferences *CodeStylePool::loadCodeStyle(const Utils::FileName &fileN
reader.load(fileName);
QVariantMap m = reader.restoreValues();
if (m.contains(QLatin1String(codeStyleDataKey))) {
- const QString id = fileName.toFileInfo().completeBaseName();
+ const QByteArray id = fileName.toFileInfo().completeBaseName().toUtf8();
const QString displayName = reader.restoreValue(QLatin1String(displayNameKey)).toString();
const QVariantMap map = reader.restoreValue(QLatin1String(codeStyleDataKey)).toMap();
if (d->m_factory) {
diff --git a/src/plugins/texteditor/codestylepool.h b/src/plugins/texteditor/codestylepool.h
index e2a58988cf..ef6dff460d 100644
--- a/src/plugins/texteditor/codestylepool.h
+++ b/src/plugins/texteditor/codestylepool.h
@@ -58,14 +58,14 @@ public:
QList<ICodeStylePreferences *> customCodeStyles() const;
ICodeStylePreferences *cloneCodeStyle(ICodeStylePreferences *originalCodeStyle);
- ICodeStylePreferences *createCodeStyle(const QString &id, const TabSettings &tabSettings,
+ ICodeStylePreferences *createCodeStyle(const QByteArray &id, const TabSettings &tabSettings,
const QVariant &codeStyleData, const QString &displayName);
// ownership is passed to the pool
void addCodeStyle(ICodeStylePreferences *codeStyle);
// is removed and deleted
void removeCodeStyle(ICodeStylePreferences *codeStyle);
- ICodeStylePreferences *codeStyle(const QString &id) const;
+ ICodeStylePreferences *codeStyle(const QByteArray &id) const;
void loadCustomCodeStyles();
@@ -81,7 +81,7 @@ private slots:
private:
QString settingsDir() const;
- Utils::FileName settingsPath(const QString &id) const;
+ Utils::FileName settingsPath(const QByteArray &id) const;
ICodeStylePreferences *loadCodeStyle(const Utils::FileName &fileName);
void saveCodeStyle(ICodeStylePreferences *codeStyle) const;
diff --git a/src/plugins/texteditor/codestyleselectorwidget.cpp b/src/plugins/texteditor/codestyleselectorwidget.cpp
index 537fdd07fe..87ffeb38bc 100644
--- a/src/plugins/texteditor/codestyleselectorwidget.cpp
+++ b/src/plugins/texteditor/codestyleselectorwidget.cpp
@@ -354,7 +354,7 @@ void CodeStyleSelectorWidget::slotExportClicked()
{
ICodeStylePreferences *currentPreferences = m_codeStyle->currentPreferences();
const QString fileName = QFileDialog::getSaveFileName(this, tr("Export Code Style"),
- currentPreferences->id() + QLatin1String(".xml"),
+ QString::fromUtf8(currentPreferences->id() + ".xml"),
tr("Code styles (*.xml);;All files (*)"));
if (!fileName.isEmpty()) {
CodeStylePool *codeStylePool = m_codeStyle->delegatingPool();
diff --git a/src/plugins/texteditor/findincurrentfile.cpp b/src/plugins/texteditor/findincurrentfile.cpp
index 705fa3fcae..ca7fdadea3 100644
--- a/src/plugins/texteditor/findincurrentfile.cpp
+++ b/src/plugins/texteditor/findincurrentfile.cpp
@@ -44,7 +44,7 @@ using namespace TextEditor::Internal;
FindInCurrentFile::FindInCurrentFile()
: m_currentDocument(0)
{
- connect(Core::ICore::editorManager(), SIGNAL(currentEditorChanged(Core::IEditor*)),
+ connect(Core::EditorManager::instance(), SIGNAL(currentEditorChanged(Core::IEditor*)),
this, SLOT(handleFileChange(Core::IEditor*)));
handleFileChange(Core::EditorManager::currentEditor());
}
@@ -64,32 +64,32 @@ Utils::FileIterator *FindInCurrentFile::files(const QStringList &nameFilters,
{
Q_UNUSED(nameFilters)
QString fileName = additionalParameters.toString();
- QMap<QString, QTextCodec *> openEditorEncodings = ITextEditor::openedTextEditorsEncodings();
+ QMap<QString, QTextCodec *> openEditorEncodings = ITextEditor::openedTextDocumentEncodings();
QTextCodec *codec = openEditorEncodings.value(fileName);
if (!codec)
- codec = Core::EditorManager::instance()->defaultTextCodec();
+ codec = Core::EditorManager::defaultTextCodec();
return new Utils::FileIterator(QStringList() << fileName, QList<QTextCodec *>() << codec);
}
QVariant FindInCurrentFile::additionalParameters() const
{
- return qVariantFromValue(m_currentDocument->fileName());
+ return qVariantFromValue(m_currentDocument->filePath());
}
QString FindInCurrentFile::label() const
{
- return tr("File '%1':").arg(QFileInfo(m_currentDocument->fileName()).fileName());
+ return tr("File '%1':").arg(QFileInfo(m_currentDocument->filePath()).fileName());
}
QString FindInCurrentFile::toolTip() const
{
// %2 is filled by BaseFileFind::runNewSearch
- return tr("File path: %1\n%2").arg(QDir::toNativeSeparators(m_currentDocument->fileName()));
+ return tr("File path: %1\n%2").arg(QDir::toNativeSeparators(m_currentDocument->filePath()));
}
bool FindInCurrentFile::isEnabled() const
{
- return m_currentDocument && !m_currentDocument->fileName().isEmpty();
+ return m_currentDocument && !m_currentDocument->filePath().isEmpty();
}
void FindInCurrentFile::handleFileChange(Core::IEditor *editor)
diff --git a/src/plugins/texteditor/findinfiles.cpp b/src/plugins/texteditor/findinfiles.cpp
index f555b6fce3..e103ced903 100644
--- a/src/plugins/texteditor/findinfiles.cpp
+++ b/src/plugins/texteditor/findinfiles.cpp
@@ -29,8 +29,10 @@
#include "findinfiles.h"
-#include <utils/filesearch.h>
#include <coreplugin/editormanager/editormanager.h>
+#include <find/findplugin.h>
+#include <utils/filesearch.h>
+#include <utils/qtcassert.h>
#include <QDebug>
#include <QSettings>
@@ -44,10 +46,15 @@
using namespace Find;
using namespace TextEditor;
+static FindInFiles *m_instance = 0;
+
FindInFiles::FindInFiles()
: m_configWidget(0),
m_directory(0)
{
+ m_instance = this;
+ connect(Core::EditorManager::instance(), SIGNAL(findOnFileSystemRequest(QString)),
+ this, SLOT(findOnFileSystem(QString)));
}
FindInFiles::~FindInFiles()
@@ -75,7 +82,7 @@ Utils::FileIterator *FindInFiles::files(const QStringList &nameFilters,
{
return new Utils::SubDirFileIterator(QStringList() << additionalParameters.toString(),
nameFilters,
- Core::EditorManager::instance()->defaultTextCodec());
+ Core::EditorManager::defaultTextCodec());
}
QVariant FindInFiles::additionalParameters() const
@@ -176,3 +183,11 @@ void FindInFiles::setDirectory(const QString &directory)
syncComboWithSettings(m_directory, directory);
}
+void FindInFiles::findOnFileSystem(const QString &path)
+{
+ QTC_ASSERT(m_instance, return);
+ const QFileInfo fi(path);
+ const QString folder = fi.isDir() ? fi.absoluteFilePath() : fi.absolutePath();
+ m_instance->setDirectory(folder);
+ Find::FindPlugin::instance()->openFindDialog(m_instance);
+}
diff --git a/src/plugins/texteditor/findinfiles.h b/src/plugins/texteditor/findinfiles.h
index 5353a69d41..e3c6f9ba63 100644
--- a/src/plugins/texteditor/findinfiles.h
+++ b/src/plugins/texteditor/findinfiles.h
@@ -64,6 +64,9 @@ protected:
QString label() const;
QString toolTip() const;
+public slots:
+ static void findOnFileSystem(const QString &path);
+
private slots:
void openFileBrowser();
diff --git a/src/plugins/texteditor/findinopenfiles.cpp b/src/plugins/texteditor/findinopenfiles.cpp
index c109e17126..7a882056d3 100644
--- a/src/plugins/texteditor/findinopenfiles.cpp
+++ b/src/plugins/texteditor/findinopenfiles.cpp
@@ -33,7 +33,7 @@
#include <utils/filesearch.h>
#include <coreplugin/icore.h>
#include <coreplugin/editormanager/editormanager.h>
-#include <coreplugin/editormanager/openeditorsmodel.h>
+#include <coreplugin/editormanager/documentmodel.h>
#include <QSettings>
@@ -43,9 +43,9 @@ using namespace TextEditor::Internal;
FindInOpenFiles::FindInOpenFiles()
{
- connect(Core::ICore::instance()->editorManager(), SIGNAL(editorOpened(Core::IEditor*)),
+ connect(Core::EditorManager::instance(), SIGNAL(editorOpened(Core::IEditor*)),
this, SLOT(updateEnabledState()));
- connect(Core::ICore::instance()->editorManager(), SIGNAL(editorsClosed(QList<Core::IEditor*>)),
+ connect(Core::EditorManager::instance(), SIGNAL(editorsClosed(QList<Core::IEditor*>)),
this, SLOT(updateEnabledState()));
}
@@ -64,17 +64,17 @@ Utils::FileIterator *FindInOpenFiles::files(const QStringList &nameFilters,
{
Q_UNUSED(nameFilters)
Q_UNUSED(additionalParameters)
- QMap<QString, QTextCodec *> openEditorEncodings = ITextEditor::openedTextEditorsEncodings();
+ QMap<QString, QTextCodec *> openEditorEncodings = ITextEditor::openedTextDocumentEncodings();
QStringList fileNames;
QList<QTextCodec *> codecs;
- foreach (const Core::OpenEditorsModel::Entry &entry,
- Core::EditorManager::instance()->openedEditorsModel()->entries()) {
- QString fileName = entry.fileName();
+ foreach (Core::DocumentModel::Entry *entry,
+ Core::EditorManager::documentModel()->documents()) {
+ QString fileName = entry->fileName();
if (!fileName.isEmpty()) {
fileNames.append(fileName);
QTextCodec *codec = openEditorEncodings.value(fileName);
if (!codec)
- codec = Core::EditorManager::instance()->defaultTextCodec();
+ codec = Core::EditorManager::defaultTextCodec();
codecs.append(codec);
}
}
@@ -100,7 +100,7 @@ QString FindInOpenFiles::toolTip() const
bool FindInOpenFiles::isEnabled() const
{
- return Core::EditorManager::instance()->openedEditors().count() > 0;
+ return Core::EditorManager::documentModel()->documentCount() > 0;
}
void FindInOpenFiles::writeSettings(QSettings *settings)
diff --git a/src/plugins/texteditor/fontsettingspage.cpp b/src/plugins/texteditor/fontsettingspage.cpp
index a1a52cfd79..e3cd7e496a 100644
--- a/src/plugins/texteditor/fontsettingspage.cpp
+++ b/src/plugins/texteditor/fontsettingspage.cpp
@@ -260,15 +260,15 @@ QColor FormatDescription::foreground() const
QColor FormatDescription::background() const
{
- if (m_id == C_TEXT)
+ if (m_id == C_TEXT) {
return Qt::white;
- else if (m_id == C_LINE_NUMBER)
+ } else if (m_id == C_LINE_NUMBER) {
return QApplication::palette().background().color();
- else if (m_id == C_SEARCH_RESULT)
+ } else if (m_id == C_SEARCH_RESULT) {
return QColor(0xffef0b);
- else if (m_id == C_PARENTHESES)
+ } else if (m_id == C_PARENTHESES) {
return QColor(0xb4, 0xee, 0xb4);
- else if (m_id == C_CURRENT_LINE || m_id == C_SEARCH_SCOPE) {
+ } else if (m_id == C_CURRENT_LINE || m_id == C_SEARCH_SCOPE) {
const QPalette palette = QApplication::palette();
const QColor &fg = palette.color(QPalette::Highlight);
const QColor &bg = palette.color(QPalette::Base);
diff --git a/src/plugins/texteditor/fontsettingspage.ui b/src/plugins/texteditor/fontsettingspage.ui
index 4e27fc00a6..529deccde6 100644
--- a/src/plugins/texteditor/fontsettingspage.ui
+++ b/src/plugins/texteditor/fontsettingspage.ui
@@ -200,7 +200,7 @@
<customwidget>
<class>TextEditor::Internal::ColorSchemeEdit</class>
<extends>QWidget</extends>
- <header>colorschemeedit.h</header>
+ <header location="global">texteditor/colorschemeedit.h</header>
<container>1</container>
</customwidget>
</customwidgets>
diff --git a/src/plugins/texteditor/generichighlighter/highlighter.cpp b/src/plugins/texteditor/generichighlighter/highlighter.cpp
index d511e7a44c..06106e9703 100644
--- a/src/plugins/texteditor/generichighlighter/highlighter.cpp
+++ b/src/plugins/texteditor/generichighlighter/highlighter.cpp
@@ -50,8 +50,6 @@ namespace {
static const QLatin1Char kHash('#');
}
-const Highlighter::KateFormatMap Highlighter::m_kateFormats;
-
Highlighter::Highlighter(QTextDocument *parent) :
TextEditor::SyntaxHighlighter(parent),
m_regionDepth(0),
@@ -60,7 +58,28 @@ Highlighter::Highlighter(QTextDocument *parent) :
m_persistentObservableStatesCounter(PersistentsStart),
m_dynamicContextsCounter(0),
m_isBroken(false)
-{}
+{
+ static QVector<TextEditor::TextStyle> categories;
+ if (categories.isEmpty()) {
+ categories << TextEditor::C_TEXT
+ << TextEditor::C_VISUAL_WHITESPACE
+ << TextEditor::C_KEYWORD
+ << TextEditor::C_TYPE
+ << TextEditor::C_COMMENT
+ << TextEditor::C_NUMBER
+ << TextEditor::C_NUMBER
+ << TextEditor::C_NUMBER
+ << TextEditor::C_STRING
+ << TextEditor::C_STRING
+ << TextEditor::C_TEXT
+ << TextEditor::C_TEXT
+ << TextEditor::C_TEXT
+ << TextEditor::C_TEXT
+ << TextEditor::C_TEXT;
+ }
+
+ setTextFormatCategories(categories);
+}
Highlighter::~Highlighter()
{}
@@ -71,7 +90,14 @@ Highlighter::BlockData::BlockData() : m_foldingIndentDelta(0), m_originalObserva
Highlighter::BlockData::~BlockData()
{}
-Highlighter::KateFormatMap::KateFormatMap()
+// Mapping from Kate format strings to format ids.
+struct KateFormatMap
+{
+ KateFormatMap();
+ QHash<QString, Highlighter::TextFormatId> m_ids;
+};
+
+KateFormatMap::KateFormatMap()
{
m_ids.insert(QLatin1String("dsNormal"), Highlighter::Normal);
m_ids.insert(QLatin1String("dsKeyword"), Highlighter::Keyword);
@@ -82,19 +108,16 @@ Highlighter::KateFormatMap::KateFormatMap()
m_ids.insert(QLatin1String("dsChar"), Highlighter::Char);
m_ids.insert(QLatin1String("dsString"), Highlighter::String);
m_ids.insert(QLatin1String("dsComment"), Highlighter::Comment);
- m_ids.insert(QLatin1String("dsOthers"), Highlighter::Others);
m_ids.insert(QLatin1String("dsAlert"), Highlighter::Alert);
+ m_ids.insert(QLatin1String("dsError"), Highlighter::Error);
m_ids.insert(QLatin1String("dsFunction"), Highlighter::Function);
m_ids.insert(QLatin1String("dsRegionMarker"), Highlighter::RegionMarker);
- m_ids.insert(QLatin1String("dsError"), Highlighter::Error);
+ m_ids.insert(QLatin1String("dsOthers"), Highlighter::Others);
}
-void Highlighter::configureFormat(TextFormatId id, const QTextCharFormat &format)
-{
- m_creatorFormats[id] = format;
-}
+Q_GLOBAL_STATIC(KateFormatMap, kateFormatMap)
-void Highlighter::setDefaultContext(const QSharedPointer<Context> &defaultContext)
+void Highlighter::setDefaultContext(const QSharedPointer<Context> &defaultContext)
{
m_defaultContext = defaultContext;
m_persistentObservableStates.insert(m_defaultContext->name(), Default);
@@ -140,7 +163,7 @@ void Highlighter::highlightBlock(const QString &text)
}
}
- applyFormatToSpaces(text, m_creatorFormats.value(VisualWhitespace));
+ applyFormatToSpaces(text, formatForCategory(VisualWhitespace));
}
void Highlighter::setupDataForBlock(const QString &text)
@@ -388,34 +411,30 @@ void Highlighter::applyFormat(int offset,
return;
}
- TextFormatId formatId = m_kateFormats.m_ids.value(itemData->style());
+ TextFormatId formatId = kateFormatMap()->m_ids.value(itemData->style(), Normal);
if (formatId != Normal) {
- QHash<TextFormatId, QTextCharFormat>::const_iterator cit =
- m_creatorFormats.constFind(formatId);
- if (cit != m_creatorFormats.constEnd()) {
- QTextCharFormat format = cit.value();
- if (itemData->isCustomized()) {
- // Please notice that the following are applied every time for item data which have
- // customizations. The configureFormats method could be used to provide a "one time"
- // configuration, but it would probably require to traverse all item data from all
- // definitions available/loaded (either to set the values or for some "notifying"
- // strategy). This is because the highlighter does not really know on which
- // definition(s) it is working. Since not many item data specify customizations I
- // think this approach would fit better. If there are other ideas...
- if (itemData->color().isValid())
- format.setForeground(itemData->color());
- if (itemData->isItalicSpecified())
- format.setFontItalic(itemData->isItalic());
- if (itemData->isBoldSpecified())
- format.setFontWeight(toFontWeight(itemData->isBold()));
- if (itemData->isUnderlinedSpecified())
- format.setFontUnderline(itemData->isUnderlined());
- if (itemData->isStrikeOutSpecified())
- format.setFontStrikeOut(itemData->isStrikeOut());
- }
-
- setFormat(offset, count, format);
+ QTextCharFormat format = formatForCategory(formatId);
+ if (itemData->isCustomized()) {
+ // Please notice that the following are applied every time for item data which have
+ // customizations. The configureFormats method could be used to provide a "one time"
+ // configuration, but it would probably require to traverse all item data from all
+ // definitions available/loaded (either to set the values or for some "notifying"
+ // strategy). This is because the highlighter does not really know on which
+ // definition(s) it is working. Since not many item data specify customizations I
+ // think this approach would fit better. If there are other ideas...
+ if (itemData->color().isValid())
+ format.setForeground(itemData->color());
+ if (itemData->isItalicSpecified())
+ format.setFontItalic(itemData->isItalic());
+ if (itemData->isBoldSpecified())
+ format.setFontWeight(toFontWeight(itemData->isBold()));
+ if (itemData->isUnderlinedSpecified())
+ format.setFontUnderline(itemData->isUnderlined());
+ if (itemData->isStrikeOutSpecified())
+ format.setFontStrikeOut(itemData->isStrikeOut());
}
+
+ setFormat(offset, count, format);
}
}
diff --git a/src/plugins/texteditor/generichighlighter/highlighter.h b/src/plugins/texteditor/generichighlighter/highlighter.h
index dc3445663a..968a48a6c1 100644
--- a/src/plugins/texteditor/generichighlighter/highlighter.h
+++ b/src/plugins/texteditor/generichighlighter/highlighter.h
@@ -30,8 +30,11 @@
#ifndef HIGHLIGHTER_H
#define HIGHLIGHTER_H
-#include "basetextdocumentlayout.h"
-#include "syntaxhighlighter.h"
+#include "context.h"
+
+// Yes, this is correct. These are found somewhere else when building the autotest.
+#include <basetextdocumentlayout.h>
+#include <syntaxhighlighter.h>
#include <QString>
#include <QVector>
@@ -44,14 +47,19 @@
namespace TextEditor {
class TabSettings;
-
namespace Internal {
class Rule;
-class Context;
class HighlightDefinition;
class ProgressData;
+} // namespace Internal
+
+/*
+ Warning: Due to a very ugly hack with generichighlighter test
+ you can't export this class, so that it would be used from
+ other plugins. That's why highlighterutils.h was introduced.
+*/
class Highlighter : public TextEditor::SyntaxHighlighter
{
Q_OBJECT
@@ -65,12 +73,12 @@ public:
VisualWhitespace,
Keyword,
DataType,
+ Comment,
Decimal,
BaseN,
Float,
Char,
String,
- Comment,
Alert,
Error,
Function,
@@ -78,9 +86,8 @@ public:
Others
};
- void configureFormat(TextFormatId id, const QTextCharFormat &format);
void setTabSettings(const TabSettings &ts);
- void setDefaultContext(const QSharedPointer<Context> &defaultContext);
+ void setDefaultContext(const QSharedPointer<Internal::Context> &defaultContext);
protected:
virtual void highlightBlock(const QString &text);
@@ -95,17 +102,17 @@ private:
void iterateThroughRules(const QString &text,
const int length,
- ProgressData *progress,
+ Internal::ProgressData *progress,
const bool childRule,
- const QList<QSharedPointer<Rule> > &rules);
+ const QList<QSharedPointer<Internal::Rule> > &rules);
void assignCurrentContext();
bool contextChangeRequired(const QString &contextName) const;
void handleContextChange(const QString &contextName,
- const QSharedPointer<HighlightDefinition> &definition,
+ const QSharedPointer<Internal::HighlightDefinition> &definition,
const bool setCurrent = true);
void changeContext(const QString &contextName,
- const QSharedPointer<HighlightDefinition> &definition,
+ const QSharedPointer<Internal::HighlightDefinition> &definition,
const bool assignCurrent = true);
QString currentContextSequence() const;
@@ -113,7 +120,7 @@ private:
void mapLeadingSequence(const QString &contextSequence);
void pushContextSequence(int state);
- void pushDynamicContext(const QSharedPointer<Context> &baseContext);
+ void pushDynamicContext(const QSharedPointer<Internal::Context> &baseContext);
void createWillContinueBlock();
void analyseConsistencyOfWillContinueBlock(const QString &text);
@@ -121,21 +128,12 @@ private:
void applyFormat(int offset,
int count,
const QString &itemDataName,
- const QSharedPointer<HighlightDefinition> &definition);
+ const QSharedPointer<Internal::HighlightDefinition> &definition);
void applyRegionBasedFolding() const;
void applyIndentationBasedFolding(const QString &text) const;
int neighbouringNonEmptyBlockIndent(QTextBlock block, const bool previous) const;
- // Mapping from Kate format strings to format ids.
- struct KateFormatMap
- {
- KateFormatMap();
- QHash<QString, TextFormatId> m_ids;
- };
- static const KateFormatMap m_kateFormats;
- QHash<TextFormatId, QTextCharFormat> m_creatorFormats;
-
struct BlockData : TextBlockUserData
{
BlockData();
@@ -144,7 +142,7 @@ private:
int m_foldingIndentDelta;
int m_originalObservableState;
QStack<QString> m_foldingRegions;
- QSharedPointer<Context> m_contextToContinue;
+ QSharedPointer<Internal::Context> m_contextToContinue;
};
BlockData *initializeBlockData();
static BlockData *blockData(QTextBlockUserData *userData);
@@ -181,22 +179,21 @@ private:
bool m_isBroken;
- QSharedPointer<Context> m_defaultContext;
- QSharedPointer<Context> m_currentContext;
- QVector<QSharedPointer<Context> > m_contexts;
+ QSharedPointer<Internal::Context> m_defaultContext;
+ QSharedPointer<Internal::Context> m_currentContext;
+ QVector<QSharedPointer<Internal::Context> > m_contexts;
// Mapping from context sequences to the observable persistent state they represent.
QHash<QString, int> m_persistentObservableStates;
// Mapping from context sequences to the non-persistent observable state that led to them.
QHash<QString, int> m_leadingObservableStates;
// Mapping from observable persistent states to context sequences (the actual "stack").
- QHash<int, QVector<QSharedPointer<Context> > > m_persistentContexts;
+ QHash<int, QVector<QSharedPointer<Internal::Context> > > m_persistentContexts;
// Captures used in dynamic rules.
QStringList m_currentCaptures;
};
-} // namespace Internal
} // namespace TextEditor
#endif // HIGHLIGHTER_H
diff --git a/src/plugins/texteditor/generichighlighter/managedefinitionsdialog.cpp b/src/plugins/texteditor/generichighlighter/managedefinitionsdialog.cpp
index f01fcf6621..d1e8ef6ac7 100644
--- a/src/plugins/texteditor/generichighlighter/managedefinitionsdialog.cpp
+++ b/src/plugins/texteditor/generichighlighter/managedefinitionsdialog.cpp
@@ -84,9 +84,9 @@ void ManageDefinitionsDialog::populateDefinitionsWidget()
for (int j = 0; j < 3; ++j) {
QTableWidgetItem *item = new QTableWidgetItem;
- if (j == 0)
+ if (j == 0) {
item->setText(downloadData.name);
- else if (j == 1) {
+ } else if (j == 1) {
item->setText(dirVersion);
item->setTextAlignment(Qt::AlignCenter);
} else if (j == 2) {
diff --git a/src/plugins/texteditor/generichighlighter/manager.cpp b/src/plugins/texteditor/generichighlighter/manager.cpp
index 109b667387..05dcdcf06f 100644
--- a/src/plugins/texteditor/generichighlighter/manager.cpp
+++ b/src/plugins/texteditor/generichighlighter/manager.cpp
@@ -33,10 +33,10 @@
#include "highlighterexception.h"
#include "definitiondownloader.h"
#include "highlightersettings.h"
-#include "plaintexteditorfactory.h"
-#include "texteditorconstants.h"
-#include "texteditorplugin.h"
-#include "texteditorsettings.h"
+#include <texteditor/plaintexteditorfactory.h>
+#include <texteditor/texteditorconstants.h>
+#include <texteditor/texteditorplugin.h>
+#include <texteditor/texteditorsettings.h>
#include <coreplugin/icore.h>
#include <coreplugin/progressmanager/progressmanager.h>
@@ -64,8 +64,10 @@
#include <QNetworkRequest>
#include <QNetworkReply>
-using namespace TextEditor;
-using namespace Internal;
+using namespace Core;
+
+namespace TextEditor {
+namespace Internal {
const char kPriority[] = "priority";
const char kName[] = "name";
@@ -157,21 +159,18 @@ bool Manager::isBuildingDefinition(const QString &id) const
return m_isBuildingDefinition.contains(id);
}
-namespace TextEditor {
-namespace Internal {
-
class ManagerProcessor : public QObject
{
Q_OBJECT
public:
ManagerProcessor();
void process(QFutureInterface<QPair<Manager::RegisterData,
- QList<Core::MimeType> > > &future);
+ QList<MimeType> > > &future);
QStringList m_definitionsPaths;
QSet<QString> m_knownMimeTypes;
QSet<QString> m_knownSuffixes;
- QHash<QString, Core::MimeType> m_userModified;
+ QHash<QString, MimeType> m_userModified;
static const int kMaxProgress;
};
@@ -184,22 +183,21 @@ bool priorityComp(const QSharedPointer<HighlightDefinitionMetaData> &a,
const int ManagerProcessor::kMaxProgress = 200;
ManagerProcessor::ManagerProcessor()
- : m_knownSuffixes(QSet<QString>::fromList(Core::ICore::mimeDatabase()->suffixes()))
+ : m_knownSuffixes(QSet<QString>::fromList(MimeDatabase::suffixes()))
{
- const HighlighterSettings &settings = TextEditorSettings::instance()->highlighterSettings();
+ const HighlighterSettings &settings = TextEditorSettings::highlighterSettings();
m_definitionsPaths.append(settings.definitionFilesPath());
if (settings.useFallbackLocation())
m_definitionsPaths.append(settings.fallbackDefinitionFilesPath());
- Core::MimeDatabase *mimeDatabase = Core::ICore::mimeDatabase();
- foreach (const Core::MimeType &userMimeType, mimeDatabase->readUserModifiedMimeTypes())
+ foreach (const MimeType &userMimeType, MimeDatabase::readUserModifiedMimeTypes())
m_userModified.insert(userMimeType.type(), userMimeType);
- foreach (const Core::MimeType &mimeType, mimeDatabase->mimeTypes())
+ foreach (const MimeType &mimeType, MimeDatabase::mimeTypes())
m_knownMimeTypes.insert(mimeType.type());
}
void ManagerProcessor::process(QFutureInterface<QPair<Manager::RegisterData,
- QList<Core::MimeType> > > &future)
+ QList<MimeType> > > &future)
{
future.setProgressRange(0, kMaxProgress);
@@ -215,7 +213,7 @@ void ManagerProcessor::process(QFutureInterface<QPair<Manager::RegisterData,
// is a change in the generic highlighter settings.
Manager::RegisterData data;
- QList<Core::MimeType> newMimeTypes;
+ QList<MimeType> newMimeTypes;
foreach (const QString &path, m_definitionsPaths) {
if (path.isEmpty())
@@ -253,7 +251,7 @@ void ManagerProcessor::process(QFutureInterface<QPair<Manager::RegisterData,
// A definition can specify multiple MIME types and file extensions/patterns,
// but all on a single string. So associate all patterns with all MIME types.
- QList<Core::MimeGlobPattern> globPatterns;
+ QList<MimeGlobPattern> globPatterns;
foreach (const QString &type, metaData->mimeTypes) {
if (data.m_idByMimeType.contains(type))
continue;
@@ -262,7 +260,7 @@ void ManagerProcessor::process(QFutureInterface<QPair<Manager::RegisterData,
if (!m_knownMimeTypes.contains(type)) {
m_knownMimeTypes.insert(type);
- Core::MimeType mimeType;
+ MimeType mimeType;
mimeType.setType(type);
mimeType.setSubClassesOf(textPlain);
mimeType.setComment(metaData->name);
@@ -270,7 +268,7 @@ void ManagerProcessor::process(QFutureInterface<QPair<Manager::RegisterData,
// If there's a user modification for this mime type, we want to use the
// modified patterns and rule-based matchers. If not, just consider what
// is specified in the definition file.
- QHash<QString, Core::MimeType>::const_iterator it =
+ QHash<QString, MimeType>::const_iterator it =
m_userModified.find(mimeType.type());
if (it == m_userModified.end()) {
if (globPatterns.isEmpty()) {
@@ -283,7 +281,7 @@ void ManagerProcessor::process(QFutureInterface<QPair<Manager::RegisterData,
else
continue;
}
- globPatterns.append(Core::MimeGlobPattern(pattern, 50));
+ globPatterns.append(MimeGlobPattern(pattern, 50));
}
}
mimeType.setGlobPatterns(globPatterns);
@@ -301,24 +299,18 @@ void ManagerProcessor::process(QFutureInterface<QPair<Manager::RegisterData,
future.reportResult(qMakePair(data, newMimeTypes));
}
-} // Internal
-} // TextEditor
-
-
void Manager::registerMimeTypes()
{
if (!m_registeringWatcher.isRunning()) {
clear();
ManagerProcessor *processor = new ManagerProcessor;
- QFuture<QPair<RegisterData, QList<Core::MimeType> > > future =
+ QFuture<QPair<RegisterData, QList<MimeType> > > future =
QtConcurrent::run(&ManagerProcessor::process, processor);
connect(&m_registeringWatcher, SIGNAL(finished()), processor, SLOT(deleteLater()));
m_registeringWatcher.setFuture(future);
- Core::ICore::progressManager()->addTask(future,
- tr("Registering definitions"),
- QLatin1String(Constants::TASK_REGISTER_DEFINITIONS));
+ ProgressManager::addTask(future, tr("Registering definitions"), "TextEditor.Task.Register");
} else {
m_hasQueuedRegistration = true;
m_registeringWatcher.cancel();
@@ -331,13 +323,13 @@ void Manager::registerMimeTypesFinished()
m_hasQueuedRegistration = false;
registerMimeTypes();
} else if (!m_registeringWatcher.isCanceled()) {
- const QPair<RegisterData, QList<Core::MimeType> > &result = m_registeringWatcher.result();
+ const QPair<RegisterData, QList<MimeType> > &result = m_registeringWatcher.result();
m_register = result.first;
PlainTextEditorFactory *factory = TextEditorPlugin::instance()->editorFactory();
const QSet<QString> &inFactory = factory->mimeTypes().toSet();
- foreach (const Core::MimeType &mimeType, result.second) {
- Core::ICore::mimeDatabase()->addMimeType(mimeType);
+ foreach (const MimeType &mimeType, result.second) {
+ MimeDatabase::addMimeType(mimeType);
if (!inFactory.contains(mimeType.type()))
factory->addMimeType(mimeType.type());
}
@@ -451,9 +443,7 @@ void Manager::downloadDefinitions(const QList<QUrl> &urls, const QString &savePa
m_isDownloadingDefinitionsSpec = true;
QFuture<void> future = QtConcurrent::map(m_downloaders, DownloaderStarter());
m_downloadWatcher.setFuture(future);
- Core::ICore::progressManager()->addTask(future,
- tr("Downloading definitions"),
- QLatin1String(Constants::TASK_DOWNLOAD_DEFINITIONS));
+ ProgressManager::addTask(future, tr("Downloading definitions"), "TextEditor.Task.Download");
}
void Manager::downloadDefinitionsFinished()
@@ -497,4 +487,7 @@ void Manager::clear()
m_definitions.clear();
}
+} // namespace Internal
+} // namespace TextEditor
+
#include "manager.moc"
diff --git a/src/plugins/texteditor/generichighlighter/manager.h b/src/plugins/texteditor/generichighlighter/manager.h
index 548ef118ee..9c39d194ec 100644
--- a/src/plugins/texteditor/generichighlighter/manager.h
+++ b/src/plugins/texteditor/generichighlighter/manager.h
@@ -95,6 +95,7 @@ private:
Manager();
void clear();
+ int foo();
bool m_isDownloadingDefinitionsSpec;
QList<DefinitionDownloader *> m_downloaders;
diff --git a/src/plugins/texteditor/helpitem.cpp b/src/plugins/texteditor/helpitem.cpp
index 48ce056510..eca956d29b 100644
--- a/src/plugins/texteditor/helpitem.cpp
+++ b/src/plugins/texteditor/helpitem.cpp
@@ -99,7 +99,7 @@ QString HelpItem::extractContent(bool extended) const
helpLinks.insert(m_helpId, m_helpId);
}
foreach (const QUrl &url, helpLinks) {
- const QString html = QString::fromUtf8(Core::HelpManager::instance()->fileData(url));
+ const QString html = QString::fromUtf8(Core::HelpManager::fileData(url));
switch (m_category) {
case Brief:
contents = htmlExtractor.getClassOrNamespaceBrief(html, m_docMark);
@@ -142,6 +142,6 @@ QString HelpItem::extractContent(bool extended) const
QMap<QString, QUrl> HelpItem::retrieveHelpLinks() const
{
if (m_helpLinks.isEmpty())
- m_helpLinks = Core::HelpManager::instance()->linksForIdentifier(m_helpId);
+ m_helpLinks = Core::HelpManager::linksForIdentifier(m_helpId);
return m_helpLinks;
}
diff --git a/src/plugins/texteditor/highlighterutils.cpp b/src/plugins/texteditor/highlighterutils.cpp
new file mode 100644
index 0000000000..360bb7bb91
--- /dev/null
+++ b/src/plugins/texteditor/highlighterutils.cpp
@@ -0,0 +1,76 @@
+/****************************************************************************
+**
+** 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 "highlighterutils.h"
+#include "generichighlighter/highlighter.h"
+#include "generichighlighter/highlightdefinition.h"
+#include "generichighlighter/manager.h"
+#include <coreplugin/icore.h>
+
+using namespace TextEditor;
+using namespace Internal;
+
+QString TextEditor::findDefinitionId(const Core::MimeType &mimeType,
+ bool considerParents)
+{
+ QString definitionId = Manager::instance()->definitionIdByAnyMimeType(mimeType.aliases());
+ if (definitionId.isEmpty() && considerParents) {
+ definitionId = Manager::instance()->definitionIdByAnyMimeType(mimeType.subClassesOf());
+ if (definitionId.isEmpty()) {
+ foreach (const QString &parent, mimeType.subClassesOf()) {
+ const Core::MimeType &parentMimeType = Core::MimeDatabase::findByType(parent);
+ definitionId = findDefinitionId(parentMimeType, considerParents);
+ }
+ }
+ }
+ return definitionId;
+}
+
+void TextEditor::setMimeTypeForHighlighter(Highlighter *highlighter, const Core::MimeType &mimeType)
+{
+ const QString type = mimeType.type();
+ QString definitionId = Manager::instance()->definitionIdByMimeType(type);
+ if (definitionId.isEmpty())
+ definitionId = findDefinitionId(mimeType, true);
+
+ if (!definitionId.isEmpty()) {
+ const QSharedPointer<HighlightDefinition> &definition =
+ Manager::instance()->definition(definitionId);
+ if (!definition.isNull() && definition->isValid()) {
+ highlighter->setDefaultContext(definition->initialContext());
+ }
+ }
+}
+
+SyntaxHighlighter *TextEditor::createGenericSyntaxHighlighter(const Core::MimeType &mimeType)
+{
+ TextEditor::Highlighter *highlighter = new TextEditor::Highlighter();
+ setMimeTypeForHighlighter(highlighter, mimeType);
+ return highlighter;
+}
diff --git a/src/plugins/texteditor/highlighterutils.h b/src/plugins/texteditor/highlighterutils.h
new file mode 100644
index 0000000000..dd6bc5343d
--- /dev/null
+++ b/src/plugins/texteditor/highlighterutils.h
@@ -0,0 +1,55 @@
+/****************************************************************************
+**
+** 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 HIGHLIGHTERUTILS_H
+#define HIGHLIGHTERUTILS_H
+
+#include <QString>
+#include "texteditor_global.h"
+
+/* These methods were originally a part of TextEditor::Highlighter,
+ * but due to a very hackish test of that generic highlighter,
+ * there methods must be outside. */
+
+namespace Core {
+class MimeType;
+}
+
+namespace TextEditor {
+
+class Highlighter;
+class SyntaxHighlighter;
+
+void setMimeTypeForHighlighter(Highlighter *highlighter, const Core::MimeType &mimeType);
+QString findDefinitionId(const Core::MimeType &mimeType, bool considerParents);
+TEXTEDITOR_EXPORT SyntaxHighlighter *createGenericSyntaxHighlighter(const Core::MimeType &mimeType);
+
+} // namespace TextEditor
+
+#endif // HIGHLIGHTERUTILS_H
diff --git a/src/plugins/texteditor/icodestylepreferences.cpp b/src/plugins/texteditor/icodestylepreferences.cpp
index 5d7159bf78..0db62335c7 100644
--- a/src/plugins/texteditor/icodestylepreferences.cpp
+++ b/src/plugins/texteditor/icodestylepreferences.cpp
@@ -53,7 +53,7 @@ public:
CodeStylePool *m_pool;
ICodeStylePreferences *m_currentDelegate;
TabSettings m_tabSettings;
- QString m_id;
+ QByteArray m_id;
QString m_displayName;
bool m_readOnly;
};
@@ -72,12 +72,12 @@ ICodeStylePreferences::~ICodeStylePreferences()
delete d;
}
-QString ICodeStylePreferences::id() const
+QByteArray ICodeStylePreferences::id() const
{
return d->m_id;
}
-void ICodeStylePreferences::setId(const QString &name)
+void ICodeStylePreferences::setId(const QByteArray &name)
{
d->m_id = name;
}
@@ -203,14 +203,14 @@ void ICodeStylePreferences::setCurrentDelegate(ICodeStylePreferences *delegate)
emit currentValueChanged(currentValue());
}
-QString ICodeStylePreferences::currentDelegateId() const
+QByteArray ICodeStylePreferences::currentDelegateId() const
{
if (currentDelegate())
return currentDelegate()->id();
return id(); // or 0?
}
-void ICodeStylePreferences::setCurrentDelegate(const QString &id)
+void ICodeStylePreferences::setCurrentDelegate(const QByteArray &id)
{
if (d->m_pool)
setCurrentDelegate(d->m_pool->codeStyle(id));
@@ -237,7 +237,7 @@ void ICodeStylePreferences::toMap(const QString &prefix, QVariantMap *map) const
void ICodeStylePreferences::fromMap(const QString &prefix, const QVariantMap &map)
{
d->m_tabSettings.fromMap(prefix, map);
- const QString delegateId = map.value(prefix + QLatin1String(currentPreferencesKey)).toString();
+ const QByteArray delegateId = map.value(prefix + QLatin1String(currentPreferencesKey)).toByteArray();
if (delegatingPool()) {
ICodeStylePreferences *delegate = delegatingPool()->codeStyle(delegateId);
if (!delegateId.isEmpty() && delegate)
diff --git a/src/plugins/texteditor/icodestylepreferences.h b/src/plugins/texteditor/icodestylepreferences.h
index ec41756709..1e63589608 100644
--- a/src/plugins/texteditor/icodestylepreferences.h
+++ b/src/plugins/texteditor/icodestylepreferences.h
@@ -57,8 +57,8 @@ public:
explicit ICodeStylePreferences(QObject *parentObject = 0);
virtual ~ICodeStylePreferences();
- QString id() const;
- void setId(const QString &name);
+ QByteArray id() const;
+ void setId(const QByteArray &name);
QString displayName() const;
void setDisplayName(const QString &name);
@@ -83,8 +83,8 @@ public:
ICodeStylePreferences *currentDelegate() const; // null or one of delegates from the pool
void setCurrentDelegate(ICodeStylePreferences *delegate);
- QString currentDelegateId() const;
- void setCurrentDelegate(const QString &id);
+ QByteArray currentDelegateId() const;
+ void setCurrentDelegate(const QByteArray &id);
void toSettings(const QString &category, QSettings *s) const;
void fromSettings(const QString &category, const QSettings *s);
diff --git a/src/plugins/texteditor/ihighlighterfactory.h b/src/plugins/texteditor/ihighlighterfactory.h
new file mode 100644
index 0000000000..0909d72898
--- /dev/null
+++ b/src/plugins/texteditor/ihighlighterfactory.h
@@ -0,0 +1,66 @@
+/****************************************************************************
+**
+** 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 IHIGHLIGHTERFACTORY_H
+#define IHIGHLIGHTERFACTORY_H
+
+#include <texteditor/texteditor_global.h>
+#include <coreplugin/id.h>
+
+#include <QObject>
+#include <QStringList>
+
+namespace TextEditor {
+
+class SyntaxHighlighter;
+
+class TEXTEDITOR_EXPORT IHighlighterFactory : public QObject
+{
+ Q_OBJECT
+public:
+ virtual TextEditor::SyntaxHighlighter *createHighlighter() const = 0;
+
+ Core::Id id() const { return m_id; }
+ QStringList mimeTypes() const { return m_mimeTypes; }
+
+protected:
+ void setId(Core::Id id) { m_id = id; }
+ void setMimeTypes(const QStringList &mimeTypes) { m_mimeTypes = mimeTypes; }
+ void addMimeType(const char *mimeType) { m_mimeTypes.append(QLatin1String(mimeType)); }
+ void addMimeType(const QString &mimeType) { m_mimeTypes.append(mimeType); }
+
+private:
+ Core::Id m_id;
+ QStringList m_mimeTypes;
+};
+
+} // TextEditor
+
+#endif // IHIGHLIGHTERFACTORY_H
+
diff --git a/src/plugins/texteditor/itexteditor.cpp b/src/plugins/texteditor/itexteditor.cpp
index 75248dd1b3..ab2b80b9b2 100644
--- a/src/plugins/texteditor/itexteditor.cpp
+++ b/src/plugins/texteditor/itexteditor.cpp
@@ -38,28 +38,28 @@ ITextEditorDocument::ITextEditorDocument(QObject *parent)
{
}
-QMap<QString, QString> ITextEditor::openedTextEditorsContents()
+QMap<QString, QString> ITextEditor::openedTextDocumentContents()
{
QMap<QString, QString> workingCopy;
- foreach (Core::IEditor *editor, Core::EditorManager::instance()->openedEditors()) {
- ITextEditor *textEditor = qobject_cast<ITextEditor *>(editor);
- if (!textEditor)
+ foreach (Core::IDocument *document, Core::EditorManager::documentModel()->openedDocuments()) {
+ ITextEditorDocument *textEditorDocument = qobject_cast<ITextEditorDocument *>(document);
+ if (!textEditorDocument)
continue;
- QString fileName = textEditor->document()->fileName();
- workingCopy[fileName] = textEditor->textDocument()->contents();
+ QString fileName = textEditorDocument->filePath();
+ workingCopy[fileName] = textEditorDocument->contents();
}
return workingCopy;
}
-QMap<QString, QTextCodec *> TextEditor::ITextEditor::openedTextEditorsEncodings()
+QMap<QString, QTextCodec *> TextEditor::ITextEditor::openedTextDocumentEncodings()
{
QMap<QString, QTextCodec *> workingCopy;
- foreach (Core::IEditor *editor, Core::EditorManager::instance()->openedEditors()) {
- ITextEditor *textEditor = qobject_cast<ITextEditor *>(editor);
- if (!textEditor)
+ foreach (Core::IDocument *document, Core::EditorManager::documentModel()->openedDocuments()) {
+ ITextEditorDocument *textEditorDocument = qobject_cast<ITextEditorDocument *>(document);
+ if (!textEditorDocument)
continue;
- QString fileName = textEditor->document()->fileName();
- workingCopy[fileName] = textEditor->textCodec();
+ QString fileName = textEditorDocument->filePath();
+ workingCopy[fileName] = const_cast<QTextCodec *>(textEditorDocument->codec());
}
return workingCopy;
}
diff --git a/src/plugins/texteditor/itexteditor.h b/src/plugins/texteditor/itexteditor.h
index dd9a3fcb7f..2fa63d34c1 100644
--- a/src/plugins/texteditor/itexteditor.h
+++ b/src/plugins/texteditor/itexteditor.h
@@ -56,6 +56,25 @@ namespace Utils {
namespace TextEditor {
+class TEXTEDITOR_EXPORT BlockRange
+{
+public:
+ BlockRange() : _first(0), _last(-1) {}
+ BlockRange(int firstPosition, int lastPosition)
+ : _first(firstPosition), _last(lastPosition)
+ {}
+
+ inline bool isNull() const { return _last < _first; }
+
+ int first() const { return _first; }
+ int last() const { return _last; }
+
+private:
+ int _first;
+ int _last;
+};
+
+
class TEXTEDITOR_EXPORT ITextEditorDocument : public Core::TextDocument
{
Q_OBJECT
@@ -109,19 +128,10 @@ public:
virtual ITextMarkable *markableInterface() = 0;
- enum TextCodecReason {
- TextCodecOtherReason,
- TextCodecFromSystemSetting,
- TextCodecFromProjectSetting
- };
-
- virtual void setTextCodec(QTextCodec *, TextCodecReason reason = TextCodecOtherReason) = 0;
- virtual QTextCodec *textCodec() const = 0;
-
virtual const Utils::CommentDefinition* commentDefinition() const = 0;
- static QMap<QString, QString> openedTextEditorsContents();
- static QMap<QString, QTextCodec *> openedTextEditorsEncodings();
+ static QMap<QString, QString> openedTextDocumentContents();
+ static QMap<QString, QTextCodec *> openedTextDocumentEncodings();
enum MarkRequestKind {
BreakpointRequest,
diff --git a/src/plugins/texteditor/linenumberfilter.cpp b/src/plugins/texteditor/linenumberfilter.cpp
index d5f44e7cd7..1247f96d02 100644
--- a/src/plugins/texteditor/linenumberfilter.cpp
+++ b/src/plugins/texteditor/linenumberfilter.cpp
@@ -91,8 +91,7 @@ void LineNumberFilter::accept(FilterEntry selection) const
{
ITextEditor *editor = currentTextEditor();
if (editor) {
- Core::EditorManager *editorManager = Core::EditorManager::instance();
- editorManager->addCurrentPositionToNavigationHistory();
+ EditorManager::addCurrentPositionToNavigationHistory();
LineColumn data = selection.internalData.value<LineColumn>();
if (data.first < 1) { // jump to column in same line
int currLine, currColumn;
@@ -100,7 +99,7 @@ void LineNumberFilter::accept(FilterEntry selection) const
data.first = currLine;
}
editor->gotoLine(data.first, data.second);
- Core::EditorManager::activateEditor(editor);
+ EditorManager::activateEditor(editor);
}
}
diff --git a/src/plugins/texteditor/outlinefactory.cpp b/src/plugins/texteditor/outlinefactory.cpp
index c2eaad2675..4df0013e44 100644
--- a/src/plugins/texteditor/outlinefactory.cpp
+++ b/src/plugins/texteditor/outlinefactory.cpp
@@ -71,8 +71,7 @@ OutlineWidgetStack::OutlineWidgetStack(OutlineFactory *factory) :
m_filterMenu = new QMenu(m_filterButton);
m_filterButton->setMenu(m_filterMenu);
- Core::EditorManager *editorManager = Core::EditorManager::instance();
- connect(editorManager, SIGNAL(currentEditorChanged(Core::IEditor*)),
+ connect(Core::EditorManager::instance(), SIGNAL(currentEditorChanged(Core::IEditor*)),
this, SLOT(updateCurrentEditor(Core::IEditor*)));
updateCurrentEditor(Core::EditorManager::currentEditor());
}
@@ -197,7 +196,7 @@ int OutlineFactory::priority() const
Core::Id OutlineFactory::id() const
{
- return Core::Id("Outline");
+ return "Outline";
}
QKeySequence OutlineFactory::activationSequence() const
diff --git a/src/plugins/texteditor/plaintexteditor.cpp b/src/plugins/texteditor/plaintexteditor.cpp
index 322113738f..1e99aa448e 100644
--- a/src/plugins/texteditor/plaintexteditor.cpp
+++ b/src/plugins/texteditor/plaintexteditor.cpp
@@ -32,21 +32,19 @@
#include "texteditorplugin.h"
#include "texteditorsettings.h"
#include "basetextdocument.h"
-#include "highlightdefinition.h"
-#include "highlighter.h"
-#include "highlightersettings.h"
-#include "manager.h"
-#include "context.h"
#include "normalindenter.h"
-#include "fontsettings.h"
+#include "highlighterutils.h"
+#include <texteditor/generichighlighter/context.h>
+#include <texteditor/generichighlighter/highlightdefinition.h>
+#include <texteditor/generichighlighter/highlighter.h>
+#include <texteditor/generichighlighter/highlightersettings.h>
+#include <texteditor/generichighlighter/manager.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/icore.h>
#include <QSharedPointer>
-#include <QDebug>
-
using namespace Core;
using namespace TextEditor::Internal;
@@ -69,7 +67,6 @@ PlainTextEditorWidget::PlainTextEditorWidget(QWidget *parent)
setIndenter(new NormalIndenter); // Currently only "normal" indentation is supported.
setMimeType(QLatin1String(TextEditor::Constants::C_TEXTEDITOR_MIMETYPE_TEXT));
- setDisplayName(tr(Core::Constants::K_DEFAULT_TEXT_EDITOR_DISPLAY_NAME));
m_commentDefinition.clearCommentStyles();
@@ -77,7 +74,7 @@ PlainTextEditorWidget::PlainTextEditorWidget(QWidget *parent)
connect(Manager::instance(), SIGNAL(mimeTypesRegistered()), this, SLOT(configure()));
}
-Core::IEditor *PlainTextEditor::duplicate(QWidget *parent)
+IEditor *PlainTextEditor::duplicate(QWidget *parent)
{
PlainTextEditorWidget *newWidget = new PlainTextEditorWidget(parent);
newWidget->duplicateFrom(editorWidget());
@@ -85,9 +82,9 @@ Core::IEditor *PlainTextEditor::duplicate(QWidget *parent)
return newWidget->editor();
}
-Core::Id PlainTextEditor::id() const
+Id PlainTextEditor::id() const
{
- return Core::Id(Core::Constants::K_DEFAULT_TEXT_EDITOR_ID);
+ return Core::Constants::K_DEFAULT_TEXT_EDITOR_ID;
}
void PlainTextEditorWidget::unCommentSelection()
@@ -95,30 +92,6 @@ void PlainTextEditorWidget::unCommentSelection()
Utils::unCommentSelection(this, m_commentDefinition);
}
-void PlainTextEditorWidget::setFontSettings(const FontSettings &fs)
-{
- BaseTextEditorWidget::setFontSettings(fs);
-
- if (baseTextDocument()->syntaxHighlighter()) {
- Highlighter *highlighter =
- static_cast<Highlighter *>(baseTextDocument()->syntaxHighlighter());
-
- highlighter->configureFormat(Highlighter::VisualWhitespace, fs.toTextCharFormat(C_VISUAL_WHITESPACE));
- highlighter->configureFormat(Highlighter::Keyword, fs.toTextCharFormat(C_KEYWORD));
- highlighter->configureFormat(Highlighter::DataType, fs.toTextCharFormat(C_TYPE));
- highlighter->configureFormat(Highlighter::Comment, fs.toTextCharFormat(C_COMMENT));
- // Using C_NUMBER for all kinds of numbers.
- highlighter->configureFormat(Highlighter::Decimal, fs.toTextCharFormat(C_NUMBER));
- highlighter->configureFormat(Highlighter::BaseN, fs.toTextCharFormat(C_NUMBER));
- highlighter->configureFormat(Highlighter::Float, fs.toTextCharFormat(C_NUMBER));
- // Using C_STRING for strings and chars.
- highlighter->configureFormat(Highlighter::Char, fs.toTextCharFormat(C_STRING));
- highlighter->configureFormat(Highlighter::String, fs.toTextCharFormat(C_STRING));
-
- highlighter->rehighlight();
- }
-}
-
void PlainTextEditorWidget::setTabSettings(const TextEditor::TabSettings &ts)
{
BaseTextEditorWidget::setTabSettings(ts);
@@ -132,18 +105,18 @@ void PlainTextEditorWidget::setTabSettings(const TextEditor::TabSettings &ts)
void PlainTextEditorWidget::configure()
{
- Core::MimeType mimeType;
+ MimeType mimeType;
if (editorDocument())
- mimeType = Core::ICore::mimeDatabase()->findByFile(editorDocument()->fileName());
+ mimeType = MimeDatabase::findByFile(editorDocument()->filePath());
configure(mimeType);
}
void PlainTextEditorWidget::configure(const QString &mimeType)
{
- configure(Core::ICore::mimeDatabase()->findByType(mimeType));
+ configure(MimeDatabase::findByType(mimeType));
}
-void PlainTextEditorWidget::configure(const Core::MimeType &mimeType)
+void PlainTextEditorWidget::configure(const MimeType &mimeType)
{
Highlighter *highlighter = new Highlighter();
baseTextDocument()->setSyntaxHighlighter(highlighter);
@@ -153,6 +126,7 @@ void PlainTextEditorWidget::configure(const Core::MimeType &mimeType)
if (!mimeType.isNull()) {
m_isMissingSyntaxDefinition = true;
+ setMimeTypeForHighlighter(highlighter, mimeType);
const QString &type = mimeType.type();
setMimeType(type);
@@ -165,8 +139,6 @@ void PlainTextEditorWidget::configure(const Core::MimeType &mimeType)
const QSharedPointer<HighlightDefinition> &definition =
Manager::instance()->definition(definitionId);
if (!definition.isNull() && definition->isValid()) {
- highlighter->setDefaultContext(definition->initialContext());
-
m_commentDefinition.isAfterWhiteSpaces = definition->isCommentAfterWhiteSpaces();
m_commentDefinition.singleLine = definition->singleLineComment();
m_commentDefinition.multiLineStart = definition->multiLineCommentStart();
@@ -175,13 +147,13 @@ void PlainTextEditorWidget::configure(const Core::MimeType &mimeType)
setCodeFoldingSupported(true);
}
} else if (editorDocument()) {
- const QString &fileName = editorDocument()->fileName();
- if (TextEditorSettings::instance()->highlighterSettings().isIgnoredFilePattern(fileName))
+ const QString &fileName = editorDocument()->filePath();
+ if (TextEditorSettings::highlighterSettings().isIgnoredFilePattern(fileName))
m_isMissingSyntaxDefinition = false;
}
}
- setFontSettings(TextEditorSettings::instance()->fontSettings());
+ setFontSettings(TextEditorSettings::fontSettings());
emit configured(editor());
}
@@ -191,23 +163,6 @@ bool PlainTextEditorWidget::isMissingSyntaxDefinition() const
return m_isMissingSyntaxDefinition;
}
-QString PlainTextEditorWidget::findDefinitionId(const Core::MimeType &mimeType,
- bool considerParents) const
-{
- QString definitionId = Manager::instance()->definitionIdByAnyMimeType(mimeType.aliases());
- if (definitionId.isEmpty() && considerParents) {
- definitionId = Manager::instance()->definitionIdByAnyMimeType(mimeType.subClassesOf());
- if (definitionId.isEmpty()) {
- foreach (const QString &parent, mimeType.subClassesOf()) {
- const Core::MimeType &parentMimeType =
- Core::ICore::mimeDatabase()->findByType(parent);
- definitionId = findDefinitionId(parentMimeType, considerParents);
- }
- }
- }
- return definitionId;
-}
-
void PlainTextEditorWidget::acceptMissingSyntaxDefinitionInfo()
{
ICore::showOptionsDialog(Constants::TEXT_EDITOR_SETTINGS_CATEGORY,
diff --git a/src/plugins/texteditor/plaintexteditor.h b/src/plugins/texteditor/plaintexteditor.h
index 624708f878..35850625a4 100644
--- a/src/plugins/texteditor/plaintexteditor.h
+++ b/src/plugins/texteditor/plaintexteditor.h
@@ -51,7 +51,6 @@ public:
bool duplicateSupported() const { return true; }
Core::IEditor *duplicate(QWidget *parent);
- bool isTemporary() const { return false; }
Core::Id id() const;
};
@@ -68,7 +67,6 @@ public:
public slots:
virtual void unCommentSelection();
- virtual void setFontSettings(const FontSettings &fs);
virtual void setTabSettings(const TextEditor::TabSettings &);
private slots:
@@ -82,8 +80,6 @@ protected:
virtual BaseTextEditor *createEditor() { return new PlainTextEditor(this); }
private:
- QString findDefinitionId(const Core::MimeType &mimeType, bool considerParents) const;
-
bool m_isMissingSyntaxDefinition;
Utils::CommentDefinition m_commentDefinition;
};
diff --git a/src/plugins/texteditor/plaintexteditorfactory.cpp b/src/plugins/texteditor/plaintexteditorfactory.cpp
index d58827e367..c31d411e58 100644
--- a/src/plugins/texteditor/plaintexteditorfactory.cpp
+++ b/src/plugins/texteditor/plaintexteditorfactory.cpp
@@ -46,12 +46,15 @@ using namespace TextEditor::Internal;
PlainTextEditorFactory::PlainTextEditorFactory(QObject *parent)
: Core::IEditorFactory(parent)
{
+ setId(Core::Constants::K_DEFAULT_TEXT_EDITOR_ID);
+ setDisplayName(qApp->translate("OpenWith::Editors", Core::Constants::K_DEFAULT_TEXT_EDITOR_DISPLAY_NAME));
+ addMimeType(QLatin1String(TextEditor::Constants::C_TEXTEDITOR_MIMETYPE_TEXT));
+
m_actionHandler = new TextEditorActionHandler(
TextEditor::Constants::C_TEXTEDITOR,
TextEditorActionHandler::Format |
TextEditorActionHandler::UnCommentSelection |
TextEditorActionHandler::UnCollapseAll);
- m_mimeTypes << QLatin1String(TextEditor::Constants::C_TEXTEDITOR_MIMETYPE_TEXT);
}
PlainTextEditorFactory::~PlainTextEditorFactory()
@@ -59,16 +62,6 @@ PlainTextEditorFactory::~PlainTextEditorFactory()
delete m_actionHandler;
}
-Core::Id PlainTextEditorFactory::id() const
-{
- return Core::Id(Core::Constants::K_DEFAULT_TEXT_EDITOR_ID);
-}
-
-QString PlainTextEditorFactory::displayName() const
-{
- return qApp->translate("OpenWith::Editors", Core::Constants::K_DEFAULT_TEXT_EDITOR_DISPLAY_NAME);
-}
-
Core::IEditor *PlainTextEditorFactory::createEditor(QWidget *parent)
{
PlainTextEditorWidget *rc = new PlainTextEditorWidget(parent);
@@ -106,13 +99,3 @@ void PlainTextEditorFactory::updateEditorInfoBar(Core::IEditor *editor)
}
}
}
-
-void PlainTextEditorFactory::addMimeType(const QString &type)
-{
- m_mimeTypes.append(type);
-}
-
-QStringList PlainTextEditorFactory::mimeTypes() const
-{
- return m_mimeTypes;
-}
diff --git a/src/plugins/texteditor/plaintexteditorfactory.h b/src/plugins/texteditor/plaintexteditorfactory.h
index 712c6701ff..facf43fa9b 100644
--- a/src/plugins/texteditor/plaintexteditorfactory.h
+++ b/src/plugins/texteditor/plaintexteditorfactory.h
@@ -44,22 +44,16 @@ class PlainTextEditorFactory : public Core::IEditorFactory
public:
PlainTextEditorFactory(QObject *parent = 0);
- virtual ~PlainTextEditorFactory();
+ ~PlainTextEditorFactory();
- void addMimeType(const QString &type);
- virtual QStringList mimeTypes() const;
- //Core::IEditorFactory
- Core::Id id() const;
- QString displayName() const;
+ using Core::IEditorFactory::addMimeType;
Core::IEditor *createEditor(QWidget *parent);
-
TextEditor::TextEditorActionHandler *actionHandler() const { return m_actionHandler; }
private slots:
void updateEditorInfoBar(Core::IEditor *editor);
private:
- QStringList m_mimeTypes;
TextEditor::TextEditorActionHandler *m_actionHandler;
};
diff --git a/src/plugins/texteditor/refactoringchanges.cpp b/src/plugins/texteditor/refactoringchanges.cpp
index e8b73f582a..57dd3a9a81 100644
--- a/src/plugins/texteditor/refactoringchanges.cpp
+++ b/src/plugins/texteditor/refactoringchanges.cpp
@@ -56,19 +56,6 @@ RefactoringChanges::RefactoringChanges(RefactoringChangesData *data)
RefactoringChanges::~RefactoringChanges()
{}
-BaseTextEditorWidget *RefactoringChanges::editorForFile(const QString &fileName)
-{
- Core::EditorManager *editorManager = Core::EditorManager::instance();
-
- const QList<Core::IEditor *> editors = editorManager->editorsForFileName(fileName);
- foreach (Core::IEditor *editor, editors) {
- BaseTextEditorWidget *textEditor = qobject_cast<BaseTextEditorWidget *>(editor->widget());
- if (textEditor != 0)
- return textEditor;
- }
- return 0;
-}
-
QList<QPair<QTextCursor, QTextCursor > > RefactoringChanges::rangesToSelections(QTextDocument *document,
const QList<Range> &ranges)
{
@@ -107,7 +94,7 @@ bool RefactoringChanges::createFile(const QString &fileName, const QString &cont
// Write the file to disk:
Utils::TextFileFormat format;
- format.codec = Core::EditorManager::instance()->defaultTextCodec();
+ format.codec = Core::EditorManager::defaultTextCodec();
QString error;
bool saveOk = format.writeFile(fileName, document->toPlainText(), &error);
delete document;
@@ -171,7 +158,7 @@ RefactoringFile::RefactoringFile(QTextDocument *document, const QString &fileNam
{ }
RefactoringFile::RefactoringFile(BaseTextEditorWidget *editor)
- : m_fileName(editor->editorDocument()->fileName())
+ : m_fileName(editor->editorDocument()->filePath())
, m_document(0)
, m_editor(editor)
, m_openEditor(false)
@@ -190,7 +177,9 @@ RefactoringFile::RefactoringFile(const QString &fileName, const QSharedPointer<R
, m_editorCursorPosition(-1)
, m_appliedOnce(false)
{
- m_editor = RefactoringChanges::editorForFile(fileName);
+ QList<Core::IEditor *> editors = Core::EditorManager::documentModel()->editorsForFilePath(fileName);
+ if (!editors.isEmpty())
+ m_editor = qobject_cast<TextEditor::BaseTextEditorWidget *>(editors.first()->widget());
}
RefactoringFile::~RefactoringFile()
@@ -214,11 +203,11 @@ QTextDocument *RefactoringFile::mutableDocument() const
{
if (m_editor)
return m_editor->document();
- else if (!m_document) {
+ if (!m_document) {
QString fileContents;
if (!m_fileName.isEmpty()) {
QString error;
- QTextCodec *defaultCodec = Core::EditorManager::instance()->defaultTextCodec();
+ QTextCodec *defaultCodec = Core::EditorManager::defaultTextCodec();
Utils::TextFileFormat::ReadResult result = Utils::TextFileFormat::readFile(
m_fileName, defaultCodec,
&fileContents, &m_textFileFormat,
@@ -238,7 +227,7 @@ const QTextCursor RefactoringFile::cursor() const
{
if (m_editor)
return m_editor->textCursor();
- else if (!m_fileName.isEmpty()) {
+ if (!m_fileName.isEmpty()) {
if (QTextDocument *doc = mutableDocument())
return QTextCursor(doc);
}
@@ -251,6 +240,11 @@ QString RefactoringFile::fileName() const
return m_fileName;
}
+BaseTextEditorWidget *RefactoringFile::editor() const
+{
+ return m_editor;
+}
+
int RefactoringFile::position(unsigned line, unsigned column) const
{
QTC_ASSERT(line != 0, return -1);
diff --git a/src/plugins/texteditor/refactoringchanges.h b/src/plugins/texteditor/refactoringchanges.h
index 3a33901b0a..f97056777e 100644
--- a/src/plugins/texteditor/refactoringchanges.h
+++ b/src/plugins/texteditor/refactoringchanges.h
@@ -66,6 +66,7 @@ public:
// mustn't use the cursor to change the document
const QTextCursor cursor() const;
QString fileName() const;
+ BaseTextEditorWidget *editor() const;
// converts 1-based line and column into 0-based source offset
int position(unsigned line, unsigned column) const;
@@ -134,8 +135,6 @@ public:
bool createFile(const QString &fileName, const QString &contents, bool reindent = true, bool openEditor = true) const;
bool removeFile(const QString &fileName) const;
- static BaseTextEditorWidget *editorForFile(const QString &fileName);
-
protected:
explicit RefactoringChanges(RefactoringChangesData *data);
diff --git a/src/plugins/texteditor/snippets/snippet.cpp b/src/plugins/texteditor/snippets/snippet.cpp
index 26c5c07c02..45bf15fe95 100644
--- a/src/plugins/texteditor/snippets/snippet.cpp
+++ b/src/plugins/texteditor/snippets/snippet.cpp
@@ -29,12 +29,56 @@
#include "snippet.h"
+#include <coreplugin/id.h>
+
#include <QLatin1Char>
#include <QLatin1String>
#include <QTextDocument>
using namespace TextEditor;
+const char NOMANGLER_ID[] = "TextEditor::NoMangler";
+const char UCMANGLER_ID[] = "TextEditor::UppercaseMangler";
+const char LCMANGLER_ID[] = "TextEditor::LowercaseMangler";
+const char TCMANGLER_ID[] = "TextEditor::TitlecaseMangler";
+
+Q_DECLARE_METATYPE(QList<int>)
+
+// --------------------------------------------------------------------
+// Manglers:
+// --------------------------------------------------------------------
+
+class UppercaseMangler : public NameMangler
+{
+public:
+ Core::Id id() const { return UCMANGLER_ID; }
+ QString mangle(const QString &unmangled) const { return unmangled.toUpper(); }
+};
+
+class LowercaseMangler : public NameMangler
+{
+public:
+ Core::Id id() const { return LCMANGLER_ID; }
+ QString mangle(const QString &unmangled) const { return unmangled.toLower(); }
+};
+
+class TitlecaseMangler : public NameMangler
+{
+public:
+ Core::Id id() const { return TCMANGLER_ID; }
+ QString mangle(const QString &unmangled) const
+ {
+ QString result = unmangled;
+ if (!result.isEmpty())
+ result[0] = unmangled.at(0).toTitleCase();
+ return result;
+ }
+};
+
+// --------------------------------------------------------------------
+// Snippet:
+// --------------------------------------------------------------------
+
const QChar Snippet::kVariableDelimiter(QLatin1Char('$'));
Snippet::Snippet(const QString &groupId, const QString &id) :
@@ -142,3 +186,198 @@ QString Snippet::generateTip() const
return tip;
}
+
+Snippet::ParsedSnippet Snippet::parse(const QString &snippet)
+{
+ static UppercaseMangler ucMangler;
+ static LowercaseMangler lcMangler;
+ static TitlecaseMangler tcMangler;
+
+ Snippet::ParsedSnippet result;
+ result.success = true;
+
+ const int count = snippet.count();
+ bool success = true;
+ int start = -1;
+ NameMangler *mangler = 0;
+
+ result.text.reserve(count);
+
+ for (int i = 0; i < count; ++i) {
+ QChar current = snippet.at(i);
+ QChar next = (i + 1) < count ? snippet.at(i + 1) : QChar();
+
+ if (current == Snippet::kVariableDelimiter) {
+ if (start < 0) {
+ // start delimiter:
+ start = result.text.count();
+ } else {
+ int length = result.text.count() - start;
+ result.ranges << ParsedSnippet::Range(start, length, mangler);
+ mangler = 0;
+ start = -1;
+ }
+ continue;
+ }
+
+ if (mangler) {
+ success = false;
+ break;
+ }
+
+ if (current == QLatin1Char(':') && start >= 0) {
+ if (mangler != 0) {
+ success = false;
+ break;
+ }
+ if (next == QLatin1Char('l')) {
+ mangler = &lcMangler;
+ } else if (next == QLatin1Char('u')) {
+ mangler = &ucMangler;
+ } else if (next == QLatin1Char('c')) {
+ mangler = &tcMangler;
+ } else {
+ success = false;
+ break;
+ }
+ ++i;
+ continue;
+ }
+
+ if (current == QLatin1Char('\\')) {
+ if (next.isNull()) {
+ success = false;
+ break;
+ }
+ result.text.append(next);
+ ++i;
+ continue;
+ }
+
+ result.text.append(current);
+ }
+
+ if (start >= 0)
+ success = false;
+
+ result.success = success;
+
+ if (!success) {
+ result.ranges.clear();
+ result.text = snippet;
+ }
+
+ return result;
+}
+
+#ifdef WITH_TESTS
+# include <QTest>
+
+# include "../texteditorplugin.h"
+
+void Internal::TextEditorPlugin::testSnippetParsing_data()
+{
+ QTest::addColumn<QString>("input");
+ QTest::addColumn<QString>("text");
+ QTest::addColumn<bool>("success");
+ QTest::addColumn<QList<int> >("ranges_start");
+ QTest::addColumn<QList<int> >("ranges_length");
+ QTest::addColumn<QList<Core::Id> >("ranges_mangler");
+
+ QTest::newRow("no input")
+ << QString() << QString() << true
+ << (QList<int>()) << (QList<int>()) << (QList<Core::Id>());
+ QTest::newRow("empty input")
+ << QString::fromLatin1("") << QString::fromLatin1("") << true
+ << (QList<int>()) << (QList<int>()) << (QList<Core::Id>());
+
+ QTest::newRow("simple identifier")
+ << QString::fromLatin1("$tESt$") << QString::fromLatin1("tESt") << true
+ << (QList<int>() << 0) << (QList<int>() << 4)
+ << (QList<Core::Id>() << NOMANGLER_ID);
+ QTest::newRow("simple identifier with lc")
+ << QString::fromLatin1("$tESt:l$") << QString::fromLatin1("tESt") << true
+ << (QList<int>() << 0) << (QList<int>() << 4)
+ << (QList<Core::Id>() << LCMANGLER_ID);
+ QTest::newRow("simple identifier with uc")
+ << QString::fromLatin1("$tESt:u$") << QString::fromLatin1("tESt") << true
+ << (QList<int>() << 0) << (QList<int>() << 4)
+ << (QList<Core::Id>() << UCMANGLER_ID);
+ QTest::newRow("simple identifier with tc")
+ << QString::fromLatin1("$tESt:c$") << QString::fromLatin1("tESt") << true
+ << (QList<int>() << 0) << (QList<int>() << 4)
+ << (QList<Core::Id>() << TCMANGLER_ID);
+
+ QTest::newRow("escaped string")
+ << QString::fromLatin1("\\$test\\$") << QString::fromLatin1("$test$") << true
+ << (QList<int>()) << (QList<int>())
+ << (QList<Core::Id>());
+ QTest::newRow("escaped escape")
+ << QString::fromLatin1("\\\\$test\\\\$") << QString::fromLatin1("\\test\\") << true
+ << (QList<int>() << 1) << (QList<int>() << 5)
+ << (QList<Core::Id>() << NOMANGLER_ID);
+
+ QTest::newRow("Q_PROPERTY")
+ << QString::fromLatin1("Q_PROPERTY($type$ $name$ READ $name$ WRITE set$name:c$ NOTIFY $name$Changed)")
+ << QString::fromLatin1("Q_PROPERTY(type name READ name WRITE setname NOTIFY nameChanged)") << true
+ << (QList<int>() << 11 << 16 << 26 << 40 << 52)
+ << (QList<int>() << 4 << 4 << 4 << 4 << 4)
+ << (QList<Core::Id>() << NOMANGLER_ID << NOMANGLER_ID << NOMANGLER_ID << TCMANGLER_ID << NOMANGLER_ID);
+
+ QTest::newRow("broken escape")
+ << QString::fromLatin1("\\\\$test\\\\$\\") << QString::fromLatin1("\\\\$test\\\\$\\") << false
+ << (QList<int>()) << (QList<int>())
+ << (QList<Core::Id>());
+ QTest::newRow("open identifier")
+ << QString::fromLatin1("$test") << QString::fromLatin1("$test") << false
+ << (QList<int>()) << (QList<int>())
+ << (QList<Core::Id>());
+ QTest::newRow("wrong mangler")
+ << QString::fromLatin1("$test:X$") << QString::fromLatin1("$test:X$") << false
+ << (QList<int>()) << (QList<int>())
+ << (QList<Core::Id>());
+
+ QTest::newRow("multiline with :")
+ << QString::fromLatin1("class $name$\n"
+ "{\n"
+ "public:\n"
+ " $name$() {}\n"
+ "};")
+ << QString::fromLatin1("class name\n"
+ "{\n"
+ "public:\n"
+ " name() {}\n"
+ "};")
+ << true
+ << (QList<int>() << 6 << 25)
+ << (QList<int>() << 4 << 4)
+ << (QList<Core::Id>() << NOMANGLER_ID << NOMANGLER_ID);
+}
+
+void Internal::TextEditorPlugin::testSnippetParsing()
+{
+ QFETCH(QString, input);
+ QFETCH(QString, text);
+ QFETCH(bool, success);
+ QFETCH(QList<int>, ranges_start);
+ QFETCH(QList<int>, ranges_length);
+ QFETCH(QList<Core::Id>, ranges_mangler);
+ Q_ASSERT(ranges_start.count() == ranges_length.count()); // sanity check for the test data
+ Q_ASSERT(ranges_start.count() == ranges_mangler.count()); // sanity check for the test data
+
+ Snippet::ParsedSnippet result = Snippet::parse(input);
+
+ QCOMPARE(result.text, text);
+ QCOMPARE(result.success, success);
+ QCOMPARE(result.ranges.count(), ranges_start.count());
+ for (int i = 0; i < ranges_start.count(); ++i) {
+ QCOMPARE(result.ranges.at(i).start, ranges_start.at(i));
+ QCOMPARE(result.ranges.at(i).length, ranges_length.at(i));
+ Core::Id id = NOMANGLER_ID;
+ if (result.ranges.at(i).mangler)
+ id = result.ranges.at(i).mangler->id();
+ QCOMPARE(id, ranges_mangler.at(i));
+ }
+}
+#endif
+
diff --git a/src/plugins/texteditor/snippets/snippet.h b/src/plugins/texteditor/snippets/snippet.h
index 56adccc117..8163f31a47 100644
--- a/src/plugins/texteditor/snippets/snippet.h
+++ b/src/plugins/texteditor/snippets/snippet.h
@@ -33,10 +33,22 @@
#include <texteditor/texteditor_global.h>
#include <QChar>
+#include <QList>
#include <QString>
+namespace Core { class Id; }
+
namespace TextEditor {
+class TEXTEDITOR_EXPORT NameMangler
+{
+public:
+ virtual ~NameMangler() { }
+
+ virtual Core::Id id() const = 0;
+ virtual QString mangle(const QString &unmangled) const = 0;
+};
+
class TEXTEDITOR_EXPORT Snippet
{
public:
@@ -67,6 +79,21 @@ public:
static const QChar kVariableDelimiter;
+ class ParsedSnippet {
+ public:
+ QString text;
+ bool success;
+ struct Range {
+ Range(int s, int l, NameMangler *m) : start(s), length(l), mangler(m) { }
+ int start;
+ int length;
+ NameMangler *mangler;
+ };
+ QList<Range> ranges;
+ };
+
+ static ParsedSnippet parse(const QString &snippet);
+
private:
bool m_isRemoved;
bool m_isModified;
diff --git a/src/plugins/texteditor/snippets/snippeteditor.h b/src/plugins/texteditor/snippets/snippeteditor.h
index 043e81ba69..6e4e49f1ce 100644
--- a/src/plugins/texteditor/snippets/snippeteditor.h
+++ b/src/plugins/texteditor/snippets/snippeteditor.h
@@ -50,7 +50,6 @@ public:
bool duplicateSupported() const { return false; }
Core::IEditor *duplicate(QWidget * /* parent */ ) { return 0; }
- bool isTemporary() const { return false; }
Core::Id id() const;
};
diff --git a/src/plugins/texteditor/snippets/snippetssettingspage.cpp b/src/plugins/texteditor/snippets/snippetssettingspage.cpp
index d9d2c72312..c59d510f32 100644
--- a/src/plugins/texteditor/snippets/snippetssettingspage.cpp
+++ b/src/plugins/texteditor/snippets/snippetssettingspage.cpp
@@ -334,7 +334,7 @@ void SnippetsSettingsPagePrivate::configureUi(QWidget *w)
foreach (ISnippetProvider *provider, providers) {
m_ui.groupCombo->addItem(provider->displayName(), provider->groupId());
SnippetEditorWidget *snippetEditor = new SnippetEditorWidget(w);
- snippetEditor->setFontSettings(TextEditorSettings::instance()->fontSettings());
+ snippetEditor->setFontSettings(TextEditorSettings::fontSettings());
provider->decorateEditor(snippetEditor);
m_ui.snippetsEditorStack->insertWidget(m_ui.groupCombo->count() - 1, snippetEditor);
connect(snippetEditor, SIGNAL(snippetContentChanged()), this, SLOT(setSnippetContent()));
diff --git a/src/plugins/texteditor/syntaxhighlighter.cpp b/src/plugins/texteditor/syntaxhighlighter.cpp
index 90a3263318..1cf9359c37 100644
--- a/src/plugins/texteditor/syntaxhighlighter.cpp
+++ b/src/plugins/texteditor/syntaxhighlighter.cpp
@@ -30,6 +30,10 @@
#include "syntaxhighlighter.h"
#include "basetextdocument.h"
#include "basetextdocumentlayout.h"
+#include "texteditorsettings.h"
+#include "fontsettings.h"
+
+#include <utils/qtcassert.h>
#include <qtimer.h>
@@ -70,12 +74,15 @@ public:
}
void applyFormatChanges(int from, int charsRemoved, int charsAdded);
+ void updateFormatsForCategories(const TextEditor::FontSettings &fontSettings);
QVector<QTextCharFormat> formatChanges;
QTextBlock currentBlock;
bool rehighlightPending;
bool inReformatBlocks;
BaseTextDocumentLayout::FoldValidator foldValidator;
+ QVector<QTextCharFormat> formats;
+ QVector<TextEditor::TextStyle> formatCategories;
};
static bool adjustRange(QTextLayout::FormatRange &range, int from, int charsRemoved, int charsAdded) {
@@ -784,4 +791,31 @@ QList<QColor> SyntaxHighlighter::generateColors(int n, const QColor &background)
return result;
}
+void SyntaxHighlighter::setFontSettings(const TextEditor::FontSettings &fontSettings)
+{
+ Q_D(SyntaxHighlighter);
+ d->updateFormatsForCategories(fontSettings);
+}
+
+void SyntaxHighlighter::setTextFormatCategories(const QVector<TextEditor::TextStyle> &categories)
+{
+ Q_D(SyntaxHighlighter);
+ d->formatCategories = categories;
+ d->updateFormatsForCategories(TextEditorSettings::fontSettings());
+}
+
+QTextCharFormat SyntaxHighlighter::formatForCategory(int category) const
+{
+ Q_D(const SyntaxHighlighter);
+ QTC_ASSERT(d->formats.size() > category, return QTextCharFormat());
+
+ return d->formats.at(category);
+}
+
+void SyntaxHighlighterPrivate::updateFormatsForCategories(const TextEditor::FontSettings &fontSettings)
+{
+ formats = fontSettings.toTextCharFormats(formatCategories);
+}
+
+
#include "moc_syntaxhighlighter.cpp"
diff --git a/src/plugins/texteditor/syntaxhighlighter.h b/src/plugins/texteditor/syntaxhighlighter.h
index 8cee09a209..e66fa86f72 100644
--- a/src/plugins/texteditor/syntaxhighlighter.h
+++ b/src/plugins/texteditor/syntaxhighlighter.h
@@ -31,7 +31,7 @@
#define TEXTEDITOR_SYNTAXHIGHLIGHTER_H
#include "texteditor_global.h"
-
+#include <texteditor/texteditorconstants.h>
#include <QObject>
#include <QTextLayout>
@@ -48,6 +48,7 @@ QT_END_NAMESPACE
namespace TextEditor {
class BaseTextDocument;
+class FontSettings;
class SyntaxHighlighterPrivate;
class TEXTEDITOR_EXPORT SyntaxHighlighter : public QObject
@@ -68,11 +69,15 @@ public:
static QList<QColor> generateColors(int n, const QColor &background);
+ // Don't call in constructors of derived classes
+ virtual void setFontSettings(const TextEditor::FontSettings &fontSettings);
public Q_SLOTS:
void rehighlight();
void rehighlightBlock(const QTextBlock &block);
protected:
+ void setTextFormatCategories(const QVector<TextEditor::TextStyle> &categories);
+ QTextCharFormat formatForCategory(int categoryIndex) const;
virtual void highlightBlock(const QString &text) = 0;
void setFormat(int start, int count, const QTextCharFormat &format);
diff --git a/src/plugins/texteditor/texteditor.pro b/src/plugins/texteditor/texteditor.pro
index 34b4463488..2a449986b6 100644
--- a/src/plugins/texteditor/texteditor.pro
+++ b/src/plugins/texteditor/texteditor.pro
@@ -3,9 +3,6 @@ QT += xml network
CONFIG += exceptions
greaterThan(QT_MAJOR_VERSION, 4): QT += printsupport
include(../../qtcreatorplugin.pri)
-INCLUDEPATH += generichighlighter \
- snippets \
- codeassist
SOURCES += texteditorplugin.cpp \
textfilewizard.cpp \
plaintexteditor.cpp \
@@ -41,6 +38,7 @@ SOURCES += texteditorplugin.cpp \
indenter.cpp \
quickfix.cpp \
syntaxhighlighter.cpp \
+ highlighterutils.cpp \
generichighlighter/itemdata.cpp \
generichighlighter/specificrules.cpp \
generichighlighter/rule.cpp \
@@ -146,7 +144,9 @@ HEADERS += texteditorplugin.h \
normalindenter.h \
indenter.h \
quickfix.h \
+ ihighlighterfactory.h \
syntaxhighlighter.h \
+ highlighterutils.h \
generichighlighter/reuse.h \
generichighlighter/itemdata.h \
generichighlighter/specificrules.h \
diff --git a/src/plugins/texteditor/texteditor.qbs b/src/plugins/texteditor/texteditor.qbs
index a004705c04..cf5e4b68e6 100644
--- a/src/plugins/texteditor/texteditor.qbs
+++ b/src/plugins/texteditor/texteditor.qbs
@@ -10,12 +10,7 @@ QtcPlugin {
Depends { name: "Find" }
Depends { name: "Locator" }
- cpp.includePaths: base.concat([
- "generichighlighter",
- "snippets",
- "codeassist",
- "."
- ])
+ cpp.includePaths: base.concat([path]) // Needed for the highlighterengine autotest.
files: [
"autocompleter.cpp",
@@ -85,10 +80,13 @@ QtcPlugin {
"fontsettingspage.ui",
"helpitem.cpp",
"helpitem.h",
+ "highlighterutils.cpp",
+ "highlighterutils.h",
"icodestylepreferences.cpp",
"icodestylepreferences.h",
"icodestylepreferencesfactory.cpp",
"icodestylepreferencesfactory.h",
+ "ihighlighterfactory.h",
"indenter.cpp",
"indenter.h",
"ioutlinewidget.h",
diff --git a/src/plugins/texteditor/texteditoractionhandler.cpp b/src/plugins/texteditor/texteditoractionhandler.cpp
index 70dd1f0e9e..7c492a44b0 100644
--- a/src/plugins/texteditor/texteditoractionhandler.cpp
+++ b/src/plugins/texteditor/texteditoractionhandler.cpp
@@ -107,7 +107,7 @@ TextEditorActionHandler::TextEditorActionHandler(const char *context,
m_contextId(context),
m_initialized(false)
{
- connect(Core::ICore::editorManager(), SIGNAL(currentEditorChanged(Core::IEditor*)),
+ connect(Core::EditorManager::instance(), SIGNAL(currentEditorChanged(Core::IEditor*)),
this, SLOT(updateCurrentEditor(Core::IEditor*)));
}
@@ -135,361 +135,261 @@ void TextEditorActionHandler::initializeActions()
void TextEditorActionHandler::createActions()
{
- m_undoAction = registerNewAction(Core::Constants::UNDO, this, SLOT(undoAction()),
- true, tr("&Undo"));
- m_redoAction = registerNewAction(Core::Constants::REDO, this, SLOT(redoAction()),
- true, tr("&Redo"));
- m_copyAction = registerNewAction(Core::Constants::COPY, this, SLOT(copyAction()), true);
- m_cutAction = registerNewAction(Core::Constants::CUT, this, SLOT(cutAction()), true);
- m_pasteAction = registerNewAction(Core::Constants::PASTE, this, SLOT(pasteAction()), true);
+ using namespace Core::Constants;
+ using namespace TextEditor::Constants;
+
+ m_undoAction = registerAction(UNDO,
+ SLOT(undoAction()), true, tr("&Undo"));
+ m_redoAction = registerAction(REDO,
+ SLOT(redoAction()), true, tr("&Redo"));
+ m_copyAction = registerAction(COPY,
+ SLOT(copyAction()), true);
+ m_cutAction = registerAction(CUT,
+ SLOT(cutAction()), true);
+ m_pasteAction = registerAction(PASTE,
+ SLOT(pasteAction()), true);
+ m_selectAllAction = registerAction(SELECTALL,
+ SLOT(selectAllAction()), true);
+ m_gotoAction = registerAction(GOTO,
+ SLOT(gotoAction()));
+ m_printAction = registerAction(PRINT,
+ SLOT(printAction()));
+ m_cutLineAction = registerAction(CUT_LINE,
+ SLOT(cutLine()), true, tr("Cut &Line"),
+ QKeySequence(tr("Shift+Del")));
+ m_copyLineAction = registerAction(COPY_LINE,
+ SLOT(copyLine()), false, tr("Copy &Line"),
+ QKeySequence(tr("Ctrl+Ins")));
+ m_deleteLineAction = registerAction(DELETE_LINE,
+ SLOT(deleteLine()), true, tr("Delete &Line"));
+ m_deleteEndOfWordAction = registerAction(DELETE_END_OF_WORD,
+ SLOT(deleteEndOfWord()), true, tr("Delete Word from Cursor On"));
+ m_deleteEndOfWordCamelCaseAction = registerAction(DELETE_END_OF_WORD_CAMEL_CASE,
+ SLOT(deleteEndOfWordCamelCase()), true, tr("Delete Word Camel Case from Cursor On"));
+ m_deleteStartOfWordAction = registerAction(DELETE_START_OF_WORD,
+ SLOT(deleteStartOfWord()), true, tr("Delete Word up to Cursor"));
+ m_deleteStartOfWordCamelCaseAction = registerAction(DELETE_START_OF_WORD_CAMEL_CASE,
+ SLOT(deleteStartOfWordCamelCase()), true, tr("Delete Word Camel Case up to Cursor"));
+ m_gotoBlockStartWithSelectionAction = registerAction(GOTO_BLOCK_START_WITH_SELECTION,
+ SLOT(gotoBlockStartWithSelection()), true, tr("Go to Block Start with Selection"),
+ QKeySequence(tr("Ctrl+{")));
+ m_gotoBlockEndWithSelectionAction = registerAction(GOTO_BLOCK_END_WITH_SELECTION,
+ SLOT(gotoBlockEndWithSelection()), true, tr("Go to Block End with Selection"),
+ QKeySequence(tr("Ctrl+}")));
+ m_moveLineUpAction = registerAction(MOVE_LINE_UP,
+ SLOT(moveLineUp()), true, tr("Move Line Up"),
+ QKeySequence(tr("Ctrl+Shift+Up")));
+ m_moveLineDownAction = registerAction(MOVE_LINE_DOWN,
+ SLOT(moveLineDown()), true, tr("Move Line Down"),
+ QKeySequence(tr("Ctrl+Shift+Down")));
+ m_copyLineUpAction = registerAction(COPY_LINE_UP,
+ SLOT(copyLineUp()), true, tr("Copy Line Up"),
+ QKeySequence(tr("Ctrl+Alt+Up")));
+ m_copyLineDownAction = registerAction(COPY_LINE_DOWN,
+ SLOT(copyLineDown()), true, tr("Copy Line Down"),
+ QKeySequence(tr("Ctrl+Alt+Down")));
+ m_joinLinesAction = registerAction(JOIN_LINES,
+ SLOT(joinLines()), true, tr("Join Lines"),
+ QKeySequence(tr("Ctrl+J")));
+ m_insertLineAboveAction = registerAction(INSERT_LINE_ABOVE,
+ SLOT(insertLineAbove()), true, tr("Insert Line Above Current Line"),
+ QKeySequence(tr("Ctrl+Shift+Return")));
+ m_insertLineBelowAction = registerAction(INSERT_LINE_BELOW,
+ SLOT(insertLineBelow()), true, tr("Insert Line Below Current Line"),
+ QKeySequence(tr("Ctrl+Return")));
+ m_upperCaseSelectionAction = registerAction(UPPERCASE_SELECTION,
+ SLOT(uppercaseSelection()), true, tr("Uppercase Selection"),
+ QKeySequence(Core::UseMacShortcuts ? tr("Meta+Shift+U") : tr("Alt+Shift+U")));
+ m_lowerCaseSelectionAction = registerAction(LOWERCASE_SELECTION,
+ SLOT(lowercaseSelection()), true, tr("Lowercase Selection"),
+ QKeySequence(Core::UseMacShortcuts ? tr("Meta+U") : tr("Alt+U")));
+ m_switchUtf8bomAction = registerAction(SWITCH_UTF8BOM,
+ SLOT(switchUtf8bomAction()), true);
+ m_indentAction = registerAction(INDENT,
+ SLOT(indent()), true, tr("Indent"));
+ m_unindentAction = registerAction(UNINDENT,
+ SLOT(unindent()), true, tr("Unindent"));
+ m_followSymbolAction = registerAction(FOLLOW_SYMBOL_UNDER_CURSOR,
+ SLOT(openLinkUnderCursor()), true, tr("Follow Symbol Under Cursor"),
+ QKeySequence(Qt::Key_F2));
+ m_followSymbolInNextSplitAction = registerAction(FOLLOW_SYMBOL_UNDER_CURSOR_IN_NEXT_SPLIT,
+ SLOT(openLinkUnderCursorInNextSplit()), true, tr("Follow Symbol Under Cursor in Next Split"),
+ QKeySequence(Utils::HostOsInfo::isMacHost() ? tr("Meta+E, F2") : tr("Ctrl+E, F2")));
+ m_jumpToFileAction = registerAction(JUMP_TO_FILE_UNDER_CURSOR,
+ SLOT(openLinkUnderCursor()), true, tr("Jump To File Under Cursor"),
+ QKeySequence(Qt::Key_F2));
+ m_jumpToFileInNextSplitAction = registerAction(JUMP_TO_FILE_UNDER_CURSOR_IN_NEXT_SPLIT,
+ SLOT(openLinkUnderCursorInNextSplit()), true,
+ QKeySequence(Utils::HostOsInfo::isMacHost() ? tr("Meta+E, F2") : tr("Ctrl+E, F2")));
+
+ // register "Edit" Menu Actions
+ Core::ActionContainer *editMenu = Core::ActionManager::actionContainer(M_EDIT);
+ m_selectEncodingAction = registerAction(SELECT_ENCODING,
+ SLOT(selectEncoding()), false, tr("Select Encoding..."),
+ QKeySequence(), G_EDIT_OTHER, editMenu);
+ m_circularPasteAction = registerAction(CIRCULAR_PASTE,
+ SLOT(circularPasteAction()), false, tr("Paste from Clipboard History"),
+ QKeySequence(tr("Ctrl+Shift+V")), G_EDIT_COPYPASTE, editMenu);
+
+ // register "Edit -> Advanced" Menu Actions
+ Core::ActionContainer *advancedEditMenu = Core::ActionManager::actionContainer(M_EDIT_ADVANCED);
+ m_formatAction = registerAction(AUTO_INDENT_SELECTION,
+ SLOT(formatAction()), true, tr("Auto-&indent Selection"),
+ QKeySequence(tr("Ctrl+I")),
+ G_EDIT_FORMAT, advancedEditMenu);
+ m_rewrapParagraphAction = registerAction(REWRAP_PARAGRAPH,
+ SLOT(rewrapParagraphAction()), true, tr("&Rewrap Paragraph"),
+ QKeySequence(Core::UseMacShortcuts ? tr("Meta+E, R") : tr("Ctrl+E, R")),
+ G_EDIT_FORMAT, advancedEditMenu);
+ m_visualizeWhitespaceAction = registerAction(VISUALIZE_WHITESPACE,
+ SLOT(setVisualizeWhitespace(bool)), false, tr("&Visualize Whitespace"),
+ QKeySequence(Core::UseMacShortcuts ? tr("Meta+E, Meta+V") : tr("Ctrl+E, Ctrl+V")),
+ G_EDIT_FORMAT, advancedEditMenu);
+ m_visualizeWhitespaceAction->setCheckable(true);
+ m_cleanWhitespaceAction = registerAction(CLEAN_WHITESPACE,
+ SLOT(setTextWrapping(bool)), true, tr("Clean Whitespace"),
+ QKeySequence(),
+ G_EDIT_FORMAT, advancedEditMenu);
+ m_textWrappingAction = registerAction(TEXT_WRAPPING,
+ SLOT(setTextWrapping(bool)), false, tr("Enable Text &Wrapping"),
+ QKeySequence(Core::UseMacShortcuts ? tr("Meta+E, Meta+W") : tr("Ctrl+E, Ctrl+W")),
+ G_EDIT_FORMAT, advancedEditMenu);
+ m_textWrappingAction->setCheckable(true);
+ m_unCommentSelectionAction = registerAction(UN_COMMENT_SELECTION,
+ SLOT(unCommentSelection()), true, tr("Toggle Comment &Selection"),
+ QKeySequence(tr("Ctrl+/")),
+ G_EDIT_FORMAT, advancedEditMenu);
+ m_foldAction = registerAction(FOLD,
+ SLOT(fold()), true, tr("Fold"),
+ QKeySequence(tr("Ctrl+<")),
+ G_EDIT_COLLAPSING, advancedEditMenu);
+ m_unfoldAction = registerAction(UNFOLD,
+ SLOT(unfold()), true, tr("Unfold"),
+ QKeySequence(tr("Ctrl+>")),
+ G_EDIT_COLLAPSING, advancedEditMenu);
+ m_unfoldAllAction = registerAction(UNFOLD_ALL,
+ SLOT(unfoldAll()), true, tr("Toggle &Fold All"),
+ QKeySequence(),
+ G_EDIT_COLLAPSING, advancedEditMenu);
+ m_increaseFontSizeAction = registerAction(INCREASE_FONT_SIZE,
+ SLOT(increaseFontSize()), false, tr("Increase Font Size"),
+ QKeySequence(tr("Ctrl++")),
+ G_EDIT_FONT, advancedEditMenu);
+ m_decreaseFontSizeAction = registerAction(DECREASE_FONT_SIZE,
+ SLOT(decreaseFontSize()), false, tr("Decrease Font Size"),
+ QKeySequence(tr("Ctrl+-")),
+ G_EDIT_FONT, advancedEditMenu);
+ m_resetFontSizeAction = registerAction(RESET_FONT_SIZE,
+ SLOT(resetFontSize()), false, tr("Reset Font Size"),
+ QKeySequence(Core::UseMacShortcuts ? tr("Meta+0") : tr("Ctrl+0")),
+ G_EDIT_FONT, advancedEditMenu);
+ m_gotoBlockStartAction = registerAction(GOTO_BLOCK_START,
+ SLOT(gotoBlockStart()), true, tr("Go to Block Start"),
+ QKeySequence(tr("Ctrl+[")),
+ G_EDIT_BLOCKS, advancedEditMenu);
+ m_gotoBlockEndAction = registerAction(GOTO_BLOCK_END,
+ SLOT(gotoBlockEnd()), true, tr("Go to Block End"),
+ QKeySequence(tr("Ctrl+]")),
+ G_EDIT_BLOCKS, advancedEditMenu);
+ m_selectBlockUpAction = registerAction(SELECT_BLOCK_UP,
+ SLOT(selectBlockUp()), true, tr("Select Block Up"),
+ QKeySequence(tr("Ctrl+U")),
+ G_EDIT_BLOCKS, advancedEditMenu);
+ m_selectBlockDownAction = registerAction(SELECT_BLOCK_DOWN,
+ SLOT(selectBlockDown()), true, tr("Select Block Down"),
+ QKeySequence(),
+ G_EDIT_BLOCKS, advancedEditMenu);
+
+ // register GOTO Actions
+ registerAction(GOTO_LINE_START,
+ SLOT(gotoLineStart()), true, tr("Go to Line Start"));
+ registerAction(GOTO_LINE_END,
+ SLOT(gotoLineEnd()), true, tr("Go to Line End"));
+ registerAction(GOTO_NEXT_LINE,
+ SLOT(gotoNextLine()), true, tr("Go to Next Line"));
+ registerAction(GOTO_PREVIOUS_LINE,
+ SLOT(gotoPreviousLine()), true, tr("Go to Previous Line"));
+ registerAction(GOTO_PREVIOUS_CHARACTER,
+ SLOT(gotoPreviousCharacter()), true, tr("Go to Previous Character"));
+ registerAction(GOTO_NEXT_CHARACTER,
+ SLOT(gotoNextCharacter()), true, tr("Go to Next Character"));
+ registerAction(GOTO_PREVIOUS_WORD,
+ SLOT(gotoPreviousWord()), true, tr("Go to Previous Word"));
+ registerAction(GOTO_NEXT_WORD,
+ SLOT(gotoNextWord()), true, tr("Go to Next Word"));
+ registerAction(GOTO_PREVIOUS_WORD_CAMEL_CASE,
+ SLOT(gotoPreviousWordCamelCase()), false, tr("Go to Previous Word Camel Case"));
+ registerAction(GOTO_NEXT_WORD_CAMEL_CASE,
+ SLOT(gotoNextWordCamelCase()), false, tr("Go to Next Word Camel Case"));
+
+ // register GOTO actions with selection
+ registerAction(GOTO_LINE_START_WITH_SELECTION,
+ SLOT(gotoLineStartWithSelection()), true, tr("Go to Line Start with Selection"));
+ registerAction(GOTO_LINE_END_WITH_SELECTION,
+ SLOT(gotoLineEndWithSelection()), true, tr("Go to Line End with Selection"));
+ registerAction(GOTO_NEXT_LINE_WITH_SELECTION,
+ SLOT(gotoNextLineWithSelection()), true, tr("Go to Next Line with Selection"));
+ registerAction(GOTO_PREVIOUS_LINE_WITH_SELECTION,
+ SLOT(gotoPreviousLineWithSelection()), true, tr("Go to Previous Line with Selection"));
+ registerAction(GOTO_PREVIOUS_CHARACTER_WITH_SELECTION,
+ SLOT(gotoPreviousCharacterWithSelection()), true, tr("Go to Previous Character with Selection"));
+ registerAction(GOTO_NEXT_CHARACTER_WITH_SELECTION,
+ SLOT(gotoNextCharacterWithSelection()), true, tr("Go to Next Character with Selection"));
+ registerAction(GOTO_PREVIOUS_WORD_WITH_SELECTION,
+ SLOT(gotoPreviousWordWithSelection()), true, tr("Go to Previous Word with Selection"));
+ registerAction(GOTO_NEXT_WORD_WITH_SELECTION,
+ SLOT(gotoNextWordWithSelection()), true, tr("Go to Next Word with Selection"));
+ registerAction(GOTO_PREVIOUS_WORD_CAMEL_CASE_WITH_SELECTION,
+ SLOT(gotoPreviousWordCamelCaseWithSelection()), false, tr("Go to Previous Word Camel Case with Selection"));
+ registerAction(GOTO_NEXT_WORD_CAMEL_CASE_WITH_SELECTION,
+ SLOT(gotoNextWordCamelCaseWithSelection()), false, tr("Go to Next Word Camel Case with Selection"));
+
+ // Collect all modifying actions so we can check for them inside a readonly file
+ // and disable them
m_modifyingActions << m_pasteAction;
- m_selectAllAction = registerNewAction(Core::Constants::SELECTALL, this, SLOT(selectAllAction()), true);
- m_gotoAction = registerNewAction(Core::Constants::GOTO, this, SLOT(gotoAction()));
- m_printAction = registerNewAction(Core::Constants::PRINT, this, SLOT(printAction()));
-
- Core::ActionContainer *medit = Core::ActionManager::actionContainer(Core::Constants::M_EDIT);
- Core::ActionContainer *advancedMenu = Core::ActionManager::actionContainer(Core::Constants::M_EDIT_ADVANCED);
-
- m_selectEncodingAction = new QAction(tr("Select Encoding..."), this);
- Core::Command *command = Core::ActionManager::registerAction(m_selectEncodingAction, Constants::SELECT_ENCODING, m_contextId);
- connect(m_selectEncodingAction, SIGNAL(triggered()), this, SLOT(selectEncoding()));
- medit->addAction(command, Core::Constants::G_EDIT_OTHER);
-
-
- m_formatAction = new QAction(tr("Auto-&indent Selection"), this);
m_modifyingActions << m_formatAction;
- command = Core::ActionManager::registerAction(m_formatAction, TextEditor::Constants::AUTO_INDENT_SELECTION, m_contextId, true);
- command->setDefaultKeySequence(QKeySequence(tr("Ctrl+I")));
- advancedMenu->addAction(command, Core::Constants::G_EDIT_FORMAT);
- connect(m_formatAction, SIGNAL(triggered(bool)), this, SLOT(formatAction()));
-
- m_rewrapParagraphAction = new QAction(tr("&Rewrap Paragraph"), this);
m_modifyingActions << m_rewrapParagraphAction;
- command = Core::ActionManager::registerAction(m_rewrapParagraphAction, TextEditor::Constants::REWRAP_PARAGRAPH, m_contextId, true);
- command->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+E, R") : tr("Ctrl+E, R")));
- advancedMenu->addAction(command, Core::Constants::G_EDIT_FORMAT);
- connect(m_rewrapParagraphAction, SIGNAL(triggered(bool)), this, SLOT(rewrapParagraphAction()));
-
-
- m_visualizeWhitespaceAction = new QAction(tr("&Visualize Whitespace"), this);
- m_visualizeWhitespaceAction->setCheckable(true);
- command = Core::ActionManager::registerAction(m_visualizeWhitespaceAction,
- TextEditor::Constants::VISUALIZE_WHITESPACE, m_contextId);
- command->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+E, Meta+V") : tr("Ctrl+E, Ctrl+V")));
- advancedMenu->addAction(command, Core::Constants::G_EDIT_FORMAT);
- connect(m_visualizeWhitespaceAction, SIGNAL(triggered(bool)), this, SLOT(setVisualizeWhitespace(bool)));
-
- m_cleanWhitespaceAction = new QAction(tr("Clean Whitespace"), this);
m_modifyingActions << m_cleanWhitespaceAction;
- command = Core::ActionManager::registerAction(m_cleanWhitespaceAction,
- TextEditor::Constants::CLEAN_WHITESPACE, m_contextId, true);
-
- advancedMenu->addAction(command, Core::Constants::G_EDIT_FORMAT);
- connect(m_cleanWhitespaceAction, SIGNAL(triggered()), this, SLOT(cleanWhitespace()));
-
- m_textWrappingAction = new QAction(tr("Enable Text &Wrapping"), this);
- m_textWrappingAction->setCheckable(true);
- command = Core::ActionManager::registerAction(m_textWrappingAction, TextEditor::Constants::TEXT_WRAPPING, m_contextId);
- command->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+E, Meta+W") : tr("Ctrl+E, Ctrl+W")));
- advancedMenu->addAction(command, Core::Constants::G_EDIT_FORMAT);
- connect(m_textWrappingAction, SIGNAL(triggered(bool)), this, SLOT(setTextWrapping(bool)));
-
-
- m_unCommentSelectionAction = new QAction(tr("Toggle Comment &Selection"), this);
m_modifyingActions << m_unCommentSelectionAction;
- command = Core::ActionManager::registerAction(m_unCommentSelectionAction, Constants::UN_COMMENT_SELECTION, m_contextId, true);
- command->setDefaultKeySequence(QKeySequence(tr("Ctrl+/")));
- connect(m_unCommentSelectionAction, SIGNAL(triggered()), this, SLOT(unCommentSelection()));
- advancedMenu->addAction(command, Core::Constants::G_EDIT_FORMAT);
-
- m_cutLineAction = new QAction(tr("Cut &Line"), this);
m_modifyingActions << m_cutLineAction;
- command = Core::ActionManager::registerAction(m_cutLineAction, Constants::CUT_LINE, m_contextId, true);
- command->setDefaultKeySequence(QKeySequence(tr("Shift+Del")));
- connect(m_cutLineAction, SIGNAL(triggered()), this, SLOT(cutLine()));
-
- m_copyLineAction = new QAction(tr("Copy &Line"), this);
- command = Core::ActionManager::registerAction(m_copyLineAction, Constants::COPY_LINE, m_contextId);
- command->setDefaultKeySequence(QKeySequence(tr("Ctrl+Ins")));
- connect(m_copyLineAction, SIGNAL(triggered()), this, SLOT(copyLine()));
-
- m_deleteLineAction = new QAction(tr("Delete &Line"), this);
m_modifyingActions << m_deleteLineAction;
- command = Core::ActionManager::registerAction(m_deleteLineAction, Constants::DELETE_LINE, m_contextId, true);
- connect(m_deleteLineAction, SIGNAL(triggered()), this, SLOT(deleteLine()));
-
- m_deleteEndOfWordAction = new QAction(tr("Delete Word from Cursor On"), this);
m_modifyingActions << m_deleteEndOfWordAction;
- Core::ActionManager::registerAction(m_deleteEndOfWordAction, Constants::DELETE_END_OF_WORD, m_contextId, true);
- connect(m_deleteEndOfWordAction, SIGNAL(triggered()), this, SLOT(deleteEndOfWord()));
-
- m_deleteEndOfWordCamelCaseAction = new QAction(tr("Delete Word Camel Case from Cursor On"), this);
m_modifyingActions << m_deleteEndOfWordCamelCaseAction;
- Core::ActionManager::registerAction(m_deleteEndOfWordCamelCaseAction, Constants::DELETE_END_OF_WORD_CAMEL_CASE, m_contextId, true);
- connect(m_deleteEndOfWordCamelCaseAction, SIGNAL(triggered()), this, SLOT(deleteEndOfWordCamelCase()));
-
- m_deleteStartOfWordAction = new QAction(tr("Delete Word up to Cursor"), this);
m_modifyingActions << m_deleteStartOfWordAction;
- Core::ActionManager::registerAction(m_deleteStartOfWordAction, Constants::DELETE_START_OF_WORD, m_contextId, true);
- connect(m_deleteStartOfWordAction, SIGNAL(triggered()), this, SLOT(deleteStartOfWord()));
-
- m_deleteStartOfWordCamelCaseAction = new QAction(tr("Delete Word Camel Case up to Cursor"), this);
m_modifyingActions << m_deleteStartOfWordCamelCaseAction;
- Core::ActionManager::registerAction(m_deleteStartOfWordCamelCaseAction, Constants::DELETE_START_OF_WORD_CAMEL_CASE, m_contextId, true);
- connect(m_deleteStartOfWordCamelCaseAction, SIGNAL(triggered()), this, SLOT(deleteStartOfWordCamelCase()));
-
- m_foldAction = new QAction(tr("Fold"), this);
- command = Core::ActionManager::registerAction(m_foldAction, Constants::FOLD, m_contextId, true);
- command->setDefaultKeySequence(QKeySequence(tr("Ctrl+<")));
- connect(m_foldAction, SIGNAL(triggered()), this, SLOT(fold()));
- advancedMenu->addAction(command, Core::Constants::G_EDIT_COLLAPSING);
-
- m_unfoldAction = new QAction(tr("Unfold"), this);
- command = Core::ActionManager::registerAction(m_unfoldAction, Constants::UNFOLD, m_contextId, true);
- command->setDefaultKeySequence(QKeySequence(tr("Ctrl+>")));
- connect(m_unfoldAction, SIGNAL(triggered()), this, SLOT(unfold()));
- advancedMenu->addAction(command, Core::Constants::G_EDIT_COLLAPSING);
-
- m_unfoldAllAction = new QAction(tr("Toggle &Fold All"), this);
- command = Core::ActionManager::registerAction(m_unfoldAllAction, Constants::UNFOLD_ALL, m_contextId, true);
- connect(m_unfoldAllAction, SIGNAL(triggered()), this, SLOT(unfoldAll()));
- advancedMenu->addAction(command, Core::Constants::G_EDIT_COLLAPSING);
-
- m_increaseFontSizeAction = new QAction(tr("Increase Font Size"), this);
- command = Core::ActionManager::registerAction(m_increaseFontSizeAction, Constants::INCREASE_FONT_SIZE, m_contextId);
- command->setDefaultKeySequence(QKeySequence(tr("Ctrl++")));
- connect(m_increaseFontSizeAction, SIGNAL(triggered()), this, SLOT(increaseFontSize()));
- advancedMenu->addAction(command, Core::Constants::G_EDIT_FONT);
-
- m_decreaseFontSizeAction = new QAction(tr("Decrease Font Size"), this);
- command = Core::ActionManager::registerAction(m_decreaseFontSizeAction, Constants::DECREASE_FONT_SIZE, m_contextId);
- command->setDefaultKeySequence(QKeySequence(tr("Ctrl+-")));
- connect(m_decreaseFontSizeAction, SIGNAL(triggered()), this, SLOT(decreaseFontSize()));
- advancedMenu->addAction(command, Core::Constants::G_EDIT_FONT);
-
- m_resetFontSizeAction = new QAction(tr("Reset Font Size"), this);
- command = Core::ActionManager::registerAction(m_resetFontSizeAction, Constants::RESET_FONT_SIZE, m_contextId);
- command->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+0") : tr("Ctrl+0")));
- connect(m_resetFontSizeAction, SIGNAL(triggered()), this, SLOT(resetFontSize()));
- advancedMenu->addAction(command, Core::Constants::G_EDIT_FONT);
-
- m_gotoBlockStartAction = new QAction(tr("Go to Block Start"), this);
- command = Core::ActionManager::registerAction(m_gotoBlockStartAction, Constants::GOTO_BLOCK_START, m_contextId, true);
- command->setDefaultKeySequence(QKeySequence(tr("Ctrl+[")));
- connect(m_gotoBlockStartAction, SIGNAL(triggered()), this, SLOT(gotoBlockStart()));
- advancedMenu->addAction(command, Core::Constants::G_EDIT_BLOCKS);
-
- m_gotoBlockEndAction = new QAction(tr("Go to Block End"), this);
- command = Core::ActionManager::registerAction(m_gotoBlockEndAction, Constants::GOTO_BLOCK_END, m_contextId, true);
- command->setDefaultKeySequence(QKeySequence(tr("Ctrl+]")));
- connect(m_gotoBlockEndAction, SIGNAL(triggered()), this, SLOT(gotoBlockEnd()));
- advancedMenu->addAction(command, Core::Constants::G_EDIT_BLOCKS);
-
- m_gotoBlockStartWithSelectionAction = new QAction(tr("Go to Block Start with Selection"), this);
- command = Core::ActionManager::registerAction(m_gotoBlockStartWithSelectionAction, Constants::GOTO_BLOCK_START_WITH_SELECTION, m_contextId, true);
- command->setDefaultKeySequence(QKeySequence(tr("Ctrl+{")));
- connect(m_gotoBlockStartWithSelectionAction, SIGNAL(triggered()), this, SLOT(gotoBlockStartWithSelection()));
-
- m_gotoBlockEndWithSelectionAction = new QAction(tr("Go to Block End with Selection"), this);
- command = Core::ActionManager::registerAction(m_gotoBlockEndWithSelectionAction, Constants::GOTO_BLOCK_END_WITH_SELECTION, m_contextId, true);
- command->setDefaultKeySequence(QKeySequence(tr("Ctrl+}")));
- connect(m_gotoBlockEndWithSelectionAction, SIGNAL(triggered()), this, SLOT(gotoBlockEndWithSelection()));
-
- m_selectBlockUpAction = new QAction(tr("Select Block Up"), this);
- command = Core::ActionManager::registerAction(m_selectBlockUpAction, Constants::SELECT_BLOCK_UP, m_contextId, true);
- command->setDefaultKeySequence(QKeySequence(tr("Ctrl+U")));
- connect(m_selectBlockUpAction, SIGNAL(triggered()), this, SLOT(selectBlockUp()));
- advancedMenu->addAction(command, Core::Constants::G_EDIT_BLOCKS);
-
- m_selectBlockDownAction = new QAction(tr("Select Block Down"), this);
- command = Core::ActionManager::registerAction(m_selectBlockDownAction, Constants::SELECT_BLOCK_DOWN, m_contextId, true);
- connect(m_selectBlockDownAction, SIGNAL(triggered()), this, SLOT(selectBlockDown()));
- advancedMenu->addAction(command, Core::Constants::G_EDIT_BLOCKS);
-
- m_moveLineUpAction = new QAction(tr("Move Line Up"), this);
m_modifyingActions << m_moveLineUpAction;
- command = Core::ActionManager::registerAction(m_moveLineUpAction, Constants::MOVE_LINE_UP, m_contextId, true);
- command->setDefaultKeySequence(QKeySequence(tr("Ctrl+Shift+Up")));
- connect(m_moveLineUpAction, SIGNAL(triggered()), this, SLOT(moveLineUp()));
-
- m_moveLineDownAction = new QAction(tr("Move Line Down"), this);
m_modifyingActions << m_moveLineDownAction;
- command = Core::ActionManager::registerAction(m_moveLineDownAction, Constants::MOVE_LINE_DOWN, m_contextId, true);
- command->setDefaultKeySequence(QKeySequence(tr("Ctrl+Shift+Down")));
- connect(m_moveLineDownAction, SIGNAL(triggered()), this, SLOT(moveLineDown()));
-
- m_copyLineUpAction = new QAction(tr("Copy Line Up"), this);
m_modifyingActions << m_copyLineUpAction;
- command = Core::ActionManager::registerAction(m_copyLineUpAction, Constants::COPY_LINE_UP, m_contextId, true);
- command->setDefaultKeySequence(QKeySequence(tr("Ctrl+Alt+Up")));
- connect(m_copyLineUpAction, SIGNAL(triggered()), this, SLOT(copyLineUp()));
-
- m_copyLineDownAction = new QAction(tr("Copy Line Down"), this);
m_modifyingActions << m_copyLineDownAction;
- command = Core::ActionManager::registerAction(m_copyLineDownAction, Constants::COPY_LINE_DOWN, m_contextId, true);
- command->setDefaultKeySequence(QKeySequence(tr("Ctrl+Alt+Down")));
- connect(m_copyLineDownAction, SIGNAL(triggered()), this, SLOT(copyLineDown()));
-
- m_joinLinesAction = new QAction(tr("Join Lines"), this);
m_modifyingActions << m_joinLinesAction;
- command = Core::ActionManager::registerAction(m_joinLinesAction, Constants::JOIN_LINES, m_contextId, true);
- command->setDefaultKeySequence(QKeySequence(tr("Ctrl+J")));
- connect(m_joinLinesAction, SIGNAL(triggered()), this, SLOT(joinLines()));
-
- m_insertLineAboveAction = new QAction(tr("Insert Line Above Current Line"), this);
m_modifyingActions << m_insertLineAboveAction;
- command = Core::ActionManager::registerAction(m_insertLineAboveAction, Constants::INSERT_LINE_ABOVE, m_contextId, true);
- command->setDefaultKeySequence(QKeySequence(tr("Ctrl+Shift+Return")));
- connect(m_insertLineAboveAction, SIGNAL(triggered()), this, SLOT(insertLineAbove()));
-
- m_insertLineBelowAction = new QAction(tr("Insert Line Below Current Line"), this);
m_modifyingActions << m_insertLineBelowAction;
- command = Core::ActionManager::registerAction(m_insertLineBelowAction, Constants::INSERT_LINE_BELOW, m_contextId, true);
- command->setDefaultKeySequence(QKeySequence(tr("Ctrl+Return")));
- connect(m_insertLineBelowAction, SIGNAL(triggered()), this, SLOT(insertLineBelow()));
-
- m_upperCaseSelectionAction = new QAction(tr("Uppercase Selection"), this);
m_modifyingActions << m_upperCaseSelectionAction;
- command = Core::ActionManager::registerAction(m_upperCaseSelectionAction, Constants::UPPERCASE_SELECTION, m_contextId, true);
- command->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+Shift+U") : tr("Alt+Shift+U")));
- connect(m_upperCaseSelectionAction, SIGNAL(triggered()), this, SLOT(uppercaseSelection()));
-
- m_lowerCaseSelectionAction = new QAction(tr("Lowercase Selection"), this);
m_modifyingActions << m_lowerCaseSelectionAction;
- command = Core::ActionManager::registerAction(m_lowerCaseSelectionAction, Constants::LOWERCASE_SELECTION, m_contextId, true);
- command->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+U") : tr("Alt+U")));
- connect(m_lowerCaseSelectionAction, SIGNAL(triggered()), this, SLOT(lowercaseSelection()));
-
- m_circularPasteAction = new QAction(tr("Paste from Clipboard History"), this);
m_modifyingActions << m_circularPasteAction;
- command = Core::ActionManager::registerAction(m_circularPasteAction, Constants::CIRCULAR_PASTE, m_contextId, true);
- command->setDefaultKeySequence(QKeySequence(tr("Ctrl+Shift+V")));
- connect(m_circularPasteAction, SIGNAL(triggered()), this, SLOT(circularPasteAction()));
- medit->addAction(command, Core::Constants::G_EDIT_COPYPASTE);
-
- m_switchUtf8bomAction = new QAction(this);
m_modifyingActions << m_switchUtf8bomAction;
- command = Core::ActionManager::registerAction(m_switchUtf8bomAction, Constants::SWITCH_UTF8BOM, m_contextId, true);
- connect(m_switchUtf8bomAction, SIGNAL(triggered()), this, SLOT(switchUtf8bomAction()));
-
- m_indentAction = new QAction(tr("Indent"), this);
m_modifyingActions << m_indentAction;
- command = Core::ActionManager::registerAction(m_indentAction, Constants::INDENT, m_contextId, true);
- connect(m_indentAction, SIGNAL(triggered()), this, SLOT(indent()));
-
- m_unindentAction = new QAction(tr("Unindent"), this);
m_modifyingActions << m_unindentAction;
- command = Core::ActionManager::registerAction(m_unindentAction, Constants::UNINDENT, m_contextId, true);
- connect(m_unindentAction, SIGNAL(triggered()), this, SLOT(unindent()));
-
- m_followSymbolAction = new QAction(tr("Follow Symbol Under Cursor"), this);
- command = Core::ActionManager::registerAction(m_followSymbolAction, Constants::FOLLOW_SYMBOL_UNDER_CURSOR, m_contextId, true);
- command->setDefaultKeySequence(QKeySequence(Qt::Key_F2));
- connect(m_followSymbolAction, SIGNAL(triggered()), this, SLOT(openLinkUnderCursor()));
-
- m_followSymbolInNextSplitAction = new QAction(tr("Follow Symbol Under Cursor in Next Split"), this);
- command = Core::ActionManager::registerAction(m_followSymbolInNextSplitAction, Constants::FOLLOW_SYMBOL_UNDER_CURSOR_IN_NEXT_SPLIT, m_contextId, true);
- command->setDefaultKeySequence(QKeySequence(Utils::HostOsInfo::isMacHost()
- ? tr("Meta+E, F2")
- : tr("Ctrl+E, F2")));
- connect(m_followSymbolInNextSplitAction, SIGNAL(triggered()), this, SLOT(openLinkUnderCursorInNextSplit()));
-
- m_jumpToFileAction = new QAction(tr("Jump To File Under Cursor"), this);
- command = Core::ActionManager::registerAction(m_jumpToFileAction, Constants::JUMP_TO_FILE_UNDER_CURSOR, m_contextId, true);
- command->setDefaultKeySequence(QKeySequence(Qt::Key_F2));
- connect(m_jumpToFileAction, SIGNAL(triggered()), this, SLOT(openLinkUnderCursor()));
-
- m_jumpToFileInNextSplitAction = new QAction(tr("Jump to File Under Cursor in Next Split"), this);
- command = Core::ActionManager::registerAction(m_jumpToFileInNextSplitAction, Constants::JUMP_TO_FILE_UNDER_CURSOR_IN_NEXT_SPLIT, m_contextId, true);
- command->setDefaultKeySequence(QKeySequence(Utils::HostOsInfo::isMacHost()
- ? tr("Meta+E, F2")
- : tr("Ctrl+E, F2")));
- connect(m_jumpToFileInNextSplitAction, SIGNAL(triggered()), this, SLOT(openLinkUnderCursorInNextSplit()));
-
- QAction *a = 0;
- a = new QAction(tr("Go to Line Start"), this);
- command = Core::ActionManager::registerAction(a, Constants::GOTO_LINE_START, m_contextId, true);
- connect(a, SIGNAL(triggered()), this, SLOT(gotoLineStart()));
- a = new QAction(tr("Go to Line End"), this);
- command = Core::ActionManager::registerAction(a, Constants::GOTO_LINE_END, m_contextId, true);
- connect(a, SIGNAL(triggered()), this, SLOT(gotoLineEnd()));
- a = new QAction(tr("Go to Next Line"), this);
- command = Core::ActionManager::registerAction(a, Constants::GOTO_NEXT_LINE, m_contextId, true);
- connect(a, SIGNAL(triggered()), this, SLOT(gotoNextLine()));
- a = new QAction(tr("Go to Previous Line"), this);
- command = Core::ActionManager::registerAction(a, Constants::GOTO_PREVIOUS_LINE, m_contextId, true);
- connect(a, SIGNAL(triggered()), this, SLOT(gotoPreviousLine()));
- a = new QAction(tr("Go to Previous Character"), this);
- command = Core::ActionManager::registerAction(a, Constants::GOTO_PREVIOUS_CHARACTER, m_contextId, true);
- connect(a, SIGNAL(triggered()), this, SLOT(gotoPreviousCharacter()));
- a = new QAction(tr("Go to Next Character"), this);
- command = Core::ActionManager::registerAction(a, Constants::GOTO_NEXT_CHARACTER, m_contextId, true);
- connect(a, SIGNAL(triggered()), this, SLOT(gotoNextCharacter()));
- a = new QAction(tr("Go to Previous Word"), this);
- command = Core::ActionManager::registerAction(a, Constants::GOTO_PREVIOUS_WORD, m_contextId, true);
- connect(a, SIGNAL(triggered()), this, SLOT(gotoPreviousWord()));
- a = new QAction(tr("Go to Next Word"), this);
- command = Core::ActionManager::registerAction(a, Constants::GOTO_NEXT_WORD, m_contextId, true);
- connect(a, SIGNAL(triggered()), this, SLOT(gotoNextWord()));
- a = new QAction(tr("Go to Previous Word Camel Case"), this);
- command = Core::ActionManager::registerAction(a, Constants::GOTO_PREVIOUS_WORD_CAMEL_CASE, m_contextId);
- connect(a, SIGNAL(triggered()), this, SLOT(gotoPreviousWordCamelCase()));
- a = new QAction(tr("Go to Next Word Camel Case"), this);
- command = Core::ActionManager::registerAction(a, Constants::GOTO_NEXT_WORD_CAMEL_CASE, m_contextId);
- connect(a, SIGNAL(triggered()), this, SLOT(gotoNextWordCamelCase()));
-
- a = new QAction(tr("Go to Line Start with Selection"), this);
- command = Core::ActionManager::registerAction(a, Constants::GOTO_LINE_START_WITH_SELECTION, m_contextId, true);
- connect(a, SIGNAL(triggered()), this, SLOT(gotoLineStartWithSelection()));
- a = new QAction(tr("Go to Line End with Selection"), this);
- command = Core::ActionManager::registerAction(a, Constants::GOTO_LINE_END_WITH_SELECTION, m_contextId, true);
- connect(a, SIGNAL(triggered()), this, SLOT(gotoLineEndWithSelection()));
- a = new QAction(tr("Go to Next Line with Selection"), this);
- command = Core::ActionManager::registerAction(a, Constants::GOTO_NEXT_LINE_WITH_SELECTION, m_contextId, true);
- connect(a, SIGNAL(triggered()), this, SLOT(gotoNextLineWithSelection()));
- a = new QAction(tr("Go to Previous Line with Selection"), this);
- command = Core::ActionManager::registerAction(a, Constants::GOTO_PREVIOUS_LINE_WITH_SELECTION, m_contextId, true);
- connect(a, SIGNAL(triggered()), this, SLOT(gotoPreviousLineWithSelection()));
- a = new QAction(tr("Go to Previous Character with Selection"), this);
- command = Core::ActionManager::registerAction(a, Constants::GOTO_PREVIOUS_CHARACTER_WITH_SELECTION, m_contextId, true);
- connect(a, SIGNAL(triggered()), this, SLOT(gotoPreviousCharacterWithSelection()));
- a = new QAction(tr("Go to Next Character with Selection"), this);
- command = Core::ActionManager::registerAction(a, Constants::GOTO_NEXT_CHARACTER_WITH_SELECTION, m_contextId, true);
- connect(a, SIGNAL(triggered()), this, SLOT(gotoNextCharacterWithSelection()));
- a = new QAction(tr("Go to Previous Word with Selection"), this);
- command = Core::ActionManager::registerAction(a, Constants::GOTO_PREVIOUS_WORD_WITH_SELECTION, m_contextId, true);
- connect(a, SIGNAL(triggered()), this, SLOT(gotoPreviousWordWithSelection()));
- a = new QAction(tr("Go to Next Word with Selection"), this);
- command = Core::ActionManager::registerAction(a, Constants::GOTO_NEXT_WORD_WITH_SELECTION, m_contextId, true);
- connect(a, SIGNAL(triggered()), this, SLOT(gotoNextWordWithSelection()));
- a = new QAction(tr("Go to Previous Word Camel Case with Selection"), this);
- command = Core::ActionManager::registerAction(a, Constants::GOTO_PREVIOUS_WORD_CAMEL_CASE_WITH_SELECTION, m_contextId);
- connect(a, SIGNAL(triggered()), this, SLOT(gotoPreviousWordCamelCaseWithSelection()));
- a = new QAction(tr("Go to Next Word Camel Case with Selection"), this);
- command = Core::ActionManager::registerAction(a, Constants::GOTO_NEXT_WORD_CAMEL_CASE_WITH_SELECTION, m_contextId);
- connect(a, SIGNAL(triggered()), this, SLOT(gotoNextWordCamelCaseWithSelection()));
-
}
-QAction *TextEditorActionHandler::registerNewAction(const Core::Id &id, bool scriptable, const QString &title)
+QAction *TextEditorActionHandler::registerAction(const Core::Id &id,
+ const char *slot,
+ bool scriptable,
+ const QString &title,
+ const QKeySequence &keySequence,
+ const char *menueGroup,
+ Core::ActionContainer *container)
{
QAction *result = new QAction(title, this);
- Core::ActionManager::registerAction(result, id, m_contextId, scriptable);
- return result;
-}
+ Core::Command *command = Core::ActionManager::registerAction(result, id, m_contextId, scriptable);
+ if (!keySequence.isEmpty())
+ command->setKeySequence(keySequence);
-QAction *TextEditorActionHandler::registerNewAction(const Core::Id &id,
- QObject *receiver,
- const char *slot,
- bool scriptable,
- const QString &title)
-{
- QAction *rc = registerNewAction(id, scriptable, title);
- if (!rc)
- return 0;
+ if (container && menueGroup)
+ container->addAction(command, menueGroup);
- connect(rc, SIGNAL(triggered()), receiver, slot);
- return rc;
+ connect(result, SIGNAL(triggered(bool)), this, slot);
+ return result;
}
TextEditorActionHandler::UpdateMode TextEditorActionHandler::updateMode() const
@@ -549,13 +449,11 @@ void TextEditorActionHandler::updateCopyAction()
void TextEditorActionHandler::gotoAction()
{
- Locator::LocatorManager *locatorManager = Locator::LocatorManager::instance();
- QTC_ASSERT(locatorManager, return);
QString locatorString = TextEditorPlugin::instance()->lineNumberFilter()->shortcutString();
locatorString += QLatin1Char(' ');
const int selectionStart = locatorString.size();
locatorString += tr("<line>:<column>");
- locatorManager->show(locatorString, selectionStart, locatorString.size() - selectionStart);
+ Locator::LocatorManager::show(locatorString, selectionStart, locatorString.size() - selectionStart);
}
void TextEditorActionHandler::printAction()
diff --git a/src/plugins/texteditor/texteditoractionhandler.h b/src/plugins/texteditor/texteditoractionhandler.h
index dd6e1cfe54..2e768b4b4e 100644
--- a/src/plugins/texteditor/texteditoractionhandler.h
+++ b/src/plugins/texteditor/texteditoractionhandler.h
@@ -43,6 +43,7 @@ QT_FORWARD_DECLARE_CLASS(QAction)
namespace Core {
class ICore;
class IEditor;
+class ActionContainer;
}
namespace TextEditor {
@@ -79,9 +80,14 @@ public slots:
protected:
const QPointer<BaseTextEditorWidget> &currentEditor() const;
- QAction *registerNewAction(const Core::Id &id, bool scriptable = false, const QString &title = QString());
- QAction *registerNewAction(const Core::Id &id, QObject *receiver, const char *slot, bool scriptable = false,
- const QString &title = QString());
+
+ QAction *registerAction(const Core::Id &id,
+ const char *slot,
+ bool scriptable = false,
+ const QString &title = QString(),
+ const QKeySequence &keySequence = QKeySequence(),
+ const char *menueGroup = 0,
+ Core::ActionContainer *container = 0);
enum UpdateMode { ReadOnlyMode, WriteMode };
UpdateMode updateMode() const;
diff --git a/src/plugins/texteditor/texteditorconstants.h b/src/plugins/texteditor/texteditorconstants.h
index e65b158d79..99370a26a5 100644
--- a/src/plugins/texteditor/texteditorconstants.h
+++ b/src/plugins/texteditor/texteditorconstants.h
@@ -159,8 +159,6 @@ const char GOTO_PREVIOUS_WORD_CAMEL_CASE_WITH_SELECTION[] = "TextEditor.GotoPrev
const char GOTO_NEXT_WORD_CAMEL_CASE_WITH_SELECTION[] = "TextEditor.GotoNextWordCamelCaseWithSelection";
const char C_TEXTEDITOR_MIMETYPE_TEXT[] = "text/plain";
const char INFO_SYNTAX_DEFINITION[] = "TextEditor.InfoSyntaxDefinition";
-const char TASK_DOWNLOAD_DEFINITIONS[] = "TextEditor.Task.Download";
-const char TASK_REGISTER_DEFINITIONS[] = "TextEditor.Task.Register";
const char TASK_OPEN_FILE[] = "TextEditor.Task.OpenFile";
const char CIRCULAR_PASTE[] = "TextEditor.CircularPaste";
const char SWITCH_UTF8BOM[] = "TextEditor.SwitchUtf8bom";
diff --git a/src/plugins/texteditor/texteditoroverlay.cpp b/src/plugins/texteditor/texteditoroverlay.cpp
index a20376364a..102e917c9c 100644
--- a/src/plugins/texteditor/texteditoroverlay.cpp
+++ b/src/plugins/texteditor/texteditoroverlay.cpp
@@ -29,6 +29,7 @@
#include "texteditoroverlay.h"
#include "basetexteditor.h"
+#include "snippets/snippet.h"
#include <QDebug>
#include <QMap>
@@ -72,6 +73,8 @@ void TextEditorOverlay::clear()
return;
m_selections.clear();
m_firstSelectionOriginalBegin = -1;
+ m_equivalentSelections.clear();
+ m_manglers.clear();
update();
}
@@ -490,7 +493,7 @@ void TextEditorOverlay::mapEquivalentSelections()
QMap<QString, int> all;
for (int i = 0; i < m_selections.size(); ++i)
- all.insertMulti(selectionText(i), i);
+ all.insertMulti(selectionText(i).toLower(), i);
const QList<QString> &uniqueKeys = all.uniqueKeys();
foreach (const QString &key, uniqueKeys) {
@@ -529,6 +532,29 @@ void TextEditorOverlay::updateEquivalentSelections(const QTextCursor &cursor)
}
}
+void TextEditorOverlay::setNameMangler(const QList<NameMangler *> &manglers)
+{
+ m_manglers = manglers;
+}
+
+void TextEditorOverlay::mangle()
+{
+ for (int i = 0; i < m_manglers.count(); ++i) {
+ if (!m_manglers.at(i))
+ continue;
+
+ const QString current = selectionText(i);
+ const QString result = m_manglers.at(i)->mangle(current);
+ if (result != current) {
+ QTextCursor selectionCursor = assembleCursorForSelection(i);
+ selectionCursor.joinPreviousEditBlock();
+ selectionCursor.removeSelectedText();
+ selectionCursor.insertText(result);
+ selectionCursor.endEditBlock();
+ }
+ }
+}
+
bool TextEditorOverlay::hasFirstSelectionBeginMoved() const
{
if (m_firstSelectionOriginalBegin == -1 || m_selections.isEmpty())
diff --git a/src/plugins/texteditor/texteditoroverlay.h b/src/plugins/texteditor/texteditoroverlay.h
index 05a8163038..0b9391faf0 100644
--- a/src/plugins/texteditor/texteditoroverlay.h
+++ b/src/plugins/texteditor/texteditoroverlay.h
@@ -39,6 +39,7 @@
QT_FORWARD_DECLARE_CLASS(QWidget)
namespace TextEditor {
+class NameMangler;
class BaseTextEditorWidget;
namespace Internal {
@@ -100,6 +101,8 @@ public:
void mapEquivalentSelections();
void updateEquivalentSelections(const QTextCursor &cursor);
+ void setNameMangler(const QList<NameMangler *> &manglers);
+ void mangle();
bool hasFirstSelectionBeginMoved() const;
@@ -120,6 +123,7 @@ private:
QWidget *m_viewport;
QList<OverlaySelection> m_selections;
QVector<QList<int> > m_equivalentSelections;
+ QList<NameMangler *> m_manglers;
};
} // namespace Internal
diff --git a/src/plugins/texteditor/texteditorplugin.cpp b/src/plugins/texteditor/texteditorplugin.cpp
index 5bd897625e..a61e82f02a 100644
--- a/src/plugins/texteditor/texteditorplugin.cpp
+++ b/src/plugins/texteditor/texteditorplugin.cpp
@@ -38,10 +38,10 @@
#include "textfilewizard.h"
#include "plaintexteditorfactory.h"
#include "plaintexteditor.h"
-#include "manager.h"
#include "outlinefactory.h"
#include "snippets/plaintextsnippetprovider.h"
#include "basetextmarkregistry.h"
+#include <texteditor/generichighlighter/manager.h>
#include <coreplugin/icore.h>
#include <coreplugin/variablemanager.h>
@@ -102,25 +102,18 @@ class ScratchFileWizard : public Core::IWizard
Q_OBJECT
public:
- virtual WizardKind kind() const { return FileWizard; }
- virtual QIcon icon() const { return QIcon(); }
- virtual QString description() const
- { return TextEditorPlugin::tr("Creates a scratch buffer using a temporary file."); }
- virtual QString displayName() const
- { return TextEditorPlugin::tr("Scratch Buffer"); }
- virtual QString id() const
- { return QLatin1String("Z.ScratchFile"); }
- virtual QString category() const
- { return QLatin1String(wizardCategoryC); }
- virtual QString displayCategory() const
- { return wizardDisplayCategory(); }
- virtual QString descriptionImage() const
- { return QString(); }
- virtual Core::FeatureSet requiredFeatures() const
- { return Core::FeatureSet(); }
- virtual WizardFlags flags() const
- { return Core::IWizard::PlatformIndependent; }
- virtual void runWizard(const QString &, QWidget *, const QString &, const QVariantMap &)
+ ScratchFileWizard()
+ {
+ setWizardKind(FileWizard);
+ setDescription(TextEditorPlugin::tr("Creates a scratch buffer using a temporary file."));
+ setDisplayName(TextEditorPlugin::tr("Scratch Buffer"));
+ setId(QLatin1String("Z.ScratchFile"));
+ setCategory(QLatin1String(wizardCategoryC));
+ setDisplayCategory(wizardDisplayCategory());
+ setFlags(Core::IWizard::PlatformIndependent);
+ }
+
+ void runWizard(const QString &, QWidget *, const QString &, const QVariantMap &)
{ createFile(); }
public Q_SLOTS:
@@ -145,19 +138,19 @@ bool TextEditorPlugin::initialize(const QStringList &arguments, QString *errorMe
{
Q_UNUSED(arguments)
- if (!Core::ICore::mimeDatabase()->addMimeTypes(QLatin1String(":/texteditor/TextEditor.mimetypes.xml"), errorMessage))
+ if (!Core::MimeDatabase::addMimeTypes(QLatin1String(":/texteditor/TextEditor.mimetypes.xml"), errorMessage))
return false;
- Core::BaseFileWizardParameters wizardParameters(Core::IWizard::FileWizard);
- wizardParameters.setDescription(tr("Creates a text file. The default file extension is <tt>.txt</tt>. "
- "You can specify a different extension as part of the filename."));
- wizardParameters.setDisplayName(tr("Text File"));
- wizardParameters.setCategory(QLatin1String(wizardCategoryC));
- wizardParameters.setDisplayCategory(wizardDisplayCategory());
- wizardParameters.setFlags(Core::IWizard::PlatformIndependent);
TextFileWizard *wizard = new TextFileWizard(QLatin1String(Constants::C_TEXTEDITOR_MIMETYPE_TEXT),
- QLatin1String("text$"),
- wizardParameters);
+ QLatin1String("text$"));
+ wizard->setWizardKind(Core::IWizard::FileWizard);
+ wizard->setDescription(tr("Creates a text file. The default file extension is <tt>.txt</tt>. "
+ "You can specify a different extension as part of the filename."));
+ wizard->setDisplayName(tr("Text File"));
+ wizard->setCategory(QLatin1String(wizardCategoryC));
+ wizard->setDisplayCategory(wizardDisplayCategory());
+ wizard->setFlags(Core::IWizard::PlatformIndependent);
+
// Add text file wizard
addAutoReleasedObject(wizard);
ScratchFileWizard *scratchFile = new ScratchFileWizard;
@@ -258,7 +251,7 @@ void TextEditorPlugin::initializeEditor(PlainTextEditorWidget *editor)
// common actions
m_editorFactory->actionHandler()->setupActions(editor);
- TextEditorSettings::instance()->initializeEditor(editor);
+ TextEditorSettings::initializeEditor(editor);
}
void TextEditorPlugin::invokeCompletion()
diff --git a/src/plugins/texteditor/texteditorplugin.h b/src/plugins/texteditor/texteditorplugin.h
index 906a05bd0e..3d19745a64 100644
--- a/src/plugins/texteditor/texteditorplugin.h
+++ b/src/plugins/texteditor/texteditorplugin.h
@@ -77,6 +77,11 @@ private slots:
void updateVariable(const QByteArray &variable);
void updateCurrentSelection(const QString &text);
+#ifdef WITH_TESTS
+ void testSnippetParsing_data();
+ void testSnippetParsing();
+#endif
+
private:
static TextEditorPlugin *m_instance;
TextEditorSettings *m_settings;
diff --git a/src/plugins/texteditor/texteditorsettings.cpp b/src/plugins/texteditor/texteditorsettings.cpp
index cbdf323387..e795b3ab3b 100644
--- a/src/plugins/texteditor/texteditorsettings.cpp
+++ b/src/plugins/texteditor/texteditorsettings.cpp
@@ -40,10 +40,10 @@
#include "storagesettings.h"
#include "tabsettings.h"
#include "extraencodingsettings.h"
-#include "highlightersettingspage.h"
-#include "snippetssettingspage.h"
#include "icodestylepreferences.h"
#include "icodestylepreferencesfactory.h"
+#include <texteditor/generichighlighter/highlightersettingspage.h>
+#include <texteditor/snippets/snippetssettingspage.h>
#include <extensionsystem/pluginmanager.h>
#include <coreplugin/icore.h>
@@ -74,37 +74,21 @@ public:
QMap<QString, Core::Id> m_mimeTypeToLanguage;
CompletionSettings m_completionSettings;
-
- void fontZoomRequested(int pointSize);
- void zoomResetRequested();
};
-void TextEditorSettingsPrivate::fontZoomRequested(int zoom)
-{
- FontSettings &fs = const_cast<FontSettings&>(m_fontSettingsPage->fontSettings());
- fs.setFontZoom(qMax(10, fs.fontZoom() + zoom));
- m_fontSettingsPage->saveSettings();
-}
-
-void TextEditorSettingsPrivate::zoomResetRequested()
-{
- FontSettings &fs = const_cast<FontSettings&>(m_fontSettingsPage->fontSettings());
- fs.setFontZoom(100);
- m_fontSettingsPage->saveSettings();
-}
-
} // namespace Internal
} // namespace TextEditor
-TextEditorSettings *TextEditorSettings::m_instance = 0;
+static TextEditorSettingsPrivate *d = 0;
+static TextEditorSettings *m_instance = 0;
TextEditorSettings::TextEditorSettings(QObject *parent)
: QObject(parent)
- , m_d(new Internal::TextEditorSettingsPrivate)
{
QTC_ASSERT(!m_instance, return);
m_instance = this;
+ d = new Internal::TextEditorSettingsPrivate;
// Note: default background colors are coming from FormatDescription::background()
@@ -279,58 +263,58 @@ TextEditorSettings::TextEditorSettings(QObject *parent)
"in differences (in side-by-side diff editor)."),
Format(QColor(), QColor(175, 255, 175))));
- m_d->m_fontSettingsPage = new FontSettingsPage(formatDescr,
+ d->m_fontSettingsPage = new FontSettingsPage(formatDescr,
Constants::TEXT_EDITOR_FONT_SETTINGS,
this);
- ExtensionSystem::PluginManager::addObject(m_d->m_fontSettingsPage);
+ ExtensionSystem::PluginManager::addObject(d->m_fontSettingsPage);
// Add the GUI used to configure the tab, storage and interaction settings
TextEditor::BehaviorSettingsPageParameters behaviorSettingsPageParameters;
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);
+ d->m_behaviorSettingsPage = new BehaviorSettingsPage(behaviorSettingsPageParameters, this);
+ ExtensionSystem::PluginManager::addObject(d->m_behaviorSettingsPage);
TextEditor::DisplaySettingsPageParameters displaySettingsPageParameters;
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);
+ d->m_displaySettingsPage = new DisplaySettingsPage(displaySettingsPageParameters, this);
+ ExtensionSystem::PluginManager::addObject(d->m_displaySettingsPage);
- m_d->m_highlighterSettingsPage =
+ d->m_highlighterSettingsPage =
new HighlighterSettingsPage(Constants::TEXT_EDITOR_HIGHLIGHTER_SETTINGS, this);
- ExtensionSystem::PluginManager::addObject(m_d->m_highlighterSettingsPage);
+ ExtensionSystem::PluginManager::addObject(d->m_highlighterSettingsPage);
- m_d->m_snippetsSettingsPage =
+ d->m_snippetsSettingsPage =
new SnippetsSettingsPage(Constants::TEXT_EDITOR_SNIPPETS_SETTINGS, this);
- ExtensionSystem::PluginManager::addObject(m_d->m_snippetsSettingsPage);
+ ExtensionSystem::PluginManager::addObject(d->m_snippetsSettingsPage);
- connect(m_d->m_fontSettingsPage, SIGNAL(changed(TextEditor::FontSettings)),
+ connect(d->m_fontSettingsPage, SIGNAL(changed(TextEditor::FontSettings)),
this, SIGNAL(fontSettingsChanged(TextEditor::FontSettings)));
- connect(m_d->m_behaviorSettingsPage, SIGNAL(typingSettingsChanged(TextEditor::TypingSettings)),
+ connect(d->m_behaviorSettingsPage, SIGNAL(typingSettingsChanged(TextEditor::TypingSettings)),
this, SIGNAL(typingSettingsChanged(TextEditor::TypingSettings)));
- connect(m_d->m_behaviorSettingsPage, SIGNAL(storageSettingsChanged(TextEditor::StorageSettings)),
+ connect(d->m_behaviorSettingsPage, SIGNAL(storageSettingsChanged(TextEditor::StorageSettings)),
this, SIGNAL(storageSettingsChanged(TextEditor::StorageSettings)));
- connect(m_d->m_behaviorSettingsPage, SIGNAL(behaviorSettingsChanged(TextEditor::BehaviorSettings)),
+ connect(d->m_behaviorSettingsPage, SIGNAL(behaviorSettingsChanged(TextEditor::BehaviorSettings)),
this, SIGNAL(behaviorSettingsChanged(TextEditor::BehaviorSettings)));
- connect(m_d->m_displaySettingsPage, SIGNAL(displaySettingsChanged(TextEditor::DisplaySettings)),
+ connect(d->m_displaySettingsPage, SIGNAL(displaySettingsChanged(TextEditor::DisplaySettings)),
this, SIGNAL(displaySettingsChanged(TextEditor::DisplaySettings)));
// TODO: Move these settings to TextEditor category
- m_d->m_completionSettings.fromSettings(QLatin1String("CppTools/"), Core::ICore::settings());
+ d->m_completionSettings.fromSettings(QLatin1String("CppTools/"), Core::ICore::settings());
}
TextEditorSettings::~TextEditorSettings()
{
- ExtensionSystem::PluginManager::removeObject(m_d->m_fontSettingsPage);
- ExtensionSystem::PluginManager::removeObject(m_d->m_behaviorSettingsPage);
- ExtensionSystem::PluginManager::removeObject(m_d->m_displaySettingsPage);
- ExtensionSystem::PluginManager::removeObject(m_d->m_highlighterSettingsPage);
- ExtensionSystem::PluginManager::removeObject(m_d->m_snippetsSettingsPage);
+ ExtensionSystem::PluginManager::removeObject(d->m_fontSettingsPage);
+ ExtensionSystem::PluginManager::removeObject(d->m_behaviorSettingsPage);
+ ExtensionSystem::PluginManager::removeObject(d->m_displaySettingsPage);
+ ExtensionSystem::PluginManager::removeObject(d->m_highlighterSettingsPage);
+ ExtensionSystem::PluginManager::removeObject(d->m_snippetsSettingsPage);
- delete m_d;
+ delete d;
m_instance = 0;
}
@@ -347,25 +331,25 @@ TextEditorSettings *TextEditorSettings::instance()
void TextEditorSettings::initializeEditor(BaseTextEditorWidget *editor)
{
// Connect to settings change signals
- connect(this, SIGNAL(fontSettingsChanged(TextEditor::FontSettings)),
+ connect(m_instance, SIGNAL(fontSettingsChanged(TextEditor::FontSettings)),
editor, SLOT(setFontSettingsIfVisible(TextEditor::FontSettings)));
- connect(this, SIGNAL(typingSettingsChanged(TextEditor::TypingSettings)),
+ connect(m_instance, SIGNAL(typingSettingsChanged(TextEditor::TypingSettings)),
editor, SLOT(setTypingSettings(TextEditor::TypingSettings)));
- connect(this, SIGNAL(storageSettingsChanged(TextEditor::StorageSettings)),
+ connect(m_instance, SIGNAL(storageSettingsChanged(TextEditor::StorageSettings)),
editor, SLOT(setStorageSettings(TextEditor::StorageSettings)));
- connect(this, SIGNAL(behaviorSettingsChanged(TextEditor::BehaviorSettings)),
+ connect(m_instance, SIGNAL(behaviorSettingsChanged(TextEditor::BehaviorSettings)),
editor, SLOT(setBehaviorSettings(TextEditor::BehaviorSettings)));
- connect(this, SIGNAL(displaySettingsChanged(TextEditor::DisplaySettings)),
+ connect(m_instance, SIGNAL(displaySettingsChanged(TextEditor::DisplaySettings)),
editor, SLOT(setDisplaySettings(TextEditor::DisplaySettings)));
- connect(this, SIGNAL(completionSettingsChanged(TextEditor::CompletionSettings)),
+ connect(m_instance, SIGNAL(completionSettingsChanged(TextEditor::CompletionSettings)),
editor, SLOT(setCompletionSettings(TextEditor::CompletionSettings)));
- connect(this, SIGNAL(extraEncodingSettingsChanged(TextEditor::ExtraEncodingSettings)),
+ connect(m_instance, SIGNAL(extraEncodingSettingsChanged(TextEditor::ExtraEncodingSettings)),
editor, SLOT(setExtraEncodingSettings(TextEditor::ExtraEncodingSettings)));
connect(editor, SIGNAL(requestFontZoom(int)),
- this, SLOT(fontZoomRequested(int)));
+ m_instance, SLOT(fontZoomRequested(int)));
connect(editor, SIGNAL(requestZoomReset()),
- this, SLOT(zoomResetRequested()));
+ m_instance, SLOT(zoomResetRequested()));
// Apply current settings (tab settings depend on font settings)
editor->setFontSettings(fontSettings());
@@ -379,130 +363,142 @@ void TextEditorSettings::initializeEditor(BaseTextEditorWidget *editor)
editor->setCodeStyle(codeStyle(editor->languageSettingsId()));
}
-const FontSettings &TextEditorSettings::fontSettings() const
+const FontSettings &TextEditorSettings::fontSettings()
{
- return m_d->m_fontSettingsPage->fontSettings();
+ return d->m_fontSettingsPage->fontSettings();
}
-const TypingSettings &TextEditorSettings::typingSettings() const
+const TypingSettings &TextEditorSettings::typingSettings()
{
- return m_d->m_behaviorSettingsPage->typingSettings();
+ return d->m_behaviorSettingsPage->typingSettings();
}
-const StorageSettings &TextEditorSettings::storageSettings() const
+const StorageSettings &TextEditorSettings::storageSettings()
{
- return m_d->m_behaviorSettingsPage->storageSettings();
+ return d->m_behaviorSettingsPage->storageSettings();
}
-const BehaviorSettings &TextEditorSettings::behaviorSettings() const
+const BehaviorSettings &TextEditorSettings::behaviorSettings()
{
- return m_d->m_behaviorSettingsPage->behaviorSettings();
+ return d->m_behaviorSettingsPage->behaviorSettings();
}
-const DisplaySettings &TextEditorSettings::displaySettings() const
+const DisplaySettings &TextEditorSettings::displaySettings()
{
- return m_d->m_displaySettingsPage->displaySettings();
+ return d->m_displaySettingsPage->displaySettings();
}
-const CompletionSettings &TextEditorSettings::completionSettings() const
+const CompletionSettings &TextEditorSettings::completionSettings()
{
- return m_d->m_completionSettings;
+ return d->m_completionSettings;
}
-const HighlighterSettings &TextEditorSettings::highlighterSettings() const
+const HighlighterSettings &TextEditorSettings::highlighterSettings()
{
- return m_d->m_highlighterSettingsPage->highlighterSettings();
+ return d->m_highlighterSettingsPage->highlighterSettings();
}
-const ExtraEncodingSettings &TextEditorSettings::extraEncodingSettings() const
+const ExtraEncodingSettings &TextEditorSettings::extraEncodingSettings()
{
- return m_d->m_behaviorSettingsPage->extraEncodingSettings();
+ return d->m_behaviorSettingsPage->extraEncodingSettings();
}
void TextEditorSettings::setCompletionSettings(const TextEditor::CompletionSettings &settings)
{
- if (m_d->m_completionSettings == settings)
+ if (d->m_completionSettings == settings)
return;
- m_d->m_completionSettings = settings;
- m_d->m_completionSettings.toSettings(QLatin1String("CppTools/"), Core::ICore::settings());
+ d->m_completionSettings = settings;
+ d->m_completionSettings.toSettings(QLatin1String("CppTools/"), Core::ICore::settings());
- emit completionSettingsChanged(m_d->m_completionSettings);
+ emit m_instance->completionSettingsChanged(d->m_completionSettings);
}
void TextEditorSettings::registerCodeStyleFactory(ICodeStylePreferencesFactory *factory)
{
- m_d->m_languageToFactory.insert(factory->languageId(), factory);
+ d->m_languageToFactory.insert(factory->languageId(), factory);
}
void TextEditorSettings::unregisterCodeStyleFactory(Core::Id languageId)
{
- m_d->m_languageToFactory.remove(languageId);
+ d->m_languageToFactory.remove(languageId);
}
-QMap<Core::Id, ICodeStylePreferencesFactory *> TextEditorSettings::codeStyleFactories() const
+QMap<Core::Id, ICodeStylePreferencesFactory *> TextEditorSettings::codeStyleFactories()
{
- return m_d->m_languageToFactory;
+ return d->m_languageToFactory;
}
-ICodeStylePreferencesFactory *TextEditorSettings::codeStyleFactory(Core::Id languageId) const
+ICodeStylePreferencesFactory *TextEditorSettings::codeStyleFactory(Core::Id languageId)
{
- return m_d->m_languageToFactory.value(languageId);
+ return d->m_languageToFactory.value(languageId);
}
-ICodeStylePreferences *TextEditorSettings::codeStyle() const
+ICodeStylePreferences *TextEditorSettings::codeStyle()
{
- return m_d->m_behaviorSettingsPage->codeStyle();
+ return d->m_behaviorSettingsPage->codeStyle();
}
-ICodeStylePreferences *TextEditorSettings::codeStyle(Core::Id languageId) const
+ICodeStylePreferences *TextEditorSettings::codeStyle(Core::Id languageId)
{
- return m_d->m_languageToCodeStyle.value(languageId, codeStyle());
+ return d->m_languageToCodeStyle.value(languageId, codeStyle());
}
-QMap<Core::Id, ICodeStylePreferences *> TextEditorSettings::codeStyles() const
+QMap<Core::Id, ICodeStylePreferences *> TextEditorSettings::codeStyles()
{
- return m_d->m_languageToCodeStyle;
+ return d->m_languageToCodeStyle;
}
void TextEditorSettings::registerCodeStyle(Core::Id languageId, ICodeStylePreferences *prefs)
{
- m_d->m_languageToCodeStyle.insert(languageId, prefs);
+ d->m_languageToCodeStyle.insert(languageId, prefs);
}
void TextEditorSettings::unregisterCodeStyle(Core::Id languageId)
{
- m_d->m_languageToCodeStyle.remove(languageId);
+ d->m_languageToCodeStyle.remove(languageId);
}
-CodeStylePool *TextEditorSettings::codeStylePool() const
+CodeStylePool *TextEditorSettings::codeStylePool()
{
- return m_d->m_behaviorSettingsPage->codeStylePool();
+ return d->m_behaviorSettingsPage->codeStylePool();
}
-CodeStylePool *TextEditorSettings::codeStylePool(Core::Id languageId) const
+CodeStylePool *TextEditorSettings::codeStylePool(Core::Id languageId)
{
- return m_d->m_languageToCodeStylePool.value(languageId);
+ return d->m_languageToCodeStylePool.value(languageId);
}
void TextEditorSettings::registerCodeStylePool(Core::Id languageId, CodeStylePool *pool)
{
- m_d->m_languageToCodeStylePool.insert(languageId, pool);
+ d->m_languageToCodeStylePool.insert(languageId, pool);
}
void TextEditorSettings::unregisterCodeStylePool(Core::Id languageId)
{
- m_d->m_languageToCodeStylePool.remove(languageId);
+ d->m_languageToCodeStylePool.remove(languageId);
+}
+
+void TextEditorSettings::registerMimeTypeForLanguageId(const char *mimeType, Core::Id languageId)
+{
+ d->m_mimeTypeToLanguage.insert(QString::fromLatin1(mimeType), languageId);
}
-void TextEditorSettings::registerMimeTypeForLanguageId(const QString &mimeType, Core::Id languageId)
+Core::Id TextEditorSettings::languageId(const QString &mimeType)
{
- m_d->m_mimeTypeToLanguage.insert(mimeType, languageId);
+ return d->m_mimeTypeToLanguage.value(mimeType);
}
-Core::Id TextEditorSettings::languageId(const QString &mimeType) const
+void TextEditorSettings::fontZoomRequested(int zoom)
{
- return m_d->m_mimeTypeToLanguage.value(mimeType);
+ FontSettings &fs = const_cast<FontSettings&>(d->m_fontSettingsPage->fontSettings());
+ fs.setFontZoom(qMax(10, fs.fontZoom() + zoom));
+ d->m_fontSettingsPage->saveSettings();
}
-#include "moc_texteditorsettings.cpp"
+void TextEditorSettings::zoomResetRequested()
+{
+ FontSettings &fs = const_cast<FontSettings&>(d->m_fontSettingsPage->fontSettings());
+ fs.setFontZoom(100);
+ d->m_fontSettingsPage->saveSettings();
+}
diff --git a/src/plugins/texteditor/texteditorsettings.h b/src/plugins/texteditor/texteditorsettings.h
index 5bd56ced17..5a170247a7 100644
--- a/src/plugins/texteditor/texteditorsettings.h
+++ b/src/plugins/texteditor/texteditorsettings.h
@@ -57,10 +57,6 @@ class ICodeStylePreferences;
class ICodeStylePreferencesFactory;
class CodeStylePool;
-namespace Internal {
-class TextEditorSettingsPrivate;
-}
-
/**
* This class provides a central place for basic text editor settings. These
* settings include font settings, tab settings, storage settings, behavior
@@ -76,37 +72,37 @@ public:
static TextEditorSettings *instance();
- void initializeEditor(BaseTextEditorWidget *editor);
+ static void initializeEditor(BaseTextEditorWidget *editor);
- const FontSettings &fontSettings() const;
- const TypingSettings &typingSettings() const;
- const StorageSettings &storageSettings() const;
- const BehaviorSettings &behaviorSettings() const;
- const DisplaySettings &displaySettings() const;
- const CompletionSettings &completionSettings() const;
- const HighlighterSettings &highlighterSettings() const;
- const ExtraEncodingSettings &extraEncodingSettings() const;
+ static const FontSettings &fontSettings();
+ static const TypingSettings &typingSettings();
+ static const StorageSettings &storageSettings();
+ static const BehaviorSettings &behaviorSettings();
+ static const DisplaySettings &displaySettings();
+ static const CompletionSettings &completionSettings();
+ static const HighlighterSettings &highlighterSettings();
+ static const ExtraEncodingSettings &extraEncodingSettings();
- void setCompletionSettings(const TextEditor::CompletionSettings &);
+ static void setCompletionSettings(const TextEditor::CompletionSettings &);
- ICodeStylePreferencesFactory *codeStyleFactory(Core::Id languageId) const;
- QMap<Core::Id, ICodeStylePreferencesFactory *> codeStyleFactories() const;
- void registerCodeStyleFactory(ICodeStylePreferencesFactory *codeStyleFactory);
- void unregisterCodeStyleFactory(Core::Id languageId);
+ static ICodeStylePreferencesFactory *codeStyleFactory(Core::Id languageId);
+ static QMap<Core::Id, ICodeStylePreferencesFactory *> codeStyleFactories();
+ static void registerCodeStyleFactory(ICodeStylePreferencesFactory *codeStyleFactory);
+ static void unregisterCodeStyleFactory(Core::Id languageId);
- CodeStylePool *codeStylePool() const;
- CodeStylePool *codeStylePool(Core::Id languageId) const;
- void registerCodeStylePool(Core::Id languageId, CodeStylePool *pool);
- void unregisterCodeStylePool(Core::Id languageId);
+ static CodeStylePool *codeStylePool();
+ static CodeStylePool *codeStylePool(Core::Id languageId);
+ static void registerCodeStylePool(Core::Id languageId, CodeStylePool *pool);
+ static void unregisterCodeStylePool(Core::Id languageId);
- ICodeStylePreferences *codeStyle() const;
- ICodeStylePreferences *codeStyle(Core::Id languageId) const;
- QMap<Core::Id, ICodeStylePreferences *> codeStyles() const;
- void registerCodeStyle(Core::Id languageId, ICodeStylePreferences *prefs);
- void unregisterCodeStyle(Core::Id languageId);
+ static ICodeStylePreferences *codeStyle();
+ static ICodeStylePreferences *codeStyle(Core::Id languageId);
+ static QMap<Core::Id, ICodeStylePreferences *> codeStyles();
+ static void registerCodeStyle(Core::Id languageId, ICodeStylePreferences *prefs);
+ static void unregisterCodeStyle(Core::Id languageId);
- void registerMimeTypeForLanguageId(const QString &mimeType, Core::Id languageId);
- Core::Id languageId(const QString &mimeType) const;
+ static void registerMimeTypeForLanguageId(const char *mimeType, Core::Id languageId);
+ static Core::Id languageId(const QString &mimeType);
signals:
void fontSettingsChanged(const TextEditor::FontSettings &);
@@ -117,12 +113,9 @@ signals:
void completionSettingsChanged(const TextEditor::CompletionSettings &);
void extraEncodingSettingsChanged(const TextEditor::ExtraEncodingSettings &);
-private:
- Internal::TextEditorSettingsPrivate *m_d;
- Q_PRIVATE_SLOT(m_d, void fontZoomRequested(int pointSize))
- Q_PRIVATE_SLOT(m_d, void zoomResetRequested())
-
- static TextEditorSettings *m_instance;
+private slots:
+ void fontZoomRequested(int zoom);
+ void zoomResetRequested();
};
} // namespace TextEditor
diff --git a/src/plugins/texteditor/textfilewizard.cpp b/src/plugins/texteditor/textfilewizard.cpp
index a2dbca480f..737c761d25 100644
--- a/src/plugins/texteditor/textfilewizard.cpp
+++ b/src/plugins/texteditor/textfilewizard.cpp
@@ -28,15 +28,11 @@
****************************************************************************/
#include "textfilewizard.h"
-#include <QDebug>
-using namespace TextEditor;
+namespace TextEditor {
TextFileWizard::TextFileWizard(const QString &mimeType,
- const QString &suggestedFileName,
- const BaseFileWizardParameters &parameters,
- QObject *parent) :
- Core::StandardFileWizard(parameters, parent),
+ const QString &suggestedFileName) :
m_mimeType(mimeType),
m_suggestedFileName(suggestedFileName)
{
@@ -52,3 +48,5 @@ Core::GeneratedFiles
file.setAttributes(Core::GeneratedFile::OpenEditorAttribute);
return Core::GeneratedFiles() << file;
}
+
+} // namespace TextEditor
diff --git a/src/plugins/texteditor/textfilewizard.h b/src/plugins/texteditor/textfilewizard.h
index 849a1fce40..753061f0e4 100644
--- a/src/plugins/texteditor/textfilewizard.h
+++ b/src/plugins/texteditor/textfilewizard.h
@@ -41,11 +41,8 @@ class TEXTEDITOR_EXPORT TextFileWizard : public Core::StandardFileWizard
Q_OBJECT
public:
- typedef Core::BaseFileWizardParameters BaseFileWizardParameters;
TextFileWizard(const QString &mimeType,
- const QString &suggestedFileName,
- const BaseFileWizardParameters &parameters,
- QObject *parent = 0);
+ const QString &suggestedFileName);
protected:
virtual Core::GeneratedFiles
diff --git a/src/plugins/todo/Todo.pluginspec.in b/src/plugins/todo/Todo.pluginspec.in
index c53f32262b..a24d2062d3 100644
--- a/src/plugins/todo/Todo.pluginspec.in
+++ b/src/plugins/todo/Todo.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"Todo\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\" experimental=\"true\">
+<plugin name=\"Todo\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\" experimental=\"true\">
<vendor>Dmitry Savchenko</vendor>
<copyright>(C) 2013 Dmitry Savchenko, (C) 2013 Vasiliy Sorokin</copyright>
<license>
diff --git a/src/plugins/todo/todoitemsprovider.cpp b/src/plugins/todo/todoitemsprovider.cpp
index b2e985a633..d1fcf4dc41 100644
--- a/src/plugins/todo/todoitemsprovider.cpp
+++ b/src/plugins/todo/todoitemsprovider.cpp
@@ -41,6 +41,8 @@
#include <QTimer>
+using namespace ProjectExplorer;
+
namespace Todo {
namespace Internal {
@@ -78,11 +80,9 @@ void TodoItemsProvider::updateList()
// Show only items of the current file if any
if (m_settings.scanningScope == ScanningScopeCurrentFile) {
if (m_currentEditor)
- m_itemsList = m_itemsHash.value(m_currentEditor->document()->fileName());
- }
-
+ m_itemsList = m_itemsHash.value(m_currentEditor->document()->filePath());
// Show only items of the startup project if any
- else {
+ } else {
if (m_startupProject)
setItemsListWithinStartupProject();
}
@@ -152,20 +152,16 @@ void TodoItemsProvider::updateListTimeoutElapsed()
void TodoItemsProvider::setupStartupProjectBinding()
{
- ProjectExplorer::ProjectExplorerPlugin *projectExplorerPlugin = ProjectExplorer::ProjectExplorerPlugin::instance();
-
- m_startupProject = projectExplorerPlugin->startupProject();
- connect(projectExplorerPlugin->session(), SIGNAL(startupProjectChanged(ProjectExplorer::Project*)),
+ m_startupProject = SessionManager::startupProject();
+ connect(SessionManager::instance(), SIGNAL(startupProjectChanged(ProjectExplorer::Project*)),
SLOT(startupProjectChanged(ProjectExplorer::Project*)));
- connect(projectExplorerPlugin, SIGNAL(fileListChanged()), SLOT(projectsFilesChanged()));
+ connect(ProjectExplorerPlugin::instance(), SIGNAL(fileListChanged()), SLOT(projectsFilesChanged()));
}
void TodoItemsProvider::setupCurrentEditorBinding()
{
- Core::EditorManager *editorManager = Core::EditorManager::instance();
-
m_currentEditor = Core::EditorManager::currentEditor();
- connect(editorManager, SIGNAL(currentEditorChanged(Core::IEditor*)),
+ connect(Core::EditorManager::instance(), SIGNAL(currentEditorChanged(Core::IEditor*)),
SLOT(currentEditorChanged(Core::IEditor*)));
}
diff --git a/src/plugins/updateinfo/UpdateInfo.pluginspec.in b/src/plugins/updateinfo/UpdateInfo.pluginspec.in
index 1046fc92ff..862c62ceb3 100644
--- a/src/plugins/updateinfo/UpdateInfo.pluginspec.in
+++ b/src/plugins/updateinfo/UpdateInfo.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"UpdateInfo\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\" experimental=\"$$UPDATEINFO_EXPERIMENTAL_STR\">
+<plugin name=\"UpdateInfo\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\" experimental=\"$$UPDATEINFO_EXPERIMENTAL_STR\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/updateinfo/updateinfo.qbs b/src/plugins/updateinfo/updateinfo.qbs
index 0063247ce5..a2e15ec828 100644
--- a/src/plugins/updateinfo/updateinfo.qbs
+++ b/src/plugins/updateinfo/updateinfo.qbs
@@ -11,11 +11,6 @@ QtcPlugin {
property bool enable: false
pluginspecreplacements: ({"UPDATEINFO_EXPERIMENTAL_STR": (enable ? "false": "true")})
- cpp.includePaths: [
- "..",
- buildDirectory,
- ]
-
files: [
"updateinfobutton.cpp",
"updateinfobutton.h",
diff --git a/src/plugins/updateinfo/updateinfoplugin.cpp b/src/plugins/updateinfo/updateinfoplugin.cpp
index 78f5d06ff7..f0c7051543 100644
--- a/src/plugins/updateinfo/updateinfoplugin.cpp
+++ b/src/plugins/updateinfo/updateinfoplugin.cpp
@@ -57,6 +57,8 @@ namespace {
static const quint32 OneMinute = 60000;
}
+using namespace Core;
+
namespace UpdateInfo {
namespace Internal {
@@ -79,7 +81,7 @@ public:
QString updaterRunUiArgument;
int currentTimerId;
QFuture<QDomDocument> lastCheckUpdateInfoTask;
- QPointer<Core::FutureProgress> updateInfoProgress;
+ QPointer<FutureProgress> updateInfoProgress;
UpdateInfoButton *progressUpdateInfoButton;
QFutureWatcher<QDomDocument> *checkUpdateInfoWatcher;
};
@@ -120,7 +122,7 @@ bool UpdateInfoPlugin::initialize(const QStringList & /* arguments */, QString *
d->checkUpdateInfoWatcher = new QFutureWatcher<QDomDocument>(this);
connect(d->checkUpdateInfoWatcher, SIGNAL(finished()), this, SLOT(reactOnUpdaterOutput()));
- QSettings *settings = Core::ICore::settings();
+ QSettings *settings = ICore::settings();
d->updaterProgram = settings->value(QLatin1String("Updater/Application")).toString();
d->updaterCheckOnlyArgument = settings->value(QLatin1String("Updater/CheckOnlyArgument")).toString();
d->updaterRunUiArgument = settings->value(QLatin1String("Updater/RunUiArgument")).toString();
@@ -137,7 +139,7 @@ bool UpdateInfoPlugin::initialize(const QStringList & /* arguments */, QString *
return false;
}
- Core::ActionContainer* const helpActionContainer = Core::ActionManager::actionContainer(Core::Constants::M_HELP);
+ ActionContainer *const helpActionContainer = ActionManager::actionContainer(Core::Constants::M_HELP);
helpActionContainer->menu()->addAction(tr("Start Updater"), this, SLOT(startUpdaterUiApplication()));
//wait some time before we want to have the first check
@@ -181,10 +183,10 @@ void UpdateInfoPlugin::reactOnUpdaterOutput()
startCheckTimer(60 * OneMinute);
} else {
//added the current almost finished task to the progressmanager
- d->updateInfoProgress = Core::ICore::progressManager()->addTask(
- d->lastCheckUpdateInfoTask, tr("Update"), QLatin1String("Update.GetInfo"), Core::ProgressManager::KeepOnFinish);
+ d->updateInfoProgress = ProgressManager::addTask(
+ d->lastCheckUpdateInfoTask, tr("Update"), "Update.GetInfo", ProgressManager::KeepOnFinish);
- d->updateInfoProgress->setKeepOnFinish(Core::FutureProgress::KeepOnFinish);
+ d->updateInfoProgress->setKeepOnFinish(FutureProgress::KeepOnFinish);
d->progressUpdateInfoButton = new UpdateInfoButton();
//the old widget is deleted inside this function
@@ -201,7 +203,7 @@ void UpdateInfoPlugin::startUpdaterUiApplication()
{
QProcess::startDetached(d->updaterProgram, QStringList() << d->updaterRunUiArgument);
if (!d->updateInfoProgress.isNull())
- d->updateInfoProgress->setKeepOnFinish(Core::FutureProgress::HideOnFinish); //this is fading out the last updateinfo
+ d->updateInfoProgress->setKeepOnFinish(FutureProgress::HideOnFinish); //this is fading out the last updateinfo
startCheckTimer(OneMinute);
}
diff --git a/src/plugins/valgrind/Valgrind.pluginspec.in b/src/plugins/valgrind/Valgrind.pluginspec.in
index 5d2ebda21d..6fc15f3832 100644
--- a/src/plugins/valgrind/Valgrind.pluginspec.in
+++ b/src/plugins/valgrind/Valgrind.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"Valgrind\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"Valgrind\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/valgrind/callgrind/callgrind.pri b/src/plugins/valgrind/callgrind/callgrind.pri
index 292f3a962f..2c93b7ee9d 100644
--- a/src/plugins/valgrind/callgrind/callgrind.pri
+++ b/src/plugins/valgrind/callgrind/callgrind.pri
@@ -1,7 +1,5 @@
QT *= network
-INCLUDEPATH *= $$PWD
-
HEADERS += \
$$PWD/callgrindparser.h \
$$PWD/callgrindparsedata.h \
diff --git a/src/plugins/valgrind/callgrind/callgrindcontroller.cpp b/src/plugins/valgrind/callgrind/callgrindcontroller.cpp
index bcccd143ce..095de6eca4 100644
--- a/src/plugins/valgrind/callgrind/callgrindcontroller.cpp
+++ b/src/plugins/valgrind/callgrind/callgrindcontroller.cpp
@@ -99,10 +99,10 @@ void CallgrindController::run(Option option)
}
QTC_ASSERT(m_valgrindProc, return);
- if (RemoteValgrindProcess *remote = qobject_cast<RemoteValgrindProcess *>(m_valgrindProc))
- m_process = new RemoteValgrindProcess(remote->connection(), this);
- else
- m_process = new LocalValgrindProcess(this);
+ QSsh::SshConnection *connection = m_valgrindProc->connection();
+ m_process = new ValgrindProcess(m_valgrindProc->isLocal(),
+ connection ? connection->connectionParameters() : QSsh::SshConnectionParameters(),
+ connection, this);
connect(m_process, SIGNAL(finished(int,QProcess::ExitStatus)),
SLOT(processFinished(int,QProcess::ExitStatus)));
@@ -203,10 +203,10 @@ void CallgrindController::getLocalDataFile()
// first, set the to-be-parsed file to callgrind.out.PID
QString fileName = workingDir.isEmpty() ? baseFileName : (workingDir + QDir::separator() + baseFileName);
- if (RemoteValgrindProcess *remote = qobject_cast<RemoteValgrindProcess *>(m_valgrindProc)) {
+ if (!m_valgrindProc->isLocal()) {
///TODO: error handling
emit statusMessage(tr("Downloading remote profile data..."));
- m_ssh = remote->connection();
+ m_ssh = m_valgrindProc->connection();
// if there are files like callgrind.out.PID.NUM, set it to the most recent one of those
QString cmd = QString::fromLatin1("ls -t %1* | head -n 1").arg(fileName);
m_findRemoteFile = m_ssh->createRemoteProcess(cmd.toUtf8());
diff --git a/src/plugins/valgrind/callgrind/callgrinddatamodel.cpp b/src/plugins/valgrind/callgrind/callgrinddatamodel.cpp
index 10abb6cc0f..66f52d06da 100644
--- a/src/plugins/valgrind/callgrind/callgrinddatamodel.cpp
+++ b/src/plugins/valgrind/callgrind/callgrinddatamodel.cpp
@@ -44,18 +44,6 @@
namespace Valgrind {
namespace Callgrind {
-//BEGIN Helper
-
-namespace {
- // minimum amount of columns, i.e.:
- // function name
- // file name
- // object name
- // num called
- // Additional to this, 2 * ParseData::events().size will be shown (inclusive + self cost)
- const int MinColumnSize = 4;
-}
-
//BEGIN DataModel::Private
class DataModel::Private
diff --git a/src/plugins/valgrind/callgrindengine.cpp b/src/plugins/valgrind/callgrindengine.cpp
index b4bc9fedbb..c8e6099c25 100644
--- a/src/plugins/valgrind/callgrindengine.cpp
+++ b/src/plugins/valgrind/callgrindengine.cpp
@@ -42,9 +42,9 @@ using namespace Analyzer;
using namespace Valgrind;
using namespace Valgrind::Internal;
-CallgrindEngine::CallgrindEngine(IAnalyzerTool *tool, const AnalyzerStartParameters &sp,
+CallgrindRunControl::CallgrindRunControl(const AnalyzerStartParameters &sp,
ProjectExplorer::RunConfiguration *runConfiguration)
- : ValgrindEngine(tool, sp, runConfiguration)
+ : ValgrindRunControl(sp, runConfiguration)
, m_markAsPaused(false)
{
connect(&m_runner, SIGNAL(finished()), this, SLOT(slotFinished()));
@@ -55,28 +55,27 @@ CallgrindEngine::CallgrindEngine(IAnalyzerTool *tool, const AnalyzerStartParamet
m_progress->setProgressRange(0, 2);
}
-void CallgrindEngine::showStatusMessage(const QString &msg)
+void CallgrindRunControl::showStatusMessage(const QString &msg)
{
AnalyzerManager::showStatusMessage(msg);
}
-QStringList CallgrindEngine::toolArguments() const
+QStringList CallgrindRunControl::toolArguments() const
{
QStringList arguments;
- ValgrindBaseSettings *callgrindSettings = m_settings->subConfig<ValgrindBaseSettings>();
- QTC_ASSERT(callgrindSettings, return arguments);
+ QTC_ASSERT(m_settings, return arguments);
- if (callgrindSettings->enableCacheSim())
+ if (m_settings->enableCacheSim())
arguments << QLatin1String("--cache-sim=yes");
- if (callgrindSettings->enableBranchSim())
+ if (m_settings->enableBranchSim())
arguments << QLatin1String("--branch-sim=yes");
- if (callgrindSettings->collectBusEvents())
+ if (m_settings->collectBusEvents())
arguments << QLatin1String("--collect-bus=yes");
- if (callgrindSettings->collectSystime())
+ if (m_settings->collectSystime())
arguments << QLatin1String("--collect-systime=yes");
if (m_markAsPaused)
@@ -89,28 +88,28 @@ QStringList CallgrindEngine::toolArguments() const
return arguments;
}
-QString CallgrindEngine::progressTitle() const
+QString CallgrindRunControl::progressTitle() const
{
return tr("Profiling");
}
-Valgrind::ValgrindRunner * CallgrindEngine::runner()
+Valgrind::ValgrindRunner * CallgrindRunControl::runner()
{
return &m_runner;
}
-bool CallgrindEngine::start()
+bool CallgrindRunControl::startEngine()
{
- emit outputReceived(tr("Profiling %1\n").arg(executable()), Utils::NormalMessageFormat);
- return ValgrindEngine::start();
+ appendMessage(tr("Profiling %1\n").arg(executable()), Utils::NormalMessageFormat);
+ return ValgrindRunControl::startEngine();
}
-void CallgrindEngine::dump()
+void CallgrindRunControl::dump()
{
m_runner.controller()->run(Valgrind::Callgrind::CallgrindController::Dump);
}
-void CallgrindEngine::setPaused(bool paused)
+void CallgrindRunControl::setPaused(bool paused)
{
if (m_markAsPaused == paused)
return;
@@ -126,7 +125,7 @@ void CallgrindEngine::setPaused(bool paused)
}
}
-void CallgrindEngine::setToggleCollectFunction(const QString &toggleCollectFunction)
+void CallgrindRunControl::setToggleCollectFunction(const QString &toggleCollectFunction)
{
if (toggleCollectFunction.isEmpty())
return;
@@ -134,32 +133,32 @@ void CallgrindEngine::setToggleCollectFunction(const QString &toggleCollectFunct
m_argumentForToggleCollect = QLatin1String("--toggle-collect=") + toggleCollectFunction;
}
-void CallgrindEngine::reset()
+void CallgrindRunControl::reset()
{
m_runner.controller()->run(Valgrind::Callgrind::CallgrindController::ResetEventCounters);
}
-void CallgrindEngine::pause()
+void CallgrindRunControl::pause()
{
m_runner.controller()->run(Valgrind::Callgrind::CallgrindController::Pause);
}
-void CallgrindEngine::unpause()
+void CallgrindRunControl::unpause()
{
m_runner.controller()->run(Valgrind::Callgrind::CallgrindController::UnPause);
}
-Valgrind::Callgrind::ParseData *CallgrindEngine::takeParserData()
+Valgrind::Callgrind::ParseData *CallgrindRunControl::takeParserData()
{
return m_runner.parser()->takeData();
}
-void CallgrindEngine::slotFinished()
+void CallgrindRunControl::slotFinished()
{
emit parserDataReady(this);
}
-void CallgrindEngine::slotStarted()
+void CallgrindRunControl::slotStarted()
{
- m_progress->setProgressValue(1);;
+ m_progress->setProgressValue(1);
}
diff --git a/src/plugins/valgrind/callgrindengine.h b/src/plugins/valgrind/callgrindengine.h
index a02e4cc9f8..ef77d575c9 100644
--- a/src/plugins/valgrind/callgrindengine.h
+++ b/src/plugins/valgrind/callgrindengine.h
@@ -38,15 +38,15 @@
namespace Valgrind {
namespace Internal {
-class CallgrindEngine : public Valgrind::Internal::ValgrindEngine
+class CallgrindRunControl : public ValgrindRunControl
{
Q_OBJECT
public:
- CallgrindEngine(Analyzer::IAnalyzerTool *tool, const Analyzer::AnalyzerStartParameters &sp,
+ CallgrindRunControl(const Analyzer::AnalyzerStartParameters &sp,
ProjectExplorer::RunConfiguration *runConfiguration);
- bool start();
+ bool startEngine();
Valgrind::Callgrind::ParseData *takeParserData();
@@ -71,7 +71,7 @@ protected:
virtual Valgrind::ValgrindRunner *runner();
signals:
- void parserDataReady(CallgrindEngine *engine);
+ void parserDataReady(CallgrindRunControl *engine);
private slots:
void slotFinished();
diff --git a/src/plugins/valgrind/callgrindtool.cpp b/src/plugins/valgrind/callgrindtool.cpp
index efaaba214d..9621f9cb87 100644
--- a/src/plugins/valgrind/callgrindtool.cpp
+++ b/src/plugins/valgrind/callgrindtool.cpp
@@ -41,26 +41,21 @@
#include <valgrind/callgrind/callgrindfunction.h>
#include <valgrind/callgrind/callgrindfunctioncall.h>
#include <valgrind/callgrind/callgrindparsedata.h>
+#include <valgrind/callgrind/callgrindparser.h>
#include <valgrind/callgrind/callgrindproxymodel.h>
#include <valgrind/callgrind/callgrindstackbrowser.h>
#include <valgrind/valgrindplugin.h>
#include <valgrind/valgrindsettings.h>
#include <analyzerbase/analyzermanager.h>
-#include <analyzerbase/analyzersettings.h>
#include <analyzerbase/analyzerutils.h>
#include <analyzerbase/analyzerconstants.h>
-#include <coreplugin/actionmanager/actioncontainer.h>
-#include <coreplugin/actionmanager/actionmanager.h>
-#include <coreplugin/actionmanager/command.h>
#include <coreplugin/coreconstants.h>
-#include <coreplugin/icontext.h>
#include <coreplugin/icore.h>
#include <cplusplus/LookupContext.h>
#include <cplusplus/Overview.h>
-#include <cppeditor/cppeditorconstants.h>
#include <extensionsystem/iplugin.h>
#include <texteditor/itexteditor.h>
@@ -80,10 +75,12 @@
#include <QCheckBox>
#include <QComboBox>
#include <QDockWidget>
+#include <QFileDialog>
#include <QGraphicsItem>
#include <QHBoxLayout>
#include <QLineEdit>
#include <QMenu>
+#include <QMessageBox>
#include <QSortFilterProxyModel>
#include <QToolBar>
#include <QToolButton>
@@ -95,6 +92,7 @@
using namespace Analyzer;
using namespace Core;
using namespace Valgrind::Callgrind;
+using namespace ProjectExplorer;
namespace Valgrind {
namespace Internal {
@@ -117,7 +115,7 @@ public:
void doClear(bool clearParseData);
void updateEventCombo();
- IAnalyzerEngine *createEngine(const AnalyzerStartParameters &sp,
+ AnalyzerRunControl *createRunControl(const AnalyzerStartParameters &sp,
ProjectExplorer::RunConfiguration *runConfiguration = 0);
signals:
@@ -129,6 +127,7 @@ signals:
public slots:
void slotClear();
void slotRequestDump();
+ void loadExternalXmlLogFile();
void selectFunction(const Valgrind::Callgrind::Function *);
void setCostFormat(Valgrind::Internal::CostDelegate::CostFormat format);
@@ -162,8 +161,9 @@ public slots:
void visualisationFunctionSelected(const Valgrind::Callgrind::Function *function);
void showParserResults(const Valgrind::Callgrind::ParseData *data);
- void takeParserData(CallgrindEngine *engine);
- void engineStarting(const Analyzer::IAnalyzerEngine *);
+ void takeParserData(CallgrindRunControl *rc);
+ void takeParserData(ParseData *data);
+ void engineStarting(const Analyzer::AnalyzerRunControl *);
void engineFinished();
void editorOpened(Core::IEditor *);
@@ -203,13 +203,12 @@ public:
QVector<CallgrindTextMark *> m_textMarks;
+ QAction *m_loadExternalLogFile;
QAction *m_dumpAction;
QAction *m_resetAction;
QAction *m_pauseAction;
- QAction *m_showCostsOfFunctionAction;
QString m_toggleCollectFunction;
- ValgrindGlobalSettings *m_settings; // Not owned
};
@@ -236,8 +235,6 @@ CallgrindToolPrivate::CallgrindToolPrivate(CallgrindTool *parent)
, m_dumpAction(0)
, m_resetAction(0)
, m_pauseAction(0)
- , m_showCostsOfFunctionAction(0)
- , m_settings(0)
{
m_updateTimer->setInterval(200);
m_updateTimer->setSingleShot(true);
@@ -248,8 +245,6 @@ CallgrindToolPrivate::CallgrindToolPrivate(CallgrindTool *parent)
m_proxyModel->setFilterKeyColumn(DataModel::NameColumn);
m_proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
- m_settings = AnalyzerGlobalSettings::instance()->subConfig<ValgrindGlobalSettings>();
-
connect(m_stackBrowser, SIGNAL(currentChanged()), SLOT(stackBrowserChanged()));
connect(m_updateTimer, SIGNAL(timeout()), SLOT(updateFilterString()));
}
@@ -322,7 +317,7 @@ void CallgrindToolPrivate::selectFunction(const Function *func)
if (QFile::exists(func->file())) {
///TODO: custom position support?
int line = func->lineNumber();
- Core::EditorManager::openEditorAt(func->file(), qMax(line, 0));
+ EditorManager::openEditorAt(func->file(), qMax(line, 0));
}
}
@@ -396,8 +391,8 @@ void CallgrindToolPrivate::updateCostFormat()
m_calleesView->setCostFormat(format);
m_callersView->setCostFormat(format);
}
- if (m_settings)
- m_settings->setCostFormat(format);
+ if (ValgrindGlobalSettings *settings = ValgrindPlugin::globalSettings())
+ settings->setCostFormat(format);
}
void CallgrindToolPrivate::handleFilterProjectCosts()
@@ -408,8 +403,7 @@ void CallgrindToolPrivate::handleFilterProjectCosts()
if (m_filterProjectCosts->isChecked()) {
const QString projectDir = pro->projectDirectory();
m_proxyModel->setFilterBaseDir(projectDir);
- }
- else {
+ } else {
m_proxyModel->setFilterBaseDir(QString());
}
}
@@ -505,7 +499,7 @@ CallgrindTool::CallgrindTool(QObject *parent)
d = new CallgrindToolPrivate(this);
setObjectName(QLatin1String("CallgrindTool"));
- connect(Core::ICore::editorManager(), SIGNAL(editorOpened(Core::IEditor*)),
+ connect(EditorManager::instance(), SIGNAL(editorOpened(Core::IEditor*)),
d, SLOT(editorOpened(Core::IEditor*)));
}
@@ -514,25 +508,9 @@ CallgrindTool::~CallgrindTool()
delete d;
}
-Core::Id CallgrindTool::id() const
-{
- return Core::Id("Callgrind");
-}
-
-ProjectExplorer::RunMode CallgrindTool::runMode() const
-{
- return ProjectExplorer::CallgrindRunMode;
-}
-
-QString CallgrindTool::displayName() const
-{
- return tr("Valgrind Function Profiler");
-}
-
-QString CallgrindTool::description() const
+RunMode CallgrindTool::runMode() const
{
- return tr("Valgrind Profile uses the \"callgrind\" tool to "
- "record function calls when a program runs.");
+ return CallgrindRunMode;
}
IAnalyzerTool::ToolMode CallgrindTool::toolMode() const
@@ -540,82 +518,66 @@ IAnalyzerTool::ToolMode CallgrindTool::toolMode() const
return ReleaseMode;
}
-void CallgrindTool::extensionsInitialized()
+AnalyzerRunControl *CallgrindTool::createRunControl(const AnalyzerStartParameters &sp,
+ RunConfiguration *runConfiguration)
{
- Core::Context analyzerContext = Core::Context(Analyzer::Constants::C_ANALYZEMODE);
-
- // check if there is a CppEditor context menu, if true, add our own context menu actions
- if (Core::ActionContainer *editorContextMenu =
- Core::ActionManager::actionContainer(CppEditor::Constants::M_CONTEXT)) {
- QAction *action = 0;
- Core::Command *cmd = 0;
-
- editorContextMenu->addSeparator(analyzerContext);
-
- action = new QAction(tr("Profile Costs of this Function and its Callees"), this);
- 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);
- editorContextMenu->addAction(cmd);
- cmd->setAttribute(Core::Command::CA_Hide);
- cmd->setAttribute(Core::Command::CA_NonConfigurable);
- d->m_showCostsOfFunctionAction = action;
- }
+ return d->createRunControl(sp, runConfiguration);
}
-IAnalyzerEngine *CallgrindTool::createEngine(const AnalyzerStartParameters &sp,
- ProjectExplorer::RunConfiguration *runConfiguration)
+AnalyzerRunControl *CallgrindToolPrivate::createRunControl(const AnalyzerStartParameters &sp,
+ RunConfiguration *runConfiguration)
{
- return d->createEngine(sp, runConfiguration);
-}
+ CallgrindRunControl *rc = new CallgrindRunControl(sp, runConfiguration);
-IAnalyzerEngine *CallgrindToolPrivate::createEngine(const AnalyzerStartParameters &sp,
- ProjectExplorer::RunConfiguration *runConfiguration)
-{
- CallgrindEngine *engine = new CallgrindEngine(q, sp, runConfiguration);
-
- connect(engine, SIGNAL(parserDataReady(CallgrindEngine*)),
- SLOT(takeParserData(CallgrindEngine*)));
- connect(engine, SIGNAL(starting(const Analyzer::IAnalyzerEngine*)),
- SLOT(engineStarting(const Analyzer::IAnalyzerEngine*)));
- connect(engine, SIGNAL(finished()),
+ connect(rc, SIGNAL(parserDataReady(CallgrindRunControl*)),
+ SLOT(takeParserData(CallgrindRunControl*)));
+ connect(rc, SIGNAL(starting(const Analyzer::AnalyzerRunControl*)),
+ SLOT(engineStarting(const Analyzer::AnalyzerRunControl*)));
+ connect(rc, SIGNAL(finished()),
SLOT(engineFinished()));
- connect(this, SIGNAL(dumpRequested()), engine, SLOT(dump()));
- connect(this, SIGNAL(resetRequested()), engine, SLOT(reset()));
- connect(this, SIGNAL(pauseToggled(bool)), engine, SLOT(setPaused(bool)));
+ connect(this, SIGNAL(dumpRequested()), rc, SLOT(dump()));
+ connect(this, SIGNAL(resetRequested()), rc, SLOT(reset()));
+ connect(this, SIGNAL(pauseToggled(bool)), rc, SLOT(setPaused(bool)));
- // initialize engine
- engine->setPaused(m_pauseAction->isChecked());
+ // initialize run control
+ rc->setPaused(m_pauseAction->isChecked());
// we may want to toggle collect for one function only in this run
- engine->setToggleCollectFunction(m_toggleCollectFunction);
+ rc->setToggleCollectFunction(m_toggleCollectFunction);
m_toggleCollectFunction.clear();
- AnalyzerManager::showStatusMessage(AnalyzerManager::msgToolStarted(q->displayName()));
-
- QTC_ASSERT(m_visualisation, return engine);
+ QTC_ASSERT(m_visualisation, return rc);
// apply project settings
if (runConfiguration) {
- if (const AnalyzerRunConfigurationAspect *analyzerSettings = runConfiguration->extraAspect<AnalyzerRunConfigurationAspect>()) {
- if (const ValgrindProjectSettings *settings = analyzerSettings->subConfig<ValgrindProjectSettings>()) {
+ if (IRunConfigurationAspect *analyzerAspect = runConfiguration->extraAspect(ANALYZER_VALGRIND_SETTINGS)) {
+ if (const ValgrindBaseSettings *settings = qobject_cast<ValgrindBaseSettings *>(analyzerAspect->currentSettings())) {
m_visualisation->setMinimumInclusiveCostRatio(settings->visualisationMinimumInclusiveCostRatio() / 100.0);
m_proxyModel->setMinimumInclusiveCostRatio(settings->minimumInclusiveCostRatio() / 100.0);
m_dataModel->setVerboseToolTipsEnabled(settings->enableEventToolTips());
}
}
}
- return engine;
+ return rc;
}
void CallgrindTool::startTool(StartMode mode)
{
- ValgrindPlugin::startValgrindTool(this, mode);
+ ValgrindTool::startTool(mode);
d->setBusyCursor(true);
}
+void CallgrindTool::loadExternalXmlLogFile()
+{
+ d->loadExternalXmlLogFile();
+}
+
+void CallgrindTool::handleShowCostsOfFunction()
+{
+ d->handleShowCostsOfFunction();
+}
+
QWidget *CallgrindTool::createWidgets()
{
return d->createWidgets();
@@ -703,6 +665,14 @@ QWidget *CallgrindToolPrivate::createWidgets()
layout->setSpacing(0);
widget->setLayout(layout);
+ // load external XML log file
+ action = new QAction(this);
+ action->setIcon(QIcon(QLatin1String(Core::Constants::ICON_OPENFILE)));
+ action->setToolTip(tr("Load External XML Log File."));
+ connect(action, SIGNAL(triggered(bool)), this, SLOT(loadExternalXmlLogFile()));
+ layout->addWidget(createToolButton(action));
+ m_loadExternalLogFile = action;
+
// dump action
action = new QAction(this);
action->setDisabled(true);
@@ -800,13 +770,16 @@ QWidget *CallgrindToolPrivate::createWidgets()
layout->addWidget(button);
}
+
+ ValgrindGlobalSettings *settings = ValgrindPlugin::globalSettings();
+
// cycle detection
//action = new QAction(QLatin1String("Cycle Detection"), this); ///FIXME: icon
action = new QAction(QLatin1String("O"), this); ///FIXME: icon
action->setToolTip(tr("Enable cycle detection to properly handle recursive or circular function calls."));
action->setCheckable(true);
connect(action, SIGNAL(toggled(bool)), m_dataModel, SLOT(enableCycleDetection(bool)));
- connect(action, SIGNAL(toggled(bool)), m_settings, SLOT(setDetectCycles(bool)));
+ connect(action, SIGNAL(toggled(bool)), settings, SLOT(setDetectCycles(bool)));
layout->addWidget(createToolButton(action));
m_cycleDetection = action;
@@ -815,7 +788,7 @@ QWidget *CallgrindToolPrivate::createWidgets()
action->setToolTip(tr("This removes template parameter lists when displaying function names."));
action->setCheckable(true);
connect(action, SIGNAL(toggled(bool)), m_dataModel, SLOT(setShortenTemplates(bool)));
- connect(action, SIGNAL(toggled(bool)), m_settings, SLOT(setShortenTemplates(bool)));
+ connect(action, SIGNAL(toggled(bool)), settings, SLOT(setShortenTemplates(bool)));
layout->addWidget(createToolButton(action));
m_shortenTemplates = action;
@@ -836,8 +809,8 @@ QWidget *CallgrindToolPrivate::createWidgets()
layout->addWidget(filter);
m_searchFilter = filter;
- setCostFormat(m_settings->costFormat());
- enableCycleDetection(m_settings->detectCycles());
+ setCostFormat(settings->costFormat());
+ enableCycleDetection(settings->detectCycles());
layout->addWidget(new Utils::StyledSeparator);
layout->addStretch();
@@ -851,11 +824,12 @@ void CallgrindToolPrivate::clearTextMarks()
m_textMarks.clear();
}
-void CallgrindToolPrivate::engineStarting(const Analyzer::IAnalyzerEngine *)
+void CallgrindToolPrivate::engineStarting(const Analyzer::AnalyzerRunControl *)
{
// enable/disable actions
m_resetAction->setEnabled(true);
m_dumpAction->setEnabled(true);
+ m_loadExternalLogFile->setEnabled(false);
clearTextMarks();
slotClear();
}
@@ -865,6 +839,7 @@ void CallgrindToolPrivate::engineFinished()
// enable/disable actions
m_resetAction->setEnabled(false);
m_dumpAction->setEnabled(false);
+ m_loadExternalLogFile->setEnabled(true);
const ParseData *data = m_dataModel->parseData();
if (data)
@@ -892,7 +867,7 @@ void CallgrindToolPrivate::showParserResults(const ParseData *data)
AnalyzerManager::showStatusMessage(msg);
}
-void CallgrindToolPrivate::editorOpened(Core::IEditor *editor)
+void CallgrindToolPrivate::editorOpened(IEditor *editor)
{
TextEditor::ITextEditor *textEditor = qobject_cast<TextEditor::ITextEditor *>(editor);
if (!textEditor)
@@ -908,7 +883,7 @@ void CallgrindToolPrivate::requestContextMenu(TextEditor::ITextEditor *editor, i
// find callgrind text mark that corresponds to this editor's file and line number
const Function *func = 0;
foreach (CallgrindTextMark *textMark, m_textMarks) {
- if (textMark->fileName() == editor->document()->fileName() && textMark->lineNumber() == line) {
+ if (textMark->fileName() == editor->document()->filePath() && textMark->lineNumber() == line) {
func = textMark->function();
break;
}
@@ -948,8 +923,8 @@ void CallgrindToolPrivate::handleShowCostsOfFunction()
m_toggleCollectFunction = qualifiedFunctionName + QLatin1String("()");
- AnalyzerManager::selectTool(q, StartMode(StartLocal));
- AnalyzerManager::startTool(q, StartMode(StartLocal));
+ AnalyzerManager::selectTool(q, StartLocal);
+ AnalyzerManager::startTool();
}
void CallgrindToolPrivate::slotRequestDump()
@@ -959,9 +934,38 @@ void CallgrindToolPrivate::slotRequestDump()
dumpRequested();
}
-void CallgrindToolPrivate::takeParserData(CallgrindEngine *engine)
+void CallgrindToolPrivate::loadExternalXmlLogFile()
+{
+ const QString filePath = QFileDialog::getOpenFileName(
+ Core::ICore::mainWindow(),
+ tr("Open Callgrind XML Log File"),
+ QString(),
+ tr("XML Files (*.xml);;All Files (*)"));
+ if (filePath.isEmpty())
+ return;
+
+ QFile logFile(filePath);
+ if (!logFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
+ QMessageBox::critical(AnalyzerManager::mainWindow(), tr("Internal Error"),
+ tr("Failed to open file for reading: %1").arg(filePath));
+ return;
+ }
+
+ AnalyzerManager::showStatusMessage(tr("Parsing Profile Data..."));
+ QCoreApplication::processEvents();
+
+ Parser parser;
+ parser.parse(&logFile);
+ takeParserData(parser.takeData());
+}
+
+void CallgrindToolPrivate::takeParserData(CallgrindRunControl *rc)
+{
+ takeParserData(rc->takeParserData());
+}
+
+void CallgrindToolPrivate::takeParserData(ParseData *data)
{
- ParseData *data = engine->takeParserData();
showParserResults(data);
if (!data)
diff --git a/src/plugins/valgrind/callgrindtool.h b/src/plugins/valgrind/callgrindtool.h
index 9c8c2cefc2..68a6c54e86 100644
--- a/src/plugins/valgrind/callgrindtool.h
+++ b/src/plugins/valgrind/callgrindtool.h
@@ -45,19 +45,18 @@ public:
CallgrindTool(QObject *parent);
~CallgrindTool();
- Core::Id id() const;
ProjectExplorer::RunMode runMode() const;
- QString displayName() const;
- QString description() const;
ToolMode toolMode() const;
- void extensionsInitialized();
-
- Analyzer::IAnalyzerEngine *createEngine(const Analyzer::AnalyzerStartParameters &sp,
+ Analyzer::AnalyzerRunControl *createRunControl(const Analyzer::AnalyzerStartParameters &sp,
ProjectExplorer::RunConfiguration *runConfiguration = 0);
QWidget *createWidgets();
void startTool(Analyzer::StartMode mode);
+ void loadExternalXmlLogFile();
+
+public slots:
+ void handleShowCostsOfFunction();
private:
CallgrindToolPrivate *d;
diff --git a/src/plugins/valgrind/callgrindvisualisation.cpp b/src/plugins/valgrind/callgrindvisualisation.cpp
index 9da37c6711..b70eee9528 100644
--- a/src/plugins/valgrind/callgrindvisualisation.cpp
+++ b/src/plugins/valgrind/callgrindvisualisation.cpp
@@ -188,8 +188,7 @@ void FunctionGraphicsItem::paint(QPainter *painter,
gradient.setColorAt(0.5, color.lighter(200));
gradient.setColorAt(1, color.darker(100));
painter->setBrush(gradient);
- }
- else {
+ } else {
painter->setBrush(color);
}
@@ -256,9 +255,9 @@ void Visualisation::Private::handleMousePressEvent(QMouseEvent *event,
if (itemAtPos) {
const Function *func = q->functionForItem(itemAtPos);
- if (doubleClicked)
+ if (doubleClicked) {
q->functionActivated(func);
- else {
+ } else {
q->scene()->clearSelection();
itemAtPos->setSelected(true);
q->functionSelected(func);
diff --git a/src/plugins/valgrind/memcheck/memcheck.pri b/src/plugins/valgrind/memcheck/memcheck.pri
index facf1c4e11..b2d46a715f 100644
--- a/src/plugins/valgrind/memcheck/memcheck.pri
+++ b/src/plugins/valgrind/memcheck/memcheck.pri
@@ -1,7 +1,5 @@
QT *= network
-INCLUDEPATH *= $$PWD
-
HEADERS += \
$$PWD/memcheckrunner.h
diff --git a/src/plugins/valgrind/memcheck/memcheckrunner.cpp b/src/plugins/valgrind/memcheck/memcheckrunner.cpp
index 81a91005d0..cb3608f01c 100644
--- a/src/plugins/valgrind/memcheck/memcheckrunner.cpp
+++ b/src/plugins/valgrind/memcheck/memcheckrunner.cpp
@@ -94,58 +94,100 @@ void MemcheckRunner::setParser(XmlProtocol::ThreadedParser *parser)
bool MemcheckRunner::start()
{
+ QTC_ASSERT(d->parser, return false);
+
+ QString ip;
+ QHostAddress hostAddr;
+
if (startMode() == Analyzer::StartLocal) {
- QTC_ASSERT(d->parser, return false);
-
- bool check = d->xmlServer.listen(QHostAddress(QHostAddress::LocalHost));
- QTC_ASSERT(check, return false);
- d->xmlServer.setMaxPendingConnections(1);
- const quint16 xmlPortNumber = d->xmlServer.serverPort();
- connect(&d->xmlServer, SIGNAL(newConnection()), SLOT(xmlSocketConnected()));
-
- check = d->logServer.listen(QHostAddress(QHostAddress::LocalHost));
- QTC_ASSERT(check, return false);
- d->logServer.setMaxPendingConnections(1);
- const quint16 logPortNumber = d->logServer.serverPort();
- connect(&d->logServer, SIGNAL(newConnection()), SLOT(logSocketConnected()));
-
- QStringList memcheckArguments;
- 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);
+ ip = QLatin1String("127.0.0.1");
+ hostAddr = QHostAddress(QHostAddress::LocalHost);
}
-
if (startMode() == Analyzer::StartRemote) {
- QTC_ASSERT(d->parser, return false);
- QString ip = connectionParameters().host;
+ QList<QHostAddress> possibleHostAddresses;
+ //NOTE: ::allAddresses does not seem to work for usb interfaces...
+ foreach (const QNetworkInterface &iface, QNetworkInterface::allInterfaces()) {
+ foreach (const QNetworkAddressEntry &entry, iface.addressEntries()) {
+ const QHostAddress addr = entry.ip();
+ if (addr.toString() != QLatin1String("127.0.0.1")
+ && addr.toString() != QLatin1String("0:0:0:0:0:0:0:1"))
+ {
+ possibleHostAddresses << addr;
+ break;
+ }
+ }
+ }
+
+ if (possibleHostAddresses.isEmpty()) {
+ emit processErrorReceived(tr("No network interface found for remote analysis."),
+ QProcess::FailedToStart);
+ return false;
+ } else if (possibleHostAddresses.size() > 1) {
+ QDialog dlg;
+ dlg.setWindowTitle(tr("Select Network Interface"));
+ QVBoxLayout *layout = new QVBoxLayout;
+ QLabel *description = new QLabel;
+ description->setWordWrap(true);
+ description->setText(tr("More than one network interface was found on your machine. Please select which one you want to use for remote analysis."));
+ layout->addWidget(description);
+ QListWidget *list = new QListWidget;
+ foreach (const QHostAddress &address, possibleHostAddresses)
+ list->addItem(address.toString());
+
+ list->setSelectionMode(QAbstractItemView::SingleSelection);
+ list->setCurrentRow(0);
+ layout->addWidget(list);
+
+ QDialogButtonBox *buttons = new QDialogButtonBox;
+ buttons->addButton(QDialogButtonBox::Ok);
+ buttons->addButton(QDialogButtonBox::Cancel);
+ connect(buttons, SIGNAL(accepted()),
+ &dlg, SLOT(accept()));
+ connect(buttons, SIGNAL(rejected()),
+ &dlg, SLOT(reject()));
+ layout->addWidget(buttons);
+
+ dlg.setLayout(layout);
+ if (dlg.exec() != QDialog::Accepted) {
+ emit processErrorReceived(tr("No Network Interface was chosen for remote analysis"), QProcess::FailedToStart);
+ return false;
+ }
+
+ QTC_ASSERT(list->currentRow() >= 0, return false);
+ QTC_ASSERT(list->currentRow() < possibleHostAddresses.size(), return false);
+ hostAddr = possibleHostAddresses.at(list->currentRow());
+ } else {
+ hostAddr = possibleHostAddresses.first();
+ }
+
+ ip = hostAddr.toString();
QTC_ASSERT(!ip.isEmpty(), return false);
-
- QHostAddress hostAddr(ip);
- bool check = d->xmlServer.listen(hostAddr);
- QTC_ASSERT(check, return false);
- d->xmlServer.setMaxPendingConnections(1);
- const quint16 xmlPortNumber = d->xmlServer.serverPort();
- connect(&d->xmlServer, SIGNAL(newConnection()), SLOT(xmlSocketConnected()));
-
- check = d->logServer.listen(hostAddr);
- QTC_ASSERT(check, return false);
- d->logServer.setMaxPendingConnections(1);
- const quint16 logPortNumber = d->logServer.serverPort();
- connect(&d->logServer, SIGNAL(newConnection()), SLOT(logSocketConnected()));
-
- QStringList memcheckArguments;
- 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);
+ hostAddr = QHostAddress(ip);
}
+ bool check = d->xmlServer.listen(hostAddr);
+ if (!check) emit processErrorReceived( tr("XmlServer on %1: ").arg(ip) + d->xmlServer.errorString(), QProcess::FailedToStart );
+ QTC_ASSERT(check, return false);
+ d->xmlServer.setMaxPendingConnections(1);
+ const quint16 xmlPortNumber = d->xmlServer.serverPort();
+ connect(&d->xmlServer, SIGNAL(newConnection()), SLOT(xmlSocketConnected()));
+
+ check = d->logServer.listen(hostAddr);
+ if (!check) emit processErrorReceived( tr("LogServer on %1: ").arg(ip) + d->logServer.errorString(), QProcess::FailedToStart );
+ QTC_ASSERT(check, return false);
+ d->logServer.setMaxPendingConnections(1);
+ const quint16 logPortNumber = d->logServer.serverPort();
+ connect(&d->logServer, SIGNAL(newConnection()), SLOT(logSocketConnected()));
+
+ QStringList memcheckLogArguments;
+ memcheckLogArguments << 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(memcheckLogArguments + valgrindArguments());
+
return ValgrindRunner::start();
}
diff --git a/src/plugins/valgrind/memcheckengine.cpp b/src/plugins/valgrind/memcheckengine.cpp
index ec3bef87ee..232b01e72f 100644
--- a/src/plugins/valgrind/memcheckengine.cpp
+++ b/src/plugins/valgrind/memcheckengine.cpp
@@ -32,7 +32,8 @@
#include "valgrindsettings.h"
-#include <analyzerbase/analyzersettings.h>
+#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/taskhub.h>
#include <valgrind/xmlprotocol/error.h>
#include <valgrind/xmlprotocol/status.h>
@@ -40,14 +41,15 @@
#include <utils/qtcassert.h>
using namespace Analyzer;
+using namespace ProjectExplorer;
using namespace Valgrind::XmlProtocol;
namespace Valgrind {
namespace Internal {
-MemcheckEngine::MemcheckEngine(IAnalyzerTool *tool, const AnalyzerStartParameters &sp,
+MemcheckRunControl::MemcheckRunControl(const AnalyzerStartParameters &sp,
ProjectExplorer::RunConfiguration *runConfiguration)
- : ValgrindEngine(tool, sp, runConfiguration)
+ : ValgrindRunControl(sp, runConfiguration)
{
connect(&m_parser, SIGNAL(error(Valgrind::XmlProtocol::Error)),
SIGNAL(parserError(Valgrind::XmlProtocol::Error)));
@@ -61,61 +63,81 @@ MemcheckEngine::MemcheckEngine(IAnalyzerTool *tool, const AnalyzerStartParameter
m_progress->setProgressRange(0, XmlProtocol::Status::Finished + 1);
}
-QString MemcheckEngine::progressTitle() const
+QString MemcheckRunControl::progressTitle() const
{
return tr("Analyzing Memory");
}
-Valgrind::ValgrindRunner *MemcheckEngine::runner()
+Valgrind::ValgrindRunner *MemcheckRunControl::runner()
{
return &m_runner;
}
-bool MemcheckEngine::start()
+bool MemcheckRunControl::startEngine()
{
m_runner.setParser(&m_parser);
- emit outputReceived(tr("Analyzing memory of %1\n").arg(executable()),
+ // Clear about-to-be-outdated tasks.
+ TaskHub::clearTasks(Analyzer::Constants::ANALYZERTASK_ID);
+
+ appendMessage(tr("Analyzing memory of %1\n").arg(executable()),
Utils::NormalMessageFormat);
- return ValgrindEngine::start();
+ return ValgrindRunControl::startEngine();
}
-void MemcheckEngine::stop()
+void MemcheckRunControl::stopEngine()
{
disconnect(&m_parser, SIGNAL(internalError(QString)),
this, SIGNAL(internalParserError(QString)));
- ValgrindEngine::stop();
+ ValgrindRunControl::stopEngine();
}
-QStringList MemcheckEngine::toolArguments() const
+QStringList MemcheckRunControl::toolArguments() const
{
QStringList arguments;
arguments << QLatin1String("--gen-suppressions=all");
- ValgrindBaseSettings *memcheckSettings = m_settings->subConfig<ValgrindBaseSettings>();
- QTC_ASSERT(memcheckSettings, return arguments);
+ QTC_ASSERT(m_settings, return arguments);
- if (memcheckSettings->trackOrigins())
+ if (m_settings->trackOrigins())
arguments << QLatin1String("--track-origins=yes");
- foreach (const QString &file, memcheckSettings->suppressionFiles())
+ if (m_settings->showReachable())
+ arguments << QLatin1String("--show-reachable=yes");
+
+ QString leakCheckValue;
+ switch (m_settings->leakCheckOnFinish()) {
+ case ValgrindBaseSettings::LeakCheckOnFinishNo:
+ leakCheckValue = QLatin1String("no");
+ break;
+ case ValgrindBaseSettings::LeakCheckOnFinishYes:
+ leakCheckValue = QLatin1String("full");
+ break;
+ case ValgrindBaseSettings::LeakCheckOnFinishSummaryOnly:
+ default:
+ leakCheckValue = QLatin1String("summary");
+ break;
+ }
+ arguments << QLatin1String("--leak-check=") + leakCheckValue;
+
+ foreach (const QString &file, m_settings->suppressionFiles())
arguments << QString::fromLatin1("--suppressions=%1").arg(file);
- arguments << QString::fromLatin1("--num-callers=%1").arg(memcheckSettings->numCallers());
+ arguments << QString::fromLatin1("--num-callers=%1").arg(m_settings->numCallers());
return arguments;
}
-QStringList MemcheckEngine::suppressionFiles() const
+QStringList MemcheckRunControl::suppressionFiles() const
{
- return m_settings->subConfig<ValgrindBaseSettings>()->suppressionFiles();
+ return m_settings->suppressionFiles();
}
-void MemcheckEngine::status(const Status &status)
+void MemcheckRunControl::status(const Status &status)
{
m_progress->setProgressValue(status.state() + 1);
}
-void MemcheckEngine::receiveLogMessage(const QByteArray &b)
+void MemcheckRunControl::receiveLogMessage(const QByteArray &b)
{
QString error = QString::fromLocal8Bit(b);
// workaround https://bugs.kde.org/show_bug.cgi?id=255888
@@ -126,7 +148,7 @@ void MemcheckEngine::receiveLogMessage(const QByteArray &b)
if (error.isEmpty())
return;
- stop();
+ stopEngine();
QString file;
int line = -1;
@@ -138,7 +160,9 @@ void MemcheckEngine::receiveLogMessage(const QByteArray &b)
line = suppressionError.cap(2).toInt();
}
- emit taskToBeAdded(ProjectExplorer::Task::Error, error, file, line);
+ TaskHub::addTask(Task(Task::Error, error, Utils::FileName::fromUserInput(file), line,
+ Analyzer::Constants::ANALYZERTASK_ID));
+ TaskHub::requestPopup();
}
} // namespace Internal
diff --git a/src/plugins/valgrind/memcheckengine.h b/src/plugins/valgrind/memcheckengine.h
index ebf371639f..f8a2387b02 100644
--- a/src/plugins/valgrind/memcheckengine.h
+++ b/src/plugins/valgrind/memcheckengine.h
@@ -39,16 +39,16 @@
namespace Valgrind {
namespace Internal {
-class MemcheckEngine : public ValgrindEngine
+class MemcheckRunControl : public ValgrindRunControl
{
Q_OBJECT
public:
- MemcheckEngine(Analyzer::IAnalyzerTool *tool, const Analyzer::AnalyzerStartParameters &sp,
+ MemcheckRunControl(const Analyzer::AnalyzerStartParameters &sp,
ProjectExplorer::RunConfiguration *runConfiguration);
- bool start();
- void stop();
+ bool startEngine();
+ void stopEngine();
QStringList suppressionFiles() const;
diff --git a/src/plugins/valgrind/memcheckerrorview.cpp b/src/plugins/valgrind/memcheckerrorview.cpp
index 3f421b280a..83b9a7b421 100644
--- a/src/plugins/valgrind/memcheckerrorview.cpp
+++ b/src/plugins/valgrind/memcheckerrorview.cpp
@@ -44,6 +44,7 @@
#include <coreplugin/editormanager/editormanager.h>
#include <projectexplorer/project.h>
#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/session.h>
#include <utils/qtcassert.h>
#include <QDir>
@@ -185,8 +186,7 @@ static QString makeFrameName(const Frame &frame, const QString &relativeTo,
static QString relativeToPath()
{
// The project for which we insert the snippet.
- const ProjectExplorer::Project *project =
- ProjectExplorer::ProjectExplorerPlugin::instance()->startupProject();
+ const ProjectExplorer::Project *project = ProjectExplorer::SessionManager::startupProject();
QString relativeTo(project ? project->projectDirectory() : QDir::homePath());
if (!relativeTo.endsWith(QDir::separator()))
@@ -494,7 +494,7 @@ QString MemcheckErrorView::defaultSuppressionFile() const
// slot, can (for now) be invoked either when the settings were modified *or* when the active
// settings object has changed.
-void MemcheckErrorView::settingsChanged(Analyzer::AnalyzerSettings *settings)
+void MemcheckErrorView::settingsChanged(ValgrindBaseSettings *settings)
{
QTC_ASSERT(settings, return);
m_settings = settings;
diff --git a/src/plugins/valgrind/memcheckerrorview.h b/src/plugins/valgrind/memcheckerrorview.h
index 3ba9c84def..24ce06c859 100644
--- a/src/plugins/valgrind/memcheckerrorview.h
+++ b/src/plugins/valgrind/memcheckerrorview.h
@@ -33,11 +33,11 @@
#include <QListView>
-namespace Analyzer { class AnalyzerSettings; }
-
namespace Valgrind {
namespace Internal {
+class ValgrindBaseSettings;
+
class MemcheckErrorView : public QListView
{
Q_OBJECT
@@ -52,10 +52,10 @@ public:
void setDefaultSuppressionFile(const QString &suppFile);
QString defaultSuppressionFile() const;
- Analyzer::AnalyzerSettings *settings() const { return m_settings; }
+ ValgrindBaseSettings *settings() const { return m_settings; }
public slots:
- void settingsChanged(Analyzer::AnalyzerSettings *settings);
+ void settingsChanged(ValgrindBaseSettings *settings);
void goNext();
void goBack();
@@ -75,7 +75,7 @@ private:
QAction *m_copyAction;
QAction *m_suppressAction;
QString m_defaultSuppFile;
- Analyzer::AnalyzerSettings *m_settings;
+ ValgrindBaseSettings *m_settings;
};
} // namespace Internal
diff --git a/src/plugins/valgrind/memchecktool.cpp b/src/plugins/valgrind/memchecktool.cpp
index 39e91f9bc0..8641aa53d0 100644
--- a/src/plugins/valgrind/memchecktool.cpp
+++ b/src/plugins/valgrind/memchecktool.cpp
@@ -37,6 +37,7 @@
#include <analyzerbase/analyzermanager.h>
#include <analyzerbase/analyzerconstants.h>
+#include <valgrind/valgrindsettings.h>
#include <valgrind/xmlprotocol/errorlistmodel.h>
#include <valgrind/xmlprotocol/stackmodel.h>
#include <valgrind/xmlprotocol/error.h>
@@ -68,6 +69,7 @@
#include <QString>
#include <QLatin1String>
+#include <QFileDialog>
#include <QFileInfo>
#include <QFile>
#include <QDir>
@@ -138,13 +140,12 @@ bool MemcheckErrorFilterProxyModel::filterAcceptsRow(int sourceRow, const QModel
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
- SessionManager *session = ProjectExplorerPlugin::instance()->session();
QSet<QString> validFolders;
- foreach (Project *project, session->projects()) {
+ foreach (Project *project, SessionManager::projects()) {
validFolders << project->projectDirectory();
foreach (Target *target, project->targets()) {
foreach (BuildConfiguration *config, target->buildConfigurations())
- validFolders << config->buildDirectory();
+ validFolders << config->buildDirectory().toString();
}
}
@@ -220,91 +221,66 @@ MemcheckTool::MemcheckTool(QObject *parent)
void MemcheckTool::settingsDestroyed(QObject *settings)
{
QTC_ASSERT(m_settings == settings, return);
- m_settings = AnalyzerGlobalSettings::instance();
+ m_settings = ValgrindPlugin::globalSettings();
}
-void MemcheckTool::maybeActiveRunConfigurationChanged()
+void MemcheckTool::updateFromSettings()
{
- AnalyzerSettings *settings = 0;
- 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();
-
- if (m_settings == settings)
- return;
-
- // disconnect old settings class if any
- if (m_settings) {
- m_settings->disconnect(this);
- m_settings->disconnect(m_errorProxyModel);
- }
-
- // now make the new settings current, update and connect input widgets
- m_settings = settings;
- QTC_ASSERT(m_settings, return);
-
- connect(m_settings, SIGNAL(destroyed(QObject*)), SLOT(settingsDestroyed(QObject*)));
-
- ValgrindBaseSettings *memcheckSettings = m_settings->subConfig<ValgrindBaseSettings>();
- QTC_ASSERT(memcheckSettings, return);
-
foreach (QAction *action, m_errorFilterActions) {
bool contained = true;
foreach (const QVariant &v, action->data().toList()) {
bool ok;
int kind = v.toInt(&ok);
- if (ok && !memcheckSettings->visibleErrorKinds().contains(kind))
+ if (ok && !m_settings->visibleErrorKinds().contains(kind))
contained = false;
}
action->setChecked(contained);
}
- m_filterProjectAction->setChecked(!memcheckSettings->filterExternalIssues());
+ m_filterProjectAction->setChecked(!m_settings->filterExternalIssues());
m_errorView->settingsChanged(m_settings);
- connect(memcheckSettings, SIGNAL(visibleErrorKindsChanged(QList<int>)),
+ connect(m_settings, SIGNAL(visibleErrorKindsChanged(QList<int>)),
m_errorProxyModel, SLOT(setAcceptedKinds(QList<int>)));
- m_errorProxyModel->setAcceptedKinds(memcheckSettings->visibleErrorKinds());
+ m_errorProxyModel->setAcceptedKinds(m_settings->visibleErrorKinds());
- connect(memcheckSettings, SIGNAL(filterExternalIssuesChanged(bool)),
+ connect(m_settings, SIGNAL(filterExternalIssuesChanged(bool)),
m_errorProxyModel, SLOT(setFilterExternalIssues(bool)));
- m_errorProxyModel->setFilterExternalIssues(memcheckSettings->filterExternalIssues());
+ m_errorProxyModel->setFilterExternalIssues(m_settings->filterExternalIssues());
}
-Core::Id MemcheckTool::id() const
+void MemcheckTool::maybeActiveRunConfigurationChanged()
{
- return Core::Id("Memcheck");
-}
+ ValgrindBaseSettings *settings = 0;
+ if (Project *project = SessionManager::startupProject())
+ if (Target *target = project->activeTarget())
+ if (RunConfiguration *rc = target->activeRunConfiguration())
+ if (IRunConfigurationAspect *aspect = rc->extraAspect(ANALYZER_VALGRIND_SETTINGS))
+ settings = qobject_cast<ValgrindBaseSettings *>(aspect->currentSettings());
-RunMode MemcheckTool::runMode() const
-{
- return MemcheckRunMode;
-}
+ if (!settings) // fallback to global settings
+ settings = ValgrindPlugin::globalSettings();
-QString MemcheckTool::displayName() const
-{
- return tr("Valgrind Memory Analyzer");
-}
+ if (m_settings == settings)
+ return;
-QString MemcheckTool::description() const
-{
- return tr("Valgrind Analyze Memory uses the \"memcheck\" tool to find "
- "memory leaks");
-}
+ // disconnect old settings class if any
+ if (m_settings) {
+ m_settings->disconnect(this);
+ m_settings->disconnect(m_errorProxyModel);
+ }
-AbstractAnalyzerSubConfig *MemcheckTool::createGlobalSettings()
-{
- return new ValgrindGlobalSettings();
+ // now make the new settings current, update and connect input widgets
+ m_settings = settings;
+ QTC_ASSERT(m_settings, return);
+ connect(m_settings, SIGNAL(destroyed(QObject*)), SLOT(settingsDestroyed(QObject*)));
+
+ updateFromSettings();
}
-AbstractAnalyzerSubConfig *MemcheckTool::createProjectSettings()
+RunMode MemcheckTool::runMode() const
{
- return new ValgrindProjectSettings();
+ return MemcheckRunMode;
}
IAnalyzerTool::ToolMode MemcheckTool::toolMode() const
@@ -401,6 +377,16 @@ QWidget *MemcheckTool::createWidgets()
layout->setMargin(0);
layout->setSpacing(0);
+ // Load external XML log file
+ action = new QAction(this);
+ action->setIcon(QIcon(QLatin1String(Core::Constants::ICON_OPENFILE)));
+ action->setToolTip(tr("Load External XML Log File."));
+ connect(action, SIGNAL(triggered(bool)), this, SLOT(loadExternalXmlLogFile()));
+ button = new QToolButton;
+ button->setDefaultAction(action);
+ layout->addWidget(button);
+ m_loadExternalLogFile = action;
+
// Go to previous leak.
action = new QAction(this);
action->setDisabled(true);
@@ -445,40 +431,35 @@ QWidget *MemcheckTool::createWidgets()
return widget;
}
-IAnalyzerEngine *MemcheckTool::createEngine(const AnalyzerStartParameters &sp,
+AnalyzerRunControl *MemcheckTool::createRunControl(const AnalyzerStartParameters &sp,
RunConfiguration *runConfiguration)
{
m_frameFinder->setFiles(runConfiguration ? runConfiguration->target()
->project()->files(Project::AllFiles) : QStringList());
- MemcheckEngine *engine = new MemcheckEngine(this, sp, runConfiguration);
+ MemcheckRunControl *engine = new MemcheckRunControl(sp, runConfiguration);
- connect(engine, SIGNAL(starting(const Analyzer::IAnalyzerEngine*)),
- this, SLOT(engineStarting(const Analyzer::IAnalyzerEngine*)));
+ connect(engine, SIGNAL(starting(const Analyzer::AnalyzerRunControl*)),
+ this, SLOT(engineStarting(const Analyzer::AnalyzerRunControl*)));
connect(engine, SIGNAL(parserError(Valgrind::XmlProtocol::Error)),
this, SLOT(parserError(Valgrind::XmlProtocol::Error)));
connect(engine, SIGNAL(internalParserError(QString)),
this, SLOT(internalParserError(QString)));
- connect(engine, SIGNAL(finished()), this, SLOT(finished()));
- AnalyzerManager::showStatusMessage(AnalyzerManager::msgToolStarted(displayName()));
+ connect(engine, SIGNAL(finished()), this, SLOT(engineFinished()));
return engine;
}
-void MemcheckTool::startTool(StartMode mode)
-{
- ValgrindPlugin::startValgrindTool(this, mode);
-}
-
-void MemcheckTool::engineStarting(const IAnalyzerEngine *engine)
+void MemcheckTool::engineStarting(const AnalyzerRunControl *engine)
{
setBusyCursor(true);
clearErrorView();
+ m_loadExternalLogFile->setDisabled(true);
QString dir;
if (RunConfiguration *rc = engine->runConfiguration())
dir = rc->target()->project()->projectDirectory() + QDir::separator();
- const MemcheckEngine *mEngine = dynamic_cast<const MemcheckEngine *>(engine);
+ const MemcheckRunControl *mEngine = dynamic_cast<const MemcheckRunControl *>(engine);
QTC_ASSERT(mEngine, return);
const QString name = QFileInfo(mEngine->executable()).fileName();
@@ -504,6 +485,45 @@ void MemcheckTool::suppressionActionTriggered()
Core::EditorManager::openEditorAt(file, 0);
}
+void MemcheckTool::loadExternalXmlLogFile()
+{
+ const QString filePath = QFileDialog::getOpenFileName(
+ Core::ICore::mainWindow(),
+ tr("Open Memcheck XML Log File"),
+ QString(),
+ tr("XML Files (*.xml);;All Files (*)"));
+ if (filePath.isEmpty())
+ return;
+
+ QFile *logFile = new QFile(filePath);
+ if (!logFile->open(QIODevice::ReadOnly | QIODevice::Text)) {
+ delete logFile;
+ QMessageBox::critical(m_errorView, tr("Internal Error"),
+ tr("Failed to open file for reading: %1").arg(filePath));
+ return;
+ }
+
+ setBusyCursor(true);
+ clearErrorView();
+ m_loadExternalLogFile->setDisabled(true);
+
+ if (!m_settings || m_settings != ValgrindPlugin::globalSettings()) {
+ m_settings = ValgrindPlugin::globalSettings();
+ m_errorView->settingsChanged(m_settings);
+ updateFromSettings();
+ }
+
+ ThreadedParser *parser = new ThreadedParser;
+ connect(parser, SIGNAL(error(Valgrind::XmlProtocol::Error)),
+ this, SLOT(parserError(Valgrind::XmlProtocol::Error)));
+ connect(parser, SIGNAL(internalError(QString)),
+ this, SLOT(internalParserError(QString)));
+ connect(parser, SIGNAL(finished()), this, SLOT(loadingExternalXmlLogFileFinished()));
+ connect(parser, SIGNAL(finished()), parser, SLOT(deleteLater()));
+
+ parser->parse(logFile); // ThreadedParser owns the file
+}
+
void MemcheckTool::parserError(const Valgrind::XmlProtocol::Error &error)
{
m_errorModel->addError(error);
@@ -530,9 +550,7 @@ void MemcheckTool::updateErrorFilter()
QTC_ASSERT(m_errorView, return);
QTC_ASSERT(m_settings, return);
- ValgrindBaseSettings *memcheckSettings = m_settings->subConfig<ValgrindBaseSettings>();
- QTC_ASSERT(memcheckSettings, return);
- memcheckSettings->setFilterExternalIssues(!m_filterProjectAction->isChecked());
+ m_settings->setFilterExternalIssues(!m_filterProjectAction->isChecked());
QList<int> errorKinds;
foreach (QAction *a, m_errorFilterActions) {
@@ -545,17 +563,33 @@ void MemcheckTool::updateErrorFilter()
errorKinds << kind;
}
}
- memcheckSettings->setVisibleErrorKinds(errorKinds);
+ m_settings->setVisibleErrorKinds(errorKinds);
}
-void MemcheckTool::finished()
+int MemcheckTool::updateUiAfterFinishedHelper()
{
- const int n = m_errorModel->rowCount();
- m_goBack->setEnabled(n > 1);
- m_goNext->setEnabled(n > 1);
- const QString msg = AnalyzerManager::msgToolFinished(displayName(), n);
- AnalyzerManager::showStatusMessage(msg);
+ const int issuesFound = m_errorModel->rowCount();
+ m_goBack->setEnabled(issuesFound > 1);
+ m_goNext->setEnabled(issuesFound > 1);
+ m_loadExternalLogFile->setEnabled(true);
setBusyCursor(false);
+ return issuesFound;
+}
+
+void MemcheckTool::engineFinished()
+{
+ const int issuesFound = updateUiAfterFinishedHelper();
+ AnalyzerManager::showStatusMessage(issuesFound > 0
+ ? AnalyzerManager::tr("Memory Analyzer Tool finished, %n issues were found.", 0, issuesFound)
+ : AnalyzerManager::tr("Memory Analyzer Tool finished, no issues were found."));
+}
+
+void MemcheckTool::loadingExternalXmlLogFileFinished()
+{
+ const int issuesFound = updateUiAfterFinishedHelper();
+ AnalyzerManager::showStatusMessage(issuesFound > 0
+ ? AnalyzerManager::tr("Log file processed, %n issues were found.", 0, issuesFound)
+ : AnalyzerManager::tr("Log file processed, no issues were found."));
}
void MemcheckTool::setBusyCursor(bool busy)
diff --git a/src/plugins/valgrind/memchecktool.h b/src/plugins/valgrind/memchecktool.h
index 26c632c8f2..93d913477a 100644
--- a/src/plugins/valgrind/memchecktool.h
+++ b/src/plugins/valgrind/memchecktool.h
@@ -34,15 +34,10 @@
#include "valgrindtool.h"
#include <QSortFilterProxyModel>
-#include <QSharedPointer>
QT_BEGIN_NAMESPACE
-class QItemSelection;
-class QTreeView;
class QModelIndex;
class QAction;
-class QSpinBox;
-class QCheckBox;
class QMenu;
QT_END_NAMESPACE
@@ -53,15 +48,12 @@ class Error;
}
}
-namespace Analyzer {
-class AnalyzerSettings;
-}
-
namespace Valgrind {
namespace Internal {
-class MemcheckErrorView;
class FrameFinder;
+class MemcheckErrorView;
+class ValgrindBaseSettings;
class MemcheckErrorFilterProxyModel : public QSortFilterProxyModel
{
@@ -89,41 +81,37 @@ class MemcheckTool : public ValgrindTool
public:
MemcheckTool(QObject *parent);
- Core::Id id() const;
ProjectExplorer::RunMode runMode() const;
- QString displayName() const;
- QString description() const;
-
- // Create the valgrind settings (for all valgrind tools)
- Analyzer::AbstractAnalyzerSubConfig *createGlobalSettings();
- Analyzer::AbstractAnalyzerSubConfig *createProjectSettings();
private slots:
void settingsDestroyed(QObject *settings);
void maybeActiveRunConfigurationChanged();
- void engineStarting(const Analyzer::IAnalyzerEngine *engine);
- void finished();
+ void engineStarting(const Analyzer::AnalyzerRunControl *engine);
+ void engineFinished();
+ void loadingExternalXmlLogFileFinished();
void parserError(const Valgrind::XmlProtocol::Error &error);
void internalParserError(const QString &errorString);
void updateErrorFilter();
void suppressionActionTriggered();
+ void loadExternalXmlLogFile();
+
private:
ToolMode toolMode() const;
- void extensionsInitialized() {}
QWidget *createWidgets();
void setBusyCursor(bool busy);
- Analyzer::IAnalyzerEngine *createEngine(const Analyzer::AnalyzerStartParameters &sp,
+ Analyzer::AnalyzerRunControl *createRunControl(const Analyzer::AnalyzerStartParameters &sp,
ProjectExplorer::RunConfiguration *runConfiguration = 0);
- void startTool(Analyzer::StartMode mode);
void clearErrorView();
+ void updateFromSettings();
+ int updateUiAfterFinishedHelper();
private:
- Analyzer::AnalyzerSettings *m_settings;
+ ValgrindBaseSettings *m_settings;
QMenu *m_filterMenu;
FrameFinder *m_frameFinder;
@@ -135,6 +123,7 @@ private:
QAction *m_filterProjectAction;
QList<QAction *> m_suppressionActions;
QAction *m_suppressionSeparator;
+ QAction *m_loadExternalLogFile;
QAction *m_goBack;
QAction *m_goNext;
};
diff --git a/src/plugins/valgrind/suppressiondialog.cpp b/src/plugins/valgrind/suppressiondialog.cpp
index 8e1a4c25a4..cd19cd6e33 100644
--- a/src/plugins/valgrind/suppressiondialog.cpp
+++ b/src/plugins/valgrind/suppressiondialog.cpp
@@ -55,7 +55,6 @@
#include <QLabel>
#include <QPlainTextEdit>
-using namespace Analyzer;
using namespace Valgrind::XmlProtocol;
namespace Valgrind {
@@ -212,17 +211,16 @@ void SuppressionDialog::accept()
return;
// Add file to project if there is a project containing this file on the file system.
- ProjectExplorer::SessionManager *session = ProjectExplorer::ProjectExplorerPlugin::instance()->session();
- if (!session->projectForFile(path)) {
- foreach (ProjectExplorer::Project *p, session->projects()) {
+ if (!ProjectExplorer::SessionManager::projectForFile(path)) {
+ foreach (ProjectExplorer::Project *p, ProjectExplorer::SessionManager::projects()) {
if (path.startsWith(p->projectDirectory())) {
- p->rootProjectNode()->addFiles(ProjectExplorer::UnknownFileType, QStringList() << path);
+ p->rootProjectNode()->addFiles(QStringList() << path);
break;
}
}
}
- m_settings->subConfig<ValgrindBaseSettings>()->addSuppressionFiles(QStringList(path));
+ m_settings->addSuppressionFiles(QStringList(path));
QModelIndexList indices = m_view->selectionModel()->selectedRows();
qSort(indices.begin(), indices.end(), sortIndizesReverse);
diff --git a/src/plugins/valgrind/suppressiondialog.h b/src/plugins/valgrind/suppressiondialog.h
index cecbb6afe7..5c0c25535d 100644
--- a/src/plugins/valgrind/suppressiondialog.h
+++ b/src/plugins/valgrind/suppressiondialog.h
@@ -42,12 +42,11 @@ class QPlainTextEdit;
class QDialogButtonBox;
QT_END_NAMESPACE
-namespace Analyzer { class AnalyzerSettings; }
-
namespace Valgrind {
namespace Internal {
class MemcheckErrorView;
+class ValgrindBaseSettings;
class SuppressionDialog : public QDialog
{
@@ -66,7 +65,7 @@ private:
void reject();
MemcheckErrorView *m_view;
- Analyzer::AnalyzerSettings *m_settings;
+ ValgrindBaseSettings *m_settings;
bool m_cleanupIfCanceled;
QList<XmlProtocol::Error> m_errors;
diff --git a/src/plugins/valgrind/valgrind.pro b/src/plugins/valgrind/valgrind.pro
index 8d504b2ff5..188ac67ec7 100644
--- a/src/plugins/valgrind/valgrind.pro
+++ b/src/plugins/valgrind/valgrind.pro
@@ -6,8 +6,6 @@ QT *= network
CONFIG += exceptions
-INCLUDEPATH *= $$PWD
-
HEADERS += \
valgrindplugin.h \
valgrindengine.h \
@@ -24,12 +22,11 @@ HEADERS += \
callgrindengine.h \
workarounds.h \
callgrindtextmark.h \
- \
+ valgrindtool.h \
memchecktool.h \
memcheckengine.h \
memcheckerrorview.h \
suppressiondialog.h \
- valgrindtool.h \
valgrindruncontrolfactory.h
SOURCES += \
@@ -39,7 +36,7 @@ SOURCES += \
valgrindsettings.cpp \
valgrindrunner.cpp \
valgrindprocess.cpp \
- \
+ valgrindtool.cpp \
callgrindcostdelegate.cpp \
callgrindcostview.cpp \
callgrindhelper.cpp \
@@ -53,7 +50,6 @@ SOURCES += \
memcheckengine.cpp \
memcheckerrorview.cpp \
suppressiondialog.cpp \
- valgrindtool.cpp \
valgrindruncontrolfactory.cpp
FORMS += \
diff --git a/src/plugins/valgrind/valgrind.qbs b/src/plugins/valgrind/valgrind.qbs
index 0f6d1a9a89..a0e758ab49 100644
--- a/src/plugins/valgrind/valgrind.qbs
+++ b/src/plugins/valgrind/valgrind.qbs
@@ -14,101 +14,78 @@ QtcPlugin {
Depends { name: "RemoteLinux" }
Depends { name: "CPlusPlus"}
- files: [
- "callgrindcostdelegate.cpp",
- "callgrindcostdelegate.h",
- "callgrindcostview.cpp",
- "callgrindcostview.h",
- "callgrindengine.cpp",
- "callgrindengine.h",
- "callgrindhelper.cpp",
- "callgrindhelper.h",
- "callgrindnamedelegate.cpp",
- "callgrindnamedelegate.h",
- "callgrindtextmark.cpp",
- "callgrindtextmark.h",
- "callgrindtool.cpp",
- "callgrindtool.h",
- "callgrindvisualisation.cpp",
- "callgrindvisualisation.h",
- "memcheckengine.cpp",
- "memcheckengine.h",
- "memcheckerrorview.cpp",
- "memcheckerrorview.h",
- "memchecktool.cpp",
- "memchecktool.h",
- "suppressiondialog.cpp",
- "suppressiondialog.h",
- "valgrindconfigwidget.cpp",
- "valgrindconfigwidget.h",
- "valgrindconfigwidget.ui",
- "valgrindengine.cpp",
- "valgrindengine.h",
- "valgrindplugin.cpp",
- "valgrindplugin.h",
- "valgrindprocess.cpp",
- "valgrindprocess.h",
- "valgrindruncontrolfactory.cpp",
- "valgrindruncontrolfactory.h",
- "valgrindrunner.cpp",
- "valgrindrunner.h",
- "valgrindsettings.cpp",
- "valgrindsettings.h",
- "valgrindtool.cpp",
- "valgrindtool.h",
- "workarounds.cpp",
- "workarounds.h",
- "callgrind/callgrindabstractmodel.h",
- "callgrind/callgrindcallmodel.cpp",
- "callgrind/callgrindcallmodel.h",
- "callgrind/callgrindcontroller.cpp",
- "callgrind/callgrindcontroller.h",
- "callgrind/callgrindcostitem.cpp",
- "callgrind/callgrindcostitem.h",
- "callgrind/callgrindcycledetection.cpp",
- "callgrind/callgrindcycledetection.h",
- "callgrind/callgrinddatamodel.cpp",
- "callgrind/callgrinddatamodel.h",
- "callgrind/callgrindfunction.cpp",
- "callgrind/callgrindfunction.h",
- "callgrind/callgrindfunction_p.h",
- "callgrind/callgrindfunctioncall.cpp",
- "callgrind/callgrindfunctioncall.h",
- "callgrind/callgrindfunctioncycle.cpp",
- "callgrind/callgrindfunctioncycle.h",
- "callgrind/callgrindparsedata.cpp",
- "callgrind/callgrindparsedata.h",
- "callgrind/callgrindparser.cpp",
- "callgrind/callgrindparser.h",
- "callgrind/callgrindproxymodel.cpp",
- "callgrind/callgrindproxymodel.h",
- "callgrind/callgrindrunner.cpp",
- "callgrind/callgrindrunner.h",
- "callgrind/callgrindstackbrowser.cpp",
- "callgrind/callgrindstackbrowser.h",
- "memcheck/memcheckrunner.cpp",
- "memcheck/memcheckrunner.h",
- "xmlprotocol/announcethread.cpp",
- "xmlprotocol/announcethread.h",
- "xmlprotocol/error.cpp",
- "xmlprotocol/error.h",
- "xmlprotocol/errorlistmodel.cpp",
- "xmlprotocol/errorlistmodel.h",
- "xmlprotocol/frame.cpp",
- "xmlprotocol/frame.h",
- "xmlprotocol/modelhelpers.cpp",
- "xmlprotocol/modelhelpers.h",
- "xmlprotocol/parser.cpp",
- "xmlprotocol/parser.h",
- "xmlprotocol/stack.cpp",
- "xmlprotocol/stack.h",
- "xmlprotocol/stackmodel.cpp",
- "xmlprotocol/stackmodel.h",
- "xmlprotocol/status.cpp",
- "xmlprotocol/status.h",
- "xmlprotocol/suppression.cpp",
- "xmlprotocol/suppression.h",
- "xmlprotocol/threadedparser.cpp",
- "xmlprotocol/threadedparser.h",
- ]
+ Group {
+ name: "General"
+ files: [
+ "callgrindcostdelegate.cpp", "callgrindcostdelegate.h",
+ "callgrindcostview.cpp", "callgrindcostview.h",
+ "callgrindengine.cpp", "callgrindengine.h",
+ "callgrindhelper.cpp", "callgrindhelper.h",
+ "callgrindnamedelegate.cpp", "callgrindnamedelegate.h",
+ "callgrindtextmark.cpp", "callgrindtextmark.h",
+ "callgrindtool.cpp", "callgrindtool.h",
+ "callgrindvisualisation.cpp", "callgrindvisualisation.h",
+ "memcheckengine.cpp", "memcheckengine.h",
+ "memcheckerrorview.cpp", "memcheckerrorview.h",
+ "memchecktool.cpp", "memchecktool.h",
+ "suppressiondialog.cpp", "suppressiondialog.h",
+ "valgrindconfigwidget.cpp", "valgrindconfigwidget.h", "valgrindconfigwidget.ui",
+ "valgrindengine.cpp", "valgrindengine.h",
+ "valgrindplugin.cpp", "valgrindplugin.h",
+ "valgrindprocess.cpp", "valgrindprocess.h",
+ "valgrindruncontrolfactory.cpp", "valgrindruncontrolfactory.h",
+ "valgrindrunner.cpp", "valgrindrunner.h",
+ "valgrindsettings.cpp", "valgrindsettings.h",
+ "valgrindtool.cpp", "valgrindtool.h",
+ "workarounds.cpp", "workarounds.h",
+ ]
+ }
+
+ Group {
+ name: "Callgrind"
+ prefix: "callgrind/"
+ files: [
+ "callgrindabstractmodel.h",
+ "callgrindcallmodel.cpp", "callgrindcallmodel.h",
+ "callgrindcontroller.cpp", "callgrindcontroller.h",
+ "callgrindcostitem.cpp", "callgrindcostitem.h",
+ "callgrindcycledetection.cpp", "callgrindcycledetection.h",
+ "callgrinddatamodel.cpp", "callgrinddatamodel.h",
+ "callgrindfunction.cpp", "callgrindfunction.h", "callgrindfunction_p.h",
+ "callgrindfunctioncall.cpp", "callgrindfunctioncall.h",
+ "callgrindfunctioncycle.cpp", "callgrindfunctioncycle.h",
+ "callgrindparsedata.cpp", "callgrindparsedata.h",
+ "callgrindparser.cpp", "callgrindparser.h",
+ "callgrindproxymodel.cpp", "callgrindproxymodel.h",
+ "callgrindrunner.cpp", "callgrindrunner.h",
+ "callgrindstackbrowser.cpp", "callgrindstackbrowser.h"
+ ]
+ }
+
+ Group {
+ name: "Memcheck"
+ prefix: "memcheck/"
+ files: [
+ "memcheckrunner.cpp",
+ "memcheckrunner.h"
+ ]
+ }
+
+ Group {
+ name: "XML Protocol"
+ prefix: "xmlprotocol/"
+ files: [
+ "announcethread.cpp", "announcethread.h",
+ "error.cpp", "error.h",
+ "errorlistmodel.cpp", "errorlistmodel.h",
+ "frame.cpp", "frame.h",
+ "modelhelpers.cpp", "modelhelpers.h",
+ "parser.cpp", "parser.h",
+ "stack.cpp", "stack.h",
+ "stackmodel.cpp", "stackmodel.h",
+ "status.cpp", "status.h",
+ "suppression.cpp", "suppression.h",
+ "threadedparser.cpp", "threadedparser.h",
+ ]
+ }
}
diff --git a/src/plugins/valgrind/valgrindconfigwidget.cpp b/src/plugins/valgrind/valgrindconfigwidget.cpp
index e39eff145c..d4f3a99dcd 100644
--- a/src/plugins/valgrind/valgrindconfigwidget.cpp
+++ b/src/plugins/valgrind/valgrindconfigwidget.cpp
@@ -30,6 +30,7 @@
#include "valgrindconfigwidget.h"
#include "valgrindsettings.h"
+#include "valgrindplugin.h"
#include "ui_valgrindconfigwidget.h"
@@ -63,6 +64,8 @@ ValgrindConfigWidget::ValgrindConfigWidget(ValgrindBaseSettings *settings,
m_settings, SLOT(setValgrindExecutable(QString)));
connect(m_settings, SIGNAL(valgrindExecutableChanged(QString)),
m_ui->valgrindExeChooser, SLOT(setPath(QString)));
+ connect(m_ui->smcDetectionComboBox, SIGNAL(currentIndexChanged(int)),
+ m_settings, SLOT(setSelfModifyingCodeDetection(int)));
if (Utils::HostOsInfo::isWindowsHost()) {
// FIXME: On Window we know that we don't have a local valgrind
@@ -123,6 +126,16 @@ ValgrindConfigWidget::ValgrindConfigWidget(ValgrindBaseSettings *settings,
connect(m_ui->numCallers, SIGNAL(valueChanged(int)), m_settings, SLOT(setNumCallers(int)));
connect(m_settings, SIGNAL(numCallersChanged(int)), m_ui->numCallers, SLOT(setValue(int)));
+ connect(m_ui->leakCheckOnFinish, SIGNAL(currentIndexChanged(int)),
+ m_settings, SLOT(setLeakCheckOnFinish(int)));
+ connect(m_settings, SIGNAL(leakCheckOnFinishChanged(int)),
+ m_ui->leakCheckOnFinish, SLOT(setCurrentIndex(int)));
+
+ connect(m_ui->showReachable, SIGNAL(toggled(bool)),
+ m_settings, SLOT(setShowReachable(bool)));
+ connect(m_settings, SIGNAL(showReachableChanged(bool)),
+ m_ui->showReachable, SLOT(setChecked(bool)));
+
connect(m_ui->trackOrigins, SIGNAL(toggled(bool)),
m_settings, SLOT(setTrackOrigins(bool)));
connect(m_settings, SIGNAL(trackOriginsChanged(bool)),
@@ -157,6 +170,7 @@ ValgrindConfigWidget::~ValgrindConfigWidget()
void ValgrindConfigWidget::updateUi()
{
m_ui->valgrindExeChooser->setPath(m_settings->valgrindExecutable());
+ m_ui->smcDetectionComboBox->setCurrentIndex(m_settings->selfModifyingCodeDetection());
m_ui->enableCacheSim->setChecked(m_settings->enableCacheSim());
m_ui->enableBranchSim->setChecked(m_settings->enableBranchSim());
m_ui->collectSystime->setChecked(m_settings->collectSystime());
@@ -165,6 +179,8 @@ void ValgrindConfigWidget::updateUi()
m_ui->minimumInclusiveCostRatio->setValue(m_settings->minimumInclusiveCostRatio());
m_ui->visualisationMinimumInclusiveCostRatio->setValue(m_settings->visualisationMinimumInclusiveCostRatio());
m_ui->numCallers->setValue(m_settings->numCallers());
+ m_ui->leakCheckOnFinish->setCurrentIndex(m_settings->leakCheckOnFinish());
+ m_ui->showReachable->setChecked(m_settings->showReachable());
m_ui->trackOrigins->setChecked(m_settings->trackOrigins());
m_model->clear();
foreach (const QString &file, m_settings->suppressionFiles())
@@ -173,7 +189,7 @@ void ValgrindConfigWidget::updateUi()
void ValgrindConfigWidget::slotAddSuppression()
{
- ValgrindGlobalSettings *conf = Analyzer::AnalyzerGlobalSettings::instance()->subConfig<ValgrindGlobalSettings>();
+ ValgrindGlobalSettings *conf = ValgrindPlugin::globalSettings();
QTC_ASSERT(conf, return);
QStringList files = QFileDialog::getOpenFileNames(this,
tr("Valgrind Suppression Files"),
diff --git a/src/plugins/valgrind/valgrindconfigwidget.ui b/src/plugins/valgrind/valgrindconfigwidget.ui
index 0b8bd1a07c..2c0e989760 100644
--- a/src/plugins/valgrind/valgrindconfigwidget.ui
+++ b/src/plugins/valgrind/valgrindconfigwidget.ui
@@ -6,8 +6,8 @@
<rect>
<x>0</x>
<y>0</y>
- <width>597</width>
- <height>312</height>
+ <width>655</width>
+ <height>364</height>
</rect>
</property>
<layout class="QGridLayout" name="gridLayout">
@@ -22,15 +22,15 @@
<property name="title">
<string>Generic Settings</string>
</property>
- <layout class="QHBoxLayout" name="horizontalLayout_2">
- <item>
+ <layout class="QGridLayout" name="gridLayout_2">
+ <item row="0" column="0">
<widget class="QLabel" name="valgrindExeLabel">
<property name="text">
<string>Valgrind executable:</string>
</property>
</widget>
</item>
- <item>
+ <item row="0" column="1">
<widget class="Utils::PathChooser" name="valgrindExeChooser" native="true">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
@@ -40,118 +40,57 @@
</property>
</widget>
</item>
- </layout>
- </widget>
- </item>
- <item row="1" column="0">
- <widget class="QGroupBox" name="memcheckOptions">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="title">
- <string>Memory Analysis Options</string>
- </property>
- <layout class="QFormLayout" name="formLayout_4">
- <property name="fieldGrowthPolicy">
- <enum>QFormLayout::ExpandingFieldsGrow</enum>
- </property>
- <item row="2" column="0">
- <widget class="QLabel" name="numCallersLabel">
+ <item row="1" column="0">
+ <widget class="QLabel" name="smcDetectionLabel">
<property name="text">
- <string>Backtrace frame count:</string>
- </property>
- <property name="buddy">
- <cstring>numCallers</cstring>
+ <string>Detect self-modifying code:</string>
</property>
</widget>
</item>
- <item row="3" column="0">
- <widget class="QLabel" name="label">
- <property name="text">
- <string>Suppression files:</string>
- </property>
- <property name="buddy">
- <cstring>suppressionList</cstring>
- </property>
- </widget>
- </item>
- <item row="4" column="0" colspan="2">
- <layout class="QHBoxLayout" name="horizontalLayout">
- <item>
- <widget class="QListView" name="suppressionList">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Expanding" vsizetype="Expanding">
- <horstretch>0</horstretch>
- <verstretch>1</verstretch>
- </sizepolicy>
- </property>
- </widget>
- </item>
+ <item row="1" column="1">
+ <layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
- <layout class="QVBoxLayout" name="verticalLayout_2" stretch="0,0,1">
- <property name="sizeConstraint">
- <enum>QLayout::SetMinimumSize</enum>
+ <widget class="QComboBox" name="smcDetectionComboBox">
+ <property name="currentIndex">
+ <number>1</number>
</property>
<item>
- <widget class="QPushButton" name="addSuppression">
- <property name="text">
- <string>Add...</string>
- </property>
- </widget>
+ <property name="text">
+ <string>No</string>
+ </property>
</item>
<item>
- <widget class="QPushButton" name="removeSuppression">
- <property name="text">
- <string>Remove</string>
- </property>
- <property name="flat">
- <bool>false</bool>
- </property>
- </widget>
+ <property name="text">
+ <string>Only on Stack</string>
+ </property>
</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>
+ <property name="text">
+ <string>Everywhere</string>
+ </property>
</item>
- </layout>
+ <item>
+ <property name="text">
+ <string>Everywhere Except in File-backend Mappings</string>
+ </property>
+ </item>
+ </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 row="2" column="1">
- <widget class="QSpinBox" name="numCallers">
- <property name="minimum">
- <number>5</number>
- </property>
- <property name="maximum">
- <number>50</number>
- </property>
- <property name="value">
- <number>12</number>
- </property>
- </widget>
- </item>
- <item row="1" column="0" colspan="2">
- <widget class="QCheckBox" name="trackOrigins">
- <property name="text">
- <string>Track origins of uninitialized memory</string>
- </property>
- <property name="checked">
- <bool>true</bool>
- </property>
- </widget>
- </item>
</layout>
</widget>
</item>
@@ -309,6 +248,185 @@ With cache simulation, further event counters are enabled:
</property>
</spacer>
</item>
+ <item row="1" column="0">
+ <widget class="QGroupBox" name="memcheckOptions">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="title">
+ <string>Memory Analysis Options</string>
+ </property>
+ <layout class="QFormLayout" name="formLayout">
+ <item row="0" column="0" colspan="2">
+ <widget class="QCheckBox" name="trackOrigins">
+ <property name="text">
+ <string>Track origins of uninitialized memory</string>
+ </property>
+ <property name="checked">
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="0" colspan="2">
+ <widget class="QCheckBox" name="showReachable">
+ <property name="text">
+ <string>Show reachable and indirectly lost blocks</string>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="0">
+ <widget class="QLabel" name="leakCheckOnFinishLabel">
+ <property name="text">
+ <string>Check for leaks on finish:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="1">
+ <layout class="QHBoxLayout" name="horizontalLayout_3">
+ <item>
+ <widget class="QComboBox" name="leakCheckOnFinish">
+ <property name="currentIndex">
+ <number>0</number>
+ </property>
+ <item>
+ <property name="text">
+ <string>No</string>
+ </property>
+ </item>
+ <item>
+ <property name="text">
+ <string>Summary Only</string>
+ </property>
+ </item>
+ <item>
+ <property name="text">
+ <string>Full</string>
+ </property>
+ </item>
+ </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 row="3" column="0">
+ <widget class="QLabel" name="numCallersLabel">
+ <property name="text">
+ <string>Backtrace frame count:</string>
+ </property>
+ <property name="buddy">
+ <cstring>numCallers</cstring>
+ </property>
+ </widget>
+ </item>
+ <item row="3" column="1">
+ <layout class="QHBoxLayout" name="horizontalLayout_4">
+ <item>
+ <widget class="QSpinBox" name="numCallers">
+ <property name="minimum">
+ <number>5</number>
+ </property>
+ <property name="maximum">
+ <number>50</number>
+ </property>
+ <property name="value">
+ <number>12</number>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <spacer name="horizontalSpacer_3">
+ <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 row="4" column="0">
+ <widget class="QLabel" name="label">
+ <property name="text">
+ <string>Suppression files:</string>
+ </property>
+ <property name="buddy">
+ <cstring>suppressionList</cstring>
+ </property>
+ </widget>
+ </item>
+ <item row="5" column="0" colspan="2">
+ <layout class="QHBoxLayout" name="horizontalLayout">
+ <item>
+ <widget class="QListView" name="suppressionList">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Expanding" vsizetype="Expanding">
+ <horstretch>0</horstretch>
+ <verstretch>1</verstretch>
+ </sizepolicy>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <layout class="QVBoxLayout" name="verticalLayout_2" stretch="0,0,1">
+ <property name="sizeConstraint">
+ <enum>QLayout::SetMinimumSize</enum>
+ </property>
+ <item>
+ <widget class="QPushButton" name="addSuppression">
+ <property name="text">
+ <string>Add...</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="removeSuppression">
+ <property name="text">
+ <string>Remove</string>
+ </property>
+ <property name="flat">
+ <bool>false</bool>
+ </property>
+ </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>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ </item>
</layout>
</widget>
<customwidgets>
diff --git a/src/plugins/valgrind/valgrindengine.cpp b/src/plugins/valgrind/valgrindengine.cpp
index 74f49dd959..b36d5230c0 100644
--- a/src/plugins/valgrind/valgrindengine.cpp
+++ b/src/plugins/valgrind/valgrindengine.cpp
@@ -30,13 +30,14 @@
#include "valgrindengine.h"
#include "valgrindsettings.h"
+#include "valgrindplugin.h"
#include <coreplugin/icore.h>
#include <coreplugin/ioutputpane.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <coreplugin/progressmanager/futureprogress.h>
#include <extensionsystem/pluginmanager.h>
-#include <projectexplorer/localapplicationrunconfiguration.h>
+#include <projectexplorer/runconfiguration.h>
#include <analyzerbase/analyzermanager.h>
#include <QApplication>
@@ -47,25 +48,27 @@
using namespace Analyzer;
using namespace Core;
using namespace Utils;
+using namespace ProjectExplorer;
namespace Valgrind {
namespace Internal {
const int progressMaximum = 1000000;
-ValgrindEngine::ValgrindEngine(IAnalyzerTool *tool, const AnalyzerStartParameters &sp,
+ValgrindRunControl::ValgrindRunControl(const AnalyzerStartParameters &sp,
ProjectExplorer::RunConfiguration *runConfiguration)
- : IAnalyzerEngine(tool, sp, runConfiguration),
+ : AnalyzerRunControl(sp, runConfiguration),
m_settings(0),
m_progress(new QFutureInterface<void>()),
m_progressWatcher(new QFutureWatcher<void>()),
m_isStopping(false)
{
if (runConfiguration)
- m_settings = runConfiguration->extraAspect<AnalyzerRunConfigurationAspect>();
+ if (IRunConfigurationAspect *aspect = runConfiguration->extraAspect(ANALYZER_VALGRIND_SETTINGS))
+ m_settings = qobject_cast<ValgrindBaseSettings *>(aspect->currentSettings());
- if (!m_settings)
- m_settings = AnalyzerGlobalSettings::instance();
+ if (!m_settings)
+ m_settings = ValgrindPlugin::globalSettings();
connect(m_progressWatcher, SIGNAL(canceled()),
this, SLOT(handleProgressCanceled()));
@@ -73,17 +76,17 @@ ValgrindEngine::ValgrindEngine(IAnalyzerTool *tool, const AnalyzerStartParameter
this, SLOT(handleProgressFinished()));
}
-ValgrindEngine::~ValgrindEngine()
+ValgrindRunControl::~ValgrindRunControl()
{
delete m_progress;
}
-bool ValgrindEngine::start()
+bool ValgrindRunControl::startEngine()
{
emit starting(this);
- FutureProgress *fp = ICore::progressManager()->addTask(m_progress->future(),
- progressTitle(), QLatin1String("valgrind"));
+ FutureProgress *fp = ProgressManager::addTask(m_progress->future(),
+ progressTitle(), "valgrind");
fp->setKeepOnFinish(FutureProgress::HideOnFinish);
m_progress->setProgressRange(0, progressMaximum);
m_progress->reportStarted();
@@ -97,58 +100,80 @@ bool ValgrindEngine::start()
emit outputReceived(tr("Commandline arguments: %1").arg(sp.debuggeeArgs), DebugFormat);
#endif
- runner()->setWorkingDirectory(sp.workingDirectory);
- QString valgrindExe = m_settings->subConfig<ValgrindBaseSettings>()->valgrindExecutable();
+ ValgrindRunner *run = runner();
+ run->setWorkingDirectory(sp.workingDirectory);
+ QString valgrindExe = m_settings->valgrindExecutable();
if (!sp.analyzerCmdPrefix.isEmpty())
valgrindExe = sp.analyzerCmdPrefix + QLatin1Char(' ') + valgrindExe;
- runner()->setValgrindExecutable(valgrindExe);
- runner()->setValgrindArguments(toolArguments());
- runner()->setDebuggeeExecutable(sp.debuggee);
- runner()->setDebuggeeArguments(sp.debuggeeArgs);
- runner()->setEnvironment(sp.environment);
- runner()->setConnectionParameters(sp.connParams);
- runner()->setStartMode(sp.startMode);
-
- connect(runner(), SIGNAL(processOutputReceived(QByteArray,Utils::OutputFormat)),
+ run->setValgrindExecutable(valgrindExe);
+ run->setValgrindArguments(genericToolArguments() + toolArguments());
+ run->setDebuggeeExecutable(sp.debuggee);
+ run->setDebuggeeArguments(sp.debuggeeArgs);
+ run->setEnvironment(sp.environment);
+ run->setConnectionParameters(sp.connParams);
+ run->setStartMode(sp.startMode);
+
+ connect(run, SIGNAL(processOutputReceived(QByteArray,Utils::OutputFormat)),
SLOT(receiveProcessOutput(QByteArray,Utils::OutputFormat)));
- connect(runner(), SIGNAL(processErrorReceived(QString,QProcess::ProcessError)),
+ connect(run, SIGNAL(processErrorReceived(QString,QProcess::ProcessError)),
SLOT(receiveProcessError(QString,QProcess::ProcessError)));
- connect(runner(), SIGNAL(finished()),
- SLOT(runnerFinished()));
+ connect(run, SIGNAL(finished()), SLOT(runnerFinished()));
- if (!runner()->start()) {
+ if (!run->start()) {
m_progress->cancel();
return false;
}
return true;
}
-void ValgrindEngine::stop()
+void ValgrindRunControl::stopEngine()
{
m_isStopping = true;
runner()->stop();
}
-QString ValgrindEngine::executable() const
+QString ValgrindRunControl::executable() const
{
return startParameters().debuggee;
}
-void ValgrindEngine::handleProgressCanceled()
+QStringList ValgrindRunControl::genericToolArguments() const
+{
+ QTC_ASSERT(m_settings, return QStringList());
+ QString smcCheckValue;
+ switch (m_settings->selfModifyingCodeDetection()) {
+ case ValgrindBaseSettings::DetectSmcNo:
+ smcCheckValue = QLatin1String("none");
+ break;
+ case ValgrindBaseSettings::DetectSmcEverywhere:
+ smcCheckValue = QLatin1String("all");
+ break;
+ case ValgrindBaseSettings::DetectSmcEverywhereButFile:
+ smcCheckValue = QLatin1String("all-non-file");
+ break;
+ case ValgrindBaseSettings::DetectSmcStackOnly:
+ default:
+ smcCheckValue = QLatin1String("stack");
+ break;
+ }
+ return QStringList() << QLatin1String("--smc-check=") + smcCheckValue;
+}
+
+void ValgrindRunControl::handleProgressCanceled()
{
AnalyzerManager::stopTool();
m_progress->reportCanceled();
m_progress->reportFinished();
}
-void ValgrindEngine::handleProgressFinished()
+void ValgrindRunControl::handleProgressFinished()
{
QApplication::alert(ICore::mainWindow(), 3000);
}
-void ValgrindEngine::runnerFinished()
+void ValgrindRunControl::runnerFinished()
{
- emit outputReceived(tr("** Analyzing finished **\n"), NormalMessageFormat);
+ appendMessage(tr("** Analyzing finished **\n"), NormalMessageFormat);
emit finished();
m_progress->reportFinished();
@@ -159,7 +184,7 @@ void ValgrindEngine::runnerFinished()
this, SLOT(runnerFinished()));
}
-void ValgrindEngine::receiveProcessOutput(const QByteArray &output, OutputFormat format)
+void ValgrindRunControl::receiveProcessOutput(const QByteArray &output, OutputFormat format)
{
int progress = m_progress->progressValue();
if (progress < 5 * progressMaximum / 10)
@@ -167,21 +192,21 @@ void ValgrindEngine::receiveProcessOutput(const QByteArray &output, OutputFormat
else if (progress < 9 * progressMaximum / 10)
progress += progress / 1000;
m_progress->setProgressValue(progress);
- emit outputReceived(QString::fromLocal8Bit(output), format);
+ appendMessage(QString::fromLocal8Bit(output), format);
}
-void ValgrindEngine::receiveProcessError(const QString &message, QProcess::ProcessError error)
+void ValgrindRunControl::receiveProcessError(const QString &message, QProcess::ProcessError error)
{
if (error == QProcess::FailedToStart) {
- const QString &valgrind = m_settings->subConfig<ValgrindBaseSettings>()->valgrindExecutable();
+ const QString valgrind = m_settings->valgrindExecutable();
if (!valgrind.isEmpty())
- emit outputReceived(tr("** Error: \"%1\" could not be started: %2 **\n").arg(valgrind).arg(message), ErrorMessageFormat);
+ appendMessage(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);
+ appendMessage(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);
+ appendMessage(tr("** Process Terminated **\n"), ErrorMessageFormat);
} else {
- emit outputReceived(QString::fromLatin1("** %1 **\n").arg(message), ErrorMessageFormat);
+ appendMessage(QString::fromLatin1("** %1 **\n").arg(message), ErrorMessageFormat);
}
if (m_isStopping)
diff --git a/src/plugins/valgrind/valgrindengine.h b/src/plugins/valgrind/valgrindengine.h
index f58f0bfc83..335b587947 100644
--- a/src/plugins/valgrind/valgrindengine.h
+++ b/src/plugins/valgrind/valgrindengine.h
@@ -31,30 +31,28 @@
#ifndef VALGRINDENGINE_H
#define VALGRINDENGINE_H
-#include <analyzerbase/ianalyzerengine.h>
+#include <analyzerbase/analyzerruncontrol.h>
#include <utils/environment.h>
#include <valgrind/valgrindrunner.h>
+#include <valgrind/valgrindsettings.h>
#include <QFutureInterface>
#include <QFutureWatcher>
-namespace Analyzer { class AnalyzerSettings; }
-
namespace Valgrind {
namespace Internal {
-class ValgrindEngine : public Analyzer::IAnalyzerEngine
+class ValgrindRunControl : public Analyzer::AnalyzerRunControl
{
Q_OBJECT
public:
- ValgrindEngine(Analyzer::IAnalyzerTool *tool,
- const Analyzer::AnalyzerStartParameters &sp,
+ ValgrindRunControl(const Analyzer::AnalyzerStartParameters &sp,
ProjectExplorer::RunConfiguration *runConfiguration);
- ~ValgrindEngine();
+ ~ValgrindRunControl();
- bool start();
- void stop();
+ bool startEngine();
+ void stopEngine();
QString executable() const;
@@ -63,7 +61,7 @@ protected:
virtual QStringList toolArguments() const = 0;
virtual Valgrind::ValgrindRunner *runner() = 0;
- Analyzer::AnalyzerSettings *m_settings;
+ ValgrindBaseSettings *m_settings;
QFutureInterface<void> *m_progress;
QFutureWatcher<void> *m_progressWatcher;
@@ -76,6 +74,9 @@ private slots:
void receiveProcessError(const QString &message, QProcess::ProcessError error);
private:
+ QStringList genericToolArguments() const;
+
+private:
bool m_isStopping;
};
diff --git a/src/plugins/valgrind/valgrindplugin.cpp b/src/plugins/valgrind/valgrindplugin.cpp
index 88a0232b4d..aaa566d3c9 100644
--- a/src/plugins/valgrind/valgrindplugin.cpp
+++ b/src/plugins/valgrind/valgrindplugin.cpp
@@ -33,78 +33,157 @@
#include "callgrindtool.h"
#include "memchecktool.h"
#include "valgrindruncontrolfactory.h"
+#include "valgrindsettings.h"
+#include "valgrindconfigwidget.h"
-#include <analyzerbase/analyzerconstants.h>
#include <analyzerbase/analyzermanager.h>
-#include <analyzerbase/analyzerrunconfigwidget.h>
-#include <analyzerbase/analyzerruncontrol.h>
-#include <analyzerbase/analyzerstartparameters.h>
-#include <analyzerbase/startremotedialog.h>
-#include <projectexplorer/localapplicationrunconfiguration.h>
-#include <projectexplorer/projectexplorer.h>
+#include <coreplugin/dialogs/ioptionspage.h>
+#include <coreplugin/actionmanager/actioncontainer.h>
+#include <coreplugin/actionmanager/actionmanager.h>
+#include <coreplugin/actionmanager/command.h>
+#include <coreplugin/coreconstants.h>
+#include <coreplugin/icontext.h>
+#include <coreplugin/icore.h>
+
+#include <cppeditor/cppeditorconstants.h>
#include <utils/hostosinfo.h>
-#include <utils/qtcassert.h>
-#include <QDebug>
-#include <QStringList>
#include <QtPlugin>
-#include <QAction>
+#include <QCoreApplication>
using namespace Analyzer;
-using namespace ProjectExplorer;
-
namespace Valgrind {
namespace Internal {
-static void startRemoteTool(IAnalyzerTool *tool)
+static ValgrindGlobalSettings *theGlobalSettings = 0;
+
+class ValgrindOptionsPage : public Core::IOptionsPage
{
- Q_UNUSED(tool);
- StartRemoteDialog dlg;
- if (dlg.exec() != QDialog::Accepted)
- return;
-
- AnalyzerStartParameters sp;
- sp.toolId = tool->id();
- sp.startMode = StartRemote;
- sp.connParams = dlg.sshParams();
- sp.debuggee = dlg.executable();
- sp.debuggeeArgs = dlg.arguments();
- sp.displayName = dlg.executable();
- sp.workingDirectory = dlg.workingDirectory();
-
- AnalyzerRunControl *rc = new AnalyzerRunControl(tool, sp, 0);
- //m_currentRunControl = rc;
- QObject::connect(AnalyzerManager::stopAction(), SIGNAL(triggered()), rc, SLOT(stopIt()));
-
- ProjectExplorerPlugin::instance()->startRunControl(rc, tool->runMode());
-}
+public:
+ explicit ValgrindOptionsPage()
+ {
+ setId(ANALYZER_VALGRIND_SETTINGS);
+ setDisplayName(QCoreApplication::translate("Valgrind::Internal::ValgrindOptionsPage", "Valgrind"));
+ setCategory("T.Analyzer");
+ setDisplayCategory(QCoreApplication::translate("Analyzer", "Analyzer"));
+ setCategoryIcon(QLatin1String(":/images/analyzer_category.png"));
+ }
+
+ QWidget *createPage(QWidget *parent) {
+ return new ValgrindConfigWidget(theGlobalSettings, parent, true);
+ }
+
+ void apply() {
+ theGlobalSettings->writeSettings();
+ }
+ void finish() {}
+};
+
+class ValgrindAction : public AnalyzerAction
+{
+public:
+ ValgrindAction() {}
+};
+
-void ValgrindPlugin::startValgrindTool(IAnalyzerTool *tool, StartMode mode)
+ValgrindPlugin::~ValgrindPlugin()
{
- if (mode == StartLocal)
- AnalyzerManager::startLocalTool(tool);
- if (mode == StartRemote)
- startRemoteTool(tool);
+ delete theGlobalSettings;
+ theGlobalSettings = 0;
}
bool ValgrindPlugin::initialize(const QStringList &, QString *)
{
- StartModes modes;
- if (!Utils::HostOsInfo::isWindowsHost())
- modes.append(StartMode(StartLocal));
- modes.append(StartMode(StartRemote));
-
- AnalyzerManager::addTool(new MemcheckTool(this), modes);
- AnalyzerManager::addTool(new CallgrindTool(this), modes);
+ theGlobalSettings = new ValgrindGlobalSettings();
+ theGlobalSettings->readSettings();
+
+ addAutoReleasedObject(new ValgrindOptionsPage());
+
+ m_memcheckTool = new MemcheckTool(this);
+ m_callgrindTool = new CallgrindTool(this);
+
+ ValgrindAction *action = 0;
+
+ QString callgrindToolTip = tr("Valgrind Function Profile uses the "
+ "\"callgrind\" tool to record function calls when a program runs.");
+
+ QString memcheckToolTip = tr("Valgrind Analyze Memory uses the "
+ "\"memcheck\" tool to find memory leaks");
+
+ if (!Utils::HostOsInfo::isWindowsHost()) {
+ action = new ValgrindAction;
+ action->setId("Memcheck.Local");
+ action->setTool(m_memcheckTool);
+ action->setText(tr("Valgrind Memory Analyzer"));
+ action->setToolTip(memcheckToolTip);
+ action->setMenuGroup(Constants::G_ANALYZER_TOOLS);
+ action->setStartMode(StartLocal);
+ action->setEnabled(false);
+ AnalyzerManager::addAction(action);
+
+ action = new ValgrindAction;
+ action->setId("Callgrind.Local");
+ action->setTool(m_callgrindTool);
+ action->setText(tr("Valgrind Function Profiler"));
+ action->setToolTip(callgrindToolTip);
+ action->setMenuGroup(Constants::G_ANALYZER_TOOLS);
+ action->setStartMode(StartLocal);
+ action->setEnabled(false);
+ AnalyzerManager::addAction(action);
+ }
+
+ action = new ValgrindAction;
+ action->setId("Memcheck.Remote");
+ action->setTool(m_memcheckTool);
+ action->setText(tr("Valgrind Memory Analyzer (Remote)"));
+ action->setToolTip(memcheckToolTip);
+ action->setMenuGroup(Constants::G_ANALYZER_REMOTE_TOOLS);
+ action->setStartMode(StartRemote);
+ AnalyzerManager::addAction(action);
+
+ action = new ValgrindAction;
+ action->setId("Callgrind.Remote");
+ action->setTool(m_callgrindTool);
+ action->setText(tr("Valgrind Function Profiler (Remote)"));
+ action->setToolTip(callgrindToolTip);
+ action->setMenuGroup(Constants::G_ANALYZER_REMOTE_TOOLS);
+ action->setStartMode(StartRemote);
+ AnalyzerManager::addAction(action);
addAutoReleasedObject(new ValgrindRunControlFactory());
return true;
}
+ValgrindGlobalSettings *ValgrindPlugin::globalSettings()
+{
+ return theGlobalSettings;
+}
+
+void ValgrindPlugin::extensionsInitialized()
+{
+ using namespace Core;
+
+ // If there is a CppEditor context menu add our own context menu actions.
+ if (ActionContainer *editorContextMenu =
+ ActionManager::actionContainer(CppEditor::Constants::M_CONTEXT)) {
+ Context analyzerContext = Context(Analyzer::Constants::C_ANALYZEMODE);
+ editorContextMenu->addSeparator(analyzerContext);
+
+ QAction *action = new QAction(tr("Profile Costs of this Function and its Callees"), this);
+ action->setIcon(QIcon(QLatin1String(Analyzer::Constants::ANALYZER_CONTROL_START_ICON)));
+ connect(action, SIGNAL(triggered()), m_callgrindTool, SLOT(handleShowCostsOfFunction()));
+ Command *cmd = ActionManager::registerAction(action, "Analyzer.Callgrind.ShowCostsOfFunction",
+ analyzerContext);
+ editorContextMenu->addAction(cmd);
+ cmd->setAttribute(Command::CA_Hide);
+ cmd->setAttribute(Command::CA_NonConfigurable);
+ }
+}
+
} // namespace Internal
} // namespace Valgrind
diff --git a/src/plugins/valgrind/valgrindplugin.h b/src/plugins/valgrind/valgrindplugin.h
index 28e24df3db..0ee4138c0a 100644
--- a/src/plugins/valgrind/valgrindplugin.h
+++ b/src/plugins/valgrind/valgrindplugin.h
@@ -37,6 +37,10 @@
namespace Valgrind {
namespace Internal {
+class ValgrindGlobalSettings;
+class MemcheckTool;
+class CallgrindTool;
+
class ValgrindPlugin : public ExtensionSystem::IPlugin
{
Q_OBJECT
@@ -44,11 +48,16 @@ class ValgrindPlugin : public ExtensionSystem::IPlugin
public:
ValgrindPlugin() {}
+ ~ValgrindPlugin();
+
+ bool initialize(const QStringList &arguments, QString *errorString);
+ void extensionsInitialized();
- virtual bool initialize(const QStringList &arguments, QString *errorString);
- virtual void extensionsInitialized() {}
+ static ValgrindGlobalSettings *globalSettings();
- static void startValgrindTool(Analyzer::IAnalyzerTool *tool, Analyzer::StartMode mode);
+private:
+ MemcheckTool *m_memcheckTool;
+ CallgrindTool *m_callgrindTool;
};
} // namespace Internal
diff --git a/src/plugins/valgrind/valgrindprocess.cpp b/src/plugins/valgrind/valgrindprocess.cpp
index 6fa61b288a..d112044e6c 100644
--- a/src/plugins/valgrind/valgrindprocess.cpp
+++ b/src/plugins/valgrind/valgrindprocess.cpp
@@ -35,6 +35,7 @@
#include <QFileInfo>
#include <utils/qtcassert.h>
+#include <utils/winutils.h>
#ifdef Q_OS_WIN
# include <qt_windows.h>
@@ -42,191 +43,213 @@
namespace Valgrind {
-ValgrindProcess::ValgrindProcess(QObject *parent)
- : QObject(parent)
+ValgrindProcess::ValgrindProcess(bool isLocal, const QSsh::SshConnectionParameters &sshParams,
+ QSsh::SshConnection *connection, QObject *parent)
+ : QObject(parent), m_isLocal(isLocal)
{
+ m_remote.m_params = sshParams;
+ m_remote.m_connection = connection;
+ m_remote.m_error = QProcess::UnknownError;
+ m_pid = 0;
}
-////////////////////////
-
-LocalValgrindProcess::LocalValgrindProcess(QObject *parent)
-: ValgrindProcess(parent)
+void ValgrindProcess::setProcessChannelMode(QProcess::ProcessChannelMode mode)
{
- connect(&m_process, SIGNAL(finished(int,QProcess::ExitStatus)),
- this, SIGNAL(finished(int,QProcess::ExitStatus)));
- connect(&m_process, SIGNAL(started()),
- this, SIGNAL(started()));
- connect(&m_process, SIGNAL(error(QProcess::ProcessError)),
- this, SIGNAL(error(QProcess::ProcessError)));
- connect(&m_process, SIGNAL(readyReadStandardError()),
- this, SLOT(readyReadStandardError()));
- connect(&m_process, SIGNAL(readyReadStandardOutput()),
- this, SLOT(readyReadStandardOutput()));
+ if (isLocal())
+ m_localProcess.setProcessChannelMode(mode);
+ ///TODO: remote support this by handling the mode internally
}
-void LocalValgrindProcess::setProcessChannelMode(QProcess::ProcessChannelMode mode)
+void ValgrindProcess::setWorkingDirectory(const QString &path)
{
- m_process.setProcessChannelMode(mode);
+ if (isLocal())
+ m_localProcess.setWorkingDirectory(path);
+ else
+ m_remote.m_workingDir = path;
}
-void LocalValgrindProcess::setWorkingDirectory(const QString &path)
+QString ValgrindProcess::workingDirectory() const
{
- m_process.setWorkingDirectory(path);
+ if (isLocal())
+ return m_localProcess.workingDirectory();
+ else
+ return m_remote.m_workingDir;
}
-QString LocalValgrindProcess::workingDirectory() const
+bool ValgrindProcess::isRunning() const
{
- return m_process.workingDirectory();
+ if (isLocal())
+ return m_localProcess.state() != QProcess::NotRunning;
+ else
+ return m_remote.m_process && m_remote.m_process->isRunning();
}
-bool LocalValgrindProcess::isRunning() const
+void ValgrindProcess::setEnvironment(const Utils::Environment &environment)
{
- return m_process.state() != QProcess::NotRunning;
+ if (isLocal())
+ m_localProcess.setEnvironment(environment);
+ ///TODO: remote anything that should/could be done here?
}
-void LocalValgrindProcess::setEnvironment(const Utils::Environment &environment)
+void ValgrindProcess::close()
{
- m_process.setEnvironment(environment);
+ if (isLocal()) {
+ m_localProcess.terminate();
+ } else {
+ QTC_ASSERT(m_remote.m_connection->state() == QSsh::SshConnection::Connected, return);
+ if (m_remote.m_process) {
+ if (m_pid) {
+ const QString killTemplate = QString::fromLatin1("kill -%2 %1" // kill
+ ).arg(m_pid);
+
+ 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_remote.m_connection->createRemoteProcess(remoteCall.toUtf8());
+ cleanup->start();
+ }
+ }
+ }
}
-void LocalValgrindProcess::close()
+void ValgrindProcess::run(const QString &valgrindExecutable, const QStringList &valgrindArguments,
+ const QString &debuggeeExecutable, const QString &debuggeeArguments)
{
- m_process.terminate();
+ Utils::QtcProcess::addArgs(&m_arguments, valgrindArguments);
+ Utils::QtcProcess::addArg(&m_arguments, debuggeeExecutable);
+ Utils::QtcProcess::addArgs(&m_arguments, debuggeeArguments);
+
+ if (isLocal()) {
+ connect(&m_localProcess, SIGNAL(finished(int,QProcess::ExitStatus)),
+ this, SIGNAL(finished(int,QProcess::ExitStatus)));
+ connect(&m_localProcess, SIGNAL(started()),
+ this, SIGNAL(started()));
+ connect(&m_localProcess, SIGNAL(error(QProcess::ProcessError)),
+ this, SIGNAL(error(QProcess::ProcessError)));
+ connect(&m_localProcess, SIGNAL(readyReadStandardError()),
+ this, SLOT(handleReadyReadStandardError()));
+ connect(&m_localProcess, SIGNAL(readyReadStandardOutput()),
+ this, SLOT(handleReadyReadStandardOutput()));
+
+ m_localProcess.setCommand(valgrindExecutable, m_arguments);
+ m_localProcess.start();
+ m_localProcess.waitForStarted();
+ m_pid = Utils::qPidToPid(m_localProcess.pid());
+ } else {
+ m_remote.m_valgrindExe = valgrindExecutable;
+ m_remote.m_debuggee = debuggeeExecutable;
+
+ // connect to host and wait for connection
+ if (!m_remote.m_connection)
+ m_remote.m_connection = new QSsh::SshConnection(m_remote.m_params, this);
+
+ if (m_remote.m_connection->state() != QSsh::SshConnection::Connected) {
+ connect(m_remote.m_connection, SIGNAL(connected()), this, SLOT(connected()));
+ connect(m_remote.m_connection, SIGNAL(error(QSsh::SshError)),
+ this, SLOT(handelError(QSsh::SshError)));
+ if (m_remote.m_connection->state() == QSsh::SshConnection::Unconnected)
+ m_remote.m_connection->connectToHost();
+ } else {
+ connected();
+ }
+ }
}
-void LocalValgrindProcess::run(const QString &valgrindExecutable, const QStringList &valgrindArguments,
- const QString &debuggeeExecutable, const QString &debuggeeArguments)
+QString ValgrindProcess::errorString() const
{
- QString arguments;
- Utils::QtcProcess::addArgs(&arguments, valgrindArguments);
-
- Utils::QtcProcess::addArg(&arguments, debuggeeExecutable);
- Utils::QtcProcess::addArgs(&arguments, debuggeeArguments);
-
- m_process.setCommand(valgrindExecutable, arguments);
- m_process.start();
- m_process.waitForStarted();
-#ifdef Q_OS_WIN
- m_pid = m_process.pid()->dwProcessId;
-#else
- m_pid = m_process.pid();
-#endif
+ if (isLocal())
+ return m_localProcess.errorString();
+ else
+ return m_remote.m_errorString;
}
-QString LocalValgrindProcess::errorString() const
+QProcess::ProcessError ValgrindProcess::error() const
{
- return m_process.errorString();
+ if (isLocal())
+ return m_localProcess.error();
+ else
+ return m_remote.m_error;
}
-QProcess::ProcessError LocalValgrindProcess::error() const
+void ValgrindProcess::handleError(QSsh::SshError error)
{
- return m_process.error();
+ if (isLocal()) {
+ } else {
+ switch (error) {
+ case QSsh::SshTimeoutError:
+ m_remote.m_error = QProcess::Timedout;
+ break;
+ default:
+ m_remote.m_error = QProcess::FailedToStart;
+ break;
+ }
+ }
+ m_remote.m_errorString = m_remote.m_connection->errorString();
+ emit this->error(m_remote.m_error);
}
-qint64 LocalValgrindProcess::pid() const
+qint64 ValgrindProcess::pid() const
{
return m_pid;
}
-void LocalValgrindProcess::readyReadStandardError()
+void ValgrindProcess::handleReadyReadStandardError()
{
- const QByteArray b = m_process.readAllStandardError();
+ QByteArray b;
+ if (isLocal())
+ b = m_localProcess.readAllStandardError();
+ else
+ b = m_remote.m_process->readAllStandardError();
if (!b.isEmpty())
emit processOutput(b, Utils::StdErrFormat);
}
-void LocalValgrindProcess::readyReadStandardOutput()
+void ValgrindProcess::handleReadyReadStandardOutput()
{
- const QByteArray b = m_process.readAllStandardOutput();
+ QByteArray b;
+ if (isLocal())
+ b = m_localProcess.readAllStandardOutput();
+ else
+ b = m_remote.m_process->readAllStandardOutput();
if (!b.isEmpty())
emit processOutput(b, Utils::StdOutFormat);
}
-////////////////////////
-
-RemoteValgrindProcess::RemoteValgrindProcess(const QSsh::SshConnectionParameters &sshParams,
- QObject *parent)
- : ValgrindProcess(parent)
- , m_params(sshParams)
- , m_connection(0)
- , m_error(QProcess::UnknownError)
- , m_pid(0)
-{}
-
-RemoteValgrindProcess::RemoteValgrindProcess(QSsh::SshConnection *connection, QObject *parent)
- : ValgrindProcess(parent)
- , m_params(connection->connectionParameters())
- , m_connection(connection)
- , m_error(QProcess::UnknownError)
- , m_pid(0)
-{}
-
-RemoteValgrindProcess::~RemoteValgrindProcess()
+/// Remote
+void ValgrindProcess::connected()
{
-}
-
-bool RemoteValgrindProcess::isRunning() const
-{
- return m_process && m_process->isRunning();
-}
-
-void RemoteValgrindProcess::run(const QString &valgrindExecutable, const QStringList &valgrindArguments,
- const QString &debuggeeExecutable, const QString &debuggeeArguments)
-{
- m_valgrindExe = valgrindExecutable;
- m_debuggee = debuggeeExecutable;
- m_debuggeeArgs = debuggeeArguments;
- m_valgrindArgs = valgrindArguments;
-
- // connect to host and wait for connection
- if (!m_connection)
- m_connection = new QSsh::SshConnection(m_params, this);
-
- if (m_connection->state() != QSsh::SshConnection::Connected) {
- connect(m_connection, SIGNAL(connected()), this, SLOT(connected()));
- connect(m_connection, SIGNAL(error(QSsh::SshError)),
- this, SLOT(error(QSsh::SshError)));
- if (m_connection->state() == QSsh::SshConnection::Unconnected)
- m_connection->connectToHost();
- } else {
- connected();
- }
-}
-
-void RemoteValgrindProcess::connected()
-{
- QTC_ASSERT(m_connection->state() == QSsh::SshConnection::Connected, return);
+ QTC_ASSERT(m_remote.m_connection->state() == QSsh::SshConnection::Connected, return);
// connected, run command
QString cmd;
- if (!m_workingDir.isEmpty())
- cmd += QString::fromLatin1("cd '%1' && ").arg(m_workingDir);
+ if (!m_remote.m_workingDir.isEmpty())
+ cmd += QString::fromLatin1("cd '%1' && ").arg(m_remote.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 + QLatin1Char(' ') + arguments;
+ cmd += m_remote.m_valgrindExe + QLatin1Char(' ') + m_arguments;
- m_process = m_connection->createRemoteProcess(cmd.toUtf8());
- connect(m_process.data(), SIGNAL(readyReadStandardError()), this, SLOT(standardError()));
- connect(m_process.data(), SIGNAL(readyReadStandardOutput()), this, SLOT(standardOutput()));
- connect(m_process.data(), SIGNAL(closed(int)),
+ m_remote.m_process = m_remote.m_connection->createRemoteProcess(cmd.toUtf8());
+ connect(m_remote.m_process.data(), SIGNAL(readyReadStandardError()),
+ this, SLOT(handleReadyReadStandardError()));
+ connect(m_remote.m_process.data(), SIGNAL(readyReadStandardOutput()),
+ this, SLOT(handleReadyReadStandardOutput()));
+ connect(m_remote.m_process.data(), SIGNAL(closed(int)),
this, SLOT(closed(int)));
- connect(m_process.data(), SIGNAL(started()),
+ connect(m_remote.m_process.data(), SIGNAL(started()),
this, SLOT(processStarted()));
- m_process->start();
+ m_remote.m_process->start();
}
-QSsh::SshConnection *RemoteValgrindProcess::connection() const
+
+QSsh::SshConnection *ValgrindProcess::connection() const
{
- return m_connection;
+ return m_remote.m_connection;
}
-void RemoteValgrindProcess::processStarted()
+void ValgrindProcess::processStarted()
{
- QTC_ASSERT(m_connection->state() == QSsh::SshConnection::Connected, return);
+ QTC_ASSERT(m_remote.m_connection->state() == QSsh::SshConnection::Connected, return);
// find out what PID our process has
@@ -237,7 +260,7 @@ void RemoteValgrindProcess::processStarted()
// hence we need to do something more complex...
// plain path to exe, m_valgrindExe contains e.g. env vars etc. pp.
- const QString proc = m_valgrindExe.split(QLatin1Char(' ')).last();
+ const QString proc = m_remote.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::fromLatin1("sleep 1; ps ax" // list all processes with aliased name
@@ -245,22 +268,24 @@ void RemoteValgrindProcess::processStarted()
" | 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());
+ ).arg(proc, QFileInfo(m_remote.m_debuggee).fileName());
- m_findPID = m_connection->createRemoteProcess(cmd.toUtf8());
- connect(m_findPID.data(), SIGNAL(readyReadStandardError()), this, SLOT(standardError()));
- connect(m_findPID.data(), SIGNAL(readyReadStandardOutput()), SLOT(findPIDOutputReceived()));
- m_findPID->start();
+ m_remote.m_findPID = m_remote.m_connection->createRemoteProcess(cmd.toUtf8());
+ connect(m_remote.m_findPID.data(), SIGNAL(readyReadStandardError()),
+ this, SLOT(handleReadyReadStandardError()));
+ connect(m_remote.m_findPID.data(), SIGNAL(readyReadStandardOutput()),
+ this, SLOT(findPIDOutputReceived()));
+ m_remote.m_findPID->start();
}
-void RemoteValgrindProcess::findPIDOutputReceived()
+void ValgrindProcess::findPIDOutputReceived()
{
bool ok;
- m_pid = m_findPID->readAllStandardOutput().trimmed().toLongLong(&ok);
+ m_pid = m_remote.m_findPID->readAllStandardOutput().trimmed().toLongLong(&ok);
if (!ok) {
m_pid = 0;
- m_errorString = tr("Could not determine remote PID.");
- m_error = QProcess::FailedToStart;
+ m_remote.m_errorString = tr("Could not determine remote PID.");
+ m_remote.m_error = QProcess::FailedToStart;
emit ValgrindProcess::error(QProcess::FailedToStart);
close();
} else {
@@ -268,99 +293,23 @@ void RemoteValgrindProcess::findPIDOutputReceived()
}
}
-void RemoteValgrindProcess::standardOutput()
-{
- emit processOutput(m_process->readAllStandardOutput(), Utils::StdOutFormat);
-}
-
-void RemoteValgrindProcess::standardError()
-{
- emit processOutput(m_process->readAllStandardError(), Utils::StdErrFormat);
-}
-
-void RemoteValgrindProcess::error(QSsh::SshError error)
-{
- switch (error) {
- case QSsh::SshTimeoutError:
- m_error = QProcess::Timedout;
- break;
- default:
- m_error = QProcess::FailedToStart;
- break;
- }
- m_errorString = m_connection->errorString();
- emit ValgrindProcess::error(m_error);
-}
-void RemoteValgrindProcess::close()
-{
- QTC_ASSERT(m_connection->state() == QSsh::SshConnection::Connected, return);
- if (m_process) {
- if (m_pid) {
- const QString killTemplate = QString::fromLatin1("kill -%2 %1" // kill
- ).arg(m_pid);
-
- 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());
- cleanup->start();
- }
- }
-}
+///////////
-void RemoteValgrindProcess::closed(int status)
+void ValgrindProcess::closed(int status)
{
- QTC_ASSERT(m_process, return);
+ QTC_ASSERT(m_remote.m_process, return);
- m_errorString = m_process->errorString();
+ m_remote.m_errorString = m_remote.m_process->errorString();
if (status == QSsh::SshRemoteProcess::FailedToStart) {
- m_error = QProcess::FailedToStart;
+ m_remote.m_error = QProcess::FailedToStart;
emit ValgrindProcess::error(QProcess::FailedToStart);
} else if (status == QSsh::SshRemoteProcess::NormalExit) {
- emit finished(m_process->exitCode(), QProcess::NormalExit);
+ emit finished(m_remote.m_process->exitCode(), QProcess::NormalExit);
} else if (status == QSsh::SshRemoteProcess::CrashExit) {
- m_error = QProcess::Crashed;
- emit finished(m_process->exitCode(), QProcess::CrashExit);
+ m_remote.m_error = QProcess::Crashed;
+ emit finished(m_remote.m_process->exitCode(), QProcess::CrashExit);
}
}
-QString RemoteValgrindProcess::errorString() const
-{
- return m_errorString;
-}
-
-QProcess::ProcessError RemoteValgrindProcess::error() const
-{
- return m_error;
-}
-
-void RemoteValgrindProcess::setEnvironment(const Utils::Environment &environment)
-{
- Q_UNUSED(environment);
- ///TODO: anything that should/could be done here?
-}
-
-void RemoteValgrindProcess::setProcessChannelMode(QProcess::ProcessChannelMode mode)
-{
- Q_UNUSED(mode);
- ///TODO: support this by handling the mode internally
-}
-
-void RemoteValgrindProcess::setWorkingDirectory(const QString &path)
-{
- m_workingDir = path;
-}
-
-QString RemoteValgrindProcess::workingDirectory() const
-{
- return m_workingDir;
-}
-
-qint64 RemoteValgrindProcess::pid() const
-{
- return m_pid;
-}
-
} // namespace Valgrind
diff --git a/src/plugins/valgrind/valgrindprocess.h b/src/plugins/valgrind/valgrindprocess.h
index 4d066e514c..319c4fa14a 100644
--- a/src/plugins/valgrind/valgrindprocess.h
+++ b/src/plugins/valgrind/valgrindprocess.h
@@ -38,130 +38,74 @@
namespace Valgrind {
+struct Remote {
+ QSsh::SshConnectionParameters m_params;
+ QSsh::SshConnection *m_connection;
+ QSsh::SshRemoteProcess::Ptr m_process;
+ QString m_workingDir;
+ QString m_valgrindExe;
+ QString m_debuggee;
+ QString m_errorString;
+ QProcess::ProcessError m_error;
+ QSsh::SshRemoteProcess::Ptr m_findPID;
+};
+
/**
- * Abstract process that can be subclassed to supply local and remote valgrind runs
+ * Process for supplying local and remote valgrind runs
*/
class ValgrindProcess : public QObject
{
Q_OBJECT
public:
- explicit ValgrindProcess(QObject *parent = 0);
+ ValgrindProcess(bool isLocal, const QSsh::SshConnectionParameters &sshParams,
+ QSsh::SshConnection *connection = 0, QObject *parent = 0);
- virtual bool isRunning() const = 0;
+ bool isRunning() const;
- virtual void run(const QString &valgrindExecutable, const QStringList &valgrindArguments,
- const QString &debuggeeExecutable, const QString &debuggeeArguments) = 0;
- virtual void close() = 0;
+ void run(const QString &valgrindExecutable, const QStringList &valgrindArguments,
+ const QString &debuggeeExecutable, const QString &debuggeeArguments);
+ void close();
- virtual QString errorString() const = 0;
- virtual QProcess::ProcessError error() const = 0;
+ QString errorString() const;
+ QProcess::ProcessError error() const;
- virtual void setProcessChannelMode(QProcess::ProcessChannelMode mode) = 0;
- virtual void setWorkingDirectory(const QString &path) = 0;
- virtual QString workingDirectory() const = 0;
- virtual void setEnvironment(const Utils::Environment &environment) = 0;
+ void setProcessChannelMode(QProcess::ProcessChannelMode mode);
+ void setWorkingDirectory(const QString &path);
+ QString workingDirectory() const;
+ void setEnvironment(const Utils::Environment &environment);
- virtual qint64 pid() const = 0;
+ qint64 pid() const;
+ QSsh::SshConnection *connection() const;
+ bool isLocal() const { return m_isLocal; }
signals:
void started();
void finished(int, QProcess::ExitStatus);
void error(QProcess::ProcessError);
void processOutput(const QByteArray &, Utils::OutputFormat format);
-};
-
-/**
- * Run valgrind on the local machine
- */
-class LocalValgrindProcess : public ValgrindProcess
-{
- Q_OBJECT
-
-public:
- explicit LocalValgrindProcess(QObject *parent = 0);
-
- virtual bool isRunning() const;
-
- virtual void run(const QString &valgrindExecutable, const QStringList &valgrindArguments,
- const QString &debuggeeExecutable, const QString &debuggeeArguments);
- virtual void close();
-
- virtual QString errorString() const;
- QProcess::ProcessError error() const;
-
- virtual void setProcessChannelMode(QProcess::ProcessChannelMode mode);
- virtual void setWorkingDirectory(const QString &path);
- virtual QString workingDirectory() const;
- virtual void setEnvironment(const Utils::Environment &environment);
-
- virtual qint64 pid() const;
private slots:
- void readyReadStandardError();
- void readyReadStandardOutput();
+ void handleReadyReadStandardError();
+ void handleReadyReadStandardOutput();
+ void handleError(QSsh::SshError);
-private:
- Utils::QtcProcess m_process;
- qint64 m_pid;
-};
-
-/**
- * Run valgrind on a remote machine via SSH
- */
-class RemoteValgrindProcess : public ValgrindProcess
-{
- Q_OBJECT
-
-public:
- explicit RemoteValgrindProcess(const QSsh::SshConnectionParameters &sshParams,
- QObject *parent = 0);
- explicit RemoteValgrindProcess(QSsh::SshConnection *connection,
- QObject *parent = 0);
- ~RemoteValgrindProcess();
-
- virtual bool isRunning() const;
-
- virtual void run(const QString &valgrindExecutable, const QStringList &valgrindArguments,
- const QString &debuggeeExecutable, const QString &debuggeeArguments);
- virtual void close();
-
- virtual QString errorString() const;
- QProcess::ProcessError error() const;
-
- virtual void setProcessChannelMode(QProcess::ProcessChannelMode mode);
- virtual void setWorkingDirectory(const QString &path);
- virtual QString workingDirectory() const;
- virtual void setEnvironment(const Utils::Environment &environment);
-
- virtual qint64 pid() const;
-
- QSsh::SshConnection *connection() const;
-
-private slots:
void closed(int);
void connected();
- void error(QSsh::SshError error);
void processStarted();
void findPIDOutputReceived();
- void standardOutput();
- void standardError();
private:
- QSsh::SshConnectionParameters m_params;
- QSsh::SshConnection *m_connection;
- QSsh::SshRemoteProcess::Ptr m_process;
- QString m_workingDir;
- QString m_valgrindExe;
- QStringList m_valgrindArgs;
- QString m_debuggee;
- QString m_debuggeeArgs;
- QString m_errorString;
- QProcess::ProcessError m_error;
+ Utils::QtcProcess m_localProcess;
qint64 m_pid;
- QSsh::SshRemoteProcess::Ptr m_findPID;
+
+ Remote m_remote;
+ QString m_arguments;
+ bool m_isLocal;
};
+
+
} // namespace Valgrind
#endif // VALGRINDPROCESS_H
diff --git a/src/plugins/valgrind/valgrindruncontrolfactory.cpp b/src/plugins/valgrind/valgrindruncontrolfactory.cpp
index 9e56e21cf8..fc2335bb0f 100644
--- a/src/plugins/valgrind/valgrindruncontrolfactory.cpp
+++ b/src/plugins/valgrind/valgrindruncontrolfactory.cpp
@@ -28,15 +28,28 @@
****************************************************************************/
#include "valgrindruncontrolfactory.h"
+#include "valgrindsettings.h"
+#include "valgrindplugin.h"
#include <analyzerbase/ianalyzertool.h>
#include <analyzerbase/analyzermanager.h>
#include <analyzerbase/analyzerstartparameters.h>
#include <analyzerbase/analyzerruncontrol.h>
-#include <analyzerbase/analyzersettings.h>
+#include <analyzerbase/analyzerrunconfigwidget.h>
+
+#include <remotelinux/remotelinuxrunconfiguration.h>
+
+#include <debugger/debuggerrunconfigurationaspect.h>
+#include <projectexplorer/environmentaspect.h>
+#include <projectexplorer/localapplicationrunconfiguration.h>
+#include <projectexplorer/kitinformation.h>
+#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/target.h>
#include <utils/qtcassert.h>
+#include <QTcpServer>
+
using namespace Analyzer;
using namespace ProjectExplorer;
@@ -50,36 +63,80 @@ ValgrindRunControlFactory::ValgrindRunControlFactory(QObject *parent) :
bool ValgrindRunControlFactory::canRun(RunConfiguration *runConfiguration, RunMode mode) const
{
- if (mode != CallgrindRunMode && mode != MemcheckRunMode)
- return false;
- IAnalyzerTool *tool = AnalyzerManager::toolFromRunMode(mode);
- if (tool)
- return tool->canRun(runConfiguration, mode);
- return false;
+ Q_UNUSED(runConfiguration);
+ return mode == CallgrindRunMode || mode == MemcheckRunMode;
}
RunControl *ValgrindRunControlFactory::create(RunConfiguration *runConfiguration, RunMode mode, QString *errorMessage)
{
- IAnalyzerTool *tool = AnalyzerManager::toolFromRunMode(mode);
- if (!tool) {
- if (errorMessage)
- *errorMessage = tr("No analyzer tool selected"); // never happens
- return 0;
+ Q_UNUSED(errorMessage);
+
+ AnalyzerStartParameters sp;
+ sp.displayName = runConfiguration->displayName();
+ sp.runMode = mode;
+ if (LocalApplicationRunConfiguration *rc1 =
+ qobject_cast<LocalApplicationRunConfiguration *>(runConfiguration)) {
+ EnvironmentAspect *aspect = runConfiguration->extraAspect<EnvironmentAspect>();
+ if (aspect)
+ sp.environment = aspect->environment();
+ sp.workingDirectory = rc1->workingDirectory();
+ sp.debuggee = rc1->executable();
+ sp.debuggeeArgs = rc1->commandLineArguments();
+ const IDevice::ConstPtr device =
+ DeviceKitInformation::device(runConfiguration->target()->kit());
+ QTC_ASSERT(device, return 0);
+ QTC_ASSERT(device->type() == ProjectExplorer::Constants::DESKTOP_DEVICE_TYPE, return 0);
+ QTcpServer server;
+ if (!server.listen(QHostAddress::LocalHost) && !server.listen(QHostAddress::LocalHostIPv6)) {
+ qWarning() << "Cannot open port on host for profiling.";
+ return 0;
+ }
+ sp.connParams.host = server.serverAddress().toString();
+ sp.connParams.port = server.serverPort();
+ sp.startMode = StartLocal;
+ } else if (RemoteLinux::RemoteLinuxRunConfiguration *rc2 =
+ qobject_cast<RemoteLinux::RemoteLinuxRunConfiguration *>(runConfiguration)) {
+ sp.startMode = StartRemote;
+ sp.debuggee = rc2->remoteExecutableFilePath();
+ sp.connParams = DeviceKitInformation::device(rc2->target()->kit())->sshParameters();
+ sp.debuggeeArgs = rc2->arguments().join(QLatin1String(" "));
+ } else {
+ QTC_ASSERT(false, return 0);
}
- QTC_ASSERT(canRun(runConfiguration, mode), return 0);
+ return AnalyzerManager::createRunControl(sp, runConfiguration);
+}
- AnalyzerStartParameters sp = tool->createStartParameters(runConfiguration, mode);
- sp.toolId = tool->id();
- AnalyzerRunControl *rc = new AnalyzerRunControl(tool, sp, runConfiguration);
- return rc;
-}
+class ValgrindRunConfigurationAspect : public IRunConfigurationAspect
+{
+public:
+ ValgrindRunConfigurationAspect(RunConfiguration *parent)
+ : IRunConfigurationAspect(parent)
+ {
+ setProjectSettings(new ValgrindProjectSettings());
+ setGlobalSettings(ValgrindPlugin::globalSettings());
+ setId(ANALYZER_VALGRIND_SETTINGS);
+ setDisplayName(QCoreApplication::translate("Valgrind::Internal::ValgrindRunConfigurationAspect", "Valgrind Settings"));
+ setUsingGlobalSettings(true);
+ resetProjectToGlobalSettings();
+ }
+
+ IRunConfigurationAspect *create(RunConfiguration *parent) const
+ {
+ return new ValgrindRunConfigurationAspect(parent);
+ }
+
+ RunConfigWidget *createConfigurationWidget()
+ {
+ return new Analyzer::AnalyzerRunConfigWidget(this);
+
+ }
+};
IRunConfigurationAspect *ValgrindRunControlFactory::createRunConfigurationAspect(RunConfiguration *rc)
{
- Q_UNUSED(rc);
- return new AnalyzerRunConfigurationAspect;
+ return new ValgrindRunConfigurationAspect(rc);
}
} // namespace Internal
diff --git a/src/plugins/valgrind/valgrindrunner.cpp b/src/plugins/valgrind/valgrindrunner.cpp
index 55e2a26faa..dfc6392445 100644
--- a/src/plugins/valgrind/valgrindrunner.cpp
+++ b/src/plugins/valgrind/valgrindrunner.cpp
@@ -216,10 +216,7 @@ void ValgrindRunner::waitForFinished() const
bool ValgrindRunner::start()
{
- if (d->startMode == Analyzer::StartLocal)
- d->run(new LocalValgrindProcess(this));
- else if (d->startMode == Analyzer::StartRemote)
- d->run(new RemoteValgrindProcess(d->connParams, this));
+ d->run(new ValgrindProcess(d->startMode == Analyzer::StartLocal, d->connParams, 0, this));
return true;
}
diff --git a/src/plugins/valgrind/valgrindsettings.cpp b/src/plugins/valgrind/valgrindsettings.cpp
index 7d89a79e8e..8a33ce1b26 100644
--- a/src/plugins/valgrind/valgrindsettings.cpp
+++ b/src/plugins/valgrind/valgrindsettings.cpp
@@ -29,6 +29,7 @@
****************************************************************************/
#include "valgrindsettings.h"
+#include "valgrindplugin.h"
#include "valgrindconfigwidget.h"
#include <coreplugin/icore.h>
@@ -42,7 +43,10 @@
using namespace Analyzer;
const char numCallersC[] = "Analyzer.Valgrind.NumCallers";
+const char leakCheckOnFinishC[] = "Analyzer.Valgrind.LeakCheckOnFinish";
+const char showReachableC[] = "Analyzer.Valgrind.ShowReachable";
const char trackOriginsC[] = "Analyzer.Valgrind.TrackOrigins";
+const char selfModifyingCodeDetectionC[] = "Analyzer.Valgrind.SelfModifyingCodeDetection";
const char suppressionFilesC[] = "Analyzer.Valgrind.SupressionFiles";
const char removedSuppressionFilesC[] = "Analyzer.Valgrind.RemovedSuppressionFiles";
const char addedSuppressionFilesC[] = "Analyzer.Valgrind.AddedSuppressionFiles";
@@ -75,41 +79,26 @@ namespace Internal {
//
//////////////////////////////////////////////////////////////////
-QVariantMap ValgrindBaseSettings::defaults() const
+/**
+ * Utility function to set @p val if @p key is present in @p map.
+ */
+template <typename T> void setIfPresent(const QVariantMap &map, const QString &key, T *val)
{
- QVariantMap map;
-
- // General
- map.insert(QLatin1String(valgrindExeC), QLatin1String("valgrind"));
-
- // Memcheck
- map.insert(QLatin1String(numCallersC), 25);
- map.insert(QLatin1String(trackOriginsC), true);
- map.insert(QLatin1String(filterExternalIssuesC), true);
- QVariantList defaultErrorKinds;
- for (int i = 0; i < Valgrind::XmlProtocol::MemcheckErrorKindCount; ++i)
- defaultErrorKinds << i;
- map.insert(QLatin1String(visibleErrorKindsC), defaultErrorKinds);
-
- // Callgrind
- map.insert(QLatin1String(callgrindEnableCacheSimC), false);
- map.insert(QLatin1String(callgrindEnableBranchSimC), false);
- map.insert(QLatin1String(callgrindCollectSystimeC), false);
- map.insert(QLatin1String(callgrindCollectBusEventsC), false);
- map.insert(QLatin1String(callgrindEnableEventToolTipsC), true);
- map.insert(QLatin1String(callgrindMinimumCostRatioC), 0.01);
- map.insert(QLatin1String(callgrindVisualisationMinimumCostRatioC), 10.0);
-
- return map;
+ if (map.contains(key))
+ *val = map.value(key).template value<T>();
}
void ValgrindBaseSettings::fromMap(const QVariantMap &map)
{
// General
setIfPresent(map, QLatin1String(valgrindExeC), &m_valgrindExecutable);
+ setIfPresent(map, QLatin1String(selfModifyingCodeDetectionC),
+ (int*) &m_selfModifyingCodeDetection);
// Memcheck
setIfPresent(map, QLatin1String(numCallersC), &m_numCallers);
+ setIfPresent(map, QLatin1String(leakCheckOnFinishC), (int*) &m_leakCheckOnFinish);
+ setIfPresent(map, QLatin1String(showReachableC), &m_showReachable);
setIfPresent(map, QLatin1String(trackOriginsC), &m_trackOrigins);
setIfPresent(map, QLatin1String(filterExternalIssuesC), &m_filterExternalIssues);
if (map.contains(QLatin1String(visibleErrorKindsC))) {
@@ -131,15 +120,16 @@ void ValgrindBaseSettings::fromMap(const QVariantMap &map)
emit changed();
}
-QVariantMap ValgrindBaseSettings::toMap() const
+void ValgrindBaseSettings::toMap(QVariantMap &map) const
{
- QVariantMap map;
-
// General
map.insert(QLatin1String(valgrindExeC), m_valgrindExecutable);
+ map.insert(QLatin1String(selfModifyingCodeDetectionC), m_selfModifyingCodeDetection);
// Memcheck
map.insert(QLatin1String(numCallersC), m_numCallers);
+ map.insert(QLatin1String(leakCheckOnFinishC), m_leakCheckOnFinish);
+ map.insert(QLatin1String(showReachableC), m_showReachable);
map.insert(QLatin1String(trackOriginsC), m_trackOrigins);
map.insert(QLatin1String(filterExternalIssuesC), m_filterExternalIssues);
QVariantList errorKinds;
@@ -156,7 +146,6 @@ QVariantMap ValgrindBaseSettings::toMap() const
map.insert(QLatin1String(callgrindMinimumCostRatioC), m_minimumInclusiveCostRatio);
map.insert(QLatin1String(callgrindVisualisationMinimumCostRatioC),
m_visualisationMinimumInclusiveCostRatio);
- return map;
}
void ValgrindBaseSettings::setValgrindExecutable(const QString &valgrindExecutable)
@@ -167,19 +156,22 @@ void ValgrindBaseSettings::setValgrindExecutable(const QString &valgrindExecutab
}
}
-QString ValgrindBaseSettings::valgrindExecutable() const
+void ValgrindBaseSettings::setSelfModifyingCodeDetection(int smcDetection)
{
- return m_valgrindExecutable;
+ if (m_selfModifyingCodeDetection != smcDetection) {
+ m_selfModifyingCodeDetection = (SelfModifyingCodeDetection) smcDetection;
+ emit selfModifyingCodeDetectionChanged(smcDetection);
+ }
}
-Core::Id ValgrindBaseSettings::id() const
+QString ValgrindBaseSettings::valgrindExecutable() const
{
- return "Analyzer.Valgrind.Settings";
+ return m_valgrindExecutable;
}
-QString ValgrindBaseSettings::displayName() const
+ValgrindBaseSettings::SelfModifyingCodeDetection ValgrindBaseSettings::selfModifyingCodeDetection() const
{
- return tr("Valgrind");
+ return m_selfModifyingCodeDetection;
}
void ValgrindBaseSettings::setNumCallers(int numCallers)
@@ -190,6 +182,22 @@ void ValgrindBaseSettings::setNumCallers(int numCallers)
}
}
+void ValgrindBaseSettings::setLeakCheckOnFinish(int leakCheckOnFinish)
+{
+ if (m_leakCheckOnFinish != leakCheckOnFinish) {
+ m_leakCheckOnFinish = (LeakCheckOnFinish) leakCheckOnFinish;
+ emit leakCheckOnFinishChanged(leakCheckOnFinish);
+ }
+}
+
+void ValgrindBaseSettings::setShowReachable(bool showReachable)
+{
+ if (m_showReachable != showReachable) {
+ m_showReachable = showReachable;
+ emit showReachableChanged(showReachable);
+ }
+}
+
void ValgrindBaseSettings::setTrackOrigins(bool trackOrigins)
{
if (m_trackOrigins != trackOrigins) {
@@ -286,25 +294,14 @@ void ValgrindBaseSettings::setVisualisationMinimumInclusiveCostRatio(
//
//////////////////////////////////////////////////////////////////
-QWidget *ValgrindGlobalSettings::createConfigWidget(QWidget *parent)
+ValgrindGlobalSettings::ValgrindGlobalSettings()
{
- return new ValgrindConfigWidget(this, parent, true);
+ readSettings();
}
-QVariantMap ValgrindGlobalSettings::defaults() const
+QWidget *ValgrindGlobalSettings::createConfigWidget(QWidget *parent)
{
- QVariantMap map = ValgrindBaseSettings::defaults();
-
- // Memcheck
- map.insert(QLatin1String(suppressionFilesC), QStringList());
- map.insert(QLatin1String(lastSuppressionDirectoryC), QString());
- map.insert(QLatin1String(lastSuppressionHistoryC), QStringList());
-
- // Callgrind
- map.insert(QLatin1String(callgrindCostFormatC), CostDelegate::FormatRelative);
- map.insert(QLatin1String(callgrindCycleDetectionC), true);
-
- return map;
+ return new ValgrindConfigWidget(this, parent, true);
}
void ValgrindGlobalSettings::fromMap(const QVariantMap &map)
@@ -324,16 +321,9 @@ void ValgrindGlobalSettings::fromMap(const QVariantMap &map)
setIfPresent(map, QLatin1String(callgrindShortenTemplates), &m_shortenTemplates);
}
-AbstractAnalyzerSubConfig *ValgrindGlobalSettings::clone()
+void ValgrindGlobalSettings::toMap(QVariantMap &map) const
{
- ValgrindGlobalSettings *other = new ValgrindGlobalSettings;
- other->fromMap(toMap());
- return other;
-}
-
-QVariantMap ValgrindGlobalSettings::toMap() const
-{
- QVariantMap map = ValgrindBaseSettings::toMap();
+ ValgrindBaseSettings::toMap(map);
// Memcheck
map.insert(QLatin1String(suppressionFilesC), m_suppressionFiles);
@@ -344,8 +334,6 @@ QVariantMap ValgrindGlobalSettings::toMap() const
map.insert(QLatin1String(callgrindCostFormatC), m_costFormat);
map.insert(QLatin1String(callgrindCycleDetectionC), m_detectCycles);
map.insert(QLatin1String(callgrindShortenTemplates), m_shortenTemplates);
-
- return map;
}
//
@@ -390,6 +378,65 @@ void ValgrindGlobalSettings::setLastSuppressionDialogHistory(const QStringList &
m_lastSuppressionHistory = history;
}
+static const char groupC[] = "Analyzer";
+
+void ValgrindGlobalSettings::readSettings()
+{
+ QVariantMap defaults;
+
+ // General
+ defaults.insert(QLatin1String(valgrindExeC), QLatin1String("valgrind"));
+ defaults.insert(QLatin1String(selfModifyingCodeDetectionC), DetectSmcStackOnly);
+
+ // Memcheck
+ defaults.insert(QLatin1String(numCallersC), 25);
+ defaults.insert(QLatin1String(leakCheckOnFinishC), LeakCheckOnFinishSummaryOnly);
+ defaults.insert(QLatin1String(showReachableC), false);
+ defaults.insert(QLatin1String(trackOriginsC), true);
+ defaults.insert(QLatin1String(filterExternalIssuesC), true);
+ QVariantList defaultErrorKinds;
+ for (int i = 0; i < Valgrind::XmlProtocol::MemcheckErrorKindCount; ++i)
+ defaultErrorKinds << i;
+ defaults.insert(QLatin1String(visibleErrorKindsC), defaultErrorKinds);
+
+ defaults.insert(QLatin1String(suppressionFilesC), QStringList());
+ defaults.insert(QLatin1String(lastSuppressionDirectoryC), QString());
+ defaults.insert(QLatin1String(lastSuppressionHistoryC), QStringList());
+
+ // Callgrind
+ defaults.insert(QLatin1String(callgrindEnableCacheSimC), false);
+ defaults.insert(QLatin1String(callgrindEnableBranchSimC), false);
+ defaults.insert(QLatin1String(callgrindCollectSystimeC), false);
+ defaults.insert(QLatin1String(callgrindCollectBusEventsC), false);
+ defaults.insert(QLatin1String(callgrindEnableEventToolTipsC), true);
+ defaults.insert(QLatin1String(callgrindMinimumCostRatioC), 0.01);
+ defaults.insert(QLatin1String(callgrindVisualisationMinimumCostRatioC), 10.0);
+
+ defaults.insert(QLatin1String(callgrindCostFormatC), CostDelegate::FormatRelative);
+ defaults.insert(QLatin1String(callgrindCycleDetectionC), true);
+
+ // Read stored values
+ QSettings *settings = Core::ICore::settings();
+ settings->beginGroup(QLatin1String(groupC));
+ QVariantMap map = defaults;
+ for (QVariantMap::ConstIterator it = defaults.constBegin(); it != defaults.constEnd(); ++it)
+ map.insert(it.key(), settings->value(it.key(), it.value()));
+ settings->endGroup();
+
+ fromMap(map);
+}
+
+void ValgrindGlobalSettings::writeSettings() const
+{
+ QSettings *settings = Core::ICore::settings();
+ settings->beginGroup(QLatin1String(groupC));
+ QVariantMap map;
+ toMap(map);
+ for (QVariantMap::ConstIterator it = map.begin(); it != map.end(); ++it)
+ settings->setValue(it.key(), it.value());
+ settings->endGroup();
+}
+
//
// Callgrind
//
@@ -401,7 +448,7 @@ CostDelegate::CostFormat ValgrindGlobalSettings::costFormat() const
void ValgrindGlobalSettings::setCostFormat(CostDelegate::CostFormat format)
{
m_costFormat = format;
- AnalyzerGlobalSettings::instance()->writeSettings();
+ writeSettings();
}
bool ValgrindGlobalSettings::detectCycles() const
@@ -412,7 +459,7 @@ bool ValgrindGlobalSettings::detectCycles() const
void ValgrindGlobalSettings::setDetectCycles(bool on)
{
m_detectCycles = on;
- AnalyzerGlobalSettings::instance()->writeSettings();
+ writeSettings();
}
bool ValgrindGlobalSettings::shortenTemplates() const
@@ -423,15 +470,9 @@ bool ValgrindGlobalSettings::shortenTemplates() const
void ValgrindGlobalSettings::setShortenTemplates(bool on)
{
m_shortenTemplates = on;
- AnalyzerGlobalSettings::instance()->writeSettings();
+ writeSettings();
}
-ValgrindGlobalSettings *globalValgrindSettings()
-{
- ValgrindGlobalSettings *ret = AnalyzerGlobalSettings::instance()->subConfig<ValgrindGlobalSettings>();
- QTC_ASSERT(ret, return 0);
- return ret;
-}
//////////////////////////////////////////////////////////////////
//
@@ -444,17 +485,6 @@ QWidget *ValgrindProjectSettings::createConfigWidget(QWidget *parent)
return new ValgrindConfigWidget(this, parent, false);
}
-QVariantMap ValgrindProjectSettings::defaults() const
-{
- QVariantMap map = ValgrindBaseSettings::defaults();
-
- // Memcheck
- map.insert(QLatin1String(addedSuppressionFilesC), QStringList());
- map.insert(QLatin1String(removedSuppressionFilesC), QStringList());
-
- return map;
-}
-
void ValgrindProjectSettings::fromMap(const QVariantMap &map)
{
ValgrindBaseSettings::fromMap(map);
@@ -464,22 +494,13 @@ void ValgrindProjectSettings::fromMap(const QVariantMap &map)
setIfPresent(map, QLatin1String(removedSuppressionFilesC), &m_disabledGlobalSuppressionFiles);
}
-AbstractAnalyzerSubConfig *ValgrindProjectSettings::clone()
+void ValgrindProjectSettings::toMap(QVariantMap &map) const
{
- ValgrindProjectSettings *other = new ValgrindProjectSettings;
- other->fromMap(toMap());
- return other;
-}
-
-QVariantMap ValgrindProjectSettings::toMap() const
-{
- QVariantMap map = ValgrindBaseSettings::toMap();
+ ValgrindBaseSettings::toMap(map);
// Memcheck
map.insert(QLatin1String(addedSuppressionFilesC), m_addedSuppressionFiles);
map.insert(QLatin1String(removedSuppressionFilesC), m_disabledGlobalSuppressionFiles);
-
- return map;
}
//
@@ -488,7 +509,7 @@ QVariantMap ValgrindProjectSettings::toMap() const
void ValgrindProjectSettings::addSuppressionFiles(const QStringList &suppressions)
{
- QStringList globalSuppressions = globalValgrindSettings()->suppressionFiles();
+ QStringList globalSuppressions = ValgrindPlugin::globalSettings()->suppressionFiles();
foreach (const QString &s, suppressions) {
if (m_addedSuppressionFiles.contains(s))
continue;
@@ -500,7 +521,7 @@ void ValgrindProjectSettings::addSuppressionFiles(const QStringList &suppression
void ValgrindProjectSettings::removeSuppressionFiles(const QStringList &suppressions)
{
- QStringList globalSuppressions = globalValgrindSettings()->suppressionFiles();
+ QStringList globalSuppressions = ValgrindPlugin::globalSettings()->suppressionFiles();
foreach (const QString &s, suppressions) {
m_addedSuppressionFiles.removeAll(s);
if (globalSuppressions.contains(s))
@@ -510,7 +531,7 @@ void ValgrindProjectSettings::removeSuppressionFiles(const QStringList &suppress
QStringList ValgrindProjectSettings::suppressionFiles() const
{
- QStringList ret = globalValgrindSettings()->suppressionFiles();
+ QStringList ret = ValgrindPlugin::globalSettings()->suppressionFiles();
foreach (const QString &s, m_disabledGlobalSuppressionFiles)
ret.removeAll(s);
ret.append(m_addedSuppressionFiles);
diff --git a/src/plugins/valgrind/valgrindsettings.h b/src/plugins/valgrind/valgrindsettings.h
index b7d56d06b8..df03c173f5 100644
--- a/src/plugins/valgrind/valgrindsettings.h
+++ b/src/plugins/valgrind/valgrindsettings.h
@@ -31,8 +31,8 @@
#ifndef ANALYZER_INTERNAL_VALGRINDSETTINGS_H
#define ANALYZER_INTERNAL_VALGRINDSETTINGS_H
-#include <analyzerbase/analyzersettings.h>
#include "callgrindcostdelegate.h"
+#include <projectexplorer/runconfiguration.h>
#include <QObject>
#include <QString>
@@ -41,22 +41,33 @@
namespace Valgrind {
namespace Internal {
+const char ANALYZER_VALGRIND_SETTINGS[] = "Analyzer.Valgrind.Settings";
+
/**
* Valgrind settings shared for global and per-project.
*/
-class ValgrindBaseSettings : public Analyzer::AbstractAnalyzerSubConfig
+class ValgrindBaseSettings : public ProjectExplorer::ISettingsAspect
{
Q_OBJECT
public:
- ValgrindBaseSettings() {}
+ enum SelfModifyingCodeDetection {
+ DetectSmcNo,
+ DetectSmcStackOnly,
+ DetectSmcEverywhere,
+ DetectSmcEverywhereButFile
+ };
+
+ enum LeakCheckOnFinish {
+ LeakCheckOnFinishNo,
+ LeakCheckOnFinishSummaryOnly,
+ LeakCheckOnFinishYes
+ };
- virtual QVariantMap toMap() const;
- virtual QVariantMap defaults() const;
- virtual void fromMap(const QVariantMap &map);
+ ValgrindBaseSettings() {}
- virtual Core::Id id() const;
- virtual QString displayName() const;
+ void toMap(QVariantMap &map) const;
+ void fromMap(const QVariantMap &map);
signals:
void changed(); // sent when multiple values have changed simulatenously (e.g. fromMap)
@@ -66,15 +77,19 @@ signals:
*/
public:
QString valgrindExecutable() const;
+ SelfModifyingCodeDetection selfModifyingCodeDetection() const;
public slots:
void setValgrindExecutable(const QString &);
+ void setSelfModifyingCodeDetection(int);
signals:
void valgrindExecutableChanged(const QString &);
+ void selfModifyingCodeDetectionChanged(int);
private:
QString m_valgrindExecutable;
+ SelfModifyingCodeDetection m_selfModifyingCodeDetection;
/**
@@ -82,6 +97,8 @@ private:
*/
public:
int numCallers() const { return m_numCallers; }
+ LeakCheckOnFinish leakCheckOnFinish() const { return m_leakCheckOnFinish; }
+ bool showReachable() const { return m_showReachable; }
bool trackOrigins() const { return m_trackOrigins; }
bool filterExternalIssues() const { return m_filterExternalIssues; }
QList<int> visibleErrorKinds() const { return m_visibleErrorKinds; }
@@ -92,12 +109,16 @@ public:
public slots:
void setNumCallers(int);
+ void setLeakCheckOnFinish(int);
+ void setShowReachable(bool);
void setTrackOrigins(bool);
void setFilterExternalIssues(bool);
void setVisibleErrorKinds(const QList<int> &);
signals:
void numCallersChanged(int);
+ void leakCheckOnFinishChanged(int);
+ void showReachableChanged(bool);
void trackOriginsChanged(bool);
void filterExternalIssuesChanged(bool);
void visibleErrorKindsChanged(const QList<int> &);
@@ -106,6 +127,8 @@ signals:
protected:
int m_numCallers;
+ LeakCheckOnFinish m_leakCheckOnFinish;
+ bool m_showReachable;
bool m_trackOrigins;
bool m_filterExternalIssues;
QList<int> m_visibleErrorKinds;
@@ -167,13 +190,13 @@ class ValgrindGlobalSettings : public ValgrindBaseSettings
Q_OBJECT
public:
- ValgrindGlobalSettings() {}
+ ValgrindGlobalSettings();
QWidget *createConfigWidget(QWidget *parent);
- QVariantMap toMap() const;
- QVariantMap defaults() const;
+ void toMap(QVariantMap &map) const;
void fromMap(const QVariantMap &map);
- virtual AbstractAnalyzerSubConfig *clone();
+ ISettingsAspect *create() const { return new ValgrindGlobalSettings; }
+
/*
* Global memcheck settings
@@ -191,6 +214,9 @@ public:
void setLastSuppressionDialogHistory(const QStringList &history);
QStringList lastSuppressionDialogHistory() const;
+ void writeSettings() const;
+ void readSettings();
+
private:
QStringList m_suppressionFiles;
QString m_lastSuppressionDirectory;
@@ -228,10 +254,9 @@ public:
ValgrindProjectSettings() {}
QWidget *createConfigWidget(QWidget *parent);
- QVariantMap toMap() const;
- QVariantMap defaults() const;
+ void toMap(QVariantMap &map) const;
void fromMap(const QVariantMap &map);
- virtual AbstractAnalyzerSubConfig *clone();
+ ISettingsAspect *create() const { return new ValgrindProjectSettings; }
/**
* 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 041ecd07e6..fd1f008b4c 100644
--- a/src/plugins/valgrind/valgrindtool.cpp
+++ b/src/plugins/valgrind/valgrindtool.cpp
@@ -1,7 +1,8 @@
-/**************************************************************************
+/****************************************************************************
**
-** Copyright (C) 2013 Kläralvdalens Datakonsult AB, a KDAB Group company.
-** Contact: Kläralvdalens Datakonsult AB (info@kdab.com)
+** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+** Author: Nicolas Arnaud-Cormos, KDAB (nicolas.arnaud-cormos@kdab.com)
**
** This file is part of Qt Creator.
**
@@ -29,75 +30,151 @@
#include "valgrindtool.h"
-#include <remotelinux/remotelinuxrunconfiguration.h>
+#include <analyzerbase/analyzermanager.h>
+#include <analyzerbase/analyzerruncontrol.h>
+#include <analyzerbase/startremotedialog.h>
+
+#include <coreplugin/icore.h>
+#include <coreplugin/imode.h>
+#include <coreplugin/modemanager.h>
-#include <debugger/debuggerrunconfigurationaspect.h>
-#include <projectexplorer/environmentaspect.h>
-#include <projectexplorer/localapplicationrunconfiguration.h>
-#include <projectexplorer/kitinformation.h>
#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/project.h>
+#include <projectexplorer/buildconfiguration.h>
+#include <projectexplorer/session.h>
#include <projectexplorer/target.h>
#include <utils/qtcassert.h>
+#include <utils/checkablemessagebox.h>
-#include <QTcpServer>
+#include <QAction>
+#include <QDialog>
+#include <QDialogButtonBox>
+#include <QSettings>
+using namespace Analyzer;
+using namespace Core;
using namespace ProjectExplorer;
-using namespace RemoteLinux;
namespace Valgrind {
namespace Internal {
-ValgrindTool::ValgrindTool(QObject *parent) :
- Analyzer::IAnalyzerTool(parent)
-{
-}
+ValgrindTool::ValgrindTool(QObject *parent)
+ : IAnalyzerTool(parent)
+{}
-bool ValgrindTool::canRun(RunConfiguration *, RunMode mode) const
+static bool buildTypeAccepted(IAnalyzerTool::ToolMode toolMode,
+ BuildConfiguration::BuildType buildType)
{
- return mode == runMode();
+ if (toolMode == IAnalyzerTool::AnyMode)
+ return true;
+ if (buildType == BuildConfiguration::Unknown)
+ return true;
+ if (buildType == BuildConfiguration::Debug
+ && toolMode == IAnalyzerTool::DebugMode)
+ return true;
+ if (buildType == BuildConfiguration::Release
+ && toolMode == IAnalyzerTool::ReleaseMode)
+ return true;
+ return false;
}
-Analyzer::AnalyzerStartParameters ValgrindTool::createStartParameters(
- RunConfiguration *runConfiguration, RunMode mode) const
+static void startLocalTool(IAnalyzerTool *tool)
{
- Q_UNUSED(mode);
-
- Analyzer::AnalyzerStartParameters sp;
- sp.displayName = runConfiguration->displayName();
- if (LocalApplicationRunConfiguration *rc1 =
- qobject_cast<LocalApplicationRunConfiguration *>(runConfiguration)) {
- EnvironmentAspect *aspect = runConfiguration->extraAspect<EnvironmentAspect>();
- if (aspect)
- sp.environment = aspect->environment();
- sp.workingDirectory = rc1->workingDirectory();
- sp.debuggee = rc1->executable();
- sp.debuggeeArgs = rc1->commandLineArguments();
- const IDevice::ConstPtr device =
- DeviceKitInformation::device(runConfiguration->target()->kit());
- QTC_ASSERT(device, return sp);
- QTC_ASSERT(device->type() == Constants::DESKTOP_DEVICE_TYPE, return sp);
- QTcpServer server;
- if (!server.listen(QHostAddress::LocalHost) && !server.listen(QHostAddress::LocalHostIPv6)) {
- qWarning() << "Cannot open port on host for profiling.";
- return sp;
+ // Make sure mode is shown.
+ AnalyzerManager::showMode();
+
+ // ### not sure if we're supposed to check if the RunConFiguration isEnabled
+ Project *pro = SessionManager::startupProject();
+ BuildConfiguration::BuildType buildType = BuildConfiguration::Unknown;
+ if (pro) {
+ if (const Target *target = pro->activeTarget()) {
+ // Build configuration is 0 for QML projects.
+ if (const BuildConfiguration *buildConfig = target->activeBuildConfiguration())
+ buildType = buildConfig->buildType();
+ }
+ }
+
+ // Check the project for whether the build config is in the correct mode
+ // if not, notify the user and urge him to use the correct mode.
+ if (!buildTypeAccepted(tool->toolMode(), buildType)) {
+ const QString currentMode = buildType == BuildConfiguration::Debug
+ ? AnalyzerManager::tr("Debug")
+ : AnalyzerManager::tr("Release");
+
+ QSettings *settings = ICore::settings();
+ const QString configKey = QLatin1String("Analyzer.AnalyzeCorrectMode");
+ int ret;
+ if (settings->contains(configKey)) {
+ ret = settings->value(configKey, QDialog::Accepted).toInt();
+ } else {
+ QString toolModeString;
+ switch (tool->toolMode()) {
+ case IAnalyzerTool::DebugMode:
+ toolModeString = AnalyzerManager::tr("Debug");
+ break;
+ case IAnalyzerTool::ReleaseMode:
+ toolModeString = AnalyzerManager::tr("Release");
+ break;
+ default:
+ QTC_CHECK(false);
+ }
+ //const QString toolName = tool->displayName();
+ const QString toolName = AnalyzerManager::tr("Tool"); // FIXME
+ const QString title = AnalyzerManager::tr("Run %1 in %2 Mode?").arg(toolName).arg(currentMode);
+ const QString message = AnalyzerManager::tr("<html><head/><body><p>You are trying "
+ "to run the tool \"%1\" on an application in %2 mode. "
+ "The tool is designed to be used in %3 mode.</p><p>"
+ "Debug and Release mode run-time characteristics differ "
+ "significantly, analytical findings for one mode may or "
+ "may not be relevant for the other.</p><p>"
+ "Do you want to continue and run the tool in %2 mode?</p></body></html>")
+ .arg(toolName).arg(currentMode).arg(toolModeString);
+ const QString checkBoxText = AnalyzerManager::tr("&Do not ask again");
+ bool checkBoxSetting = false;
+ const QDialogButtonBox::StandardButton button =
+ Utils::CheckableMessageBox::question(ICore::mainWindow(),
+ title, message, checkBoxText,
+ &checkBoxSetting, QDialogButtonBox::Yes|QDialogButtonBox::Cancel,
+ QDialogButtonBox::Cancel);
+ ret = button == QDialogButtonBox::Yes ? QDialog::Accepted : QDialog::Rejected;
+
+ if (checkBoxSetting && ret == QDialog::Accepted)
+ settings->setValue(configKey, ret);
}
- sp.connParams.host = server.serverAddress().toString();
- sp.connParams.port = server.serverPort();
- sp.startMode = Analyzer::StartLocal;
- } else if (RemoteLinuxRunConfiguration *rc2 =
- qobject_cast<RemoteLinuxRunConfiguration *>(runConfiguration)) {
- sp.startMode = Analyzer::StartRemote;
- sp.debuggee = rc2->remoteExecutableFilePath();
- sp.connParams = DeviceKitInformation::device(rc2->target()->kit())->sshParameters();
- sp.analyzerCmdPrefix = rc2->commandPrefix();
- sp.debuggeeArgs = rc2->arguments();
- } else {
- // Might be S60DeviceRunfiguration, or something else ...
- //sp.startMode = StartRemote;
- sp.startMode = Analyzer::StartRemote;
+ if (ret == QDialog::Rejected)
+ return;
}
- return sp;
+
+ ProjectExplorerPlugin::instance()->runProject(pro, tool->runMode());
+}
+
+static void startRemoteTool(IAnalyzerTool *tool)
+{
+ StartRemoteDialog dlg;
+ if (dlg.exec() != QDialog::Accepted)
+ return;
+
+ AnalyzerStartParameters sp;
+ sp.startMode = StartRemote;
+ sp.connParams = dlg.sshParams();
+ sp.debuggee = dlg.executable();
+ sp.debuggeeArgs = dlg.arguments();
+ sp.displayName = dlg.executable();
+ sp.workingDirectory = dlg.workingDirectory();
+
+ AnalyzerRunControl *rc = tool->createRunControl(sp, 0);
+ QObject::connect(AnalyzerManager::stopAction(), SIGNAL(triggered()), rc, SLOT(stopIt()));
+
+ ProjectExplorerPlugin::instance()->startRunControl(rc, tool->runMode());
+}
+
+void ValgrindTool::startTool(StartMode mode)
+{
+ if (mode == StartLocal)
+ startLocalTool(this);
+ if (mode == StartRemote)
+ startRemoteTool(this);
}
} // namespace Internal
diff --git a/src/plugins/valgrind/valgrindtool.h b/src/plugins/valgrind/valgrindtool.h
index 3338155b79..24aacfb72f 100644
--- a/src/plugins/valgrind/valgrindtool.h
+++ b/src/plugins/valgrind/valgrindtool.h
@@ -1,7 +1,8 @@
-/**************************************************************************
+/****************************************************************************
**
-** Copyright (C) 2013 Kläralvdalens Datakonsult AB, a KDAB Group company.
-** Contact: Kläralvdalens Datakonsult AB (info@kdab.com)
+** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+** Author: Nicolas Arnaud-Cormos, KDAB (nicolas.arnaud-cormos@kdab.com)
**
** This file is part of Qt Creator.
**
@@ -38,18 +39,14 @@ namespace Internal {
class ValgrindTool : public Analyzer::IAnalyzerTool
{
Q_OBJECT
-public:
- explicit ValgrindTool(QObject *parent);
- bool canRun(ProjectExplorer::RunConfiguration *runConfiguration,
- ProjectExplorer::RunMode mode) const;
+public:
+ explicit ValgrindTool(QObject *parent = 0);
- Analyzer::AnalyzerStartParameters createStartParameters(
- ProjectExplorer::RunConfiguration *runConfiguration,
- ProjectExplorer::RunMode mode) const;
+ void startTool(Analyzer::StartMode mode);
};
} // namespace Internal
} // namespace Valgrind
-#endif // VALGRINDTOOL_H
+#endif // VALGRIND_TOOL
diff --git a/src/plugins/valgrind/xmlprotocol/parser.cpp b/src/plugins/valgrind/xmlprotocol/parser.cpp
index ca76a006f5..d029009b6d 100644
--- a/src/plugins/valgrind/xmlprotocol/parser.cpp
+++ b/src/plugins/valgrind/xmlprotocol/parser.cpp
@@ -440,29 +440,27 @@ void Parser::Private::parseError()
if (reader.isStartElement())
lastAuxWhat++;
const QStringRef name = reader.name();
- if (name == QLatin1String("unique"))
+ if (name == QLatin1String("unique")) {
e.setUnique(parseHex(blockingReadElementText(), QLatin1String("unique")));
- else if (name == QLatin1String("tid"))
+ } else if (name == QLatin1String("tid")) {
e.setTid(parseInt64(blockingReadElementText(), QLatin1String("error/tid")));
- else if (name == QLatin1String("kind")) //TODO this is memcheck-specific:
+ } else if (name == QLatin1String("kind")) { //TODO this is memcheck-specific:
e.setKind(parseErrorKind(blockingReadElementText()));
- else if (name == QLatin1String("suppression"))
+ } else if (name == QLatin1String("suppression")) {
e.setSuppression(parseSuppression());
- else if (name == QLatin1String("xwhat")) {
+ } else if (name == QLatin1String("xwhat")) {
const XWhat xw = parseXWhat();
e.setWhat(xw.text);
e.setLeakedBlocks(xw.leakedblocks);
e.setLeakedBytes(xw.leakedbytes);
e.setHelgrindThreadId(xw.hthreadid);
- }
- else if (name == QLatin1String("what"))
+ } else if (name == QLatin1String("what")) {
e.setWhat(blockingReadElementText());
- else if (name == QLatin1String("xauxwhat")) {
+ } else if (name == QLatin1String("xauxwhat")) {
if (!currentAux.text.isEmpty())
auxs.push_back(currentAux);
currentAux = parseXauxWhat();
- }
- else if (name == QLatin1String("auxwhat")) {
+ } else if (name == QLatin1String("auxwhat")) {
const QString aux = blockingReadElementText();
//concatenate multiple consecutive <auxwhat> tags
if (lastAuxWhat > 1) {
@@ -476,12 +474,11 @@ void Parser::Private::parseError()
currentAux.text.append(aux);
}
lastAuxWhat = 0;
- }
- else if (name == QLatin1String("stack")) {
+ } else if (name == QLatin1String("stack")) {
frames.push_back(parseStack());
- }
- else if (reader.isStartElement())
+ } else if (reader.isStartElement()) {
reader.skipCurrentElement();
+ }
}
if (!currentAux.text.isEmpty())
diff --git a/src/plugins/valgrind/xmlprotocol/xmlprotocol.pri b/src/plugins/valgrind/xmlprotocol/xmlprotocol.pri
index fe3fda438f..d9e4262d2c 100644
--- a/src/plugins/valgrind/xmlprotocol/xmlprotocol.pri
+++ b/src/plugins/valgrind/xmlprotocol/xmlprotocol.pri
@@ -1,7 +1,5 @@
QT *= network
-INCLUDEPATH *= $$PWD
-
HEADERS += \
$$PWD/frame.h \
$$PWD/parser.h \
diff --git a/src/plugins/vcsbase/VcsBase.pluginspec.in b/src/plugins/vcsbase/VcsBase.pluginspec.in
index 33a440d238..2ea0c5ffcd 100644
--- a/src/plugins/vcsbase/VcsBase.pluginspec.in
+++ b/src/plugins/vcsbase/VcsBase.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"VcsBase\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"VcsBase\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/vcsbase/baseannotationhighlighter.cpp b/src/plugins/vcsbase/baseannotationhighlighter.cpp
index 3a04647103..841b7ed479 100644
--- a/src/plugins/vcsbase/baseannotationhighlighter.cpp
+++ b/src/plugins/vcsbase/baseannotationhighlighter.cpp
@@ -28,6 +28,7 @@
****************************************************************************/
#include "baseannotationhighlighter.h"
+#include <texteditor/fontsettings.h>
#include <QDebug>
#include <QColor>
@@ -51,34 +52,63 @@ typedef QMap<QString, QTextCharFormat> ChangeNumberFormatMap;
*/
namespace VcsBase {
-namespace Internal {
class BaseAnnotationHighlighterPrivate
{
+ BaseAnnotationHighlighter *q_ptr;
+ Q_DECLARE_PUBLIC(BaseAnnotationHighlighter)
public:
+ enum Formats {
+ BackgroundFormat // C_TEXT
+ };
+
+ BaseAnnotationHighlighterPrivate();
+
+ void updateOtherFormats();
+
ChangeNumberFormatMap m_changeNumberMap;
QColor m_background;
};
-} // namespace Internal
+BaseAnnotationHighlighterPrivate::BaseAnnotationHighlighterPrivate()
+ : q_ptr(0)
+{
+}
+
+void BaseAnnotationHighlighterPrivate::updateOtherFormats()
+{
+ Q_Q(BaseAnnotationHighlighter);
+ m_background = q->formatForCategory(BackgroundFormat).brushProperty(QTextFormat::BackgroundBrush).color();
+ q->setChangeNumbers(m_changeNumberMap.keys().toSet());
+}
+
BaseAnnotationHighlighter::BaseAnnotationHighlighter(const ChangeNumbers &changeNumbers,
- const QColor &bg,
QTextDocument *document) :
TextEditor::SyntaxHighlighter(document),
- d(new Internal::BaseAnnotationHighlighterPrivate)
+ d_ptr(new BaseAnnotationHighlighterPrivate())
{
- d->m_background = bg;
+ d_ptr->q_ptr = this;
+
+ Q_D(BaseAnnotationHighlighter);
+
+ static QVector<TextEditor::TextStyle> categories;
+ if (categories.isEmpty())
+ categories << TextEditor::C_TEXT;
+
+ setTextFormatCategories(categories);
+ d->updateOtherFormats();
+
setChangeNumbers(changeNumbers);
}
BaseAnnotationHighlighter::~BaseAnnotationHighlighter()
{
- delete d;
}
void BaseAnnotationHighlighter::setChangeNumbers(const ChangeNumbers &changeNumbers)
{
+ Q_D(BaseAnnotationHighlighter);
d->m_changeNumberMap.clear();
if (!changeNumbers.isEmpty()) {
// Assign a color gradient to annotation change numbers. Give
@@ -99,6 +129,7 @@ void BaseAnnotationHighlighter::setChangeNumbers(const ChangeNumbers &changeNumb
void BaseAnnotationHighlighter::highlightBlock(const QString &text)
{
+ Q_D(BaseAnnotationHighlighter);
if (text.isEmpty() || d->m_changeNumberMap.empty())
return;
const QString change = changeNumber(text);
@@ -107,10 +138,11 @@ void BaseAnnotationHighlighter::highlightBlock(const QString &text)
setFormat(0, text.length(), it.value());
}
-void BaseAnnotationHighlighter::setBackgroundColor(const QColor &color)
+void BaseAnnotationHighlighter::setFontSettings(const TextEditor::FontSettings &fontSettings)
{
- d->m_background = color;
- setChangeNumbers(d->m_changeNumberMap.keys().toSet());
+ Q_D(BaseAnnotationHighlighter);
+ SyntaxHighlighter::setFontSettings(fontSettings);
+ d->updateOtherFormats();
}
} // namespace VcsBase
diff --git a/src/plugins/vcsbase/baseannotationhighlighter.h b/src/plugins/vcsbase/baseannotationhighlighter.h
index e1845477e4..ff5fdfb1a4 100644
--- a/src/plugins/vcsbase/baseannotationhighlighter.h
+++ b/src/plugins/vcsbase/baseannotationhighlighter.h
@@ -35,17 +35,16 @@
#include <texteditor/syntaxhighlighter.h>
namespace VcsBase {
-namespace Internal {
class BaseAnnotationHighlighterPrivate;
-} // namespace Internal
class VCSBASE_EXPORT BaseAnnotationHighlighter : public TextEditor::SyntaxHighlighter
{
Q_OBJECT
+ Q_DECLARE_PRIVATE(BaseAnnotationHighlighter)
public:
typedef QSet<QString> ChangeNumbers;
- explicit BaseAnnotationHighlighter(const ChangeNumbers &changeNumbers, const QColor &bg,
+ explicit BaseAnnotationHighlighter(const ChangeNumbers &changeNumbers,
QTextDocument *document = 0);
virtual ~BaseAnnotationHighlighter();
@@ -53,13 +52,13 @@ public:
virtual void highlightBlock(const QString &text);
- void setBackgroundColor(const QColor &color);
+ virtual void setFontSettings(const TextEditor::FontSettings &fontSettings);
private:
// Implement this to return the change number of a line
virtual QString changeNumber(const QString &block) const = 0;
- Internal::BaseAnnotationHighlighterPrivate *const d;
+ QScopedPointer<BaseAnnotationHighlighterPrivate> d_ptr;
};
} // namespace VcsBase
diff --git a/src/plugins/vcsbase/basecheckoutwizard.cpp b/src/plugins/vcsbase/basecheckoutwizard.cpp
index 7999c6ea99..48ba1264c8 100644
--- a/src/plugins/vcsbase/basecheckoutwizard.cpp
+++ b/src/plugins/vcsbase/basecheckoutwizard.cpp
@@ -29,7 +29,6 @@
#include "basecheckoutwizard.h"
#include "checkoutwizarddialog.h"
-#include "checkoutjobs.h"
#include <coreplugin/featureprovider.h>
@@ -72,7 +71,8 @@ public:
Internal::CheckoutWizardDialog *dialog;
QList<QWizardPage *> parameterPages;
QString checkoutPath;
- QString id;
+ QString progressTitle;
+ QString startedStatus;
};
void BaseCheckoutWizardPrivate::clear()
@@ -88,6 +88,11 @@ BaseCheckoutWizard::BaseCheckoutWizard(QObject *parent) :
Core::IWizard(parent),
d(new Internal::BaseCheckoutWizardPrivate)
{
+ setWizardKind(IWizard::ProjectWizard);
+ setCategory(QLatin1String(ProjectExplorer::Constants::IMPORT_WIZARD_CATEGORY));
+ setDisplayCategory(QCoreApplication::translate("ProjectExplorer",
+ ProjectExplorer::Constants::IMPORT_WIZARD_CATEGORY_DISPLAY));
+ setFlags(Core::IWizard::PlatformIndependent);
}
BaseCheckoutWizard::~BaseCheckoutWizard()
@@ -95,42 +100,16 @@ BaseCheckoutWizard::~BaseCheckoutWizard()
delete d;
}
-Core::IWizard::WizardKind BaseCheckoutWizard::kind() const
-{
- return Core::IWizard::ProjectWizard;
-}
-
-QString BaseCheckoutWizard::category() const
-{
- return QLatin1String(ProjectExplorer::Constants::IMPORT_WIZARD_CATEGORY);
-}
-
-QString BaseCheckoutWizard::displayCategory() const
-{
- return QCoreApplication::translate("ProjectExplorer", ProjectExplorer::Constants::IMPORT_WIZARD_CATEGORY_DISPLAY);
-}
-
-QString BaseCheckoutWizard::id() const
-{
- return d->id;
-}
-
-QString BaseCheckoutWizard::descriptionImage() const
-{
- return QString();
-}
-
-void BaseCheckoutWizard::setId(const QString &id)
-{
- d->id = id;
-}
-
void BaseCheckoutWizard::runWizard(const QString &path, QWidget *parent, const QString & /*platform*/, const QVariantMap &extraValues)
{
Q_UNUSED(extraValues)
// Create dialog and launch
d->parameterPages = createParameterPages(path);
Internal::CheckoutWizardDialog dialog(d->parameterPages, parent);
+ if (!d->progressTitle.isEmpty())
+ dialog.setTitle(d->progressTitle);
+ if (!d->startedStatus.isEmpty())
+ dialog.setStartedStatus(d->startedStatus);
d->dialog = &dialog;
connect(&dialog, SIGNAL(progressPageShown()), this, SLOT(slotProgressPageShown()));
dialog.setWindowTitle(displayName());
@@ -149,16 +128,6 @@ void BaseCheckoutWizard::runWizard(const QString &path, QWidget *parent, const Q
}
}
-Core::FeatureSet BaseCheckoutWizard::requiredFeatures() const
-{
- return Core::FeatureSet();
-}
-
-Core::IWizard::WizardFlags BaseCheckoutWizard::flags() const
-{
- return Core::IWizard::PlatformIndependent;
-}
-
static inline QString msgNoProjectFiles(const QDir &dir, const QStringList &patterns)
{
return BaseCheckoutWizard::tr("Could not find any project files matching (%1) in the directory '%2'.").arg(patterns.join(QLatin1String(", ")), QDir::toNativeSeparators(dir.absolutePath()));
@@ -184,7 +153,7 @@ static QFileInfoList findProjectFiles(const QDir &projectDir, QString *errorMess
*errorMessage = msgNoProjectFiles(srcDir, projectFilePatterns);
return QFileInfoList();
}
- return projectFiles;;
+ return projectFiles;
}
QString BaseCheckoutWizard::openProject(const QString &path, QString *errorMessage)
@@ -213,10 +182,16 @@ QString BaseCheckoutWizard::openProject(const QString &path, QString *errorMessa
return projectFile;
}
+void BaseCheckoutWizard::setCustomLabels(const QString &progressTitle, const QString &startedStatus)
+{
+ d->progressTitle = progressTitle;
+ d->startedStatus = startedStatus;
+}
+
void BaseCheckoutWizard::slotProgressPageShown()
{
- const QSharedPointer<AbstractCheckoutJob> job = createJob(d->parameterPages, &(d->checkoutPath));
- d->dialog->start(job);
+ Command *command = createCommand(d->parameterPages, &(d->checkoutPath));
+ d->dialog->start(command);
}
} // namespace VcsBase
diff --git a/src/plugins/vcsbase/basecheckoutwizard.h b/src/plugins/vcsbase/basecheckoutwizard.h
index 4ca72d6ff2..08f7e10555 100644
--- a/src/plugins/vcsbase/basecheckoutwizard.h
+++ b/src/plugins/vcsbase/basecheckoutwizard.h
@@ -45,7 +45,7 @@ namespace Internal {
class BaseCheckoutWizardPrivate;
}
-class AbstractCheckoutJob;
+class Command;
class VCSBASE_EXPORT BaseCheckoutWizard : public Core::IWizard
{
@@ -53,31 +53,17 @@ class VCSBASE_EXPORT BaseCheckoutWizard : public Core::IWizard
public:
explicit BaseCheckoutWizard(QObject *parent = 0);
- virtual ~BaseCheckoutWizard();
+ ~BaseCheckoutWizard();
- virtual WizardKind kind() const;
-
- virtual QString category() const;
- virtual QString displayCategory() const;
- virtual QString id() const;
-
- virtual QString descriptionImage() const;
-
- virtual void runWizard(const QString &path, QWidget *parent, const QString &platform, const QVariantMap &extraValues);
-
- virtual Core::FeatureSet requiredFeatures() const;
-
- virtual WizardFlags flags() const;
+ void runWizard(const QString &path, QWidget *parent, const QString &platform, const QVariantMap &extraValues);
static QString openProject(const QString &path, QString *errorMessage);
protected:
+ void setCustomLabels(const QString &progressTitle, const QString &startedStatus);
virtual QList<QWizardPage *> createParameterPages(const QString &path) = 0;
- virtual QSharedPointer<AbstractCheckoutJob> createJob(const QList<QWizardPage *> &parameterPages,
- QString *checkoutPath) = 0;
-
-public slots:
- void setId(const QString &id);
+ virtual Command *createCommand(const QList<QWizardPage *> &parameterPages,
+ QString *checkoutPath) = 0;
private slots:
void slotProgressPageShown();
diff --git a/src/plugins/vcsbase/basecheckoutwizardpage.ui b/src/plugins/vcsbase/basecheckoutwizardpage.ui
index 2ae4b6e19d..edf34f080b 100644
--- a/src/plugins/vcsbase/basecheckoutwizardpage.ui
+++ b/src/plugins/vcsbase/basecheckoutwizardpage.ui
@@ -94,7 +94,7 @@
<string>The path in which the directory containing the checkout will be created.</string>
</property>
<property name="text">
- <string>Checkout path:</string>
+ <string>Path:</string>
</property>
</widget>
</item>
@@ -107,7 +107,7 @@
<string>The local directory that will contain the code after the checkout.</string>
</property>
<property name="text">
- <string>Checkout directory:</string>
+ <string>Directory:</string>
</property>
</widget>
</item>
diff --git a/src/plugins/vcsbase/basevcseditorfactory.cpp b/src/plugins/vcsbase/basevcseditorfactory.cpp
index 0d2780bf45..9d085ab639 100644
--- a/src/plugins/vcsbase/basevcseditorfactory.cpp
+++ b/src/plugins/vcsbase/basevcseditorfactory.cpp
@@ -54,16 +54,11 @@ public:
BaseVcsEditorFactoryPrivate(const VcsBaseEditorParameters *t);
const VcsBaseEditorParameters *m_type;
- const Core::Id m_id;
- QString m_displayName;
- const QStringList m_mimeTypes;
TextEditor::TextEditorActionHandler *m_editorHandler;
};
BaseVcsEditorFactoryPrivate::BaseVcsEditorFactoryPrivate(const VcsBaseEditorParameters *t) :
m_type(t),
- m_id(t->id),
- m_mimeTypes(QStringList(QLatin1String(t->mimeType))),
m_editorHandler(new TextEditor::TextEditorActionHandler(t->context))
{
}
@@ -73,7 +68,9 @@ BaseVcsEditorFactoryPrivate::BaseVcsEditorFactoryPrivate(const VcsBaseEditorPara
BaseVcsEditorFactory::BaseVcsEditorFactory(const VcsBaseEditorParameters *t)
: d(new Internal::BaseVcsEditorFactoryPrivate(t))
{
- d->m_displayName = QCoreApplication::translate("VCS", t->displayName);
+ setId(t->id);
+ setDisplayName(QCoreApplication::translate("VCS", t->displayName));
+ addMimeType(t->mimeType);
}
BaseVcsEditorFactory::~BaseVcsEditorFactory()
@@ -81,33 +78,17 @@ BaseVcsEditorFactory::~BaseVcsEditorFactory()
delete d;
}
-QStringList BaseVcsEditorFactory::mimeTypes() const
-{
- return d->m_mimeTypes;
-}
-
-Core::Id BaseVcsEditorFactory::id() const
-{
- return d->m_id;
-}
-
-QString BaseVcsEditorFactory::displayName() const
-{
- return d->m_displayName;
-}
-
Core::IEditor *BaseVcsEditorFactory::createEditor(QWidget *parent)
{
VcsBaseEditorWidget *vcsEditor = createVcsBaseEditor(d->m_type, parent);
- vcsEditor ->setMimeType(d->m_mimeTypes.front());
+ vcsEditor->setMimeType(mimeTypes().front());
d->m_editorHandler->setupActions(vcsEditor);
// Wire font settings and set initial values
- TextEditor::TextEditorSettings *settings = TextEditor::TextEditorSettings::instance();
- connect(settings, SIGNAL(fontSettingsChanged(TextEditor::FontSettings)),
+ connect(TextEditor::TextEditorSettings::instance(), SIGNAL(fontSettingsChanged(TextEditor::FontSettings)),
vcsEditor, SLOT(setFontSettings(TextEditor::FontSettings)));
- vcsEditor->setFontSettings(settings->fontSettings());
+ vcsEditor->setFontSettings(TextEditor::TextEditorSettings::fontSettings());
return vcsEditor->editor();
}
diff --git a/src/plugins/vcsbase/basevcseditorfactory.h b/src/plugins/vcsbase/basevcseditorfactory.h
index 1f0d440200..727ac353ca 100644
--- a/src/plugins/vcsbase/basevcseditorfactory.h
+++ b/src/plugins/vcsbase/basevcseditorfactory.h
@@ -35,8 +35,6 @@
#include <coreplugin/editormanager/ieditorfactory.h>
-QT_FORWARD_DECLARE_CLASS(QStringList)
-
namespace VcsBase {
namespace Internal {
class BaseVcsEditorFactoryPrivate;
@@ -45,15 +43,11 @@ class BaseVcsEditorFactoryPrivate;
class VCSBASE_EXPORT BaseVcsEditorFactory : public Core::IEditorFactory
{
Q_OBJECT
+
public:
explicit BaseVcsEditorFactory(const VcsBaseEditorParameters *type);
~BaseVcsEditorFactory();
- QStringList mimeTypes() const;
- // IEditorFactory
-
- Core::Id id() const;
- QString displayName() const;
Core::IEditor *createEditor(QWidget *parent);
private:
diff --git a/src/plugins/vcsbase/basevcssubmiteditorfactory.cpp b/src/plugins/vcsbase/basevcssubmiteditorfactory.cpp
index d17ba6a582..8ceed8177e 100644
--- a/src/plugins/vcsbase/basevcssubmiteditorfactory.cpp
+++ b/src/plugins/vcsbase/basevcssubmiteditorfactory.cpp
@@ -32,58 +32,21 @@
namespace VcsBase {
-namespace Internal {
-
-class BaseVcsSubmitEditorFactoryPrivate
-{
-public:
- BaseVcsSubmitEditorFactoryPrivate(const VcsBaseSubmitEditorParameters *parameters);
-
- const VcsBaseSubmitEditorParameters *m_parameters;
- const Core::Id m_id;
- const QString m_displayName;
- const QStringList m_mimeTypes;
-};
-
-BaseVcsSubmitEditorFactoryPrivate::BaseVcsSubmitEditorFactoryPrivate(const VcsBaseSubmitEditorParameters *parameters) :
- m_parameters(parameters),
- m_id(parameters->id),
- m_displayName(QLatin1String(parameters->displayName)),
- m_mimeTypes(QLatin1String(parameters->mimeType))
-{
-}
-
-} // namespace Internal
-
-BaseVcsSubmitEditorFactory::BaseVcsSubmitEditorFactory(const VcsBaseSubmitEditorParameters *parameters) :
- d(new Internal::BaseVcsSubmitEditorFactoryPrivate(parameters))
+BaseVcsSubmitEditorFactory::BaseVcsSubmitEditorFactory(const VcsBaseSubmitEditorParameters *parameters)
+ : m_parameters(parameters)
{
+ setId(parameters->id);
+ setDisplayName(QLatin1String(parameters->displayName));
+ addMimeType(parameters->mimeType);
}
BaseVcsSubmitEditorFactory::~BaseVcsSubmitEditorFactory()
{
- delete d;
}
Core::IEditor *BaseVcsSubmitEditorFactory::createEditor(QWidget *parent)
{
- return createBaseSubmitEditor(d->m_parameters, parent);
-}
-
-Core::Id BaseVcsSubmitEditorFactory::id() const
-{
- return d->m_id;
-}
-
-QString BaseVcsSubmitEditorFactory::displayName() const
-{
- return d->m_displayName;
-}
-
-
-QStringList BaseVcsSubmitEditorFactory::mimeTypes() const
-{
- return d->m_mimeTypes;
+ return createBaseSubmitEditor(m_parameters, parent);
}
} // namespace VcsBase
diff --git a/src/plugins/vcsbase/basevcssubmiteditorfactory.h b/src/plugins/vcsbase/basevcssubmiteditorfactory.h
index 7943df52e0..95280ca34b 100644
--- a/src/plugins/vcsbase/basevcssubmiteditorfactory.h
+++ b/src/plugins/vcsbase/basevcssubmiteditorfactory.h
@@ -39,10 +39,6 @@ namespace VcsBase {
class VcsBaseSubmitEditor;
class VcsBaseSubmitEditorParameters;
-namespace Internal {
-class BaseVcsSubmitEditorFactoryPrivate;
-} // namespace Internal
-
// Parametrizable base class for editor factories creating instances of
// VcsBaseSubmitEditor subclasses.
class VCSBASE_EXPORT BaseVcsSubmitEditorFactory : public Core::IEditorFactory
@@ -51,21 +47,17 @@ class VCSBASE_EXPORT BaseVcsSubmitEditorFactory : public Core::IEditorFactory
protected:
explicit BaseVcsSubmitEditorFactory(const VcsBaseSubmitEditorParameters *parameters);
-
-public:
~BaseVcsSubmitEditorFactory();
+public:
Core::IEditor *createEditor(QWidget *parent);
- Core::Id id() const;
- QString displayName() const;
- QStringList mimeTypes() const;
private:
virtual VcsBaseSubmitEditor
*createBaseSubmitEditor(const VcsBaseSubmitEditorParameters *parameters,
QWidget *parent) = 0;
- Internal::BaseVcsSubmitEditorFactoryPrivate *const d;
+ const VcsBaseSubmitEditorParameters *const m_parameters; // Not owned.
};
// Utility template to create an editor that has a constructor taking the
diff --git a/src/plugins/vcsbase/checkoutjobs.cpp b/src/plugins/vcsbase/checkoutjobs.cpp
deleted file mode 100644
index 6def0ade5f..0000000000
--- a/src/plugins/vcsbase/checkoutjobs.cpp
+++ /dev/null
@@ -1,215 +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 "checkoutjobs.h"
-
-#include "vcsbaseplugin.h"
-#include "vcsbaseoutputwindow.h"
-
-#include <QDebug>
-#include <QQueue>
-#include <QDir>
-#include <QStringList>
-#include <utils/synchronousprocess.h>
-#include <utils/qtcassert.h>
-
-enum { debug = 0 };
-
-/*!
- \class VcsBase::AbstractCheckoutJob
-
- \brief The AbstractCheckoutJob class is an abstract base class for a job
- creating an initial project checkout.
-
- It should be something that runs in the background producing log messages.
-
- \sa VcsBase::BaseCheckoutWizard
-*/
-
-namespace VcsBase {
-
-namespace Internal {
-
-// Use a terminal-less process to suppress SSH prompts.
-static inline QSharedPointer<QProcess> createProcess()
-{
- unsigned flags = 0;
- if (VcsBasePlugin::isSshPromptConfigured())
- flags = Utils::SynchronousProcess::UnixTerminalDisabled;
- return Utils::SynchronousProcess::createProcess(flags);
-}
-
-class ProcessCheckoutJobStep
-{
-public:
- ProcessCheckoutJobStep() {}
- explicit ProcessCheckoutJobStep(const QString &bin,
- const QStringList &args,
- const QString &workingDir,
- QProcessEnvironment env) :
- binary(bin), arguments(args), workingDirectory(workingDir), environment(env) {}
-
- QString binary;
- QStringList arguments;
- QString workingDirectory;
- QProcessEnvironment environment;
-};
-
-class ProcessCheckoutJobPrivate
-{
-public:
- ProcessCheckoutJobPrivate();
-
- QSharedPointer<QProcess> process;
- QQueue<ProcessCheckoutJobStep> stepQueue;
- QString binary;
-};
-
-ProcessCheckoutJobPrivate::ProcessCheckoutJobPrivate() :
- process(createProcess())
-{
-}
-
-} // namespace Internal
-
-AbstractCheckoutJob::AbstractCheckoutJob(QObject *parent) :
- QObject(parent)
-{
-}
-
-/*!
- \class VcsBase::ProcessCheckoutJob
-
- \brief The ProcessCheckoutJob class is a convenience implementation of a
- VcsBase::AbstractCheckoutJob using a QProcess.
-*/
-
-ProcessCheckoutJob::ProcessCheckoutJob(QObject *parent) :
- AbstractCheckoutJob(parent),
- d(new Internal::ProcessCheckoutJobPrivate)
-{
- connect(d->process.data(), SIGNAL(error(QProcess::ProcessError)), this, SLOT(slotError(QProcess::ProcessError)));
- connect(d->process.data(), SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(slotFinished(int,QProcess::ExitStatus)));
- connect(d->process.data(), SIGNAL(readyReadStandardOutput()), this, SLOT(slotOutput()));
- d->process->setProcessChannelMode(QProcess::MergedChannels);
- d->process->closeWriteChannel();
-}
-
-ProcessCheckoutJob::~ProcessCheckoutJob()
-{
- delete d;
-}
-
-void ProcessCheckoutJob::addStep(const QString &binary,
- const QStringList &args,
- const QString &workingDirectory,
- const QProcessEnvironment &env)
-{
- if (debug)
- qDebug() << "ProcessCheckoutJob::addStep" << binary << args << workingDirectory;
- d->stepQueue.enqueue(Internal::ProcessCheckoutJobStep(binary, args, workingDirectory, env));
-}
-
-void ProcessCheckoutJob::slotOutput()
-{
- const QByteArray data = d->process->readAllStandardOutput();
- const QString s = QString::fromLocal8Bit(data, data.endsWith('\n') ? data.size() - 1: data.size());
- if (debug)
- qDebug() << s;
- emit output(s);
-}
-
-void ProcessCheckoutJob::slotError(QProcess::ProcessError error)
-{
- switch (error) {
- case QProcess::FailedToStart:
- emit failed(tr("Unable to start %1: %2").
- arg(QDir::toNativeSeparators(d->binary), d->process->errorString()));
- break;
- default:
- emit failed(d->process->errorString());
- break;
- }
-}
-
-void ProcessCheckoutJob::slotFinished (int exitCode, QProcess::ExitStatus exitStatus)
-{
- if (debug)
- qDebug() << "finished" << exitCode << exitStatus;
-
- switch (exitStatus) {
- case QProcess::NormalExit:
- emit output(tr("The process terminated with exit code %1.").arg(exitCode));
- if (exitCode == 0)
- slotNext();
- 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."));
- break;
- }
-}
-
-void ProcessCheckoutJob::start()
-{
- QTC_ASSERT(!d->stepQueue.empty(), return);
- slotNext();
-}
-
-void ProcessCheckoutJob::slotNext()
-{
- if (d->stepQueue.isEmpty()) {
- emit succeeded();
- return;
- }
- // Launch next
- const Internal::ProcessCheckoutJobStep step = d->stepQueue.dequeue();
- d->process->setWorkingDirectory(step.workingDirectory);
-
- // Set up SSH correctly.
- QProcessEnvironment processEnv = step.environment;
- VcsBasePlugin::setProcessEnvironment(&processEnv, false);
- d->process->setProcessEnvironment(processEnv);
-
- d->binary = step.binary;
- emit output(VcsBaseOutputWindow::msgExecutionLogEntry(step.workingDirectory, d->binary, step.arguments));
- d->process->start(d->binary, step.arguments);
-}
-
-void ProcessCheckoutJob::cancel()
-{
- if (debug)
- qDebug() << "ProcessCheckoutJob::start";
-
- emit output(tr("Stopping..."));
- Utils::SynchronousProcess::stopProcess(*d->process);
-}
-
-} // namespace VcsBase
diff --git a/src/plugins/vcsbase/checkoutjobs.h b/src/plugins/vcsbase/checkoutjobs.h
deleted file mode 100644
index ce4c9a0112..0000000000
--- a/src/plugins/vcsbase/checkoutjobs.h
+++ /dev/null
@@ -1,94 +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 CHECKOUTJOB_H
-#define CHECKOUTJOB_H
-
-#include "vcsbase_global.h"
-
-#include <QObject>
-#include <QProcess>
-#include <QProcessEnvironment>
-
-QT_FORWARD_DECLARE_CLASS(QStringList)
-
-namespace VcsBase {
-
-namespace Internal { class ProcessCheckoutJobPrivate; }
-
-/* Abstract base class for a job creating an initial project checkout.
- * It should be something that runs in the background producing log
- * messages. */
-
-class VCSBASE_EXPORT AbstractCheckoutJob : public QObject
-{
- Q_OBJECT
-
-public:
- virtual void start() = 0;
- virtual void cancel() = 0;
-
-protected:
- explicit AbstractCheckoutJob(QObject *parent = 0);
-
-signals:
- void succeeded();
- void failed(const QString &why);
- void output(const QString &what);
-};
-
-class VCSBASE_EXPORT ProcessCheckoutJob : public AbstractCheckoutJob
-{
- Q_OBJECT
-
-public:
- explicit ProcessCheckoutJob(QObject *parent = 0);
- ~ProcessCheckoutJob();
-
- void addStep(const QString &binary,
- const QStringList &args,
- const QString &workingDirectory = QString(),
- const QProcessEnvironment &env = QProcessEnvironment::systemEnvironment());
-
- void start();
- void cancel();
-
-private slots:
- void slotError(QProcess::ProcessError error);
- void slotFinished (int exitCode, QProcess::ExitStatus exitStatus);
- void slotOutput();
- void slotNext();
-
-private:
- Internal::ProcessCheckoutJobPrivate *const d;
-};
-
-} // namespace VcsBase
-
-#endif // CHECKOUTJOB_H
diff --git a/src/plugins/vcsbase/checkoutprogresswizardpage.cpp b/src/plugins/vcsbase/checkoutprogresswizardpage.cpp
index 157b07e1f4..d427a01f7f 100644
--- a/src/plugins/vcsbase/checkoutprogresswizardpage.cpp
+++ b/src/plugins/vcsbase/checkoutprogresswizardpage.cpp
@@ -28,15 +28,16 @@
****************************************************************************/
#include "checkoutprogresswizardpage.h"
-#include "checkoutjobs.h"
#include "ui_checkoutprogresswizardpage.h"
+#include "command.h"
+#include "vcsbaseplugin.h"
#include <utils/qtcassert.h>
#include <QApplication>
/*!
- \class VcsBase::CheckoutProgressWizardPage
+ \class VcsBase::Internal::CheckoutProgressWizardPage
\brief The CheckoutProgressWizardPage implements a page showing the
progress of an initial project checkout.
@@ -52,6 +53,7 @@ namespace Internal {
CheckoutProgressWizardPage::CheckoutProgressWizardPage(QWidget *parent) :
QWizardPage(parent),
ui(new Ui::CheckoutProgressWizardPage),
+ m_startedStatus(tr("Checkout started...")),
m_state(Idle)
{
ui->setupUi(this);
@@ -65,60 +67,72 @@ CheckoutProgressWizardPage::~CheckoutProgressWizardPage()
delete ui;
}
-void CheckoutProgressWizardPage::start(const QSharedPointer<AbstractCheckoutJob> &job)
+void CheckoutProgressWizardPage::setStartedStatus(const QString &startedStatus)
{
- if (job.isNull()) {
+ m_startedStatus = startedStatus;
+}
+
+void CheckoutProgressWizardPage::start(Command *command)
+{
+ if (!command) {
ui->logPlainTextEdit->setPlainText(tr("No job running, please abort."));
return;
}
QTC_ASSERT(m_state != Running, return);
- m_job = job;
- connect(job.data(), SIGNAL(output(QString)), ui->logPlainTextEdit, SLOT(appendPlainText(QString)));
- connect(job.data(), SIGNAL(failed(QString)), this, SLOT(slotFailed(QString)));
- connect(job.data(), SIGNAL(succeeded()), this, SLOT(slotSucceeded()));
+ m_command = command;
+ command->setProgressiveOutput(true);
+ connect(command, SIGNAL(output(QString)), this, SLOT(slotOutput(QString)));
+ connect(command, SIGNAL(finished(bool,int,QVariant)), this, SLOT(slotFinished(bool,int,QVariant)));
QApplication::setOverrideCursor(Qt::WaitCursor);
ui->logPlainTextEdit->clear();
- ui->statusLabel->setText(tr("Checkout started..."));
+ ui->statusLabel->setText(m_startedStatus);
ui->statusLabel->setPalette(QPalette());
m_state = Running;
- // Note: Process jobs can emit failed() right from
- // the start() method on Windows.
- job->start();
+ command->execute();
}
-void CheckoutProgressWizardPage::slotFailed(const QString &why)
+void CheckoutProgressWizardPage::slotFinished(bool ok, int exitCode, const QVariant &)
{
- ui->logPlainTextEdit->appendPlainText(why);
- if (m_state == Running) {
- m_state = Failed;
- QApplication::restoreOverrideCursor();
- ui->statusLabel->setText(tr("Failed."));
- QPalette palette = ui->statusLabel->palette();
- palette.setColor(QPalette::Active, QPalette::Text, Qt::red);
- ui->statusLabel->setPalette(palette);
- emit terminated(false);
+ if (ok && exitCode == 0) {
+ if (m_state == Running) {
+ m_state = Succeeded;
+ QApplication::restoreOverrideCursor();
+ ui->statusLabel->setText(tr("Succeeded."));
+ QPalette palette = ui->statusLabel->palette();
+ palette.setColor(QPalette::Active, QPalette::Text, Qt::green);
+ ui->statusLabel->setPalette(palette);
+ emit completeChanged();
+ emit terminated(true);
+ }
+ } else {
+ ui->logPlainTextEdit->appendPlainText(m_error);
+ if (m_state == Running) {
+ m_state = Failed;
+ QApplication::restoreOverrideCursor();
+ ui->statusLabel->setText(tr("Failed."));
+ QPalette palette = ui->statusLabel->palette();
+ palette.setColor(QPalette::Active, QPalette::Text, Qt::red);
+ ui->statusLabel->setPalette(palette);
+ emit terminated(false);
+ }
}
}
-void CheckoutProgressWizardPage::slotSucceeded()
+void CheckoutProgressWizardPage::slotOutput(const QString &text)
{
- if (m_state == Running) {
- m_state = Succeeded;
- QApplication::restoreOverrideCursor();
- ui->statusLabel->setText(tr("Succeeded."));
- QPalette palette = ui->statusLabel->palette();
- palette.setColor(QPalette::Active, QPalette::Text, Qt::green);
- ui->statusLabel->setPalette(palette);
- emit completeChanged();
- emit terminated(true);
- }
+ ui->logPlainTextEdit->appendPlainText(text.trimmed());
+}
+
+void CheckoutProgressWizardPage::slotError(const QString &text)
+{
+ m_error.append(text);
}
void CheckoutProgressWizardPage::terminate()
{
- if (!m_job.isNull())
- m_job->cancel();
+ if (m_command)
+ m_command->cancel();
}
bool CheckoutProgressWizardPage::isComplete() const
diff --git a/src/plugins/vcsbase/checkoutprogresswizardpage.h b/src/plugins/vcsbase/checkoutprogresswizardpage.h
index 87136507ed..567b7052ac 100644
--- a/src/plugins/vcsbase/checkoutprogresswizardpage.h
+++ b/src/plugins/vcsbase/checkoutprogresswizardpage.h
@@ -34,7 +34,7 @@
#include <QWizardPage>
namespace VcsBase {
-class AbstractCheckoutJob;
+class Command;
namespace Internal {
@@ -50,7 +50,8 @@ public:
explicit CheckoutProgressWizardPage(QWidget *parent = 0);
~CheckoutProgressWizardPage();
- void start(const QSharedPointer<AbstractCheckoutJob> &job);
+ void setStartedStatus(const QString &startedStatus);
+ void start(Command *command);
virtual bool isComplete() const;
bool isRunning() const{ return m_state == Running; }
@@ -61,12 +62,16 @@ signals:
void terminated(bool success);
private slots:
- void slotFailed(const QString &);
- void slotSucceeded();
+ void slotFinished(bool ok, int exitCode, const QVariant &cookie);
+ void slotOutput(const QString &text);
+ void slotError(const QString &text);
private:
Ui::CheckoutProgressWizardPage *ui;
- QSharedPointer<AbstractCheckoutJob> m_job;
+
+ Command *m_command;
+ QString m_startedStatus;
+ QString m_error;
State m_state;
};
diff --git a/src/plugins/vcsbase/checkoutwizarddialog.cpp b/src/plugins/vcsbase/checkoutwizarddialog.cpp
index fecf506c31..49e2f25d0e 100644
--- a/src/plugins/vcsbase/checkoutwizarddialog.cpp
+++ b/src/plugins/vcsbase/checkoutwizarddialog.cpp
@@ -29,7 +29,6 @@
#include "checkoutwizarddialog.h"
#include "basecheckoutwizard.h"
-#include "checkoutjobs.h"
#include "checkoutprogresswizardpage.h"
#include <coreplugin/basefilewizard.h>
@@ -62,6 +61,16 @@ CheckoutWizardDialog::CheckoutWizardDialog(const QList<QWizardPage *> &parameter
Core::BaseFileWizard::setupWizard(this);
}
+void CheckoutWizardDialog::setTitle(const QString &title)
+{
+ m_progressPage->setTitle(title);
+}
+
+void CheckoutWizardDialog::setStartedStatus(const QString &title)
+{
+ m_progressPage->setStartedStatus(title);
+}
+
void CheckoutWizardDialog::slotPageChanged(int id)
{
if (id == m_progressPageId)
@@ -75,11 +84,11 @@ void CheckoutWizardDialog::slotTerminated(bool success)
button(QWizard::BackButton)->setEnabled(true);
}
-void CheckoutWizardDialog::start(const QSharedPointer<AbstractCheckoutJob> &job)
+void CheckoutWizardDialog::start(Command *command)
{
// No "back" available while running.
button(QWizard::BackButton)->setEnabled(false);
- m_progressPage->start(job);
+ m_progressPage->start(command);
}
void CheckoutWizardDialog::reject()
diff --git a/src/plugins/vcsbase/checkoutwizarddialog.h b/src/plugins/vcsbase/checkoutwizarddialog.h
index 18181e25c7..bbecc82f78 100644
--- a/src/plugins/vcsbase/checkoutwizarddialog.h
+++ b/src/plugins/vcsbase/checkoutwizarddialog.h
@@ -35,7 +35,7 @@
#include <utils/wizard.h>
namespace VcsBase {
-class AbstractCheckoutJob;
+class Command;
namespace Internal {
class CheckoutProgressWizardPage;
@@ -48,7 +48,9 @@ public:
explicit CheckoutWizardDialog(const QList<QWizardPage *> &parameterPages,
QWidget *parent = 0);
- void start(const QSharedPointer<AbstractCheckoutJob> &job);
+ void setTitle(const QString &title);
+ void setStartedStatus(const QString &title);
+ void start(VcsBase::Command *command);
signals:
void progressPageShown();
diff --git a/src/plugins/vcsbase/cleandialog.cpp b/src/plugins/vcsbase/cleandialog.cpp
index 73087c0bf4..20a4dd7b14 100644
--- a/src/plugins/vcsbase/cleandialog.cpp
+++ b/src/plugins/vcsbase/cleandialog.cpp
@@ -32,7 +32,6 @@
#include "vcsbaseoutputwindow.h"
#include <coreplugin/editormanager/editormanager.h>
-#include <coreplugin/icore.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <QStandardItemModel>
@@ -269,8 +268,7 @@ bool CleanDialog::promptToDelete()
QFuture<void> task = QtConcurrent::run(cleanTask, &Internal::CleanFilesTask::run);
const QString taskName = tr("Cleaning %1").
arg(QDir::toNativeSeparators(d->m_workingDirectory));
- Core::ICore::progressManager()->addTask(task, taskName,
- QLatin1String("VcsBase.cleanRepository"));
+ Core::ProgressManager::addTask(task, taskName, "VcsBase.cleanRepository");
return true;
}
diff --git a/src/plugins/vcsbase/command.cpp b/src/plugins/vcsbase/command.cpp
index 1f37b83638..24fd466e9f 100644
--- a/src/plugins/vcsbase/command.cpp
+++ b/src/plugins/vcsbase/command.cpp
@@ -28,36 +28,49 @@
****************************************************************************/
#include "command.h"
+#include "vcsbaseplugin.h"
-#include <coreplugin/icore.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <coreplugin/vcsmanager.h>
+#include <coreplugin/icore.h>
+#include <vcsbase/vcsbaseoutputwindow.h>
#include <utils/synchronousprocess.h>
#include <utils/runextensions.h>
+#include <utils/qtcassert.h>
#include <QDebug>
#include <QProcess>
#include <QProcessEnvironment>
#include <QFuture>
+#include <QFutureWatcher>
#include <QtConcurrentRun>
#include <QFileInfo>
#include <QCoreApplication>
#include <QVariant>
#include <QStringList>
+#include <QTextCodec>
+#include <QMutex>
Q_DECLARE_METATYPE(QVariant)
-static QString msgTermination(int exitCode, const QString &binaryPath, const QStringList &args)
-{
- QString cmd = QFileInfo(binaryPath).baseName();
- if (!args.empty()) {
- cmd += QLatin1Char(' ');
- cmd += args.front();
- }
- return exitCode ?
- QCoreApplication::translate("VcsCommand", "\n'%1' failed (exit code %2).\n").arg(cmd).arg(exitCode) :
- QCoreApplication::translate("VcsCommand", "\n'%1' completed (exit code %2).\n").arg(cmd).arg(exitCode);
-}
+enum { debugExecution = 0 };
+
+/*!
+ \fn void VcsBase::ProgressParser::parseProgress(const QString &text)
+
+ Reimplement to parse progress as it appears in the standard output.
+ If a progress string is detected, call \c setProgressAndMaximum() to update
+ the progress bar accordingly.
+
+ \sa VcsBase::ProgressParser::setProgressAndMaximum()
+*/
+
+/*!
+ \fn void VcsBase::ProgressParser::setProgressAndMaximum(int value, int maximum)
+
+ Sets progress \a value and \a maximum for current command. Called by \c parseProgress()
+ when a progress string is detected.
+*/
namespace VcsBase {
namespace Internal {
@@ -66,26 +79,35 @@ class CommandPrivate
{
public:
struct Job {
- explicit Job(const QStringList &a, int t);
+ explicit Job(const QStringList &a, int t, Utils::ExitCodeInterpreter *interpreter = 0);
QStringList arguments;
int timeout;
+ Utils::ExitCodeInterpreter *exitCodeInterpreter;
};
CommandPrivate(const QString &binary,
const QString &workingDirectory,
const QProcessEnvironment &environment);
+ ~CommandPrivate();
const QString m_binaryPath;
const QString m_workingDirectory;
const QProcessEnvironment m_environment;
QVariant m_cookie;
- bool m_unixTerminalDisabled;
int m_defaultTimeout;
- bool m_expectChanges;
+ unsigned m_flags;
+ QTextCodec *m_codec;
+ const QString m_sshPasswordPrompt;
+ ProgressParser *m_progressParser;
+ VcsBase::VcsBaseOutputWindow *m_outputWindow;
+ bool m_progressiveOutput;
+ bool m_hadOutput;
+ bool m_preventRepositoryChanged;
+ bool m_aborted;
+ QFutureWatcher<void> m_watcher;
QList<Job> m_jobs;
- Command::TerminationReportMode m_reportTerminationMode;
bool m_lastExecSuccess;
int m_lastExecExitCode;
@@ -97,18 +119,30 @@ CommandPrivate::CommandPrivate(const QString &binary,
m_binaryPath(binary),
m_workingDirectory(workingDirectory),
m_environment(environment),
- m_unixTerminalDisabled(false),
m_defaultTimeout(10),
- m_expectChanges(false),
- m_reportTerminationMode(Command::NoReport),
+ m_flags(0),
+ m_codec(0),
+ m_sshPasswordPrompt(VcsBasePlugin::sshPrompt()),
+ m_progressParser(0),
+ m_outputWindow(VcsBase::VcsBaseOutputWindow::instance()),
+ m_progressiveOutput(false),
+ m_hadOutput(false),
+ m_preventRepositoryChanged(false),
+ m_aborted(false),
m_lastExecSuccess(false),
m_lastExecExitCode(-1)
{
}
-CommandPrivate::Job::Job(const QStringList &a, int t) :
+CommandPrivate::~CommandPrivate()
+{
+ delete m_progressParser;
+}
+
+CommandPrivate::Job::Job(const QStringList &a, int t, Utils::ExitCodeInterpreter *interpreter) :
arguments(a),
- timeout(t)
+ timeout(t),
+ exitCodeInterpreter(interpreter)
{
// Finished cookie is emitted via queued slot, needs metatype
static const int qvMetaId = qRegisterMetaType<QVariant>();
@@ -122,6 +156,8 @@ Command::Command(const QString &binary,
const QProcessEnvironment &environment) :
d(new Internal::CommandPrivate(binary, workingDirectory, environment))
{
+ connect(Core::ICore::instance(), SIGNAL(coreAboutToClose()),
+ this, SLOT(coreAboutToClose()));
}
Command::~Command()
@@ -144,16 +180,6 @@ const QProcessEnvironment &Command::processEnvironment() const
return d->m_environment;
}
-Command::TerminationReportMode Command::reportTerminationMode() const
-{
- return d->m_reportTerminationMode;
-}
-
-void Command::setTerminationReportMode(TerminationReportMode m)
-{
- d->m_reportTerminationMode = m;
-}
-
int Command::defaultTimeout() const
{
return d->m_defaultTimeout;
@@ -164,34 +190,24 @@ void Command::setDefaultTimeout(int timeout)
d->m_defaultTimeout = timeout;
}
-bool Command::unixTerminalDisabled() const
-{
- return d->m_unixTerminalDisabled;
-}
-
-void Command::setUnixTerminalDisabled(bool e)
+unsigned Command::flags() const
{
- d->m_unixTerminalDisabled = e;
+ return d->m_flags;
}
-bool Command::expectChanges() const
+void Command::addFlags(unsigned f)
{
- return d->m_expectChanges;
+ d->m_flags |= f;
}
-void Command::setExpectChanges(bool e)
+void Command::addJob(const QStringList &arguments, Utils::ExitCodeInterpreter *interpreter)
{
- d->m_expectChanges = e;
+ addJob(arguments, defaultTimeout(), interpreter);
}
-void Command::addJob(const QStringList &arguments)
+void Command::addJob(const QStringList &arguments, int timeout, Utils::ExitCodeInterpreter *interpreter)
{
- addJob(arguments, defaultTimeout());
-}
-
-void Command::addJob(const QStringList &arguments, int timeout)
-{
- d->m_jobs.push_back(Internal::CommandPrivate::Job(arguments, timeout));
+ d->m_jobs.push_back(Internal::CommandPrivate::Job(arguments, timeout, interpreter));
}
void Command::execute()
@@ -204,12 +220,26 @@ void Command::execute()
// For some reason QtConcurrent::run() only works on this
QFuture<void> task = QtConcurrent::run(&Command::run, this);
+ d->m_watcher.setFuture(task);
+ connect(&d->m_watcher, SIGNAL(canceled()), this, SLOT(cancel()));
QString binary = QFileInfo(d->m_binaryPath).baseName();
if (!binary.isEmpty())
binary = binary.replace(0, 1, binary[0].toUpper()); // Upper the first letter
const QString taskName = binary + QLatin1Char(' ') + d->m_jobs.front().arguments.at(0);
- Core::ICore::progressManager()->addTask(task, taskName, binary + QLatin1String(".action"));
+ Core::ProgressManager::addTask(task, taskName,
+ Core::Id::fromString(binary + QLatin1String(".action")));
+}
+
+void Command::abort()
+{
+ d->m_aborted = true;
+ d->m_watcher.future().cancel();
+}
+
+void Command::cancel()
+{
+ emit terminate();
}
bool Command::lastExecutionSuccess() const
@@ -222,11 +252,6 @@ int Command::lastExecutionExitCode() const
return d->m_lastExecExitCode;
}
-QString Command::msgTimeout(int seconds)
-{
- return tr("Error: VCS timed out after %1s.").arg(seconds);
-}
-
void Command::run(QFutureInterface<void> &future)
{
// Check that the binary path is not empty
@@ -235,102 +260,324 @@ void Command::run(QFutureInterface<void> &future)
return;
}
- const unsigned processFlags = unixTerminalDisabled() ?
- unsigned(Utils::SynchronousProcess::UnixTerminalDisabled) :
- unsigned(0);
- const QSharedPointer<QProcess> process = Utils::SynchronousProcess::createProcess(processFlags);
- if (!workingDirectory().isEmpty())
- process->setWorkingDirectory(workingDirectory());
-
- process->setProcessEnvironment(processEnvironment());
-
- QByteArray stdOut;
- QByteArray stdErr;
- QString error;
+ QString stdOut;
+ QString stdErr;
+ if (d->m_progressParser)
+ d->m_progressParser->setFuture(&future);
+ else
+ future.setProgressRange(0, 1);
const int count = d->m_jobs.size();
- int exitCode = -1;
- bool ok = true;
+ d->m_lastExecExitCode = -1;
+ d->m_lastExecSuccess = true;
for (int j = 0; j < count; j++) {
- process->start(binaryPath(), d->m_jobs.at(j).arguments);
- if (!process->waitForStarted()) {
- ok = false;
- error += QString::fromLatin1("Error: \"%1\" could not be started: %2")
- .arg(binaryPath(), process->errorString());
+ const Internal::CommandPrivate::Job &job = d->m_jobs.at(j);
+ const int timeOutSeconds = job.timeout;
+ Utils::SynchronousProcessResponse resp = runVcs(
+ job.arguments,
+ timeOutSeconds >= 0 ? timeOutSeconds * 1000 : -1,
+ job.exitCodeInterpreter);
+ stdOut += resp.stdOut;
+ stdErr += resp.stdErr;
+ d->m_lastExecExitCode = resp.exitCode;
+ d->m_lastExecSuccess = resp.result == Utils::SynchronousProcessResponse::Finished;
+ if (!d->m_lastExecSuccess)
break;
+ }
+
+ if (!d->m_aborted) {
+ if (!d->m_progressiveOutput) {
+ emit output(stdOut);
+ if (!stdErr.isEmpty())
+ emit errorText(stdErr);
}
- process->closeWriteChannel();
- const int timeOutSeconds = d->m_jobs.at(j).timeout;
- if (!Utils::SynchronousProcess::readDataFromProcess(*process,
- timeOutSeconds >= 0 ? timeOutSeconds * 1000 : -1,
- &stdOut, &stdErr, false)) {
- Utils::SynchronousProcess::stopProcess(*process);
- ok = false;
- error += msgTimeout(timeOutSeconds);
- break;
+ emit finished(d->m_lastExecSuccess, d->m_lastExecExitCode, cookie());
+ if (d->m_lastExecSuccess)
+ emit success(cookie());
+ future.setProgressValue(future.progressMaximum());
+ }
+
+ if (d->m_progressParser)
+ d->m_progressParser->setFuture(0);
+ // As it is used asynchronously, we need to delete ourselves
+ this->deleteLater();
+}
+
+class OutputProxy : public QObject
+{
+ Q_OBJECT
+
+ friend class Command;
+
+public:
+ OutputProxy()
+ {
+ // Users of this class can either be in the GUI thread or in other threads.
+ // Use Qt::AutoConnection to always append in the GUI thread (directly or queued)
+ VcsBase::VcsBaseOutputWindow *outputWindow = VcsBase::VcsBaseOutputWindow::instance();
+ connect(this, SIGNAL(append(QString)), outputWindow, SLOT(append(QString)));
+ connect(this, SIGNAL(appendSilently(QString)), outputWindow, SLOT(appendSilently(QString)));
+ connect(this, SIGNAL(appendError(QString)), outputWindow, SLOT(appendError(QString)));
+ connect(this, SIGNAL(appendCommand(QString,QString,QStringList)),
+ outputWindow, SLOT(appendCommand(QString,QString,QStringList)));
+ connect(this, SIGNAL(appendMessage(QString)), outputWindow, SLOT(appendMessage(QString)));
+ }
+
+signals:
+ void append(const QString &text);
+ void appendSilently(const QString &text);
+ void appendError(const QString &text);
+ void appendCommand(const QString &workingDirectory,
+ const QString &binary,
+ const QStringList &args);
+ void appendMessage(const QString &text);
+};
+
+Utils::SynchronousProcessResponse Command::runVcs(const QStringList &arguments, int timeoutMS,
+ Utils::ExitCodeInterpreter *interpreter)
+{
+ Utils::SynchronousProcessResponse response;
+ OutputProxy outputProxy;
+
+ if (d->m_binaryPath.isEmpty()) {
+ response.result = Utils::SynchronousProcessResponse::StartFailed;
+ return response;
+ }
+
+ if (!(d->m_flags & VcsBasePlugin::SuppressCommandLogging))
+ emit outputProxy.appendCommand(d->m_workingDirectory, d->m_binaryPath, arguments);
+
+ const bool sshPromptConfigured = !d->m_sshPasswordPrompt.isEmpty();
+ if (debugExecution) {
+ QDebug nsp = qDebug().nospace();
+ nsp << "Command::runVcs" << d->m_workingDirectory << d->m_binaryPath << arguments
+ << timeoutMS;
+ if (d->m_flags & VcsBasePlugin::ShowStdOutInLogWindow)
+ nsp << "stdout";
+ if (d->m_flags & VcsBasePlugin::SuppressStdErrInLogWindow)
+ nsp << "suppress_stderr";
+ if (d->m_flags & VcsBasePlugin::SuppressFailMessageInLogWindow)
+ nsp << "suppress_fail_msg";
+ if (d->m_flags & VcsBasePlugin::MergeOutputChannels)
+ nsp << "merge_channels";
+ if (d->m_flags & VcsBasePlugin::SshPasswordPrompt)
+ nsp << "ssh (" << sshPromptConfigured << ')';
+ if (d->m_flags & VcsBasePlugin::SuppressCommandLogging)
+ nsp << "suppress_log";
+ if (d->m_flags & VcsBasePlugin::ForceCLocale)
+ nsp << "c_locale";
+ if (d->m_flags & VcsBasePlugin::FullySynchronously)
+ nsp << "fully_synchronously";
+ if (d->m_flags & VcsBasePlugin::ExpectRepoChanges)
+ nsp << "expect_repo_changes";
+ if (d->m_codec)
+ nsp << " Codec: " << d->m_codec->name();
+ }
+
+ // TODO tell the document manager about expected repository changes
+ // if (d->m_flags & ExpectRepoChanges)
+ // Core::DocumentManager::expectDirectoryChange(d->m_workingDirectory);
+ if (d->m_flags & VcsBasePlugin::FullySynchronously) {
+ response = runSynchronous(arguments, timeoutMS, interpreter);
+ } else {
+ Utils::SynchronousProcess process;
+ process.setExitCodeInterpreter(interpreter);
+ connect(this, SIGNAL(terminate()), &process, SLOT(terminate()));
+ if (!d->m_workingDirectory.isEmpty())
+ process.setWorkingDirectory(d->m_workingDirectory);
+
+ QProcessEnvironment env = d->m_environment;
+ VcsBasePlugin::setProcessEnvironment(&env,
+ (d->m_flags & VcsBasePlugin::ForceCLocale),
+ d->m_sshPasswordPrompt);
+ process.setProcessEnvironment(env);
+ process.setTimeout(timeoutMS);
+ if (d->m_codec)
+ process.setCodec(d->m_codec);
+
+ // Suppress terminal on UNIX for ssh prompts if it is configured.
+ if (sshPromptConfigured && (d->m_flags & VcsBasePlugin::SshPasswordPrompt))
+ process.setFlags(Utils::SynchronousProcess::UnixTerminalDisabled);
+
+ // connect stderr to the output window if desired
+ if (d->m_flags & VcsBasePlugin::MergeOutputChannels) {
+ process.setProcessChannelMode(QProcess::MergedChannels);
+ } else if (d->m_progressiveOutput
+ || !(d->m_flags & VcsBasePlugin::SuppressStdErrInLogWindow)) {
+ process.setStdErrBufferedSignalsEnabled(true);
+ connect(&process, SIGNAL(stdErrBuffered(QString,bool)),
+ this, SLOT(bufferedError(QString)));
}
- error += QString::fromLocal8Bit(stdErr);
- exitCode = process->exitCode();
- switch (reportTerminationMode()) {
- case NoReport:
- break;
- case ReportStdout:
- stdOut += msgTermination(exitCode, binaryPath(), d->m_jobs.at(j).arguments).toUtf8();
- break;
- case ReportStderr:
- error += msgTermination(exitCode, binaryPath(), d->m_jobs.at(j).arguments);
- break;
+ // connect stdout to the output window if desired
+ if (d->m_progressParser || d->m_progressiveOutput
+ || (d->m_flags & VcsBasePlugin::ShowStdOutInLogWindow)) {
+ process.setStdOutBufferedSignalsEnabled(true);
+ connect(&process, SIGNAL(stdOutBuffered(QString,bool)), this, SLOT(bufferedOutput(QString)));
}
+
+ process.setTimeOutMessageBoxEnabled(true);
+
+ // Run!
+ response = process.run(d->m_binaryPath, arguments);
}
- if (!future.isCanceled()) {
- if (ok && d->m_jobs.front().arguments.at(0) == QLatin1String("status"))
- removeColorCodes(&stdOut);
+ if (!d->m_aborted) {
+ // Success/Fail message in appropriate window?
+ if (response.result == Utils::SynchronousProcessResponse::Finished) {
+ if (d->m_flags & VcsBasePlugin::ShowSuccessMessage)
+ emit outputProxy.appendMessage(response.exitMessage(d->m_binaryPath, timeoutMS));
+ } else if (!(d->m_flags & VcsBasePlugin::SuppressFailMessageInLogWindow)) {
+ emit outputProxy.appendError(response.exitMessage(d->m_binaryPath, timeoutMS));
+ }
+ }
+ emitRepositoryChanged();
- d->m_lastExecSuccess = ok;
- d->m_lastExecExitCode = exitCode;
+ return response;
+}
- if (ok)
- emit outputData(stdOut);
+Utils::SynchronousProcessResponse Command::runSynchronous(const QStringList &arguments, int timeoutMS,
+ Utils::ExitCodeInterpreter *interpreter)
+{
+ Utils::SynchronousProcessResponse response;
+
+ // Set up process
+ unsigned processFlags = 0;
+ if (!d->m_sshPasswordPrompt.isEmpty() && (d->m_flags & VcsBasePlugin::SshPasswordPrompt))
+ processFlags |= Utils::SynchronousProcess::UnixTerminalDisabled;
+ QSharedPointer<QProcess> process = Utils::SynchronousProcess::createProcess(processFlags);
+ if (!d->m_workingDirectory.isEmpty())
+ process->setWorkingDirectory(d->m_workingDirectory);
+ QProcessEnvironment env = d->m_environment;
+ VcsBasePlugin::setProcessEnvironment(&env,
+ (d->m_flags & VcsBasePlugin::ForceCLocale),
+ d->m_sshPasswordPrompt);
+ process->setProcessEnvironment(env);
+ if (d->m_flags & VcsBasePlugin::MergeOutputChannels)
+ process->setProcessChannelMode(QProcess::MergedChannels);
+
+ // Start
+ process->start(d->m_binaryPath, arguments, QIODevice::ReadOnly);
+ process->closeWriteChannel();
+ if (!process->waitForStarted()) {
+ response.result = Utils::SynchronousProcessResponse::StartFailed;
+ return response;
+ }
- if (!error.isEmpty())
- emit errorText(error);
+ // process output
+ QByteArray stdOut;
+ QByteArray stdErr;
+ const bool timedOut =
+ !Utils::SynchronousProcess::readDataFromProcess(*process.data(), timeoutMS,
+ &stdOut, &stdErr, true);
+
+ if (!d->m_aborted) {
+ OutputProxy outputProxy;
+ if (!stdErr.isEmpty()) {
+ response.stdErr = Utils::SynchronousProcess::normalizeNewlines(
+ d->m_codec ? d->m_codec->toUnicode(stdErr) : QString::fromLocal8Bit(stdErr));
+ if (!(d->m_flags & VcsBasePlugin::SuppressStdErrInLogWindow))
+ emit outputProxy.append(response.stdErr);
+ }
- emit finished(ok, exitCode, cookie());
- if (ok) {
- emit success(cookie());
- if (d->m_expectChanges)
- Core::ICore::vcsManager()->emitRepositoryChanged(d->m_workingDirectory);
+ if (!stdOut.isEmpty()) {
+ response.stdOut = Utils::SynchronousProcess::normalizeNewlines(
+ d->m_codec ? d->m_codec->toUnicode(stdOut) : QString::fromLocal8Bit(stdOut));
+ if (d->m_flags & VcsBasePlugin::ShowStdOutInLogWindow) {
+ if (d->m_flags & VcsBasePlugin::SilentOutput)
+ emit outputProxy.appendSilently(response.stdOut);
+ else
+ emit outputProxy.append(response.stdOut);
+ }
}
}
- // As it is used asynchronously, we need to delete ourselves
- this->deleteLater();
+ Utils::ExitCodeInterpreter defaultInterpreter(this);
+ Utils::ExitCodeInterpreter *currentInterpreter = interpreter ? interpreter : &defaultInterpreter;
+ // Result
+ if (timedOut) {
+ response.result = Utils::SynchronousProcessResponse::Hang;
+ } else if (process->exitStatus() != QProcess::NormalExit) {
+ response.result = Utils::SynchronousProcessResponse::TerminatedAbnormally;
+ } else {
+ response.result = currentInterpreter->interpretExitCode(process->exitCode());
+ }
+ return response;
}
-// Clean output from carriage return and ANSI color codes.
-// @TODO: Remove once all relevant commands support "--no-color",
-//("status" is missing it as of git 1.6.2)
+void Command::emitRepositoryChanged()
+{
+ if (d->m_preventRepositoryChanged || !(d->m_flags & VcsBasePlugin::ExpectRepoChanges))
+ return;
+ // TODO tell the document manager that the directory now received all expected changes
+ // Core::DocumentManager::unexpectDirectoryChange(d->m_workingDirectory);
+ Core::VcsManager::emitRepositoryChanged(d->m_workingDirectory);
+}
-void Command::removeColorCodes(QByteArray *data)
+bool Command::runFullySynchronous(const QStringList &arguments, int timeoutMS,
+ QByteArray *outputData, QByteArray *errorData)
{
- // Remove ansi color codes that look like "ESC[<stuff>m"
- const QByteArray ansiColorEscape("\033[");
- int escapePos = 0;
- while (true) {
- const int nextEscapePos = data->indexOf(ansiColorEscape, escapePos);
- if (nextEscapePos == -1)
- break;
- const int endEscapePos = data->indexOf('m', nextEscapePos + ansiColorEscape.size());
- if (endEscapePos != -1) {
- data->remove(nextEscapePos, endEscapePos - nextEscapePos + 1);
- escapePos = nextEscapePos;
- } else {
- escapePos = nextEscapePos + ansiColorEscape.size();
+ if (d->m_binaryPath.isEmpty())
+ return false;
+
+ OutputProxy outputProxy;
+ if (!(d->m_flags & VcsBasePlugin::SuppressCommandLogging))
+ emit outputProxy.appendCommand(d->m_workingDirectory, d->m_binaryPath, arguments);
+
+ // TODO tell the document manager about expected repository changes
+ // if (d->m_flags & ExpectRepoChanges)
+ // Core::DocumentManager::expectDirectoryChange(workingDirectory);
+ QProcess process;
+ process.setWorkingDirectory(d->m_workingDirectory);
+ process.setProcessEnvironment(d->m_environment);
+
+ process.start(d->m_binaryPath, arguments);
+ process.closeWriteChannel();
+ if (!process.waitForStarted()) {
+ if (errorData) {
+ const QString msg = QString::fromLatin1("Unable to execute '%1': %2:")
+ .arg(d->m_binaryPath, process.errorString());
+ *errorData = msg.toLocal8Bit();
}
+ return false;
+ }
+
+ if (!Utils::SynchronousProcess::readDataFromProcess(process, timeoutMS, outputData, errorData, true)) {
+ if (errorData)
+ errorData->append(tr("Error: Executable timed out after %1s.").arg(timeoutMS / 1000).toLocal8Bit());
+ Utils::SynchronousProcess::stopProcess(process);
+ return false;
}
+
+ emitRepositoryChanged();
+ return process.exitStatus() == QProcess::NormalExit && process.exitCode() == 0;
+}
+
+void Command::bufferedOutput(const QString &text)
+{
+ if (d->m_progressParser)
+ d->m_progressParser->parseProgress(text);
+ if (d->m_flags & VcsBasePlugin::ShowStdOutInLogWindow)
+ d->m_outputWindow->append(text);
+ if (d->m_progressiveOutput) {
+ emit output(text);
+ d->m_hadOutput = true;
+ }
+}
+
+void Command::bufferedError(const QString &text)
+{
+ if (!(d->m_flags & VcsBasePlugin::SuppressStdErrInLogWindow))
+ d->m_outputWindow->appendError(text);
+ if (d->m_progressiveOutput)
+ emit errorText(text);
+}
+
+void Command::coreAboutToClose()
+{
+ d->m_preventRepositoryChanged = true;
+ abort();
}
const QVariant &Command::cookie() const
@@ -343,4 +590,54 @@ void Command::setCookie(const QVariant &cookie)
d->m_cookie = cookie;
}
+QTextCodec *Command::codec() const
+{
+ return d->m_codec;
+}
+
+void Command::setCodec(QTextCodec *codec)
+{
+ d->m_codec = codec;
+}
+
+//! Use \a parser to parse progress data from stdout. Command takes ownership of \a parser
+void Command::setProgressParser(ProgressParser *parser)
+{
+ QTC_ASSERT(!d->m_progressParser, return);
+ d->m_progressParser = parser;
+}
+
+void Command::setProgressiveOutput(bool progressive)
+{
+ d->m_progressiveOutput = progressive;
+}
+
+ProgressParser::ProgressParser() :
+ m_future(0),
+ m_futureMutex(new QMutex)
+{
+}
+
+ProgressParser::~ProgressParser()
+{
+ delete m_futureMutex;
+}
+
+void ProgressParser::setProgressAndMaximum(int value, int maximum)
+{
+ QMutexLocker lock(m_futureMutex);
+ if (!m_future)
+ return;
+ m_future->setProgressRange(0, maximum);
+ m_future->setProgressValue(value);
+}
+
+void ProgressParser::setFuture(QFutureInterface<void> *future)
+{
+ QMutexLocker lock(m_futureMutex);
+ m_future = future;
+}
+
} // namespace VcsBase
+
+#include "command.moc"
diff --git a/src/plugins/vcsbase/command.h b/src/plugins/vcsbase/command.h
index efc71e4669..b44dc3e57a 100644
--- a/src/plugins/vcsbase/command.h
+++ b/src/plugins/vcsbase/command.h
@@ -32,9 +32,12 @@
#include "vcsbase_global.h"
+#include <utils/synchronousprocess.h>
+
#include <QObject>
QT_BEGIN_NAMESPACE
+class QMutex;
class QStringList;
class QVariant;
class QProcessEnvironment;
@@ -46,66 +49,89 @@ namespace VcsBase {
namespace Internal { class CommandPrivate; }
+class VCSBASE_EXPORT ProgressParser
+{
+public:
+ ProgressParser();
+ virtual ~ProgressParser();
+
+protected:
+ virtual void parseProgress(const QString &text) = 0;
+ void setProgressAndMaximum(int value, int maximum);
+
+private:
+ void setFuture(QFutureInterface<void> *future);
+
+ QFutureInterface<void> *m_future;
+ QMutex *m_futureMutex;
+ friend class Command;
+};
+
class VCSBASE_EXPORT Command : public QObject
{
Q_OBJECT
public:
- // Where to report command termination with exit code if desired
- enum TerminationReportMode
- {
- NoReport,
- ReportStdout, // This assumes UTF8
- ReportStderr
- };
-
Command(const QString &binary,
const QString &workingDirectory,
const QProcessEnvironment &environment);
~Command();
- void addJob(const QStringList &arguments);
- void addJob(const QStringList &arguments, int timeout);
+ void addJob(const QStringList &arguments, Utils::ExitCodeInterpreter *interpreter = 0);
+ void addJob(const QStringList &arguments, int timeout, Utils::ExitCodeInterpreter *interpreter = 0);
void execute();
+ void abort();
bool lastExecutionSuccess() const;
int lastExecutionExitCode() const;
- // Clean output from carriage return and ANSI color codes
- // Workaround until all relevant commands support "--no-color"
- static void removeColorCodes(QByteArray *data);
-
const QString &binaryPath() const;
const QString &workingDirectory() const;
const QProcessEnvironment &processEnvironment() const;
- // Report command termination with exit code
- TerminationReportMode reportTerminationMode() const;
- void setTerminationReportMode(TerminationReportMode m);
-
int defaultTimeout() const;
void setDefaultTimeout(int timeout);
- // Disable Terminal on UNIX (see VCS SSH handling)
- bool unixTerminalDisabled() const;
- void setUnixTerminalDisabled(bool);
-
- bool expectChanges() const;
- void setExpectChanges(bool);
-
- static QString msgTimeout(int seconds);
+ unsigned flags() const;
+ void addFlags(unsigned f);
const QVariant &cookie() const;
void setCookie(const QVariant &cookie);
+ QTextCodec *codec() const;
+ void setCodec(QTextCodec *codec);
+
+ void setProgressParser(ProgressParser *parser);
+ void setProgressiveOutput(bool progressive);
+
+ Utils::SynchronousProcessResponse runVcs(const QStringList &arguments, int timeoutMS,
+ Utils::ExitCodeInterpreter *interpreter = 0);
+ // Make sure to not pass through the event loop at all:
+ bool runFullySynchronous(const QStringList &arguments, int timeoutMS,
+ QByteArray *outputData, QByteArray *errorData);
+
private:
void run(QFutureInterface<void> &future);
+ Utils::SynchronousProcessResponse runSynchronous(const QStringList &arguments, int timeoutMS,
+ Utils::ExitCodeInterpreter *interpreter = 0);
+ void emitRepositoryChanged();
+
+public slots:
+ void cancel();
signals:
- void outputData(const QByteArray &);
+ void output(const QString &);
void errorText(const QString &);
void finished(bool ok, int exitCode, const QVariant &cookie);
void success(const QVariant &cookie);
+private slots:
+ void bufferedOutput(const QString &text);
+ void bufferedError(const QString &text);
+ void coreAboutToClose();
+
+signals:
+ void terminate(); // Internal
+
private:
class Internal::CommandPrivate *const d;
};
diff --git a/src/plugins/vcsbase/diffhighlighter.cpp b/src/plugins/vcsbase/diffhighlighter.cpp
index 9a26fa5f58..5798c30a73 100644
--- a/src/plugins/vcsbase/diffhighlighter.cpp
+++ b/src/plugins/vcsbase/diffhighlighter.cpp
@@ -72,8 +72,7 @@ enum DiffFormats {
DiffInFormat,
DiffOutFormat,
DiffFileFormat,
- DiffLocationFormat,
- NumDiffFormats
+ DiffLocationFormat
};
enum FoldingState {
@@ -83,61 +82,92 @@ enum FoldingState {
Location
};
+}; // namespace Internal;
+
+static inline QTextCharFormat invertedColorFormat(const QTextCharFormat &in)
+{
+ QTextCharFormat rc = in;
+ rc.setForeground(in.background());
+ rc.setBackground(in.foreground());
+ return rc;
+}
+
// --- DiffHighlighterPrivate
class DiffHighlighterPrivate
{
+ DiffHighlighter *q_ptr;
+ Q_DECLARE_PUBLIC(DiffHighlighter)
public:
DiffHighlighterPrivate(const QRegExp &filePattern);
- DiffFormats analyzeLine(const QString &block) const;
+ Internal::DiffFormats analyzeLine(const QString &block) const;
+ void updateOtherFormats();
mutable QRegExp m_filePattern;
const QString m_locationIndicator;
const QChar m_diffInIndicator;
const QChar m_diffOutIndicator;
- QTextCharFormat m_formats[NumDiffFormats];
QTextCharFormat m_addedTrailingWhiteSpaceFormat;
- FoldingState m_foldingState;
+ Internal::FoldingState m_foldingState;
};
DiffHighlighterPrivate::DiffHighlighterPrivate(const QRegExp &filePattern) :
+ q_ptr(0),
m_filePattern(filePattern),
m_locationIndicator(QLatin1String("@@")),
m_diffInIndicator(QLatin1Char('+')),
m_diffOutIndicator(QLatin1Char('-')),
- m_foldingState(StartOfFile)
+ m_foldingState(Internal::StartOfFile)
{
QTC_CHECK(filePattern.isValid());
}
-DiffFormats DiffHighlighterPrivate::analyzeLine(const QString &text) const
+Internal::DiffFormats DiffHighlighterPrivate::analyzeLine(const QString &text) const
{
// Do not match on git "--- a/" as a deleted line, check
// file first
if (m_filePattern.indexIn(text) == 0)
- return DiffFileFormat;
+ return Internal::DiffFileFormat;
if (text.startsWith(m_diffInIndicator))
- return DiffInFormat;
+ return Internal::DiffInFormat;
if (text.startsWith(m_diffOutIndicator))
- return DiffOutFormat;
+ return Internal::DiffOutFormat;
if (text.startsWith(m_locationIndicator))
- return DiffLocationFormat;
- return DiffTextFormat;
+ return Internal::DiffLocationFormat;
+ return Internal::DiffTextFormat;
}
-} // namespace Internal
+void DiffHighlighterPrivate::updateOtherFormats()
+{
+ Q_Q(DiffHighlighter);
+ m_addedTrailingWhiteSpaceFormat =
+ invertedColorFormat(q->formatForCategory(Internal::DiffInFormat));
+
+}
// --- DiffHighlighter
DiffHighlighter::DiffHighlighter(const QRegExp &filePattern) :
TextEditor::SyntaxHighlighter(static_cast<QTextDocument *>(0)),
- d(new Internal::DiffHighlighterPrivate(filePattern))
+ d_ptr(new DiffHighlighterPrivate(filePattern))
{
+ d_ptr->q_ptr = this;
+ Q_D(DiffHighlighter);
+
+ static QVector<TextEditor::TextStyle> categories;
+ if (categories.isEmpty()) {
+ categories << TextEditor::C_TEXT
+ << TextEditor::C_ADDED_LINE
+ << TextEditor::C_REMOVED_LINE
+ << TextEditor::C_DIFF_FILE
+ << TextEditor::C_DIFF_LOCATION;
+ }
+ setTextFormatCategories(categories);
+ d->updateOtherFormats();
}
DiffHighlighter::~DiffHighlighter()
{
- delete d;
}
// Check trailing spaces
@@ -157,6 +187,7 @@ static inline int trimmedLength(const QString &in)
*/
void DiffHighlighter::highlightBlock(const QString &text)
{
+ Q_D(DiffHighlighter);
if (text.isEmpty())
return;
@@ -168,13 +199,13 @@ void DiffHighlighter::highlightBlock(const QString &text)
case Internal::DiffInFormat: {
// Mark trailing whitespace.
const int trimmedLen = trimmedLength(text);
- setFormat(0, trimmedLen, d->m_formats[format]);
+ setFormat(0, trimmedLen, formatForCategory(format));
if (trimmedLen != length)
setFormat(trimmedLen, length - trimmedLen, d->m_addedTrailingWhiteSpaceFormat);
}
break;
default:
- setFormat(0, length, d->m_formats[format]);
+ setFormat(0, length, formatForCategory(format));
break;
}
@@ -234,24 +265,11 @@ void DiffHighlighter::highlightBlock(const QString &text)
}
}
-static inline QTextCharFormat invertedColorFormat(const QTextCharFormat &in)
+void DiffHighlighter::setFontSettings(const TextEditor::FontSettings &fontSettings)
{
- QTextCharFormat rc = in;
- rc.setForeground(in.background());
- rc.setBackground(in.foreground());
- return rc;
-}
-
-void DiffHighlighter::setFormats(const QVector<QTextCharFormat> &s)
-{
- if (s.size() == Internal::NumDiffFormats) {
- qCopy(s.constBegin(), s.constEnd(), d->m_formats);
- // Display trailing blanks with colors swapped
- d->m_addedTrailingWhiteSpaceFormat =
- invertedColorFormat(d->m_formats[Internal::DiffInFormat]);
- } else {
- qWarning("%s: insufficient setting size: %d", Q_FUNC_INFO, s.size());
- }
+ Q_D(DiffHighlighter);
+ SyntaxHighlighter::setFontSettings(fontSettings);
+ d->updateOtherFormats();
}
} // namespace VcsBase
diff --git a/src/plugins/vcsbase/diffhighlighter.h b/src/plugins/vcsbase/diffhighlighter.h
index be55af5fc2..6ce2692e18 100644
--- a/src/plugins/vcsbase/diffhighlighter.h
+++ b/src/plugins/vcsbase/diffhighlighter.h
@@ -44,23 +44,22 @@ namespace TextEditor { class FontSettingsPage; }
namespace VcsBase {
-namespace Internal { class DiffHighlighterPrivate; }
+class DiffHighlighterPrivate;
class VCSBASE_EXPORT DiffHighlighter : public TextEditor::SyntaxHighlighter
{
Q_OBJECT
-
+ Q_DECLARE_PRIVATE(DiffHighlighter)
public:
explicit DiffHighlighter(const QRegExp &filePattern);
~DiffHighlighter();
void highlightBlock(const QString &text);
- // Set formats from a sequence of type QTextCharFormat
- void setFormats(const QVector<QTextCharFormat> &s);
+ virtual void setFontSettings(const TextEditor::FontSettings &fontSettings);
private:
- Internal::DiffHighlighterPrivate *const d;
+ QScopedPointer<DiffHighlighterPrivate> d_ptr;
};
} // namespace VcsBase
diff --git a/src/plugins/vcsbase/submiteditorfile.cpp b/src/plugins/vcsbase/submiteditorfile.cpp
index c07e604c1b..1d107262d4 100644
--- a/src/plugins/vcsbase/submiteditorfile.cpp
+++ b/src/plugins/vcsbase/submiteditorfile.cpp
@@ -29,6 +29,12 @@
#include "submiteditorfile.h"
+#include "vcsbasesubmiteditor.h"
+
+#include <utils/fileutils.h>
+
+#include <QFileInfo>
+
using namespace VcsBase;
using namespace VcsBase::Internal;
@@ -39,26 +45,18 @@ using namespace VcsBase::Internal;
submit editor files.
*/
-SubmitEditorFile::SubmitEditorFile(const QString &mimeType, QObject *parent) :
+SubmitEditorFile::SubmitEditorFile(const QString &mimeType, VcsBaseSubmitEditor *parent) :
Core::IDocument(parent),
m_mimeType(mimeType),
- m_modified(false)
+ m_modified(false),
+ m_editor(parent)
{
+ setTemporary(true);
}
-void SubmitEditorFile::rename(const QString &newName)
+bool SubmitEditorFile::setContents(const QByteArray &contents)
{
- Q_UNUSED(newName);
- // We can't be renamed
- return;
-}
-
-void SubmitEditorFile::setFileName(const QString &name)
-{
- if (m_fileName == name)
- return;
- m_fileName = name;
- emit changed();
+ return m_editor->setFileContents(contents);
}
void SubmitEditorFile::setModified(bool modified)
@@ -71,7 +69,16 @@ void SubmitEditorFile::setModified(bool modified)
bool SubmitEditorFile::save(QString *errorString, const QString &fileName, bool autoSave)
{
- emit saveMe(errorString, fileName, autoSave);
+ const QString fName = fileName.isEmpty() ? filePath() : fileName;
+ Utils::FileSaver saver(fName, QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text);
+ saver.write(m_editor->fileContents());
+ if (!saver.finalize(errorString))
+ return false;
+ if (autoSave)
+ return true;
+ const QFileInfo fi(fName);
+ setFilePath(fi.absoluteFilePath());
+ setModified(false);
if (!errorString->isEmpty())
return false;
emit changed();
diff --git a/src/plugins/vcsbase/submiteditorfile.h b/src/plugins/vcsbase/submiteditorfile.h
index 51887946a1..4623a211d3 100644
--- a/src/plugins/vcsbase/submiteditorfile.h
+++ b/src/plugins/vcsbase/submiteditorfile.h
@@ -33,6 +33,8 @@
#include <coreplugin/idocument.h>
namespace VcsBase {
+class VcsBaseSubmitEditor;
+
namespace Internal {
class SubmitEditorFile : public Core::IDocument
@@ -40,9 +42,9 @@ class SubmitEditorFile : public Core::IDocument
Q_OBJECT
public:
explicit SubmitEditorFile(const QString &mimeType,
- QObject *parent = 0);
+ VcsBaseSubmitEditor *parent = 0);
- QString fileName() const { return m_fileName; }
+ bool setContents(const QByteArray &contents);
QString defaultPath() const { return QString(); }
QString suggestedFileName() const { return QString(); }
@@ -52,18 +54,13 @@ public:
bool save(QString *errorString, const QString &fileName, bool autoSave);
ReloadBehavior reloadBehavior(ChangeTrigger state, ChangeType type) const;
bool reload(QString *errorString, ReloadFlag flag, ChangeType type);
- void rename(const QString &newName);
- void setFileName(const QString &name);
void setModified(bool modified = true);
-signals:
- void saveMe(QString *errorString, const QString &fileName, bool autoSave);
-
private:
const QString m_mimeType;
bool m_modified;
- QString m_fileName;
+ VcsBaseSubmitEditor *m_editor;
};
diff --git a/src/plugins/vcsbase/submiteditorwidget.cpp b/src/plugins/vcsbase/submiteditorwidget.cpp
index 192b9d5ccd..473bb10862 100644
--- a/src/plugins/vcsbase/submiteditorwidget.cpp
+++ b/src/plugins/vcsbase/submiteditorwidget.cpp
@@ -37,7 +37,6 @@
#include <QTimer>
#include <QScopedPointer>
-#include <QPushButton>
#include <QMenu>
#include <QHBoxLayout>
#include <QToolButton>
@@ -75,7 +74,7 @@ namespace VcsBase {
// QActionPushButton: A push button tied to an action
// (similar to a QToolButton)
-class QActionPushButton : public QPushButton
+class QActionPushButton : public QToolButton
{
Q_OBJECT
public:
@@ -86,8 +85,11 @@ private slots:
};
QActionPushButton::QActionPushButton(QAction *a) :
- QPushButton(a->icon(), a->text())
+ QToolButton()
{
+ setIcon(a->icon());
+ setText(a->text());
+ setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
connect(a, SIGNAL(changed()), this, SLOT(actionChanged()));
connect(this, SIGNAL(clicked()), a, SLOT(trigger()));
setEnabled(a->isEnabled());
@@ -153,6 +155,8 @@ struct SubmitEditorWidgetPrivate
bool m_commitEnabled;
bool m_ignoreChange;
bool m_descriptionMandatory;
+
+ QActionPushButton *m_submitButton;
};
SubmitEditorWidgetPrivate::SubmitEditorWidgetPrivate() :
@@ -164,7 +168,8 @@ SubmitEditorWidgetPrivate::SubmitEditorWidgetPrivate() :
m_lineWidth(defaultLineWidth),
m_commitEnabled(false),
m_ignoreChange(false),
- m_descriptionMandatory(true)
+ m_descriptionMandatory(true),
+ m_submitButton(0)
{
}
@@ -229,7 +234,8 @@ void SubmitEditorWidget::registerActions(QAction *editorUndoAction, QAction *edi
if (!actionSlotHelper)
actionSlotHelper = new QActionSetTextSlotHelper(submitAction);
connect(this, SIGNAL(submitActionTextChanged(QString)), actionSlotHelper, SLOT(setText(QString)));
- d->m_ui.buttonLayout->addWidget(new QActionPushButton(submitAction));
+ d->m_submitButton = new QActionPushButton(submitAction);
+ d->m_ui.buttonLayout->addWidget(d->m_submitButton);
if (!d->m_submitShortcut)
d->m_submitShortcut = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Return), this);
connect(d->m_submitShortcut, SIGNAL(activated()), submitAction, SLOT(trigger()));
@@ -523,6 +529,11 @@ void SubmitEditorWidget::insertTopWidget(QWidget *w)
d->m_ui.vboxLayout->insertWidget(0, w);
}
+void SubmitEditorWidget::addSubmitButtonMenu(QMenu *menu)
+{
+ d->m_submitButton->setMenu(menu);
+}
+
void SubmitEditorWidget::hideDescription()
{
d->m_ui.descriptionBox->hide();
diff --git a/src/plugins/vcsbase/submiteditorwidget.h b/src/plugins/vcsbase/submiteditorwidget.h
index 7860eb42c0..8cec7a0c5d 100644
--- a/src/plugins/vcsbase/submiteditorwidget.h
+++ b/src/plugins/vcsbase/submiteditorwidget.h
@@ -121,6 +121,7 @@ protected:
virtual QString cleanupDescription(const QString &) const;
virtual QString commitName() const;
void insertTopWidget(QWidget *w);
+ void addSubmitButtonMenu(QMenu *menu);
void hideDescription();
protected slots:
diff --git a/src/plugins/vcsbase/submitfilemodel.cpp b/src/plugins/vcsbase/submitfilemodel.cpp
index c7c8c1b118..933fcc59f2 100644
--- a/src/plugins/vcsbase/submitfilemodel.cpp
+++ b/src/plugins/vcsbase/submitfilemodel.cpp
@@ -57,7 +57,7 @@ static QList<QStandardItem *> createFileRow(const QString &fileName, const QStri
statusItem->setData(v);
QStandardItem *fileItem = new QStandardItem(fileName);
fileItem->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled);
- fileItem->setIcon(Core::FileIconProvider::instance()->icon(QFileInfo(fileName)));
+ fileItem->setIcon(Core::FileIconProvider::icon(fileName));
QList<QStandardItem *> row;
row << statusItem << fileItem;
return row;
diff --git a/src/plugins/vcsbase/vcsbase.pro b/src/plugins/vcsbase/vcsbase.pro
index 3faed8be6b..807d501d17 100644
--- a/src/plugins/vcsbase/vcsbase.pro
+++ b/src/plugins/vcsbase/vcsbase.pro
@@ -20,7 +20,6 @@ HEADERS += vcsbase_global.h \
basecheckoutwizard.h \
checkoutwizarddialog.h \
checkoutprogresswizardpage.h \
- checkoutjobs.h \
basecheckoutwizardpage.h \
vcsbaseoutputwindow.h \
cleandialog.h \
@@ -50,7 +49,6 @@ SOURCES += vcsplugin.cpp \
basecheckoutwizard.cpp \
checkoutwizarddialog.cpp \
checkoutprogresswizardpage.cpp \
- checkoutjobs.cpp \
basecheckoutwizardpage.cpp \
vcsbaseoutputwindow.cpp \
cleandialog.cpp \
diff --git a/src/plugins/vcsbase/vcsbase.qbs b/src/plugins/vcsbase/vcsbase.qbs
index a3b1e11ca6..c901d3d9a1 100644
--- a/src/plugins/vcsbase/vcsbase.qbs
+++ b/src/plugins/vcsbase/vcsbase.qbs
@@ -25,8 +25,6 @@ QtcPlugin {
"basevcseditorfactory.h",
"basevcssubmiteditorfactory.cpp",
"basevcssubmiteditorfactory.h",
- "checkoutjobs.cpp",
- "checkoutjobs.h",
"checkoutprogresswizardpage.cpp",
"checkoutprogresswizardpage.h",
"checkoutprogresswizardpage.ui",
diff --git a/src/plugins/vcsbase/vcsbaseclient.cpp b/src/plugins/vcsbase/vcsbaseclient.cpp
index e6652842b4..feb4c5588b 100644
--- a/src/plugins/vcsbase/vcsbaseclient.cpp
+++ b/src/plugins/vcsbase/vcsbaseclient.cpp
@@ -67,9 +67,9 @@ Q_DECLARE_METATYPE(QVariant)
inline Core::IEditor *locateEditor(const char *property, const QString &entry)
{
- foreach (Core::IEditor *ed, Core::ICore::editorManager()->openedEditors())
- if (ed->document()->property(property).toString() == entry)
- return ed;
+ foreach (Core::IDocument *document, Core::EditorManager::documentModel()->openedDocuments())
+ if (document->property(property).toString() == entry)
+ return Core::EditorManager::documentModel()->editorsForDocument(document).first();
return 0;
}
@@ -89,7 +89,7 @@ class VcsBaseClientPrivate
public:
VcsBaseClientPrivate(VcsBaseClient *client, VcsBaseClientSettings *settings);
- void statusParser(QByteArray data);
+ void statusParser(const QString &text);
void annotateRevision(QString source, QString change, int lineNumber);
void saveSettings();
@@ -110,11 +110,11 @@ VcsBaseClientPrivate::VcsBaseClientPrivate(VcsBaseClient *client, VcsBaseClientS
{
}
-void VcsBaseClientPrivate::statusParser(QByteArray data)
+void VcsBaseClientPrivate::statusParser(const QString &text)
{
QList<VcsBaseClient::StatusItem> lineInfoList;
- QStringList rawStatusList = QTextCodec::codecForLocale()->toUnicode(data).split(QLatin1Char('\n'));
+ QStringList rawStatusList = text.split(QLatin1Char('\n'));
foreach (const QString &string, rawStatusList) {
const VcsBaseClient::StatusItem lineInfo = m_client->parseStatusLine(string);
@@ -143,6 +143,7 @@ void VcsBaseClientPrivate::saveSettings()
void VcsBaseClientPrivate::bindCommandToEditor(Command *cmd, VcsBaseEditorWidget *editor)
{
+ editor->setCommand(cmd);
QObject::connect(cmd, SIGNAL(finished(bool,int,QVariant)), m_cmdFinishedMapper, SLOT(map()));
m_cmdFinishedMapper->setMapping(cmd, editor);
}
@@ -189,9 +190,8 @@ bool VcsBaseClient::synchronousCreateRepository(const QString &workingDirectory,
QByteArray outputData;
if (!vcsFullySynchronousExec(workingDirectory, args, &outputData))
return false;
- QString output = QString::fromLocal8Bit(outputData);
- output.remove(QLatin1Char('\r'));
- ::vcsOutputWindow()->append(output);
+ ::vcsOutputWindow()->append(
+ Utils::SynchronousProcess::normalizeNewlines(QString::fromLocal8Bit(outputData)));
resetCachedVcsInfo(workingDirectory);
@@ -306,7 +306,7 @@ bool VcsBaseClient::vcsFullySynchronousExec(const QString &workingDir,
return false;
}
if (!stdErr.isEmpty())
- ::vcsOutputWindow()->append(QString::fromLocal8Bit(stdErr));
+ ::vcsOutputWindow()->appendError(QString::fromLocal8Bit(stdErr));
return vcsProcess.exitStatus() == QProcess::NormalExit && vcsProcess.exitCode() == 0;
}
@@ -319,8 +319,8 @@ Utils::SynchronousProcessResponse VcsBaseClient::vcsSynchronousExec(
{
const QString binary = settings()->binaryPath();
const int timeoutSec = settings()->intValue(VcsBaseClientSettings::timeoutKey);
- return VcsBase::VcsBasePlugin::runVcs(workingDirectory, binary, args,
- timeoutSec * 1000, flags, outputCodec);
+ return VcsBase::VcsBasePlugin::runVcs(workingDirectory, binary, args, timeoutSec * 1000,
+ flags, outputCodec);
}
void VcsBaseClient::annotate(const QString &workingDir, const QString &file,
@@ -366,7 +366,8 @@ void VcsBaseClient::diff(const QString &workingDir, const QStringList &files,
QStringList args;
const QStringList paramArgs = paramWidget != 0 ? paramWidget->arguments() : QStringList();
args << vcsCmdString << extraOptions << paramArgs << files;
- enqueueJob(createCommand(workingDir, editor), args);
+ Command *command = createCommand(workingDir, editor);
+ enqueueJob(command, args, exitCodeInterpreter(DiffCommand, command));
}
void VcsBaseClient::log(const QString &workingDir, const QStringList &files,
@@ -436,7 +437,7 @@ void VcsBaseClient::emitParsedStatus(const QString &repository, const QStringLis
QStringList args(vcsCommandString(StatusCommand));
args << extraOptions;
Command *cmd = createCommand(repository);
- connect(cmd, SIGNAL(outputData(QByteArray)), this, SLOT(statusParser(QByteArray)));
+ connect(cmd, SIGNAL(output(QString)), this, SLOT(statusParser(QString)));
enqueueJob(cmd, args);
}
@@ -462,6 +463,13 @@ QString VcsBaseClient::vcsCommandString(VcsCommand cmd) const
return QString();
}
+Utils::ExitCodeInterpreter *VcsBaseClient::exitCodeInterpreter(VcsCommand cmd, QObject *parent) const
+{
+ Q_UNUSED(cmd)
+ Q_UNUSED(parent)
+ return 0;
+}
+
void VcsBaseClient::import(const QString &repositoryRoot, const QStringList &files,
const QStringList &extraOptions)
{
@@ -493,7 +501,6 @@ void VcsBaseClient::update(const QString &repositoryRoot, const QString &revisio
args << revisionSpec(revision) << extraOptions;
Command *cmd = createCommand(repositoryRoot);
cmd->setCookie(repositoryRoot);
- cmd->setUnixTerminalDisabled(VcsBase::VcsBasePlugin::isSshPromptConfigured());
connect(cmd, SIGNAL(success(QVariant)), this, SIGNAL(changed(QVariant)), Qt::QueuedConnection);
enqueueJob(cmd, args);
}
@@ -560,11 +567,11 @@ VcsBase::VcsBaseEditorWidget *VcsBaseClient::createVcsEditor(Core::Id kind, QStr
const QString progressMsg = tr("Working...");
if (outputEditor) {
// Exists already
- outputEditor->createNew(progressMsg);
+ outputEditor->document()->setContents(progressMsg.toUtf8());
baseEditor = VcsBase::VcsBaseEditorWidget::getVcsBaseEditor(outputEditor);
QTC_ASSERT(baseEditor, return 0);
} else {
- outputEditor = Core::EditorManager::openEditorWithContents(kind, &title, progressMsg);
+ outputEditor = Core::EditorManager::openEditorWithContents(kind, &title, progressMsg.toUtf8());
outputEditor->document()->setProperty(registerDynamicProperty, dynamicPropertyValue);
baseEditor = VcsBase::VcsBaseEditorWidget::getVcsBaseEditor(outputEditor);
connect(baseEditor, SIGNAL(annotateRevisionRequested(QString,QString,int)),
@@ -597,37 +604,25 @@ Command *VcsBaseClient::createCommand(const QString &workingDirectory,
if (editor)
d->bindCommandToEditor(cmd, editor);
if (mode == VcsWindowOutputBind) {
- if (editor) { // assume that the commands output is the important thing
- connect(cmd, SIGNAL(outputData(QByteArray)),
- ::vcsOutputWindow(), SLOT(appendDataSilently(QByteArray)));
- }
- else {
- connect(cmd, SIGNAL(outputData(QByteArray)),
- ::vcsOutputWindow(), SLOT(appendData(QByteArray)));
- }
- }
- else if (editor) {
- connect(cmd, SIGNAL(outputData(QByteArray)),
- editor, SLOT(setPlainTextData(QByteArray)));
+ cmd->addFlags(VcsBasePlugin::ShowStdOutInLogWindow);
+ if (editor) // assume that the commands output is the important thing
+ cmd->addFlags(VcsBasePlugin::SilentOutput);
+ } else if (editor) {
+ connect(cmd, SIGNAL(output(QString)), editor, SLOT(setPlainText(QString)));
}
- if (::vcsOutputWindow())
- connect(cmd, SIGNAL(errorText(QString)),
- ::vcsOutputWindow(), SLOT(appendError(QString)));
return cmd;
}
-void VcsBaseClient::enqueueJob(Command *cmd, const QStringList &args)
+void VcsBaseClient::enqueueJob(Command *cmd, const QStringList &args, Utils::ExitCodeInterpreter *interpreter)
{
- const QString binary = QFileInfo(d->m_clientSettings->binaryPath()).baseName();
- ::vcsOutputWindow()->appendCommand(cmd->workingDirectory(), binary, args);
- cmd->addJob(args);
+ cmd->addJob(args, interpreter);
cmd->execute();
}
void VcsBaseClient::resetCachedVcsInfo(const QString &workingDir)
{
- Core::ICore::vcsManager()->resetVersionControlForDirectory(workingDir);
+ Core::VcsManager::resetVersionControlForDirectory(workingDir);
}
} // namespace VcsBase
diff --git a/src/plugins/vcsbase/vcsbaseclient.h b/src/plugins/vcsbase/vcsbaseclient.h
index cdd02c6362..f4c9bf957f 100644
--- a/src/plugins/vcsbase/vcsbaseclient.h
+++ b/src/plugins/vcsbase/vcsbaseclient.h
@@ -44,6 +44,7 @@ QT_END_NAMESPACE
namespace Utils {
struct SynchronousProcessResponse;
+class ExitCodeInterpreter;
}
namespace VcsBase {
@@ -118,6 +119,7 @@ public:
virtual QString findTopLevelForFile(const QFileInfo &file) const = 0;
virtual VcsBaseClientSettings *settings() const;
+ virtual QProcessEnvironment processEnvironment() const;
signals:
void parsedStatus(const QList<VcsBase::VcsBaseClient::StatusItem> &statusList);
@@ -149,6 +151,7 @@ protected:
};
virtual QString vcsCommandString(VcsCommand cmd) const;
virtual Core::Id vcsEditorKind(VcsCommand cmd) const = 0;
+ virtual Utils::ExitCodeInterpreter *exitCodeInterpreter(VcsCommand cmd, QObject *parent) const;
virtual QStringList revisionSpec(const QString &revision) const = 0;
virtual VcsBaseEditorParameterWidget *createDiffEditor(const QString &workingDir,
@@ -175,8 +178,6 @@ protected:
const char *registerDynamicProperty,
const QString &dynamicPropertyValue) const;
- virtual QProcessEnvironment processEnvironment() const;
-
enum JobOutputBindMode {
NoOutputBind,
VcsWindowOutputBind
@@ -184,7 +185,7 @@ protected:
Command *createCommand(const QString &workingDirectory,
VcsBase::VcsBaseEditorWidget *editor = 0,
JobOutputBindMode mode = NoOutputBind);
- void enqueueJob(Command *cmd, const QStringList &args);
+ void enqueueJob(Command *cmd, const QStringList &args, Utils::ExitCodeInterpreter *interpreter = 0);
void resetCachedVcsInfo(const QString &workingDir);
@@ -192,7 +193,7 @@ private:
friend class VcsBaseClientPrivate;
VcsBaseClientPrivate *d;
- Q_PRIVATE_SLOT(d, void statusParser(QByteArray))
+ Q_PRIVATE_SLOT(d, void statusParser(QString))
Q_PRIVATE_SLOT(d, void annotateRevision(QString, QString, int))
Q_PRIVATE_SLOT(d, void saveSettings())
Q_PRIVATE_SLOT(d, void commandFinishedGotoLine(QWidget *))
diff --git a/src/plugins/vcsbase/vcsbaseeditor.cpp b/src/plugins/vcsbase/vcsbaseeditor.cpp
index f7a98dec20..0c415cf8eb 100644
--- a/src/plugins/vcsbase/vcsbaseeditor.cpp
+++ b/src/plugins/vcsbase/vcsbaseeditor.cpp
@@ -31,6 +31,8 @@
#include "diffhighlighter.h"
#include "baseannotationhighlighter.h"
#include "vcsbaseplugin.h"
+#include "vcsbaseeditorparameterwidget.h"
+#include "command.h"
#include <coreplugin/icore.h>
#include <coreplugin/vcsmanager.h>
@@ -41,7 +43,6 @@
#include <projectexplorer/session.h>
#include <texteditor/basetextdocument.h>
#include <texteditor/basetextdocumentlayout.h>
-#include <texteditor/fontsettings.h>
#include <texteditor/texteditorsettings.h>
#include <utils/qtcassert.h>
@@ -155,23 +156,18 @@ public:
Core::Id id() const { return m_id; }
- bool isTemporary() const { return m_temporary; }
- void setTemporary(bool t) { m_temporary = t; }
-
signals:
void describeRequested(const QString &source, const QString &change);
void annotateRevisionRequested(const QString &source, const QString &change, int line);
private:
Core::Id m_id;
- bool m_temporary;
};
VcsBaseEditor::VcsBaseEditor(VcsBaseEditorWidget *widget,
const VcsBaseEditorParameters *type) :
BaseTextEditor(widget),
- m_id(type->id),
- m_temporary(false)
+ m_id(type->id)
{
setContext(Core::Context(type->context, TextEditor::Constants::C_TEXTEDITOR));
}
@@ -577,11 +573,10 @@ public:
QString m_copyRevisionTextFormat;
bool m_fileLogAnnotateEnabled;
TextEditor::BaseTextEditor *m_editor;
- QWidget *m_configurationWidget;
+ VcsBaseEditorParameterWidget *m_configurationWidget;
bool m_mouseDragging;
QList<AbstractTextCursorHandler *> m_textCursorHandlers;
-
- QColor m_backgroundColor;
+ QPointer<Command> m_command;
private:
QComboBox *m_entriesComboBox;
@@ -715,7 +710,7 @@ void VcsBaseEditorWidget::init()
setCodeFoldingSupported(true);
baseTextDocument()->setSyntaxHighlighter(dh);
}
- TextEditor::TextEditorSettings::instance()->initializeEditor(this);
+ TextEditor::TextEditorSettings::initializeEditor(this);
// override revisions display (green or red bar on the left, marking changes):
setRevisionsVisible(false);
}
@@ -730,7 +725,7 @@ void VcsBaseEditorWidget::setForceReadOnly(bool b)
VcsBaseEditor *eda = qobject_cast<VcsBaseEditor *>(editor());
QTC_ASSERT(eda != 0, return);
setReadOnly(b);
- eda->setTemporary(b);
+ eda->document()->setTemporary(b);
}
QString VcsBaseEditorWidget::source() const
@@ -891,8 +886,7 @@ void VcsBaseEditorWidget::slotJumpToEntry(int index)
int currentLine, currentColumn;
convertPosition(position(), &currentLine, &currentColumn);
if (lineNumber != currentLine) {
- Core::EditorManager *editorManager = Core::EditorManager::instance();
- editorManager->addCurrentPositionToNavigationHistory();
+ Core::EditorManager::addCurrentPositionToNavigationHistory();
gotoLine(lineNumber, 0);
}
}
@@ -963,6 +957,8 @@ void VcsBaseEditorWidget::contextMenuEvent(QContextMenuEvent *e)
QAction *revertAction = menu->addAction(tr("Revert Chunk..."));
revertAction->setData(qVariantFromValue(Internal::DiffChunkAction(chunk, true)));
connect(revertAction, SIGNAL(triggered()), this, SLOT(slotApplyDiffChunk()));
+ // Custom diff actions
+ addDiffActions(menu, chunk);
break;
}
default:
@@ -1058,7 +1054,7 @@ void VcsBaseEditorWidget::slotActivateAnnotation()
ah->setChangeNumbers(changes);
ah->rehighlight();
} else {
- baseTextDocument()->setSyntaxHighlighter(createAnnotationHighlighter(changes, d->m_backgroundColor));
+ baseTextDocument()->setSyntaxHighlighter(createAnnotationHighlighter(changes));
}
}
@@ -1083,8 +1079,11 @@ static inline bool checkChunkLine(const QString &line, int *modifiedLineNumber,
return false;
const int lineNumberPos = plusPos + 1;
const int commaPos = line.indexOf(QLatin1Char(','), lineNumberPos);
- if (commaPos == -1 || commaPos > endPos)
- return false;
+ if (commaPos == -1 || commaPos > endPos) {
+ // Git submodule appears as "@@ -1 +1 @@"
+ *modifiedLineNumber = 1;
+ return true;
+ }
const QString lineNumberStr = line.mid(lineNumberPos, commaPos - lineNumberPos);
bool ok;
*modifiedLineNumber = lineNumberStr.toInt(&ok);
@@ -1155,7 +1154,8 @@ DiffChunk VcsBaseEditorWidget::diffChunk(QTextCursor cursor) const
}
if (!chunkStart || !block.isValid())
return rc;
- rc.fileName = findDiffFile(fileNameFromDiffSpecification(block));
+ QString header;
+ rc.fileName = findDiffFile(fileNameFromDiffSpecification(block, &header));
if (rc.fileName.isEmpty())
return rc;
// Concatenate chunk and convert
@@ -1171,17 +1171,18 @@ DiffChunk VcsBaseEditorWidget::diffChunk(QTextCursor cursor) const
unicode += QLatin1Char('\n');
}
}
- const QTextCodec *cd = textCodec();
+ const QTextCodec *cd = baseTextDocument()->codec();
rc.chunk = cd ? cd->fromUnicode(unicode) : unicode.toLocal8Bit();
+ rc.header = cd ? cd->fromUnicode(header) : header.toLocal8Bit();
return rc;
}
-void VcsBaseEditorWidget::setPlainTextData(const QByteArray &data)
+void VcsBaseEditorWidget::setPlainText(const QString &text)
{
- if (data.size() > Core::EditorManager::maxTextFileSize())
- setPlainText(msgTextTooLarge(data.size()));
+ if (text.size() > Core::EditorManager::maxTextFileSize())
+ TextEditor::BaseTextEditorWidget::setPlainText(msgTextTooLarge(text.size()));
else
- setPlainText(codec()->toUnicode(data));
+ TextEditor::BaseTextEditorWidget::setPlainText(text);
}
void VcsBaseEditorWidget::reportCommandFinished(bool ok, int exitCode, const QVariant &data)
@@ -1193,33 +1194,6 @@ void VcsBaseEditorWidget::reportCommandFinished(bool ok, int exitCode, const QVa
setPlainText(tr("Failed to retrieve data."));
}
-void VcsBaseEditorWidget::setFontSettings(const TextEditor::FontSettings &fs)
-{
- TextEditor::BaseTextEditorWidget::setFontSettings(fs);
- d->m_backgroundColor = fs.toTextCharFormat(TextEditor::C_TEXT)
- .brushProperty(QTextFormat::BackgroundBrush).color();
-
- 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()) {
- categories << TextEditor::C_TEXT
- << TextEditor::C_ADDED_LINE
- << TextEditor::C_REMOVED_LINE
- << TextEditor::C_DIFF_FILE
- << TextEditor::C_DIFF_LOCATION;
- }
- highlighter->setFormats(fs.toTextCharFormats(categories));
- highlighter->rehighlight();
- }
- }
-}
-
const VcsBaseEditorParameters *VcsBaseEditorWidget::findType(const VcsBaseEditorParameters *array,
int arraySize,
EditorContentType et)
@@ -1233,17 +1207,9 @@ const VcsBaseEditorParameters *VcsBaseEditorWidget::findType(const VcsBaseEditor
// Find the codec used for a file querying the editor.
static QTextCodec *findFileCodec(const QString &source)
{
- typedef QList<Core::IEditor *> EditorList;
-
- const EditorList editors = Core::EditorManager::instance()->editorsForFileName(source);
- if (!editors.empty()) {
- const EditorList::const_iterator ecend = editors.constEnd();
- for (EditorList::const_iterator it = editors.constBegin(); it != ecend; ++it)
- if (const TextEditor::BaseTextEditor *be = qobject_cast<const TextEditor::BaseTextEditor *>(*it)) {
- QTextCodec *codec = be->editorWidget()->textCodec();
- return codec;
- }
- }
+ Core::IDocument *document = Core::EditorManager::documentModel()->documentForFilePath(source);
+ if (Core::TextDocument *textDocument = qobject_cast<Core::TextDocument *>(document))
+ return const_cast<QTextCodec *>(textDocument->codec());
return 0;
}
@@ -1252,13 +1218,12 @@ static QTextCodec *findProjectCodec(const QString &dir)
{
typedef QList<ProjectExplorer::Project*> ProjectList;
// Try to find a project under which file tree the file is.
- const ProjectExplorer::SessionManager *sm = ProjectExplorer::ProjectExplorerPlugin::instance()->session();
- const ProjectList projects = sm->projects();
+ const ProjectList projects = ProjectExplorer::SessionManager::projects();
if (!projects.empty()) {
const ProjectList::const_iterator pcend = projects.constEnd();
for (ProjectList::const_iterator it = projects.constBegin(); it != pcend; ++it)
if (const Core::IDocument *document = (*it)->document())
- if (document->fileName().startsWith(dir)) {
+ if (document->filePath().startsWith(dir)) {
QTextCodec *codec = (*it)->editorConfiguration()->textCodec();
return codec;
}
@@ -1304,7 +1269,7 @@ int VcsBaseEditorWidget::lineNumberOfCurrentEditor(const QString &currentFile)
return -1;
if (!currentFile.isEmpty()) {
const Core::IDocument *idocument = ed->document();
- if (!idocument || idocument->fileName() != currentFile)
+ if (!idocument || idocument->filePath() != currentFile)
return -1;
}
const TextEditor::BaseTextEditor *eda = qobject_cast<const TextEditor::BaseTextEditor *>(ed);
@@ -1371,7 +1336,7 @@ QString VcsBaseEditorWidget::getTitleId(const QString &workingDirectory,
return rc;
}
-bool VcsBaseEditorWidget::setConfigurationWidget(QWidget *w)
+bool VcsBaseEditorWidget::setConfigurationWidget(VcsBaseEditorParameterWidget *w)
{
if (!d->m_editor || d->m_configurationWidget)
return false;
@@ -1382,11 +1347,18 @@ bool VcsBaseEditorWidget::setConfigurationWidget(QWidget *w)
return true;
}
-QWidget *VcsBaseEditorWidget::configurationWidget() const
+VcsBaseEditorParameterWidget *VcsBaseEditorWidget::configurationWidget() const
{
return d->m_configurationWidget;
}
+void VcsBaseEditorWidget::setCommand(Command *command)
+{
+ if (d->m_command)
+ d->m_command->abort();
+ d->m_command = command;
+}
+
// Find the complete file from a diff relative specification.
QString VcsBaseEditorWidget::findDiffFile(const QString &f) const
{
@@ -1412,8 +1384,7 @@ QString VcsBaseEditorWidget::findDiffFile(const QString &f) const
return sourceFileInfo.absoluteFilePath();
QString topLevel;
- Core::VcsManager *vcsManager = Core::ICore::vcsManager();
- vcsManager->findVersionControlForDirectory(sourceDir, &topLevel); //
+ Core::VcsManager::findVersionControlForDirectory(sourceDir, &topLevel); //
if (topLevel.isEmpty())
return QString();
@@ -1435,6 +1406,10 @@ QString VcsBaseEditorWidget::findDiffFile(const QString &f) const
return QString();
}
+void VcsBaseEditorWidget::addDiffActions(QMenu *, const DiffChunk &)
+{
+}
+
void VcsBaseEditorWidget::slotAnnotateRevision()
{
if (const QAction *a = qobject_cast<const QAction *>(sender()))
@@ -1477,18 +1452,25 @@ bool VcsBaseEditorWidget::applyDiffChunk(const DiffChunk &dc, bool revert) const
d->m_diffBaseDirectory, 0, revert);
}
-QString VcsBaseEditorWidget::fileNameFromDiffSpecification(const QTextBlock &inBlock) const
+QString VcsBaseEditorWidget::fileNameFromDiffSpecification(const QTextBlock &inBlock, QString *header) const
{
// Go back chunks
+ QString fileName;
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);
+ if (header)
+ header->prepend(line + QLatin1String("\n"));
+ if (fileName.isEmpty() && !cap.isEmpty())
+ fileName = cap;
+ } else if (!fileName.isEmpty()) {
+ return findDiffFile(fileName);
+ } else if (header) {
+ header->clear();
}
}
- return QString();
+ return fileName.isEmpty() ? QString() : findDiffFile(fileName);
}
void VcsBaseEditorWidget::addChangeActions(QMenu *, const QString &)
@@ -1567,20 +1549,17 @@ static const char tagPropertyC[] = "_q_VcsBaseEditorTag";
void VcsBaseEditorWidget::tagEditor(Core::IEditor *e, const QString &tag)
{
- e->setProperty(tagPropertyC, QVariant(tag));
+ e->document()->setProperty(tagPropertyC, QVariant(tag));
}
Core::IEditor* VcsBaseEditorWidget::locateEditorByTag(const QString &tag)
{
- Core::IEditor *rc = 0;
- foreach (Core::IEditor *ed, Core::EditorManager::instance()->openedEditors()) {
- const QVariant tagPropertyValue = ed->property(tagPropertyC);
- if (tagPropertyValue.type() == QVariant::String && tagPropertyValue.toString() == tag) {
- rc = ed;
- break;
- }
+ foreach (Core::IDocument *document, Core::EditorManager::documentModel()->openedDocuments()) {
+ const QVariant tagPropertyValue = document->property(tagPropertyC);
+ if (tagPropertyValue.type() == QVariant::String && tagPropertyValue.toString() == tag)
+ return Core::EditorManager::documentModel()->editorsForDocument(document).first();
}
- return rc;
+ return 0;
}
} // namespace VcsBase
diff --git a/src/plugins/vcsbase/vcsbaseeditor.h b/src/plugins/vcsbase/vcsbaseeditor.h
index a7ceda39a8..ae2587c88a 100644
--- a/src/plugins/vcsbase/vcsbaseeditor.h
+++ b/src/plugins/vcsbase/vcsbaseeditor.h
@@ -54,6 +54,8 @@ class VcsBaseEditorWidgetPrivate;
class DiffHighlighter;
class BaseAnnotationHighlighter;
+class VcsBaseEditorParameterWidget;
+class Command;
// Documentation inside
enum EditorContentType
@@ -82,6 +84,7 @@ public:
QString fileName;
QByteArray chunk;
+ QByteArray header;
};
class VCSBASE_EXPORT VcsBaseEditorWidget : public TextEditor::BaseTextEditorWidget
@@ -183,9 +186,10 @@ public:
const QStringList &fileNames,
const QString &revision = QString());
- bool setConfigurationWidget(QWidget *w);
- QWidget *configurationWidget() const;
+ bool setConfigurationWidget(VcsBaseEditorParameterWidget *w);
+ VcsBaseEditorParameterWidget *configurationWidget() const;
+ void setCommand(Command *command);
/* Tagging editors: Sometimes, an editor should be re-used, for example, when showing
* a diff of the same file with different diff-options. In order to be able to find
* the editor, they get a 'tag' containing type and parameters (dynamic property string). */
@@ -205,7 +209,7 @@ signals:
public slots:
// Convenience slot to set data read from stdout, will use the
// documents' codec to decode
- void setPlainTextData(const QByteArray &data);
+ void setPlainText(const QString &text);
void reportCommandFinished(bool ok, int exitCode, const QVariant &data);
protected:
@@ -217,9 +221,6 @@ protected:
void mouseDoubleClickEvent(QMouseEvent *e);
void keyPressEvent(QKeyEvent *);
-public slots:
- void setFontSettings(const TextEditor::FontSettings &);
-
private slots:
void slotActivateAnnotation();
void slotPopulateDiffBrowser();
@@ -236,6 +237,8 @@ protected:
* source and version control. */
virtual QString findDiffFile(const QString &f) const;
+ virtual void addDiffActions(QMenu *menu, const DiffChunk &chunk);
+
virtual void addChangeActions(QMenu *menu, const QString &change);
// Implement to return a set of change identifiers in
@@ -244,11 +247,10 @@ protected:
// Implement to identify a change number at the cursor position
virtual QString changeUnderCursor(const QTextCursor &) const = 0;
// Factory functions for highlighters
- virtual BaseAnnotationHighlighter *createAnnotationHighlighter(const QSet<QString> &changes,
- const QColor &bg) const = 0;
+ virtual BaseAnnotationHighlighter *createAnnotationHighlighter(const QSet<QString> &changes) const = 0;
// Returns a local file name from the diff file specification
// (text cursor at position above change hunk)
- QString fileNameFromDiffSpecification(const QTextBlock &inBlock) const;
+ QString fileNameFromDiffSpecification(const QTextBlock &inBlock, QString *header = 0) const;
// Implement to return decorated annotation change for "Annotate version"
virtual QString decorateVersion(const QString &revision) const;
diff --git a/src/plugins/vcsbase/vcsbaseoutputwindow.cpp b/src/plugins/vcsbase/vcsbaseoutputwindow.cpp
index 24d0835b20..200271a325 100644
--- a/src/plugins/vcsbase/vcsbaseoutputwindow.cpp
+++ b/src/plugins/vcsbase/vcsbaseoutputwindow.cpp
@@ -92,6 +92,8 @@ public:
void appendWarning(const QString &text);
// Append a bold command "10:00 " + "Executing: vcs -diff"
void appendCommand(const QString &text);
+ // Append a message text (e.g. "command has finished successfully") and pop up.
+ void appendMessage(const QString &text);
protected:
virtual void contextMenuEvent(QContextMenuEvent *event);
@@ -103,6 +105,7 @@ private:
QTextCharFormat m_errorFormat;
QTextCharFormat m_warningFormat;
QTextCharFormat m_commandFormat;
+ QTextCharFormat m_messageFormat;
};
OutputWindowPlainTextEdit::OutputWindowPlainTextEdit(QWidget *parent) :
@@ -110,7 +113,8 @@ OutputWindowPlainTextEdit::OutputWindowPlainTextEdit(QWidget *parent) :
m_defaultFormat(currentCharFormat()),
m_errorFormat(m_defaultFormat),
m_warningFormat(m_defaultFormat),
- m_commandFormat(m_defaultFormat)
+ m_commandFormat(m_defaultFormat),
+ m_messageFormat(m_defaultFormat)
{
setReadOnly(true);
setUndoRedoEnabled(false);
@@ -118,6 +122,7 @@ OutputWindowPlainTextEdit::OutputWindowPlainTextEdit(QWidget *parent) :
m_errorFormat.setForeground(Qt::red);
m_warningFormat.setForeground(Qt::darkYellow);
m_commandFormat.setFontWeight(QFont::Bold);
+ m_messageFormat.setForeground(Qt::blue);
}
// Search back for beginning of word
@@ -240,6 +245,13 @@ void OutputWindowPlainTextEdit::appendCommand(const QString &text)
setCurrentCharFormat(m_defaultFormat);
}
+void OutputWindowPlainTextEdit::appendMessage(const QString &text)
+{
+ setCurrentCharFormat(m_messageFormat);
+ appendLines(text);
+ setCurrentCharFormat(m_defaultFormat);
+}
+
} // namespace Internal
// ------------------- VcsBaseOutputWindowPrivate
@@ -434,17 +446,9 @@ void VcsBaseOutputWindow::appendCommand(const QString &workingDirectory,
appendCommand(msgExecutionLogEntry(workingDirectory, binary, args));
}
-
-void VcsBaseOutputWindow::appendData(const QByteArray &data)
-{
- appendDataSilently(data);
- if (!d->plainTextEdit()->isVisible())
- popup(Core::IOutputPane::NoModeSwitch);
-}
-
-void VcsBaseOutputWindow::appendDataSilently(const QByteArray &data)
+void VcsBaseOutputWindow::appendMessage(const QString &text)
{
- appendSilently(QTextCodec::codecForLocale()->toUnicode(data));
+ d->plainTextEdit()->appendMessage(text);
}
VcsBaseOutputWindow *VcsBaseOutputWindow::instance()
diff --git a/src/plugins/vcsbase/vcsbaseoutputwindow.h b/src/plugins/vcsbase/vcsbaseoutputwindow.h
index e8367502f7..a1ce87586e 100644
--- a/src/plugins/vcsbase/vcsbaseoutputwindow.h
+++ b/src/plugins/vcsbase/vcsbaseoutputwindow.h
@@ -87,13 +87,9 @@ public slots:
// Append text and pop up.
void append(const QString &text);
- // Append data using the Locale's converter and pop up.
- void appendData(const QByteArray &data);
// Silently append text, do not pop up.
void appendSilently(const QString &text);
- // Silently append data using the Locale's converter, do not pop up.
- void appendDataSilently(const QByteArray &data);
// Append red error text and pop up.
void appendError(const QString &text);
@@ -110,6 +106,9 @@ public slots:
const QString &binary,
const QStringList &args);
+ // Append a blue message text and pop up.
+ void appendMessage(const QString &text);
+
private:
VcsBaseOutputWindow();
diff --git a/src/plugins/vcsbase/vcsbaseplugin.cpp b/src/plugins/vcsbase/vcsbaseplugin.cpp
index 7be43f3314..79e5373e31 100644
--- a/src/plugins/vcsbase/vcsbaseplugin.cpp
+++ b/src/plugins/vcsbase/vcsbaseplugin.cpp
@@ -33,6 +33,7 @@
#include "commonvcssettings.h"
#include "vcsbaseoutputwindow.h"
#include "corelistener.h"
+#include "command.h"
#include <coreplugin/documentmanager.h>
#include <coreplugin/icore.h>
@@ -59,7 +60,7 @@
using namespace Utils;
-enum { debug = 0, debugRepositorySearch = 0, debugExecution = 0 };
+enum { debug = 0, debugRepositorySearch = 0 };
/*!
\namespace VcsBase
@@ -205,11 +206,11 @@ public slots:
StateListener::StateListener(QObject *parent) :
QObject(parent)
{
- connect(Core::ICore::editorManager(), SIGNAL(currentEditorChanged(Core::IEditor*)),
+ connect(Core::EditorManager::instance(), SIGNAL(currentEditorChanged(Core::IEditor*)),
this, SLOT(slotStateChanged()));
- connect(Core::ICore::editorManager(), SIGNAL(currentEditorStateChanged(Core::IEditor*)),
+ connect(Core::EditorManager::instance(), SIGNAL(currentDocumentStateChanged()),
this, SLOT(slotStateChanged()));
- connect(Core::ICore::vcsManager(), SIGNAL(repositoryChanged(QString)),
+ connect(Core::VcsManager::instance(), SIGNAL(repositoryChanged(QString)),
this, SLOT(slotStateChanged()));
if (ProjectExplorer::ProjectExplorerPlugin *pe = ProjectExplorer::ProjectExplorerPlugin::instance())
@@ -219,25 +220,32 @@ StateListener::StateListener(QObject *parent) :
static inline QString displayNameOfEditor(const QString &fileName)
{
- const QList<Core::IEditor*> editors = Core::EditorManager::instance()->editorsForFileName(fileName);
- if (!editors.isEmpty())
- return editors.front()->displayName();
+ Core::IDocument *document = Core::EditorManager::documentModel()->documentForFilePath(fileName);
+ if (document)
+ return document->displayName();
return QString();
}
void StateListener::slotStateChanged()
{
- Core::VcsManager *vcsManager = Core::ICore::vcsManager();
-
// Get the current file. Are we on a temporary submit editor indicated by
// temporary path prefix or does the file contains a hash, indicating a project
// folder?
State state;
- Core::IEditor *currentEditor = Core::EditorManager::currentEditor();
- if (!currentEditor || !currentEditor->document())
+ Core::IDocument *currentDocument = Core::EditorManager::currentDocument();
+ if (!currentDocument) {
state.currentFile.clear();
- else
- state.currentFile = currentEditor->document()->fileName();
+ } else {
+ state.currentFile = currentDocument->filePath();
+ if (state.currentFile.isEmpty()) {
+ const QList<Core::IEditor *> editors =
+ Core::EditorManager::documentModel()->editorsForDocument(currentDocument);
+ if (!editors.isEmpty()) {
+ if (QWidget *editorWidget = editors.first()->widget())
+ state.currentFile = editorWidget->property("source").toString();
+ }
+ }
+ }
QScopedPointer<QFileInfo> currentFileInfo; // Instantiate QFileInfo only once if required.
if (!state.currentFile.isEmpty()) {
const bool isTempFile = state.currentFile.startsWith(QDir::tempPath());
@@ -266,19 +274,25 @@ void StateListener::slotStateChanged()
if (!state.currentFile.isEmpty()) {
if (currentFileInfo.isNull())
currentFileInfo.reset(new QFileInfo(state.currentFile));
- state.currentFileDirectory = currentFileInfo->absolutePath();
- state.currentFileName = currentFileInfo->fileName();
- fileControl = vcsManager->findVersionControlForDirectory(state.currentFileDirectory,
- &state.currentFileTopLevel);
- if (!fileControl)
- state.clearFile();
+ if (currentFileInfo->isDir()) {
+ state.currentFile.clear();
+ state.currentFileDirectory = currentFileInfo->absoluteFilePath();
+ } else {
+ state.currentFileDirectory = currentFileInfo->absolutePath();
+ state.currentFileName = currentFileInfo->fileName();
+ fileControl = Core::VcsManager::findVersionControlForDirectory(
+ state.currentFileDirectory,
+ &state.currentFileTopLevel);
+ if (!fileControl)
+ state.clearFile();
+ }
}
// Check for project, find the control
Core::IVersionControl *projectControl = 0;
if (const ProjectExplorer::Project *currentProject = ProjectExplorer::ProjectExplorerPlugin::currentProject()) {
state.currentProjectPath = currentProject->projectDirectory();
state.currentProjectName = currentProject->displayName();
- projectControl = vcsManager->findVersionControlForDirectory(state.currentProjectPath,
+ projectControl = Core::VcsManager::findVersionControlForDirectory(state.currentProjectPath,
&state.currentProjectTopLevel);
if (projectControl) {
// If we have both, let the file's one take preference
@@ -290,8 +304,10 @@ void StateListener::slotStateChanged()
}
// Assemble state and emit signal.
Core::IVersionControl *vc = state.currentFile.isEmpty() ? projectControl : fileControl;
- if (!vc) // Need a repository to patch
- state.clearPatchFile();
+ if (!vc) {
+ state.clearPatchFile(); // Need a repository to patch
+ Core::EditorManager::setWindowTitleVcsTopic(QString());
+ }
if (debug)
qDebug() << state << (vc ? vc->displayName() : QString(QLatin1String("No version control")));
emit stateChanged(state, vc);
@@ -391,13 +407,12 @@ QString VcsBasePluginState::currentProjectTopLevel() const
return data->m_state.currentProjectTopLevel;
}
-QStringList VcsBasePluginState::relativeCurrentProject() const
+QString VcsBasePluginState::relativeCurrentProject() const
{
- QStringList rc;
- QTC_ASSERT(hasProject(), return rc);
+ QTC_ASSERT(hasProject(), return QString());
if (data->m_state.currentProjectTopLevel != data->m_state.currentProjectPath)
- rc.append(QDir(data->m_state.currentProjectTopLevel).relativeFilePath(data->m_state.currentProjectPath));
- return rc;
+ return QDir(data->m_state.currentProjectTopLevel).relativeFilePath(data->m_state.currentProjectPath);
+ return QString();
}
bool VcsBasePluginState::hasTopLevel() const
@@ -548,7 +563,7 @@ void VcsBasePlugin::initializeVcs(Core::IVersionControl *vc)
SLOT(slotStateChanged(VcsBase::Internal::State,Core::IVersionControl*)));
// VCSes might have become (un-)available, so clear the VCS directory cache
connect(vc, SIGNAL(configurationChanged()),
- Core::ICore::vcsManager(), SLOT(clearVersionControlCache()));
+ Core::VcsManager::instance(), SLOT(clearVersionControlCache()));
connect(vc, SIGNAL(configurationChanged()),
VcsBasePluginPrivate::m_listener, SLOT(slotStateChanged()));
}
@@ -582,6 +597,7 @@ void VcsBasePlugin::slotStateChanged(const VcsBase::Internal::State &newInternal
d->m_state.setState(newInternalState);
updateActions(VcsEnabled);
}
+ Core::EditorManager::setWindowTitleVcsTopic(vc->vcsTopic(d->m_state.topLevel()));
} else {
// Some other VCS plugin or state changed: Reset us to empty state.
const ActionState newActionState = vc ? OtherVcsEnabled : NoVcsEnabled;
@@ -625,7 +641,7 @@ void VcsBasePlugin::promptToDeleteCurrentFile()
{
const VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasFile(), return);
- const bool rc = Core::ICore::vcsManager()->promptToDelete(versionControl(), state.currentFile());
+ const bool rc = Core::VcsManager::promptToDelete(versionControl(), state.currentFile());
if (!rc)
QMessageBox::warning(0, tr("Version Control"),
tr("The file '%1' could not be deleted.").
@@ -646,14 +662,14 @@ void VcsBasePlugin::createRepository()
// Find current starting directory
QString directory;
if (const ProjectExplorer::Project *currentProject = ProjectExplorer::ProjectExplorerPlugin::currentProject())
- directory = QFileInfo(currentProject->document()->fileName()).absolutePath();
+ directory = QFileInfo(currentProject->document()->filePath()).absolutePath();
// Prompt for a directory that is not under version control yet
QWidget *mw = Core::ICore::mainWindow();
do {
directory = QFileDialog::getExistingDirectory(mw, tr("Choose Repository Directory"), directory);
if (directory.isEmpty())
return;
- const Core::IVersionControl *managingControl = Core::ICore::vcsManager()->findVersionControlForDirectory(directory);
+ const Core::IVersionControl *managingControl = Core::VcsManager::findVersionControlForDirectory(directory);
if (managingControl == 0)
break;
const QString question = tr("The directory '%1' is already managed by a version control system (%2)."
@@ -785,9 +801,9 @@ QString VcsBasePlugin::findRepositoryForDirectory(const QString &dirS,
}
// Is SSH prompt configured?
-static inline QString sshPrompt()
+QString VcsBasePlugin::sshPrompt()
{
- return VcsBase::Internal::VcsPlugin::instance()->settings().sshPasswordPrompt;
+ return Internal::VcsPlugin::instance()->settings().sshPasswordPrompt;
}
bool VcsBasePlugin::isSshPromptConfigured()
@@ -795,254 +811,31 @@ bool VcsBasePlugin::isSshPromptConfigured()
return !sshPrompt().isEmpty();
}
-void VcsBasePlugin::setProcessEnvironment(QProcessEnvironment *e, bool forceCLocale)
+void VcsBasePlugin::setProcessEnvironment(QProcessEnvironment *e,
+ bool forceCLocale,
+ const QString &sshPromptBinary)
{
if (forceCLocale)
e->insert(QLatin1String("LANG"), QString(QLatin1Char('C')));
- const QString sshPromptBinary = sshPrompt();
if (!sshPromptBinary.isEmpty())
e->insert(QLatin1String("SSH_ASKPASS"), sshPromptBinary);
}
-// Run a process fully synchronously, returning Utils::SynchronousProcessResponse
+// Run a process synchronously, returning Utils::SynchronousProcessResponse
// response struct and using the VcsBasePlugin flags as applicable
-static SynchronousProcessResponse runVcsFullySynchronously(const QString &workingDir,
- const QString &binary,
- const QStringList &arguments,
- int timeOutMS,
- QProcessEnvironment env,
- unsigned flags,
- QTextCodec *outputCodec = 0)
-{
- SynchronousProcessResponse response;
- if (binary.isEmpty()) {
- response.result = SynchronousProcessResponse::StartFailed;
- return response;
- }
-
- VcsBase::VcsBaseOutputWindow *outputWindow = VcsBase::VcsBaseOutputWindow::instance();
-
- // Set up process
- unsigned processFlags = 0;
- if (VcsBasePlugin::isSshPromptConfigured() && (flags & VcsBasePlugin::SshPasswordPrompt))
- processFlags |= SynchronousProcess::UnixTerminalDisabled;
- QSharedPointer<QProcess> process = SynchronousProcess::createProcess(processFlags);
- if (!workingDir.isEmpty())
- process->setWorkingDirectory(workingDir);
- process->setProcessEnvironment(env);
- if (flags & VcsBasePlugin::MergeOutputChannels)
- process->setProcessChannelMode(QProcess::MergedChannels);
-
- // Start
- process->start(binary, arguments, QIODevice::ReadOnly);
- process->closeWriteChannel();
- if (!process->waitForStarted()) {
- response.result = SynchronousProcessResponse::StartFailed;
- return response;
- }
-
- // process output
- QByteArray stdOut;
- QByteArray stdErr;
- const bool timedOut =
- !SynchronousProcess::readDataFromProcess(*process.data(), timeOutMS,
- &stdOut, &stdErr, true);
-
- if (!stdErr.isEmpty()) {
- response.stdErr = QString::fromLocal8Bit(stdErr).remove(QLatin1Char('\r'));
- if (!(flags & VcsBasePlugin::SuppressStdErrInLogWindow))
- outputWindow->append(response.stdErr);
- }
-
- if (!stdOut.isEmpty()) {
- response.stdOut = (outputCodec ? outputCodec->toUnicode(stdOut) : QString::fromLocal8Bit(stdOut))
- .remove(QLatin1Char('\r'));
- if (flags & VcsBasePlugin::ShowStdOutInLogWindow)
- outputWindow->append(response.stdOut);
- }
-
- // Result
- if (timedOut) {
- response.result = SynchronousProcessResponse::Hang;
- } else if (process->exitStatus() != QProcess::NormalExit) {
- response.result = SynchronousProcessResponse::TerminatedAbnormally;
- } else {
- response.result = process->exitCode() == 0 ?
- SynchronousProcessResponse::Finished :
- SynchronousProcessResponse::FinishedError;
- }
- return response;
-}
-
-
-SynchronousProcessResponse VcsBasePlugin::runVcs(const QString &workingDir,
- const QString &binary,
- const QStringList &arguments,
- int timeOutMS,
- unsigned flags,
- QTextCodec *outputCodec)
-{
- const QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
- return runVcs(workingDir, binary, arguments, timeOutMS, env,
- flags, outputCodec);
-}
-
SynchronousProcessResponse VcsBasePlugin::runVcs(const QString &workingDir,
const QString &binary,
const QStringList &arguments,
int timeOutMS,
- QProcessEnvironment env,
unsigned flags,
- QTextCodec *outputCodec)
-{
- SynchronousProcessResponse response;
-
- if (binary.isEmpty()) {
- response.result = SynchronousProcessResponse::StartFailed;
- return response;
- }
-
- VcsBase::VcsBaseOutputWindow *outputWindow = VcsBase::VcsBaseOutputWindow::instance();
-
- if (!(flags & SuppressCommandLogging))
- outputWindow->appendCommand(workingDir, binary, arguments);
-
- const bool sshPromptConfigured = VcsBasePlugin::isSshPromptConfigured();
- if (debugExecution) {
- QDebug nsp = qDebug().nospace();
- nsp << "VcsBasePlugin::runVcs" << workingDir << binary << arguments
- << timeOutMS;
- if (flags & ShowStdOutInLogWindow)
- nsp << "stdout";
- if (flags & SuppressStdErrInLogWindow)
- nsp << "suppress_stderr";
- if (flags & SuppressFailMessageInLogWindow)
- nsp << "suppress_fail_msg";
- if (flags & MergeOutputChannels)
- nsp << "merge_channels";
- if (flags & SshPasswordPrompt)
- nsp << "ssh (" << sshPromptConfigured << ')';
- if (flags & SuppressCommandLogging)
- nsp << "suppress_log";
- if (flags & ForceCLocale)
- nsp << "c_locale";
- if (flags & FullySynchronously)
- nsp << "fully_synchronously";
- if (flags & ExpectRepoChanges)
- nsp << "expect_repo_changes";
- if (outputCodec)
- nsp << " Codec: " << outputCodec->name();
- }
-
- VcsBase::VcsBasePlugin::setProcessEnvironment(&env, (flags & ForceCLocale));
-
- // TODO tell the document manager about expected repository changes
- // if (flags & ExpectRepoChanges)
- // Core::DocumentManager::expectDirectoryChange(workingDir);
- if (flags & FullySynchronously) {
- response = runVcsFullySynchronously(workingDir, binary, arguments, timeOutMS,
- env, flags, outputCodec);
- } else {
- // Run, connect stderr to the output window
- SynchronousProcess process;
- if (!workingDir.isEmpty())
- process.setWorkingDirectory(workingDir);
-
- process.setProcessEnvironment(env);
- process.setTimeout(timeOutMS);
- if (outputCodec)
- process.setStdOutCodec(outputCodec);
-
- // Suppress terminal on UNIX for ssh prompts if it is configured.
- if (sshPromptConfigured && (flags & SshPasswordPrompt))
- process.setFlags(SynchronousProcess::UnixTerminalDisabled);
-
- // connect stderr to the output window if desired
- if (flags & MergeOutputChannels) {
- process.setProcessChannelMode(QProcess::MergedChannels);
- } else {
- if (!(flags & SuppressStdErrInLogWindow)) {
- process.setStdErrBufferedSignalsEnabled(true);
- connect(&process, SIGNAL(stdErrBuffered(QString,bool)), outputWindow, SLOT(append(QString)));
- }
- }
-
- // connect stdout to the output window if desired
- if (flags & ShowStdOutInLogWindow) {
- process.setStdOutBufferedSignalsEnabled(true);
- connect(&process, SIGNAL(stdOutBuffered(QString,bool)), outputWindow, SLOT(append(QString)));
- }
-
- process.setTimeOutMessageBoxEnabled(true);
-
- // Run!
- response = process.run(binary, arguments);
- }
-
- // Success/Fail message in appropriate window?
- if (response.result == SynchronousProcessResponse::Finished) {
- if (flags & ShowSuccessMessage)
- outputWindow->append(response.exitMessage(binary, timeOutMS));
- } else {
- if (!(flags & SuppressFailMessageInLogWindow))
- outputWindow->appendError(response.exitMessage(binary, timeOutMS));
- }
- // TODO tell the document manager that the directory now received all expected changes
- // if (flags & ExpectRepoChanges)
- // Core::DocumentManager::unexpectDirectoryChange(workingDir);
-
- return response;
-}
-
-bool VcsBasePlugin::runFullySynchronous(const QString &workingDirectory,
- const QString &binary,
- const QStringList &arguments,
- const QProcessEnvironment &env,
- QByteArray* outputText,
- QByteArray* errorText,
- int timeoutMS,
- unsigned flags)
+ QTextCodec *outputCodec,
+ const QProcessEnvironment &env)
{
- if (binary.isEmpty())
- return false;
-
- if (!(flags & SuppressCommandLogging))
- VcsBase::VcsBaseOutputWindow::instance()->appendCommand(workingDirectory, binary, arguments);
-
- // TODO tell the document manager about expected repository changes
- // if (flags & ExpectRepoChanges)
- // Core::DocumentManager::expectDirectoryChange(workingDirectory);
- QProcess process;
- process.setWorkingDirectory(workingDirectory);
- process.setProcessEnvironment(env);
-
- process.start(binary, arguments);
- process.closeWriteChannel();
- if (!process.waitForStarted()) {
- if (errorText) {
- const QString msg = QString::fromLatin1("Unable to execute '%1': %2:")
- .arg(binary, process.errorString());
- *errorText = msg.toLocal8Bit();
- }
- return false;
- }
-
- if (!SynchronousProcess::readDataFromProcess(process, timeoutMS, outputText, errorText, true)) {
- if (errorText)
- errorText->append(tr("Error: Executable timed out after %1s.").arg(timeoutMS / 1000).toLocal8Bit());
- SynchronousProcess::stopProcess(process);
- return false;
- }
- // TODO tell the document manager that the directory now received all expected changes
- // if (flags & ExpectRepoChanges)
- // Core::DocumentManager::unexpectDirectoryChange(workingDirectory);
-
- if (process.exitStatus() == QProcess::NormalExit && process.exitCode() == 0) {
- if (flags & ExpectRepoChanges)
- Core::ICore::vcsManager()->emitRepositoryChanged(workingDirectory);
- return true;
- }
- return false;
+ Command command(binary, workingDir,
+ env.isEmpty() ? QProcessEnvironment::systemEnvironment() : env);
+ command.addFlags(flags);
+ command.setCodec(outputCodec);
+ return command.runVcs(arguments, timeOutMS);
}
bool VcsBasePlugin::runPatch(const QByteArray &input, const QString &workingDirectory,
@@ -1080,7 +873,7 @@ bool VcsBasePlugin::runPatch(const QByteArray &input, const QString &workingDire
if (!stdOut.isEmpty())
ow->append(QString::fromLocal8Bit(stdOut));
if (!stdErr.isEmpty())
- ow->append(QString::fromLocal8Bit(stdErr));
+ ow->appendError(QString::fromLocal8Bit(stdErr));
if (patchProcess.exitStatus() != QProcess::NormalExit) {
ow->appendError(tr("'%1' crashed.").arg(patch));
diff --git a/src/plugins/vcsbase/vcsbaseplugin.h b/src/plugins/vcsbase/vcsbaseplugin.h
index 2e6a870575..5799f8bf99 100644
--- a/src/plugins/vcsbase/vcsbaseplugin.h
+++ b/src/plugins/vcsbase/vcsbaseplugin.h
@@ -36,10 +36,10 @@
#include <QSharedDataPointer>
#include <QList>
+#include <QProcessEnvironment>
QT_BEGIN_NAMESPACE
class QAction;
-class QProcessEnvironment;
class QTextCodec;
QT_END_NAMESPACE
@@ -94,9 +94,9 @@ public:
QString currentProjectName() const;
QString currentProjectTopLevel() const;
/* Convenience: Returns project path relative to top level if it
- * differs from top level (else empty()) as an argument list to do
+ * differs from top level (else empty string) as an argument list to do
* eg a 'vcs diff <args>' */
- QStringList relativeCurrentProject() const;
+ QString relativeCurrentProject() const;
// Top level directory for actions on the top level. Preferably
// the file one.
@@ -150,7 +150,11 @@ public:
// Sets up SSH graphical password prompting (note that the latter
// requires a terminal-less process) and sets LANG to 'C' to force English
// (suppress LOCALE warnings/parse commands output) if desired.
- static void setProcessEnvironment(QProcessEnvironment *e, bool forceCLocale);
+ static void setProcessEnvironment(QProcessEnvironment *e,
+ bool forceCLocale,
+ const QString &sshPasswordPrompt = sshPrompt());
+ // Returns SSH prompt configured in settings.
+ static QString sshPrompt();
// Returns whether an SSH prompt is configured.
static bool isSshPromptConfigured();
@@ -166,33 +170,17 @@ public:
ForceCLocale = 0x80, // Force C-locale for commands whose output is parsed.
FullySynchronously = 0x100, // Suppress local event loop (in case UI actions are
// triggered by file watchers).
- ExpectRepoChanges = 0x200 // Expect changes in repository by the command
+ ExpectRepoChanges = 0x200, // Expect changes in repository by the command
+ SilentOutput = 0x400 // With ShowStdOutInLogWindow - append output silently
};
static Utils::SynchronousProcessResponse runVcs(const QString &workingDir,
const QString &binary,
const QStringList &arguments,
int timeOutMS,
- QProcessEnvironment env,
unsigned flags = 0,
- QTextCodec *outputCodec = 0);
-
- static Utils::SynchronousProcessResponse runVcs(const QString &workingDir,
- const QString &binary,
- const QStringList &arguments,
- int timeOutMS,
- unsigned flags = 0,
- QTextCodec *outputCodec = 0);
-
- // Make sure to not pass through the event loop at all:
- static bool runFullySynchronous(const QString &workingDirectory,
- const QString &binary,
- const QStringList &arguments,
- const QProcessEnvironment &env,
- QByteArray* outputText,
- QByteArray *errorText,
- int timeoutMS,
- unsigned flags);
+ QTextCodec *outputCodec = 0,
+ const QProcessEnvironment &env = QProcessEnvironment());
// Utility to run the 'patch' command
static bool runPatch(const QByteArray &input, const QString &workingDirectory = QString(),
diff --git a/src/plugins/vcsbase/vcsbasesubmiteditor.cpp b/src/plugins/vcsbase/vcsbasesubmiteditor.cpp
index e8c1cfd1d9..2f30cc1646 100644
--- a/src/plugins/vcsbase/vcsbasesubmiteditor.cpp
+++ b/src/plugins/vcsbase/vcsbasesubmiteditor.cpp
@@ -146,7 +146,7 @@ struct VcsBaseSubmitEditorPrivate
{
VcsBaseSubmitEditorPrivate(const VcsBaseSubmitEditorParameters *parameters,
SubmitEditorWidget *editorWidget,
- QObject *q);
+ VcsBaseSubmitEditor *q);
SubmitEditorWidget *m_widget;
QToolBar *m_toolWidget;
@@ -163,7 +163,7 @@ struct VcsBaseSubmitEditorPrivate
VcsBaseSubmitEditorPrivate::VcsBaseSubmitEditorPrivate(const VcsBaseSubmitEditorParameters *parameters,
SubmitEditorWidget *editorWidget,
- QObject *q) :
+ VcsBaseSubmitEditor *q) :
m_widget(editorWidget),
m_toolWidget(0),
m_parameters(parameters),
@@ -183,21 +183,28 @@ VcsBaseSubmitEditor::VcsBaseSubmitEditor(const VcsBaseSubmitEditorParameters *pa
{
setContext(Core::Context(parameters->context));
setWidget(d->m_widget);
+ document()->setDisplayName(QCoreApplication::translate("VCS", d->m_parameters->displayName));
// Message font according to settings
- const TextEditor::FontSettings fs = TextEditor::TextEditorSettings::instance()->fontSettings();
- QFont font = editorWidget->descriptionEdit()->font();
- font.setFamily(fs.family());
- font.setPointSize(fs.fontSize());
- editorWidget->descriptionEdit()->setFont(font);
+ Utils::CompletingTextEdit *descriptionEdit = editorWidget->descriptionEdit();
+ const TextEditor::FontSettings fs = TextEditor::TextEditorSettings::fontSettings();
+ const QTextCharFormat tf = fs.toTextCharFormat(TextEditor::C_TEXT);
+ descriptionEdit->setFont(tf.font());
+ const QTextCharFormat selectionFormat = fs.toTextCharFormat(TextEditor::C_SELECTION);
+ QPalette pal = descriptionEdit->palette();
+ pal.setColor(QPalette::Base, tf.background().color());
+ pal.setColor(QPalette::Text, tf.foreground().color());
+ pal.setColor(QPalette::Foreground, tf.foreground().color());
+ if (selectionFormat.background().style() != Qt::NoBrush)
+ pal.setColor(QPalette::Highlight, selectionFormat.background().color());
+ pal.setBrush(QPalette::HighlightedText, selectionFormat.foreground());
+ descriptionEdit->setPalette(pal);
d->m_file->setModified(false);
// We are always clean to prevent the editor manager from asking to save.
- connect(d->m_file, SIGNAL(saveMe(QString*,QString,bool)),
- this, SLOT(save(QString*,QString,bool)));
connect(d->m_widget, SIGNAL(diffSelected(QList<int>)), this, SLOT(slotDiffSelectedVcsFiles(QList<int>)));
- connect(d->m_widget->descriptionEdit(), SIGNAL(textChanged()), this, SLOT(slotDescriptionChanged()));
+ connect(descriptionEdit, SIGNAL(textChanged()), this, SLOT(slotDescriptionChanged()));
const CommonVcsSettings settings = VcsPlugin::instance()->settings();
// Add additional context menu settings
@@ -232,7 +239,7 @@ VcsBaseSubmitEditor::VcsBaseSubmitEditor(const VcsBaseSubmitEditorParameters *pa
connect(Core::ICore::mainWindow(), SIGNAL(windowActivated()), this, SLOT(slotRefreshCommitData()));
Aggregation::Aggregate *aggregate = new Aggregation::Aggregate;
- aggregate->add(new Find::BaseTextFind(d->m_widget->descriptionEdit()));
+ aggregate->add(new Find::BaseTextFind(descriptionEdit));
aggregate->add(this);
}
@@ -350,12 +357,6 @@ void VcsBaseSubmitEditor::slotDescriptionChanged()
{
}
-bool VcsBaseSubmitEditor::createNew(const QString &contents)
-{
- setFileContents(contents);
- return true;
-}
-
bool VcsBaseSubmitEditor::open(QString *errorString, const QString &fileName, const QString &realFileName)
{
if (fileName.isEmpty())
@@ -366,10 +367,10 @@ bool VcsBaseSubmitEditor::open(QString *errorString, const QString &fileName, co
return false;
const QString text = QString::fromLocal8Bit(reader.data());
- if (!createNew(text))
+ if (!setFileContents(text.toUtf8()))
return false;
- d->m_file->setFileName(QFileInfo(fileName).absoluteFilePath());
+ d->m_file->setFilePath(QFileInfo(fileName).absoluteFilePath());
d->m_file->setModified(fileName != realFileName);
return true;
}
@@ -379,19 +380,6 @@ Core::IDocument *VcsBaseSubmitEditor::document()
return d->m_file;
}
-QString VcsBaseSubmitEditor::displayName() const
-{
- if (d->m_displayName.isEmpty())
- d->m_displayName = QCoreApplication::translate("VCS", d->m_parameters->displayName);
- return d->m_displayName;
-}
-
-void VcsBaseSubmitEditor::setDisplayName(const QString &title)
-{
- d->m_displayName = title;
- emit changed();
-}
-
QString VcsBaseSubmitEditor::checkScriptWorkingDirectory() const
{
return d->m_checkScriptWorkingDirectory;
@@ -527,29 +515,14 @@ void VcsBaseSubmitEditor::slotDiffSelectedVcsFiles(const QList<int> &rawList)
emit diffSelectedFiles(rowsToFiles(rawList));
}
-bool VcsBaseSubmitEditor::save(QString *errorString, const QString &fileName, bool autoSave)
-{
- const QString fName = fileName.isEmpty() ? d->m_file->fileName() : fileName;
- Utils::FileSaver saver(fName, QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text);
- saver.write(fileContents());
- if (!saver.finalize(errorString))
- return false;
- if (autoSave)
- return true;
- const QFileInfo fi(fName);
- d->m_file->setFileName(fi.absoluteFilePath());
- d->m_file->setModified(false);
- return true;
-}
-
QByteArray VcsBaseSubmitEditor::fileContents() const
{
return d->m_widget->descriptionText().toLocal8Bit();
}
-bool VcsBaseSubmitEditor::setFileContents(const QString &contents)
+bool VcsBaseSubmitEditor::setFileContents(const QByteArray &contents)
{
- d->m_widget->setDescriptionText(contents);
+ d->m_widget->setDescriptionText(QString::fromUtf8(contents));
return true;
}
diff --git a/src/plugins/vcsbase/vcsbasesubmiteditor.h b/src/plugins/vcsbase/vcsbasesubmiteditor.h
index adf27dd39b..504629523b 100644
--- a/src/plugins/vcsbase/vcsbasesubmiteditor.h
+++ b/src/plugins/vcsbase/vcsbasesubmiteditor.h
@@ -44,6 +44,7 @@ QT_END_NAMESPACE
namespace VcsBase {
namespace Internal {
class CommonVcsSettings;
+ class SubmitEditorFile;
}
struct VcsBaseSubmitEditorPrivate;
class SubmitEditorWidget;
@@ -111,13 +112,9 @@ public:
void setCheckScriptWorkingDirectory(const QString &);
// Core::IEditor
- bool createNew(const QString &contents);
bool open(QString *errorString, const QString &fileName, const QString &realFileName);
Core::IDocument *document();
- QString displayName() const;
- void setDisplayName(const QString &title);
Core::Id id() const;
- bool isTemporary() const { return true; }
QWidget *toolBar();
@@ -146,7 +143,6 @@ signals:
private slots:
void slotDiffSelectedVcsFiles(const QList<int> &rawList);
- bool save(QString *errorString, const QString &fileName, bool autoSave);
void slotDescriptionChanged();
void slotCheckSubmitMessage();
void slotInsertNickName();
@@ -159,7 +155,7 @@ protected:
* the file. The default implementation uses the text
* of the description editor. */
virtual QByteArray fileContents() const;
- virtual bool setFileContents(const QString &contents);
+ virtual bool setFileContents(const QByteArray &contents);
void setDescriptionMandatory(bool v);
bool isDescriptionMandatory() const;
@@ -171,6 +167,7 @@ private:
QString promptForNickName();
VcsBaseSubmitEditorPrivate *d;
+ friend class Internal::SubmitEditorFile; // for the file contents
};
} // namespace VcsBase
diff --git a/src/plugins/vcsbase/vcsplugin.cpp b/src/plugins/vcsbase/vcsplugin.cpp
index 23d87fad90..08612e9709 100644
--- a/src/plugins/vcsbase/vcsplugin.cpp
+++ b/src/plugins/vcsbase/vcsplugin.cpp
@@ -33,7 +33,6 @@
#include "vcsbaseoutputwindow.h"
#include "corelistener.h"
-#include <coreplugin/icore.h>
#include <coreplugin/mimedatabase.h>
#include <QtPlugin>
@@ -61,7 +60,7 @@ bool VcsPlugin::initialize(const QStringList &arguments, QString *errorMessage)
{
Q_UNUSED(arguments)
- if (!Core::ICore::mimeDatabase()->addMimeTypes(QLatin1String(":/vcsbase/VcsBase.mimetypes.xml"), errorMessage))
+ if (!Core::MimeDatabase::addMimeTypes(QLatin1String(":/vcsbase/VcsBase.mimetypes.xml"), errorMessage))
return false;
m_coreListener = new CoreListener;
diff --git a/src/plugins/welcome/Welcome.pluginspec.in b/src/plugins/welcome/Welcome.pluginspec.in
index cb2a0489ae..e6301d7861 100644
--- a/src/plugins/welcome/Welcome.pluginspec.in
+++ b/src/plugins/welcome/Welcome.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"Welcome\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"Welcome\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_COMPAT_VERSION\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
diff --git a/src/plugins/welcome/communitywelcomepage.h b/src/plugins/welcome/communitywelcomepage.h
index 7c161659fc..bf40d02a41 100644
--- a/src/plugins/welcome/communitywelcomepage.h
+++ b/src/plugins/welcome/communitywelcomepage.h
@@ -30,8 +30,6 @@
#ifndef COMMUNITYWELCOMEPAGE_H
#define COMMUNITYWELCOMEPAGE_H
-#include "welcome_global.h"
-
#include <utils/iwelcomepage.h>
#include <coreplugin/icore.h>
diff --git a/src/plugins/welcome/welcome.pro b/src/plugins/welcome/welcome.pro
index 70a58cf42f..b201120c74 100644
--- a/src/plugins/welcome/welcome.pro
+++ b/src/plugins/welcome/welcome.pro
@@ -1,9 +1,8 @@
-QT += network declarative
+QT += network quick
include(../../qtcreatorplugin.pri)
-HEADERS += welcomeplugin.h \
- welcome_global.h
+HEADERS += welcomeplugin.h
SOURCES += welcomeplugin.cpp
diff --git a/src/plugins/welcome/welcome.qbs b/src/plugins/welcome/welcome.qbs
index 39bc5b152b..8cde310ec9 100644
--- a/src/plugins/welcome/welcome.qbs
+++ b/src/plugins/welcome/welcome.qbs
@@ -4,15 +4,14 @@ import "../QtcPlugin.qbs" as QtcPlugin
QtcPlugin {
name: "Welcome"
+ minimumQtVersion: "5.1"
- Depends { name: "Qt"; submodules: ["widgets", "network", "declarative"] }
+ Depends { name: "Qt"; submodules: ["widgets", "network"] }
+ Depends { name: "Qt.quick"; condition: product.condition; }
Depends { name: "Core" }
Depends { name: "ProjectExplorer" }
- cpp.includePaths: base.concat("../../shared/scriptwrapper")
-
files: [
- "welcome_global.h",
"welcomeplugin.cpp",
"welcomeplugin.h",
]
diff --git a/src/plugins/welcome/welcome_global.h b/src/plugins/welcome/welcome_global.h
deleted file mode 100644
index 1e4b939c06..0000000000
--- a/src/plugins/welcome/welcome_global.h
+++ /dev/null
@@ -1,41 +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 WELCOME_GLOBAL_H
-#define WELCOME_GLOBAL_H
-
-#include <qglobal.h>
-
-#if defined(WELCOME_LIBRARY)
-# define WELCOME_EXPORT Q_DECL_EXPORT
-#else
-# define WELCOME_EXPORT Q_DECL_IMPORT
-#endif
-
-#endif // CPPEDITOR_GLOBAL_H
diff --git a/src/plugins/welcome/welcomeplugin.cpp b/src/plugins/welcome/welcomeplugin.cpp
index 8e5b1ddfa9..e35787ab95 100644
--- a/src/plugins/welcome/welcomeplugin.cpp
+++ b/src/plugins/welcome/welcomeplugin.cpp
@@ -61,10 +61,10 @@
#include <QUrl>
#include <QtPlugin>
-#include <QDeclarativeView>
-#include <QDeclarativeContext>
-#include <QDeclarativeEngine>
-#include <QDeclarativeNetworkAccessManagerFactory>
+#include <QtQuick/QQuickView>
+#include <QtQml/QQmlContext>
+#include <QtQml/QQmlEngine>
+#include <QtQml/QQmlNetworkAccessManagerFactory>
enum { debug = 0 };
@@ -76,10 +76,10 @@ static const char currentPageSettingsKeyC[] = "WelcomeTab";
namespace Welcome {
namespace Internal {
-class NetworkAccessManagerFactory : public QDeclarativeNetworkAccessManagerFactory
+class NetworkAccessManagerFactory : public QQmlNetworkAccessManagerFactory
{
public:
- NetworkAccessManagerFactory(): QDeclarativeNetworkAccessManagerFactory() {}
+ NetworkAccessManagerFactory(): QQmlNetworkAccessManagerFactory() {}
QNetworkAccessManager* create(QObject *parent) { return new Utils::NetworkAccessManager(parent); }
};
@@ -103,7 +103,7 @@ public:
Q_SCRIPTABLE QString platform() const;
- bool eventFilter(QObject *, QEvent *);
+// bool eventFilter(QObject *, QEvent *);
public slots:
void setActivePlugin(int pos)
@@ -121,10 +121,10 @@ private slots:
void welcomePluginAdded(QObject*);
private:
- void facilitateQml(QDeclarativeEngine *engine);
+ void facilitateQml(QQmlEngine *engine);
QWidget *m_modeWidget;
- QDeclarativeView *m_welcomePage;
+ QQuickView *m_welcomePage;
QList<QObject*> m_pluginList;
int m_activePlugin;
NetworkAccessManagerFactory *m_networkAccessManagerFactory;
@@ -146,41 +146,48 @@ WelcomeMode::WelcomeMode() :
setContextHelpId(QLatin1String("Qt Creator Manual"));
setContext(Core::Context(Core::Constants::C_WELCOME_MODE));
- m_welcomePage = new QDeclarativeView;
- m_welcomePage->setResizeMode(QDeclarativeView::SizeRootObjectToView);
- // filter to forward dragEnter events
- m_welcomePage->installEventFilter(this);
- m_welcomePage->viewport()->installEventFilter(this);
+ m_welcomePage = new QQuickView;
+ m_welcomePage->setObjectName(QLatin1String("WelcomePage"));
+ m_welcomePage->setResizeMode(QQuickView::SizeRootObjectToView);
+
+// filter to forward dragEnter events
+// m_welcomePage->installEventFilter(this);
+// m_welcomePage->viewport()->installEventFilter(this);
m_modeWidget = new QWidget;
+ m_modeWidget->setObjectName(QLatin1String("WelcomePageModeWidget"));
QVBoxLayout *layout = new QVBoxLayout;
layout->setMargin(0);
layout->setSpacing(0);
- m_modeWidget->setLayout(layout);
Utils::StyledBar* styledBar = new Utils::StyledBar(m_modeWidget);
+ styledBar->setObjectName(QLatin1String("WelcomePageStyledBar"));
layout->addWidget(styledBar);
- QScrollArea *scrollArea = new QScrollArea(m_modeWidget);
- scrollArea->setFrameShape(QFrame::NoFrame);
- layout->addWidget(scrollArea);
- scrollArea->setWidget(m_welcomePage);
- scrollArea->setWidgetResizable(true);
- m_welcomePage->setMinimumWidth(880);
- m_welcomePage->setMinimumHeight(548);
- PluginManager *pluginManager = PluginManager::instance();
- connect(pluginManager, SIGNAL(objectAdded(QObject*)), SLOT(welcomePluginAdded(QObject*)));
+
+ // QScrollArea *scrollArea = new QScrollArea(m_modeWidget);
+ // scrollArea->setFrameShape(QFrame::NoFrame);
+ // layout->addWidget(scrollArea);
+ // scrollArea->setWidget(m_welcomePage);
+ // scrollArea->setWidgetResizable(true);
+
+ QWidget *container = QWidget::createWindowContainer(m_welcomePage, m_modeWidget);
+ container->setMinimumSize(QSize(880, 548));
+ layout->addWidget(container);
+ m_modeWidget->setLayout(layout);
+
+ connect(PluginManager::instance(), SIGNAL(objectAdded(QObject*)), SLOT(welcomePluginAdded(QObject*)));
setWidget(m_modeWidget);
}
-bool WelcomeMode::eventFilter(QObject *, QEvent *e)
-{
- if (e->type() == QEvent::DragEnter) {
- e->ignore();
- return true;
- }
- return false;
-}
+//bool WelcomeMode::eventFilter(QObject *, QEvent *e)
+//{
+// if (e->type() == QEvent::DragEnter) {
+// e->ignore();
+// return true;
+// }
+// return false;
+//}
WelcomeMode::~WelcomeMode()
{
@@ -195,7 +202,7 @@ bool sortFunction(Utils::IWelcomePage * a, Utils::IWelcomePage *b)
return a->priority() < b->priority();
}
-void WelcomeMode::facilitateQml(QDeclarativeEngine * /*engine*/)
+void WelcomeMode::facilitateQml(QQmlEngine * /*engine*/)
{
}
@@ -228,7 +235,7 @@ void WelcomeMode::initPlugins()
if (activePlugin() > 1)
setActivePlugin(1);
- QDeclarativeContext *ctx = m_welcomePage->rootContext();
+ QQmlContext *ctx = m_welcomePage->rootContext();
ctx->setContextProperty(QLatin1String("welcomeMode"), this);
QList<Utils::IWelcomePage*> duplicatePlugins = PluginManager::getObjects<Utils::IWelcomePage>();
@@ -256,7 +263,7 @@ void WelcomeMode::initPlugins()
}
- QDeclarativeEngine *engine = m_welcomePage->engine();
+ QQmlEngine *engine = m_welcomePage->engine();
QStringList importPathList = engine->importPathList();
importPathList << resourcePath() + QLatin1String("/welcomescreen");
engine->setImportPathList(importPathList);
@@ -287,10 +294,10 @@ void WelcomeMode::initPlugins()
QString WelcomeMode::platform() const
{
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");
+ case OsTypeWindows: return QLatin1String("windows");
+ case OsTypeMac: return QLatin1String("mac");
+ case OsTypeLinux: return QLatin1String("linux");
+ case OsTypeOtherUnix: return QLatin1String("unix");
default: return QLatin1String("other");
}
}
@@ -323,7 +330,7 @@ void WelcomeMode::welcomePluginAdded(QObject *obj)
}
m_pluginList.insert(insertPos, plugin);
// update model through reset
- QDeclarativeContext *ctx = m_welcomePage->rootContext();
+ QQmlContext *ctx = m_welcomePage->rootContext();
ctx->setContextProperty(QLatin1String("pagesModel"), QVariant::fromValue(m_pluginList));
}
}
diff --git a/src/plugins/welcome/welcomeplugin.h b/src/plugins/welcome/welcomeplugin.h
index c320d1f711..c69eff7f38 100644
--- a/src/plugins/welcome/welcomeplugin.h
+++ b/src/plugins/welcome/welcomeplugin.h
@@ -33,7 +33,7 @@
#include <extensionsystem/iplugin.h>
QT_BEGIN_NAMESPACE
-class QDeclarativeEngine;
+class QQmlEngine;
QT_END_NAMESPACE
namespace Welcome {
diff --git a/src/shared/cpaster/cgi.cpp b/src/shared/cpaster/cgi.cpp
index 0c64e02c52..6bee94682e 100644
--- a/src/shared/cpaster/cgi.cpp
+++ b/src/shared/cpaster/cgi.cpp
@@ -44,11 +44,11 @@ QString CGI::encodeURL(const QString &rawText)
const char ch = *it;
if (('A' <= ch && ch <= 'Z')
|| ('a' <= ch && ch <= 'z')
- || ('0' <= ch && ch <= '9'))
+ || ('0' <= ch && ch <= '9')) {
enc.append(QLatin1Char(ch));
- else if (ch == ' ')
+ } else if (ch == ' ') {
enc.append(QLatin1Char('+'));
- else {
+ } else {
switch (ch) {
case '-': case '_':
case '(': case ')':
diff --git a/src/shared/designerintegrationv2/formresizer.cpp b/src/shared/designerintegrationv2/formresizer.cpp
index f4adc5153e..3c7300f38d 100644
--- a/src/shared/designerintegrationv2/formresizer.cpp
+++ b/src/shared/designerintegrationv2/formresizer.cpp
@@ -83,7 +83,7 @@ void FormResizer::updateGeometry()
const Handles::iterator hend = m_handles.end();
for (Handles::iterator it = m_handles.begin(); it != hend; ++it) {
- SizeHandleRect *hndl = *it;;
+ SizeHandleRect *hndl = *it;
switch (hndl->dir()) {
case SizeHandleRect::LeftTop:
hndl->move(geom.x() - w / 2, geom.y() - h / 2);
diff --git a/src/shared/help/bookmarkmanager.cpp b/src/shared/help/bookmarkmanager.cpp
index 7cf164d0f0..4e43a2ddd0 100644
--- a/src/shared/help/bookmarkmanager.cpp
+++ b/src/shared/help/bookmarkmanager.cpp
@@ -29,7 +29,7 @@
#include "bookmarkmanager.h"
-#include "localhelpmanager.h"
+#include <localhelpmanager.h>
#include <utils/filterlineedit.h>
#include <utils/styledbar.h>
@@ -236,8 +236,7 @@ void BookmarkDialog::customContextMenuRequested(const QPoint &point)
if (index.isValid())
name = index.data().toString();
ui.bookmarkFolders->setCurrentIndex(ui.bookmarkFolders->findText(name));
- }
- else if (picked == renameItem) {
+ } else if (picked == renameItem) {
BookmarkModel *model = bookmarkManager->treeBookmarkModel();
if (QStandardItem *item = model->itemFromIndex(proxyIndex)) {
item->setEditable(true);
@@ -397,15 +396,14 @@ 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) {
+ } else if (pickedAction == removeItem) {
bookmarkManager->removeBookmarkItem(treeView,
filterBookmarkModel->mapToSource(index));
- }
- else if (pickedAction == renameItem) {
+ } else if (pickedAction == renameItem) {
const QModelIndex &source = filterBookmarkModel->mapToSource(index);
QStandardItem *item =
bookmarkManager->treeBookmarkModel()->itemFromIndex(source);
diff --git a/src/shared/help/contentwindow.cpp b/src/shared/help/contentwindow.cpp
index 8df99b3676..768c818af8 100644
--- a/src/shared/help/contentwindow.cpp
+++ b/src/shared/help/contentwindow.cpp
@@ -29,10 +29,10 @@
#include "contentwindow.h"
-#include "centralwidget.h"
-#include "helpviewer.h"
-#include "localhelpmanager.h"
-#include "openpagesmanager.h"
+#include <centralwidget.h>
+#include <helpviewer.h>
+#include <localhelpmanager.h>
+#include <openpagesmanager.h>
#include <QLayout>
#include <QFocusEvent>
diff --git a/src/shared/help/indexwindow.cpp b/src/shared/help/indexwindow.cpp
index 60b86b7fc4..34a6721c77 100644
--- a/src/shared/help/indexwindow.cpp
+++ b/src/shared/help/indexwindow.cpp
@@ -28,13 +28,14 @@
****************************************************************************/
#include "indexwindow.h"
-#include "centralwidget.h"
-#include "helpviewer.h"
-#include "localhelpmanager.h"
-#include "openpagesmanager.h"
#include "topicchooser.h"
+#include <centralwidget.h>
+#include <helpviewer.h>
+#include <localhelpmanager.h>
+#include <openpagesmanager.h>
+
#include <utils/filterlineedit.h>
#include <utils/hostosinfo.h>
#include <utils/styledbar.h>
@@ -149,9 +150,8 @@ bool IndexWindow::eventFilter(QObject *obj, QEvent *e)
QAction *action = menu.exec();
if (curTab == action)
m_indexWidget->activateCurrentItem();
- else if (newTab == action) {
+ else if (newTab == action)
open(m_indexWidget, idx);
- }
}
} else if (m_indexWidget && obj == m_indexWidget->viewport()
&& e->type() == QEvent::MouseButtonRelease) {
diff --git a/src/shared/qbs b/src/shared/qbs
-Subproject b196bb68f7ac03b3bf9fcbcb4af3ae81e0ca0d7
+Subproject e0d292b08046c5a257b23cd45a7bebe0849bc42
diff --git a/src/shared/qtsingleapplication/qtlocalpeer.h b/src/shared/qtsingleapplication/qtlocalpeer.h
index afff3929dc..ba20243057 100644
--- a/src/shared/qtsingleapplication/qtlocalpeer.h
+++ b/src/shared/qtsingleapplication/qtlocalpeer.h
@@ -27,7 +27,7 @@
**
****************************************************************************/
-#include "qtlockedfile.h"
+#include <qtlockedfile.h>
#include <QLocalServer>
#include <QLocalSocket>
diff --git a/src/src.qbs b/src/src.qbs
index 591e0f4adc..11853ff7c5 100644
--- a/src/src.qbs
+++ b/src/src.qbs
@@ -12,9 +12,9 @@ Project {
]
property bool qbsSubModuleExists: File.exists(qbsProject.qbsBaseDir + "/qbs.qbs")
- property path qbs_build_dir: qbs.getenv("QBS_BUILD_DIR")
- property path qbs_source_dir: qbs.getenv("QBS_SOURCE_DIR")
- property bool useExternalQbs: qbs_build_dir && qbs_source_dir
+ property path qbs_install_dir: qbs.getenv("QBS_INSTALL_DIR")
+ property bool useExternalQbs: qbs_install_dir
+ property bool buildQbsProjectManager: useExternalQbs || qbsSubModuleExists
Project {
name: "qbs"
id: qbsProject
diff --git a/src/tools/QtcTool.qbs b/src/tools/QtcTool.qbs
index 4b2a4b26ef..d9b25e794c 100644
--- a/src/tools/QtcTool.qbs
+++ b/src/tools/QtcTool.qbs
@@ -1,10 +1,9 @@
import qbs.base 1.0
-import "../../qbs/defaults.js" as Defaults
Application {
type: "application" // no Mac app bundle
Depends { name: "cpp" }
- cpp.defines: Defaults.defines(qbs)
+ cpp.defines: project.generalDefines
cpp.linkerFlags: {
if (qbs.buildVariant == "release" && (qbs.toolchain.contains("gcc") || qbs.toolchain.contains("mingw")))
return ["-Wl,-s"]
diff --git a/src/tools/qml2puppet/qml2puppet/qml2puppet.pro b/src/tools/qml2puppet/qml2puppet/qml2puppet.pro
index e1934d87f1..81d91e7490 100644
--- a/src/tools/qml2puppet/qml2puppet/qml2puppet.pro
+++ b/src/tools/qml2puppet/qml2puppet/qml2puppet.pro
@@ -4,7 +4,12 @@ TEMPLATE = app
include(../../../../qtcreator.pri)
-DESTDIR = $$IDE_BIN_PATH
+
+CONFIG(debug) {
+ DESTDIR = $$[QT_INSTALL_BINS]
+} else {
+ DESTDIR = $$IDE_BIN_PATH
+}
include(../../../rpath.pri)
include(../../../../share/qtcreator/qml/qmlpuppet/qml2puppet/qml2puppet.pri)
diff --git a/src/tools/qtcdebugger/main.cpp b/src/tools/qtcdebugger/main.cpp
index 23ea477ba5..5123ce9fb3 100644
--- a/src/tools/qtcdebugger/main.cpp
+++ b/src/tools/qtcdebugger/main.cpp
@@ -45,7 +45,7 @@
#include <QProcess>
#include <QPushButton>
-#include "registryaccess.h"
+#include <registryaccess.h>
#include <windows.h>
#include <psapi.h>
diff --git a/src/tools/qtcdebugger/qtcdebugger.qbs b/src/tools/qtcdebugger/qtcdebugger.qbs
index 46990a36b6..284ad71118 100644
--- a/src/tools/qtcdebugger/qtcdebugger.qbs
+++ b/src/tools/qtcdebugger/qtcdebugger.qbs
@@ -5,10 +5,7 @@ QtcTool {
name: "qtcdebugger"
condition: qbs.targetOS.contains("windows")
- cpp.includePaths: [
- buildDirectory,
- "../../shared/registryaccess"
- ]
+ cpp.includePaths: base.concat(["../../shared/registryaccess"])
cpp.dynamicLibraries: [
"psapi",
"advapi32"
diff --git a/src/tools/qtcreatorcrashhandler/qtcreatorcrashhandler.qbs b/src/tools/qtcreatorcrashhandler/qtcreatorcrashhandler.qbs
index eeb69b86d4..4b5a4910cc 100644
--- a/src/tools/qtcreatorcrashhandler/qtcreatorcrashhandler.qbs
+++ b/src/tools/qtcreatorcrashhandler/qtcreatorcrashhandler.qbs
@@ -5,28 +5,18 @@ QtcTool {
name: "qtcreator_crash_handler"
condition: qbs.targetOS.contains("linux") && qbs.buildVariant == "debug"
- cpp.includePaths: [
- buildDirectory,
- "../../libs"
- ]
-
+ Depends { name: "Utils" }
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"
- ]
+ Group {
+ name: "Crash Handler Sources"
+ files: [
+ "backtracecollector.cpp", "backtracecollector.h",
+ "crashhandler.cpp", "crashhandler.h",
+ "crashhandlerdialog.cpp", "crashhandlerdialog.h", "crashhandlerdialog.ui",
+ "main.cpp",
+ "utils.cpp", "utils.h"
+ ]
+ }
}
diff --git a/src/tools/sdktool/operation.cpp b/src/tools/sdktool/operation.cpp
index 26813b82d0..51c7dde895 100644
--- a/src/tools/sdktool/operation.cpp
+++ b/src/tools/sdktool/operation.cpp
@@ -31,7 +31,7 @@
#include "settings.h"
-#include "utils/persistentsettings.h"
+#include <utils/persistentsettings.h>
#include <QDir>
#include <QFile>
diff --git a/src/tools/sdktool/sdktool.qbs b/src/tools/sdktool/sdktool.qbs
index e9510a4ee8..a8ea1aae1f 100644
--- a/src/tools/sdktool/sdktool.qbs
+++ b/src/tools/sdktool/sdktool.qbs
@@ -8,7 +8,6 @@ QtcTool {
Depends { name: "Utils" }
Depends { name: "app_version_header" }
- cpp.includePaths: "../../libs"
cpp.defines: base.concat([qbs.targetOS.contains("osx")
? 'DATA_PATH="."' : 'DATA_PATH="../share/qtcreator"'])
diff --git a/src/tools/tools.pro b/src/tools/tools.pro
index 240a42ee3f..fa12ab6449 100644
--- a/src/tools/tools.pro
+++ b/src/tools/tools.pro
@@ -3,20 +3,12 @@ TEMPLATE = subdirs
SUBDIRS = qtpromaker \
qmlpuppet \
../plugins/cpaster/frontend \
- sdktool
+ sdktool \
+ valgrindfake
win32 {
SUBDIRS += qtcdebugger
- # win64interrupt only make sense for 64bit builds
- ENV_CPU=$$(CPU)
- ENV_LIBPATH=$$(LIBPATH)
- contains(ENV_CPU, ^AMD64$) {
- SUBDIRS += win64interrupt
- } else:isEmpty(ENV_CPU):contains(ENV_LIBPATH, ^.*amd64.*$) {
- SUBDIRS += win64interrupt
- }
-} else {
- SUBDIRS += valgrindfake
+ SUBDIRS += wininterrupt
}
QT_BREAKPAD_ROOT_PATH = $$(QT_BREAKPAD_ROOT_PATH)
@@ -36,4 +28,4 @@ greaterThan(QT_MAJOR_VERSION, 4) {
} else {
SUBDIRS += qml2puppet
}
-} \ No newline at end of file
+}
diff --git a/src/tools/tools.qbs b/src/tools/tools.qbs
index 3b187c9d55..74b476f52a 100644
--- a/src/tools/tools.qbs
+++ b/src/tools/tools.qbs
@@ -6,6 +6,7 @@ Project {
"qtcdebugger/qtcdebugger.qbs",
"qtcreatorcrashhandler/qtcreatorcrashhandler.qbs",
"qtpromaker/qtpromaker.qbs",
- "sdktool/sdktool.qbs"
+ "sdktool/sdktool.qbs",
+ "valgrindfake/valgrindfake.qbs"
]
}
diff --git a/src/tools/valgrindfake/main.cpp b/src/tools/valgrindfake/main.cpp
index 78e479e55d..ea2fc188b3 100644
--- a/src/tools/valgrindfake/main.cpp
+++ b/src/tools/valgrindfake/main.cpp
@@ -71,12 +71,12 @@ int main(int argc, char** argv)
uint arg_wait = 0;
const QProcessEnvironment sysEnv = QProcessEnvironment::systemEnvironment();
- arg_xmlFile = sysEnv.value("QCIT_INPUT_FILE");
+ arg_xmlFile = sysEnv.value(QLatin1String("QCIT_INPUT_FILE"));
for (int i = 1; i < args.size(); ++i) {
const QString& arg = args.at(i);
if (arg.startsWith(QLatin1String("--xml-socket="))) {
- arg_server = arg.mid(13, arg.indexOf(':') - 13);
+ arg_server = arg.mid(13, arg.indexOf(QLatin1Char(':')) - 13);
arg_port = arg.mid(13 + arg_server.length() + 1);
} else if (args.size() > i + 1
&& (args.at(i) == QLatin1String("-i")
diff --git a/src/tools/valgrindfake/outputgenerator.cpp b/src/tools/valgrindfake/outputgenerator.cpp
index 9826277386..5d797e601f 100644
--- a/src/tools/valgrindfake/outputgenerator.cpp
+++ b/src/tools/valgrindfake/outputgenerator.cpp
@@ -30,6 +30,8 @@
#include "outputgenerator.h"
+#include <utils/sleep.h>
+
#include <QAbstractSocket>
#include <QIODevice>
#include <QTextStream>
@@ -37,8 +39,6 @@
#include <QStringList>
#include <QDebug>
-#include <unistd.h>
-
using namespace Valgrind::Fake;
OutputGenerator::OutputGenerator(QAbstractSocket *output, QIODevice *input) :
@@ -98,14 +98,13 @@ void OutputGenerator::produceRuntimeError()
int i = 1 / zero;
Q_UNUSED(i);
Q_ASSERT(false);
- }
- else if (m_garbage) {
+ } else if (m_garbage) {
std::cerr << "Writing garbage" << std::endl;
blockingWrite(m_output, "<</GARBAGE = '\"''asdfaqre");
m_output->flush();
} else if (m_wait) {
qDebug() << "waiting in fake valgrind for " << m_wait << " seconds..." << endl;
- sleep(m_wait);
+ Utils::sleep(1000 * m_wait);
}
}
diff --git a/src/tools/valgrindfake/valgrindfake.pro b/src/tools/valgrindfake/valgrindfake.pro
index 7bded95bb5..bd7eae2cda 100644
--- a/src/tools/valgrindfake/valgrindfake.pro
+++ b/src/tools/valgrindfake/valgrindfake.pro
@@ -10,3 +10,7 @@ isEmpty(PRECOMPILED_HEADER):PRECOMPILED_HEADER = $$PWD/../../shared/qtcreator_pc
HEADERS += outputgenerator.h
SOURCES += main.cpp \
outputgenerator.cpp
+
+QTC_LIB_DEPENDS += \
+ utils
+include(../../../qtcreator.pri)
diff --git a/src/tools/valgrindfake/valgrindfake.qbs b/src/tools/valgrindfake/valgrindfake.qbs
new file mode 100644
index 0000000000..ddedef4e80
--- /dev/null
+++ b/src/tools/valgrindfake/valgrindfake.qbs
@@ -0,0 +1,13 @@
+import qbs
+
+CppApplication {
+ name: "valgrind-fake"
+ type: "application"
+ destinationDirectory: project.ide_bin_path
+ Depends { name: "Utils" }
+ Depends { name: "Qt"; submodules: ["network", "xml"]; }
+ files: [
+ "main.cpp",
+ "outputgenerator.h", "outputgenerator.cpp"
+ ]
+}
diff --git a/src/tools/win64interrupt/win64interrupt.c b/src/tools/wininterrupt/wininterrupt.c
index f2327f8a1c..f2327f8a1c 100644
--- a/src/tools/win64interrupt/win64interrupt.c
+++ b/src/tools/wininterrupt/wininterrupt.c
diff --git a/src/tools/win64interrupt/win64interrupt.pro b/src/tools/wininterrupt/wininterrupt.pro
index 282514c54c..b306db179f 100644
--- a/src/tools/win64interrupt/win64interrupt.pro
+++ b/src/tools/wininterrupt/wininterrupt.pro
@@ -16,7 +16,7 @@ win32-msvc* {
QMAKE_CXXFLAGS += -static
}
-SOURCES = win64interrupt.c
+SOURCES = wininterrupt.c
TEMPLATE = app
DESTDIR = $$IDE_LIBEXEC_PATH
@@ -26,5 +26,15 @@ build_all:!build_pass {
CONFIG += release
}
+ENV_CPU=$$(CPU)
+ENV_LIBPATH=$$(LIBPATH)
+contains(ENV_CPU, ^AMD64$) {
+ TARGET = win64interrupt
+} else:isEmpty(ENV_CPU):contains(ENV_LIBPATH, ^.*amd64.*$) {
+ TARGET = win64interrupt
+} else {
+ TARGET = win32interrupt
+}
+
target.path = $$QTC_PREFIX/bin # FIXME: libexec, more or less
INSTALLS += target